问:
What is preventing me from using $_ in a pipeline?
The command git branch --list | select-string 2362 gives me a list of several branches that fit the pattern 2362.  I want to delete all of those branches on the server.

The command git branch --list | select-string 2362 | git push origin --delete $_ gives me the error fatal: --delete doesn't make sense without any refs, which is the same error I get from the command git push origin --delete.  It is as though $_ is empty, as though there are no branches found which match the pattern.

What am I doing wrong?

答:
You have a couple of issues with what you're trying to do. The git command doesn't accept pipeline input (as far as I know) because its not a PowerShell cmdlet.

Also Select-String returns a MatchInfo object, so $_ wouldn't contain just the name of the branches, but this object with its various properties.

Try this:

```<code>(git branch --list | select-string 2362).line | ForEach-Object {
    git push origin --delete $_
}
</code>```

Beware though that you might get a * character in one of the branch names if its the current branch.

Body:
You have a couple of issues with what you're trying to do. The git command doesn't accept pipeline input (as far as I know) because its not a PowerShell cmdlet.

Also Select-String returns a MatchInfo object, so $_ wouldn't contain just the name of the branches, but this object with its various properties.

Try this:

(git branch --list | select-string 2362).line | ForEach-Object {
    git push origin --delete $_
}

Beware though that you might get a * character in one of the branch names if its the current branch.


来源: stackexchange

问:
Pyomo: is possible to assign to a design variable only defined values?
I want that a design variable assumes only specified values during optimization process.

For example:
Let x be the variable which can assume only specific value, e.g.:

x = [0.1,0.5,1.0,1.7,2.3]
```

How can be written in python using pyomo (if it's possible)?

I hope I was clear.

答:
You have to do this with integer variables. For example, if there are N possible values of x, then let x[n] = 1 if x equals the nth possible value, and 0 otherwise. Any time you have an x in your original model, replace it with

```<code>sum {n=1,...,N} v[n] * x[n]
</code>```

where v[n] is the nth possible value. Finally, add a constraint that says:

```<code>sum {n=1,...,N} x[n] == 1
</code>```

I'm not writing these in Pyomo syntax, but this is a general modeling approach that is the same no matter what modeling language/package you use.

ContentLicense: CC BY-SA 4.0

Body:
I want that a design variable assumes only specified values during optimization process.

For example:
Let x be the variable which can assume only specific value, e.g.:

x = [0.1,0.5,1.0,1.7,2.3]

How can be written in python using pyomo (if it's possible)?

I hope I was clear.

Body:
You have to do this with integer variables. For example, if there are N possible values of x, then let x[n] = 1 if x equals the nth possible value, and 0 otherwise. Any time you have an x in your original model, replace it with

sum {n=1,...,N} v[n] * x[n]

where v[n] is the nth possible value. Finally, add a constraint that says:

sum {n=1,...,N} x[n] == 1

I'm not writing these in Pyomo syntax, but this is a general modeling approach that is the same no matter what modeling language/package you use.


问:
jQuery regular expression for decimal [17, 2]
I'd like to check number what it is decimal [17, 2] (0~17 and 0~2).

What is the regular expression for a decimal [17,2]?

For example

```<code>1
0.01
0.1
12345678901234567.01
...
</code>```

I used var regexp = /^\d+(?:\.\d\d?)?$/; but it can be over 17.

答:
Indeed, your regex doesn't include the 17 limit anywhere.

The regex for "0 to 17 digits" will be:

```<code>\d{0,17}
</code>```

You can read more on repetitions here: https://www.regular-expressions.info/repeat.html

Body:
I'd like to check number what it is decimal [17, 2] (0~17 and 0~2).

What is the regular expression for a decimal [17,2]?

For example

1
0.01
0.1
12345678901234567.01
...

I used var regexp = /^\d+(?:\.\d\d?)?$/; but it can be over 17.

Body:
Indeed, your regex doesn't include the 17 limit anywhere.

The regex for "0 to 17 digits" will be:

\d{0,17}

You can read more on repetitions here: https://www.regular-expressions.info/repeat.html


问:
Clone GitHub repository in VSCode
I'm trying to clone a GitHub repository into the newest release of VSCode (1.3.0). Can this be done natively or do I need to add an extension or additional binary?

I've also searched for a blog article and coming up empty handed so any guidance would be appreciated

Paul

答: I use github Desktop (https://desktop.github.com/) for both my github repos and gitlab repos</p>

ContentLicense: CC BY-SA 3.0

Title: Clone GitHub repository in VSCode


问:
Front controller object in zend framewok
What is diff. between below objects of front controller and how to use it?

```<code>$this->bootstrap('frontController');
    $frontController = $this->getResource('frontController');

    $front = Zend_Controller_Front::getInstance();
</code>```

What is diff. between these two objects of front controller?

答:
Both

```<code>$frontController = $this->getResource('frontController');
</code>```

and

```<code>$front = Zend_Controller_Front::getInstance();
</code>```

will return the same instance of Zend_Controller_Front. Its a singleton, so by definition there can only be one instance of that object. The difference is when you execute

```<code>$this->bootstrap('frontController');
</code>```

you are insuring that the bootstrap has executed the front controller resource, Zend_Application_Resource_Frontcontroller by default.

IMO, use the first example in your bootstraps and resources, use the latter everywhere else. They both get you the same instance of the front controller, the only benefit to the first example is that lets the bootstrap know that the front controller is a dependency.

Body:
What is diff. between below objects of front controller and how to use it?

$this->bootstrap('frontController');
    $frontController = $this->getResource('frontController');

    $front = Zend_Controller_Front::getInstance();

What is diff. between these two objects of front controller?

Body:
Both

$frontController = $this->getResource('frontController');

and

$front = Zend_Controller_Front::getInstance();

will return the same instance of Zend_Controller_Front. Its a singleton, so by definition there can only be one instance of that object. The difference is when you execute

$this->bootstrap('frontController');

you are insuring that the bootstrap has executed the front controller resource, Zend_Application_Resource_Frontcontroller by default.

IMO, use the first example in your bootstraps and resources, use the latter everywhere else. They both get you the same instance of the front controller, the only benefit to the first example is that lets the bootstrap know that the front controller is a dependency.


问:
How to populate 2 selects based on first select option using API data - ReactJS
I have a task with 3 selects, where first select need to be name of an user, and when user is selected, next two selects get options about selected user.

I am new to React and I am not sure how to do this. There is a code of what i have tried so far.

Is there a simple way to complete this task by not using Redux for React? Thank you in advance!

class Users extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoading: true,
            contacts: [],
            country: []
        }
    }

    componentDidMount() {
        this.fetchData();
    }

    fetchData() {
        fetch('https://jsonplaceholder.typicode.com/users')
            .then(response => response.json())
            .then(parsedJSON => parsedJSON.map(user => (
                {
                    name: `${user.name}`,
                    username: `${user.username}`,
                    email: `${user.email}`
                }
            )))
            .then(contacts => this.setState({
                contacts,
                isLoading: false
            }))
            .catch(error => console.log('error is: ', error))
    }

    render() {
        const {contacts} = this.state;
        return (

                        <select name="" id="" onChange={this.onChangeHandler}>
                            {
                                this.state.contacts.map(contact => {
                                    const { email, name } = contact;
                                    return <option key={email} value={name}>{name}</option>
                                })
                            }
                        </select>

                            {/* this is where filtered data render */}

        )
    }
}

ReactDOM.render(<App />, document.getElementById('app'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div></code>```

答:
This is fairly easy you just have to find the selected user among
  all contacts and maintain the selected User

```<code>class Users extends Component {
   constructor() {
      super();
      this.state = {
         isLoading: true,
         contacts: [],
         country: [],
         selectedUser: {}
      };
   }

   componentDidMount() {
      fetch("https://jsonplaceholder.typicode.com/users")
         .then(response => response.json())
         .then(parsedJSON =>
            parsedJSON.map(user => ({
               name: `${user.name}`,
               username: `${user.username}`,
               email: `${user.email}`
            }))
         )
         .then(contacts =>
            this.setState({
               contacts,
               isLoading: false
            })
         )
         .catch(error => console.log("error is: ", error));
   }

   onChangeHandler = e => {
      // get selected user
      const selectedName = e.target.value;
      // search it in existing contacts
      const selectedUser = this.state.contacts.find(user =>  user.name === selectedName);
      // if user found then maintain it as selected user
      if (!!selectedUser) {
         this.setState({
            selectedUser
         });
      }
   };

   render() {
      const { contacts, selectedUser, isLoading } = this.state;

      return (
         <div>
            {/* if all users all loaded */
            !isLoading && (
               <div className="container">
                  <div className="row">
                     <div className="filter-container col-6 mt-5">
                        <select name="" id="" onChange={this.onChangeHandler}>
                           {this.state.contacts.map(contact => {
                              const { email, name } = contact;
                              return (
                                 <option key={email} value={name}>
                                    {name}
                                 </option>
                              );
                           })}
                        </select>
                     </div>
                     <div className="filter-results col-6">
                        <p>
                           {/* this is where filtered data render */}
                           {Object.keys(selectedUser).length > 0 && (
                              ```

Filtred Data :

                                 Name: {selectedUser.name}

                                 UserName: {selectedUser.username}

                                 Email: {selectedUser.email}
                              ```
                           )}
                        </p>
                     </div>
                  </div>
               </div>
            )}
         </div>
      );
   }
}

ReactDOM.render(<App />, document.getElementById("app"));
</code>```

Code snippet https://stackblitz.com/edit/react-filtering-users

I hope this work you!!

Body:
This is fairly easy you just have to find the selected user among
  all contacts and maintain the selected User

class Users extends Component {
   constructor() {
      super();
      this.state = {
         isLoading: true,
         contacts: [],
         country: [],
         selectedUser: {}
      };
   }

   componentDidMount() {
      fetch("https://jsonplaceholder.typicode.com/users")
         .then(response => response.json())
         .then(parsedJSON =>
            parsedJSON.map(user => ({
               name: `${user.name}`,
               username: `${user.username}`,
               email: `${user.email}`
            }))
         )
         .then(contacts =>
            this.setState({
               contacts,
               isLoading: false
            })
         )
         .catch(error => console.log("error is: ", error));
   }

