问:
How to use DCG in Prolog
So I'm currently trying to achieve something similar to this tree, using a text file containing courses and the student ID's of anyone attending it.

```<code>courses(
    [
     ('MATH2221',
      [
       201000001,
       201000002
      ]
     ),

     ('MATH2251',
      [
       201000002,
       201000003
      ]
     ),

     ('COMP2231',
      [
       201000003,
       201000001
      ]
     )
    ]
).
</code>```

The text file I'm parsing from looks like this:

```<code>MATH2221
       201000001
       201000002

MATH2251
       201000002
       201000003

COMP2231
       201000003
       201000001
</code>```

I read online that using DCGs is probably the best way to go about this as every student starts with a tab so ascii value '9' and then courses are separated by 2 nl characters. I'm really lost on prolog and I'm only going to post what I have that is currently working cause everything else is a mess. Does anyone have any advice at all or can at least help me understand what a DCG is?

```<code>:- debug.
:- [library(dcg/basics)].

load:-
    open('courses.txt',read,Stream),
         read,
         close(Stream).

read:-
    open('courses.txt',read,In),
    repeat,
    read_line_to_codes(In,X),write(X), nl,
    (X=end_of_file,!,
    nl); fail.
</code>```

答:
While the idea of what you ask is simple and the translation to DCG seems relatively simple, in practice it takes experience and skill to know how to do it correctly and efficiently.

The following works with SWI-Prolog (threaded, 64 bits, version 8.1.21) on Windows 10

```<code>:- [library(dcg/basics)].

courses([Course|Courses]) -->
    course(Course),
    courses(Courses), !.
courses([]) --> [].

course(course(Course,Students)) -->
    string_without("\n", Course_codes),
    { string_codes(Course,Course_codes ) },
    "\n",
    students(Students),
    (
        empty_line
    ;
        []
    ).

students([Student|Students]) -->
    student(Student),
    students(Students).
students([]) --> [].

student(Student) -->
    "\t",
    (
        (
            string_without("\n",Student_codes),
            { string_codes(Student,Student_codes) },
            "\n"
        )
    ;
        remainder(Student_codes),
        { string_codes(Student,Student_codes) }
    ).

empty_line --> "\n".

load_courses :-
    Input = "\c
MATH2221\n\c
    \t201000001\n\c
    \t201000002\n\c
    \n\c
MATH2251\n\c
    \t201000002\n\c
    \t201000003\n\c
    \n\c
COMP2231\n\c
    \t201000003\n\c
    \t201000001\c
",
    string_codes(Input,Codes),
    DCG = courses(Courses),
    phrase(DCG,Codes,Rest),
    assertion( Rest == [] ),
    format('Courses: ~n',[]),
    print_term(Courses,[]).
</code>```

Example run:

```<code>?- load_courses.
Courses:
[ course("MATH2221",["201000001","201000002"]),
  course("MATH2251",["201000002","201000003"]),
  course("COMP2231",["201000003","201000001"])
]
true.
</code>```

In your example you are reading the data from a file but for this example I hard coded that data into the query so that it could be reproduced anywhere without needing to copy a file. Input makes use of \c, see: Character Escape Syntax to keep the formatting of the input nice.

When you load the data from a file and you are not using library(dcg/basics) make use of phrase_from_file/2 or phrase_from_file/3. When you load the data from a file and you are using library(dcg/basics) make use of read_file_to_codes/3. Also check out open_string/2 which might be of use.

You were correct in using library(dcg/basics) but be very careful when using this as the predicates in there expect the input to be charter codes and not atoms or strings.

One predicate that is very common to use when parsing with text with DCGs is string_without//2 but as I noted it works with character codes so string_codes/2 is needed to convert the codes back into a string. Also since string_codes/2 is a standard predicate, it needs to be bookended with {} to let the DCG term rewrite code know that this is not to be translated.

When creating the example I could have added a \n after the last student and added an extra line and made the parser very simple, but chose instead to follow the more real world convention of not adding the \n which required adding the ; (or) parts, e.g. ; [] for the last missing empty line and ; remainder//1 for the missing \n after the last student.

Since I don't know how much more you need to know about this to understand it and I don't want to write a few chapters going over the exact details of all of this, just ask questions if you have them, but I do expect you work with the code and explain why you are not understanding the code by showing examples of what you tried instead of just asking because you can.

I'm really struggling with simply just the I/O

Here is a modified version of the code which uses read_file_to_codes/3.

Note that read_file_to_codes/3 is one of the few predicates that uses a file path/name directly and does not require the use of open/3

File: SO_question_163_courses.txt

```<code>MATH2221
       201000001
       201000002

MATH2251
       201000002
       201000003

COMP2231
       201000003
       201000001
</code>```

```<code>:- [library(dcg/basics)].

courses([Course|Courses]) -->
    course(Course),
    courses(Courses), !.
courses([]) --> [].

course(course(Course,Students)) -->
    string_without("\n", Course_codes),
    { string_codes(Course,Course_codes ) },
    "\n",
    students(Students),
    (
        empty_line
    ;
        []
    ).

students([Student|Students]) -->
    student(Student),
    students(Students).
students([]) --> [].

student(Student) -->
    spaces_or_tabs_plus,
    (
        (
            string_without("\n",Student_codes),
            { string_codes(Student,Student_codes) },
            "\n"
        )
    ;
        remainder(Student_codes),
        { string_codes(Student,Student_codes) }
    ).

spaces_or_tabs_plus -->
    space_or_tab,
    spaces_or_tabs_star.

spaces_or_tabs_star -->
    space_or_tab,
    spaces_or_tabs_star.
spaces_or_tabs_star --> [].

space_or_tab -->
    (
        "\s"
    |
        "\t"
    ).

empty_line --> "\n".

example_01 :-
    Input = "\c
MATH2221\n\c
    \t201000001\n\c
    \t201000002\n\c
    \n\c
MATH2251\n\c
    \t201000002\n\c
    \t201000003\n\c
    \n\c
COMP2231\n\c
    \t201000003\n\c
    \t201000001\c
",
    string_codes(Input,Codes),
    parse_courses(Codes,Courses),
    display_courses(Courses).

example_02 :-
    File_name = "C:\\Users\\Groot\\Documents\\Projects\\Prolog\\SO_question_163_courses.txt",
    read_file_to_codes(File_name,Codes,[]),
    parse_courses(Codes,Courses),
    display_courses(Courses).

parse_courses(Codes,Courses) :-
    DCG = courses(Courses),
    phrase(DCG,Codes,Rest),
    assertion( Rest == [] ).

display_courses(Courses) :-
    format('Courses: ~n',[]),
    print_term(Courses,[]).
</code>```

and some example runs

```<code>?- example_01.
Courses:
[ course("MATH2221",["201000001","201000002"]),
  course("MATH2251",["201000002","201000003"]),
  course("COMP2231",["201000003","201000001"])
]
true.

?- example_02.
Courses:
[ course("MATH2221",["201000001","201000002"]),
  course("MATH2251",["201000002","201000003"]),
  course("COMP2231",["201000003","201000001"])
]
true.
</code>```

Note with SWI-Prolog: The string type and its double quoted syntax

When using SWI-Prolog with a version 7 or higher the meaning of double quotes and back quotes changes and Prolog DCG examples found at StackOverflow, in blogs, papers, etc., will sometimes work as presented and sometimes fail. There will seem to be no reason for this to a beginner and be very frustrating.

The way to solve this is be aware of the values for two Prolog flags:

double quotes and back quotes

double quotes will typically be one of codes,chars,atom,string

back quotes will typically be one of codes,chars,string

You will have to determine what to set them to for the code you are using by  either gaining experience or just trial and error.

Also with Prolog when creating test case using

```<code>:- begin_tests(some_dcg).

:- end_tests(some_dcg).
</code>```

This will create a module and since the flags scope to a module, meaning that if you have multiple modules the flag can be different in each module. So you also have to check/set the flags with the test case module.

Flags take effect from where they are to the end of the module, so if you use set_prolog_flag/2 in a module after the code you expect it to effect, it will not work, the setting of the flag has to be before the code it needs to effect. So unless you have a particular need, put the set_prolog_flag/2 directives at the top of the module.

Now to make it even more confusing, sometimes the setting in the DCG section is not the same as in the test cases, so be aware of this also.

Following is an example of a DCG that has test cases, set both flags in each module and works.

```<code>:- module(course,
      [ courses//1,
        parse_courses/2,
        display_courses/1,
        test_course/0
      ]).

test_course :-
    run_tests([course]).

:- [library(dcg/basics)].

:- set_prolog_flag(double_quotes, string).
:- set_prolog_flag(back_quotes, codes).

courses([Course|Courses]) -->
    course(Course),
    courses(Courses), !.
courses([]) --> [].

course(course(Course,Students)) -->
    string_without("\n", Course_codes),
    { string_codes(Course,Course_codes ) },
    "\n",
    students(Students),
    (
        empty_line
    ;
        []
    ).

students([Student|Students]) -->
    student(Student),
    students(Students).
students([]) --> [].

student(Student) -->
    spaces_or_tabs_plus,
    (
        (
            string_without("\n",Student_codes),
            { string_codes(Student,Student_codes) },
            "\n"
        )
    ;
        remainder(Student_codes),
        { string_codes(Student,Student_codes) }
    ).

spaces_or_tabs_plus -->
    space_or_tab,
    spaces_or_tabs_star.

spaces_or_tabs_star -->
    space_or_tab,
    spaces_or_tabs_star.
spaces_or_tabs_star --> [].

space_or_tab -->
    (
        "\s"
    |
        "\t"
    ).

empty_line --> "\n".

parse_courses(Codes,Courses) :-
    DCG = courses(Courses),
    phrase(DCG,Codes,Rest),
    assertion( Rest == [] ).

display_courses(Courses) :-
    format('Courses: ~n',[]),
    print_term(Courses,[]).

:- begin_tests(course).

:- set_prolog_flag(double_quotes, string).
:- set_prolog_flag(back_quotes, codes).

test(001) :-
    Input = "\c
        MATH2221\n\c
            \t201000001\n\c
            \t201000002\n\c
            \n\c
        MATH2251\n\c
            \t201000002\n\c
            \t201000003\n\c
            \n\c
        COMP2231\n\c
            \t201000003\n\c
            \t201000001\c
        ",
    string_codes(Input,Codes),
    parse_courses(Codes,Courses),

    assertion( Courses ==
        [
            course("MATH2221",["201000001","201000002"]),
            course("MATH2251",["201000002","201000003"]),
            course("COMP2231",["201000003","201000001"])
        ]
    ).

test(002) :-
    File_name = "C:\\Users\\Groot\\Documents\\Projects\\Prolog\\SO_question_163_courses.txt",
    read_file_to_codes(File_name,Codes,[]),
    parse_courses(Codes,Courses),

    assertion( Courses ==
        [
            course("MATH2221",["201000001","201000002"]),
            course("MATH2251",["201000002","201000003"]),
            course("COMP2231",["201000003","201000001"])
        ]
    ).

:- end_tests(course).

</code>```

