问:
I'm having trouble displaying a linked list
When I run my program, it works as intended, except the items in the list have no spaces between them when the displayList() function is called.  I have 3 files.  The main cpp file is ShoppingList.cpp.  Then I have two other files for the linked list classification and implementation.

```<code>//ShoppingList.cpp
//Michael Hery
//COP 2001
//11/9/17
//Shopping List

#include <iostream>
#include <string>
#include "strList.h"
#include "strlist.cpp"

using namespace std;

int main()
{
    //Define a NumberList object
    StrList list;
    string item;
    string delItem;
    int menuSelection;

    //Ask the user how many items to
    //put in the list
    cout << "How many items would you like to put it the list? >> ";
    cin >> menuSelection;
    while (menuSelection < 1)
    {
        cout << "Please enter a valid number (greater than 0) >> ";
        cin >> menuSelection;
    }

    for (int i = 0; i < menuSelection; i++)
    {
        cout << "Please enter item " << i + 1 << ": ";
        cin >> item;
        list.appendNode(item);
    }

    list.displayList();

    cout << "Which item do you wish to delete from the list? >> ";
    cin >> delItem;
    while (delItem == "")
    {
        cout << "Please enter a valid item >> ";
        cin >> delItem;
    }

    list.deleteNode(delItem);

    list.displayList();

    //Wait for user input to exit program
    system("PAUSE");

    return 0;
}

 //strList.h
 #ifndef STRLIST_H
 #define STRLIST_H

 #include <iostream>
 #include <string>

 namespace
 {
     class StrList
    {
    private:
        struct ListNode
        {
            std::string value;
            struct ListNode *next;
        };

        ListNode *head;
    public:
        //Constructor
        StrList()
        {
             head = nullptr;
        }

         //Destructor
         ~StrList();

         //Linked List Operations
         void appendNode(std::string item);
         void insertNode(std::string item);
         void deleteNode(std::string item);
         void displayList() const;
     };
 }
#endif

 //strList.cpp
 #ifndef STRLIST_CPP
 #define STRLIST_CPP

 #include <iostream>
 #include <string>
 #include "strList.h"

 void StrList::appendNode(std::string item)
 {
     ListNode *newNode;
     ListNode *nodePtr;

     //Allocate a new node and store item there
     newNode = new ListNode;
     newNode->value = item;
     newNode->next = nullptr;

     //If there are no nodes in the list
     //make newNode the first node
     if (!head)
         head = newNode;
     else //Otherwise, insert newNode at the end
     {
         //Initialize nodePtr to head of the list
         nodePtr = head;

         //Find the last node in the list
         while (nodePtr->next)
             nodePtr = nodePtr->next;

         //Insert newNode as the last node
         nodePtr->next = newNode;
     }
 }

 void StrList::insertNode(std::string item)
 {
     ListNode *newNode;
     ListNode *nodePtr;
     ListNode *previousNode = nullptr;

     //Allocate a new node and store num there
     newNode = new ListNode;
     newNode->value = item;

     //If there are no nodes in the list
     //make newNode the first node
     if (!head)
     {
         head = newNode;
         newNode->next = nullptr;
     }
     else //Otherwise, insert newNode
     {
         //Position nodePtr at the head of list
         nodePtr = head;

         //Initialize previousNode to nullPtr
         previousNode = nullptr;

         //Skip all nodes whose values is less than num
         while (nodePtr != nullptr && nodePtr->value < item)
         {
             previousNode = nodePtr;
             nodePtr = nodePtr->next;
         }

         //If the new node is to be the 1st in the list,
         //insert it before all the other nodes
         if (previousNode == nullptr)
         {
             head = newNode;
             newNode->next = nodePtr;
         }
         else //Otherwise insert after the previous node
         {
             previousNode->next = newNode;
             newNode->next = nodePtr;
         }
     }
 }

 void StrList::deleteNode(std::string item)
 {
     ListNode *nodePtr;     //To traverse the list
     ListNode *previousNode = nullptr; //To point to the previous node

                             //If the list is empty, do nothing
     if (!head)
         return;

     //Determine if the first node is the one
     if (head->value == item)
     {
        nodePtr = head->next;
        delete head;
        head = nodePtr;
     }
     else
     {
         //Initialize nodePtr to head of list
         nodePtr = head;

         //Skip all nodes whose value member is
         //not equal to num
         while (nodePtr != nullptr && nodePtr->value != item)
         {
             previousNode = nodePtr;
             nodePtr = nodePtr->next;
         }

         //If nodePtr is not at the end of the list,
         //link the previous node to the node after
         //nodePtr, then delete nodePtr
         if (nodePtr)
         {
             previousNode->next = nodePtr->next;
             delete nodePtr;
         }
     }
 }

 StrList::~StrList()
 {
     ListNode *nodePtr; //To traverse the list
     ListNode *nextNode; //To point to the next node

                    //Position nodePtr at the head of the list
     nodePtr = head;

     //While nodePtr is not at the end of the list
     while (nodePtr != nullptr)
     {
         //Save a pointer to the next node
         nextNode = nodePtr->next;

         //Delete the current node
         delete nodePtr;

         //Position nodePtr at the next node
         nodePtr = nextNode;
     }
 }

 void StrList::displayList() const
 {
     ListNode *display;
     display = head;

     std::cout << "**********************************" << std::endl;
     std::cout << "****    Your Shopping List    ****" << std::endl;
     std::cout << "**********************************" << std::endl;

     while (display)
     {
         std::cout << display->value;
         display = display->next;
     }
 }

 #endif
</code>```

The problem lies in the displayList(); function towards the end of the file.

答:
Add a separator for between your values.</p>

```<code>char const* sep = "";
while (display)
{
    std::cout << sep << display->value;
    sep = " ";
    display = display->next;
}
</code>```

Body:
When I run my program, it works as intended, except the items in the list have no spaces between them when the displayList() function is called.  I have 3 files.  The main cpp file is ShoppingList.cpp.  Then I have two other files for the linked list classification and implementation.

//ShoppingList.cpp
//Michael Hery
//COP 2001
//11/9/17
//Shopping List

#include <iostream>
#include <string>
#include "strList.h"
#include "strlist.cpp"

using namespace std;

int main()
{
    //Define a NumberList object
    StrList list;
    string item;
    string delItem;
    int menuSelection;

    //Ask the user how many items to
    //put in the list
    cout << "How many items would you like to put it the list? >> ";
    cin >> menuSelection;
    while (menuSelection < 1)
    {
        cout << "Please enter a valid number (greater than 0) >> ";
        cin >> menuSelection;
    }

    for (int i = 0; i < menuSelection; i++)
    {
        cout << "Please enter item " << i + 1 << ": ";
        cin >> item;
        list.appendNode(item);
    }

    list.displayList();

    cout << "Which item do you wish to delete from the list? >> ";
    cin >> delItem;
    while (delItem == "")
    {
        cout << "Please enter a valid item >> ";
        cin >> delItem;
    }

    list.deleteNode(delItem);

    list.displayList();

    //Wait for user input to exit program
    system("PAUSE");

    return 0;
}

 //strList.h
 #ifndef STRLIST_H
 #define STRLIST_H

 #include <iostream>
 #include <string>

 namespace
 {
     class StrList
    {
    private:
        struct ListNode
        {
            std::string value;
            struct ListNode *next;
        };

        ListNode *head;
    public:
        //Constructor
        StrList()
        {
             head = nullptr;
        }

         //Destructor
         ~StrList();

         //Linked List Operations
         void appendNode(std::string item);
         void insertNode(std::string item);
         void deleteNode(std::string item);
         void displayList() const;
     };
 }
#endif

 //strList.cpp
 #ifndef STRLIST_CPP
 #define STRLIST_CPP

 #include <iostream>
 #include <string>
 #include "strList.h"

 void StrList::appendNode(std::string item)
 {
     ListNode *newNode;
     ListNode *nodePtr;

     //Allocate a new node and store item there
     newNode = new ListNode;
     newNode->value = item;
     newNode->next = nullptr;

     //If there are no nodes in the list
     //make newNode the first node
     if (!head)
         head = newNode;
     else //Otherwise, insert newNode at the end
     {
         //Initialize nodePtr to head of the list
         nodePtr = head;

         //Find the last node in the list
         while (nodePtr->next)
             nodePtr = nodePtr->next;

         //Insert newNode as the last node
         nodePtr->next = newNode;
     }
 }

 void StrList::insertNode(std::string item)
 {
     ListNode *newNode;
     ListNode *nodePtr;
     ListNode *previousNode = nullptr;

     //Allocate a new node and store num there
     newNode = new ListNode;
     newNode->value = item;

     //If there are no nodes in the list
     //make newNode the first node
     if (!head)
     {
         head = newNode;
         newNode->next = nullptr;
     }
     else //Otherwise, insert newNode
     {
         //Position nodePtr at the head of list
         nodePtr = head;

         //Initialize previousNode to nullPtr
         previousNode = nullptr;

         //Skip all nodes whose values is less than num
         while (nodePtr != nullptr && nodePtr->value < item)
         {
             previousNode = nodePtr;
             nodePtr = nodePtr->next;
         }

         //If the new node is to be the 1st in the list,
         //insert it before all the other nodes
         if (previousNode == nullptr)
         {
             head = newNode;
             newNode->next = nodePtr;
         }
         else //Otherwise insert after the previous node
         {
             previousNode->next = newNode;
             newNode->next = nodePtr;
         }
     }
 }

 void StrList::deleteNode(std::string item)
 {
     ListNode *nodePtr;     //To traverse the list
     ListNode *previousNode = nullptr; //To point to the previous node

                             //If the list is empty, do nothing
     if (!head)
         return;

     //Determine if the first node is the one
     if (head->value == item)
     {
        nodePtr = head->next;
        delete head;
        head = nodePtr;
     }
     else
     {
         //Initialize nodePtr to head of list
         nodePtr = head;

         //Skip all nodes whose value member is
         //not equal to num
         while (nodePtr != nullptr && nodePtr->value != item)
         {
             previousNode = nodePtr;
             nodePtr = nodePtr->next;
         }

         //If nodePtr is not at the end of the list,
         //link the previous node to the node after
         //nodePtr, then delete nodePtr
         if (nodePtr)
         {
             previousNode->next = nodePtr->next;
             delete nodePtr;
         }
     }
 }

 StrList::~StrList()
 {
     ListNode *nodePtr; //To traverse the list
     ListNode *nextNode; //To point to the next node

                    //Position nodePtr at the head of the list
     nodePtr = head;

     //While nodePtr is not at the end of the list
     while (nodePtr != nullptr)
     {
         //Save a pointer to the next node
         nextNode = nodePtr->next;

         //Delete the current node
         delete nodePtr;

         //Position nodePtr at the next node
         nodePtr = nextNode;
     }
 }

 void StrList::displayList() const
 {
     ListNode *display;
     display = head;

     std::cout << "**********************************" << std::endl;
     std::cout << "****    Your Shopping List    ****" << std::endl;
     std::cout << "**********************************" << std::endl;

     while (display)
     {
         std::cout << display->value;
         display = display->next;
     }
 }

 #endif

The problem lies in the displayList(); function towards the end of the file.

Body:
Add a separator for between your values.

char const* sep = "";
while (display)
{
    std::cout << sep << display->value;
    sep = " ";
    display = display->next;
}


来源: stackexchange

问:
Unable to print HTML output on new line using JS
I am trying to print the following output onto my html page:

100.101.102.103

Trying 192.168.30.61 ... Open

