问:
Sentence parsing and matching in Prolog
I'm trying to create a sentence parser in Prolog. I want the sentence to be parsed into three separate lists that will be matched with a suggested outcome.

For example, here's the code I have come up with so far...

This is the vocabulary which will be used to parse certain words:

```<code>det(the).
det(a).
det(an).
noun(cat).
noun(boy).
noun(girl).
noun(grandfather).
noun(person).
noun(mat).
noun(party).
noun(book).
noun(problem).
noun(father).
noun(student).
noun(golf).
noun(conversation).
noun(challenge).
noun(person).
noun(problem).
noun(sat).
verb(thrives).
verb(loves).
verb(likes).
prep(on).
prep(with).
adj(big).
adj(lonely).
adj(elderly).
adj(teenage).
adj(good).
adj(fat).

sentence(Sentence,sentence(Noun_Phrase,Verb_Phrase)):-
      np(Sentence,Noun_Phrase,Rem),
      vp(Rem,Verb_Phrase).
</code>```

Code for parsing:

```<code>np([X|T],np(det(X),NP2),Rem):- /* Det NP2 */
    det(X),
    np2(T,NP2,Rem).
np(Sentence,Parse,Rem):- np2(Sentence,Parse,Rem). /* NP2 */
np(Sentence,np(NP,PP),Rem):- /* NP PP */
    np(Sentence,NP,Rem1),
    pp(Rem1,PP,Rem).

np2([H|T],np2(noun(H)),T):- noun(H). /* Noun */
np2([H|T],np2(adj(H),Rest),Rem):- adj(H),np2(T,Rest,Rem).

pp([H|T],pp(prep(H),Parse),Rem):- /* PP NP */
    prep(H),
    np(T,Parse,Rem).

vp([H| []], vp(verb(H))):- /* Verb */
    verb(H).

vp([H|T], vp(verb(H), Rem)):- /* VP PP */
    vp(H, Rem),
    pp(T, Rem, _).

vp([H|T], vp(verb(H), Rem)):- /* Verb NP */
    verb(H),
    np(T, Rem, _).
</code>```

I then want to get the output from this with something like this...

```<code>?- sentence([a,very,young,boy,loves,a,manual,problem],Parse).
</code>```

And then somehow suggest a present out of a fact like this...

```<code>present(construction_kit, subject(very,young,boy), verb(loves), object(manual,problem)).
present(a_golfing_sweater, subject(young,father), verb(loves), object(golf)).
</code>```

As you can probably see, I would want to match this with the 'construction_kit' present.

答:
Let's try and trim this down to a small problem so we can see how we might approach it. Let's start with a simpler grammar.

```<code>sentence(NP, VP) --> noun_phrase(NP), verb_phrase(VP).
noun_phrase(np(Noun, Adj)) --> det, adjectives(Adj), noun(Noun).

det --> [D], { det(D) }.
det --> [].

noun(N) --> [N], { noun(N) }.

adjectives([]) --> [].
adjectives([A|As]) --> adjective(A), adjectives(As).
adjective(A) --> [A], { adj(A) }.

verb_phrase(vp(Verb, Noun)) --> verb(Verb), noun_phrase(Noun).

verb(V) --> [V], { verb(V) }.
</code>```

This is not a complete grammar even for your problem, but it will parse some sentences:

```<code>?- phrase(sentence(NP,VP), [a,teenage,boy,loves,a,big,problem]).
NP = np(boy, [teenage]),
VP = vp(loves, np(problem, [big]))
</code>```

Now we can make a present database. I'm just going to consider the "head" of the noun phrase for now.

```<code>present('construction kit', boy, loves, problem).
</code>```

Now you can deploy a very simple query to try and match them up:

```<code>?- phrase(sentence(np(Noun,_), vp(Verb, np(Object, _))),
   [a,teenage,boy,loves,a,big,problem]),
   present(Suggestion, Noun, Verb, Object).
Noun = boy,
Verb = loves,
Object = problem,
Suggestion = 'construction kit' ;
</code>```

Now you can see immediately your biggest problem: if you try to match a more complex grammar, you're going to have to have a corresponding increase in the complexity of your query which turns that into a suggestion. The solution to this kind of problem, where two things appear to increase in complexity in concert, is always to create an abstraction between them, but that is out of scope for this question.

Edit It's worth noting that if you want to build a general recommendation system, this is not a modern approach. I would recommend the book Programming Collective Intelligence for a quick overview of several approaches, backed by fairly readable Python.

Edit Is it clear that making the grammar more complex will result in more complexity in matching presents?

For starters, I have omitted entirely your prepositional phrase production. I just didn't include that. If it were there, would it have bearing on the suggestion? Consider a sentence like "a teenage boy who loves to code loves a big problem"—the natural extension of my noun_phrase//1 to cover this case will miss out on an important detail of this child which might lead you to a different present than the construction set.

Supposing you want to handle that supplemental information, you will have to add more patterns to the first argument to phrase/3. In fact, you'll probably accept whatever comes out and then dispatch to some kind of suggestion system.

One thing @TomasBy gets right is that we are using a very simple intermediate representation here, which is just (noun,verb,object). But if we make the grammar more complex, we will have to capture and handle more of it in this representation which will raise the complexity of the suggestion system. I don't see how to extend this simple representation to handle prepositional phrases, for instance, unless you just throw them away.

Converting the DCG back to ordinary Prolog

This is straightforward to do, but Prolog will do it for you. You can simply load the DCG above and use listing/0 to get the answer.

```<code>| ?- listing.

% file: user

sentence(A, B, C, D) :-
    noun_phrase(A, C, E),
    verb_phrase(B, E, D).

noun_phrase(np(A, B), C, D) :-
    det(C, E),
    adjectives(B, E, F),
    noun(A, F, D).

det([A|B], C) :-
    det(A),
    B = C.
det(A, A).

noun(A, [A|B], C) :-
    noun(A),
    B = C.

adjectives([], A, A).
adjectives([A|B], C, D) :-
    adjective(A, C, E),
    adjectives(B, E, D).

adjective(A, [A|B], C) :-
    adj(A),
    B = C.

verb_phrase(vp(A, B), C, D) :-
    verb(A, C, E),
    noun_phrase(B, E, D).

verb(A, [A|B], C) :-
    verb(A),
    B = C.
</code>```

Title: Sentence parsing and matching in Prolog

Body:
I'm trying to create a sentence parser in Prolog. I want the sentence to be parsed into three separate lists that will be matched with a suggested outcome.

For example, here's the code I have come up with so far...

This is the vocabulary which will be used to parse certain words:

det(the).
det(a).
det(an).
noun(cat).
noun(boy).
noun(girl).
noun(grandfather).
noun(person).
noun(mat).
noun(party).
noun(book).
noun(problem).
noun(father).
noun(student).
noun(golf).
noun(conversation).
noun(challenge).
noun(person).
noun(problem).
noun(sat).
verb(thrives).
verb(loves).
verb(likes).
prep(on).
prep(with).
adj(big).
adj(lonely).
adj(elderly).
adj(teenage).
adj(good).
adj(fat).

sentence(Sentence,sentence(Noun_Phrase,Verb_Phrase)):-
      np(Sentence,Noun_Phrase,Rem),
      vp(Rem,Verb_Phrase).

Code for parsing:

np([X|T],np(det(X),NP2),Rem):- /* Det NP2 */
    det(X),
    np2(T,NP2,Rem).
np(Sentence,Parse,Rem):- np2(Sentence,Parse,Rem). /* NP2 */
np(Sentence,np(NP,PP),Rem):- /* NP PP */
    np(Sentence,NP,Rem1),
    pp(Rem1,PP,Rem).

np2([H|T],np2(noun(H)),T):- noun(H). /* Noun */
np2([H|T],np2(adj(H),Rest),Rem):- adj(H),np2(T,Rest,Rem).

pp([H|T],pp(prep(H),Parse),Rem):- /* PP NP */
    prep(H),
    np(T,Parse,Rem).

vp([H| []], vp(verb(H))):- /* Verb */
    verb(H).

vp([H|T], vp(verb(H), Rem)):- /* VP PP */
    vp(H, Rem),
    pp(T, Rem, _).

vp([H|T], vp(verb(H), Rem)):- /* Verb NP */
    verb(H),
    np(T, Rem, _).

I then want to get the output from this with something like this...

?- sentence([a,very,young,boy,loves,a,manual,problem],Parse).

And then somehow suggest a present out of a fact like this...

present(construction_kit, subject(very,young,boy), verb(loves), object(manual,problem)).
present(a_golfing_sweater, subject(young,father), verb(loves), object(golf)).

As you can probably see, I would want to match this with the 'construction_kit' present.

Body:
Let's try and trim this down to a small problem so we can see how we might approach it. Let's start with a simpler grammar.

sentence(NP, VP) --> noun_phrase(NP), verb_phrase(VP).
noun_phrase(np(Noun, Adj)) --> det, adjectives(Adj), noun(Noun).

det --> [D], { det(D) }.
det --> [].

noun(N) --> [N], { noun(N) }.

adjectives([]) --> [].
adjectives([A|As]) --> adjective(A), adjectives(As).
adjective(A) --> [A], { adj(A) }.

verb_phrase(vp(Verb, Noun)) --> verb(Verb), noun_phrase(Noun).

verb(V) --> [V], { verb(V) }.

This is not a complete grammar even for your problem, but it will parse some sentences:

?- phrase(sentence(NP,VP), [a,teenage,boy,loves,a,big,problem]).
NP = np(boy, [teenage]),
VP = vp(loves, np(problem, [big]))

Now we can make a present database. I'm just going to consider the "head" of the noun phrase for now.

present('construction kit', boy, loves, problem).

Now you can deploy a very simple query to try and match them up:

?- phrase(sentence(np(Noun,_), vp(Verb, np(Object, _))),
   [a,teenage,boy,loves,a,big,problem]),
   present(Suggestion, Noun, Verb, Object).
Noun = boy,
Verb = loves,
Object = problem,
Suggestion = 'construction kit' ;

Now you can see immediately your biggest problem: if you try to match a more complex grammar, you're going to have to have a corresponding increase in the complexity of your query which turns that into a suggestion. The solution to this kind of problem, where two things appear to increase in complexity in concert, is always to create an abstraction between them, but that is out of scope for this question.

Edit It's worth noting that if you want to build a general recommendation system, this is not a modern approach. I would recommend the book Programming Collective Intelligence for a quick overview of several approaches, backed by fairly readable Python.

Edit Is it clear that making the grammar more complex will result in more complexity in matching presents?

For starters, I have omitted entirely your prepositional phrase production. I just didn't include that. If it were there, would it have bearing on the suggestion? Consider a sentence like "a teenage boy who loves to code loves a big problem"—the natural extension of my noun_phrase//1 to cover this case will miss out on an important detail of this child which might lead you to a different present than the construction set.

Supposing you want to handle that supplemental information, you will have to add more patterns to the first argument to phrase/3. In fact, you'll probably accept whatever comes out and then dispatch to some kind of suggestion system.