Running of test cases

```<code>?- run_tests.
% PL-Unit: course .. done
% All 2 tests passed
true.
</code>```

or if you have multiple tests in multiple files and only need to test course

```<code>?- test_course.
% PL-Unit: course .. done
% All 2 tests passed
true.
</code>```

Another thing that can be confusing is that when debugging with gtrace/0 is that a code list and string will be represented as a string with double quotes, e.g. "this is a string", the way to tell them apart is

In the Bindings section will be the list of bound variables locate a variable and right click on it.

There will be a popup dialog, select Details

This will present a window with the bound value display. There are options at the top.

Uncheck Portray

Example code used for following examples

```<code>dcg_test :-
    String = "string",
    Codes = [65,66,67],
    Atom = 'abc',
    dcg_test(String,Codes,Atom).

dcg_test(String,Codes,Atom) :-
    true.
</code>```

Bindings

String example

Codes example

If you are wondering why no one tells you these things about DCGs, I just did; you should try learning this without knowing this, it took me months to realize all of this.

Notes:

I tried to do this using phrase_from_file/3 with dcg/basics, but dcg/basics expected closed list and phrase_from_file/3 creates lazy list and in massaging the code it was turning into a rewrite of the predicates in dcg/basics and dealing with end of stream issues which are some of the biggest problems when learning DCGs.

Title: How to use DCG in Prolog

Body:
So I'm currently trying to achieve something similar to this tree, using a text file containing courses and the student ID's of anyone attending it.

courses(
    [
     ('MATH2221',
      [
       201000001,
       201000002
      ]
     ),

     ('MATH2251',
      [
       201000002,
       201000003
      ]
     ),

     ('COMP2231',
      [
       201000003,
       201000001
      ]
     )
    ]
).

The text file I'm parsing from looks like this:

MATH2221
       201000001
       201000002

MATH2251
       201000002
       201000003

COMP2231
       201000003
       201000001

I read online that using DCGs is probably the best way to go about this as every student starts with a tab so ascii value '9' and then courses are separated by 2 nl characters. I'm really lost on prolog and I'm only going to post what I have that is currently working cause everything else is a mess. Does anyone have any advice at all or can at least help me understand what a DCG is?

:- debug.
:- [library(dcg/basics)].

load:-
    open('courses.txt',read,Stream),
         read,
         close(Stream).

read:-
    open('courses.txt',read,In),
    repeat,
    read_line_to_codes(In,X),write(X), nl,
    (X=end_of_file,!,
    nl); fail.

Body:
While the idea of what you ask is simple and the translation to DCG seems relatively simple, in practice it takes experience and skill to know how to do it correctly and efficiently.

The following works with SWI-Prolog (threaded, 64 bits, version 8.1.21) on Windows 10

:- [library(dcg/basics)].

courses([Course|Courses]) -->
    course(Course),
    courses(Courses), !.
courses([]) --> [].

course(course(Course,Students)) -->
    string_without("\n", Course_codes),
    { string_codes(Course,Course_codes ) },
    "\n",
    students(Students),
    (
        empty_line
    ;
        []
    ).

students([Student|Students]) -->
    student(Student),
    students(Students).
students([]) --> [].

student(Student) -->
    "\t",
    (
        (
            string_without("\n",Student_codes),
            { string_codes(Student,Student_codes) },
            "\n"
        )
    ;
        remainder(Student_codes),
        { string_codes(Student,Student_codes) }
    ).

empty_line --> "\n".

load_courses :-
    Input = "\c
MATH2221\n\c
    \t201000001\n\c
    \t201000002\n\c
    \n\c
MATH2251\n\c
    \t201000002\n\c
    \t201000003\n\c
    \n\c
COMP2231\n\c
    \t201000003\n\c
    \t201000001\c
",
    string_codes(Input,Codes),
    DCG = courses(Courses),
    phrase(DCG,Codes,Rest),
    assertion( Rest == [] ),
    format('Courses: ~n',[]),
    print_term(Courses,[]).

Example run:

?- load_courses.
Courses:
[ course("MATH2221",["201000001","201000002"]),
  course("MATH2251",["201000002","201000003"]),
  course("COMP2231",["201000003","201000001"])
]
true.

In your example you are reading the data from a file but for this example I hard coded that data into the query so that it could be reproduced anywhere without needing to copy a file. Input makes use of \c, see: Character Escape Syntax to keep the formatting of the input nice.

When you load the data from a file and you are not using library(dcg/basics) make use of phrase_from_file/2 or phrase_from_file/3. When you load the data from a file and you are using library(dcg/basics) make use of read_file_to_codes/3. Also check out open_string/2 which might be of use.

You were correct in using library(dcg/basics) but be very careful when using this as the predicates in there expect the input to be charter codes and not atoms or strings.

One predicate that is very common to use when parsing with text with DCGs is string_without//2 but as I noted it works with character codes so string_codes/2 is needed to convert the codes back into a string. Also since string_codes/2 is a standard predicate, it needs to be bookended with {} to let the DCG term rewrite code know that this is not to be translated.

When creating the example I could have added a \n after the last student and added an extra line and made the parser very simple, but chose instead to follow the more real world convention of not adding the \n which required adding the ; (or) parts, e.g. ; [] for the last missing empty line and ; remainder//1 for the missing \n after the last student.

Since I don't know how much more you need to know about this to understand it and I don't want to write a few chapters going over the exact details of all of this, just ask questions if you have them, but I do expect you work with the code and explain why you are not understanding the code by showing examples of what you tried instead of just asking because you can.

I'm really struggling with simply just the I/O

Here is a modified version of the code which uses read_file_to_codes/3.

Note that read_file_to_codes/3 is one of the few predicates that uses a file path/name directly and does not require the use of open/3

File: SO_question_163_courses.txt

MATH2221
       201000001
       201000002

MATH2251
       201000002
       201000003

COMP2231
       201000003
       201000001

:- [library(dcg/basics)].

courses([Course|Courses]) -->
    course(Course),
    courses(Courses), !.
courses([]) --> [].

course(course(Course,Students)) -->
    string_without("\n", Course_codes),
    { string_codes(Course,Course_codes ) },
    "\n",
    students(Students),
    (
        empty_line
    ;
        []
    ).

students([Student|Students]) -->
    student(Student),
    students(Students).
students([]) --> [].

student(Student) -->
    spaces_or_tabs_plus,
    (
        (
            string_without("\n",Student_codes),
            { string_codes(Student,Student_codes) },
            "\n"
        )
    ;
        remainder(Student_codes),
        { string_codes(Student,Student_codes) }
    ).

spaces_or_tabs_plus -->
    space_or_tab,
    spaces_or_tabs_star.

spaces_or_tabs_star -->
    space_or_tab,
    spaces_or_tabs_star.
spaces_or_tabs_star --> [].

space_or_tab -->
    (
        "\s"
    |
        "\t"
    ).

empty_line --> "\n".

example_01 :-
    Input = "\c
MATH2221\n\c
    \t201000001\n\c
    \t201000002\n\c
    \n\c
MATH2251\n\c
    \t201000002\n\c
    \t201000003\n\c
    \n\c
COMP2231\n\c
    \t201000003\n\c
    \t201000001\c
",
    string_codes(Input,Codes),
    parse_courses(Codes,Courses),
    display_courses(Courses).

example_02 :-
    File_name = "C:\\Users\\Groot\\Documents\\Projects\\Prolog\\SO_question_163_courses.txt",
    read_file_to_codes(File_name,Codes,[]),
    parse_courses(Codes,Courses),
    display_courses(Courses).

parse_courses(Codes,Courses) :-
    DCG = courses(Courses),
    phrase(DCG,Codes,Rest),
    assertion( Rest == [] ).

display_courses(Courses) :-
    format('Courses: ~n',[]),
    print_term(Courses,[]).

and some example runs

?- example_01.
Courses:
[ course("MATH2221",["201000001","201000002"]),
  course("MATH2251",["201000002","201000003"]),
  course("COMP2231",["201000003","201000001"])
]
true.

?- example_02.
Courses:
[ course("MATH2221",["201000001","201000002"]),
  course("MATH2251",["201000002","201000003"]),
  course("COMP2231",["201000003","201000001"])
]
true.

Note with SWI-Prolog: The string type and its double quoted syntax

When using SWI-Prolog with a version 7 or higher the meaning of double quotes and back quotes changes and Prolog DCG examples found at StackOverflow, in blogs, papers, etc., will sometimes work as presented and sometimes fail. There will seem to be no reason for this to a beginner and be very frustrating.

The way to solve this is be aware of the values for two Prolog flags:

double quotes and back quotes

double quotes will typically be one of codes,chars,atom,string

back quotes will typically be one of codes,chars,string

You will have to determine what to set them to for the code you are using by  either gaining experience or just trial and error.

Also with Prolog when creating test case using

:- begin_tests(some_dcg).

:- end_tests(some_dcg).

This will create a module and since the flags scope to a module, meaning that if you have multiple modules the flag can be different in each module. So you also have to check/set the flags with the test case module.

Flags take effect from where they are to the end of the module, so if you use set_prolog_flag/2 in a module after the code you expect it to effect, it will not work, the setting of the flag has to be before the code it needs to effect. So unless you have a particular need, put the set_prolog_flag/2 directives at the top of the module.

Now to make it even more confusing, sometimes the setting in the DCG section is not the same as in the test cases, so be aware of this also.

Following is an example of a DCG that has test cases, set both flags in each module and works.

:- module(course,
      [ courses//1,
        parse_courses/2,
        display_courses/1,
        test_course/0
      ]).

test_course :-
    run_tests([course]).

:- [library(dcg/basics)].

:- set_prolog_flag(double_quotes, string).
:- set_prolog_flag(back_quotes, codes).

courses([Course|Courses]) -->
    course(Course),
    courses(Courses), !.
courses([]) --> [].

course(course(Course,Students)) -->
    string_without("\n", Course_codes),
    { string_codes(Course,Course_codes ) },
    "\n",
    students(Students),
    (
        empty_line
    ;
        []
    ).

students([Student|Students]) -->
    student(Student),
    students(Students).
students([]) --> [].

student(Student) -->
    spaces_or_tabs_plus,
    (
        (
            string_without("\n",Student_codes),
            { string_codes(Student,Student_codes) },
            "\n"
        )
    ;
        remainder(Student_codes),
        { string_codes(Student,Student_codes) }
    ).

spaces_or_tabs_plus -->
    space_or_tab,
    spaces_or_tabs_star.

spaces_or_tabs_star -->
    space_or_tab,
    spaces_or_tabs_star.
spaces_or_tabs_star --> [].

space_or_tab -->
    (
        "\s"
    |
        "\t"
    ).

empty_line --> "\n".

parse_courses(Codes,Courses) :-
    DCG = courses(Courses),
    phrase(DCG,Codes,Rest),
    assertion( Rest == [] ).

display_courses(Courses) :-
    format('Courses: ~n',[]),
    print_term(Courses,[]).

:- begin_tests(course).

:- set_prolog_flag(double_quotes, string).
:- set_prolog_flag(back_quotes, codes).