Warning Notice

This system is restricted solely to company authorized users

But instead i am getting this :
'\n100.101.102.103\r\nTrying 100.101.102.103 ... Open\r\n\r\n*************                       **************************************************************\r\n                                              Warning Notice\r\n\r\nThis system is restricted solely to company authoriz                       ed users

The JS:

```<code><script>
    $(function() {
    $('button').click(function() {
        $.ajax({
            url: '/runCommand_query',
            data: $('form').serialize(),
            type: 'POST',
            success: function(response) {
            //alert("hi");
            console.log(response);
            //$("#opt").html(response);
            $("#opt").html(response);
        },
        error: function(error) {
        console.log(error);
    $("#opt").val(error);
        }
    });
});
</code>```

});

The HTML:

```output id="opt" name="opt"```

I need a solution to get rid of the "\r" and "\n"

答:
You need to convert the JavaScript string escape code for a new line to an HTML
 element.

At the beginning of your AJAX success handler, add:

```<code>response = response.replace(/(\n|\r)/g, "<br>");
</code>```

Here's an example:

var response = " '\n100.101.102.103\r\nTrying 100.101.102.103 ...";

response = response.replace(/(\n|\r)/g, "
");

document.querySelector("p").innerHTML = response;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p></p></code>```

ContentLicense: CC BY-SA 3.0

Body:
You need to convert the JavaScript string escape code for a new line to an HTML <br> element.

At the beginning of your AJAX success handler, add:

response = response.replace(/(\n|\r)/g, "<br>");

Here's an example:

var response = " '\n100.101.102.103\r\nTrying 100.101.102.103 ...";

response = response.replace(/(\n|\r)/g, "<br>");

document.querySelector("p").innerHTML = response;

<p></p>


问:
Dynamically adding WCF Data Services Endpoints
I've been researching oData and WCF DataServices and I think it would work great for my project.

However, each of our clients have their own database.

So, is there a way to dynamically create a WCF endpoint that I could point to a database.
The schema for all the databases are identical.

For Example:
Client1 needs DB1, they would use the URL: https://webservice.com/wcf/Client1 which would use DB1

Client2 needs DB2, they would use the URL: https://webservice.com/wcf/Client2 which would use DB2

Client3 needs DB3, they would use the URL: https://webservice.com/wcf/Client3 which would use DB3

Or I would need to be able to pass which database to connect to, but I don't how i would do that with WCF Data Services., I've done it with normal WCF services in the past though

They need to be dynamic because we are adding new clients all the time and we have an automated process for creating databases.

I know I could create a web service per database, but it would be much easier to maintain with 1 web service.

答:
I found the answer.

Rather then creating multiple endpoints, I can just pass the Connection String from the webservice as a header.

Here's example code. It's really easy to implement and works great.

http://social.msdn.microsoft.com/Forums/en-NZ/adodotnetdataservices/thread/2eb0e7a8-10c5-4c6c-80b8-23cb39161345

ContentLicense: CC BY-SA 2.5


问:
Javascript - Anonymous functions declared without type declarations, should they be local scoped?
I'm reading some JavaScript for work and have come across a section of code I'm finding interesting. I've done some reading and came across:

Is using 'var' to declare variables optional?

Which illuminates the lack of a var type declaration as putting the var into a scope bubbling mutable global-not-global state.

Example:

```<code>var foo = bar  // locally scoped
foo = bar // outer scope, can have global ramifications
</code>```

My question here is when combining outer scope declarations with anonymous functions, is this acceptable and what would be the recommended way of handling this? Is it "good" convention? Should this be locally scoped? It is inside a class for my purposes, so I see no reason why it would be anything other than locally scoped. Again, JS noob though, so looking for some insights.

Example:

```<code>updateThing = (e) => {
    this.state.items = e.target.value;
}
</code>```

Much appreciated, thanks.

答:
Anonymous functions declared without type declarations

There are no anonymous function declarations (except in export default). All the examples you have are assignments or variable declarations with initialisers.

When combining outer scope declarations with anonymous functions, is this acceptable and what would be the recommended way of handling this? Is it "good" convention?

No, this is a bad practice. Just don't do it. Never assign to variables you have not declared anywhere.

It is inside a class for my purposes

If you mean a class definition body: the assignment syntax there is an experimental shortcut for property intialisations in the constructor. Don't use it especially if you don't know what it means. Just write it explicitly:

```<code>class … {
    constructor(…) {
         …
         this.updateThing = (e) => {
             this.state.items = e.target.value;
         };
    }
    …
}
</code>```

This is not a variable assignment and has nothing to do with declarations at all.

Body:
I'm reading some JavaScript for work and have come across a section of code I'm finding interesting. I've done some reading and came across:

Is using 'var' to declare variables optional?

Which illuminates the lack of a var type declaration as putting the var into a scope bubbling mutable global-not-global state.

Example:

var foo = bar  // locally scoped
foo = bar // outer scope, can have global ramifications

My question here is when combining outer scope declarations with anonymous functions, is this acceptable and what would be the recommended way of handling this? Is it "good" convention? Should this be locally scoped? It is inside a class for my purposes, so I see no reason why it would be anything other than locally scoped. Again, JS noob though, so looking for some insights.

Example:

updateThing = (e) => {
    this.state.items = e.target.value;
}

Much appreciated, thanks.

Body:
Anonymous functions declared without type declarations

There are no anonymous function declarations (except in export default). All the examples you have are assignments or variable declarations with initialisers.

When combining outer scope declarations with anonymous functions, is this acceptable and what would be the recommended way of handling this? Is it "good" convention?

No, this is a bad practice. Just don't do it. Never assign to variables you have not declared anywhere.

It is inside a class for my purposes

If you mean a class definition body: the assignment syntax there is an experimental shortcut for property intialisations in the constructor. Don't use it especially if you don't know what it means. Just write it explicitly:

class … {
    constructor(…) {
         …
         this.updateThing = (e) => {
             this.state.items = e.target.value;
         };
    }
    …
}

This is not a variable assignment and has nothing to do with declarations at all.


问:
List with arrays into seperate arrays
I have a constructor which uses a List parameter. Inside that list I have three items which are 3 integer arrays.

```<code>public HistogramLogic(List<Tuple<int[], int[], int[]>> separateRGB)
</code>```

Now I want to initialize three new integer arrays with the arrays inside that list. But when I try this code, the index of my new arrays stay 0.

```<code>for (int i = 0; i < histogramXValues.Length; i++)
{
     rArray = separateRGB.Select(obj => obj.Item1[i]).ToArray();
     gArray = separateRGB.Select(obj => obj.Item2[i]).ToArray();
     bArray = separateRGB.Select(obj => obj.Item3[i]).ToArray();
}
</code>```

Anyone got any suggestions on how to fix this?

答:
You can just get the item from touple</p>

```<code>rArray = separateRGB.Select(obj => obj.Item1);
</code>```

Title: List with arrays into seperate arrays

Body:
I have a constructor which uses a List parameter. Inside that list I have three items which are 3 integer arrays.

public HistogramLogic(List<Tuple<int[], int[], int[]>> separateRGB)

Now I want to initialize three new integer arrays with the arrays inside that list. But when I try this code, the index of my new arrays stay 0.

for (int i = 0; i < histogramXValues.Length; i++)
{
     rArray = separateRGB.Select(obj => obj.Item1[i]).ToArray();
     gArray = separateRGB.Select(obj => obj.Item2[i]).ToArray();
     bArray = separateRGB.Select(obj => obj.Item3[i]).ToArray();
}

Anyone got any suggestions on how to fix this?

Body:
You can just get the item from touple

rArray = separateRGB.Select(obj => obj.Item1);


问:
Send email with href tag
I am trying to send an email with a link which will open an ionic app. The email is being sent but the href tag is being stripped. So I just get a plain Hello string. No href.

In the example below, Hello World is in plain text while World is in bold.

```<code>exports.sendNewEventEmail = functions.database.ref('/email/{pushId}/{uid}')
  .onWrite(event => {

    if (event.data.previous.exists()) {
      return;
    }

    if (!event.data.exists()) {
      return;
    }

    const mailOptions = {
      from: `${APP_NAME} <noreply@example.com>`,
      to: event.data.val(),
      html: '<a href="myappname://app">Hello world ?</a><strong>World!</strong>',
      isHtml: true
    };

    mailOptions.subject = `Welcome to ${APP_NAME}!`;

    return mailTransport.sendMail(mailOptions).then(() => {
      console.log('New invite email sent');
    });

  });
</code>```

答: set isHtml : true for your mailOptions object.

Title: Send email with href tag

Body:
I am trying to send an email with a link which will open an ionic app. The email is being sent but the href tag is being stripped. So I just get a plain Hello string. No href.

In the example below, Hello World is in plain text while World is in bold.

exports.sendNewEventEmail = functions.database.ref('/email/{pushId}/{uid}')
  .onWrite(event => {

    if (event.data.previous.exists()) {
      return;
    }

    if (!event.data.exists()) {
      return;
    }

    const mailOptions = {
      from: `${APP_NAME} <noreply@example.com>`,
      to: event.data.val(),
      html: 'Hello world ?World!',
      isHtml: true
    };

    mailOptions.subject = `Welcome to ${APP_NAME}!`;

    return mailTransport.sendMail(mailOptions).then(() => {
      console.log('New invite email sent');
    });

  });


问:
Matching keywords in a dictionary to a list in Python
The following dictionary gives the word and its value:

```<code>keywords = {'alone': 1, 'amazed': 10, 'amazing': 10, 'bad': 1, 'best': 10, 'better': 7, 'excellent': 10, 'excited': 10, 'excite': 10}
</code>```

Following the dictionary are two tweets in a list in a list.
For each tweet, we need to find which of the words from keywords are present in it.

```<code>tweets = [['work', 'needs', 'to', 'fly', 'by', '', "i'm", 'so', 'excited', 'to', 'see', 'spy', 'kids', '4', 'with', 'then', 'love', 'of', 'my', 'life', '', 'arreic'], ['today', 'is', 'going', 'to', 'be', 'the', 'greatest', 'day', 'of', 'my', 'life', 'hired', 'to', 'take', 'pictures', 'at', 'my', 'best', "friend's", 'gparents', '50th', 'anniversary', '60', 'old', 'people', 'woo']]
</code>```

The target is to find the sum of the keyword values found in each tweet line.

The code created needs to be a loop because there are more than 2 tweets.
I do not understand how I should execute this process.

Appreciate your insight!

答:
```<code>keywords = {'alone': 1, 'amazed': 10, 'amazing': 10, 'bad': 1, 'best': 10, 'better': 7, 'excellent': 10, 'excited': 10, 'excite': 10}
tweets = [['work', 'needs', 'to', 'fly', 'by', '', "i'm", 'so', 'excited', 'to', 'see', 'spy', 'kids', '4', 'with', 'then', 'love', 'of', 'my', 'life', '', 'arreic'], ['today', 'is', 'going', 'to', 'be', 'the', 'greatest', 'day', 'of', 'my', 'life', 'hired', 'to', 'take', 'pictures', 'at', 'my', 'best', "friend's", 'gparents', '50th', 'anniversary', '60', 'old', 'people', 'woo']]

values = []              # Here we will store the score of each tweat like an item

for tweet in tweets:     # We iterate over each tweet
    values.append(0)     # We add a new item to the list values, we'll change this number later.
    for word in tweet:   # We iterate over each word in the tweet
        values[-1] += keywords.get(word, 0) # Using .get() we get the value of a word if it's inside keyword, if not, we get a default value: 0, instead of an KeyError.
print(values) # Obviously, print the values in console
</code>```

If you don't like the values.append(0) you can change it to new = 0 and the values[-1] to tmp. You will also need to add at the end of the first loop values.append(tmp).

Also, remember that x += y can be read as x = x + y.

If you want to have a total score, you can:

```<code># ^ Use the code above ^
total_value = sum(values) # It sum all the items of values
print(total_value)

# Or total new code.

total_score = 0
for tweet in tweets:
    for word in tweet:
        total_score += keywords.get(word, 0)
print(total_score)
</code>```

Or if you want small codes:

```<code>total_value = sum([keywords.get(word,0) for tweet in tweets for word in tweet])

value = [sum([keywords.get(word, 0) for word in tweet]) for tweet in tweets]
</code>```

Your choice.

Body:
The following dictionary gives the word and its value:

keywords = {'alone': 1, 'amazed': 10, 'amazing': 10, 'bad': 1, 'best': 10, 'better': 7, 'excellent': 10, 'excited': 10, 'excite': 10}

Following the dictionary are two tweets in a list in a list.
For each tweet, we need to find which of the words from keywords are present in it.

tweets = [['work', 'needs', 'to', 'fly', 'by', '', "i'm", 'so', 'excited', 'to', 'see', 'spy', 'kids', '4', 'with', 'then', 'love', 'of', 'my', 'life', '', 'arreic'], ['today', 'is', 'going', 'to', 'be', 'the', 'greatest', 'day', 'of', 'my', 'life', 'hired', 'to', 'take', 'pictures', 'at', 'my', 'best', "friend's", 'gparents', '50th', 'anniversary', '60', 'old', 'people', 'woo']]

The target is to find the sum of the keyword values found in each tweet line.

The code created needs to be a loop because there are more than 2 tweets.
I do not understand how I should execute this process.

Appreciate your insight!

Body:
keywords = {'alone': 1, 'amazed': 10, 'amazing': 10, 'bad': 1, 'best': 10, 'better': 7, 'excellent': 10, 'excited': 10, 'excite': 10}
tweets = [['work', 'needs', 'to', 'fly', 'by', '', "i'm", 'so', 'excited', 'to', 'see', 'spy', 'kids', '4', 'with', 'then', 'love', 'of', 'my', 'life', '', 'arreic'], ['today', 'is', 'going', 'to', 'be', 'the', 'greatest', 'day', 'of', 'my', 'life', 'hired', 'to', 'take', 'pictures', 'at', 'my', 'best', "friend's", 'gparents', '50th', 'anniversary', '60', 'old', 'people', 'woo']]

values = []              # Here we will store the score of each tweat like an item

for tweet in tweets:     # We iterate over each tweet
    values.append(0)     # We add a new item to the list values, we'll change this number later.
    for word in tweet:   # We iterate over each word in the tweet
        values[-1] += keywords.get(word, 0) # Using .get() we get the value of a word if it's inside keyword, if not, we get a default value: 0, instead of an KeyError.
print(values) # Obviously, print the values in console

If you don't like the values.append(0) you can change it to new = 0 and the values[-1] to tmp. You will also need to add at the end of the first loop values.append(tmp).

Also, remember that x += y can be read as x = x + y.

If you want to have a total score, you can:

# ^ Use the code above ^
total_value = sum(values) # It sum all the items of values
print(total_value)

# Or total new code.

total_score = 0
for tweet in tweets:
    for word in tweet:
        total_score += keywords.get(word, 0)
print(total_score)

Or if you want small codes:

total_value = sum([keywords.get(word,0) for tweet in tweets for word in tweet])

value = [sum([keywords.get(word, 0) for word in tweet]) for tweet in tweets]

Your choice.


问:
Divide values by lists of three and comparing elements in it
I have some values coming from sensor. My task is to divide them into lists of three elements.  If two consecutive elements differ by at least 10, I should ignore the rest of the list.

From this:

```<code>values = [1,3,6,8,9,11,15,17,28,29]
</code>```

I should get:

```<code>[1,3,6]
[8,9,11]
[15,17]
</code>```

I've managed to divide values by list of three:

```<code>list_of_values = [1,3,6,8,9,11,15,17,28,29]
def divide(values, size):
    return (values[pos:pos + size] for pos in range(0, len(values), size))
for group in divide(list_of_values, 3):
    print(group)
</code>```

But I can't figure out how to compare previous and next value like the task says.

答:
First, calculate where to the index of where to stop the chunking:

```<code>stp = [i for i in range(len(values)-1) if values[i]+10 < values[i+1]] [0]
</code>```

then chunk to this index:

```<code>[values[:stp+1][i:i+3] for i in range(0, stp, 3)]
</code>```

which outputs:

```<code>[[1, 3, 6], [8, 9, 11], [15, 17]]
</code>```

Body:
I have some values coming from sensor. My task is to divide them into lists of three elements.  If two consecutive elements differ by at least 10, I should ignore the rest of the list.

From this:

values = [1,3,6,8,9,11,15,17,28,29]

I should get:

[1,3,6]
[8,9,11]
[15,17]

I've managed to divide values by list of three:

list_of_values = [1,3,6,8,9,11,15,17,28,29]
def divide(values, size):
    return (values[pos:pos + size] for pos in range(0, len(values), size))
for group in divide(list_of_values, 3):
    print(group)

But I can't figure out how to compare previous and next value like the task says.

Body:
First, calculate where to the index of where to stop the chunking:

stp = [i for i in range(len(values)-1) if values[i]+10 < values[i+1]] [0]

then chunk to this index:

[values[:stp+1][i:i+3] for i in range(0, stp, 3)]

which outputs:

[[1, 3, 6], [8, 9, 11], [15, 17]]


问:
How to find the longest set of consecutive increasing (ascending) elements in array?
One straightforward way to find it is just check each element and its following element and include it in another array. But it's not so clear. Another way would be Divide & Conquer approach using Merge Sorting algorithm. In this case it's not supposed to sort numbers but divide them recursively in subarrays and merge only those numbers which satisfy condition n < n+1. But I'm not sure about code implementation of program that is merging and checking part.</p>

答:
Forgive me if I misunderstand your problem but why use separate arrays, merging, sorting, etc.?  If as I understand it you're just looking for the longest sequence of increasing elements, recursion could be your friend.  Pass a pointer to element N to func(n), if N+1 is greater than N, then N++, and call func(N) calls itself again (making sure you don't exceed the bounds of your array.

A simplistic explanation but think you see what I'm driving at.


问:
LDAP- Error opening connection : xx.xx.xx.xx:389
I'm trying to connect the LDAP server available on cloud. The web interface for the server is  :  xx.xx.xx.xx/phpldapadmin where I can login and do whatever operation I want to do.

But when I'm trying to bind the ldap from my local machine through JXplorer, I'm getting connection timeout error. Here are the screenshots :

Connection Wizard

Error wizard:

Stack Trace

javax.naming.CommunicationException: XX.XX.XX.XX:389 [Root exception is java.net.ConnectException: Connection timed out: connect]
at com.sun.jndi.ldap.Connection.<init>(Connection.java:223)
at com.sun.jndi.ldap.LdapClient.<init>(LdapClient.java:136)
at com.sun.jndi.ldap.LdapClient.getInstance(LdapClient.java:1600)
at com.sun.jndi.ldap.LdapCtx.connect(LdapCtx.java:2698)
at com.sun.jndi.ldap.LdapCtx.<init>(LdapCtx.java:316)
at com.sun.jndi.ldap.LdapCtxFactory.getUsingURL(LdapCtxFactory.java:193)
at com.sun.jndi.ldap.LdapCtxFactory.getUsingURLs(LdapCtxFactory.java:211)
at com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance(LdapCtxFactory.java:154)
at com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(LdapCtxFactory.java:84)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:684)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:307)
at javax.naming.InitialContext.init(InitialContext.java:242)
at javax.naming.ldap.InitialLdapContext.<init>(InitialLdapContext.java:153)
at com.ca.commons.jndi.JNDIOps.openContext(JNDIOps.java:529)
at com.ca.commons.jndi.JNDIOps.<init>(JNDIOps.java:123)
at com.ca.commons.jndi.BasicOps.<init>(BasicOps.java:55)
at com.ca.commons.jndi.AdvancedOps.<init>(AdvancedOps.java:59)
at com.ca.commons.naming.DXOps.<init>(DXOps.java:41)
at com.ca.directory.jxplorer.broker.CBGraphicsOps.<init>(CBGraphicsOps.java:46)
at com.ca.directory.jxplorer.broker.JNDIDataBroker.openConnection(JNDIDataBroker.java:477)
at com.ca.directory.jxplorer.broker.JNDIDataBroker.openConnection(JNDIDataBroker.java:422)
at com.ca.directory.jxplorer.broker.JNDIDataBroker.processRequest(JNDIDataBroker.java:396)
at com.ca.directory.jxplorer.broker.DataBroker.processQueue(DataBroker.java:200)
at com.ca.directory.jxplorer.broker.JNDIDataBroker.processQueue(JNDIDataBroker.java:913)
at com.ca.directory.jxplorer.broker.DataBroker.run(DataBroker.java:165)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:337)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:198)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:180)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at com.sun.jndi.ldap.Connection.createSocket(Connection.java:365)
at com.sun.jndi.ldap.Connection.<init>(Connection.java:200)
... 25 more

Please help !

答:
Connection timed out indicates that the port 389 is not accessible from your network. Make sure the firewall in cloud allows your ip to access port 389 of the LDAP host. phpldapadmin will work since it will listen on port 80/443 and it in turn connects with LDAP locally.

You can test the connectivity by running telnet <LDAP Host> 389. If the port is accessible from you host, you'll be able to establish a connection.


问:
Presto not returning rows from Hive Metabase
I'm very new to AWS EMR. I've got Hive up and running and been querying external tables in S3 with no problems. I have now installed Presto onto the EMR cluster and this seems to be up and running and can read the Hive metabase. However, every query I run returns the column headers but not actually any columns (query below).

```<code>presto:default> select count(*) from patrequests;
 _col0
-------
     0
(1 row)

Query 20171113_163811_00033_vdw6c, FINISHED, 1 node
Splits: 17 total, 17 done (100.00%)
0:00 [0 rows, 0B] [0 rows/s, 0B/s]
</code>```

The same query in Hive runs fine:

```<code>hive> select * from patrequests limit 10;
OK
2017-10-01T00:00:18.6772628Z    779     *****  *****  *****      *****      2017    10
Time taken: 2.876 seconds, Fetched: 10 row(s)
</code>```

The data is stored in an S3 bucket in JSON format - no nesting.

Any help greatly appreciated.

Thanks

答:
The problem seemed to be with the JSON Serde org.openx.data.jsonserde.JsonSerDe not being available to Presto. Bootstrapping the instance with the following from an S3 bucket seemed to resolve the issues:</p>

```<code>#!/bin/bash
wget -P /usr/lib/presto/plugin/hive-hadoop2/  'https://s3-eu-west-1.amazonaws.com/########/json-serde-1.3.9-SNAPSHOT-jar-with-dependencies.jar';
wget -P /usr/lib/hive-hcatalog/share/hcatalog/ 'https://s3-eu-west-1.amazonaws.com/########/json-serde-1.3.9-SNAPSHOT-jar-with-dependencies.jar';
</code>```

Body:
I'm very new to AWS EMR. I've got Hive up and running and been querying external tables in S3 with no problems. I have now installed Presto onto the EMR cluster and this seems to be up and running and can read the Hive metabase. However, every query I run returns the column headers but not actually any columns (query below).

presto:default> select count(*) from patrequests;
 _col0
-------
     0
(1 row)

Query 20171113_163811_00033_vdw6c, FINISHED, 1 node
Splits: 17 total, 17 done (100.00%)
0:00 [0 rows, 0B] [0 rows/s, 0B/s]

The same query in Hive runs fine:

hive> select * from patrequests limit 10;
OK
2017-10-01T00:00:18.6772628Z    779     *****  *****  *****      *****      2017    10
Time taken: 2.876 seconds, Fetched: 10 row(s)

The data is stored in an S3 bucket in JSON format - no nesting.

Any help greatly appreciated.

Thanks

Body:
The problem seemed to be with the JSON Serde org.openx.data.jsonserde.JsonSerDe not being available to Presto. Bootstrapping the instance with the following from an S3 bucket seemed to resolve the issues:

#!/bin/bash
wget -P /usr/lib/presto/plugin/hive-hadoop2/  'https://s3-eu-west-1.amazonaws.com/########/json-serde-1.3.9-SNAPSHOT-jar-with-dependencies.jar';
wget -P /usr/lib/hive-hcatalog/share/hcatalog/ 'https://s3-eu-west-1.amazonaws.com/########/json-serde-1.3.9-SNAPSHOT-jar-with-dependencies.jar';


问:
unable to locate factory with name [default] [Subject]
I just want some dummy data that I can loop out from my database but when I try to using the seeder I get this error:

```<code>unable to locate factory with name [default] [Subject]
</code>```

The code I run is:

```<code>php artisan db:seed --class=SubjectSeeder
</code>```

ModelFactory.php:

```<code>$factory->define(App\Subject::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'code' => $faker->str_random(3),
        ];
});
</code>```

SubjectSeeder.php:

```<code>public function run()
{
    $subject = factory(Subject::class)->make();

    Product::create([
        'name' => $subject->name,
        'code' => $subject->code
    ]);
}
</code>```

subject.php:

```<code>class Subject extends Model
{
    protected $fillable = [
        'name', 'code',
    ];
};
</code>```

答:
If someone makes the same mistake as me, i tried just to define state factories, without default one:

```<code>$factory->define(\App\Model::class, function (Faker $faker) {
</code>```

Body:
I just want some dummy data that I can loop out from my database but when I try to using the seeder I get this error:

unable to locate factory with name [default] [Subject]

The code I run is:

php artisan db:seed --class=SubjectSeeder

ModelFactory.php:

$factory->define(App\Subject::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'code' => $faker->str_random(3),
        ];
});

SubjectSeeder.php:

public function run()
{
    $subject = factory(Subject::class)->make();

    Product::create([
        'name' => $subject->name,
        'code' => $subject->code
    ]);
}

subject.php:

class Subject extends Model
{
    protected $fillable = [
        'name', 'code',
    ];
};

Body:
If someone makes the same mistake as me, i tried just to define state factories, without default one:

$factory->define(\App\Model::class, function (Faker $faker) {


答:
Bear in mind, if you have a list of N tuples, you start with 3 x N arrays. Sounds like you want them combined into 3 arrays, each containing all of the elements throughout the list. Which you can do with SelectMany.

```<code>rArray = separateRGB.SelectMany(obj => obj.Item1).ToArray();
gArray = separateRGB.SelectMany(obj => obj.Item2).ToArray();
bArray = separateRGB.SelectMany(obj => obj.Item3).ToArray();
</code>```

Full example:

```<code>using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    static public void HistogramLogic(List<Tuple<int[], int[], int[]>> separateRGB)
    {
        var rArray = separateRGB.SelectMany(obj => obj.Item1).ToArray();
        var gArray = separateRGB.SelectMany(obj => obj.Item2).ToArray();
        var bArray = separateRGB.SelectMany(obj => obj.Item3).ToArray();

        Console.WriteLine("rArray = {{{0}}}", string.Join(",", rArray));
        Console.WriteLine("gArray = {{{0}}}", string.Join(",", gArray));
        Console.WriteLine("bArray = {{{0}}}", string.Join(",", bArray));
    }

    public static void Main()
    {
        var mockData = new List<Tuple<int[], int[], int[]>>
        {
            Tuple.Create(new[] {11,12,13}, new[] {14,15,16}, new[] {17,18,19}),
            Tuple.Create(new[] {21,22,23}, new[] {24,25,26}, new[] {27,28,29}),
            Tuple.Create(new[] {31,32,33}, new[] {34,35,36}, new[] {37,38,39})
        };

        HistogramLogic(mockData);
    }
}
</code>```

Output:

```<code>rArray = {11,12,13,21,22,23,31,32,33}
gArray = {14,15,16,24,25,26,34,35,36}
bArray = {17,18,19,27,28,29,37,38,39}
</code>```

Click here for code on DotNetFiddle

Title: List with arrays into seperate arrays

Body:
Bear in mind, if you have a list of N tuples, you start with 3 x N arrays. Sounds like you want them combined into 3 arrays, each containing all of the elements throughout the list. Which you can do with SelectMany.

rArray = separateRGB.SelectMany(obj => obj.Item1).ToArray();
gArray = separateRGB.SelectMany(obj => obj.Item2).ToArray();
bArray = separateRGB.SelectMany(obj => obj.Item3).ToArray();

Full example:

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    static public void HistogramLogic(List<Tuple<int[], int[], int[]>> separateRGB)
    {
        var rArray = separateRGB.SelectMany(obj => obj.Item1).ToArray();
        var gArray = separateRGB.SelectMany(obj => obj.Item2).ToArray();
        var bArray = separateRGB.SelectMany(obj => obj.Item3).ToArray();

        Console.WriteLine("rArray = {{{0}}}", string.Join(",", rArray));
        Console.WriteLine("gArray = {{{0}}}", string.Join(",", gArray));
        Console.WriteLine("bArray = {{{0}}}", string.Join(",", bArray));
    }

    public static void Main()
    {
        var mockData = new List<Tuple<int[], int[], int[]>>
        {
            Tuple.Create(new[] {11,12,13}, new[] {14,15,16}, new[] {17,18,19}),
            Tuple.Create(new[] {21,22,23}, new[] {24,25,26}, new[] {27,28,29}),
            Tuple.Create(new[] {31,32,33}, new[] {34,35,36}, new[] {37,38,39})
        };

        HistogramLogic(mockData);
    }
}

Output:

rArray = {11,12,13,21,22,23,31,32,33}
gArray = {14,15,16,24,25,26,34,35,36}
bArray = {17,18,19,27,28,29,37,38,39}

Click here for code on DotNetFiddle


问:
Creating default object from empty value in PHP?
I see this error only after upgrading my PHP environment to PHP 5.4 and beyond. The error points to this line of code:

Error:

Creating default object from empty value

Code:

```<code>$res->success = false;
</code>```

Do I first need to declare my $res object?

答:
You may need to check if variable declared and has correct type.

```<code>if (!isset($res) || !is_object($res)) {
    $res = new \stdClass();
    // With php7 you also can create an object in several ways.
    // Object that implements some interface.
    $res = new class implements MyInterface {};
    // Object that extends some object.
    $res = new class extends MyClass {};
}

$res->success = true;
</code>```

See PHP anonymous classes.

Body:
I see this error only after upgrading my PHP environment to PHP 5.4 and beyond. The error points to this line of code:

Error:

Creating default object from empty value

Code:

$res->success = false;

Do I first need to declare my $res object?

Body:
You may need to check if variable declared and has correct type.

if (!isset($res) || !is_object($res)) {
    $res = new \stdClass();
    // With php7 you also can create an object in several ways.
    // Object that implements some interface.
    $res = new class implements MyInterface {};
    // Object that extends some object.
    $res = new class extends MyClass {};
}

$res->success = true;

See PHP anonymous classes.


问:
CSS gradual background change of a moving div?
What I am trying to achieve is this:

a coin (ring) sinking into the slot. Initially it is blue. when it enters the red background it becomes white. when it reaches the slot - it is gradually disappearing.

and this is what I have come up with so far:

```<code>  .circle {
  transition: all 1s ease;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background: url(http://a5w.org/up/uploads/mike/2017-11-15/1510773962_red_square.png) no-repeat;
  background-color: #fff;
  background-position: 0 0;
  position: absolute;
  top: 0;
  left: 20px;
  z-index: 22;
}

.circle:hover {
  margin-top: 100px;
  background-position: 0px -100px;
}

.rect {
  margin-top: 200px;
  width: 100%;
  height: 400px;
  background: #666;
  transition: all 0.5s ease;
}

.slot{

  position: absolute;
  z-index: 666;
  background: #666;
  margin-top: 50px;

  height: 200px;
  width: 230px;
  border-top: solid 2px #333

}
</code>```

https://jsfiddle.net/y4fpyjsa/17/

This looks more like a hack though so I am wondering if there is a better solution, probably? Without moving backgrounds and extra layers.

答:
You can use 2 circles and play with z-index. One will be a part of the rect but hidden with overflow:hidden and will only be visible on hover when you increase its margin. The second one (the main one) will be hidden on hover below the rect because its low z-index.

With this trick you will visually have one circle with 2 different border colors and no need to change background.

.circle {
  transition: all 1s ease;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background-color: transparent;
  border:40px solid red;
  background-position: 0 0;
  position: absolute;
  top: 0;
  left: 50%;
  margin-left:-100px;
  z-index: 22;
}
.white {
  top:-200px;
  border:40px solid white;
  z-index:21
}

body:hover .circle {
  margin-top: 100px;
}

.rect {
  margin-top: 200px;
  width: 100%;
  height: 400px;
  background: #666;
  transition: all 0.5s ease;
  position:relative;
  z-index:500;
  overflow:hidden;
}

.slot {
  position: absolute;
  z-index: 666;
  background: #666;
  margin-top: 50px;
  height: 200px;
  width: 230px;
  border-top: solid 2px #333;
  right:50%;
  margin-right:-115px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="circle">
</div>
<div class="slot">
</div>
<div class="rect">
<div class="circle white">
</div>
</div></code>```

The only issue with this solution is that you have to make the hover effect on the container (here i used the body) as you cannot target one circle to move both of them.

Body:
What I am trying to achieve is this:

a coin (ring) sinking into the slot. Initially it is blue. when it enters the red background it becomes white. when it reaches the slot - it is gradually disappearing.

and this is what I have come up with so far:

  .circle {
  transition: all 1s ease;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background: url(http://a5w.org/up/uploads/mike/2017-11-15/1510773962_red_square.png) no-repeat;
  background-color: #fff;
  background-position: 0 0;
  position: absolute;
  top: 0;
  left: 20px;
  z-index: 22;
}

.circle:hover {
  margin-top: 100px;
  background-position: 0px -100px;
}

.rect {
  margin-top: 200px;
  width: 100%;
  height: 400px;
  background: #666;
  transition: all 0.5s ease;
}

.slot{

  position: absolute;
  z-index: 666;
  background: #666;
  margin-top: 50px;

  height: 200px;
  width: 230px;
  border-top: solid 2px #333

}

https://jsfiddle.net/y4fpyjsa/17/

This looks more like a hack though so I am wondering if there is a better solution, probably? Without moving backgrounds and extra layers.

Body:
You can use 2 circles and play with z-index. One will be a part of the rect but hidden with overflow:hidden and will only be visible on hover when you increase its margin. The second one (the main one) will be hidden on hover below the rect because its low z-index.

With this trick you will visually have one circle with 2 different border colors and no need to change background.

.circle {
  transition: all 1s ease;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background-color: transparent;
  border:40px solid red;
  background-position: 0 0;
  position: absolute;
  top: 0;
  left: 50%;
  margin-left:-100px;
  z-index: 22;
}
.white {
  top:-200px;
  border:40px solid white;
  z-index:21
}

body:hover .circle {
  margin-top: 100px;
}

.rect {
  margin-top: 200px;
  width: 100%;
  height: 400px;
  background: #666;
  transition: all 0.5s ease;
  position:relative;
  z-index:500;
  overflow:hidden;
}

.slot {
  position: absolute;
  z-index: 666;
  background: #666;
  margin-top: 50px;
  height: 200px;
  width: 230px;
  border-top: solid 2px #333;
  right:50%;
  margin-right:-115px;
}

<div class="circle">
</div>
<div class="slot">
</div>
<div class="rect">
<div class="circle white">
</div>
</div>

The only issue with this solution is that you have to make the hover effect on the container (here i used the body) as you cannot target one circle to move both of them.


问:
Powershell Scripting Code Execution Issue After Adding a While Loop
I am trying to write a Powershell script that communicates with some java server code. The script calls the following function to communicate with the server and currently the server is just printing out the message it receives.

```<code>Function Send-StringOverTcp (
    [Parameter(Mandatory=$True)][String]$DataToSend,
    [Parameter(Mandatory=$True)][UInt16]$Port)
{
    Try {
        $IPAddress = "XX.XXX.XX.X"                          #ip of server
        $IPAddress = [IPAddress]$IPAddress.Trim()

        $ErrorActionPreference = "Stop"
        $TCPClient  = New-Object Net.Sockets.TcpClient
        $IPEndpoint = New-Object Net.IPEndPoint($IPAddress, $Port)
        $TCPClient.Connect($IPEndpoint)
        Write-Host -ForegroundColor Green "Connection established with
$IPAddress on port $Port"

        $NetStream  = $TCPClient.GetStream()
        [Byte[]]$Buffer = [Text.Encoding]::ASCII.GetBytes($DataToSend)
        $NetStream.Write($Buffer, 0, $Buffer.Length)
        $NetStream.Flush()
        Write-Host -ForegroundColor Green "Data sent to server"

        while($true) {

        }

        If ($NetStream) { $NetStream.close() }
        If ($TCPClient) { $TCPClient.close() }
    } catch {
    Write-Error $_.Exception.ToString()
    Read-Host -Prompt "The above error occurred. Press Enter to exit."
    }
}
</code>```

In the script when I don't have the while loop before I close the TCPClient, the message is sent to the server and the server prints it out with no issues. However when I add this while loop the script never actually sends the message to the server code until after the while loop finishes. Is there any way to get the lines

```<code>$NetStream.Write($Buffer, 0, $Buffer.Length)
$NetStream.Flush()
</code>```

to execute before the while loop ends. Is there a reason Powershell isn't executing those statements in the correct order before the while loop instead of after it?

答: I'm still not sure what caused Powershell to act this way. In case anyone is having a similar issue I worked around this by just pulling the while loop out into it's own function and calling that with no issues.</p>

Body:
I am trying to write a Powershell script that communicates with some java server code. The script calls the following function to communicate with the server and currently the server is just printing out the message it receives.

Function Send-StringOverTcp (
    [Parameter(Mandatory=$True)][String]$DataToSend,
    [Parameter(Mandatory=$True)][UInt16]$Port)
{
    Try {
        $IPAddress = "XX.XXX.XX.X"                          #ip of server
        $IPAddress = [IPAddress]$IPAddress.Trim()

        $ErrorActionPreference = "Stop"
        $TCPClient  = New-Object Net.Sockets.TcpClient
        $IPEndpoint = New-Object Net.IPEndPoint($IPAddress, $Port)
        $TCPClient.Connect($IPEndpoint)
        Write-Host -ForegroundColor Green "Connection established with
$IPAddress on port $Port"

        $NetStream  = $TCPClient.GetStream()
        [Byte[]]$Buffer = [Text.Encoding]::ASCII.GetBytes($DataToSend)
        $NetStream.Write($Buffer, 0, $Buffer.Length)
        $NetStream.Flush()
        Write-Host -ForegroundColor Green "Data sent to server"

        while($true) {

        }

        If ($NetStream) { $NetStream.close() }
        If ($TCPClient) { $TCPClient.close() }
    } catch {
    Write-Error $_.Exception.ToString()
    Read-Host -Prompt "The above error occurred. Press Enter to exit."
    }
}

In the script when I don't have the while loop before I close the TCPClient, the message is sent to the server and the server prints it out with no issues. However when I add this while loop the script never actually sends the message to the server code until after the while loop finishes. Is there any way to get the lines

$NetStream.Write($Buffer, 0, $Buffer.Length)
$NetStream.Flush()

to execute before the while loop ends. Is there a reason Powershell isn't executing those statements in the correct order before the while loop instead of after it?


答:
It can be done using a single pass scan operation on the candidate array to see the length of the consecutive increasing sequence. So the pseudocode can be like the following:

```<code>a = [5 1 3 10 5 15 25 35 45 3 4 5];
longest_seq = 1;
temp_sec = 1;
for i =1:size(a)
    if a[i-1]<a[i[
       temp_sec = temp_sec +1;
    else
       if(temp_sec  > longest_seq )
           longest_seq  = temp_sec ;
       end
       temp_sec  = 1;
    end
end
</code>```

longest_seq is the number you are looking for (To my understanding).

Title: How to find the longest set of consecutive increasing (ascending) elements in array?

Body: One straightforward way to find it is just check each element and its following element and include it in another array. But it's not so clear. Another way would be Divide & Conquer approach using Merge Sorting algorithm. In this case it's not supposed to sort numbers but divide them recursively in subarrays and merge only those numbers which satisfy condition n < n+1. But I'm not sure about code implementation of program that is merging and checking part.

Body:
It can be done using a single pass scan operation on the candidate array to see the length of the consecutive increasing sequence. So the pseudocode can be like the following:

a = [5 1 3 10 5 15 25 35 45 3 4 5];
longest_seq = 1;
temp_sec = 1;
for i =1:size(a)
    if a[i-1]<a[i[
       temp_sec = temp_sec +1;
    else
       if(temp_sec  > longest_seq )
           longest_seq  = temp_sec ;
       end
       temp_sec  = 1;
    end
end

longest_seq is the number you are looking for (To my understanding).


问:
Insert a new row into DataTable
I have a datatable filled with staff data like..

```<code>Staff 1 - Day 1 - Total
Staff 1 - Day 2 - Total
Staff 1 - Day 3 - Total
Staff 2 - Day 1 - Total
Staff 2 - Day 2 - Total
Staff 2 - Day 3 - Total
Staff 2 - Day 4 - Total
</code>```

I want to modify so that the result would be sth like..

```<code>Staff 1 - Day 1 - Total
Staff 1 - Day 2 - Total
Staff 1 - Day 3 - Total
Total   -       - Total Value
Staff 2 - Day 1 - Total
Staff 2 - Day 2 - Total
Staff 2 - Day 3 - Total
Staff 2 - Day 4 - Total
Total   -       - Total Value
</code>```

to be concluded, I need to insert the total row at the end of each staff record.

So, my question is how to insert a row into a datatable? Tkz..

答:
```<code>// get the data table
DataTable dt = ...;

// generate the data you want to insert
DataRow toInsert = dt.NewRow();

// insert in the desired place
dt.Rows.InsertAt(toInsert, index);
</code>```

Title: Insert a new row into DataTable

Body:
I have a datatable filled with staff data like..

Staff 1 - Day 1 - Total
Staff 1 - Day 2 - Total
Staff 1 - Day 3 - Total
Staff 2 - Day 1 - Total
Staff 2 - Day 2 - Total
Staff 2 - Day 3 - Total
Staff 2 - Day 4 - Total

I want to modify so that the result would be sth like..

Staff 1 - Day 1 - Total
Staff 1 - Day 2 - Total
Staff 1 - Day 3 - Total
Total   -       - Total Value
Staff 2 - Day 1 - Total
Staff 2 - Day 2 - Total
Staff 2 - Day 3 - Total
Staff 2 - Day 4 - Total
Total   -       - Total Value

to be concluded, I need to insert the total row at the end of each staff record.

So, my question is how to insert a row into a datatable? Tkz..


问:
Why does my .values() not work as intended
I've been trying to list loans out to the console using .values(), it works with the maps when listing out items or borrowers but for my loans, anyone know why?

```<code>public void listLoans(){
  System.out.println("Loans:");
  for (LoanTransaction t: loans.values()) {
      System.out.println(t);
  }
  System.out.println();
}
</code>```

Accessors

```<code>public Map<Integer, Borrower>  getBorrowers() { return borrowers; }
public Map<Integer, Item>      getItems()     { return items; }
public List<LoanTransaction> getLoans()       { return loans; }
</code>```

Example of Listing Items that works as intended

```<code>public void listItems() {
    System.out.println("Items:");
    for (Item i: items.values()) {
      System.out.println(i);
    }
    System.out.println();
  }
</code>```

答:
There's no values() method for List. Maps need it to distinguish from the keySet() (and entrySet() which return key-value pairs). It's enough to use

```<code>for(LoanTransaction t: loans)
</code>```

Generally speaking, anything that implements Iterable can be used as the right hand side of the for-each loop.

Body:
I've been trying to list loans out to the console using .values(), it works with the maps when listing out items or borrowers but for my loans, anyone know why?

public void listLoans(){
  System.out.println("Loans:");
  for (LoanTransaction t: loans.values()) {
      System.out.println(t);
  }
  System.out.println();
}

Accessors

public Map<Integer, Borrower>  getBorrowers() { return borrowers; }
public Map<Integer, Item>      getItems()     { return items; }
public List<LoanTransaction> getLoans()       { return loans; }

Example of Listing Items that works as intended

public void listItems() {
    System.out.println("Items:");
    for (Item i: items.values()) {
      System.out.println(i);
    }
    System.out.println();
  }

Body:
There's no values() method for List. Maps need it to distinguish from the keySet() (and entrySet() which return key-value pairs). It's enough to use

for(LoanTransaction t: loans)

Generally speaking, anything that implements Iterable can be used as the right hand side of the for-each loop.


问:
Jumping between braces not working in SSMS
I am trying to jump to the closing brace for any open brace in a valid SQL which has subqueries, using ctrl+]. It's not doing anything. The key combo seems to be mapped correctly. Using SSMS 17.3.

Any adeas?

答:
are you sure you don't need to hold down the shift key?
from SSMS docs

```<code>Text Selection Keyboard Shortcuts
Action                 SQL Server 2017                SQL Server 2008 R2
Move the cursor to the next brace, extending the selection
                       CTRL+SHIFT+]                   No equivalent
</code>```

and

```<code>Microsoft IntelliSense Keyboard Shortcuts
Action                      SQL Server 2017 SQL Server 2008 R2
Jump between syntax pairs   CTRL+]          CTRL+]
</code>```

take a look under tools/options/text editor/all languages/general/settings (lower) section/Automatic Brace completion.  Mine was filled in solid instead of checked.
May not affect what you want, but may have some conflict dependent on the setting.
Also, under the Transact-SQL language, the automatic brace completion option is disabled.  Not sure if the settings are related.

ContentLicense: CC BY-SA 4.0

Body:
are you sure you don't need to hold down the shift key?
from SSMS docs

Text Selection Keyboard Shortcuts
Action                 SQL Server 2017                SQL Server 2008 R2
Move the cursor to the next brace, extending the selection
                       CTRL+SHIFT+]                   No equivalent

and

Microsoft IntelliSense Keyboard Shortcuts
Action                      SQL Server 2017 SQL Server 2008 R2
Jump between syntax pairs   CTRL+]          CTRL+]

take a look under tools/options/text editor/all languages/general/settings (lower) section/Automatic Brace completion.  Mine was filled in solid instead of checked.
May not affect what you want, but may have some conflict dependent on the setting.
Also, under the Transact-SQL language, the automatic brace completion option is disabled.  Not sure if the settings are related.


问:
PyCharm interpreting backward slashes wrong when checking regex expressions
The expression is:

```<code>re.search("(%s)\\(%d)([0-9]+)".format(newspaper, year2))
</code>```

where newspaper is a string and year2 is an integer.

Instead of interpreting \\ as an escape to the \ character, PyCharm interprets this as escaping ( and warns that I have an unmatched closing parenthesis in (%d). It also highlights the opening parenthesis in orange as well. When I replaced this with \\\, there is no warning but I'm not able to find my matches with this regex.

Is this how \ supposed to be escaped or am I missing another character?

答:
According to: https://regex101.com/

You are correct, \\ should be escaping the \

Try adding an r before your regex string and compile it, example:

```<code>regex = re.compile(r"(%s)\\(%d)([0-9]+)".format(newspaper, year2))
found = re.search(regex, stringy_thing)
</code>```

You can then use the group method to probe the returned found item(s); regex101 will also show you the capture groups in the upper right pane.

Body:
The expression is:

re.search("(%s)\\(%d)([0-9]+)".format(newspaper, year2))

where newspaper is a string and year2 is an integer.

Instead of interpreting \\ as an escape to the \ character, PyCharm interprets this as escaping ( and warns that I have an unmatched closing parenthesis in (%d). It also highlights the opening parenthesis in orange as well. When I replaced this with \\\, there is no warning but I'm not able to find my matches with this regex.

Is this how \ supposed to be escaped or am I missing another character?

Body:
According to: https://regex101.com/

You are correct, \\ should be escaping the \

Try adding an r before your regex string and compile it, example:

regex = re.compile(r"(%s)\\(%d)([0-9]+)".format(newspaper, year2))
found = re.search(regex, stringy_thing)

You can then use the group method to probe the returned found item(s); regex101 will also show you the capture groups in the upper right pane.


答:
values() available only on map as you said.

In case of List, those are the values it self. So just don't need the values

```<code>for (LoanTransaction t: loans.values())
</code>```

should be

```<code>for (LoanTransaction t: loans)
</code>```

Title: Why does my .values() not work as intended

Body:
values() available only on map as you said.

In case of List, those are the values it self. So just don't need the values

for (LoanTransaction t: loans.values())

should be

for (LoanTransaction t: loans)


问:
Azure hybrid connection Manager does not work
Requirement

I have an On-Premise SQL Server and an Azure webApp Service that needs to talk each other. I installed Hybrid Connection Manager on another computer which is in the same LAN as the SQL server. Let's refer this computer as the Connection PC.

The working part

Installation and configuration was straight forward, status of the hybrid connection showing as connected.

Tested the WebApp on localhost, it worked fine. Which means nothing wrong with the asp.net code

SSMS on the connection PC can access and query SQL DB

I installed a test SQL DB on the connection PC itself and use the WebApp to talk to the test DB instead, It worked fine.

The Problem

After tested ok on localhost, I published ASP.Net WebApp to Azure, it gave following error:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

troubleshoot attempt

Does that mean Hybrid Connection manager has to be installed on the same computer that runs SQL Server?

I did attempt to install HCM on the SQL Server, but it says it cannot work with Win2008R2. The connection PC has win2012 on it. So it can have HCM.
I just do not have time to migrate the SQL Server to another server. So I hope HCM does not have to be on SQL server.

Connection String

In my webapp, the connection string is as follows.

connectionString="metadata=res:///ScaleDataModel.csdl|res:///ScaleDataModel.ssdl|res://*/ScaleDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=WIN2008R2\DataPlus;initial catalog=DataPlus;persist security info=True;user id=test;password=testpass;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient"

答: Since you have a hybrid connection, your connection string should have the endpoint name of your hybrid connection as the data source. Try replacing it.</p>


问:
Having trouble aligning my dropdown menu without pushing the div content down
```<code><div id="header">
<a href="#" id="logo"></a>

</div>
<div id="nav_cont">
<ul id="nav">
    <li id="main_btn"><a class="mainlink" href="#">Parent 01</a></li>
    <li id="communities_btn"><a class="mainlink" href="#" class="selected">Parent 02</a>
        <ul>
            <li><a href="#">Item 01</a></li>
            <li><a href="#" class="selected">Item 02</a></li>
            <li><a href="#">Item 03</a></li>
        </ul>
        <div class="clear"></div>
    </li>
    <li id="occupancy_btn"><a class="mainlink" href="#">Parent 03</a>
    <ul>
        <li><a href="#">Item 04</a></li>
        <li><a href="#">Item 05</a></li>
        <li><a href="#">Item 06</a></li>
        <li><a href="#">Item 07</a></li>
    </ul>
        <div class="clear"></div>
    </li>
    <li id="resources_btn"><a class="mainlink" href="#">Parent 04</a></li>
    <li id="about_btn"><a class="mainlink" href="#">Parent 04</a></li>
    <li id="newsletter_btn"><a class="mainlink" href="#">Parent 04</a></li>
    <li id="contact_btn"><a class="mainlink" href="#">Parent 04</a></li>

</ul>

<div class="clear"></div>
</div>
<div id="content">

</div>

#header{
border: 0px solid;
width:1024px;
margin: 0 auto;

}
#content{
border: 1px solid;
width:1024px;
height:400px;
margin: 0 auto;

}

#nav_cont{
position: absolute;
top:20px;
border:1px solid;
width:1024px;
left:50%;
margin-left:-512px;
}
</code>```

I'll try to explain the best I can. I have a header div tag that holds the logo. Next, I have the nav_cont that is a menu with hidden drop down menus. Lastly, the rest of the content is in the content div tags.

I've aligned the menu to appear to the user that it is level and within by centering it using absolute, thus not pushing content down when the dropdowns appear.

However when I shrink the browser the nav_cont continues to move off screen even though header and content have stopped. If I use relative or just margin: 0 auto; it minimizes fine, but again my problem is that it pushes the content down when the dropdowns are shown.

I hope im making sense. Thanks.

答: Try setting position:absolute to inner dropdowns, so when you show them does not push content down</p>

Body:
Parent 01

Parent 02

Item 01

Item 02

Item 03

Parent 03

Item 04

Item 05

Item 06

Item 07

Parent 04

Parent 04

Parent 04

Parent 04

#header{
border: 0px solid;
width:1024px;
margin: 0 auto;

}
#content{
border: 1px solid;
width:1024px;
height:400px;
margin: 0 auto;

}

#nav_cont{
position: absolute;
top:20px;
border:1px solid;
width:1024px;
left:50%;
margin-left:-512px;
}