   onChangeHandler = e => {
      // get selected user
      const selectedName = e.target.value;
      // search it in existing contacts
      const selectedUser = this.state.contacts.find(user =>  user.name === selectedName);
      // if user found then maintain it as selected user
      if (!!selectedUser) {
         this.setState({
            selectedUser
         });
      }
   };

   render() {
      const { contacts, selectedUser, isLoading } = this.state;

      return (
         <div>
            {/* if all users all loaded */
            !isLoading && (
               <div className="container">
                  <div className="row">
                     <div className="filter-container col-6 mt-5">
                        <select name="" id="" onChange={this.onChangeHandler}>
                           {this.state.contacts.map(contact => {
                              const { email, name } = contact;
                              return (
                                 <option key={email} value={name}>
                                    {name}
                                 </option>
                              );
                           })}
                        </select>
                     </div>
                     <div className="filter-results col-6">
                        <p>
                           {/* this is where filtered data render */}
                           {Object.keys(selectedUser).length > 0 && (
                              <pre>
                                 <h3>Filtred Data :</h3>
                                 <span>Name: {selectedUser.name}</span>
                                 <br />
                                 <span>UserName: {selectedUser.username}
                                  </span>
                                 <br />
                                 <span>Email: {selectedUser.email}</span>
                              </pre>
                           )}
                        </p>
                     </div>
                  </div>
               </div>
            )}
         </div>
      );
   }
}

ReactDOM.render(<App />, document.getElementById("app"));

Code snippet https://stackblitz.com/edit/react-filtering-users

I hope this work you!!


问:
Custom object select field in Salesforce web-to-lead form
I have a custom object in salesforce called Classes and I am using the Leads object for storing student information. I have a web-to-lead form for capturing student registrations, but I would like to have the students select which class they are registering for, from a dropdown select field.

Is that possible using the web-to-lead form, or do I have to create a custom one with SQL queries?

Thanks in advance.

答:
What's the relation between the two? Simple lookup from Lead to Class? In theory it should be many-to-many, with junction object.

From what I remember custom lookups from lead aren't available in the W2L form. Only Campaign is. And it renders to similar HTML:

Campaign<select  id="Campaign_ID" name="Campaign_ID"><option value="">--None--</option><option value="701700000005lMn">International Electrical Engineers Association Trade Show - Mar 4-5, 2002</option>
<option value="701700000005lMl">User Conference - Jun 17-19, 2002</option>
<option value="701700000005lMk">GC Product Webinar - Jan 7, 2002</option>
<option value="701700000005lMm">DM Campaign to Top Customers - Nov 12-23, 2001</option>
</select>

```

So perhaps you could fake it, hand-craft similar HTML, point to your custom field, put right record ids in the options... Messy. Or consider displaying Campaigns & Campaign member stuff and then have something else (process builder? trigger?) that maps it from campaign to class.

If you have many-to-many or don't really like such workarounds - yup, looks like some code needed. Perhaps expose a Visualforce page as Site for signing up. Or - for non-technical people - Site.com might be tempting. https://salesforce.stackexchange.com/questions/23252/difference-between-force-com-site-and-site-com

Body:
What's the relation between the two? Simple lookup from Lead to Class? In theory it should be many-to-many, with junction object.

From what I remember custom lookups from lead aren't available in the W2L form. Only Campaign is. And it renders to similar HTML:

<label for="Campaign_ID">Campaign</label><select  id="Campaign_ID" name="Campaign_ID"><option value="">--None--</option><option value="701700000005lMn">International Electrical Engineers Association Trade Show - Mar 4-5, 2002</option>
<option value="701700000005lMl">User Conference - Jun 17-19, 2002</option>
<option value="701700000005lMk">GC Product Webinar - Jan 7, 2002</option>
<option value="701700000005lMm">DM Campaign to Top Customers - Nov 12-23, 2001</option>
</select><br>

So perhaps you could fake it, hand-craft similar HTML, point to your custom field, put right record ids in the options... Messy. Or consider displaying Campaigns & Campaign member stuff and then have something else (process builder? trigger?) that maps it from campaign to class.

If you have many-to-many or don't really like such workarounds - yup, looks like some code needed. Perhaps expose a Visualforce page as Site for signing up. Or - for non-technical people - Site.com might be tempting. https://salesforce.stackexchange.com/questions/23252/difference-between-force-com-site-and-site-com


问:
Will full memory barriers around std::shared_ptr's use_count() make it a reliable counter?
I'm implementing a thread-safe "lazy-synchronized" Set as a linked list of nodes connected by shared_ptr's. The algorithm is from "The Art of Multiprocessor Programming". I'm adding an is_empty() function that needs to be linearizable with the existing functions: contains(), add(), remove(). In the code below, you can see  remove  is a 2 step process. First it "lazy" marks the node by setting marked = nullptr, then it physically moves the linked list next pointers.

Modified classes to support is_empty()

template <class T>
class LazySet : public Set<T> {
    public:
      LazySet ();
      bool contains (const T&) const;
      bool is_empty ()         const;
      bool add      (const T&);
      bool remove   (const T&);
    private:
      bool validate(const std::shared_ptr<Node>&, const std::shared_ptr<Node>&);
      class Node;
      std::shared_ptr<Node> head;
      std::shared_ptr<bool> counter; //note: type is unimportant, will never change true/fase
};

template <class T>
class LazySet<T>::Node {
    public:
      Node ();
      Node (const T&);
      T key;
      std::shared_ptr<bool> marked; //assume initialized to = LazySet.counter
                                    // nullptr means it's marked; otherwise unmarked
      std::shared_ptr<Node> next;
      std::mutex mtx;
};
```

<p>Relevant modified methods to support is_empty</p>

<pre class="lang-cpp prettyprint-override"><code>template <class T>
bool LazySet<T>::remove(const T& k) {
    std::shared_ptr<Node> pred;
    std::shared_ptr<Node> curr;
    while (true) {
        pred = head;
        curr = atomic_load(&(head->next));
        //Find window where key should be in sorted list
        while ((curr) && (curr->key < k)) {
            pred = atomic_load(&curr);
            curr = atomic_load(&(curr->next));
        }
        //Aquire locks on the window, left to right locking prevents deadlock
        (pred->mtx).lock();
        if (curr) { //only lock if not nullptr
            (curr->mtx).lock();
        }
        //Ensure window didn't change before locking, and then remove
        if (validate(pred, curr)) {
            if (!curr) { //key doesn't exist, do nothing
                //## unimportant ##
            } else { //key exists, remove it
                atomic_store(&(curr->marked), nullptr); //logical "lazy" remove
                atomic_store(&(pred->next), curr->next) //physically remove
                (curr->mtx).unlock();
                (pred->mtx).unlock();
                return true;
            }
        } else {
            //## unlock and loop again ##
        }
    }
}

template <class T>
bool LazySet<T>::contains(const T& k) const {
    std::shared_ptr<Node> curr;
    curr = atomic_load(&(head->next));
    //Find window where key should be in sorted list
    while ((curr) && (curr->key < k)) {
        curr = atomic_load(&(curr->next));
    }
    //Check if key exists in window
    if (curr) {
        if (curr->key == k) { //key exists, unless marked
            return (atomic_load(&(curr->marked)) != nullptr);
        } else { //doesn't exist
            return false;
        }
    } else { //doesn't exist
        return false;
    }
}
</code>```

Node.marked was originally a plain bool, and LazySet.counter didn't exist. The choice to make them shared_ptrs was to be able to be able to atomically modify both a counter on the number of nodes and the lazy removal mark on the nodes. Modifying both simultaneously in remove() is necessary for is_empty() to be linearizable with contains(). (It can't be a separate bool mark and int counter without a double wide CAS or something.) I hope to implement the counter with shared_ptr's  use_count() function, but in multithreaded contexts it's only an approximation due to relaxed_memory_order.

I know standalone fences are usually bad practice, and I'm not too familiar with using them. But if I implemented is_empty like below, would the fences ensure it's no longer an approximation, but an exact value for a reliable counter?

template <class T>
bool LazySet<T>::is_empty() const {
    // ## SOME FULL MEMORY BARRIER
    if (counter.use_count() == 1) {
        // ## SOME FULL MEMORY BARRIER
        return true
    }
    // ## SOME FULL MEMORY BARRIER
    return false
}
```

I only ask because LWG Issue 2776 says:

We can't make  use_count()  reliable without adding substantially more fencing.

答:
```<code>// ## SOME FULL MEMORY BARRIER
if (counter.use_count() == 1) {
    // ## SOME FULL MEMORY BARRIER
</code>```

With an acquire fence before, you can make sure you can make sure you "see" the results of all the resets (including during assignment and destruction) of all owners in other threads. The acquire fence gives all following relaxed operation acquire semantics, preventing them from "fetching values in the future" (which is semantic insanity in any case and probably makes all programs formally UB).

(There is no meaningful fence that you could put after the call.)

Body:
I'm implementing a thread-safe "lazy-synchronized" Set as a linked list of nodes connected by shared_ptr's. The algorithm is from "The Art of Multiprocessor Programming". I'm adding an is_empty() function that needs to be linearizable with the existing functions: contains(), add(), remove(). In the code below, you can see  remove  is a 2 step process. First it "lazy" marks the node by setting marked = nullptr, then it physically moves the linked list next pointers.

Modified classes to support is_empty()

template <class T>
class LazySet : public Set<T> {
    public:
      LazySet ();
      bool contains (const T&) const;
      bool is_empty ()         const;
      bool add      (const T&);
      bool remove   (const T&);
    private:
      bool validate(const std::shared_ptr<Node>&, const std::shared_ptr<Node>&);
      class Node;
      std::shared_ptr<Node> head;
      std::shared_ptr<bool> counter; //note: type is unimportant, will never change true/fase
};

template <class T>
class LazySet<T>::Node {
    public:
      Node ();
      Node (const T&);
      T key;
      std::shared_ptr<bool> marked; //assume initialized to = LazySet.counter
                                    // nullptr means it's marked; otherwise unmarked
      std::shared_ptr<Node> next;
      std::mutex mtx;
};

Relevant modified methods to support is_empty