One thing @TomasBy gets right is that we are using a very simple intermediate representation here, which is just (noun,verb,object). But if we make the grammar more complex, we will have to capture and handle more of it in this representation which will raise the complexity of the suggestion system. I don't see how to extend this simple representation to handle prepositional phrases, for instance, unless you just throw them away.

Converting the DCG back to ordinary Prolog

This is straightforward to do, but Prolog will do it for you. You can simply load the DCG above and use listing/0 to get the answer.

| ?- listing.

% file: user

sentence(A, B, C, D) :-
    noun_phrase(A, C, E),
    verb_phrase(B, E, D).

noun_phrase(np(A, B), C, D) :-
    det(C, E),
    adjectives(B, E, F),
    noun(A, F, D).

det([A|B], C) :-
    det(A),
    B = C.
det(A, A).

noun(A, [A|B], C) :-
    noun(A),
    B = C.

adjectives([], A, A).
adjectives([A|B], C, D) :-
    adjective(A, C, E),
    adjectives(B, E, D).

adjective(A, [A|B], C) :-
    adj(A),
    B = C.

verb_phrase(vp(A, B), C, D) :-
    verb(A, C, E),
    noun_phrase(B, E, D).

verb(A, [A|B], C) :-
    verb(A),
    B = C.


来源: stackexchange

问:
Creating a modal for multiple images
Hello I'm trying to find a solution to having a modal appear when I click on an image on a carousel. I have done this for one of my images however I want to use this same bit of code for around 20 images. Is there a way to do this without copying the code for each image? This is using bootstrap but I dont think it is needed to be able to do this, thanks.</p>

```<code>    <html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
    <title>Photography</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/styles.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

    <style>

    </style>

<body>

    <div class="container" style="padding-bottom:15px;">
         <div class="row">
             <div class="col-2"></div>
             <div class="col-8">
                 <h2>Carousel Example</h2>
                  <div id="myCarousel" class="carousel slide" data-ride="carousel">
                    <!-- Indicators -->
                    <ol class="carousel-indicators">
                      <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
                      <li data-target="#myCarousel" data-slide-to="1"></li>
                      <li data-target="#myCarousel" data-slide-to="2"></li>
                    </ol>

                    <!-- Wrapper for slides -->
                    <div class="carousel-inner">
                      <div class="item active">
                        <img src="Photos/Buttons/BridgeNON.png" alt= "Bridge" class="img‐fluid" onmouseover="this.src='Photos/Buttons/Bridge.png'" onmouseout="this.src='Photos/Buttons/BridgeNON.png'" style="width:100%;">
                      </div>

                      <div class="item">
                        <img id="myImg" src="Photos/Buttons/waterNON.png" alt= "Water" class="img‐fluid" onmouseover="this.src='Photos/Buttons/water.png'" onmouseout="this.src='Photos/Buttons/waterNON.png'" style="width:100%;">
                      </div>

                      <div class="item">
                        <img src="" alt="" style="width:100%;">
                      </div>
                    </div>

                    <a class="left carousel-control" href="#myCarousel" data-slide="prev">
                      <span class="glyphicon glyphicon-chevron-left"></span>
                      <span class="sr-only">Previous</span>
                    </a>
                    <a class="right carousel-control" href="#myCarousel" data-slide="next">
                      <span class="glyphicon glyphicon-chevron-right"></span>
                      <span class="sr-only">Next</span>
                    </a>
                  </div>
             </div>
             <div class="col-2"></div>
        </div>
    </div>

    <div id="myModal" class="modal">
        <span class="close">×</span>
        <img class="modal-content" id="img01">
        <div id="caption"></div>
    </div>

    <script>
var modal = document.getElementById('myModal');

var img = document.getElementById('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
    modal.style.display = "block";
    modalImg.src = this.src;
    captionText.innerHTML = this.alt;
}

var span = document.getElementsByClassName("close")[0];

span.onclick = function() {
    modal.style.display = "none";
}
</script>

</body>
</html>
</code>```

答:
Replace your Javascript with the following. This gets all the images in #myCarousel, loops through them, and adds the event.

var modal = document.getElementById('myModal');

var imgs = document.getElementById('myCarousel').getElementsByTagName('img');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");

for (var i = 0; i < imgs.length; i++) {
  imgs[i].onclick = function() {
    modal.style.display = "block";
    modalImg.src = this.src;
    captionText.innerHTML = this.alt;
  }
}

var span = document.getElementsByClassName("close")[0];

span.onclick = function() {
  modal.style.display = "none";
}```

ContentLicense: CC BY-SA 3.0

Title: Creating a modal for multiple images

Body:
Hello I'm trying to find a solution to having a modal appear when I click on an image on a carousel. I have done this for one of my images however I want to use this same bit of code for around 20 images. Is there a way to do this without copying the code for each image? This is using bootstrap but I dont think it is needed to be able to do this, thanks.

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
    <title>Photography</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/styles.css">

Carousel Example

                      Previous

                      Next

        ×


问:
Firebase Auth Creating new user with text input from a different class
I have two view controllers, first view controller contains the textfield for the (email/username) input from the user. The second view controller contains the textfield for the (password) input from the user. The second view controller also contains a Button to execute the FireBase Auth code to create a new user. I want to take the email text from the first view controller class one and transfer that data onto to the second view controller class in order to successfully create a new user. I tried using a global variable but it doesn't seem to work, any help this dilemma? Any help is appreciated thanks!

答:
A global variable, although not the best way to go about this, can work if you do it correctly:

1 Declare a global variable, which should be outside of both classes(don't use a structure):

```<code>var emailOrUsername: String = ""
</code>```

2 Implement the textFieldDidEndEditing method(assuming that you have set the text field delegate to be self), and assign the string in the text field to emailOrUsername:

```<code>func textFieldDidEndEditing(_ textField: UITextField) {
    emailOrUsername = emailTextField.text
}
</code>```

3 After you navigate to the next view controller, just reference that variable. Simple.

EDIT: Although this method may seem simple, when your app gradually gets more and more complicated, it will be very hard to maintain. So, I suggest you check out my answer to this question(the concept is the same: protocols).

Another method you could use is to define the emailOrUsername variable in the second viewcontroller, then, in your prepareForSegue:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let secondViewController = segue.destination as? SecondViewController {
        secondViewController.emailOrUsername = emailTextField.text!
    }
}
</code>```

Body:
A global variable, although not the best way to go about this, can work if you do it correctly:

1 Declare a global variable, which should be outside of both classes(don't use a structure):

var emailOrUsername: String = ""

2 Implement the textFieldDidEndEditing method(assuming that you have set the text field delegate to be self), and assign the string in the text field to emailOrUsername:

func textFieldDidEndEditing(_ textField: UITextField) {
    emailOrUsername = emailTextField.text
}

3 After you navigate to the next view controller, just reference that variable. Simple.

EDIT: Although this method may seem simple, when your app gradually gets more and more complicated, it will be very hard to maintain. So, I suggest you check out my answer to this question(the concept is the same: protocols).

Another method you could use is to define the emailOrUsername variable in the second viewcontroller, then, in your prepareForSegue:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let secondViewController = segue.destination as? SecondViewController {
        secondViewController.emailOrUsername = emailTextField.text!
    }
}


问:
C string arrays
I just wrote a string splitting function:

```<code>typedef enum {
    strspl_allocation_error = 1
} strspl_error;

int strspl(const char *string, const char separator, char ***result) {

    const int stringLength = strlen(string);
    int lastSplit = 0;
    int numberOfComponents = 1;

    // Compute the number of components
    for (int i = 0; i <= stringLength; i++) {
        if (string[i] == separator)
            numberOfComponents++;
    }

    // Allocate space to hold pointers to each component
    *result = (char **) malloc(numberOfComponents * sizeof(char *));
    if (result == NULL)
        return strspl_allocation_error;

    numberOfComponents = 0;

    for (int i = 0; i <= stringLength; i++) {
        char c = string[i];
        if (c == separator || i == stringLength) {

            const int componentLength = i - lastSplit;

            // Allocate space to hold the component
            char *component = (char *) malloc(componentLength * sizeof(char));
            if (component == NULL)
                return strspl_allocation_error;

            // Copy the characters from the string into the component
            for (int j = 0; j < componentLength; j++)
                component[j] = string[lastSplit + j];
            component[componentLength] = '\0';

            // Put the component into the array
            *result[numberOfComponents] = component;

            lastSplit = i + 1;
            numberOfComponents++;
        }
    }

    return numberOfComponents;
}
</code>```

Example:

```<code>char **result;
int r = strspl("aaaBcBddddeeBk", 'B', result);

for (int i = 0; i < r; i++)
    printf("component: %s\n", result[i]);
</code>```

should output:

```<code>component: aaa
component: c
component: ddddee
component: k
</code>```

But when I run it, it either crashes or returns garbage values. I don't understand where I'm making a mistake...

Update: here's a hopefully bugfree version:

```<code>int strspl(const char *string, const char separator, char ***results) {

    const char *separatorString = (char[]){separator, '\0'};
    int numberOfComponents = 0;
    int stringLength = strlen(string);

    int lastCharacterWasSeparator = 1;

    // Compute the number of components
    for (int i = 0; i < stringLength; i++) {
        if (string[i] != separator) {
            if (lastCharacterWasSeparator)
                numberOfComponents++;
            lastCharacterWasSeparator = 0;
        }
        else
            lastCharacterWasSeparator = 1;
    }

    // Allocate space to hold pointers to components
    *results = malloc(numberOfComponents * sizeof(**results));

    char *stringCopy = strdup(string); // A reference to the copy of the string to modify it and to free() it later.
    char *strptr = stringCopy; // This will be used to iterate through the string.
    int componentLength = 0;
    int component = 0;

    while (component < numberOfComponents) {

        // Move to the startpoint of the next component.
        while (componentLength == 0) {
            componentLength = strcspn(strptr, separatorString);

            // Break out the while loop if we found an actual component.
            if (componentLength != 0)
                break;

            // If we found two adjacent separators, we just "silently" move over them.
            strptr += componentLength + 1;
        }

        // Replace the terminating separator character with a NULL character.
        strptr[componentLength] = '\0';

        // Copy the new component into the array.
        (*results)[component++] = strdup(strptr);

        // Move the string pointer ahead so we can work on the next component.
        strptr += componentLength + 1;

        componentLength = 0;
    }

    // Free the copy of the string.
    free(stringCopy);

    return numberOfComponents;
}
</code>```

答:
You never assign the component
strings into the result array

You have an off-by-one error when you malloc component because you don't account for the NUL

You need one more layer of indirection so you can alter the char **result when you pass it to your function

Don't cast malloc()'s return value in C.  See here as to why

See THIS LINK for a working implementation.

Update

Here is how I would implement strspl()

```<code>int strspl(const char *string, const int separator, char ***result)
{
    int len, n=1, i=0;
    char *strptr = *copy = strdup(string);

    while(*strptr++) {
        if (*strptr == separator){ n++; }
    }

    *result = malloc(n * sizeof(**result));

    //Reset Pointer to Beginning of string
    strptr = copy;

    while(len = strcspn(strptr, (char []){separator, '\0'})) {
        strptr[len] = '\0';
        (*result)[i++] = strdup(strptr);
        strptr += len + 1;
    }

    free(copy);
    return n;
}
</code>```