I'll try to explain the best I can. I have a header div tag that holds the logo. Next, I have the nav_cont that is a menu with hidden drop down menus. Lastly, the rest of the content is in the content div tags.

I've aligned the menu to appear to the user that it is level and within by centering it using absolute, thus not pushing content down when the dropdowns appear.

However when I shrink the browser the nav_cont continues to move off screen even though header and content have stopped. If I use relative or just margin: 0 auto; it minimizes fine, but again my problem is that it pushes the content down when the dropdowns are shown.

I hope im making sense. Thanks.


问:
Is it possible to make this PHP code shorter?
I need a help with this code. How can I make it shorter ? I think How can I create an array with name for example errors a modify code without so many If statements. I still can't solve it. I'm a beginner in PHP.

```<code>$error1 = $error2 = $error3 = $error4 = $error5 = $error6 = $error7 = $error8 = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
  $error1 = "fill in fname";
}
if (empty($_POST["lname"])) {
  $error2 = "fill in lname";
}
if (empty($_POST["street"])) {
  $error3 = "fill in street";
}
if (empty($_POST["city"])) {
  $error4 = "fill in city";
}
if (empty($_POST["postcode"])) {
  $error5 = "fill in postcode";
}
if (empty($_POST["country"])) {
  $error6 = "fill in country";
}
if (empty($_POST["email"])) {
  $error7 = "fill in email";
}
if (empty($_POST["phone"])) {
  $error8 = "fill in phone";
}
if (empty($_POST["fname"]) ||
    empty($_POST["lname"]) ||
    empty($_POST["street"]) ||
    empty($_POST["city"]) ||
    empty($_POST["postcode"]) ||
    empty($_POST["country"]) ||
    empty($_POST["email"]) ||
    empty($_POST["phone"])) {
} else {
  $form_items = $_POST;
    $document = new DOMDocument("1.0", "utf-8");
    if (is_file('form_data.xml'))
    {
        $document->load("form_data.xml");
        $xmlko = $document->getElementsByTagName('xml')->item(0);
    }
    else
    {
        $xmlko = $document->createElement("xml");
        $document->appendChild($xmlko);
        $xmlko = $document->getElementsByTagName('xml')->item(0);
    }
            $form = $document->createElement("form");
                $new_user = $document->createElement("user");
                foreach ($form_items as $ite => $val) {
                    $this_user = $document->createElement($ite, $val);
                    $new_user->appendChild($this_user);
                }
               $form->appendChild($new_user);
           $xmlko->appendChild($form);
    $document->save("form_data.xml");

  }
}

?>
</code>```