test(001) :-
    Input = "\c
        MATH2221\n\c
            \t201000001\n\c
            \t201000002\n\c
            \n\c
        MATH2251\n\c
            \t201000002\n\c
            \t201000003\n\c
            \n\c
        COMP2231\n\c
            \t201000003\n\c
            \t201000001\c
        ",
    string_codes(Input,Codes),
    parse_courses(Codes,Courses),

    assertion( Courses ==
        [
            course("MATH2221",["201000001","201000002"]),
            course("MATH2251",["201000002","201000003"]),
            course("COMP2231",["201000003","201000001"])
        ]
    ).

test(002) :-
    File_name = "C:\\Users\\Groot\\Documents\\Projects\\Prolog\\SO_question_163_courses.txt",
    read_file_to_codes(File_name,Codes,[]),
    parse_courses(Codes,Courses),

    assertion( Courses ==
        [
            course("MATH2221",["201000001","201000002"]),
            course("MATH2251",["201000002","201000003"]),
            course("COMP2231",["201000003","201000001"])
        ]
    ).

:- end_tests(course).

Running of test cases

?- run_tests.
% PL-Unit: course .. done
% All 2 tests passed
true.

or if you have multiple tests in multiple files and only need to test course

?- test_course.
% PL-Unit: course .. done
% All 2 tests passed
true.

Another thing that can be confusing is that when debugging with gtrace/0 is that a code list and string will be represented as a string with double quotes, e.g. "this is a string", the way to tell them apart is

In the Bindings section will be the list of bound variables locate a variable and right click on it.

There will be a popup dialog, select Details

This will present a window with the bound value display. There are options at the top.

Uncheck Portray

Example code used for following examples

dcg_test :-
    String = "string",
    Codes = [65,66,67],
    Atom = 'abc',
    dcg_test(String,Codes,Atom).

dcg_test(String,Codes,Atom) :-
    true.

Bindings

String example

Codes example

If you are wondering why no one tells you these things about DCGs, I just did; you should try learning this without knowing this, it took me months to realize all of this.

Notes:

I tried to do this using phrase_from_file/3 with dcg/basics, but dcg/basics expected closed list and phrase_from_file/3 creates lazy list and in massaging the code it was turning into a rewrite of the predicates in dcg/basics and dealing with end of stream issues which are some of the biggest problems when learning DCGs.


来源: stackexchange

问:
Extract all unique URL from log with only POST type of the request
I've got a log file with the such type of the records:

41.201.181.27 - [2019-04-06 18:22:02] "GET /images/stands/photo_mois.jpg HTTP/1.1" 304 - "http://example.com/popup.php?choix=mois" "Mozilla/4.0" "-"

I've got the script for getting all records with unique URLs:
cut -f4 -d\" < logfile | sort -u
How i need to change it for getting unique URLs with only POST type of the request?

答:
You can always pipe to cut command. Something like below

grep POST /path/to/myfile.log | cut -f4 -d\"  | sort -u
```

ContentLicense: CC BY-SA 4.0


问:
how do I compare a date in case statement in mysql
I want to compare date data and then assign a new name, here is my query

```<code>SELECT EMPLOYEE_ID,FIRST_NAME,HIRE_DATE
CASE
WHEN HIRE_DATE < DATE('1987-09-01')THEN 'JUNIOR'
WHEN HIRE_DATE BETWEEN DATE('1987-05-01') AND DATE('1987-08-31') THEN 'MID LEVEL SENIOR'
WHEN HIRE_DATE > DATE('1987-05-01') THEN 'SENIOR'
END AS 'experience_level'
FROM employees;
</code>```

there is some error that occurred.
what is my problem?

```<code>SQL query: Documentation

SELECT EMPLOYEE_ID,FIRST_NAME,HIRE_DATE
CASE
WHEN HIRE_DATE < DATE('1987-09-01')THEN 'JUNIOR'
WHEN HIRE_DATE BETWEEN DATE('1987-05-01') AND DATE('1987-08-31') THEN 'MID LEVEL SENIOR'
WHEN HIRE_DATE > DATE('1987-05-01') THEN 'SENIOR'
END AS 'experience_level'
FROM employees LIMIT 0, 25
MySQL said: Documentation
</code>```

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CASE
      WHEN HIRE_DATE < DATE('1987-09-01')THEN 'JUNIOR'
      WHEN HIRE_DATE BETWEEN D' at line 2

答:
You're missing "," after "HIRE_DATE". i.e. your query should be like:</p>

```<code>SELECT EMPLOYEE_ID,FIRST_NAME,HIRE_DATE,
CASE
  WHEN HIRE_DATE < DATE('1987-09-01')THEN 'JUNIOR'
  WHEN HIRE_DATE BETWEEN DATE('1987-05-01') AND DATE('1987-08-31') THEN 'MID LEVEL SENIOR'
  WHEN HIRE_DATE > DATE('1987-05-01') THEN 'SENIOR'
END AS 'experience_level'
FROM employees;
</code>```

Body:
I want to compare date data and then assign a new name, here is my query

SELECT EMPLOYEE_ID,FIRST_NAME,HIRE_DATE
CASE
WHEN HIRE_DATE < DATE('1987-09-01')THEN 'JUNIOR'
WHEN HIRE_DATE BETWEEN DATE('1987-05-01') AND DATE('1987-08-31') THEN 'MID LEVEL SENIOR'
WHEN HIRE_DATE > DATE('1987-05-01') THEN 'SENIOR'
END AS 'experience_level'
FROM employees;

there is some error that occurred.
what is my problem?

SQL query: Documentation

SELECT EMPLOYEE_ID,FIRST_NAME,HIRE_DATE
CASE
WHEN HIRE_DATE < DATE('1987-09-01')THEN 'JUNIOR'
WHEN HIRE_DATE BETWEEN DATE('1987-05-01') AND DATE('1987-08-31') THEN 'MID LEVEL SENIOR'
WHEN HIRE_DATE > DATE('1987-05-01') THEN 'SENIOR'
END AS 'experience_level'
FROM employees LIMIT 0, 25
MySQL said: Documentation

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CASE
      WHEN HIRE_DATE < DATE('1987-09-01')THEN 'JUNIOR'
      WHEN HIRE_DATE BETWEEN D' at line 2

Body:
You're missing "," after "HIRE_DATE". i.e. your query should be like:

SELECT EMPLOYEE_ID,FIRST_NAME,HIRE_DATE,
CASE
  WHEN HIRE_DATE < DATE('1987-09-01')THEN 'JUNIOR'
  WHEN HIRE_DATE BETWEEN DATE('1987-05-01') AND DATE('1987-08-31') THEN 'MID LEVEL SENIOR'
  WHEN HIRE_DATE > DATE('1987-05-01') THEN 'SENIOR'
END AS 'experience_level'
FROM employees;


问:
Pointcloud to Model with CGAL complete beginner, Tutourial? Guide or tips?
I've stumbled upon CGAL and it seems amazing.

Anyone know of any simple ways I can test some of it's magic out without knowing any prior C++ or programming? Or a really thorough guide?

Just to get you an understanding of my general tech level(unrelated to CGAL) I know printf.. prints.. stuff.. but I have no idea how to put that into practice. And I've managed to install npm modules by slamming commands into cmd and run a module afterwards.

If there's no easy beginning to get a taste of this, other tips is also welcome if I have to take a longer route to understanding this.

What I want to achive is my input is pointcloud data scans -> magic/CGAL/ -> 3D models is my output

答:
You can try the 3D polyhedron demo that contains most of the functionalities of CGAL.
You can compile it yourself by compiling the code in demo/Polyhedron from a release or use the pre-compiled windows demo available: demo + dlls to be extracted in the directory of the demo.

Also here is a WIP version of a tutorial that should be integrated in the official documentation soon.


问:
BaseException.message deprecated in Python 2.6
I get a warning that BaseException.message is deprecated in Python 2.6 when I use the following user-defined exception:

```<code>class MyException(Exception):

    def __init__(self, message):
        self.message = message

    def __str__(self):
        return repr(self.message)
</code>```

This is the warning:

DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
self.message = message
```

What's wrong with this? What do I have to change to get rid of the deprecation warning?

答:
Solution - almost no coding needed

Just inherit your exception class from Exception and pass the message as the first parameter to the constructor

Example:

```<code>class MyException(Exception):
    """My documentation"""

try:
    raise MyException('my detailed description')
except MyException as my:
    print my # outputs 'my detailed description'
</code>```

You can use str(my) or (less elegant) my.args[0] to access the custom message.

Background

In the newer versions of Python (from 2.6) we are supposed to inherit our custom exception classes from Exception which (starting from Python 2.5) inherits from BaseException. The background is described in detail in PEP 352.

```<code>class BaseException(object):

    """Superclass representing the base of the exception hierarchy.
    Provides an 'args' attribute that contains all arguments passed
    to the constructor.  Suggested practice, though, is that only a
    single string argument be passed to the constructor."""
</code>```

__str__ and __repr__ are already implemented in a meaningful way,
especially for the case of only one arg (that can be used as message).

You do not need to repeat __str__ or __init__ implementation or create _get_message as suggested by others.

ContentLicense: CC BY-SA 3.0

Body:
I get a warning that BaseException.message is deprecated in Python 2.6 when I use the following user-defined exception:

class MyException(Exception):

    def __init__(self, message):
        self.message = message

    def __str__(self):
        return repr(self.message)

This is the warning:

DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
self.message = message

What's wrong with this? What do I have to change to get rid of the deprecation warning?

Body:
Solution - almost no coding needed

Just inherit your exception class from Exception and pass the message as the first parameter to the constructor

Example:

class MyException(Exception):
    """My documentation"""

try:
    raise MyException('my detailed description')
except MyException as my:
    print my # outputs 'my detailed description'

You can use str(my) or (less elegant) my.args[0] to access the custom message.

Background

In the newer versions of Python (from 2.6) we are supposed to inherit our custom exception classes from Exception which (starting from Python 2.5) inherits from BaseException. The background is described in detail in PEP 352.

class BaseException(object):

    """Superclass representing the base of the exception hierarchy.
    Provides an 'args' attribute that contains all arguments passed
    to the constructor.  Suggested practice, though, is that only a
    single string argument be passed to the constructor."""

__str__ and __repr__ are already implemented in a meaningful way,
especially for the case of only one arg (that can be used as message).

You do not need to repeat __str__ or __init__ implementation or create _get_message as suggested by others.


问:
Eloquent queries without database (data is retrieved from external API)
I have a Laravel web application (website.nl) AND an Laravel API (api.website.nl).

When the user logs in with the login form on the website. A post request is done to the API. When the login request is successfull a token AND User object is send back in the form of a JSON string. The login method looks like this.