Output

```<code>component: aaa
component: c
component: ddddee
component: k
</code>```

ContentLicense: CC BY-SA 2.5

Title: C string arrays

Body:
I just wrote a string splitting function:

typedef enum {
    strspl_allocation_error = 1
} strspl_error;

int strspl(const char *string, const char separator, char ***result) {

    const int stringLength = strlen(string);
    int lastSplit = 0;
    int numberOfComponents = 1;

    // Compute the number of components
    for (int i = 0; i <= stringLength; i++) {
        if (string[i] == separator)
            numberOfComponents++;
    }

    // Allocate space to hold pointers to each component
    *result = (char **) malloc(numberOfComponents * sizeof(char *));
    if (result == NULL)
        return strspl_allocation_error;

    numberOfComponents = 0;

    for (int i = 0; i <= stringLength; i++) {
        char c = string[i];
        if (c == separator || i == stringLength) {

            const int componentLength = i - lastSplit;

            // Allocate space to hold the component
            char *component = (char *) malloc(componentLength * sizeof(char));
            if (component == NULL)
                return strspl_allocation_error;

            // Copy the characters from the string into the component
            for (int j = 0; j < componentLength; j++)
                component[j] = string[lastSplit + j];
            component[componentLength] = '\0';

            // Put the component into the array
            *result[numberOfComponents] = component;

            lastSplit = i + 1;
            numberOfComponents++;
        }
    }

    return numberOfComponents;
}

Example:

char **result;
int r = strspl("aaaBcBddddeeBk", 'B', result);

for (int i = 0; i < r; i++)
    printf("component: %s\n", result[i]);

should output:

component: aaa
component: c
component: ddddee
component: k

But when I run it, it either crashes or returns garbage values. I don't understand where I'm making a mistake...

Update: here's a hopefully bugfree version:

int strspl(const char *string, const char separator, char ***results) {

    const char *separatorString = (char[]){separator, '\0'};
    int numberOfComponents = 0;
    int stringLength = strlen(string);

    int lastCharacterWasSeparator = 1;

    // Compute the number of components
    for (int i = 0; i < stringLength; i++) {
        if (string[i] != separator) {
            if (lastCharacterWasSeparator)
                numberOfComponents++;
            lastCharacterWasSeparator = 0;
        }
        else
            lastCharacterWasSeparator = 1;
    }

    // Allocate space to hold pointers to components
    *results = malloc(numberOfComponents * sizeof(**results));

    char *stringCopy = strdup(string); // A reference to the copy of the string to modify it and to free() it later.
    char *strptr = stringCopy; // This will be used to iterate through the string.
    int componentLength = 0;
    int component = 0;

    while (component < numberOfComponents) {

        // Move to the startpoint of the next component.
        while (componentLength == 0) {
            componentLength = strcspn(strptr, separatorString);

            // Break out the while loop if we found an actual component.
            if (componentLength != 0)
                break;

            // If we found two adjacent separators, we just "silently" move over them.
            strptr += componentLength + 1;
        }

        // Replace the terminating separator character with a NULL character.
        strptr[componentLength] = '\0';

        // Copy the new component into the array.
        (*results)[component++] = strdup(strptr);

        // Move the string pointer ahead so we can work on the next component.
        strptr += componentLength + 1;

        componentLength = 0;
    }

    // Free the copy of the string.
    free(stringCopy);

    return numberOfComponents;
}

Body:
You never assign the component
strings into the result array

You have an off-by-one error when you malloc component because you don't account for the NUL

You need one more layer of indirection so you can alter the char **result when you pass it to your function

Don't cast malloc()'s return value in C.  See here as to why

See THIS LINK for a working implementation.

Update

Here is how I would implement strspl()

int strspl(const char *string, const int separator, char ***result)
{
    int len, n=1, i=0;
    char *strptr = *copy = strdup(string);

    while(*strptr++) {
        if (*strptr == separator){ n++; }
    }

    *result = malloc(n * sizeof(**result));

    //Reset Pointer to Beginning of string
    strptr = copy;

    while(len = strcspn(strptr, (char []){separator, '\0'})) {
        strptr[len] = '\0';
        (*result)[i++] = strdup(strptr);
        strptr += len + 1;
    }

    free(copy);
    return n;
}

Output

component: aaa
component: c
component: ddddee
component: k


问:
Matlab: Cannot compile mex with openmp (undefined reference)
When compiling some C++ code in Matlab 2016b using:

```<code>mex CXXFLAGS="\$CXXFLAGS -std=c++11 -fopenmp" CXXOPTIMFLAGS='\$CXXOPTIMFLAGS -Ofast -DNDEBUG mexMyFunction.cpp
</code>```

I got the following errors:

```<code>undefined reference to `omp_get_thread_num'
undefined reference to `omp_get_num_threads'
</code>```

System: Ubuntu 16.04, g++ version: 5.4.0.

If I remove -fopenmp from the above command then it worked fine. Compiling directly with g++ (without mex) also worked.

Could you please help me to resolve this?

Thank you so much in advance!

答:
The the following linking flags were missing:

```<code>LDOPTIMFLAGS="$LDOPTIMFLAGS -fopenmp -O2" -lgomp
</code>```

Complete command:

```<code>mex CXXFLAGS="\$CXXFLAGS -std=c++11 -fopenmp" CXXOPTIMFLAGS='\$CXXOPTIMFLAGS -Ofast -DNDEBUG' LDOPTIMFLAGS="$LDOPTIMFLAGS -fopenmp -O2" -lgomp -I"/home/khue/Libs/Eigen" mexMyFunction.cpp
</code>```

Thanks to @Zulan for his suggestion.

Body:
When compiling some C++ code in Matlab 2016b using:

mex CXXFLAGS="\$CXXFLAGS -std=c++11 -fopenmp" CXXOPTIMFLAGS='\$CXXOPTIMFLAGS -Ofast -DNDEBUG mexMyFunction.cpp

I got the following errors:

undefined reference to `omp_get_thread_num'
undefined reference to `omp_get_num_threads'

System: Ubuntu 16.04, g++ version: 5.4.0.

If I remove -fopenmp from the above command then it worked fine. Compiling directly with g++ (without mex) also worked.

Could you please help me to resolve this?

Thank you so much in advance!

Body:
The the following linking flags were missing:

LDOPTIMFLAGS="$LDOPTIMFLAGS -fopenmp -O2" -lgomp

Complete command:

mex CXXFLAGS="\$CXXFLAGS -std=c++11 -fopenmp" CXXOPTIMFLAGS='\$CXXOPTIMFLAGS -Ofast -DNDEBUG' LDOPTIMFLAGS="$LDOPTIMFLAGS -fopenmp -O2" -lgomp -I"/home/khue/Libs/Eigen" mexMyFunction.cpp

Thanks to @Zulan for his suggestion.


问:
Prevent user from overwriting the record CRM 2011
I have a process that runs at specific time and updates records in "Open" state and disables them.
Recently I had a case when user opened the record almost at the same minute as the process was doing it's job. So while user was manually entering the data, process would already update the record and set record status to "Disabled". However, since user doesn't refresh the screen, when record saved, the status would change back to "Open" and wipe some data.

Any ideas on how this overwriting can be prevented?

P.S Process and the user should both have power to edit the record, but once it's disabled it should be locked somehow.

答:
In crm 2011, not sure if the optimistic concurrency is available in any update rollups. But Optimistic concurrency using row version concept was introduced later in 2015 update 1.

You can implement similar approach, by querying the record again and verify the modifiedon between DB record & user modified record, then stop the execution & ask user to refresh to get latest data.


问:
Logical operator with different types
I'm trying to solve the famous FizzBuzz quiz but I decided to use the logical operator or instead of else to provide fullback.

for (var num = 1; num <= 100; num++) {
  var output;
 if (num % 5 === 0 && num % 3 === 0) {
     output = "FizzBuzz";
    } else if (num % 5 === 0) {
     output = "Buzz";
    } else if (num % 3 === 0) {
     output = "Fizz";
    }
  console.log(output || num);
}```

This was supposed to print all the numbers from 1 to 100, with some exceptions. For numbers divisible by 3, print "Fizz" instead of the number, and for numbers divisible by 5, print "Buzz" instead and "FizzBuzz", for numbers that are divisible by both 3 and 5.

But it doesn't print any numbers.

答:
I will say that Zakaria's answer is correct, but for exposure's sake, here is my answer

for (var i = 1; i <= 100; i++) {
  var output = "";
  if (!(i % 3)) output += "Fizz";
  if (!(i % 5)) output += "Buzz";
  console.log(output || i);

}```

My logic here:
set the output value to be equal to "", which evaluates to a falsey value.

If a number is divisible by 3, then i % 3 will be 0, this is also a falsey value so we flip it by using the ! operator. Assume that i=9, then ! (i%3) = !(9%3) = !(0) = !(false) = true.

Therefore, if !(i%3) becomes true we append our empty string with "Fizz", then we use the same sort of logic for i%5, but instead appending "Buzz"

Note the order of these two if statements is important -- flip them around and you'll get BuzzFizz instead of FizzBuzz.

If output is not the empty string we set it to originally, output || i will return the value of output, giving us "Fizz", "Buzz", or "FizzBuzz" depending.

If ouput is empty, then output || i will return the value for i

Title: Logical operator with different types

Body:
I'm trying to solve the famous FizzBuzz quiz but I decided to use the logical operator or instead of else to provide fullback.

for (var num = 1; num <= 100; num++) {
  var output;
 if (num % 5 === 0 && num % 3 === 0) {
     output = "FizzBuzz";
    } else if (num % 5 === 0) {
     output = "Buzz";
    } else if (num % 3 === 0) {
     output = "Fizz";
    }
  console.log(output || num);
}

This was supposed to print all the numbers from 1 to 100, with some exceptions. For numbers divisible by 3, print "Fizz" instead of the number, and for numbers divisible by 5, print "Buzz" instead and "FizzBuzz", for numbers that are divisible by both 3 and 5.

But it doesn't print any numbers.

Body:
I will say that Zakaria's answer is correct, but for exposure's sake, here is my answer

for (var i = 1; i <= 100; i++) {
  var output = "";
  if (!(i % 3)) output += "Fizz";
  if (!(i % 5)) output += "Buzz";
  console.log(output || i);

}

My logic here:
set the output value to be equal to "", which evaluates to a falsey value.

If a number is divisible by 3, then i % 3 will be 0, this is also a falsey value so we flip it by using the ! operator. Assume that i=9, then ! (i%3) = !(9%3) = !(0) = !(false) = true.

Therefore, if !(i%3) becomes true we append our empty string with "Fizz", then we use the same sort of logic for i%5, but instead appending "Buzz"

Note the order of these two if statements is important -- flip them around and you'll get BuzzFizz instead of FizzBuzz.

If output is not the empty string we set it to originally, output || i will return the value of output, giving us "Fizz", "Buzz", or "FizzBuzz" depending.

If ouput is empty, then output || i will return the value for i

ContentLicense: CC BY-SA 4.0