Here is HTML code. Everything is in one php file.

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>form</title>
    <link rel="stylesheet" href="CSS/styly.css">
  </head>
  <body>
    <h1>FORM</h1>
    <form action="" method="post">
      <p>FName:</p>
      <input type="text" name="fname"/><span class="error"><?php echo $error1?></span>
      <p>LName:</p>
      <input type="text" name="lname"/><span class="error"><?php echo $error2?></span>
      <p>Street:</p>
      <input type="text" name="street"/><span class="error"><?php echo $error3?></span>
      <p>City:</p>
      <input type="text" name="city"/><span class="error"><?php echo $error4?></span>
      <p>Postcode:</p>
      <input type="text" name="postcode"/><span class="error"><?php echo $error5?></span>
      <p>Country:</p>
      <input type="text" name="country"/><span class="error"><?php echo $error6?></span>
      <p>E-mail:</p>
      <input type="text" name="email"/><span class="error"><?php echo $error7?></span>
      <p>Phone:</p>
      <input type="text" name="phone"/><span class="error"><?php echo $error8?></span>
      <input type="submit" value="SUBMIT"/>
    </form>

   <?php

      $document = new DOMDocument("1.0", "utf-8");
      if (is_file('form_data.xml')) {
        $document->load("form_data.xml");
        $users = $document->getElementsByTagName("user");

        echo "<table>";

            echo '<tr>';
            foreach($users->item(0)->childNodes as $data) {
                echo '<th>'.$data->nodeName."</th>";
            }
            echo '</tr>';

            foreach($users as $user){
                echo '<tr>';
                foreach($user->childNodes as $data) {
                    echo '<td>'.$data->nodeValue."</td>";
                }
                echo '</tr>';
            }

        echo "</table>";
      }

   ?>

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