template <class T>
bool LazySet<T>::remove(const T& k) {
    std::shared_ptr<Node> pred;
    std::shared_ptr<Node> curr;
    while (true) {
        pred = head;
        curr = atomic_load(&(head->next));
        //Find window where key should be in sorted list
        while ((curr) && (curr->key < k)) {
            pred = atomic_load(&curr);
            curr = atomic_load(&(curr->next));
        }
        //Aquire locks on the window, left to right locking prevents deadlock
        (pred->mtx).lock();
        if (curr) { //only lock if not nullptr
            (curr->mtx).lock();
        }
        //Ensure window didn't change before locking, and then remove
        if (validate(pred, curr)) {
            if (!curr) { //key doesn't exist, do nothing
                //## unimportant ##
            } else { //key exists, remove it
                atomic_store(&(curr->marked), nullptr); //logical "lazy" remove
                atomic_store(&(pred->next), curr->next) //physically remove
                (curr->mtx).unlock();
                (pred->mtx).unlock();
                return true;
            }
        } else {
            //## unlock and loop again ##
        }
    }
}

template <class T>
bool LazySet<T>::contains(const T& k) const {
    std::shared_ptr<Node> curr;
    curr = atomic_load(&(head->next));
    //Find window where key should be in sorted list
    while ((curr) && (curr->key < k)) {
        curr = atomic_load(&(curr->next));
    }
    //Check if key exists in window
    if (curr) {
        if (curr->key == k) { //key exists, unless marked
            return (atomic_load(&(curr->marked)) != nullptr);
        } else { //doesn't exist
            return false;
        }
    } else { //doesn't exist
        return false;
    }
}

Node.marked was originally a plain bool, and LazySet.counter didn't exist. The choice to make them shared_ptrs was to be able to be able to atomically modify both a counter on the number of nodes and the lazy removal mark on the nodes. Modifying both simultaneously in remove() is necessary for is_empty() to be linearizable with contains(). (It can't be a separate bool mark and int counter without a double wide CAS or something.) I hope to implement the counter with shared_ptr's  use_count() function, but in multithreaded contexts it's only an approximation due to relaxed_memory_order.

I know standalone fences are usually bad practice, and I'm not too familiar with using them. But if I implemented is_empty like below, would the fences ensure it's no longer an approximation, but an exact value for a reliable counter?

template <class T>
bool LazySet<T>::is_empty() const {
    // ## SOME FULL MEMORY BARRIER
    if (counter.use_count() == 1) {
        // ## SOME FULL MEMORY BARRIER
        return true
    }
    // ## SOME FULL MEMORY BARRIER
    return false
}

I only ask because LWG Issue 2776 says:

We can't make  use_count()  reliable without adding substantially more fencing.

Body:
// ## SOME FULL MEMORY BARRIER
if (counter.use_count() == 1) {
    // ## SOME FULL MEMORY BARRIER

With an acquire fence before, you can make sure you can make sure you "see" the results of all the resets (including during assignment and destruction) of all owners in other threads. The acquire fence gives all following relaxed operation acquire semantics, preventing them from "fetching values in the future" (which is semantic insanity in any case and probably makes all programs formally UB).

(There is no meaningful fence that you could put after the call.)


问:
Why are my user-settings not persisted after calling Properties.Settings.Default.Saved()?
This is just for demo purposes. I will not actually cache passwords this way as I've received advice that Application Settings is not secure.

Problem Statement

I'm creating a login Windows Forms application that persists the string values entered into the Name and Password fields between application sessions using Application Settings. The form should load the Name and Password values that was entered from the previous session.

I ran into a problem where the fields fail to get saved and reloaded if I use Properties.Settings.Default.Save() to save those field values from a private method:

```<code>    // Save the current values of each field
    private void SaveSettings()
    {
        Properties.Settings.Default.Name = textBox1.Text;
        Properties.Settings.Default.Password = textBox2.Text;
        Properties.Settings.Default.Save();
    }
</code>```

When the field values change, this is how `SaveSettings() would be called:

```<code>    // Saves ALL field values in the form whenever the field changes.
    // Warning: This function gets called each time a character is added to the 'Name' field.
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        SaveSettings();
        UpdateRichTextbox();
    }

    // Saves ALL field values in the form whenever the field changes.
    // Warning: This function gets called each time a character is added to the 'Password' field.
    private void textBox2_TextChanged(object sender, EventArgs e)
    {
        SaveSettings();
        UpdateRichTextbox();
    }
</code>```

UpdateRichTextbox() simply writes Name and Password to a rich text box in a formatted manner so that I can see their values:

```<code>    // Writes current values of each setting to Rich Textbox
    private void UpdateRichTextbox()
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendLine($"Name: {Properties.Settings.Default.Name}");
        sb.AppendLine($"Password: {Properties.Settings.Default.Password}");
        richTextBox1.Text = sb.ToString();
    }
</code>```

Attempt

I made sure to set the scope for both Name and Password setting in Project Settings to 'User'. I tried calling Properties.Settings.Default.Upgrade() after .Save().

Name and Password persisted when I moved the content of SaveSettings() to the callbacks invoked when those fields are changed:

```<code>    // Saves ALL field values in the form whenever the field changes.
    // Warning: This function gets called each time a character is added to the 'Name' field.
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        Properties.Settings.Default.Name = textBox1.Text;
        Properties.Settings.Default.Save();
        UpdateRichTextbox();
    }

    // Saves ALL field values in the form whenever the field changes.
    // Warning: This function gets called each time a character is added to the 'Password' field.
    private void textBox2_TextChanged(object sender, EventArgs e)
    {
        Properties.Settings.Default.Password = textBox2.Text;
        Properties.Settings.Default.Save();
        UpdateRichTextbox();
    }
</code>```

I'm not sure why my first approach didn't work. How did the API devs intend for .Save() to be used?

Full Example

```<code>using System;
using System.Text;
using System.Windows.Forms;

namespace LoginForm
{
    public partial class Form1 : Form
    {
        // Called initially when the form application starts up
        public Form1()
        {
            InitializeComponent();
            LoadSettings();
        }

        // Load saved values to their respective field textboxes
        private void LoadSettings()
        {
            textBox1.Text = Properties.Settings.Default.Name;
            textBox2.Text = Properties.Settings.Default.Password;
        }

        // Writes current values of each setting to Rich Textbox
        private void UpdateRichTextbox()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"Name: {Properties.Settings.Default.Name}");
            sb.AppendLine($"Password: {Properties.Settings.Default.Password}");
            richTextBox1.Text = sb.ToString();
        }

        // Saves ALL field values in the form whenever the field changes.
        // Warning: This function gets called each time a character is added to the 'Name' field.
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.Name = textBox1.Text;
            Properties.Settings.Default.Save();
            UpdateRichTextbox();
        }

        // Saves ALL field values in the form whenever the field changes.
        // Warning: This function gets called each time a character is added to the 'Password' field.
        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.Password = textBox2.Text;
            Properties.Settings.Default.Save();
            UpdateRichTextbox();
        }
    }
}
</code>```

答:
When the application restarts, Form1() calls LoadSettings() which, when executing textBox1.Text = Properties.Settings.Default.Name, modifies the textBox1.Text property causing the textBox1_TextChanged handler to run. That handler function calls SaveSettings() which then overwrites what had previously been stored in Properties.Settings.Default.Password using what's currently in the textBox2.Text field. Because the application had restarted, textBox2.Text is empty and thus the old value of Properties.Settings.Default.Password was overwritten with an empty string.

Thank you Jimi for helping me locate the user.config file and for his sage advice on what not to do in a textChanged event. I can't see a good reason why you'd need to do something every time a character changes in your textBox either -- makes sense why most applications use an Apply or Save button. Seeing this file change as I step-debugged helped me identify the problem with my code.

Body:
This is just for demo purposes. I will not actually cache passwords this way as I've received advice that Application Settings is not secure.

Problem Statement

I'm creating a login Windows Forms application that persists the string values entered into the Name and Password fields between application sessions using Application Settings. The form should load the Name and Password values that was entered from the previous session.

I ran into a problem where the fields fail to get saved and reloaded if I use Properties.Settings.Default.Save() to save those field values from a private method:

    // Save the current values of each field
    private void SaveSettings()
    {
        Properties.Settings.Default.Name = textBox1.Text;
        Properties.Settings.Default.Password = textBox2.Text;
        Properties.Settings.Default.Save();
    }

When the field values change, this is how `SaveSettings() would be called:

    // Saves ALL field values in the form whenever the field changes.
    // Warning: This function gets called each time a character is added to the 'Name' field.
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        SaveSettings();
        UpdateRichTextbox();
    }

    // Saves ALL field values in the form whenever the field changes.
    // Warning: This function gets called each time a character is added to the 'Password' field.
    private void textBox2_TextChanged(object sender, EventArgs e)
    {
        SaveSettings();
        UpdateRichTextbox();
    }

UpdateRichTextbox() simply writes Name and Password to a rich text box in a formatted manner so that I can see their values:

    // Writes current values of each setting to Rich Textbox
    private void UpdateRichTextbox()
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendLine($"Name: {Properties.Settings.Default.Name}");
        sb.AppendLine($"Password: {Properties.Settings.Default.Password}");
        richTextBox1.Text = sb.ToString();
    }

Attempt

I made sure to set the scope for both Name and Password setting in Project Settings to 'User'. I tried calling Properties.Settings.Default.Upgrade() after .Save().

Name and Password persisted when I moved the content of SaveSettings() to the callbacks invoked when those fields are changed:

    // Saves ALL field values in the form whenever the field changes.
    // Warning: This function gets called each time a character is added to the 'Name' field.
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        Properties.Settings.Default.Name = textBox1.Text;
        Properties.Settings.Default.Save();
        UpdateRichTextbox();
    }

    // Saves ALL field values in the form whenever the field changes.
    // Warning: This function gets called each time a character is added to the 'Password' field.
    private void textBox2_TextChanged(object sender, EventArgs e)
    {
        Properties.Settings.Default.Password = textBox2.Text;
        Properties.Settings.Default.Save();
        UpdateRichTextbox();
    }

I'm not sure why my first approach didn't work. How did the API devs intend for .Save() to be used?

Full Example

using System;
using System.Text;
using System.Windows.Forms;

namespace LoginForm
{
    public partial class Form1 : Form
    {
        // Called initially when the form application starts up
        public Form1()
        {
            InitializeComponent();
            LoadSettings();
        }

        // Load saved values to their respective field textboxes
        private void LoadSettings()
        {
            textBox1.Text = Properties.Settings.Default.Name;
            textBox2.Text = Properties.Settings.Default.Password;
        }