问:
Fastest way to zero out a range of positions of an array?
I have an array which I wish to assign zeros to all positions in a given range (positions 10 to 24, in this case). I'm doing this:

```<code>ulong st[25];
...
for(int i = 10; i < 25; ++i) st[i] = 0x00UL;
</code>```

Is this the fastest way to do that? It seems that there should be a faster way without a loop, given that it's a contiguous position in memory, but I don't know what that would be (perhaps XORing that memory space with itself? If so, how would I do that?)

Any ideas?

答:
I'd be tempted to write it with the simple loop as you have done, and leave the optimisation trickery to the compiler.

If you are in any doubt that the compiler has done a good job then check the generated assembly.

As a rule of thumb, programmers are more expensive than computers. So keep maintenance cheap; i.e. write clear code whenever possible.

Body:
I have an array which I wish to assign zeros to all positions in a given range (positions 10 to 24, in this case). I'm doing this:

ulong st[25];
...
for(int i = 10; i < 25; ++i) st[i] = 0x00UL;

Is this the fastest way to do that? It seems that there should be a faster way without a loop, given that it's a contiguous position in memory, but I don't know what that would be (perhaps XORing that memory space with itself? If so, how would I do that?)

Any ideas?


问:
Query from Oracle 10g to 11g
I am developing an automatization with Oracle 11g. I have the following query that works fine on oracle 10g but not 11.

```<code>update(
    select rirr.NUM_SERIE_ULT,
           tri.T_USED_IMEI,
           rirr.celular,
           tri.MSISDN,
           rirr.TRAFICO,
           case when rirr.celular =  tri.MSISDN then 'MISMO ABONADO'
                when rirr.celular <> tri.MSISDN then 'OTRO ABONADO'
                else 'SIN TRAFICO'
           end  as TRAFICO_ACTUALIZAR
    from RENOVACIONES_INT_RENO_REPO rirr
         left join TRAFICO_RENOVACION_INTERNA tri
         on rirr.NUM_SERIE_ULT = tri.T_USED_IMEI
    )
set TRAFICO = TRAFICO_ACTUALIZAR;
</code>```

答:
The error:

You are updating the column TRAFICO from table rirr (not the actual table name, but the alias you use for it in the query). This table is joined to table tri on the join condition rirr.NUM_SERIE_ULT = tri.T_USED_IMEI.

For each row in rirr, Oracle must find a unique row in tri where the join condition is satisfied. This means: column NUM_SERIE_ULT in table rirr may have duplicates; but column T_USED_IMEI in table tri must be UNIQUE (must not have duplicates). IN ADDITION, in Oracle's implementation of UPDATE statements using joins, it is required (and was in Oracle 10, I believe) that table tri have a UNIQUE index or UNIQUE constraint on column T_USED_IMEI. If the UPDATE statement worked in Oracle 10, it is very likely you had such an index or constraint.

Does such an index or constraint still exist in Oracle 11? If all you did was an upgrade, it should not have deleted/removed indexes or constraints; but that IS what the error message means...

Unrelated observation:

What is the point of selecting other columns in the SELECT subquery of the UPDATE? Namely: rirr.NUM_SERIE_ULT, tri.T_USED_IMEI, rirr.celular, tri.MSISDN. The first two appear in the join condition; the other two appear in the definition of TRAFICO_ACTUALIZAR. But that doesn't mean you need any of those four columns to also appear separately in the SELECT list.

Title: Query from Oracle 10g to 11g

Body:
I am developing an automatization with Oracle 11g. I have the following query that works fine on oracle 10g but not 11.

update(
    select rirr.NUM_SERIE_ULT,
           tri.T_USED_IMEI,
           rirr.celular,
           tri.MSISDN,
           rirr.TRAFICO,
           case when rirr.celular =  tri.MSISDN then 'MISMO ABONADO'
                when rirr.celular <> tri.MSISDN then 'OTRO ABONADO'
                else 'SIN TRAFICO'
           end  as TRAFICO_ACTUALIZAR
    from RENOVACIONES_INT_RENO_REPO rirr
         left join TRAFICO_RENOVACION_INTERNA tri
         on rirr.NUM_SERIE_ULT = tri.T_USED_IMEI
    )
set TRAFICO = TRAFICO_ACTUALIZAR;


问:
Using external tooltip JS library with networkD3 and Shiny
I'm trying to display the value variables of nodes and links in a networkD3 forceNetwork diagram as tooltips. To do this, I am using Shiny with htmlwidgets and the external JS library Tippy.

Here is what I have so far:

```<code>library(shiny)
library(htmlwidgets)
library(networkD3)

fn <- forceNetwork(
  Links  = MisLinks, Nodes   = MisNodes,
  Source = "source", Target  = "target",
  Value  = "value",  NodeID  = "name",
  Group  = "group",  opacity = input$opacity)

tippyJS <- 'tippy(".node")'

server <- function(input, output) {

  # Load data
  data(MisLinks)
  data(MisNodes)

  # Append value variables to links and nodes in fn network
  fn$x$links$value <- "links tooltips"
  fn$x$nodes$value <- "nodes tooltips"

  output$net <- renderForceNetwork(onRender(fn,
  '
  function(el, x) {
  d3.selectAll(".node, .link").append("svg:title")
  .text(function(d) { return d.value; });
  }
  '
  )
)

}

ui <- fluidPage(
  tags$head(tags$script(src="https://unpkg.com/tippy.js@2.0.2/dist/tippy.all.min.js")),
  tags$script(tippyJS),
  titlePanel("ForceNetD3"),

    mainPanel(
      forceNetworkOutput(outputId = "net")
    )
  )

shinyApp(ui = ui, server = server)
</code>```

Tippy is supposed to take the title attribute of the .node class and convert it to a nicer-looking tooltip. I've added title tags to all of my nodes and links, loaded the Tippy library in the head tag of the underlying HTML page, and then called the Tippy function on all objects of the .node class in a separate script tag. Tippy doesn't seem to pick up on it: I continue to get default browser tooltips instead of Tippy tooltips.

答:
There are multiple reasons why your example code doesn't work (some of which are completely unrelated to the topic of adding Tippy.js), but here's a working, modified version of your example...</p>

```<code>library(shiny)
library(htmlwidgets)
library(networkD3)

# Load data
data(MisLinks)
data(MisNodes)

server <- function(input, output) {

    output$net <- renderForceNetwork({
        fn <- forceNetwork(
            Links  = MisLinks, Nodes   = MisNodes,
            Source = "source", Target  = "target",
            Value  = "value",  NodeID  = "name",
            Group  = "group",  opacity = 1)

        # Append value variables to links and nodes in fn network
        fn$x$links$value <- "links tooltips"
        fn$x$nodes$value <- "nodes tooltips"

        onRender(fn, 'function(el, x) {
                        d3.selectAll(".node circle, .link")
                            .attr("title", function(d) { return d.value; });
                        tippy("[title]");
                     }'
        )
    })

    }

ui <- fluidPage(
    tags$head(
        tags$script(src = "https://unpkg.com/tippy.js@2.0.2/dist/tippy.all.min.js")
    ),
    titlePanel("ForceNetD3"),
    mainPanel(forceNetworkOutput("net"))
)

shinyApp(ui = ui, server = server)
</code>```

Body:
I'm trying to display the value variables of nodes and links in a networkD3 forceNetwork diagram as tooltips. To do this, I am using Shiny with htmlwidgets and the external JS library Tippy.

Here is what I have so far:

library(shiny)
library(htmlwidgets)
library(networkD3)

fn <- forceNetwork(
  Links  = MisLinks, Nodes   = MisNodes,
  Source = "source", Target  = "target",
  Value  = "value",  NodeID  = "name",
  Group  = "group",  opacity = input$opacity)

tippyJS <- 'tippy(".node")'

server <- function(input, output) {

  # Load data
  data(MisLinks)
  data(MisNodes)

  # Append value variables to links and nodes in fn network
  fn$x$links$value <- "links tooltips"
  fn$x$nodes$value <- "nodes tooltips"

  output$net <- renderForceNetwork(onRender(fn,
  '
  function(el, x) {
  d3.selectAll(".node, .link").append("svg:title")
  .text(function(d) { return d.value; });
  }
  '
  )
)

}

ui <- fluidPage(
  tags$head(tags$script(src="https://unpkg.com/tippy.js@2.0.2/dist/tippy.all.min.js")),
  tags$script(tippyJS),
  titlePanel("ForceNetD3"),

    mainPanel(
      forceNetworkOutput(outputId = "net")
    )
  )

shinyApp(ui = ui, server = server)

Tippy is supposed to take the title attribute of the .node class and convert it to a nicer-looking tooltip. I've added title tags to all of my nodes and links, loaded the Tippy library in the head tag of the underlying HTML page, and then called the Tippy function on all objects of the .node class in a separate script tag. Tippy doesn't seem to pick up on it: I continue to get default browser tooltips instead of Tippy tooltips.

Body:
There are multiple reasons why your example code doesn't work (some of which are completely unrelated to the topic of adding Tippy.js), but here's a working, modified version of your example...

library(shiny)
library(htmlwidgets)
library(networkD3)

# Load data
data(MisLinks)
data(MisNodes)

server <- function(input, output) {

    output$net <- renderForceNetwork({
        fn <- forceNetwork(
            Links  = MisLinks, Nodes   = MisNodes,
            Source = "source", Target  = "target",
            Value  = "value",  NodeID  = "name",
            Group  = "group",  opacity = 1)

        # Append value variables to links and nodes in fn network
        fn$x$links$value <- "links tooltips"
        fn$x$nodes$value <- "nodes tooltips"

        onRender(fn, 'function(el, x) {
                        d3.selectAll(".node circle, .link")
                            .attr("title", function(d) { return d.value; });
                        tippy("[title]");
                     }'
        )
    })

    }

ui <- fluidPage(
    tags$head(
        tags$script(src = "https://unpkg.com/tippy.js@2.0.2/dist/tippy.all.min.js")
    ),
    titlePanel("ForceNetD3"),
    mainPanel(forceNetworkOutput("net"))
)

shinyApp(ui = ui, server = server)


问:
Create barplot from 2 count variables in R
I have 2 columns that I have summed up from an analysis and would like to use a barplot to compare them against each other but my code isn't working and I feel like its a dumb error. My columns simply have 1 or NA for values. So I summed them and want to take the 2 columns and compare. I can do the formatting of the graph, just getting it to display.

Code:

```<code>Keenum_total <- sum(Vikings_dataset$Keenum, na.rm = TRUE)

Bridgewater_total <- sum(Vikings_dataset$Bridgewater, na.rm = TRUE)

Quarterback_totals <- table(Keenum_total, Bridgewater_total)

barplot(Quarterback_totals)
</code>```

答:
You don't need the table() line before making the barplot, since by summing each column you have aggregated them to the level they need to be at for barplot().

Here's an example you can use with the (built-in) iris dataset:

```<code>sepal_length_total <- sum(iris$Sepal.Length, na.rm=TRUE)
sepal_width_total <- sum(iris$Sepal.Width, na.rm=TRUE)

barplot(c(sepal_length_total, sepal_width_total))
</code>```