All data from html form are inserted into the table below the form.
Thanks in advance!

答:
This way will check if the post values are set, then you can add a generic error message like some sites do at the bottom of the form.

```<code>if(!isset($_POST['fname'])|| !isset($_POST['lname']) || !isset($_POST['street']) || !isset($_POST['city']) || !isset($_POST['postcode']) || !isset($_POST['country']) || !isset($_POST['email']) || !isset($_POST['email']) || !isset($_POST['phone']){
    $error = "All values must be filled in.";
}
</code>```

HTML

```<code><?php echo $error; ?>
<input type="submit" value="SUBMIT"/>
</code>```

A better way would be to loop through the post array and add all the HTML elements to one post element array:

```<code><input type="text" name="input[]" />
<input type="text" name="input[]" />
</code>```

Body:
I need a help with this code. How can I make it shorter ? I think How can I create an array with name for example errors a modify code without so many If statements. I still can't solve it. I'm a beginner in PHP.

$error1 = $error2 = $error3 = $error4 = $error5 = $error6 = $error7 = $error8 = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
  $error1 = "fill in fname";
}
if (empty($_POST["lname"])) {
  $error2 = "fill in lname";
}
if (empty($_POST["street"])) {
  $error3 = "fill in street";
}
if (empty($_POST["city"])) {
  $error4 = "fill in city";
}
if (empty($_POST["postcode"])) {
  $error5 = "fill in postcode";
}
if (empty($_POST["country"])) {
  $error6 = "fill in country";
}
if (empty($_POST["email"])) {
  $error7 = "fill in email";
}
if (empty($_POST["phone"])) {
  $error8 = "fill in phone";
}
if (empty($_POST["fname"]) ||
    empty($_POST["lname"]) ||
    empty($_POST["street"]) ||
    empty($_POST["city"]) ||
    empty($_POST["postcode"]) ||
    empty($_POST["country"]) ||
    empty($_POST["email"]) ||
    empty($_POST["phone"])) {
} else {
  $form_items = $_POST;
    $document = new DOMDocument("1.0", "utf-8");
    if (is_file('form_data.xml'))
    {
        $document->load("form_data.xml");
        $xmlko = $document->getElementsByTagName('xml')->item(0);
    }
    else
    {
        $xmlko = $document->createElement("xml");
        $document->appendChild($xmlko);
        $xmlko = $document->getElementsByTagName('xml')->item(0);
    }
            $form = $document->createElement("form");
                $new_user = $document->createElement("user");
                foreach ($form_items as $ite => $val) {
                    $this_user = $document->createElement($ite, $val);
                    $new_user->appendChild($this_user);
                }
               $form->appendChild($new_user);
           $xmlko->appendChild($form);
    $document->save("form_data.xml");

  }
}