```<code>public function login(Request $request)
{
    $email = $request->input('email');
    $password = $request->input('password');

    $response = $this->client->request('POST', self::$apiRootUrl . '/login', [
        'headers'     => [
            'Accept' => 'application/json',
        ],
        'form_params' => [
            'email'    => $email,
            'password' => $password
        ],
    ]);

    $result = json_decode($response->getBody()->getContents());

    if (isset($result->success->token))
    {
        $user = User::create([
            'id'    => $result->success->user->id,
            'name'  => $result->success->user->name,
            'email' => $result->success->user->email,
            'password' => $password
        ]);
        Auth::login($user);
        $this->apiToken = $result->success->token;

        return $this->sendLoginResponse($request);
    }

    return $this->sendFailedLoginResponse($request);
}
</code>```

Where I want this login function to be as stupid as possible, meaning, let the API figure out if this is a valid login request. This method only passes the arguments.

The main website should not have a database. It only uses the API to login, get a token, and do requests with that token to gather data for the user to see on the main website's dashboard.

For this reason my question is this: How can I store the User object retrieved from the API in such a manner that it will be query-able like an Eloquent model. But without the need to store it in a database. Again, the main website shouldn't need a database. It only communicates with the API for it's data.

I hope this question makes sense, if not, please ask for more details.

I don't want to create a duplicate database with migrations on the main website. Because that's the job of the .api subdomain. Also, all the models are used within a session. Never being stored for a longer time, because that's also located in a store method on the .api subdomain.

答:
This would require you to write your own grammar for Eloquent, an ActiveRecord implementation for the API you're using.
In theory it's possible, in practice it's a lot of work.

Take a look here for how Laravel implements the database types it currently supports.
https://laravel.com/api/5.8/Illuminate/Database/Schema/Grammars.html

Body:
I have a Laravel web application (website.nl) AND an Laravel API (api.website.nl).

When the user logs in with the login form on the website. A post request is done to the API. When the login request is successfull a token AND User object is send back in the form of a JSON string. The login method looks like this.

public function login(Request $request)
{
    $email = $request->input('email');
    $password = $request->input('password');

    $response = $this->client->request('POST', self::$apiRootUrl . '/login', [
        'headers'     => [
            'Accept' => 'application/json',
        ],
        'form_params' => [
            'email'    => $email,
            'password' => $password
        ],
    ]);

    $result = json_decode($response->getBody()->getContents());

    if (isset($result->success->token))
    {
        $user = User::create([
            'id'    => $result->success->user->id,
            'name'  => $result->success->user->name,
            'email' => $result->success->user->email,
            'password' => $password
        ]);
        Auth::login($user);
        $this->apiToken = $result->success->token;

        return $this->sendLoginResponse($request);
    }

    return $this->sendFailedLoginResponse($request);
}

Where I want this login function to be as stupid as possible, meaning, let the API figure out if this is a valid login request. This method only passes the arguments.

The main website should not have a database. It only uses the API to login, get a token, and do requests with that token to gather data for the user to see on the main website's dashboard.

For this reason my question is this: How can I store the User object retrieved from the API in such a manner that it will be query-able like an Eloquent model. But without the need to store it in a database. Again, the main website shouldn't need a database. It only communicates with the API for it's data.

I hope this question makes sense, if not, please ask for more details.

I don't want to create a duplicate database with migrations on the main website. Because that's the job of the .api subdomain. Also, all the models are used within a session. Never being stored for a longer time, because that's also located in a store method on the .api subdomain.


问:
How to show passed props in "<Scene/>" "title" attribute in RNRF v4.0.6?
react-native-router-flux v4.0.6, how to show the passed props via
Actions.key({id:1})
and want to display in header navbar
eg. <Scene title={passedProps}>

答: Actions.key({title:'Header Title'})</p>

Body: Actions.key({title:'Header Title'})


问:
multiprocessing creates zombie process even after .join()
I have a chunk of code that I am parallelizing in the following manner:-

```<code>def stats_wrapper(a,b,c,d):
    q = mp.Queue()
    # b here is a dictionary
    processes = [mp.Process(target = stats,args = (a,{b1:b[b1]},c,d,q) ) for b1 in b]
    for p in processes:
        p.start()
    results = []
    for p in processes:
        results.append(q.get())
    return(results)
</code>```

I am seeing a lot of zombie processes after I execute this block. I am trying to use the .join() method the following way before the return(result) line :-

```<code>for p in processes:
   p.join()
</code>```

but that doesn't help with getting rid of the zombie processes. Can someone help me identify exactly where am I going wrong with my code?

Edit: - I am using elsewhere in my code another approach to parallelization which is again giving me a number of zombie processes,except  I don't know how to refactor the code to add a join.

```<code>q = mp.Queue()
jobs = (func1,func2,func3)
args = ((arg1,arg2,arg3),(arg2,arg3),(arg1,arg4))
for job,arg in zip(jobs,args):
   mp.Process(target = job,args = arg,name = str(job.__name__)).start()
result = []
for _ in range(len(job)):
   result.append(q.get())
</code>```

答:
You can try this code for getting results out of queue:</p>

```<code>def stats_wrapper(a,b,c,d):
    q = mp.Queue()
    # b here is a dictionary
    processes = [mp.Process(target = stats,args = (a,{b1:b[b1]},c,d,q)) for b1 in b]
    for p in processes:
        p.start()
    results = []
    for p in processes:
        p.join()
    while not q.empty():
        results.append(q.get())
    return(results)
</code>```

Body:
I have a chunk of code that I am parallelizing in the following manner:-

def stats_wrapper(a,b,c,d):
    q = mp.Queue()
    # b here is a dictionary
    processes = [mp.Process(target = stats,args = (a,{b1:b[b1]},c,d,q) ) for b1 in b]
    for p in processes:
        p.start()
    results = []
    for p in processes:
        results.append(q.get())
    return(results)

I am seeing a lot of zombie processes after I execute this block. I am trying to use the .join() method the following way before the return(result) line :-

for p in processes:
   p.join()

but that doesn't help with getting rid of the zombie processes. Can someone help me identify exactly where am I going wrong with my code?

Edit: - I am using elsewhere in my code another approach to parallelization which is again giving me a number of zombie processes,except  I don't know how to refactor the code to add a join.

q = mp.Queue()
jobs = (func1,func2,func3)
args = ((arg1,arg2,arg3),(arg2,arg3),(arg1,arg4))
for job,arg in zip(jobs,args):
   mp.Process(target = job,args = arg,name = str(job.__name__)).start()
result = []
for _ in range(len(job)):
   result.append(q.get())

Body:
You can try this code for getting results out of queue:

def stats_wrapper(a,b,c,d):
    q = mp.Queue()
    # b here is a dictionary
    processes = [mp.Process(target = stats,args = (a,{b1:b[b1]},c,d,q)) for b1 in b]
    for p in processes:
        p.start()
    results = []
    for p in processes:
        p.join()
    while not q.empty():
        results.append(q.get())
    return(results)


问:
How to set flags inside Jupyter Notebook or Python Shell
I need to run my script named train.py but I also need to set up the flas, by issuing this command in bash:

```<code>train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2_pets.config
</code>```

However, it catches this error:

File
  "/Users/cvsanbuenaventura/miniconda3/lib/python3.6/site-packages/google/protobuf/text_format.py",
  line 1288, in _ConsumeSingleByteString
      raise self.ParseError('String missing ending quote: %r' % (text,)) google.protobuf.text_format.ParseError: 123:17 : String missing ending
  quote:
  '"/Users/cvsanbuenaventura/Documents/tensorflow/models/research/object_detection/train.record“'

So I want to debug in Python Shell or Jupyter Notebook line by line. However I also need to set th train_dir flag. How do I accomplish this?

答:
If anyone else has the problem of not being able to add flags to IPython/Jupyter, here's a quick workaround.</p>

```<code># import sys, app and flags
import sys
sys.argv = " --train_dir training/".split(" ")
from absl import app, flags

# add the flags you need:
flags.FLAGS.train_dir = 'training/'

# add the actual code to a function
def main(argvs):
    # the code you want to debug
app.run(main)
</code>```

Body:
I need to run my script named train.py but I also need to set up the flas, by issuing this command in bash:

train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2_pets.config

However, it catches this error:

File
  "/Users/cvsanbuenaventura/miniconda3/lib/python3.6/site-packages/google/protobuf/text_format.py",
  line 1288, in _ConsumeSingleByteString
      raise self.ParseError('String missing ending quote: %r' % (text,)) google.protobuf.text_format.ParseError: 123:17 : String missing ending
  quote:
  '"/Users/cvsanbuenaventura/Documents/tensorflow/models/research/object_detection/train.record“'

So I want to debug in Python Shell or Jupyter Notebook line by line. However I also need to set th train_dir flag. How do I accomplish this?

Body:
If anyone else has the problem of not being able to add flags to IPython/Jupyter, here's a quick workaround.

# import sys, app and flags
import sys
sys.argv = " --train_dir training/".split(" ")
from absl import app, flags

# add the flags you need:
flags.FLAGS.train_dir = 'training/'

# add the actual code to a function
def main(argvs):
    # the code you want to debug
app.run(main)


问:
Array of objects how do i check for deeply nested text string duplicates & remove from array?
I have an array of objects
Deep inside those objects is a text string
I want to check if other objects in the same array have the same text string / are duplicates.
Then i need a new array with those duplicates removed.

I thought this would be quite simple but it's been testing my intellect for two days now.

```<code>const arr = [
   {..obj 1}
   {..obj 2}
   {..obj 3}
   {
      id: 4,
      uid: 24872-2847-249249892842,
      tags: ['some', 'stuff'],
      type: "blogpage",
      href: "https://link-to-stuff",
      first_publication_date: "2020-02-12T16:05:04+0000",
      last_publication_date: "2020-02-18T21:52:06+0000",
      data: {
            ...some stuff
                  heading: [
                        { type: "heading1", text: "Here Is My Text I Need To Check Duplicates
                   Of"}
                  ]
      }

   }
   {..obj 5}
   {..obj 6}
   {..obj 7}
   {..obj 8}
   {..obj 9}
   {..obj 10}
]

I figured something like:

</code>```

filterOutDuplicates = (blogIndexContent) => {

```<code>let arr = blogIndexContent.pages;

let results = [];

arr.map(each => {
  if (!results || !results.length) {
    results.push(each);
  } else {
    for (let i = 0; i < results.length; i++) {
      const headline = results[i].data.heading[0].text;
      if (headline === each.data.heading[0].text) {
        return;
      } else {
        return results.push(each);
      }
    }
  }
})

console.log('Results :', results); // <-- this just gives me the same 9 blog stories again, no duplicates removed.
</code>```

}

```<code>
What am i doing wrong guys?
</code>```

答:
If you dont mind using lodash, it could be easily solved using _.uniqBy