If you want to display the name by each bar, you can use a named vector inside of barplot(), as in:

```<code>barplot(c(sepal_length=sepal_length_total, sepal_width=sepal_width_total))
</code>```

Body:
I have 2 columns that I have summed up from an analysis and would like to use a barplot to compare them against each other but my code isn't working and I feel like its a dumb error. My columns simply have 1 or NA for values. So I summed them and want to take the 2 columns and compare. I can do the formatting of the graph, just getting it to display.

Code:

Keenum_total <- sum(Vikings_dataset$Keenum, na.rm = TRUE)

Bridgewater_total <- sum(Vikings_dataset$Bridgewater, na.rm = TRUE)

Quarterback_totals <- table(Keenum_total, Bridgewater_total)

barplot(Quarterback_totals)

Body:
You don't need the table() line before making the barplot, since by summing each column you have aggregated them to the level they need to be at for barplot().

Here's an example you can use with the (built-in) iris dataset:

sepal_length_total <- sum(iris$Sepal.Length, na.rm=TRUE)
sepal_width_total <- sum(iris$Sepal.Width, na.rm=TRUE)

barplot(c(sepal_length_total, sepal_width_total))

If you want to display the name by each bar, you can use a named vector inside of barplot(), as in:

barplot(c(sepal_length=sepal_length_total, sepal_width=sepal_width_total))


问:
TROUBLE with cerf for making HTTPS from ssl in localhost
Hello currently i am in project making progressive-web app using my local webserver-express. Im totally in my confusion after so many days no progress.

because I need to use PWA in my phone then I really need to enable https for service-worker.

I have tried using self-signed cerf, it doesnt work for the service worker and there is a way to enable http with service-worker but it only accessible in PC-chrome while i really need the service-worker works in my android or smartphone not in my PC-only.

so I just bought the real cerf to attain HTTPS and i am little bit confused because im still unfamiliar with domain etc.

I follow this guide JUST bought my ssl and a new domain cause i run my PWA in my local webserver.

but my domain is still new so it's still locked for 60days, I don't know if i buy in another site it will be locked or not and will have to buy a new ssl again.

I got 4 cerf :

my domain cerf

Root cerf

Intermediate cerf

Webserver cerf

so i try to run my webserver express in my local ip+port with these 4 cerfs and so here the questions because i have little knowledge :

My domain cerf and intermediate shouldnt be work because my domain is still locked right ?