        // Writes current values of each setting to Rich Textbox
        private void UpdateRichTextbox()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"Name: {Properties.Settings.Default.Name}");
            sb.AppendLine($"Password: {Properties.Settings.Default.Password}");
            richTextBox1.Text = sb.ToString();
        }

        // Saves ALL field values in the form whenever the field changes.
        // Warning: This function gets called each time a character is added to the 'Name' field.
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.Name = textBox1.Text;
            Properties.Settings.Default.Save();
            UpdateRichTextbox();
        }

        // Saves ALL field values in the form whenever the field changes.
        // Warning: This function gets called each time a character is added to the 'Password' field.
        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.Password = textBox2.Text;
            Properties.Settings.Default.Save();
            UpdateRichTextbox();
        }
    }
}


问:
“How to fix the 'div panel' in either CSS or JavaScript from closing
This is regarding a FAQ-page;

I've tested some code, when one div is active it doesn't automatically close when I click on another div, I do have - and + signs but when a user goes to another .div tab the previous one needs to be closed automatically;

I've tried adding a lot of CSS code but I think, that they get overwritten with the JavaScript, I have not made the JavaScript, but tried to debug it and simply my knowledge is really basic compared to HTML and CSS, been troubleshooting this for two days now, thanks in advance!

Below is the code:

  var acc = document.getElementsByClassName("accordion");
                var i;

                for (i = 0; i < acc.length; i++) {
                    acc[i].onclick = function () {
                        this.classList.toggle("active");
                        var panel = this.nextElementSibling;
                        if (panel.style.maxHeight) {
                            panel.style.maxHeight = null;
                        } else {
                            panel.style.maxHeight = panel.scrollHeight + "px";
                        }
                    }
                }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>     button.accordion {
                    background-color: #eee;
                    color: #444;
                    cursor: pointer;
                    padding: 18px;
                    width: 100%;
                    border: none;
                    text-align: left;
                    outline: none;
                    font-size: 17px;
                    transition: 0.4s;
                }

                button.accordion.active,
                button.accordion:hover {
                    background-color: #ccc;
                }

                button.accordion:after {

                    content: '\002B';
                    color: #777;
                    font-weight: bold;
                    float: right;
                    margin-left: 10px;
                }

                button.accordion.active:after {
                    content: "\2212";
                }

                div.panel {
                    padding: 0 18px;
                    background-color: white;
                    max-height: 0;
                    overflow: hidden;
                    transition: max-height 0.2s ease-out;
                }</code>```

Title

        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Esse nobis natus, laboriosam, aperiam alias enim, atque accusantium autem saepe id molestiae animi! Soluta laudantium eaque aspernatur maxime et aut, consequuntur.

```

答:
Seeing what your description code looks like would be helpful - but if it's using accordion and active classes, this might work:

```<code>$(document).on('click', '.accordion', () => {
  $('.accordion').removeClass('active');
  $(this).addClass('active');
});
</code>```

When .accordion is clicked, it removes all .active classes from all accordions and then adds it back in on the one you clicked.

Body:
This is regarding a FAQ-page;

I've tested some code, when one div is active it doesn't automatically close when I click on another div, I do have - and + signs but when a user goes to another .div tab the previous one needs to be closed automatically;

I've tried adding a lot of CSS code but I think, that they get overwritten with the JavaScript, I have not made the JavaScript, but tried to debug it and simply my knowledge is really basic compared to HTML and CSS, been troubleshooting this for two days now, thanks in advance!

Below is the code:

  var acc = document.getElementsByClassName("accordion");
                var i;

                for (i = 0; i < acc.length; i++) {
                    acc[i].onclick = function () {
                        this.classList.toggle("active");
                        var panel = this.nextElementSibling;
                        if (panel.style.maxHeight) {
                            panel.style.maxHeight = null;
                        } else {
                            panel.style.maxHeight = panel.scrollHeight + "px";
                        }
                    }
                }

     button.accordion {
                    background-color: #eee;
                    color: #444;
                    cursor: pointer;
                    padding: 18px;
                    width: 100%;
                    border: none;
                    text-align: left;
                    outline: none;
                    font-size: 17px;
                    transition: 0.4s;
                }

                button.accordion.active,
                button.accordion:hover {
                    background-color: #ccc;
                }

                button.accordion:after {

                    content: '\002B';
                    color: #777;
                    font-weight: bold;
                    float: right;
                    margin-left: 10px;
                }

                button.accordion.active:after {
                    content: "\2212";
                }

                div.panel {
                    padding: 0 18px;
                    background-color: white;
                    max-height: 0;
                    overflow: hidden;
                    transition: max-height 0.2s ease-out;
                }

Title

        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Esse nobis natus, laboriosam, aperiam alias enim, atque accusantium autem saepe id molestiae animi! Soluta laudantium eaque aspernatur maxime et aut, consequuntur.

Body:
Seeing what your description code looks like would be helpful - but if it's using accordion and active classes, this might work:

$(document).on('click', '.accordion', () => {
  $('.accordion').removeClass('active');
  $(this).addClass('active');
});

When .accordion is clicked, it removes all .active classes from all accordions and then adds it back in on the one you clicked.


问:
How can I reorder multi-indexed dataframe columns at a specific level
I have a multi-indexed DataFrame with names attached to the column levels.  I'd like to be able to easily shuffle the columns around so that they match the order specified by the user.  Since this is down the pipeline, I'm not able to use this recommended solution and order them properly at creation time.

I have a data table that looks (something) like

```<code>Experiment           BASE           IWWGCW         IWWGDW
Lead Time                24     48      24     48      24     48
2010-11-27 12:00:00   0.997  0.991   0.998  0.990   0.998  0.990
2010-11-28 12:00:00   0.998  0.987   0.997  0.990   0.997  0.990
2010-11-29 12:00:00   0.997  0.992   0.997  0.992   0.997  0.992
2010-11-30 12:00:00   0.997  0.987   0.997  0.987   0.997  0.987
2010-12-01 12:00:00   0.996  0.986   0.996  0.986   0.996  0.986
</code>```

I want to take in a list like ['IWWGCW', 'IWWGDW', 'BASE'] and reorder this to be:

```<code>Experiment           IWWGCW         IWWGDW         BASE
Lead Time                24     48      24     48      24     48
2010-11-27 12:00:00   0.998  0.990   0.998  0.990   0.997  0.991
2010-11-28 12:00:00   0.997  0.990   0.997  0.990   0.998  0.987
2010-11-29 12:00:00   0.997  0.992   0.997  0.992   0.997  0.992
2010-11-30 12:00:00   0.997  0.987   0.997  0.987   0.997  0.987
2010-12-01 12:00:00   0.996  0.986   0.996  0.986   0.996  0.986
</code>```

with the caveat that I don't always know at what level "Experiment" will be.  I tried (where df is the multi-indexed frame shown above)

```<code>df2 = df.reindex_axis(['IWWGCW', 'IWWGDW', 'BASE'], axis=1, level='Experiment')
</code>```

but that didn't seem to work - it completed successfully, but the DataFrame that was returned had its column order unchanged.

My workaround is to have a function like:

```<code>def reorder_columns(frame, column_name, new_order):
    """Shuffle the specified columns of the frame to match new_order."""

    index_level  = frame.columns.names.index(column_name)
    new_position = lambda t: new_order.index(t[index_level])
    new_index    = sorted(frame.columns, key=new_position)
    new_frame    = frame.reindex_axis(new_index, axis=1)
    return new_frame
</code>```

where reorder_columns(df, 'Experiment', ['IWWGCW', 'IWWGDW', 'BASE']) does what I expect but it feels like I'm doing extra work.  Is there an easier way to do this?

Body:
I have a multi-indexed DataFrame with names attached to the column levels.  I'd like to be able to easily shuffle the columns around so that they match the order specified by the user.  Since this is down the pipeline, I'm not able to use this recommended solution and order them properly at creation time.

I have a data table that looks (something) like

Experiment           BASE           IWWGCW         IWWGDW
Lead Time                24     48      24     48      24     48
2010-11-27 12:00:00   0.997  0.991   0.998  0.990   0.998  0.990
2010-11-28 12:00:00   0.998  0.987   0.997  0.990   0.997  0.990
2010-11-29 12:00:00   0.997  0.992   0.997  0.992   0.997  0.992
2010-11-30 12:00:00   0.997  0.987   0.997  0.987   0.997  0.987
2010-12-01 12:00:00   0.996  0.986   0.996  0.986   0.996  0.986

I want to take in a list like ['IWWGCW', 'IWWGDW', 'BASE'] and reorder this to be:

Experiment           IWWGCW         IWWGDW         BASE
Lead Time                24     48      24     48      24     48
2010-11-27 12:00:00   0.998  0.990   0.998  0.990   0.997  0.991
2010-11-28 12:00:00   0.997  0.990   0.997  0.990   0.998  0.987
2010-11-29 12:00:00   0.997  0.992   0.997  0.992   0.997  0.992
2010-11-30 12:00:00   0.997  0.987   0.997  0.987   0.997  0.987
2010-12-01 12:00:00   0.996  0.986   0.996  0.986   0.996  0.986

with the caveat that I don't always know at what level "Experiment" will be.  I tried (where df is the multi-indexed frame shown above)

df2 = df.reindex_axis(['IWWGCW', 'IWWGDW', 'BASE'], axis=1, level='Experiment')

but that didn't seem to work - it completed successfully, but the DataFrame that was returned had its column order unchanged.

My workaround is to have a function like:

def reorder_columns(frame, column_name, new_order):
    """Shuffle the specified columns of the frame to match new_order."""

    index_level  = frame.columns.names.index(column_name)
    new_position = lambda t: new_order.index(t[index_level])
    new_index    = sorted(frame.columns, key=new_position)
    new_frame    = frame.reindex_axis(new_index, axis=1)
    return new_frame

where reorder_columns(df, 'Experiment', ['IWWGCW', 'IWWGDW', 'BASE']) does what I expect but it feels like I'm doing extra work.  Is there an easier way to do this?

Body:
The comment by andrew_reece should be the accepted answer. Simply use reindex().

Copy & pasting from the github issue:

>>> df
                     vals
first second third
mid   3rd    992     1.96
             562    12.06
      1st    73     -6.46
             818   -15.75
             658     5.90