const withoutDups = _.uniqBy(arr, 'data.heading[0].text')
```

Body:
I have an array of objects
Deep inside those objects is a text string
I want to check if other objects in the same array have the same text string / are duplicates.
Then i need a new array with those duplicates removed.

I thought this would be quite simple but it's been testing my intellect for two days now.

const arr = [
   {..obj 1}
   {..obj 2}
   {..obj 3}
   {
      id: 4,
      uid: 24872-2847-249249892842,
      tags: ['some', 'stuff'],
      type: "blogpage",
      href: "https://link-to-stuff",
      first_publication_date: "2020-02-12T16:05:04+0000",
      last_publication_date: "2020-02-18T21:52:06+0000",
      data: {
            ...some stuff
                  heading: [
                        { type: "heading1", text: "Here Is My Text I Need To Check Duplicates
                   Of"}
                  ]
      }

   }
   {..obj 5}
   {..obj 6}
   {..obj 7}
   {..obj 8}
   {..obj 9}
   {..obj 10}
]

I figured something like:

filterOutDuplicates = (blogIndexContent) => {

let arr = blogIndexContent.pages;

let results = [];

arr.map(each => {
  if (!results || !results.length) {
    results.push(each);
  } else {
    for (let i = 0; i < results.length; i++) {
      const headline = results[i].data.heading[0].text;
      if (headline === each.data.heading[0].text) {
        return;
      } else {
        return results.push(each);
      }
    }
  }
})

console.log('Results :', results); // <-- this just gives me the same 9 blog stories again, no duplicates removed.

}

What am i doing wrong guys?


问:
JQuery on link click to execute curl
I have used curl to fetch a webpage. There are links on this page. On the curl fetched page when I click a link I want JQuery to execute a curl script to fetch that link. I have the following code..

This is my index page which fetches example.com via curl and echos it out.

```<code><html>
<head>
<title>Public</title>
<script type="text/javascript" src="click.js"></script>;
</head>

<?php
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, 'www.example.com');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($ch);
curl_close($ch);
echo $curl_response;
?>
</code>```

click.js
I'm targeting the  tag so when any link is clicked this will execute. Will this work?

```<code>$(".a").click(function(){
$.getScript("curllink.php");
});
</code>```

This is the script I want the js to run when a link with the  tag
curllink.php

```<code><?php
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, 'WHAT DO I PUT HERE?');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($ch);
curl_close($ch);
echo $curl_response;
?>
</code>```

Please could you check over this and fix any errors I have made. Thanks

答:
Although you'll still need to do some parsing of the incoming file, I think you want to intercept the script call and prevent the default behavior.

Your jquery would look more like this:

```<code>$('a').click(function(){
  location.href='curllink.php?url='+escape($(this).attr('href'));
  return false;
});
</code>```

PHP looks like this (removing CURL for simplification:

```<code><?php
  echo file_get_contents($_REQUEST['url']);
</code>```

I haven't tested it, but that should work... Shouldn't need to escape the incoming URL parameter.

Updated JQuery
You will need to put this after you get the page contents.

```<code>$('a').live('click',function (e){
   var href = $(this).attr('href');
   href= href.replace('example.com','your_website.com');
   e.preventDefault();
   window.location.href = href;
   return ;
});
</code>```

Title: JQuery on link click to execute curl

Body:
I have used curl to fetch a webpage. There are links on this page. On the curl fetched page when I click a link I want JQuery to execute a curl script to fetch that link. I have the following code..

This is my index page which fetches example.com via curl and echos it out.

<title>Public</title>
;

<?php
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, 'www.example.com');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($ch);
curl_close($ch);
echo $curl_response;
?>

click.js
I'm targeting the  tag so when any link is clicked this will execute. Will this work?

$(".a").click(function(){
$.getScript("curllink.php");
});

This is the script I want the js to run when a link with the  tag
curllink.php

<?php
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, 'WHAT DO I PUT HERE?');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($ch);
curl_close($ch);
echo $curl_response;
?>

Please could you check over this and fix any errors I have made. Thanks

Body:
Although you'll still need to do some parsing of the incoming file, I think you want to intercept the script call and prevent the default behavior.

Your jquery would look more like this:

$('a').click(function(){
  location.href='curllink.php?url='+escape($(this).attr('href'));
  return false;
});

PHP looks like this (removing CURL for simplification:

<?php
  echo file_get_contents($_REQUEST['url']);

I haven't tested it, but that should work... Shouldn't need to escape the incoming URL parameter.

Updated JQuery
You will need to put this after you get the page contents.

$('a').live('click',function (e){
   var href = $(this).attr('href');
   href= href.replace('example.com','your_website.com');
   e.preventDefault();
   window.location.href = href;
   return ;
});


问:
Indexing Systems of Equations in GAMS
I wanna define a set of indexing equation in GAMS as the following picture. But some errors occur at the term of (A(3-i)-A(i)).
enter link description here</p>

Title: Indexing Systems of Equations in GAMS

Body:
Try this:

act(i).. ac(i)=e=system.exp(power((1-x(i)), 2) * (A(i)+2*x(i)*(A(i+[card(i)+1-2*ord(i)])-A(i))));


问:
Datatables: How can I keep child rows opened after the Ajax reload
I'm using an Ajax source to generate the table. This one is refreshed every 5000 ms and when a child row is opened it's then closed by the table's redraw. How can I keep these ones opened?

My code:

```<code>    /* Formatting function for row details - modify as you need */
    function format ( d ) {
        // `d` is the original data object for the row
        return '<p>Text in child row</p>';
    }

    $(document).ready(function() {
        $('#table').DataTable( {
        ...
        } );

    var tr;
    var row;

    $('#table tbody').on('click', 'td.details-control', function () {

        if (tr !== null && tr !== undefined && row !== null && tr !== undefined) {
            row.child.hide();
            tr.removeClass('shown');
        }

        tr = $(this).closest('tr');
        row = table.row( tr );

        if ( row.child.isShown() ) {
            // This row is already open - close it
            row.child.hide();
            tr.removeClass('shown');
        }
        else {
            // Open this row
            row.child( format(row.data()) ).show();
            tr.addClass('shown');
        }

    } );

    $.fn.dataTable.ext.errMode = 'none';
    var table = $('#table').DataTable();
    setInterval( function () {
        table.ajax.reload( function () {
            if ( row.child.isShown() ) {
                // This row is already open - close it
                row.child.hide();
                tr.removeClass('shown');
            }
            else {
                if (tr.hasClass('shown')) {
                    // Open this row
                    row.child( format(row.data()) ).show();
                    tr.addClass('shown');
                }
            }
        } );
    }, 5000 );

    $('table td .details-control').html('<button><i class="fa fa-plus"></i></button>');

} );
</code>```

See Child rows example and ajax.reload() method for reference.

After some research I've seen that people suggest using cookies in jQuery

答:
Try to store the index value of rows (in global) , which are opened

After the table reloaded, call the following method

```<code>function openChildByIndex(){
        let row = table.row('globally stored index'); //place your index here
        row.child(format(row.data())).show();
        $(row.node()).addClass('shown');
}
</code>```

Body:
I'm using an Ajax source to generate the table. This one is refreshed every 5000 ms and when a child row is opened it's then closed by the table's redraw. How can I keep these ones opened?

My code:

    /* Formatting function for row details - modify as you need */
    function format ( d ) {
        // `d` is the original data object for the row
        return '
Text in child row
';
    }

    $(document).ready(function() {
        $('#table').DataTable( {
        ...
        } );

    var tr;
    var row;

    $('#table tbody').on('click', 'td.details-control', function () {

        if (tr !== null && tr !== undefined && row !== null && tr !== undefined) {
            row.child.hide();
            tr.removeClass('shown');
        }

        tr = $(this).closest('tr');
        row = table.row( tr );

        if ( row.child.isShown() ) {
            // This row is already open - close it
            row.child.hide();
            tr.removeClass('shown');
        }
        else {
            // Open this row
            row.child( format(row.data()) ).show();
            tr.addClass('shown');
        }

    } );

    $.fn.dataTable.ext.errMode = 'none';
    var table = $('#table').DataTable();
    setInterval( function () {
        table.ajax.reload( function () {
            if ( row.child.isShown() ) {
                // This row is already open - close it
                row.child.hide();
                tr.removeClass('shown');
            }
            else {
                if (tr.hasClass('shown')) {
                    // Open this row
                    row.child( format(row.data()) ).show();
                    tr.addClass('shown');
                }
            }
        } );
    }, 5000 );

    $('table td .details-control').html('<button></button>');

} );

See Child rows example and ajax.reload() method for reference.

After some research I've seen that people suggest using cookies in jQuery

Body:
Try to store the index value of rows (in global) , which are opened

After the table reloaded, call the following method

function openChildByIndex(){
        let row = table.row('globally stored index'); //place your index here
        row.child(format(row.data())).show();
        $(row.node()).addClass('shown');
}


问:
Will `mkl_set_num_threads` upper-bound to the number of CPU Threads?
In OpenBLAS, if you  call openblas_set_num_threads asking for a number of threads which is to be higher than the number of CPU threads that you have,
then the actual number of threads it will be set to use is your number of CPU Threads.

This can be seen in the source code

I am wondering if MKL has the same behavior?
The docs do not explicitly mention it.
but they do say:

The number specified is a hint, and Intel® MKL may actually use a smaller number.

答:
It seems to cap at the number of cores (not the number of threads). The code below ran on a 6-Core Intel Core i7:</p>

```<code>julia> using MKL_jll

julia> get_max_threads() = ccall((:mkl_get_max_threads, libmkl_rt), Int32, ());

julia> set_max_threads(n) = ccall((:mkl_set_num_threads, libmkl_rt), Cvoid, (Ptr{Int32},), Ref(Int32(n)));

julia> get_max_threads()
6

julia> set_max_threads(4)

julia> get_max_threads()
4

julia> set_max_threads(8)

julia> get_max_threads() # maxed out at 6
6

julia> set_max_threads(24)

julia> get_max_threads() # maxed out at 6
6

julia> set_max_threads(1)

julia> get_max_threads()
1
</code>```

Body:
It seems to cap at the number of cores (not the number of threads). The code below ran on a 6-Core Intel Core i7:

julia> using MKL_jll

julia> get_max_threads() = ccall((:mkl_get_max_threads, libmkl_rt), Int32, ());

julia> set_max_threads(n) = ccall((:mkl_set_num_threads, libmkl_rt), Cvoid, (Ptr{Int32},), Ref(Int32(n)));

julia> get_max_threads()
6

julia> set_max_threads(4)

julia> get_max_threads()
4

julia> set_max_threads(8)

julia> get_max_threads() # maxed out at 6
6

julia> set_max_threads(24)

julia> get_max_threads() # maxed out at 6
6

julia> set_max_threads(1)

julia> get_max_threads()
1


问:
What is the difference between null and undefined in JavaScript?
I want to know what the difference is between null and undefined in JavaScript.

答:
Check this out. The output is worth thousand words.

var b1 = document.getElementById("b1");

checkif("1, no argument"                        );
checkif("2, undefined explicitly",     undefined);
checkif("3, null explicitly",               null);
checkif("4, the 0",                            0);
checkif("5, empty string",                    '');
checkif("6, string",                    "string");
checkif("7, number",                      123456);

function checkif (a1, a2) {
 print("\ncheckif(), " + a1 + ":");
 if (a2 == undefined) {
  print("==undefined:    YES");
 } else {
  print("==undefined:    NO");
 }
 if (a2 === undefined) {
  print("===undefined:   YES");
 } else {
  print("===undefined:   NO");
 }
 if (a2 == null) {
  print("==null:         YES");
 } else {
  print("==null:         NO");
 }
 if (a2 === null) {
  print("===null:        YES");
 } else {
  print("===null:        NO");
 }
 if (a2 == '') {
  print("=='':           YES");
 } else {
  print("=='':           NO");
 }
 if (a2 === '') {
  print("==='':          YES");
 } else {
  print("==='':          NO");
 }
 if (isNaN(a2)) {
  print("isNaN():        YES");
 } else {
  print("isNaN():        NO");
 }
 if (a2) {
  print("if-?:           YES");
 } else {
  print("if-?:           NO");
 }
  print("typeof():       " + typeof(a2));
}

function print(v) {
 b1.innerHTML += v + "\n";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<body>
<pre id="b1">```