?>

Here is HTML code. Everything is in one php file.

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>form</title>
    <link rel="stylesheet" href="CSS/styly.css">

FORM

    <form action="" method="post">

FName:

      <input type="text" name="fname"/><?php echo $error1?>

LName:

      <input type="text" name="lname"/><?php echo $error2?>

Street:

      <input type="text" name="street"/><?php echo $error3?>

City:

      <input type="text" name="city"/><?php echo $error4?>

Postcode:

      <input type="text" name="postcode"/><?php echo $error5?>

Country:

      <input type="text" name="country"/><?php echo $error6?>

E-mail:

      <input type="text" name="email"/><?php echo $error7?>

Phone:

      <input type="text" name="phone"/><?php echo $error8?>
      <input type="submit" value="SUBMIT"/>
    </form>

   <?php

      $document = new DOMDocument("1.0", "utf-8");
      if (is_file('form_data.xml')) {
        $document->load("form_data.xml");
        $users = $document->getElementsByTagName("user");

        echo "
";

            echo '
';
            foreach($users->item(0)->childNodes as $data) {
                echo ''.$data->nodeName."	";
            }
            echo '
';

            foreach($users as $user){
                echo '
';
                foreach($user->childNodes as $data) {
                    echo ''.$data->nodeValue."	";
                }
                echo '
';
            }

        echo "
";
      }

   ?>