btm   2nd    915     9.75
             474    -1.47
             905    -6.03
      1st    717     8.01
             909   -21.12
      3rd    616    11.91
             675     1.06
             579    -4.01
top   1st    241     1.79
             363     1.71
      3rd    677    13.38
             238   -16.77
             407    17.19
      2nd    728   -21.55
             36      8.09
>>> df.reindex(['top', 'mid', 'btm'], level='first')
                     vals
first second third
top   1st    241     1.79
             363     1.71
      3rd    677    13.38
             238   -16.77
             407    17.19
      2nd    728   -21.55
             36      8.09
mid   3rd    992     1.96
             562    12.06
      1st    73     -6.46
             818   -15.75
             658     5.90
btm   2nd    915     9.75
             474    -1.47
             905    -6.03
      1st    717     8.01
             909   -21.12
      3rd    616    11.91
             675     1.06
             579    -4.01
>>> df.reindex(['1st', '2nd', '3rd'], level='second')
                     vals
first second third
mid   1st    73     -6.46
             818   -15.75
             658     5.90
      3rd    992     1.96
             562    12.06
btm   1st    717     8.01
             909   -21.12
      2nd    915     9.75
             474    -1.47
             905    -6.03
      3rd    616    11.91
             675     1.06
             579    -4.01
top   1st    241     1.79
             363     1.71
      2nd    728   -21.55
             36      8.09
      3rd    677    13.38
             238   -16.77
             407    17.19
>>> df.reindex(['top', 'btm'], level='first').reindex(['1st', '2nd'], level='second')
                     vals
first second third
top   1st    241     1.79
             363     1.71
      2nd    728   -21.55
             36      8.09
btm   1st    717     8.01
             909   -21.12
      2nd    915     9.75
             474    -1.47
             905    -6.03


问:
How to check whether dynamically attached event listener exists or not?
Here is my problem: is it somehow possible to check for the existence of a dynamically attached event listener? Or how can I check the status of the "onclick" (?) property in the DOM? I have searched the internet just like Stack Overflow for a solution, but no luck. Here is my html:

 link 1
 link 2
```
<p>Then in Javascript I attach a dynamically created event listener to the 2nd link:</p>
<pre class="lang-js prettyprint-override"><code>document.getElementById('link2').addEventListener('click', linkclick, false);
</code>```

The code runs well, but all my attempts to detect that attached listener fail:

// test for #link2 - dynamically created eventlistener
alert(elem.onclick); // null
alert(elem.hasAttribute('onclick')); // false
alert(elem.click); // function click(){[native code]} // btw, what's this?
```

jsFiddle is here.
If you click "Add onclick for 2" and then "[link 2]", the event fires well,
but the "Test link 2" always reports false.
Can somebody help?

答:
If I understand well you can only check if a listener has been checked but not which listener is presenter specifically.

So some ad hoc code would fill the gap to handle your coding flow. A practical method would be to create a state using variables. For example, attach a listener's checker as following:

```<code>var listenerPresent=false
</code>```

then if you set a listener just change the value:

```<code>listenerPresent=true
</code>```

then inside your eventListener 's callback you can assign specific functionalities inside and in this same way, distribute the access to functionalities depending of some state as variable for example:

```<code>accessFirstFunctionality=false
accessSecondFunctionality=true
accessThirdFunctionality=true
</code>```

Body:
Here is my problem: is it somehow possible to check for the existence of a dynamically attached event listener? Or how can I check the status of the "onclick" (?) property in the DOM? I have searched the internet just like Stack Overflow for a solution, but no luck. Here is my html:

 link 1
 link 2

Then in Javascript I attach a dynamically created event listener to the 2nd link:

document.getElementById('link2').addEventListener('click', linkclick, false);

The code runs well, but all my attempts to detect that attached listener fail:

// test for #link2 - dynamically created eventlistener
alert(elem.onclick); // null
alert(elem.hasAttribute('onclick')); // false
alert(elem.click); // function click(){[native code]} // btw, what's this?

jsFiddle is here.
If you click "Add onclick for 2" and then "[link 2]", the event fires well,
but the "Test link 2" always reports false.
Can somebody help?

Body:
If I understand well you can only check if a listener has been checked but not which listener is presenter specifically.

So some ad hoc code would fill the gap to handle your coding flow. A practical method would be to create a state using variables. For example, attach a listener's checker as following:

var listenerPresent=false

then if you set a listener just change the value:

listenerPresent=true

then inside your eventListener 's callback you can assign specific functionalities inside and in this same way, distribute the access to functionalities depending of some state as variable for example:

accessFirstFunctionality=false
accessSecondFunctionality=true
accessThirdFunctionality=true


问:
Access property/environment variables without launching Eclipse?
I want to set the log4j configuration file path/other folder paths that can be used across other class files, without hard-coding the folder path.

Rightnow, I have set the variables as Environment variable. But It can only be modified if I launch Eclipse. How do I set this variable in such away that anyone (doesn't want to launch Eclipse) can modify it, from outside. Also, it will be used in test configurations. So it's better to not hard-code it and have all the file paths etc. easy to refactor.

```<code>final static String log4jpath = System.getenv("LOG4J_PATH");
</code>```

答:
I have added all file and folder paths inside the properties file (example config.properties) and then used it inside the testsetup method by InputStream input = new FileInputStream("Path to//config.properties");
                Properties prop = new Properties();
                prop.load(input);
                System.setProperty("log4j2.configurationFile", prop.getProperty("log4j.path"));

this way, all files/folder paths can be modifies from outside and there's no need to set environment variable from inside the project.

Body:
I want to set the log4j configuration file path/other folder paths that can be used across other class files, without hard-coding the folder path.

Rightnow, I have set the variables as Environment variable. But It can only be modified if I launch Eclipse. How do I set this variable in such away that anyone (doesn't want to launch Eclipse) can modify it, from outside. Also, it will be used in test configurations. So it's better to not hard-code it and have all the file paths etc. easy to refactor.

final static String log4jpath = System.getenv("LOG4J_PATH");


问:
Keras, How to get the output of each layer?
I have trained a binary classification model with CNN, and here is my code

```<code>model = Sequential()
model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1],
                        border_mode='valid',
                        input_shape=input_shape))
model.add(Activation('relu'))
model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
# (16, 16, 32)
model.add(Convolution2D(nb_filters*2, kernel_size[0], kernel_size[1]))
model.add(Activation('relu'))
model.add(Convolution2D(nb_filters*2, kernel_size[0], kernel_size[1]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
# (8, 8, 64) = (2048)
model.add(Flatten())
model.add(Dense(1024))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(2))  # define a binary classification problem
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer='adadelta',
              metrics=['accuracy'])
model.fit(x_train, y_train,
          batch_size=batch_size,
          nb_epoch=nb_epoch,
          verbose=1,
          validation_data=(x_test, y_test))
</code>```

And here, I wanna get the output of each layer just like TensorFlow, how can I do that?

答:
Assuming you have:

1- Keras pre-trained model.

2- Input x as image or set of images. The resolution of image should be compatible with dimension of the input layer. For example 80*80*3 for 3-channels (RGB) image.

3- The name of the output layer to get the activation. For example, "flatten_2" layer. This should be include in the layer_names variable, represents name of layers of the given model.

4- batch_size is an optional argument.

Then you can easily use get_activation function to get the activation of the output layer for a given input x and pre-trained model:

```<code>import six
import numpy as np
import keras.backend as k
from numpy import float32
def get_activations(x, model, layer, batch_size=128):
"""
Return the output of the specified layer for input `x`. `layer` is specified by layer index (between 0 and
`nb_layers - 1`) or by name. The number of layers can be determined by counting the results returned by
calling `layer_names`.
:param x: Input for computing the activations.
:type x: `np.ndarray`. Example: x.shape = (80, 80, 3)
:param model: pre-trained Keras model. Including weights.
:type model: keras.engine.sequential.Sequential. Example: model.input_shape = (None, 80, 80, 3)
:param layer: Layer for computing the activations
:type layer: `int` or `str`. Example: layer = 'flatten_2'
:param batch_size: Size of batches.
:type batch_size: `int`
:return: The output of `layer`, where the first dimension is the batch size corresponding to `x`.
:rtype: `np.ndarray`. Example: activations.shape = (1, 2000)
"""

    layer_names = [layer.name for layer in model.layers]
    if isinstance(layer, six.string_types):
        if layer not in layer_names:
            raise ValueError('Layer name %s is not part of the graph.' % layer)
        layer_name = layer
    elif isinstance(layer, int):
        if layer < 0 or layer >= len(layer_names):
            raise ValueError('Layer index %d is outside of range (0 to %d included).'
                             % (layer, len(layer_names) - 1))
        layer_name = layer_names[layer]
    else:
        raise TypeError('Layer must be of type `str` or `int`.')

    layer_output = model.get_layer(layer_name).output
    layer_input = model.input
    output_func = k.function([layer_input], [layer_output])

    # Apply preprocessing
    if x.shape == k.int_shape(model.input)[1:]:
        x_preproc = np.expand_dims(x, 0)
    else:
        x_preproc = x
    assert len(x_preproc.shape) == 4

    # Determine shape of expected output and prepare array
    output_shape = output_func([x_preproc[0][None, ...]])[0].shape
    activations = np.zeros((x_preproc.shape[0],) + output_shape[1:], dtype=float32)

    # Get activations with batching
    for batch_index in range(int(np.ceil(x_preproc.shape[0] / float(batch_size)))):
        begin, end = batch_index * batch_size, min((batch_index + 1) * batch_size, x_preproc.shape[0])
        activations[begin:end] = output_func([x_preproc[begin:end]])[0]

    return activations