```

See also:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators

Cheers!

Body:
Check this out. The output is worth thousand words.

var b1 = document.getElementById("b1");

checkif("1, no argument"                        );
checkif("2, undefined explicitly",     undefined);
checkif("3, null explicitly",               null);
checkif("4, the 0",                            0);
checkif("5, empty string",                    '');
checkif("6, string",                    "string");
checkif("7, number",                      123456);

function checkif (a1, a2) {
 print("\ncheckif(), " + a1 + ":");
 if (a2 == undefined) {
  print("==undefined:    YES");
 } else {
  print("==undefined:    NO");
 }
 if (a2 === undefined) {
  print("===undefined:   YES");
 } else {
  print("===undefined:   NO");
 }
 if (a2 == null) {
  print("==null:         YES");
 } else {
  print("==null:         NO");
 }
 if (a2 === null) {
  print("===null:        YES");
 } else {
  print("===null:        NO");
 }
 if (a2 == '') {
  print("=='':           YES");
 } else {
  print("=='':           NO");
 }
 if (a2 === '') {
  print("==='':          YES");
 } else {
  print("==='':          NO");
 }
 if (isNaN(a2)) {
  print("isNaN():        YES");
 } else {
  print("isNaN():        NO");
 }
 if (a2) {
  print("if-?:           YES");
 } else {
  print("if-?:           NO");
 }
  print("typeof():       " + typeof(a2));
}

function print(v) {
 b1.innerHTML += v + "\n";
}

<!DOCTYPE html>
<html>
<body>
<pre id="b1"></pre>
</body>
</html>

See also:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators

Cheers!


问:
After stubbing function still it calls the real function
I have stubbed the content of file, so I can run through only outer function

file.html

```<code><body onload ="test('file.txt')">
<body>
</code>```

file.js

```<code>    const fs1 = require('fs');
    let param;
    module.export = {
         test,
         test1,
         param
    }

    function test (outputParam) {
      let fileData = test1(outputParam);
      param = fileData;
    }

    function test1(outputParam) {
       let data = fs1.readFileSync(outputParam);
       return data;
    }

</code>```

Here as you see I load function test from html onload and in turn test1 calls and reads file, I have stubbed this file content as shown in the test below

When I run the test I want to see the variable param has the file content value

test.spec.js

```<code>    let sinon = require("sinon");
    let filejs = require('./file.js');

    it('should run only the outer function' ,function() {

    // I try to stub my function here
    sinon.stub(filejs,'test1').callsFake ((someArg) => {
      return "this is my file content";
    });

        // Now I will call my test function
        filejs.test(someArg);

    })
</code>```

As you seen above I have stubbed function test1, still when I run the test I see test1 gets called and it reads the real file.

I am using mocha , I am new to stub or mock concepts, any suggestion is really appreciated.

答:
You should probably try to stub readFileSync.

```<code>const fs = require('fs');

// ...

sinon.stub(fs, "readFileSync").callsFake ((someArg) => {
  return "this is my file content";
});
</code>```

Besides that, I can spot two issues with your code.

The real readFileSync will return a Buffer if called without a second parameter, not a string like your stub does.

The body onload event only exists inside the DOM. The fs module is only available in Node.js. If you run your code in a browser, you won't be able to use fs.readFileSync. If you run it in Node, your HTML file and the onload event won't be useful.

Body:
I have stubbed the content of file, so I can run through only outer function

file.html

file.js

    const fs1 = require('fs');
    let param;
    module.export = {
         test,
         test1,
         param
    }

    function test (outputParam) {
      let fileData = test1(outputParam);
      param = fileData;
    }

    function test1(outputParam) {
       let data = fs1.readFileSync(outputParam);
       return data;
    }

Here as you see I load function test from html onload and in turn test1 calls and reads file, I have stubbed this file content as shown in the test below

When I run the test I want to see the variable param has the file content value

test.spec.js

    let sinon = require("sinon");
    let filejs = require('./file.js');

    it('should run only the outer function' ,function() {

    // I try to stub my function here
    sinon.stub(filejs,'test1').callsFake ((someArg) => {
      return "this is my file content";
    });

        // Now I will call my test function
        filejs.test(someArg);

    })

As you seen above I have stubbed function test1, still when I run the test I see test1 gets called and it reads the real file.

I am using mocha , I am new to stub or mock concepts, any suggestion is really appreciated.

Body:
You should probably try to stub readFileSync.

const fs = require('fs');

// ...

sinon.stub(fs, "readFileSync").callsFake ((someArg) => {
  return "this is my file content";
});

Besides that, I can spot two issues with your code.

The real readFileSync will return a Buffer if called without a second parameter, not a string like your stub does.

The body onload event only exists inside the DOM. The fs module is only available in Node.js. If you run your code in a browser, you won't be able to use fs.readFileSync. If you run it in Node, your HTML file and the onload event won't be useful.


问:
How do I return to previous state in reactjs?
I have created a sidebar component and set its state to false to hide the block until a user clicks on the hanmburger icon, then the state is shown. However I am trying to return(or close the sidebar menu) when the user clicks on the close 'X' icon. I have written a hideMenu method to return the state to false however it doesnt work, and there are no errors.
 Here is what I have written</p>

```<code>class SubMainNavbar extends React.Component{
  constructor(){
    super();
    this.state = {isShown:false}
    this.showMenu = this.showMenu.bind(this)
    this.hideMenu = this.hideMenu.bind(this)
  }

  showMenu(){
    this.setState({isShown: true})
  }

  hideMenu(){
   this.setState({isShown: false})
  }
  render() {
    return (
      <div className="sub-flex-container">
        <div className="co pt-4">
      <ul className="flex-container sub-list">
        <li>women</li>
        <li>mens</li>
        <li>health & beauty</li>
      </ul>
      <span onClick={this.showMenu} className="pl-3 hamburger hide-big pb-4"><Icon type="menu" />
      <div className="mobile-menu-display" id="mySidebar" style={{display: this.state.isShown ? 'block' : 'none' }}>
        <span onClick={this.hideMenu} className="float-right font-weight-bold hide-big close">X</span>
      </div>
      </span>

    </div>

    <div className="co">
    {/* <a href=""><Logo className="logo" /></a> */}
    <a href=""><img className="img-fluid logo" src={Logo} alt="losode logo"/></a>
    </div>

    <div className="co pt-4">
    <span className="hide-small"><SearchInput /></span>
    <div className="icon-mobile hide-big">
      <ul className="flex-icon sub-flex-container">
        <li><ion-icon name="search-outline"></ion-icon></li>
        <li><ion-icon name="person-outline"></ion-icon></li>
      <li><ion-icon name="basket-outline"></ion-icon></li>
      </ul>
    </div>
    </div>

    </div>
    );
  }
};

export default SubMainNavbar
</code>```

答:
You need to ensure that the event is not passed again to the outer container.
In your case the event is triggered by the inner element which leads to a hideMenu but afterward the event is propagated to the outer container which leads to a recall of showMenu.

Additional reading about the can be found here:
https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation
https://www.w3schools.com/jsref/event_stoppropagation.asp

Seems like Padi Dev also found the problem before me :)

Body:
I have created a sidebar component and set its state to false to hide the block until a user clicks on the hanmburger icon, then the state is shown. However I am trying to return(or close the sidebar menu) when the user clicks on the close 'X' icon. I have written a hideMenu method to return the state to false however it doesnt work, and there are no errors.
 Here is what I have written

class SubMainNavbar extends React.Component{
  constructor(){
    super();
    this.state = {isShown:false}
    this.showMenu = this.showMenu.bind(this)
    this.hideMenu = this.hideMenu.bind(this)
  }

  showMenu(){
    this.setState({isShown: true})
  }

  hideMenu(){
   this.setState({isShown: false})
  }
  render() {
    return (

women

mens

health & beauty

      <Icon type="menu" />

        X

    {/* <Logo className="logo" /> */}

    <SearchInput />

<ion-icon name="search-outline"></ion-icon>

<ion-icon name="person-outline"></ion-icon>

<ion-icon name="basket-outline"></ion-icon>

    );
  }
};

export default SubMainNavbar


问:
What does a lock statement do under the hood?
I see that for using objects which are not thread safe we wrap the code with a lock like this:

```<code>private static readonly Object obj = new Object();

lock (obj)
{
    // thread unsafe code
}
</code>```

So, what happens when multiple threads access the same code (let's assume that it is running in a ASP.NET web application). Are they queued? If so how long will they wait?

What is the performance impact because of using locks?

答: lock is actually hidden Monitor class.</p>

Body:
I see that for using objects which are not thread safe we wrap the code with a lock like this:

private static readonly Object obj = new Object();

lock (obj)
{
    // thread unsafe code
}

So, what happens when multiple threads access the same code (let's assume that it is running in a ASP.NET web application). Are they queued? If so how long will they wait?

What is the performance impact because of using locks?

Body: lock is actually hidden Monitor class.


问:
Docker : persisting data outside of containers for ElasticSearch and Mongo
So I am fairly new to Docker (Docker compose) and I am trying to replace my current setup on Ubuntu 16.04 with containers.  So I had Elasticsearch and MongoDB installed.  Elasticsearch wrote data to /fast/elasticsearch (SSD) and MongoDB wrote data to /data/mongodb (8TB disk)

So I am trying to do the same with Docker-Compose, I think I have it right for Mongo but I cant get ElasticSearch to write to /fast/

```<code>version: '3.2'

services:
  elasticsearch:
    build:
      context: elasticsearch/
      args:
        ELK_VERSION: $ELK_VERSION
    volumes:
      - type: bind
        source: ./elasticsearch/config/elasticsearch.yml
        target: /usr/share/elasticsearch/config/elasticsearch.yml
      - type: volume
        source: elasticsearch
        target: ./fast/elasticsearch

    ports:
      - "9200:9200"
      - "9300:9300"
    environment:
      ES_JAVA_OPTS: "-Xmx2048m -Xms2048m"
      discovery.type: single-node
    networks:
      - skynet

  mongo:
    image: mongo:latest
    restart: always
    volumes:
       - ./data/mongodb:/data/db
    ports:
      - "27017:27017"
    networks:
      - skynet

  burf:
    image: burf2000/burf-search-azure:v1.0.0
    restart: always
    ports:
      - "8888:80"
    networks:
        - skynet