My root cerf doesnt work either in my local-webserver even tho i have imported the cerf in chrome. ( the https is still red, i could access the my site but i don't need red https because the service worker need green-https (?) )

I don't know what to do with webserver-cerf , well I did applied it in my code, it do nothing either.

```<code>options = {
  key: fs.readFileSync(path.join(certsPath, 'my-server.key.pem'))

  , ca: [
    fs.readFileSync(path.join(caCertsPath, 'webserver.crt.pem'))

  ,fs.readFileSync(path.join(caCertsPath, 'intermediate.crt.pem'))
        ,fs.readFileSync(path.join(caCertsPath, 'my-root-
   ca.crt.pem'))
          ]

, cert: fs.readFileSync(path.join(certsPath, 'my-server.crt.pem'))

, requestCert: false
, rejectUnauthorized: true
};
</code>```

later :

```<code>https.createServer(options, app);
</code>```

I assumed you guys know how this works right ? nodejs.express

I don't really think the code for webserver is the problem but more like the cert-understanding, domain-world and how local-webserver works with https.
The more i research the more i confused now.

I run https://ip:port  none of the working with my https-cerf.

basicly i just need to make  green HTTPS in my local webserver, but how ? I did bought the cerf and it doesnt work, so before i bought another i have to make sure what kind of problem i have right now ?

another question: my domain is unlocked but there is nameserver while i dont have host-provider, could i use my local-ip to the nameserver ? im seriously confused how this things work now. I don't even know what is the thing i confused right now, don't know what to ask.

sorry for bad grammar, but i would like if you guys correct mine.

EDIT : mistaken unlocked and locked

答:
Service workers normally require https:, but localhost is the exception. Any http://localhost:<port> origins will work with service workers.

Since you mention needing to test things on your phone, and assuming it's an Android device and you're using Chrome, the information in the "Access Local Servers" guide should help you.

You can run a local web server and then use Chrome to forward the port to an Android device connected via a USB cable, and the Android device can load your content and take full advantage of service workers via the same http://localhost:<port> origin.

Body:
Hello currently i am in project making progressive-web app using my local webserver-express. Im totally in my confusion after so many days no progress.

because I need to use PWA in my phone then I really need to enable https for service-worker.

I have tried using self-signed cerf, it doesnt work for the service worker and there is a way to enable http with service-worker but it only accessible in PC-chrome while i really need the service-worker works in my android or smartphone not in my PC-only.

so I just bought the real cerf to attain HTTPS and i am little bit confused because im still unfamiliar with domain etc.

I follow this guide JUST bought my ssl and a new domain cause i run my PWA in my local webserver.

but my domain is still new so it's still locked for 60days, I don't know if i buy in another site it will be locked or not and will have to buy a new ssl again.

I got 4 cerf :

my domain cerf

Root cerf

Intermediate cerf

Webserver cerf

so i try to run my webserver express in my local ip+port with these 4 cerfs and so here the questions because i have little knowledge :

My domain cerf and intermediate shouldnt be work because my domain is still locked right ?

My root cerf doesnt work either in my local-webserver even tho i have imported the cerf in chrome. ( the https is still red, i could access the my site but i don't need red https because the service worker need green-https (?) )

I don't know what to do with webserver-cerf , well I did applied it in my code, it do nothing either.

options = {
  key: fs.readFileSync(path.join(certsPath, 'my-server.key.pem'))

  , ca: [
    fs.readFileSync(path.join(caCertsPath, 'webserver.crt.pem'))

  ,fs.readFileSync(path.join(caCertsPath, 'intermediate.crt.pem'))
        ,fs.readFileSync(path.join(caCertsPath, 'my-root-
   ca.crt.pem'))
          ]

, cert: fs.readFileSync(path.join(certsPath, 'my-server.crt.pem'))

, requestCert: false
, rejectUnauthorized: true
};

later :

https.createServer(options, app);

I assumed you guys know how this works right ? nodejs.express

I don't really think the code for webserver is the problem but more like the cert-understanding, domain-world and how local-webserver works with https.
The more i research the more i confused now.

I run https://ip:port  none of the working with my https-cerf.

basicly i just need to make  green HTTPS in my local webserver, but how ? I did bought the cerf and it doesnt work, so before i bought another i have to make sure what kind of problem i have right now ?

another question: my domain is unlocked but there is nameserver while i dont have host-provider, could i use my local-ip to the nameserver ? im seriously confused how this things work now. I don't even know what is the thing i confused right now, don't know what to ask.

sorry for bad grammar, but i would like if you guys correct mine.

EDIT : mistaken unlocked and locked


问:
How can I pass an array as Input() from the component template?
I need to pass an array of values to a component using binding, e.g.

```<code>@Component({
    selector: 'my-component',
    template: '<div data="[1, 2, 'test']"></div>
})
export class MyComponent {
    @Input() data: any[];
    ...
}
</code>```

However, it seems Angular treats this as string/string[1] (in the actual project the array is a route and I need to pass this route on to a component which has the [routerLink] directive).

How do I go about this?

答:
So lets's start from here... in Angular 2+ all input will pass down a string if they don't get brackets around...

So there are 2 ways to pass down your values...

if you write it like this: '<div data="[1, 2, 'test']"'

you basically get it as "[1, 2, 'test']" (as string)...

The way you doing is a good way for passing down strings, and you can also use interpolation and mix it with javascript before passing it down like 'Angular {{version}}'

So to pass it down as an Array or any javascript none-sting value, you need to use [] around your input like this...

```<code><div [data]="[1, 2, 'test']"></div>
</code>```

Body:
I need to pass an array of values to a component using binding, e.g.

@Component({
    selector: 'my-component',
    template: '

})
export class MyComponent {
    @Input() data: any[];
    ...
}

However, it seems Angular treats this as string/string[1] (in the actual project the array is a route and I need to pass this route on to a component which has the [routerLink] directive).

How do I go about this?

Body:
So lets's start from here... in Angular 2+ all input will pass down a string if they don't get brackets around...

So there are 2 ways to pass down your values...

if you write it like this: '<div data="[1, 2, 'test']"'

you basically get it as "[1, 2, 'test']" (as string)...

The way you doing is a good way for passing down strings, and you can also use interpolation and mix it with javascript before passing it down like 'Angular {{version}}'

So to pass it down as an Array or any javascript none-sting value, you need to use [] around your input like this...

<div [data]="[1, 2, 'test']"></div>


问:
Facebook Graph API, how to get users email?
I'm using the Graph API, but I can't figure out how to get a logged-in users email address.

The intro to Graph states "The Graph API can provide access to all of the basic account registration data you would typically request in a sign-up form for your site, including name, email address, profile picture, and birthday"

All well and good, but how do I access that info?

This is what I have so far:

```<code>$json = $facebook->api('/me');

$first = $json['first_name']; // gets first name
$last = $json['last_name'];
</code>```

答:
Make sure to fully specify the version number of the API as something like "v2.11" and not "2.11"

I'm not sure what it defaults to if this is incorrect, but I got some odd errors trying to just retrieve the email when I missed the v.

Body:
I'm using the Graph API, but I can't figure out how to get a logged-in users email address.

The intro to Graph states "The Graph API can provide access to all of the basic account registration data you would typically request in a sign-up form for your site, including name, email address, profile picture, and birthday"

All well and good, but how do I access that info?

This is what I have so far:

$json = $facebook->api('/me');

$first = $json['first_name']; // gets first name
$last = $json['last_name'];


问:
Calling mysql_fetch_assoc only returns first result, even when called multiple times (CLOSED: TYPO)
EDIT: Phil's comment on making the MySQL_query into a variable instead of running it through the while loop was the correct answer!

I'm am trying to print out all the items in an item table using the MySQL_fetch_assoc operator. It only returns the first result even when called in a while loop, but when called through the command line running, it returns all of the correct results. I have tried to run the while command without the$numRows > 0 conditional but then it just returns an infinite array with only the first result.

```<code>...
$query = "SELECT * FROM item JOIN seller ON item.seller_id = seller.seller_id;";
$numRows = MySQL_num_rows(MySQL_query($query));
while ($numRows > 0 && $row = MySQL_fetch_assoc(MySQL_query($query))) {
echo "<tr><td>" . $row["item_name"] . "</td>\n" .
" <td>" . $row["category"] . "</td>\n" .
" <td>" . $row["item_price"] . "</td>\n" .
" <td>" . $row["user_email"] . </td>\n" .
" </tr>\n";
$numRows--;
...
</code>```

It should be return a table of all the items

```<code>Name Category Price Seller Email
cup  utensils 200  bob@email.com
shaker utensils 300 sam@email.com
spoon  utensils 400 james@email.com
</code>```

but only returns a table with the first result

```<code>Name Category Price Seller Email
cup  utensils 200   bob@email.com
cup  utensils 200   bob@email.com
cup  utensils 200   bob@email.com
</code>```

答:
Your while loop is creating a new resource on each iteration with the MySQL_query($query) expression, and as such when you call MySQL_fetch_assoc(MySQL_query($query)) you are always receiving the first row of the query.

A solution to this would to create the resource before the while loop, and then call MySQL_fetch_assoc() on that resource.

Eg:

```<code>$query = "SELECT * FROM item JOIN seller ON item.seller_id = seller.seller_id;";
$res = MySQL_query($query)
$numRows = MySQL_num_rows($res); // You can also modify this line
while ($numRows > 0 && $row = MySQL_fetch_assoc($res)) {
    ...
}
</code>```

As Obsidian Age also said, you should consider moving to MySQLi or PDO. MySQLi is particularly painless to transfer to if all your code is using the older MySQL functions.

Body:
EDIT: Phil's comment on making the MySQL_query into a variable instead of running it through the while loop was the correct answer!

I'm am trying to print out all the items in an item table using the MySQL_fetch_assoc operator. It only returns the first result even when called in a while loop, but when called through the command line running, it returns all of the correct results. I have tried to run the while command without the$numRows > 0 conditional but then it just returns an infinite array with only the first result.

...
$query = "SELECT * FROM item JOIN seller ON item.seller_id = seller.seller_id;";
$numRows = MySQL_num_rows(MySQL_query($query));
while ($numRows > 0 && $row = MySQL_fetch_assoc(MySQL_query($query))) {
echo "
" . $row["item_name"] . "	\n" .
" " . $row["category"] . "	\n" .
" " . $row["item_price"] . "	\n" .
" " . $row["user_email"] . 	\n" .
"
\n";
$numRows--;
...

It should be return a table of all the items

Name Category Price Seller Email
cup  utensils 200  bob@email.com
shaker utensils 300 sam@email.com
spoon  utensils 400 james@email.com

but only returns a table with the first result

Name Category Price Seller Email
cup  utensils 200   bob@email.com
cup  utensils 200   bob@email.com
cup  utensils 200   bob@email.com

Body:
Your while loop is creating a new resource on each iteration with the MySQL_query($query) expression, and as such when you call MySQL_fetch_assoc(MySQL_query($query)) you are always receiving the first row of the query.

A solution to this would to create the resource before the while loop, and then call MySQL_fetch_assoc() on that resource.

Eg:

$query = "SELECT * FROM item JOIN seller ON item.seller_id = seller.seller_id;";
$res = MySQL_query($query)
$numRows = MySQL_num_rows($res); // You can also modify this line
while ($numRows > 0 && $row = MySQL_fetch_assoc($res)) {
    ...
}

As Obsidian Age also said, you should consider moving to MySQLi or PDO. MySQLi is particularly painless to transfer to if all your code is using the older MySQL functions.


问:
Worker not initialising Heroku+Sidekiq+Postgres+Rediscloud
I'm trying to initialize Sidekiq in a Heroku worker using:

```<code>if Rails.env.production?

  Sidekiq.configure_client do |config|
    config.redis = { url: ENV['REDISCLOUD_URL'], size: 2 }
  end

  Sidekiq.configure_server do |config|
    config.redis = { url: ENV['REDISCLOUD_URL'], size: 10 }

    Rails.application.config.after_initialize do
      Rails.logger.info("DB Connection Pool size for Sidekiq Server before disconnect is: #{ActiveRecord::Base.connection.pool.instance_variable_get('@size')}")
      ActiveRecord::Base.connection_pool.disconnect!

      ActiveSupport.on_load(:active_record) do
        config = Rails.application.config.database_configuration[Rails.env]
        config['reaping_frequency'] = ENV['DATABASE_REAP_FREQ'] || 10 # seconds
        # config['pool'] = ENV['WORKER_DB_POOL_SIZE'] || Sidekiq.options[:concurrency]
        config['pool'] = 8
        ActiveRecord::Base.establish_connection(config)

        Rails.logger.info("DB Connection Pool size for Sidekiq Server is now: #{ActiveRecord::Base.connection.pool.instance_variable_get('@size')}")
      end
    end
  end

end
</code>```

but I get the following in my log:

```<code>2017-04-12T22:33:20.435939+00:00 heroku[worker.1]: State changed from crashed to starting
2017-04-12T22:33:23.510593+00:00 heroku[worker.1]: Starting process with command `bundle exec sidekiq -e production -C config/sidekiq.yml`
2017-04-12T22:33:24.049032+00:00 heroku[worker.1]: State changed from starting to up
2017-04-12T22:33:26.528756+00:00 app[worker.1]: 4 TID-otpsq87bc INFO: Booting Sidekiq 4.2.10 with redis options {:url=>"redis://rediscloud:REDACTED@redis-14870.c1.eu-west-1-3.ec2.cloud.redislabs.com:14870", :size=>20}
2017-04-12T22:33:27.606408+00:00 heroku[worker.1]: State changed from up to crashed
2017-04-12T22:33:27.590348+00:00 heroku[worker.1]: Process exited with status 1
2017-04-12T22:33:27.506096+00:00 app[worker.1]: I, [2017-04-12T22:33:27.505980 #4]  INFO -- : DB Connection Pool size for Sidekiq Server before disconnect is: 5
2017-04-12T22:33:27.509172+00:00 app[worker.1]: could not connect to server: Connection refused
2017-04-12T22:33:27.509174+00:00 app[worker.1]:     Is the server running on host "localhost" (127.0.0.1) and accepting
2017-04-12T22:33:27.509175+00:00 app[worker.1]:     TCP/IP connections on port 5432?
</code>```

Does anyone have an idea what's wrong?

答: I had the same issue when trying to run Sidekiq on Heroku. I fixed it by adding url: <%= ENV['DATABASE_URL'] %> underneath production: in database.yml.

Body:
I'm trying to initialize Sidekiq in a Heroku worker using:

if Rails.env.production?

  Sidekiq.configure_client do |config|
    config.redis = { url: ENV['REDISCLOUD_URL'], size: 2 }
  end

  Sidekiq.configure_server do |config|
    config.redis = { url: ENV['REDISCLOUD_URL'], size: 10 }

    Rails.application.config.after_initialize do
      Rails.logger.info("DB Connection Pool size for Sidekiq Server before disconnect is: #{ActiveRecord::Base.connection.pool.instance_variable_get('@size')}")
      ActiveRecord::Base.connection_pool.disconnect!

      ActiveSupport.on_load(:active_record) do
        config = Rails.application.config.database_configuration[Rails.env]
        config['reaping_frequency'] = ENV['DATABASE_REAP_FREQ'] || 10 # seconds
        # config['pool'] = ENV['WORKER_DB_POOL_SIZE'] || Sidekiq.options[:concurrency]
        config['pool'] = 8
        ActiveRecord::Base.establish_connection(config)

        Rails.logger.info("DB Connection Pool size for Sidekiq Server is now: #{ActiveRecord::Base.connection.pool.instance_variable_get('@size')}")
      end
    end
  end

end

but I get the following in my log:

2017-04-12T22:33:20.435939+00:00 heroku[worker.1]: State changed from crashed to starting
2017-04-12T22:33:23.510593+00:00 heroku[worker.1]: Starting process with command `bundle exec sidekiq -e production -C config/sidekiq.yml`
2017-04-12T22:33:24.049032+00:00 heroku[worker.1]: State changed from starting to up
2017-04-12T22:33:26.528756+00:00 app[worker.1]: 4 TID-otpsq87bc INFO: Booting Sidekiq 4.2.10 with redis options {:url=>"redis://rediscloud:REDACTED@redis-14870.c1.eu-west-1-3.ec2.cloud.redislabs.com:14870", :size=>20}
2017-04-12T22:33:27.606408+00:00 heroku[worker.1]: State changed from up to crashed
2017-04-12T22:33:27.590348+00:00 heroku[worker.1]: Process exited with status 1
2017-04-12T22:33:27.506096+00:00 app[worker.1]: I, [2017-04-12T22:33:27.505980 #4]  INFO -- : DB Connection Pool size for Sidekiq Server before disconnect is: 5
2017-04-12T22:33:27.509172+00:00 app[worker.1]: could not connect to server: Connection refused
2017-04-12T22:33:27.509174+00:00 app[worker.1]:     Is the server running on host "localhost" (127.0.0.1) and accepting
2017-04-12T22:33:27.509175+00:00 app[worker.1]:     TCP/IP connections on port 5432?

Does anyone have an idea what's wrong?


问:
XamarinBranchAndroid: MainActivity to BranchActivity results in a blank screen
So, we have this existing App with a MainActivity, with whole bunch of interface implementations. I want to implement IBranchSessionInterface. I have followed the documentation as given here: https://docs.branch.io/pages/apps/xamarin/
Have BranchActivity and BranchErrorActivity

One thing I can't seem to understand in the following sequence:

ApplicationClass calls:

BranchAndroid.GetAutoInstance(this.ApplicationContext);

MainActivity that Implements IBranchSessionInterface has this code in OnCreate()

BranchAndroid.Init(this, Resources.GetString(Resource.String.branch_key), this);

When the Branchsession is successfully initiated, it calls the IBranchSessionInterface, InitSessionComplete callback.
Here is the full method impl:

```<code>public void InitSessionComplete(Dictionary<string, object> data)
{
    var intent = new Intent(this, typeof(BranchActivity));
    intent.PutExtra("BranchData", JsonConvert.SerializeObject(data));

    StartActivity(intent);
}
</code>```

After this, what needs to happen? Because after Starting branch activity I see nothing but empty screen. How is it suppose to come back to MainActivity?

答:
The Branch activity is simply an example of how you can use Branch link data. You don't actually need that activity, or the intent to redirect to it.
You may simply delete all of that code and replace it with the following to view the data upon app open:</p>

```<code>public void InitSessionComplete(Dictionary<string, object> data)
        {
            Console.WriteLine("Branch Link Data: " + JsonConvert.SerializeObject(data));

        }
</code>```

Body:
So, we have this existing App with a MainActivity, with whole bunch of interface implementations. I want to implement IBranchSessionInterface. I have followed the documentation as given here: https://docs.branch.io/pages/apps/xamarin/
Have BranchActivity and BranchErrorActivity

One thing I can't seem to understand in the following sequence:

ApplicationClass calls:

BranchAndroid.GetAutoInstance(this.ApplicationContext);

MainActivity that Implements IBranchSessionInterface has this code in OnCreate()

BranchAndroid.Init(this, Resources.GetString(Resource.String.branch_key), this);

When the Branchsession is successfully initiated, it calls the IBranchSessionInterface, InitSessionComplete callback.
Here is the full method impl:

public void InitSessionComplete(Dictionary<string, object> data)
{
    var intent = new Intent(this, typeof(BranchActivity));
    intent.PutExtra("BranchData", JsonConvert.SerializeObject(data));

    StartActivity(intent);
}

After this, what needs to happen? Because after Starting branch activity I see nothing but empty screen. How is it suppose to come back to MainActivity?

Body:
The Branch activity is simply an example of how you can use Branch link data. You don't actually need that activity, or the intent to redirect to it.
You may simply delete all of that code and replace it with the following to view the data upon app open:

public void InitSessionComplete(Dictionary<string, object> data)
        {
            Console.WriteLine("Branch Link Data: " + JsonConvert.SerializeObject(data));

        }


问:
Regular expressions for 301 redirect
How can I redirect http://example.com/news.php?id=268&page=25 and all pages like  http://example.com/news.php?id=X&page=Y to another page using regular expressions?

I tried using http://example.com/news.php?id=/d&page=/d.

答:
Digits are matched with \d, not /d. To match at least 1 digit, you need to add the + quantifier. And to capture the numbers so you can copy them to the replacement URL, you need a capture group around it.

You also need to escape certain characters that have special meaning in regular expressions: . and ?.

```<code>http://example\.com/news\.php\?id=(\d+)&page=(\d+)
</code>```

Title: Regular expressions for 301 redirect

Body:
Digits are matched with \d, not /d. To match at least 1 digit, you need to add the + quantifier. And to capture the numbers so you can copy them to the replacement URL, you need a capture group around it.

You also need to escape certain characters that have special meaning in regular expressions: . and ?.

http://example\.com/news\.php\?id=(\d+)&page=(\d+)


问:
Overriding the .Add method in a List of... with validation
I have a Use Case where I want to validate a specific property in a list of objects to make sure it is unique. The basic setting can be seen in the code below.

```<code>class Program
{
    static void Main(string[] args)
    {
        Directory myDirectory = new Directory("Interaction Design");
        myDirectory.Books.Add(new Book("978-0-262-64037-4", "The Design of Everyday Things")); //Should be added
        myDirectory.Books.Add(new Book("978-0-262-13474-3", "Designing Interactions")); //Should be added
        myDirectory.Books.Add(new Book("978-0-262-13474-3", "Whoops, I slipped up")); //Should NOT be added
    }
}

public class Directory
{
    public Directory(string name)
    {
        Name = name;
    }
    public string Name { get; set; }
    public List<Book> Books { get; set; } = new List<Book>();
}

public class Book
{
    public Book(string isbn, string title)
    {
        Isbn = isbn;
        Title = title;
    }
    public string Title { get; set; }
    public string Isbn { get; set; }
}
</code>```

Now, in the code above, adding a new Book in the List of Books should throw an exception if the ISBN number isn't unique.

I would like to extend on the .Add() method of the List and add that validation, but I'm not sure how to actually do that.

I've seen similar things, but they all assume that the Directory inherits from List and you write an overriding .Add method to the Directory - which doesn't look like a valid solution in this case.

Perhaps my general approach is backwards?

Please advice.

答:
One option is to create a new class and inherit from Collection<T> instead of List<T>, where you could overwrite InsertItem

e.g.

```<code>public class MyList: Collection<string>
{

    protected override void InsertItem(int index, string newItem)
    {
        DoValidation();
    }

}
</code>```

called with the following call:

```<code>var myList = new MyList();
myList.Add("item1");
</code>```

Body:
I have a Use Case where I want to validate a specific property in a list of objects to make sure it is unique. The basic setting can be seen in the code below.

class Program
{
    static void Main(string[] args)
    {
        Directory myDirectory = new Directory("Interaction Design");
        myDirectory.Books.Add(new Book("978-0-262-64037-4", "The Design of Everyday Things")); //Should be added
        myDirectory.Books.Add(new Book("978-0-262-13474-3", "Designing Interactions")); //Should be added
        myDirectory.Books.Add(new Book("978-0-262-13474-3", "Whoops, I slipped up")); //Should NOT be added
    }
}

public class Directory
{
    public Directory(string name)
    {
        Name = name;
    }
    public string Name { get; set; }
    public List<Book> Books { get; set; } = new List<Book>();
}

public class Book
{
    public Book(string isbn, string title)
    {
        Isbn = isbn;
        Title = title;
    }
    public string Title { get; set; }
    public string Isbn { get; set; }
}

Now, in the code above, adding a new Book in the List of Books should throw an exception if the ISBN number isn't unique.

I would like to extend on the .Add() method of the List and add that validation, but I'm not sure how to actually do that.

I've seen similar things, but they all assume that the Directory inherits from List and you write an overriding .Add method to the Directory - which doesn't look like a valid solution in this case.

Perhaps my general approach is backwards?

Please advice.

Body:
One option is to create a new class and inherit from Collection<T> instead of List<T>, where you could overwrite InsertItem

e.g.

public class MyList: Collection<string>
{

    protected override void InsertItem(int index, string newItem)
    {
        DoValidation();
    }

}

called with the following call:

var myList = new MyList();
myList.Add("item1");


问:
Spring Integration Kafka ClassNotFoundException: KafkaHeaderMapper
While running a Spring Boot application with spring-integration-kafka library, I am getting the following error:

Caused by: java.lang.ClassNotFoundException: org.springframework.kafka.support.KafkaHeaderMapper

The exception is thrown at the first line in the body of the following method:

```<code>@ServiceActivator(inputChannel = "producerChannel")
public MessageHandler kafkaMessageHandler() {
    KafkaProducerMessageHandler<String, String> handler =
        new KafkaProducerMessageHandler<>(kafkaTemplate());
    handler.setMessageKeyExpression(new LiteralExpression("kafka-integration"));

    return handler;
}
</code>```

My pom.xml is:

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka-clients</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-integration</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.integration</groupId>
        <artifactId>spring-integration-kafka</artifactId>
        <version>2.3.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.kafka</groupId>
        <artifactId>spring-kafka</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

What am I missing?

答:
See the compatibility matrix on the Spring for Apache Kafka project page.

Spring Integration Kafka 2.3.x requires spring-kafka version 1.3.x.

Boot 1.5.x pulls in 1.1.x by default.

Add <version>1.3.2.RELEASE</version> to the spring-kafka dependency.

Body:
While running a Spring Boot application with spring-integration-kafka library, I am getting the following error:

Caused by: java.lang.ClassNotFoundException: org.springframework.kafka.support.KafkaHeaderMapper

The exception is thrown at the first line in the body of the following method:

@ServiceActivator(inputChannel = "producerChannel")
public MessageHandler kafkaMessageHandler() {
    KafkaProducerMessageHandler<String, String> handler =
        new KafkaProducerMessageHandler<>(kafkaTemplate());
    handler.setMessageKeyExpression(new LiteralExpression("kafka-integration"));

    return handler;
}

My pom.xml is:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath />
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka-clients</artifactId>
        <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-integration</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.integration</groupId>
        <artifactId>spring-integration-kafka</artifactId>
        <version>2.3.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.kafka</groupId>
        <artifactId>spring-kafka</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

What am I missing?


问:
How can I extend a lexical cast to support enumerated types?
I have the following function that will convert a string into a numeric data type:

```<code>template <typename T>
bool ConvertString(const std::string& theString, T& theResult)
{
    std::istringstream iss(theString);
    return !(iss >> theResult).fail();
}
</code>```

This does not work for enumerated types, however, so I have done something like this:

```<code>template <typename T>
bool ConvertStringToEnum(const std::string& theString, T& theResult)
{
    std::istringstream iss(theString);
    unsigned int temp;
    const bool isValid = !(iss >> temp).fail();
    theResult = static_cast<T>(temp);
    return isValid;
}
</code>```

(I'm making the assumption that theString has a valid value for the enumerated type; I'm using this mainly for simple serialization)

Is there a way to create a single function that combines both of these?

I've played a bit with the template arguments but haven't come up with anything; it'd just be nice not to have to call one function for enumerated types and another for everything else.

Thank you

答:
And just to "complete" the question, in C++0x we can just do this:

```<code>typedef typename std::underlying_type<T>::type safe_type;
</code>```

In place of Johannes get_etype trick.

Body:
I have the following function that will convert a string into a numeric data type:

template <typename T>
bool ConvertString(const std::string& theString, T& theResult)
{
    std::istringstream iss(theString);
    return !(iss >> theResult).fail();
}

This does not work for enumerated types, however, so I have done something like this:

template <typename T>
bool ConvertStringToEnum(const std::string& theString, T& theResult)
{
    std::istringstream iss(theString);
    unsigned int temp;
    const bool isValid = !(iss >> temp).fail();
    theResult = static_cast<T>(temp);
    return isValid;
}

(I'm making the assumption that theString has a valid value for the enumerated type; I'm using this mainly for simple serialization)

Is there a way to create a single function that combines both of these?

I've played a bit with the template arguments but haven't come up with anything; it'd just be nice not to have to call one function for enumerated types and another for everything else.

Thank you

Body:
And just to "complete" the question, in C++0x we can just do this:

typedef typename std::underlying_type<T>::type safe_type;

In place of Johannes get_etype trick.


问:
learnyounode #9 juggling async
I am trying to go through nodeschool's learnyounode.

This problem is the same as the previous problem (HTTP COLLECT) in
  that you need to use http.get(). However, this time you will be
  provided with three URLs as the first three command-line arguments.

You must collect the complete content provided to you by each of the
  URLs and print it to the console (stdout). You don't need to print out
  the length, just the data as a String; one line per URL. The catch is
  that you must print them out in the same order as the URLs are
  provided to you as command-line arguments.

I'm confused as to why my solution doesn't work exactly since it looks the same to me but more functional and am unsure of their inner test workings:

```<code>1.  ACTUAL:    ""
1.  EXPECTED:  "As busy as a dead horse also lets get some dero. Built like a sleepout no dramas lets get some chook. She'll be right thingo my she'll be right ute. "

2.  ACTUAL:    "She'll be right bizzo no worries she'll be right fair dinkum. We're going aerial pingpong no worries as busy as a gyno. "
2.  EXPECTED:  "She'll be right bizzo no worries she'll be right fair dinkum. We're going aerial pingpong no worries as busy as a gyno. "

3.  ACTUAL:    "He's got a massive pretty spiffy heaps she'll be right brizzie. He hasn't got a fly wire where shazza got us some strewth. She'll be right spit the dummy with it'll be fair go. We're going gobsmacked with as stands out like arvo. He's got a massive bush bash mate she'll be right slacker. "
3.  EXPECTED:  "He's got a massive pretty spiffy heaps she'll be right brizzie. He hasn't got a fly wire where shazza got us some strewth. She'll be right spit the dummy with it'll be fair go. We're going gobsmacked with as stands out like arvo. He's got a massive bush bash mate she'll be right slacker. "

4.  ACTUAL:    ""
4.  EXPECTED:  ""
</code>```

my code:

```<code>var http = require('http');
var bl = require('bl');

var result = [];
var urls = process.argv.slice(2);
urls.forEach(function(url, i) {
  http.get(url, function(response) {
    response.pipe(bl(function(err, data) {
      if (err) return console.error(err);
      result[i] = data.toString();
      if (i === urls.length - 1) {
        console.log(result.join('\n'));
      }
    }));
  });
});
</code>```

official solution:

```<code>var http = require('http')
var bl = require('bl')
var results = []
var count = 0

function printResults () {
  for (var i = 0; i < 3; i++)
    console.log(results[i])
}

function httpGet (index) {
  http.get(process.argv[2 + index], function (response) {
    response.pipe(bl(function (err, data) {
      if (err)
        return console.error(err)

      results[index] = data.toString()
      count++

      if (count == 3)
        printResults()
    }))
  })
}

for (var i = 0; i < 3; i++)
  httpGet(i)
</code>```

Basically the first test never passes (although if there is only 1 url in the iterated array (instead of 3), the first test passes but not the others). Any insight would be great. I'm not sure where to ask about this and perhaps I'm just missing some JS thing, so sorry if this is not appropriate.

答:
I am a beginner so maybe this solution has problems, this is using async/await, by making an array of promises and waiting for them to resolve, this will control the order of responses</p>

```<code>const axios = require("axios")
const  getURL = async url =>
{
  let res = await axios.get(url)
  return res.data
}

const getUrlArray = () =>
{
  let args = process.argv.slice(2)
  .map(e => getURL(e))
  return Promise.all(args)
}

getUrlArray()
.then(data => data.forEach(e => console.log(e)))
</code>```

Title: learnyounode #9 juggling async

Body:
I am trying to go through nodeschool's learnyounode.

This problem is the same as the previous problem (HTTP COLLECT) in
  that you need to use http.get(). However, this time you will be
  provided with three URLs as the first three command-line arguments.

You must collect the complete content provided to you by each of the
  URLs and print it to the console (stdout). You don't need to print out
  the length, just the data as a String; one line per URL. The catch is
  that you must print them out in the same order as the URLs are
  provided to you as command-line arguments.

I'm confused as to why my solution doesn't work exactly since it looks the same to me but more functional and am unsure of their inner test workings:

1.  ACTUAL:    ""
1.  EXPECTED:  "As busy as a dead horse also lets get some dero. Built like a sleepout no dramas lets get some chook. She'll be right thingo my she'll be right ute. "

2.  ACTUAL:    "She'll be right bizzo no worries she'll be right fair dinkum. We're going aerial pingpong no worries as busy as a gyno. "
2.  EXPECTED:  "She'll be right bizzo no worries she'll be right fair dinkum. We're going aerial pingpong no worries as busy as a gyno. "

3.  ACTUAL:    "He's got a massive pretty spiffy heaps she'll be right brizzie. He hasn't got a fly wire where shazza got us some strewth. She'll be right spit the dummy with it'll be fair go. We're going gobsmacked with as stands out like arvo. He's got a massive bush bash mate she'll be right slacker. "
3.  EXPECTED:  "He's got a massive pretty spiffy heaps she'll be right brizzie. He hasn't got a fly wire where shazza got us some strewth. She'll be right spit the dummy with it'll be fair go. We're going gobsmacked with as stands out like arvo. He's got a massive bush bash mate she'll be right slacker. "

4.  ACTUAL:    ""
4.  EXPECTED:  ""

my code:

var http = require('http');
var bl = require('bl');

var result = [];
var urls = process.argv.slice(2);
urls.forEach(function(url, i) {
  http.get(url, function(response) {
    response.pipe(bl(function(err, data) {
      if (err) return console.error(err);
      result[i] = data.toString();
      if (i === urls.length - 1) {
        console.log(result.join('\n'));
      }
    }));
  });
});

official solution:

var http = require('http')
var bl = require('bl')
var results = []
var count = 0

function printResults () {
  for (var i = 0; i < 3; i++)
    console.log(results[i])
}

function httpGet (index) {
  http.get(process.argv[2 + index], function (response) {
    response.pipe(bl(function (err, data) {
      if (err)
        return console.error(err)

      results[index] = data.toString()
      count++

      if (count == 3)
        printResults()
    }))
  })
}

for (var i = 0; i < 3; i++)
  httpGet(i)

Basically the first test never passes (although if there is only 1 url in the iterated array (instead of 3), the first test passes but not the others). Any insight would be great. I'm not sure where to ask about this and perhaps I'm just missing some JS thing, so sorry if this is not appropriate.

Body:
I am a beginner so maybe this solution has problems, this is using async/await, by making an array of promises and waiting for them to resolve, this will control the order of responses

const axios = require("axios")
const  getURL = async url =>
{
  let res = await axios.get(url)
  return res.data
}

const getUrlArray = () =>
{
  let args = process.argv.slice(2)
  .map(e => getURL(e))
  return Promise.all(args)
}

getUrlArray()
.then(data => data.forEach(e => console.log(e)))


问:
Two level grouped plots
Is there any way to create a two level grouped bar chart (i.e. groups on the x-axis) using Python matplotlib and / or pandas.

An example of what I mean is shown

答:
Apparently this is on the wishlist.
Here's an example that is referred to in the post that does what you want, but with a couple of functions.

However, a quick solution would be to just plot two bar plots side-by-side and customising the graph a little bit.

```<code>import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

#create multindex dataframe
arrays = [['Fruit', 'Fruit', 'Fruit', 'Veggies', 'Veggies', 'Veggies'],
          ['Bananas', 'Oranges', 'Pears', 'Carrots', 'Potatoes', 'Celery']]
index = pd.MultiIndex.from_tuples(list(zip(*arrays)))
df = pd.DataFrame(np.random.randint(10, 50, size=(1, 6)), columns=index)

#plotting
fig, axes = plt.subplots(nrows=1, ncols=2, sharey=True, figsize=(14 / 2.54, 10 / 2.54))  # width, height
for i, col in enumerate(df.columns.levels[0]):
    print(col)
    ax = axes[i]
    df[col].T.plot(ax=ax, kind='bar', width=.8)

    ax.legend_.remove()
    ax.set_xlabel(col, weight='bold')
    ax.yaxis.grid(b=True, which='major', color='black', linestyle='--', alpha=.4)
    ax.set_axisbelow(True)

    for tick in ax.get_xticklabels():
        tick.set_rotation(0)

#make the ticklines invisible
ax.tick_params(axis=u'both', which=u'both', length=0)
plt.tight_layout()
# remove spacing in between
fig.subplots_adjust(wspace=0)  # space between plots

plt.show()
</code>```

Title: Two level grouped plots

Body:
Apparently this is on the wishlist.
Here's an example that is referred to in the post that does what you want, but with a couple of functions.

However, a quick solution would be to just plot two bar plots side-by-side and customising the graph a little bit.

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

#create multindex dataframe
arrays = [['Fruit', 'Fruit', 'Fruit', 'Veggies', 'Veggies', 'Veggies'],
          ['Bananas', 'Oranges', 'Pears', 'Carrots', 'Potatoes', 'Celery']]
index = pd.MultiIndex.from_tuples(list(zip(*arrays)))
df = pd.DataFrame(np.random.randint(10, 50, size=(1, 6)), columns=index)

#plotting
fig, axes = plt.subplots(nrows=1, ncols=2, sharey=True, figsize=(14 / 2.54, 10 / 2.54))  # width, height
for i, col in enumerate(df.columns.levels[0]):
    print(col)
    ax = axes[i]
    df[col].T.plot(ax=ax, kind='bar', width=.8)

    ax.legend_.remove()
    ax.set_xlabel(col, weight='bold')
    ax.yaxis.grid(b=True, which='major', color='black', linestyle='--', alpha=.4)
    ax.set_axisbelow(True)

    for tick in ax.get_xticklabels():
        tick.set_rotation(0)

#make the ticklines invisible
ax.tick_params(axis=u'both', which=u'both', length=0)
plt.tight_layout()
# remove spacing in between
fig.subplots_adjust(wspace=0)  # space between plots

plt.show()


问:
Can we no longer use window.open()
I'm working on a client site to download a PDF after submitting a form by opening the PDF url in a new tab on form submission. But in Chrome, Safari and FF, they're all blocking the "popup". I have noticed a few articles talking about ways to prevent browsers from blocking window.open(). They're usually relating to ajax but I'm not using ajax. The other articles talk about how window.open() only works inside a click event. And even that doesn't work for me.

It doesn't make a ton of sense but in my example I try triggering a click and

```<code><script>
    jQuery( document ).ready(function() {
        jQuery(".gform_confirmation_message a").on("click", function(e){
            e.preventDefault();
            var newWin = window.open("", "_blank");
            newWin.location = jQuery(".gform_confirmation_message a").attr("href");
        });

        jQuery(".gform_confirmation_message a").trigger("click");
    });
</script>
</code>```

Even if I put a simple line outside jquery, doesn't work and gets blocked.

```<code>var newWin = window.open("", "_blank");
</code>```

Also either of these on their own do absolutely nothing. It doesn't even bring up the popup blocked.

```<code>jQuery(".gform_confirmation_message a").trigger("click");
OR
jQuery(".gform_confirmation_message a").click();
</code>```

I know browsers are hammering down on spam/ad security but this is ridiculous.

答:
Popups are still possible. They just need to be triggered by a user action. Creating a fake click event is not considered a user action.

One way you can start the download is to simply redirect the page to the PDF with the correct content type set such that it will download immediately:

```<code>Content-Type: application/octet-stream
</code>```

or

```<code>Content-Disposition: attachment
</code>```

With HTML5 you can also start a download by creating a temporary  tag and set its download attribute to the file url. A virtual click event will still work.

var textFile = new Blob(["hello world"], {type: "text/plain"});
var blobUrl = URL.createObjectURL(textFile);

var a = document.createElement("a");
a.href = blobUrl;
a.download = "myTextFile.txt";
a.click();  // start the download```

I know browsers are hammering down on spam/ad security but this is ridiculous.

Popups are annoying. There are plenty of ways to download a file without creating a useless popup window.

Title: Can we no longer use window.open()

Body:
I'm working on a client site to download a PDF after submitting a form by opening the PDF url in a new tab on form submission. But in Chrome, Safari and FF, they're all blocking the "popup". I have noticed a few articles talking about ways to prevent browsers from blocking window.open(). They're usually relating to ajax but I'm not using ajax. The other articles talk about how window.open() only works inside a click event. And even that doesn't work for me.

It doesn't make a ton of sense but in my example I try triggering a click and

Even if I put a simple line outside jquery, doesn't work and gets blocked.

var newWin = window.open("", "_blank");

Also either of these on their own do absolutely nothing. It doesn't even bring up the popup blocked.

jQuery(".gform_confirmation_message a").trigger("click");
OR
jQuery(".gform_confirmation_message a").click();

I know browsers are hammering down on spam/ad security but this is ridiculous.

Body:
Popups are still possible. They just need to be triggered by a user action. Creating a fake click event is not considered a user action.

One way you can start the download is to simply redirect the page to the PDF with the correct content type set such that it will download immediately:

Content-Type: application/octet-stream

or

Content-Disposition: attachment

With HTML5 you can also start a download by creating a temporary <a> tag and set its download attribute to the file url. A virtual click event will still work.

var textFile = new Blob(["hello world"], {type: "text/plain"});
var blobUrl = URL.createObjectURL(textFile);

var a = document.createElement("a");
a.href = blobUrl;
a.download = "myTextFile.txt";
a.click();  // start the download

I know browsers are hammering down on spam/ad security but this is ridiculous.

Popups are annoying. There are plenty of ways to download a file without creating a useless popup window.