</code>```

Body:
I have trained a binary classification model with CNN, and here is my code

model = Sequential()
model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1],
                        border_mode='valid',
                        input_shape=input_shape))
model.add(Activation('relu'))
model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
# (16, 16, 32)
model.add(Convolution2D(nb_filters*2, kernel_size[0], kernel_size[1]))
model.add(Activation('relu'))
model.add(Convolution2D(nb_filters*2, kernel_size[0], kernel_size[1]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
# (8, 8, 64) = (2048)
model.add(Flatten())
model.add(Dense(1024))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(2))  # define a binary classification problem
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer='adadelta',
              metrics=['accuracy'])
model.fit(x_train, y_train,
          batch_size=batch_size,
          nb_epoch=nb_epoch,
          verbose=1,
          validation_data=(x_test, y_test))

And here, I wanna get the output of each layer just like TensorFlow, how can I do that?

Body:
Assuming you have:

1- Keras pre-trained model.

2- Input x as image or set of images. The resolution of image should be compatible with dimension of the input layer. For example 80*80*3 for 3-channels (RGB) image.

3- The name of the output layer to get the activation. For example, "flatten_2" layer. This should be include in the layer_names variable, represents name of layers of the given model.

4- batch_size is an optional argument.

Then you can easily use get_activation function to get the activation of the output layer for a given input x and pre-trained model:

import six
import numpy as np
import keras.backend as k
from numpy import float32
def get_activations(x, model, layer, batch_size=128):
"""
Return the output of the specified layer for input `x`. `layer` is specified by layer index (between 0 and
`nb_layers - 1`) or by name. The number of layers can be determined by counting the results returned by
calling `layer_names`.
:param x: Input for computing the activations.
:type x: `np.ndarray`. Example: x.shape = (80, 80, 3)
:param model: pre-trained Keras model. Including weights.
:type model: keras.engine.sequential.Sequential. Example: model.input_shape = (None, 80, 80, 3)
:param layer: Layer for computing the activations
:type layer: `int` or `str`. Example: layer = 'flatten_2'
:param batch_size: Size of batches.
:type batch_size: `int`
:return: The output of `layer`, where the first dimension is the batch size corresponding to `x`.
:rtype: `np.ndarray`. Example: activations.shape = (1, 2000)
"""

    layer_names = [layer.name for layer in model.layers]
    if isinstance(layer, six.string_types):
        if layer not in layer_names:
            raise ValueError('Layer name %s is not part of the graph.' % layer)
        layer_name = layer
    elif isinstance(layer, int):
        if layer < 0 or layer >= len(layer_names):
            raise ValueError('Layer index %d is outside of range (0 to %d included).'
                             % (layer, len(layer_names) - 1))
        layer_name = layer_names[layer]
    else:
        raise TypeError('Layer must be of type `str` or `int`.')

    layer_output = model.get_layer(layer_name).output
    layer_input = model.input
    output_func = k.function([layer_input], [layer_output])

    # Apply preprocessing
    if x.shape == k.int_shape(model.input)[1:]:
        x_preproc = np.expand_dims(x, 0)
    else:
        x_preproc = x
    assert len(x_preproc.shape) == 4

    # Determine shape of expected output and prepare array
    output_shape = output_func([x_preproc[0][None, ...]])[0].shape
    activations = np.zeros((x_preproc.shape[0],) + output_shape[1:], dtype=float32)

    # Get activations with batching
    for batch_index in range(int(np.ceil(x_preproc.shape[0] / float(batch_size)))):
        begin, end = batch_index * batch_size, min((batch_index + 1) * batch_size, x_preproc.shape[0])
        activations[begin:end] = output_func([x_preproc[begin:end]])[0]

    return activations


问:
Ajax Asynchronous in IE - Error "The Data Necessary to Complete This Operation is Not Yet Available"
I have a 100% valid Ajax model written in Javascript with a few inputs I use being, Get or Post method, What page to communicate with, What String to send to that page and What element on my own page I might be fiddling with when I receive my response.
The problem is that, should I set the request to Asynchronous (Hence Ajax), IE returns the error "The Data Necessary to Complete This Operation is Not Yet Available" in the onreadystatechange event where all I do is check if the readystate is 4 and the status is 200. The error doesn't come up in Firefox or Chrome as I would exepect as the Ajax is Asynchronous.

Heres a snippet from the Post method

```<code>xmlhttp.open("POST", commPage, true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        j = xmlhttp.responseText;
        i.innerHTML = j;
    }
}
xmlhttp.send(str);
</code>```

Edit: I should point out that in IE, I'm using the ActiveX Control -> Msxml2.XMLHTTP or Microsoft.XMLHTTP or whichever returns true first.

答:
Once I had that error, and i solve it configuring the timeouts! maybe you could try the same thing!

Cheers

OwnerDisplayName: Supernovah

ContentLicense: CC BY-SA 2.5

Body:
I have a 100% valid Ajax model written in Javascript with a few inputs I use being, Get or Post method, What page to communicate with, What String to send to that page and What element on my own page I might be fiddling with when I receive my response.
The problem is that, should I set the request to Asynchronous (Hence Ajax), IE returns the error "The Data Necessary to Complete This Operation is Not Yet Available" in the onreadystatechange event where all I do is check if the readystate is 4 and the status is 200. The error doesn't come up in Firefox or Chrome as I would exepect as the Ajax is Asynchronous.

Heres a snippet from the Post method

xmlhttp.open("POST", commPage, true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        j = xmlhttp.responseText;
        i.innerHTML = j;
    }
}
xmlhttp.send(str);

Edit: I should point out that in IE, I'm using the ActiveX Control -> Msxml2.XMLHTTP or Microsoft.XMLHTTP or whichever returns true first.

LastEditorDisplayName: Supernovah


问:
How to combine Scene2d and Bullet?
I want to display some animation using bullet on top of a scene2d stage.
No interaction with the bullet part is required, its supposed to be only an animation.

If required I can also add the SimpleSimulator (so the file has still around 200 lines, even after removing the stuff I don't need for this example).

The call to SimpleSimulator#create basically sets up the world, environment and the objects. (The whole bullet thing is based on https://github.com/xoppa/blog/blob/master/tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/dynamics/step6/BulletTest.java)

public class SimpleExample implements ApplicationListener {

    private class ExampleStage extends Stage {

        public ExampleStage() {

            Image background = new Image(new Texture(Gdx.files.internal("background.png")));
            addActor(background);

        }
    }

    private Camera cam;
    private Stage stage;
    private SimpleSimulator simulator;

    @Override
    public void create() {

        Bullet.init();

        cam = new OrthographicCamera(30, 30);
        cam.lookAt(0f, 1f, 0f);
        cam.near = 0f;
        cam.far = 500f;
        cam.update();

        this.stage = new ExampleStage();

        simulator = new SimpleSimulator();
        simulator.create();

    }

    @Override
    public void render() {

        stage.draw();
        stage.act();

        //simulator.simulate();

        // if added only the bullet part will be animated,
        // if not only scene2d
        // Gdx.gl.glClearColor(0f, 0f, 0f, 1.f);
        // Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

        simulator.modelBatch.begin(cam);
        simulator.modelBatch.render(simulator.instances, simulator.environment);
        simulator.modelBatch.end();
    }

    public void resize(int width, int height) {}
    public void pause() {}
    public void resume() {}

    @Override
    public void dispose() {
        stage.dispose();
        simulator.dispose();
    }
}
```

I might just miss a simple flag in the render method. If I call the Gdx.gl.glClear method's I only manage to see the one or the other.

I also would like to restrict the bullet animation part to a specific area on the screen, so other elements I want to have on the stage are not obstructed by it, but I have not figured out how to do that yet.

答:
Changing the order in the render method as suggested by Tenfour04 did the trick.

I just update this here to mark this question as answered.

```<code>    @Override
    public void render() {

        Gdx.input.setInputProcessor(stage);

        simulator.simulate();

        Gdx.gl.glClearColor(0f, 0f, 0f, 1.f);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

        stage.act();
        stage.draw();

        simulator.modelBatch.begin(cam);
        simulator.modelBatch.render(simulator.instances, simulator.environment);
        simulator.modelBatch.end();
    }
</code>```

Title: How to combine Scene2d and Bullet?

Body:
I want to display some animation using bullet on top of a scene2d stage.
No interaction with the bullet part is required, its supposed to be only an animation.

If required I can also add the SimpleSimulator (so the file has still around 200 lines, even after removing the stuff I don't need for this example).

The call to SimpleSimulator#create basically sets up the world, environment and the objects. (The whole bullet thing is based on https://github.com/xoppa/blog/blob/master/tutorials/src/com/xoppa/blog/libgdx/g3d/bullet/dynamics/step6/BulletTest.java)

public class SimpleExample implements ApplicationListener {

    private class ExampleStage extends Stage {

        public ExampleStage() {

            Image background = new Image(new Texture(Gdx.files.internal("background.png")));
            addActor(background);

        }
    }

    private Camera cam;
    private Stage stage;
    private SimpleSimulator simulator;

    @Override
    public void create() {

        Bullet.init();

        cam = new OrthographicCamera(30, 30);
        cam.lookAt(0f, 1f, 0f);
        cam.near = 0f;
        cam.far = 500f;
        cam.update();

        this.stage = new ExampleStage();

        simulator = new SimpleSimulator();
        simulator.create();

    }

    @Override
    public void render() {

        stage.draw();
        stage.act();

        //simulator.simulate();

        // if added only the bullet part will be animated,
        // if not only scene2d
        // Gdx.gl.glClearColor(0f, 0f, 0f, 1.f);
        // Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

        simulator.modelBatch.begin(cam);
        simulator.modelBatch.render(simulator.instances, simulator.environment);
        simulator.modelBatch.end();
    }

    public void resize(int width, int height) {}
    public void pause() {}
    public void resume() {}

    @Override
    public void dispose() {
        stage.dispose();
        simulator.dispose();
    }
}

I might just miss a simple flag in the render method. If I call the Gdx.gl.glClear method's I only manage to see the one or the other.

I also would like to restrict the bullet animation part to a specific area on the screen, so other elements I want to have on the stage are not obstructed by it, but I have not figured out how to do that yet.

Body:
Changing the order in the render method as suggested by Tenfour04 did the trick.

I just update this here to mark this question as answered.

    @Override
    public void render() {

        Gdx.input.setInputProcessor(stage);

        simulator.simulate();

        Gdx.gl.glClearColor(0f, 0f, 0f, 1.f);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

        stage.act();
        stage.draw();

        simulator.modelBatch.begin(cam);
        simulator.modelBatch.render(simulator.instances, simulator.environment);
        simulator.modelBatch.end();
    }


问:
How to use Spring WebClient to make multiple calls simultaneously?
I want to execute 3 calls simultaneously and process the results once they're all done.

I know this can be achieved using AsyncRestTemplate as it is mentioned here How to use AsyncRestTemplate to make multiple calls simultaneously?

However, AsyncRestTemplate is deprecated in favor of WebClient. I have to use Spring MVC in the project but interested if I can use a WebClient just to execute simultaneous calls. Can someone advise how this should be done properly with WebClient?

答:
You can make HTTP calls concurrently using simple RestTemplate and ExecutorService:

```<code>RestTemplate restTemplate = new RestTemplate();
ExecutorService executorService = Executors.newCachedThreadPool();

Future<String> firstCallFuture = executorService.submit(() -> restTemplate.getForObject("http://first-call-example.com", String.class));
Future<String> secondCallFuture = executorService.submit(() -> restTemplate.getForObject("http://second-call-example.com", String.class));

String firstResponse = firstCallFuture.get();
String secondResponse = secondCallFuture.get();

executorService.shutdown();
</code>```

Or

```<code>Future<String> firstCallFuture = CompletableFuture.supplyAsync(() -> restTemplate.getForObject("http://first-call-example.com", String.class));
Future<String> secondCallFuture = CompletableFuture.supplyAsync(() -> restTemplate.getForObject("http://second-call-example.com", String.class));

String firstResponse = firstCallFuture.get();
String secondResponse = secondCallFuture.get();
</code>```

Body:
You can make HTTP calls concurrently using simple RestTemplate and ExecutorService:

RestTemplate restTemplate = new RestTemplate();
ExecutorService executorService = Executors.newCachedThreadPool();

Future<String> firstCallFuture = executorService.submit(() -> restTemplate.getForObject("http://first-call-example.com", String.class));
Future<String> secondCallFuture = executorService.submit(() -> restTemplate.getForObject("http://second-call-example.com", String.class));

String firstResponse = firstCallFuture.get();
String secondResponse = secondCallFuture.get();

executorService.shutdown();

Or

Future<String> firstCallFuture = CompletableFuture.supplyAsync(() -> restTemplate.getForObject("http://first-call-example.com", String.class));
Future<String> secondCallFuture = CompletableFuture.supplyAsync(() -> restTemplate.getForObject("http://second-call-example.com", String.class));

String firstResponse = firstCallFuture.get();
String secondResponse = secondCallFuture.get();


问:
Does my PC need to execute DHCP in order to have an IP address?
This afternoon I read this from the book "Computer Networking - A Top-Down Approach":

"When Bob first connects his laptop to the network, he can’t do anything (e.g.,
download a Web page) without an IP address. Thus, the first network-related action
taken by Bob’s laptop is to run the DHCP protocol to obtain an IP address, as well
as other information, from the local DHCP server".