All data from html form are inserted into the table below the form.
Thanks in advance!

Body:
This way will check if the post values are set, then you can add a generic error message like some sites do at the bottom of the form.

if(!isset($_POST['fname'])|| !isset($_POST['lname']) || !isset($_POST['street']) || !isset($_POST['city']) || !isset($_POST['postcode']) || !isset($_POST['country']) || !isset($_POST['email']) || !isset($_POST['email']) || !isset($_POST['phone']){
    $error = "All values must be filled in.";
}

HTML

<?php echo $error; ?>
<input type="submit" value="SUBMIT"/>

A better way would be to loop through the post array and add all the HTML elements to one post element array:

<input type="text" name="input[]" />
<input type="text" name="input[]" />


问:
Python C API: WindowsError after creating some number of PyObjects
I've been having an issue getting the Python C API to not give me errors.

Background: I've been using ctypes to run native code (C++) for a while, but until now I had never actually done anything specific with the Python C API. I had mostly just been passing in structs from Python and filling them from C++. The way I was using structs was becoming cumbersome, so I decided I would try creating Python objects directly in C++ and just pass them back to my Python script.

Code:
I have a DLL (Foo.dll) with only one function:

```<code>#define N 223
__declspec(dllexport) void Bar(void)
{
    std::cout << "Bar" << std::endl;

    for (int i = 0; i < N; ++i)
    {
        auto list = PyList_New(0);
        std::cout << "Created: " << i << std::endl;
        //Py_DECREF(list);
    }
}
</code>```

And then I have the Python script I'm running:

```<code>import ctypes as C
dll = r"C:\path\to\dll\Foo.dll"
Foo = C.CDLL(dll)
# lists = [[] for _ in range(0)]
Foo.Bar()
print "Done."
</code>```

What happens: If I define N in the above DLL to be 222 or below, the code works fine (except for the memory leak, but that isn't the problem).

If I uncomment the //Py_DECREF(list) line, the code works fine.

However, with the above code, I get this:

```<code>Bar
Created: 0
Created: 1
Created: 2
...(omitted for your sake)
Created: 219
Created: 220
Created: 221
Traceback (most recent call last):
  File "C:\path_to_script\script.py", line 9, in <module>
    Foo.Bar()
WindowsError: exception: access violation reading 0x00000028
</code>```

In fact, I get this same result with dictionaries, lists, tuples and so on. I get the same result if I create a list and then append empty sublists to that list.

What's weirder, every list that I make from within the actual Python script will decrease the number of lists the DLL can make before getting this windows error.

Weirder still, if I make more than 222 lists in my python script, then the DLL won't encounter this error until it's created something like 720 more lists.

**Other details: **

Windows 10

Using the Anaconda2 32-bit Python 2.7 distribution

(Using Python.h and python27.lib from that distribution

python.exe --version: 2.7.13 :: Anaconda custom (32-bit)

Creating DLL with Visual Studio 2017

As long as I don't create many PyObjects from my C++ code, everything seems to work fine. I can pass PyObjects to and from the Python code and it works fine.. until I've created "too many" of the objects from within my C++ code.

What is going on?

答:
From the documentation for CDLL:

The Python global interpreter lock is released before calling any function exported by these libraries, and reacquired afterwards.

This makes it unsafe to use Python C API code. Exactly how it fails is unpredictable, as you are finding. I'd guess it has to do with if the allocation triggers a run of the garbage collector, but I don't think it's worth spending too much time trying to work out the exact cause.

There's (at least) two solutions to chose from:

Use ctypes.PyDLL (which the documentation notes is like CDLL except that it does not release the GIL)

Reacquire the GIL within your C++ code - an easy way to do this is:

```<code>auto state = PyGILState_Ensure();
// C++ code requiring GIL - probably your entire loop
PyGILState_Release(state);
</code>```

Body:
I've been having an issue getting the Python C API to not give me errors.

Background: I've been using ctypes to run native code (C++) for a while, but until now I had never actually done anything specific with the Python C API. I had mostly just been passing in structs from Python and filling them from C++. The way I was using structs was becoming cumbersome, so I decided I would try creating Python objects directly in C++ and just pass them back to my Python script.

Code:
I have a DLL (Foo.dll) with only one function:

#define N 223
__declspec(dllexport) void Bar(void)
{
    std::cout << "Bar" << std::endl;

    for (int i = 0; i < N; ++i)
    {
        auto list = PyList_New(0);
        std::cout << "Created: " << i << std::endl;
        //Py_DECREF(list);
    }
}

And then I have the Python script I'm running:

import ctypes as C
dll = r"C:\path\to\dll\Foo.dll"
Foo = C.CDLL(dll)
# lists = [[] for _ in range(0)]
Foo.Bar()
print "Done."

What happens: If I define N in the above DLL to be 222 or below, the code works fine (except for the memory leak, but that isn't the problem).

If I uncomment the //Py_DECREF(list) line, the code works fine.

However, with the above code, I get this:

Bar
Created: 0
Created: 1
Created: 2
...(omitted for your sake)
Created: 219
Created: 220
Created: 221
Traceback (most recent call last):
  File "C:\path_to_script\script.py", line 9, in <module>
    Foo.Bar()
WindowsError: exception: access violation reading 0x00000028

In fact, I get this same result with dictionaries, lists, tuples and so on. I get the same result if I create a list and then append empty sublists to that list.

What's weirder, every list that I make from within the actual Python script will decrease the number of lists the DLL can make before getting this windows error.

Weirder still, if I make more than 222 lists in my python script, then the DLL won't encounter this error until it's created something like 720 more lists.

**Other details: **

Windows 10

Using the Anaconda2 32-bit Python 2.7 distribution

(Using Python.h and python27.lib from that distribution

python.exe --version: 2.7.13 :: Anaconda custom (32-bit)

Creating DLL with Visual Studio 2017

As long as I don't create many PyObjects from my C++ code, everything seems to work fine. I can pass PyObjects to and from the Python code and it works fine.. until I've created "too many" of the objects from within my C++ code.

What is going on?

Body:
From the documentation for CDLL:

The Python global interpreter lock is released before calling any function exported by these libraries, and reacquired afterwards.

This makes it unsafe to use Python C API code. Exactly how it fails is unpredictable, as you are finding. I'd guess it has to do with if the allocation triggers a run of the garbage collector, but I don't think it's worth spending too much time trying to work out the exact cause.

There's (at least) two solutions to chose from:

Use ctypes.PyDLL (which the documentation notes is like CDLL except that it does not release the GIL)

Reacquire the GIL within your C++ code - an easy way to do this is:

auto state = PyGILState_Ensure();
// C++ code requiring GIL - probably your entire loop
PyGILState_Release(state);


问:
Putting Text on Three Images In A Single Row HTML CSS
I would like to have a single row of three images, with 1 line of text on each, but am unable to find a way to do it. I am reasonably new to HTML and CSS.

Text

Text

Text

```

答:
You should either use background or position: absolute to get your text on top of the images.

Here is an example using background:

.columnContainer {
  display: flex;
  flex-direction: row;
}

.imageContainer {
  flex-basis: 33%;
  text-align: center;
  background: url('http://imgsv.imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg') top no-repeat;
  background-size: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="columnContainer">
  <div class="imageContainer">
    <h4>Text</h4>
  </div>
  <div class="imageContainer">
    <h4>Text</h4>
  </div>
  <div class="imageContainer">
    <h4>Text</h4>
  </div>
</div></code>```

Explanations:

Q: What are we doing?

First, we make our three-column style with display: flex;:

```<code>.columnContainer {
  display: flex;
  flex-direction: row;
}
.imageContainer {
  flex-basis: 33%;
}
</code>```

then, we set the background-image on the div using:

```<code>background: url('http://imgsv.imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg') top no-repeat;
</code>```

next, we tell it to either cover or fill the div with:

```<code>background-size: cover; /*or contain, that's up to you*/
</code>```

Here you go :)

See some references below:

CSS Background - MDN

background-size - MDN

Flexbox, complete guide - CSS Tricks

Body:
You should either use background or position: absolute to get your text on top of the images.

Here is an example using background:

.columnContainer {
  display: flex;
  flex-direction: row;
}

.imageContainer {
  flex-basis: 33%;
  text-align: center;
  background: url('http://imgsv.imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg') top no-repeat;
  background-size: cover;
}

<div class="columnContainer">
  <div class="imageContainer">
    <h4>Text</h4>
  </div>
  <div class="imageContainer">
    <h4>Text</h4>
  </div>
  <div class="imageContainer">
    <h4>Text</h4>
  </div>
</div>

Explanations:

Q: What are we doing?

First, we make our three-column style with display: flex;:

.columnContainer {
  display: flex;
  flex-direction: row;
}
.imageContainer {
  flex-basis: 33%;
}

then, we set the background-image on the div using:

background: url('http://imgsv.imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg') top no-repeat;

next, we tell it to either cover or fill the div with:

background-size: cover; /*or contain, that's up to you*/

Here you go :)

See some references below:

CSS Background - MDN

background-size - MDN

Flexbox, complete guide - CSS Tricks


问:
Angular2/ASP.NET - "No ResourceLoader implementation has been provided. Can't read the URL"
I'm trying to build my own Angular 2/ASP.NET SPA on Visual Studio. You can find all the files here.

What I tried to do is simple: after I followed the instructions to set up the app here, I began to add in my own files in an attempt to do some basic routing and I deleted some superfluous files. I have ClientApp/app/app.module.ts bootstrapping ClientApp/app/components/app/app.component.ts, and the only route is ClientApp/app/components/app/test.component.ts

Unfortunately, I got this error:

```<code>An unhandled exception occurred while processing the request.

Exception: Call to Node module failed with error: Error: No ResourceLoader implementation has been provided. Can't read the url "app.component.html"
at Object.get (C:\Users\Student\Source\Workspaces\mvs\Test2\Test2\node_modules\@angular\compiler\bundles\compiler.umd.js:17454:17)
at DirectiveNormalizer._fetch (C:\Users\Student\Source\Workspaces\mvs\Test2\Test2\node_modules\@angular\compiler\bundles\compiler.umd.js:13455:45)
at DirectiveNormalizer.normalizeTemplateAsync (C:\Users\Student\Source\Workspaces\mvs\Test2\Test2\node_modules\@angular\compiler\bundles\compiler.umd.js:13498:23)
at DirectiveNormalizer.normalizeDirective (C:\Users\Student\Source\Workspaces\mvs\Test2\Test2\node_modules\@angular\compiler\bundles\compiler.umd.js:13473:46)
at RuntimeCompiler._createCompiledTemplate (C:\Users\Student\Source\Workspaces\mvs\Test2\Test2\node_modules\@angular\compiler\bundles\compiler.umd.js:16869:210)
at C:\Users\Student\Source\Workspaces\mvs\Test2\Test2\node_modules\@angular\compiler\bundles\compiler.umd.js:16807:43
at Array.forEach (native)
at C:\Users\Student\Source\Workspaces\mvs\Test2\Test2\node_modules\@angular\compiler\bundles\compiler.umd.js:16805:50
at Array.forEach (native)
at RuntimeCompiler._compileComponents (C:\Users\Student\Source\Workspaces\mvs\Test2\Test2\node_modules\@angular\compiler\bundles\compiler.umd.js:16804:45)
</code>```

Everything looks right to me, but I'm new to both Angular 2 and ASP.NET, so I don't know if it is a compiler issue or human error. Here is some of the code, if you need more information the link to the repo is at the top of this question.

ClientApp/app/app.module.ts

```<code>import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { UniversalModule } from 'angular2-universal';
import { AppComponent } from './components/app/app.component';
import { TestComponent } from './components/app/test.component';

@NgModule({
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        TestComponent
    ],
    imports: [
        UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
        RouterModule.forRoot([
            { path: 'test', component: TestComponent },
            { path: '', redirectTo: 'test', pathMatch: 'full' },
            { path: '**', redirectTo: 'test' }
        ])
    ]
})
export class AppModule {
}
</code>```

ClientApp/app/components/app/app.component.ts

```<code>import { Component, Input } from '@angular/core';

@Component({
    selector: 'app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
}
</code>```

ClientApp/app/components/app/test.component.ts

```<code>import {Component, Input, OnInit} from '@angular/core';

@Component({
    templateUrl: './test.component.html',
    styleUrls: ['./test.component.css']
})

export class TestComponent implements OnInit {
    testing: String;

    ngOnInit(): void {
        this.testing = "This Works";
    }
}
</code>```

答:
This issue occurs from angular2-template-loader with SSR and there are
a couple of reasons why this issue appears:

Important: Check if angular2-template-loader is up to date.

Usually, all the issues are related with @Component.

As Will mentioned - in component name. (this has been fixed)

Comments within @Component

Body:
I'm trying to build my own Angular 2/ASP.NET SPA on Visual Studio. You can find all the files here.

What I tried to do is simple: after I followed the instructions to set up the app here, I began to add in my own files in an attempt to do some basic routing and I deleted some superfluous files. I have ClientApp/app/app.module.ts bootstrapping ClientApp/app/components/app/app.component.ts, and the only route is ClientApp/app/components/app/test.component.ts

Unfortunately, I got this error:

An unhandled exception occurred while processing the request.

Exception: Call to Node module failed with error: Error: No ResourceLoader implementation has been provided. Can't read the url "app.component.html"
at Object.get (C:\Users\Student\Source\Workspaces\mvs\Test2\Test2\node_modules\@angular\compiler\bundles\compiler.umd.js:17454:17)
at DirectiveNormalizer._fetch (C:\Users\Student\Source\Workspaces\mvs\Test2\Test2\node_modules\@angular\compiler\bundles\compiler.umd.js:13455:45)
at DirectiveNormalizer.normalizeTemplateAsync (C:\Users\Student\Source\Workspaces\mvs\Test2\Test2\node_modules\@angular\compiler\bundles\compiler.umd.js:13498:23)
at DirectiveNormalizer.normalizeDirective (C:\Users\Student\Source\Workspaces\mvs\Test2\Test2\node_modules\@angular\compiler\bundles\compiler.umd.js:13473:46)
at RuntimeCompiler._createCompiledTemplate (C:\Users\Student\Source\Workspaces\mvs\Test2\Test2\node_modules\@angular\compiler\bundles\compiler.umd.js:16869:210)
at C:\Users\Student\Source\Workspaces\mvs\Test2\Test2\node_modules\@angular\compiler\bundles\compiler.umd.js:16807:43
at Array.forEach (native)
at C:\Users\Student\Source\Workspaces\mvs\Test2\Test2\node_modules\@angular\compiler\bundles\compiler.umd.js:16805:50
at Array.forEach (native)
at RuntimeCompiler._compileComponents (C:\Users\Student\Source\Workspaces\mvs\Test2\Test2\node_modules\@angular\compiler\bundles\compiler.umd.js:16804:45)

Everything looks right to me, but I'm new to both Angular 2 and ASP.NET, so I don't know if it is a compiler issue or human error. Here is some of the code, if you need more information the link to the repo is at the top of this question.

ClientApp/app/app.module.ts

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { UniversalModule } from 'angular2-universal';
import { AppComponent } from './components/app/app.component';
import { TestComponent } from './components/app/test.component';

@NgModule({
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        TestComponent
    ],
    imports: [
        UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
        RouterModule.forRoot([
            { path: 'test', component: TestComponent },
            { path: '', redirectTo: 'test', pathMatch: 'full' },
            { path: '**', redirectTo: 'test' }
        ])
    ]
})
export class AppModule {
}

ClientApp/app/components/app/app.component.ts

import { Component, Input } from '@angular/core';

@Component({
    selector: 'app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
}

ClientApp/app/components/app/test.component.ts

import {Component, Input, OnInit} from '@angular/core';

@Component({
    templateUrl: './test.component.html',
    styleUrls: ['./test.component.css']
})

export class TestComponent implements OnInit {
    testing: String;

    ngOnInit(): void {
        this.testing = "This Works";
    }
}


问:
How can I find the process id from the service name/handle in Delphi?
I have the service name for a windows service in delphi, and I know how to get the handle from that as well.  What I need to do is stop a service, and if the stop fails for some reason I need to kill the process associated with the service.  The problem is that I have multiple services running from the same executable, so I can't use the executable name to kill the process.  This means I need the process id to kill the proper associated process.  How can I get this id or some way to kill the proper process from the service name or handle?</p>

答:
Or use DSiWin32 for many useful functions, including DSiGetProcessID. This code was written by StackOverflow user (and programmer) Gabr.

Here's the function, for your own reference. It will give you what you are looking for:

```<code>//Retrieves ID of the specified process. Requires Toolhelp API.
//  @returns False if ID cannot be retrieved. Check GetLastError - if it is 0, process
//       doesn't exist; otherwise it contains the Win32 error code.
//  @author  gabr
//  @since   2004-02-12
//
  function DSiGetProcessID(const processName: string; var processID: DWORD): boolean;
  var
    hSnapshot: THandle;
    procEntry: TProcessEntry32;
  begin
    Result := false;
    hSnapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if hSnapshot = 0 then
      Exit;
    try
      procEntry.dwSize := Sizeof(procEntry);
      if not Process32First(hSnapshot, procEntry) then
        Exit;
      repeat
        if AnsiSameText(procEntry.szExeFile, processName) then begin
          processID := procEntry.th32ProcessID;
          Result := true;
          break; // repeat
        end;
      until not Process32Next(hSnapshot, procEntry);
    finally DSiCloseHandleAndNull(hSnapshot); end;
  end; { DSiGetProcessID }
</code>```

OwnerDisplayName: Chris J

Body:
Or use DSiWin32 for many useful functions, including DSiGetProcessID. This code was written by StackOverflow user (and programmer) Gabr.

Here's the function, for your own reference. It will give you what you are looking for:

//Retrieves ID of the specified process. Requires Toolhelp API.
//  @returns False if ID cannot be retrieved. Check GetLastError - if it is 0, process
//       doesn't exist; otherwise it contains the Win32 error code.
//  @author  gabr
//  @since   2004-02-12
//
  function DSiGetProcessID(const processName: string; var processID: DWORD): boolean;
  var
    hSnapshot: THandle;
    procEntry: TProcessEntry32;
  begin
    Result := false;
    hSnapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if hSnapshot = 0 then
      Exit;
    try
      procEntry.dwSize := Sizeof(procEntry);
      if not Process32First(hSnapshot, procEntry) then
        Exit;
      repeat
        if AnsiSameText(procEntry.szExeFile, processName) then begin
          processID := procEntry.th32ProcessID;
          Result := true;
          break; // repeat
        end;
      until not Process32Next(hSnapshot, procEntry);
    finally DSiCloseHandleAndNull(hSnapshot); end;
  end; { DSiGetProcessID }

OwnerDisplayName: Mick