networks:
  skynet:
    driver: bridge

volumes:
  elasticsearch:
</code>```

答:
version: '3.2'

```<code>services:
  elasticsearch:
    volumes:
      ...
      - /fast/elasticsearch:/path/your/setup/on/your/config
      # /host/absolute/path:/container/absolute/path
</code>```

The way you make it work with mongo works the same way for elasticsearch. or maybe I don't get your issue

Body:
So I am fairly new to Docker (Docker compose) and I am trying to replace my current setup on Ubuntu 16.04 with containers.  So I had Elasticsearch and MongoDB installed.  Elasticsearch wrote data to /fast/elasticsearch (SSD) and MongoDB wrote data to /data/mongodb (8TB disk)

So I am trying to do the same with Docker-Compose, I think I have it right for Mongo but I cant get ElasticSearch to write to /fast/

version: '3.2'

services:
  elasticsearch:
    build:
      context: elasticsearch/
      args:
        ELK_VERSION: $ELK_VERSION
    volumes:
      - type: bind
        source: ./elasticsearch/config/elasticsearch.yml
        target: /usr/share/elasticsearch/config/elasticsearch.yml
      - type: volume
        source: elasticsearch
        target: ./fast/elasticsearch

    ports:
      - "9200:9200"
      - "9300:9300"
    environment:
      ES_JAVA_OPTS: "-Xmx2048m -Xms2048m"
      discovery.type: single-node
    networks:
      - skynet

  mongo:
    image: mongo:latest
    restart: always
    volumes:
       - ./data/mongodb:/data/db
    ports:
      - "27017:27017"
    networks:
      - skynet

  burf:
    image: burf2000/burf-search-azure:v1.0.0
    restart: always
    ports:
      - "8888:80"
    networks:
        - skynet

networks:
  skynet:
    driver: bridge

volumes:
  elasticsearch:

Body:
version: '3.2'

services:
  elasticsearch:
    volumes:
      ...
      - /fast/elasticsearch:/path/your/setup/on/your/config
      # /host/absolute/path:/container/absolute/path

The way you make it work with mongo works the same way for elasticsearch. or maybe I don't get your issue


问:
Collect data from object separated by comma and make themselves as individual object - Javascript
I have an array contening various objects. These objects contain data separated by comma. I would like to remove each of these data from Object and make them as an individual object (including same date):

```<code>Array = [3]
 0: Object { year: "march 2019", "turnover": 120, "employee": 1000, "cars":232 }
 1: Object { year: "april 2019", "turnover": 123, "employee": 1340, "cars":682 }
 2: Object { year: "june 2019", "turnover": 1343, "employee": 760, "cars": 4345 }

</code>```

my goal is to extract data from each object and make them object himself with the same date:

```<code>Array = [9]
 0: Object { year: "march 2019", "turnover": 120 }
 1: Object { year: "march 2019" , "employee": 1000 }
 2: Object { year: "march 2019", "cars":232 }
 3: Object { year: "april 2019", "turnover": 123 }
 4: Object { year: "april 2019", "employee": 1340 }
 5: Object { year: "april 2019","cars":682 }
 6: Object { year: "june 2019", "turnover": 1343 }
 7: Object { year: "june 2019", "employee": 760 }
 8: Object { year: "june 2019","cars": 4345 }

</code>```

I appreciate your help

Thanks

答:
You can make use of object destructuring and Object.keys() combined with a simple iteration:

var array = [
   { year: "march 2019", "turnover": 120, "employee": 1000, "cars":232 },
   { year: "april 2019", "turnover": 123, "employee": 1340, "cars":682 },
   { year: "june 2019", "turnover": 1343, "employee": 760, "cars": 4345 }
];

var result = [];

array.forEach((entry) => {

  var { year, ...rest } = entry;
  Object.keys(rest).forEach((key) => result.push({ year, [key]: rest[key] }));
});

console.log(result);```

Body:
I have an array contening various objects. These objects contain data separated by comma. I would like to remove each of these data from Object and make them as an individual object (including same date):

Array = [3]
 0: Object { year: "march 2019", "turnover": 120, "employee": 1000, "cars":232 }
 1: Object { year: "april 2019", "turnover": 123, "employee": 1340, "cars":682 }
 2: Object { year: "june 2019", "turnover": 1343, "employee": 760, "cars": 4345 }

my goal is to extract data from each object and make them object himself with the same date:

Array = [9]
 0: Object { year: "march 2019", "turnover": 120 }
 1: Object { year: "march 2019" , "employee": 1000 }
 2: Object { year: "march 2019", "cars":232 }
 3: Object { year: "april 2019", "turnover": 123 }
 4: Object { year: "april 2019", "employee": 1340 }
 5: Object { year: "april 2019","cars":682 }
 6: Object { year: "june 2019", "turnover": 1343 }
 7: Object { year: "june 2019", "employee": 760 }
 8: Object { year: "june 2019","cars": 4345 }

I appreciate your help

Thanks


答:
If you're willing to try the higher-level multiprocessing.Pool(),

def stats_wrapper(a, b, c, d):
    with multiprocessing.Pool() as p:
        args = [(a, {b1: b[b1]}, c, d) for b1 in b]
        return list(p.starmap(stats, args))
```

should be equivalent (aside from q not being passed to stats;  that function can simply return the result).

If you don't need the results to be in order, use p.imap_unordered(), which can use the process pool more efficiently.

Title: multiprocessing creates zombie process even after .join()

Body:
I have a chunk of code that I am parallelizing in the following manner:-

def stats_wrapper(a,b,c,d):
    q = mp.Queue()
    # b here is a dictionary
    processes = [mp.Process(target = stats,args = (a,{b1:b[b1]},c,d,q) ) for b1 in b]
    for p in processes:
        p.start()
    results = []
    for p in processes:
        results.append(q.get())
    return(results)

I am seeing a lot of zombie processes after I execute this block. I am trying to use the .join() method the following way before the return(result) line :-

for p in processes:
   p.join()

but that doesn't help with getting rid of the zombie processes. Can someone help me identify exactly where am I going wrong with my code?

Edit: - I am using elsewhere in my code another approach to parallelization which is again giving me a number of zombie processes,except  I don't know how to refactor the code to add a join.

q = mp.Queue()
jobs = (func1,func2,func3)
args = ((arg1,arg2,arg3),(arg2,arg3),(arg1,arg4))
for job,arg in zip(jobs,args):
   mp.Process(target = job,args = arg,name = str(job.__name__)).start()
result = []
for _ in range(len(job)):
   result.append(q.get())

Body:
If you're willing to try the higher-level multiprocessing.Pool(),

def stats_wrapper(a, b, c, d):
    with multiprocessing.Pool() as p:
        args = [(a, {b1: b[b1]}, c, d) for b1 in b]
        return list(p.starmap(stats, args))

should be equivalent (aside from q not being passed to stats;  that function can simply return the result).

If you don't need the results to be in order, use p.imap_unordered(), which can use the process pool more efficiently.


问:
Argparse SystemExit: 2
My code...

```<code>import numpy as np
import argparse
import imutils
import sys
import cv2 as cv

ap = argparse.ArgumentParser()
ap.add_argument("-m", "--model", required=True,   help = "path to trained activity recognition
model")
ap.add_argument("-c", "--classes", required=True, help = "path to class label file")
ap.add_argument("-i", "--input", type = str, default = "", help = "optional file to video file")

args = vars(ap.parse_args())
</code>```

I'm following this tutorial. Here getting the error is

usage: ipykernel_launcher.py [-h] -m MODEL -c CLASSES [-i INPUT]
ipykernel_launcher.py: error: the following arguments are required: -m/--model, -c/--classes

An exception has occurred, use %tb to see the full traceback.

SystemExit: 2

答: For argparse, you need to supply the arguments on the command line. For example, you can save the script as script.py and run as python script.py -m somemodel -c someclass to give the required arguments. If you are using an IDE such as Spyder, it should have an option to supply command line arguments somewhere.

Title: Argparse SystemExit: 2

Body:
My code...

import numpy as np
import argparse
import imutils
import sys
import cv2 as cv

ap = argparse.ArgumentParser()
ap.add_argument("-m", "--model", required=True,   help = "path to trained activity recognition
model")
ap.add_argument("-c", "--classes", required=True, help = "path to class label file")
ap.add_argument("-i", "--input", type = str, default = "", help = "optional file to video file")

args = vars(ap.parse_args())

I'm following this tutorial. Here getting the error is

usage: ipykernel_launcher.py [-h] -m MODEL -c CLASSES [-i INPUT]
ipykernel_launcher.py: error: the following arguments are required: -m/--model, -c/--classes

An exception has occurred, use %tb to see the full traceback.

SystemExit: 2


问:
Setting time out in apache http client
I'm using Apache http client 4.3.2 to send get requests. What I have done is:

```<code>private final RequestConfig requestConfig = RequestConfig.custom()
        .setConnectTimeout(1000)
        .setConnectionRequestTimeout(1000)
        .setSocketTimeout(1000)
        .build();
private final HttpClient client = HttpClientBuilder.create()
        .disableAuthCaching()
        .disableAutomaticRetries()
        .disableConnectionState()
        .disableContentCompression()
        .disableCookieManagement()
        .disableRedirectHandling()
        .setDefaultRequestConfig(requestConfig)
        .build();
</code>```

And when sending request:

```<code>HttpGet request = null;

try {
    request = new HttpGet(url);
    if (client.execute(request).getStatusLine().getStatusCode() == 200) {
        /* do some work here */
    }
} catch (Exception e) {
    Logger.error(e);
} finally {
    if (request != null) {
        request.releaseConnection();
    }
}
</code>```

But some of my requests still takes long time to timeout. This is stack trace of exception:

```<code>java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:152)
    at java.net.SocketInputStream.read(SocketInputStream.java:122)
    at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:136)
    at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:152)
    at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:270)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:140)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:57)
    at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:260)
    at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:161)
    at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.http.impl.conn.CPoolProxy.invoke(CPoolProxy.java:138)
    at com.sun.proxy.$Proxy0.receiveResponseHeader(Unknown Source)
    at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:271)
    at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:123)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:254)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:186)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:57)
</code>```

Is there any other time out value I should set? What am I doing wrong?

答:
```<code>private static final Integer TIMEOUT = 300;
private static final Integer MILLISECONDS = 1000;

RequestConfig config =
RequestConfig.custom()
             .setConnectTimeout(TIMEOUT * MILLISECONDS)
             .setConnectionRequestTimeout(TIMEOUT * MILLISECONDS)
             .setSocketTimeout(TIMEOUT * MILLISECONDS)
             .build();