Now i have 2 questions:

1-Does this mean in order for my PC to have an IP it needs always to execute DHCP protocol ? (And so does that mean if my PC is offline i don`t have an IP? ).

2-The IP of my PC changes depending from the local DHCP server?

答:
1-Does this mean in order for my PC to have an IP it needs always to execute DHCP protocol ? (And so does that mean if my PC is offline i don`t have an IP? ).

The PC does not actually have to send a DHCP request to the router/modem/switch. It means then when your pc is offline is does not uses a connection to servers on the web. but the IP is also registerd in your PC when there was a DHCP request answered succesfull.

2-The IP of my PC changes depending from the local DHCP server?

The IP of your PC could change from the local DHCP server when the lease is expired


问:
Any good Expression Blend Tutorial out there?
i want to learn Expression blend.. ive been reading some blogs.. about it.. but the applications are some what hard to follow cuse i haven't had a crash course on Blend.. any good tutorial to learn the basics?? i think i need to learn XAML first..what do you recommend?</p>

答: There's also a really nice course by Microsoft: http://www.microsoft.com/design/toolbox/school/</p>


问:
MouseOver Flicking
Why is mouse over flickering with these set events?

I have tried the following code

```<code>const headerTags1 = document.querySelector('h1');
headerTags1.addEventListener('mouseenter', function(event){
event.target.style.display = "none";
})
console.log(headerTags1)

const headerTags2 = document.querySelector('h1');
headerTags2.addEventListener('mouseleave', function(event){
event.target.style.display = "initial";
})
console.log(headerTags2)
</code>```

答:
Scott Marcus gave an excellent explanation for the flickering.

As an alternative you could use the opacity-property of the style. But the element would be still clickable.

const headerTags = document.querySelector('h1');

headerTags.addEventListener('mouseenter', function(event){
  event.target.style.opacity = 0;
})

headerTags.addEventListener('mouseleave', function(event){
  event.target.style.opacity = 1;
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Now you see me...</h1></code>```

Title: MouseOver Flicking

Body:
Why is mouse over flickering with these set events?

I have tried the following code

const headerTags1 = document.querySelector('h1');
headerTags1.addEventListener('mouseenter', function(event){
event.target.style.display = "none";
})
console.log(headerTags1)

const headerTags2 = document.querySelector('h1');
headerTags2.addEventListener('mouseleave', function(event){
event.target.style.display = "initial";
})
console.log(headerTags2)

Body:
Scott Marcus gave an excellent explanation for the flickering.

As an alternative you could use the opacity-property of the style. But the element would be still clickable.

const headerTags = document.querySelector('h1');

headerTags.addEventListener('mouseenter', function(event){
  event.target.style.opacity = 0;
})

headerTags.addEventListener('mouseleave', function(event){
  event.target.style.opacity = 1;
})

<h1>Now you see me...</h1>


答:
Paraphrasing a comment:

[How to get value from] outside of the Java program such as a separate file, that contains all other filepaths?

That is called a configuration file.

It is often a properties file, similar to a Log4j configuration file, but it can be any types of file, e.g. XML, JSON, YAML, ...

To identify a single such file, you can use:

An environment variable (like you are right now)

A system property (more common)

A specifically named file in the current directory

...

The entries in that file will identify all the values you really want.

For example, Spring, which is a populate Java framework, will look for configuration values in many places. See 24. Externalized Configuration for full detail, but here is a summary of the most common ones:

Command line arguments, e.g. java -jar MyApp.jar --foo=bar

Java System properties, e.g. set using -Dfoo=bar on the command-line

OS environment variables, e.g. SET foo=bar (Windows) or export foo=bar (Linux)

Application properties outside of your packaged jar, i.e. relative to current directory.

Name and location can be overridden on command-line.

config/application.properties

config/application.yaml

application.properties

application.yaml

Title: Access property/environment variables without launching Eclipse?


问:
Airflow DAG Loop - How to make each iteration sequential instead of parallel
I have an Apache Airflow DAG like so:

```<code>DAG_NAME='my_dag'
sections = ["0", "1", "2", "3"]

with DAG(DAG_NAME, default_args=default_args, schedule_interval=None) as dag:

        for s in sections:
            a = DummyOperator(task_id=f"section_{s}_start")
            b = SubDagOperator(task_id=f"init_{s}_subdag",subdag=init_section(DAG_NAME,f"init_{s}_subdag", default_args))
            c = SubDagOperator(task_id=f"process_{s}_subdag", subdag=process_section(DAG_NAME,f"process_{s}_subdag", default_args))
            d = SubDagOperator(task_id=f"update_{s}_subdag", subdag=update_section(DAG_NAME,f"update_{s}_subdag", default_args))
            e = DummyOperator(task_id=f"section_{s}_end")
            a>>b>>c>>d>>e
</code>```

This code renders my tasks like so

How can I make the sequence of tasks be:

section_0_start>>init_0_subdag>>process_0_subdag>>update_0_subdag>>section_0_end
section_0_end>>section_1_start
section_1_start>>init_1_subdag>>process_1_subdag>>update_1_subdag>>section_1_end

.....

and so on in sequence from section 0 ending with section 3 tasks

Thanks

答:
Modify the for-loop like this:</p>

```<code>    previous_e = None
    for s in sections:
        a = ...
        ...
        e = ...
        if previous_e:
            previous_e >> a
        a>>b>>c>>d>>e
        previous_e = e
</code>```

Body:
I have an Apache Airflow DAG like so:

DAG_NAME='my_dag'
sections = ["0", "1", "2", "3"]

with DAG(DAG_NAME, default_args=default_args, schedule_interval=None) as dag:

        for s in sections:
            a = DummyOperator(task_id=f"section_{s}_start")
            b = SubDagOperator(task_id=f"init_{s}_subdag",subdag=init_section(DAG_NAME,f"init_{s}_subdag", default_args))
            c = SubDagOperator(task_id=f"process_{s}_subdag", subdag=process_section(DAG_NAME,f"process_{s}_subdag", default_args))
            d = SubDagOperator(task_id=f"update_{s}_subdag", subdag=update_section(DAG_NAME,f"update_{s}_subdag", default_args))
            e = DummyOperator(task_id=f"section_{s}_end")
            a>>b>>c>>d>>e

This code renders my tasks like so

How can I make the sequence of tasks be:

section_0_start>>init_0_subdag>>process_0_subdag>>update_0_subdag>>section_0_end
section_0_end>>section_1_start
section_1_start>>init_1_subdag>>process_1_subdag>>update_1_subdag>>section_1_end

.....

and so on in sequence from section 0 ending with section 3 tasks

Thanks

Body:
Modify the for-loop like this:

    previous_e = None
    for s in sections:
        a = ...
        ...
        e = ...
        if previous_e:
            previous_e >> a
        a>>b>>c>>d>>e
        previous_e = e


问:
Python Pandas Series.str.contains
I have some data that looks like this in a CSV file:

Is it possible to print a Boolean statement if the dataframe columns names are MAT and OAT and RAT?

Is pandas series needed for this? Like Series.str.contains?

```<code>import pandas as pd

df = pd.read_csv('static/data.csv')

#OAT = pd.Series(df['OAT'])
#RAT = pd.Series(df['RAT'])
#MAT = pd.Series(df['MAT'])

dfS = pd.Series(df)

print(dfS.str.contains('OAT', 'MAT', 'RAT'))
</code>```

答:
Work on the columns of the dataframe.

```<code>mask = df.columns.isin(['OAT', 'MAT', 'RAT'])
</code>```

mask is now a boolean numpy.ndarray with True for any column position
that matches your 'isin' list.

Title: Python Pandas Series.str.contains

Body:
I have some data that looks like this in a CSV file:

Is it possible to print a Boolean statement if the dataframe columns names are MAT and OAT and RAT?

Is pandas series needed for this? Like Series.str.contains?

import pandas as pd

df = pd.read_csv('static/data.csv')

#OAT = pd.Series(df['OAT'])
#RAT = pd.Series(df['RAT'])
#MAT = pd.Series(df['MAT'])

dfS = pd.Series(df)

print(dfS.str.contains('OAT', 'MAT', 'RAT'))

Body:
Work on the columns of the dataframe.

mask = df.columns.isin(['OAT', 'MAT', 'RAT'])

mask is now a boolean numpy.ndarray with True for any column position
that matches your 'isin' list.


问:
Errors processing bullet point via regex replace in VB to clean up XML file
I'm trying to clean up an XML file to have only UTF-8 characters but I'm having issues with a bullet point.  The files have a bullet point in them and if I remove these characters, the rest of the regex replace works fine, but it doesn't seem to replace this specific bullet character.  Looking at HEX it is 0x07 and in unicode /u0007 but neither of these resolved the error ("hexidecimal value 0x07, is an invalid character")

here is some of the regex replace code (VB script in SSIS) I'm using with several iterations I've tried.  Any help would be greatly appreciated.

```<code>    XMLString = FileIO.FileSystem.ReadAllText(filelocation)
    'Dim rgx As Regex = New Regex("[\x00-\x08\x0B-\x0C\x0E-\x1F\u0000-\u0007]", RegexOptions.None)
    'Dim rgx As Regex = New Regex("[^0-9a-zA-Z]", RegexOptions.None)
    'Dim rgx As Regex = New Regex("[[:^print:]]", RegexOptions.None)
    'Dim rgx As Regex = New Regex("[[:^print:][\u0007]]", RegexOptions.None)
    Dim rgx As Regex = New Regex("[^\x09\x0A\x0D\x20-\xD7FF\xE000-\xFFFD\x10000-x10FFFF]", RegexOptions.None)
    'Dim rgx As Regex = New Regex("[\x00-\x1F\x7F-\xFF]+", RegexOptions.None)
    rgx.Replace(XMLString, "")
</code>```

thanks

答:
One think you need to know is whether your regular expression is being applied against a string of bytes, or a string of characters. (In perl there is an explicit difference, not too sure about VB - its usually controlled by the way you read the data in). The below two points are not "rules" as such, more good form.

If running against bytes, then you should only use the \xXX escape sequences. (and XX can only be 2 "digits")

If running against characters, then you should use the \uXXXX escape sequences (\xXXXX is the same thing in most languages)

Looking at your uncommented regex, it seems you're looking at characters. This would imply the file must already be in some valid character encoding (probably one of UTF-8, UTF-16LE, or cp1252). So all this regex is doing is stripping out valid UTF-8 characters which are not allowed according the the XML spec. http://www.w3.org/TR/xml/#charsets . That should be fine.

But if your string is a stream of bytes, and you are trying to ensure it is valid UTF-8 then that is harder to do with a regex. Other than non-ascii I don't know how.

One other point: Shouldn't you be setting the Global attribute of your regex before doing the replace. Could this be your problem? Its fixing the first occurance but not the whole file?

Body:
I'm trying to clean up an XML file to have only UTF-8 characters but I'm having issues with a bullet point.  The files have a bullet point in them and if I remove these characters, the rest of the regex replace works fine, but it doesn't seem to replace this specific bullet character.  Looking at HEX it is 0x07 and in unicode /u0007 but neither of these resolved the error ("hexidecimal value 0x07, is an invalid character")

here is some of the regex replace code (VB script in SSIS) I'm using with several iterations I've tried.  Any help would be greatly appreciated.

    XMLString = FileIO.FileSystem.ReadAllText(filelocation)
    'Dim rgx As Regex = New Regex("[\x00-\x08\x0B-\x0C\x0E-\x1F\u0000-\u0007]", RegexOptions.None)
    'Dim rgx As Regex = New Regex("[^0-9a-zA-Z]", RegexOptions.None)
    'Dim rgx As Regex = New Regex("[[:^print:]]", RegexOptions.None)
    'Dim rgx As Regex = New Regex("[[:^print:][\u0007]]", RegexOptions.None)
    Dim rgx As Regex = New Regex("[^\x09\x0A\x0D\x20-\xD7FF\xE000-\xFFFD\x10000-x10FFFF]", RegexOptions.None)
    'Dim rgx As Regex = New Regex("[\x00-\x1F\x7F-\xFF]+", RegexOptions.None)
    rgx.Replace(XMLString, "")

thanks


问:
How to unittest a function where the result is based on a conditional statement contained within a while loop
I'm wondering what is the best way to unittest a while loop that breaks only when a specific input is entered (see code for more detail). My test actually works as intended and fails correctly. However, I feel like it's 'hacked together' and isn't the best way to test this kind of code.

Currently, I have to manually break the loop within the test by mocking an user input that breaks the loop (see code for more detail). I've tried you parametrize in pytest, however, the test gets stuck on an infinite loop as soon as I mock an input that doesn't break the loop. It never gets to the next parametrized value.

Function Being Tested

```<code>def export_options():
    while True:
        try:
            choice = int(input("\nPlease make a selection"))
            if choice in range(1, 5):
                return choice
            else:
                 # I want to test this line when the input is bad
                print("\nNot a valid selection\n")
        except ValueError as err:
            print("Please enter an integer")
</code>```

Test Function

```<code>@mock.patch('realestate.app.user_inputs.print')
# The 1 is used to break the loop otherwise the test never ends!
@mock.patch('realestate.app.user_inputs.input', side_effect=[0, 5, 1])
def test_export_options_invalid_integer(mock_choice, mock_print):
    user_inputs.export_options()

    # Best way I could think of to test bad inputs. Anything that is less than 1 or greater than 4 will fail the test.
    # Make sure I call the correct print function
    mock_print.assert_called_with("\nNot a valid selection\n")
    # Make sure I call the correct print function twice
    assert mock_print.call_count == 2
</code>```

I get the results I want based on my current code. However, I'd like to use best practices when possible and apply them to all future tests when dealing with while loops that only break based on a specific user input.

答:
Regarding "real" infinite loops that never exit: Processes on embedded systems are sometimes implemented like this, and will terminate only when the system shuts down by power-off or by getting killed by the operating system.  For such loops the typical solution is to extract the loop body into a separate function/method.

```<code>def main_loop():
    while True:
        main_body()
</code>```

This way, you have maximized the amount of code that can be unit-tested by extracting it to main_body.  Clearly, main_loop can still not be unit-tested, but it can be tested in higher-level tests.

Obviously, your loop is not of that kind since you have a possibility to leave the loop without killing threads or the like.  Therefore, I would argue that your approach to testing that function is quite sound in principle.

There are some ways to improve the test suite, however.  To give some example: The test case you have shown as an example is already a complex test, and I would recommend to start with more fundamental tests:

Test that the number 1 is accepted

Test that the number 4 is accepted

Test that the number 0 is not accepted (sequence: 0, one from 1..4)

Test that the number 5 is not accepted (sequence: 5, one from 1..4)

If any of these tests fail, it will give you a more direct indication where the problem could lie.  What these tests do not yet test (in contrast to your test) is, whether the routine will be able to handle more than one bad input, and, whether the prompts and error messages are as expected.  These are, however, individual aspects and thus it would make sense to split your test into separate tests, one test per aspect.

Body:
I'm wondering what is the best way to unittest a while loop that breaks only when a specific input is entered (see code for more detail). My test actually works as intended and fails correctly. However, I feel like it's 'hacked together' and isn't the best way to test this kind of code.

Currently, I have to manually break the loop within the test by mocking an user input that breaks the loop (see code for more detail). I've tried you parametrize in pytest, however, the test gets stuck on an infinite loop as soon as I mock an input that doesn't break the loop. It never gets to the next parametrized value.

Function Being Tested

def export_options():
    while True:
        try:
            choice = int(input("\nPlease make a selection"))
            if choice in range(1, 5):
                return choice
            else:
                 # I want to test this line when the input is bad
                print("\nNot a valid selection\n")
        except ValueError as err:
            print("Please enter an integer")

Test Function

@mock.patch('realestate.app.user_inputs.print')
# The 1 is used to break the loop otherwise the test never ends!
@mock.patch('realestate.app.user_inputs.input', side_effect=[0, 5, 1])
def test_export_options_invalid_integer(mock_choice, mock_print):
    user_inputs.export_options()

    # Best way I could think of to test bad inputs. Anything that is less than 1 or greater than 4 will fail the test.
    # Make sure I call the correct print function
    mock_print.assert_called_with("\nNot a valid selection\n")
    # Make sure I call the correct print function twice
    assert mock_print.call_count == 2

I get the results I want based on my current code. However, I'd like to use best practices when possible and apply them to all future tests when dealing with while loops that only break based on a specific user input.

Body:
Regarding "real" infinite loops that never exit: Processes on embedded systems are sometimes implemented like this, and will terminate only when the system shuts down by power-off or by getting killed by the operating system.  For such loops the typical solution is to extract the loop body into a separate function/method.

def main_loop():
    while True:
        main_body()

This way, you have maximized the amount of code that can be unit-tested by extracting it to main_body.  Clearly, main_loop can still not be unit-tested, but it can be tested in higher-level tests.

Obviously, your loop is not of that kind since you have a possibility to leave the loop without killing threads or the like.  Therefore, I would argue that your approach to testing that function is quite sound in principle.

There are some ways to improve the test suite, however.  To give some example: The test case you have shown as an example is already a complex test, and I would recommend to start with more fundamental tests:

Test that the number 1 is accepted

Test that the number 4 is accepted

Test that the number 0 is not accepted (sequence: 0, one from 1..4)

Test that the number 5 is not accepted (sequence: 5, one from 1..4)

If any of these tests fail, it will give you a more direct indication where the problem could lie.  What these tests do not yet test (in contrast to your test) is, whether the routine will be able to handle more than one bad input, and, whether the prompts and error messages are as expected.  These are, however, individual aspects and thus it would make sense to split your test into separate tests, one test per aspect.


答:
You can use the issubset method to return boolean if ['OAT', 'MAT', 'RAT'] is in the dataframe's columns:

```<code>expected = set(['OAT', 'MAT', 'RAT'])
print(expected.issubset(df.columns))
</code>```

Title: Python Pandas Series.str.contains

Body:
You can use the issubset method to return boolean if ['OAT', 'MAT', 'RAT'] is in the dataframe's columns:

expected = set(['OAT', 'MAT', 'RAT'])
print(expected.issubset(df.columns))