httpClientBuilder.setDefaultRequestConfig(config);
httpClientBuilder.setSSLSocketFactory(sslConnectionSocketFactory);
</code>```

I am geting failed: Connection timed out: connect error for 20 seconds even though i have set time 5 minutes.

Title: Setting time out in apache http client

Body:
I'm using Apache http client 4.3.2 to send get requests. What I have done is:

private final RequestConfig requestConfig = RequestConfig.custom()
        .setConnectTimeout(1000)
        .setConnectionRequestTimeout(1000)
        .setSocketTimeout(1000)
        .build();
private final HttpClient client = HttpClientBuilder.create()
        .disableAuthCaching()
        .disableAutomaticRetries()
        .disableConnectionState()
        .disableContentCompression()
        .disableCookieManagement()
        .disableRedirectHandling()
        .setDefaultRequestConfig(requestConfig)
        .build();

And when sending request:

HttpGet request = null;

try {
    request = new HttpGet(url);
    if (client.execute(request).getStatusLine().getStatusCode() == 200) {
        /* do some work here */
    }
} catch (Exception e) {
    Logger.error(e);
} finally {
    if (request != null) {
        request.releaseConnection();
    }
}

But some of my requests still takes long time to timeout. This is stack trace of exception:

java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:152)
    at java.net.SocketInputStream.read(SocketInputStream.java:122)
    at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:136)
    at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:152)
    at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:270)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:140)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:57)
    at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:260)
    at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:161)
    at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.http.impl.conn.CPoolProxy.invoke(CPoolProxy.java:138)
    at com.sun.proxy.$Proxy0.receiveResponseHeader(Unknown Source)
    at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:271)
    at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:123)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:254)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:186)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:57)

Is there any other time out value I should set? What am I doing wrong?

Body:
private static final Integer TIMEOUT = 300;
private static final Integer MILLISECONDS = 1000;

RequestConfig config =
RequestConfig.custom()
             .setConnectTimeout(TIMEOUT * MILLISECONDS)
             .setConnectionRequestTimeout(TIMEOUT * MILLISECONDS)
             .setSocketTimeout(TIMEOUT * MILLISECONDS)
             .build();

httpClientBuilder.setDefaultRequestConfig(config);
httpClientBuilder.setSSLSocketFactory(sslConnectionSocketFactory);

I am geting failed: Connection timed out: connect error for 20 seconds even though i have set time 5 minutes.


问:
add a view to window in react native
I'm developing a react native app primarily for android. I am trying to add a sticky view to the window of the phone, as in iOS, where I can easily access the Window and add a subview to it. But I am struggling with how to do it with react-native.

答:
You can achieve that by using position: 'absolute' and zIndex.

Wrap the whole app with a single view and add to it style={{position: absolute}}

See an example here:

```<code><View style={{flex: 1}}>
  <View style={{position: 'absolute', zIndex: 999}}>...</>
  <SomeView/>
</View>
</code>```

Title: add a view to window in react native

Body:
You can achieve that by using position: 'absolute' and zIndex.

Wrap the whole app with a single view and add to it style={{position: absolute}}

See an example here:

<View style={{flex: 1}}>
  <View style={{position: 'absolute', zIndex: 999}}>...</>
  <SomeView/>
</View>


问:
Excel Deletes query table connection while running VBA macro
I am struggling with an interesting problem that I have never experienced before and cannot seem to find any information about online. Here is the setup:

I am looping through a set of rows in a table - each row has a column for sheet name and a link from which I want to webscrape some data. I have written VBA code which loops through each row, creates a new sheet with the correct name, creates a querytable in that sheet, web scrapes the correct link and deletes the querytable.

Here is the code:

```<code>Sub WQ_Refresh(wsname As String, wqName As String, wqURL As String, strFC As String)

Dim ws As Worksheet
Dim wq As QueryTable
Dim errno As Long
Dim loopcnt As Integer
Dim refreshTime As Double
Dim lastrow As Long

refreshTime = Timer

Application.StatusBar = "Now downloading " & wqName & " for " & strFC

If wsname = "" Then Exit Sub

Set ws = ThisWorkbook.Sheets(wsname)

    If ws.QueryTables.Count > 0 Then

    Set wq = ws.QueryTables(1)

    wq.Delete

End If

lastrow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row

If lastrow > 1 Then lastrow = lastrow + 1

Set wq = ws.QueryTables.Add(Connection:="URL;" & wqURL, Destination:=ws.Range("A" & lastrow))

errno = 1
loopcnt = 0

Do While Not (errno = 0 And loopcnt < 10)

    On Error Resume Next

    With wq

        .FieldNames = True
        .WebFormatting = xlWebFormattingNone
        .WebSelectionType = xlAllTables
        .Refresh BackgroundQuery:=False
        .Delete

    End With

    loopcnt = loopcnt + 1
    errno = Err.Number

    If loopcnt = 10 Then HashtagFail wqName

    On Error GoTo 0

Loop

If lastrow > 1 Then

   ws.Rows(lastrow - 1 & ":" & lastrow).Delete

End If

Set wq = Nothing

Application.StatusBar = "Downloaded " & wqName & " in " & Round(Timer - refreshTime, 0) & " seconds"
</code>```

For some reason that I cannot understand, the wq.Delete function will correctly delete the created wq but it will also remove a connection in another sheet which is set up manually as part of the file.

To be clear - it does not DELETE the connection. It is still there but if you look at its properties, and go to the Used In tab, it shows as no longer used in any sheet.

I have no idea why this is happening - for me, the code should clearly delete only the connection in the sheet in the loop and not impact any other connections in the file.

This seems like a fundamental excel bug but I'd really like any input you have because I'm completely stuck.

Appreciate your help!

答:
Based on the comment form @DeanDeVilliers The solution that worked was to reference the table by name. Here is the working code if anyone is curious</p>

```<code>Sub WQ_Refresh(wsname As String, wqName As String, wqURL As String, strFC As String)
Dim ws As Worksheet
Dim wq As QueryTable
Dim errno As Long
Dim loopcnt As Integer
Dim refreshTime As Double
Dim lastrow As Long

refreshTime = Timer

Application.StatusBar = "Now downloading " & wqName & " for " & strFC

If wsname = "" Then Exit Sub

Set ws = ThisWorkbook.Sheets(wsname)

    If ws.QueryTables.Count > 0 Then ws.QueryTables("WQ_" & wqName).Delete

lastrow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row

If lastrow > 1 Then lastrow = lastrow + 1

Set wq = ws.QueryTables.Add(Connection:="URL;" & wqURL, Destination:=ws.Range("A" & lastrow))

errno = 1
loopcnt = 0

Do While Not (errno = 0 And loopcnt < 10)

    On Error Resume Next

    With wq

        .FieldNames = True
        .WebFormatting = xlWebFormattingNone
        .WebSelectionType = xlAllTables
        .Refresh BackgroundQuery:=False
        .Name = "WQ_" & wqName
        ' .Delete

    End With

    loopcnt = loopcnt + 1
    errno = Err.Number

    If loopcnt = 10 Then HashtagFail wqName

    On Error GoTo 0

ws.QueryTables("WQ_" & wqName).Delete

Loop

If lastrow > 1 Then

   ws.Rows(lastrow - 1 & ":" & lastrow).Delete

End If

Set wq = Nothing

Application.StatusBar = "Downloaded " & wqName & " in " & Round(Timer - refreshTime, 0) & " seconds"

End Sub
</code>```

Body:
I am struggling with an interesting problem that I have never experienced before and cannot seem to find any information about online. Here is the setup:

I am looping through a set of rows in a table - each row has a column for sheet name and a link from which I want to webscrape some data. I have written VBA code which loops through each row, creates a new sheet with the correct name, creates a querytable in that sheet, web scrapes the correct link and deletes the querytable.

Here is the code:

Sub WQ_Refresh(wsname As String, wqName As String, wqURL As String, strFC As String)

Dim ws As Worksheet
Dim wq As QueryTable
Dim errno As Long
Dim loopcnt As Integer
Dim refreshTime As Double
Dim lastrow As Long

refreshTime = Timer

Application.StatusBar = "Now downloading " & wqName & " for " & strFC

If wsname = "" Then Exit Sub

Set ws = ThisWorkbook.Sheets(wsname)

    If ws.QueryTables.Count > 0 Then

    Set wq = ws.QueryTables(1)

    wq.Delete

End If

lastrow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row

If lastrow > 1 Then lastrow = lastrow + 1

Set wq = ws.QueryTables.Add(Connection:="URL;" & wqURL, Destination:=ws.Range("A" & lastrow))

errno = 1
loopcnt = 0

Do While Not (errno = 0 And loopcnt < 10)

    On Error Resume Next

    With wq

        .FieldNames = True
        .WebFormatting = xlWebFormattingNone
        .WebSelectionType = xlAllTables
        .Refresh BackgroundQuery:=False
        .Delete

    End With

    loopcnt = loopcnt + 1
    errno = Err.Number

    If loopcnt = 10 Then HashtagFail wqName

    On Error GoTo 0

Loop

If lastrow > 1 Then

   ws.Rows(lastrow - 1 & ":" & lastrow).Delete

End If

Set wq = Nothing

Application.StatusBar = "Downloaded " & wqName & " in " & Round(Timer - refreshTime, 0) & " seconds"

For some reason that I cannot understand, the wq.Delete function will correctly delete the created wq but it will also remove a connection in another sheet which is set up manually as part of the file.

To be clear - it does not DELETE the connection. It is still there but if you look at its properties, and go to the Used In tab, it shows as no longer used in any sheet.

I have no idea why this is happening - for me, the code should clearly delete only the connection in the sheet in the loop and not impact any other connections in the file.

This seems like a fundamental excel bug but I'd really like any input you have because I'm completely stuck.

Appreciate your help!

Body:
Based on the comment form @DeanDeVilliers The solution that worked was to reference the table by name. Here is the working code if anyone is curious

Sub WQ_Refresh(wsname As String, wqName As String, wqURL As String, strFC As String)
Dim ws As Worksheet
Dim wq As QueryTable
Dim errno As Long
Dim loopcnt As Integer
Dim refreshTime As Double
Dim lastrow As Long

refreshTime = Timer

Application.StatusBar = "Now downloading " & wqName & " for " & strFC

If wsname = "" Then Exit Sub

Set ws = ThisWorkbook.Sheets(wsname)

    If ws.QueryTables.Count > 0 Then ws.QueryTables("WQ_" & wqName).Delete

lastrow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row

If lastrow > 1 Then lastrow = lastrow + 1

Set wq = ws.QueryTables.Add(Connection:="URL;" & wqURL, Destination:=ws.Range("A" & lastrow))

errno = 1
loopcnt = 0

Do While Not (errno = 0 And loopcnt < 10)

    On Error Resume Next

    With wq

        .FieldNames = True
        .WebFormatting = xlWebFormattingNone
        .WebSelectionType = xlAllTables
        .Refresh BackgroundQuery:=False
        .Name = "WQ_" & wqName
        ' .Delete

    End With

    loopcnt = loopcnt + 1
    errno = Err.Number

    If loopcnt = 10 Then HashtagFail wqName

    On Error GoTo 0

ws.QueryTables("WQ_" & wqName).Delete

Loop

If lastrow > 1 Then

   ws.Rows(lastrow - 1 & ":" & lastrow).Delete

End If

Set wq = Nothing

Application.StatusBar = "Downloaded " & wqName & " in " & Round(Timer - refreshTime, 0) & " seconds"

End Sub