问:
C++ String Interview Question
I was recently in a C++ technical interview, where I was given a bit of simple string manipulation code, which is intended to take a string and return a string that is comprised of the first and last n-characters, and then proceed to correct any bugs and to also make the function as efficient as possible, I came up with the solution below, however the interviewer claimed there was an even faster more optimal way:

Original code:

```<code>std::string first_last_n(int n, std::string s)
{
   std::string first_n = s.substr(0,n);
   std::string last_n = s.substr(s.size()-n-1,n);
   return first_n + last_n;
}
</code>```

My code:

```<code>bool first_last_n(const std::size_t& n, const std::string& s, std::string& r)
{
   if (s.size() < n)
      return false;
   r.reserve(2 * n);
   r.resize(0);
   r.append(s.data(),s.data() + n);
   r.append(s.data() + (s.size() - n), s.data() + s.size());
   return true;
}
</code>```

Summary of my changes:

Changed the interface to take a return string as reference (assuming RVO and rvalues are not available yet)

Removed temporary strings being constructed via substr

Passed input string as a const reference inorder to get around temporary instantiation of input

Fixed off-by-1 error in last_n string

Reduced the number of times each character is touched down to once, or twice (in the event of an overlapping scenario)

Placed a check in the event the string s's size is less than n, returning false for failure.

Assuming only native C++ is allowed, is there some other way of doing the above more efficiently or optimally?

Note 1: The original input string instance is not to be modified.

Note 2: All solutions must pass the following test case, otherwise they are not valid.

```<code>void test()
{
   {
      std::string s = "0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "0123456789ABC0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "1234321";
      std::string r = first_last_n(5,s);
      assert(r == "1234334321");
   }

}
</code>```

答:
```<code>// compiled with cl /Ox first_last_n.cpp /W4 /EHsc

inline void
first_last_n2(string::size_type n, const std::string &s, string &out)  // method 2
{
  // check against degenerate input
  assert(n > 0);
  assert(n <= s.size());

  out.reserve(2*n);
  out.assign(s, 0, n);
  out.append(s, s.size()-n, n);
}
</code>```

Times:

```<code>method 1:  // original method
2.281
method 2:  // my method
0.687
method 3:  // your code.
0.782
</code>```

Note: Timing specifically tests "long" strings. I.e. those where short string optimization is not used. (My strings were 100 length).

OwnerDisplayName: Matthieu N.

LastEditorDisplayName: Matthieu N.

Title: C++ String Interview Question

Body:
I was recently in a C++ technical interview, where I was given a bit of simple string manipulation code, which is intended to take a string and return a string that is comprised of the first and last n-characters, and then proceed to correct any bugs and to also make the function as efficient as possible, I came up with the solution below, however the interviewer claimed there was an even faster more optimal way:

Original code:

std::string first_last_n(int n, std::string s)
{
   std::string first_n = s.substr(0,n);
   std::string last_n = s.substr(s.size()-n-1,n);
   return first_n + last_n;
}

My code:

bool first_last_n(const std::size_t& n, const std::string& s, std::string& r)
{
   if (s.size() < n)
      return false;
   r.reserve(2 * n);
   r.resize(0);
   r.append(s.data(),s.data() + n);
   r.append(s.data() + (s.size() - n), s.data() + s.size());
   return true;
}

Summary of my changes:

Changed the interface to take a return string as reference (assuming RVO and rvalues are not available yet)

Removed temporary strings being constructed via substr

Passed input string as a const reference inorder to get around temporary instantiation of input

Fixed off-by-1 error in last_n string

Reduced the number of times each character is touched down to once, or twice (in the event of an overlapping scenario)

Placed a check in the event the string s's size is less than n, returning false for failure.

Assuming only native C++ is allowed, is there some other way of doing the above more efficiently or optimally?

Note 1: The original input string instance is not to be modified.

Note 2: All solutions must pass the following test case, otherwise they are not valid.

void test()
{
   {
      std::string s = "0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "0123456789ABC0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "1234321";
      std::string r = first_last_n(5,s);
      assert(r == "1234334321");
   }

}

Body:
// compiled with cl /Ox first_last_n.cpp /W4 /EHsc

inline void
first_last_n2(string::size_type n, const std::string &s, string &out)  // method 2
{
  // check against degenerate input
  assert(n > 0);
  assert(n <= s.size());

  out.reserve(2*n);
  out.assign(s, 0, n);
  out.append(s, s.size()-n, n);
}

Times:

method 1:  // original method
2.281
method 2:  // my method
0.687
method 3:  // your code.
0.782

Note: Timing specifically tests "long" strings. I.e. those where short string optimization is not used. (My strings were 100 length).


来源: stackexchange

问:
Exception Handling Error
When a method throws an exception, it searches through the call stack to find a handler right? In that sense, why is there an error with exep.second();? even though i've caught the exception in method second(). Here's my code:

```<code>public class Exep {
void first()throws IOException{
    throw new IOException("device error");
}
void second()throws IOException{
    try{
        first();
    }catch(Exception e){
        System.out.println(e);
    }
}
public static void main(String args[]){
    Exep exep = new Exep();
    exep.second();
}
</code>```

}

But the error disappears on adding  throws IOException to the main(). Why?

答:
You are telling the compiler that second() throws IOException, but when you call second() you aren't wrapping it in a try/catch block. If you want to leave it as is then you need to include a try catch block inside your main.

However, as you have it, you're never throwing an exception from inside of second() so you can remove the line throws IOException from there.

ContentLicense: CC BY-SA 3.0

Title: Exception Handling Error

Body:
When a method throws an exception, it searches through the call stack to find a handler right? In that sense, why is there an error with exep.second();? even though i've caught the exception in method second(). Here's my code:

public class Exep {
void first()throws IOException{
    throw new IOException("device error");
}
void second()throws IOException{
    try{
        first();
    }catch(Exception e){
        System.out.println(e);
    }
}
public static void main(String args[]){
    Exep exep = new Exep();
    exep.second();
}

}

But the error disappears on adding  throws IOException to the main(). Why?


问:
Number of months between given months
I want to find the count of number of months between given months such as Jan,Feb,Mar...

eg - Input - Jun , Aug
 Output -3
Input - Dec,Mar
Output - 4

```<code> $string = "Jun";
 $month_number1 = date("n",strtotime($string));
 $string = "Aug";
 $month_number2 = date("n",strtotime($string));
 $monthCount = ($month_number2 - $month_number1) +1 ;
</code>```

But this doesn't work for Dec and Mar .
Please help.Thank you

答:
The secret to cyclic quantities like this is to calc the modulus of your delta by the number of elements, in this case 12, for twelve months. So, basically

```<code>(m2 - m1) % 12
</code>```

But many languages don't do mods on negative numbers very effectively, so add the same number into the difference calc:

```<code>n = (12 + m2 - m1) % 12
</code>```

Title: Number of months between given months

Body:
I want to find the count of number of months between given months such as Jan,Feb,Mar...

eg - Input - Jun , Aug
 Output -3
Input - Dec,Mar
Output - 4

 $string = "Jun";
 $month_number1 = date("n",strtotime($string));
 $string = "Aug";
 $month_number2 = date("n",strtotime($string));
 $monthCount = ($month_number2 - $month_number1) +1 ;

But this doesn't work for Dec and Mar .
Please help.Thank you

Body:
The secret to cyclic quantities like this is to calc the modulus of your delta by the number of elements, in this case 12, for twelve months. So, basically

(m2 - m1) % 12

But many languages don't do mods on negative numbers very effectively, so add the same number into the difference calc:

n = (12 + m2 - m1) % 12


问:
Virtually turn vector of struct into vector of struct members
I have a function that takes a vector-like input. To simplify things, let's use this print_in_order function:

```<code>#include <iostream>
#include <vector>

template <typename vectorlike>
void print_in_order(std::vector<int> const & order,
                    vectorlike const & printme) {
    for (int i : order)
        std::cout << printme[i] << std::endl;
}

int main() {
    std::vector<int> printme = {100, 200, 300};
    std::vector<int> order = {2,0,1};
    print_in_order(order, printme);
}
</code>```

Now I have a vector<Elem> and want to print a single integer member, Elem.a, for each Elem in the vector. I could do this by creating a new vector<int> (copying a for all Elems) and pass this to the print function - however, I feel like there must be a way to pass a "virtual" vector that, when operator[] is used on it, returns this only the member a. Note that I don't want to change the print_in_order function to access the member, it should remain general.

Is this possible, maybe with a lambda expression?
Full code below.

```<code>#include <iostream>
#include <vector>

struct Elem {
    int a,b;
    Elem(int a, int b) : a(a),b(b) {}
};

template <typename vectorlike>
void print_in_order(std::vector<int> const & order,
                    vectorlike const & printme) {
    for (int i : order)
        std::cout << printme[i] << std::endl;
}

int main() {
    std::vector<Elem> printme = {Elem(1,100), Elem(2,200), Elem(3,300)};
    std::vector<int> order = {2,0,1};

    // how to do this?
    virtual_vector X(printme) // behaves like a std::vector<Elem.a>
    print_in_order(order, X);
}
</code>```

答:
Using member pointers you can implement a proxy type that will allow you view a container of objects by substituting each object by one of it's members (see pointer to data member) or by one of it's getters (see pointer to member function). The first solution addresses only data members, the second accounts for both.

The container will necessarily need to know which container to use and which member to map, which will be provided at construction. The type of a pointer to member depends on the type of that member so it will have to be considered as an additional template argument.

```<code>template<class Container, class MemberPtr>
class virtual_vector
{
public:
    virtual_vector(const Container & p_container, MemberPtr p_member_ptr) :
        m_container(&p_container),
        m_member(p_member_ptr)
    {}

private:
    const Container * m_container;
    MemberPtr m_member;
};
</code>```

Next, implement the operator[] operator, since you mentioned that it's how you wanted to access your elements. The syntax for dereferencing a member pointer can be surprising at first.

```<code>template<class Container, class MemberPtr>
class virtual_vector
{
public:
    virtual_vector(const Container & p_container, MemberPtr p_member_ptr) :
        m_container(&p_container),
        m_member(p_member_ptr)
    {}

    // Dispatch to the right get method
    auto operator[](const size_t p_index) const
    {
        return (*m_container)[p_index].*m_member;
    }

private:
    const Container * m_container;
    MemberPtr m_member;
};
</code>```

To use this implementation, you would write something like this :

```<code>int main() {
    std::vector<Elem> printme = { Elem(1,100), Elem(2,200), Elem(3,300) };
    std::vector<int> order = { 2,0,1 };

    virtual_vector<decltype(printme), decltype(&Elem::a)> X(printme, &Elem::a);
    print_in_order(order, X);
}
</code>```

This is a bit cumbersome since there is no template argument deduction happening. So lets add a free function to deduce the template arguments.

```<code>template<class Container, class MemberPtr>
virtual_vector<Container, MemberPtr>
make_virtual_vector(const Container & p_container, MemberPtr p_member_ptr)
{
    return{ p_container, p_member_ptr };
}
</code>```

The usage becomes :

```<code>int main() {
    std::vector<Elem> printme = { Elem(1,100), Elem(2,200), Elem(3,300) };
    std::vector<int> order = { 2,0,1 };

    auto X = make_virtual_vector(printme, &Elem::a);
    print_in_order(order, X);
}
</code>```

If you want to support member functions, it's a little bit more complicated. First, the syntax to dereference a data member pointer is slightly different from calling a function member pointer. You have to implement two versions of the operator[] and enable the correct one based on the member pointer type. Luckily the standard provides std::enable_if and std::is_member_function_pointer (both in the <type_trait> header) which allow us to do just that. The member function pointer requires you to specify the arguments to pass to the function (non in this case) and an extra set of parentheses around the expression that would evaluate to the function to call (everything before the list of arguments).

```<code>template<class Container, class MemberPtr>
class virtual_vector
{
public:
    virtual_vector(const Container & p_container, MemberPtr p_member_ptr) :
        m_container(&p_container),
        m_member(p_member_ptr)
    {}

    // For mapping to a method
    template<class T = MemberPtr>
    auto operator[](std::enable_if_t<std::is_member_function_pointer<T>::value == true, const size_t> p_index) const
    {
        return ((*m_container)[p_index].*m_member)();
    }

    // For mapping to a member
    template<class T = MemberPtr>
    auto operator[](std::enable_if_t<std::is_member_function_pointer<T>::value == false, const size_t> p_index) const
    {
        return (*m_container)[p_index].*m_member;
    }

private:
    const Container * m_container;
    MemberPtr m_member;
};
</code>```

To test this, I've added a getter to the Elem class, for illustrative purposes.

```<code>struct Elem {
    int a, b;
    int foo() const { return a; }
    Elem(int a, int b) : a(a), b(b) {}
};
</code>```

And here is how it would be used :

```<code>int main() {
    std::vector<Elem> printme = { Elem(1,100), Elem(2,200), Elem(3,300) };
    std::vector<int> order = { 2,0,1 };

    {   // print member
        auto X = make_virtual_vector(printme, &Elem::a);
        print_in_order(order, X);
    }
    {   // print method
        auto X = make_virtual_vector(printme, &Elem::foo);
        print_in_order(order, X);
    }
}
</code>```

Body:
I have a function that takes a vector-like input. To simplify things, let's use this print_in_order function:

#include <iostream>
#include <vector>

template <typename vectorlike>
void print_in_order(std::vector<int> const & order,
                    vectorlike const & printme) {
    for (int i : order)
        std::cout << printme[i] << std::endl;
}

int main() {
    std::vector<int> printme = {100, 200, 300};
    std::vector<int> order = {2,0,1};
    print_in_order(order, printme);
}

Now I have a vector<Elem> and want to print a single integer member, Elem.a, for each Elem in the vector. I could do this by creating a new vector<int> (copying a for all Elems) and pass this to the print function - however, I feel like there must be a way to pass a "virtual" vector that, when operator[] is used on it, returns this only the member a. Note that I don't want to change the print_in_order function to access the member, it should remain general.

Is this possible, maybe with a lambda expression?
Full code below.

#include <iostream>
#include <vector>

struct Elem {
    int a,b;
    Elem(int a, int b) : a(a),b(b) {}
};

template <typename vectorlike>
void print_in_order(std::vector<int> const & order,
                    vectorlike const & printme) {
    for (int i : order)
        std::cout << printme[i] << std::endl;
}

int main() {
    std::vector<Elem> printme = {Elem(1,100), Elem(2,200), Elem(3,300)};
    std::vector<int> order = {2,0,1};

    // how to do this?
    virtual_vector X(printme) // behaves like a std::vector<Elem.a>
    print_in_order(order, X);
}

Body:
Using member pointers you can implement a proxy type that will allow you view a container of objects by substituting each object by one of it's members (see pointer to data member) or by one of it's getters (see pointer to member function). The first solution addresses only data members, the second accounts for both.

The container will necessarily need to know which container to use and which member to map, which will be provided at construction. The type of a pointer to member depends on the type of that member so it will have to be considered as an additional template argument.

template<class Container, class MemberPtr>
class virtual_vector
{
public:
    virtual_vector(const Container & p_container, MemberPtr p_member_ptr) :
        m_container(&p_container),
        m_member(p_member_ptr)
    {}

private:
    const Container * m_container;
    MemberPtr m_member;
};

Next, implement the operator[] operator, since you mentioned that it's how you wanted to access your elements. The syntax for dereferencing a member pointer can be surprising at first.

template<class Container, class MemberPtr>
class virtual_vector
{
public:
    virtual_vector(const Container & p_container, MemberPtr p_member_ptr) :
        m_container(&p_container),
        m_member(p_member_ptr)
    {}

    // Dispatch to the right get method
    auto operator[](const size_t p_index) const
    {
        return (*m_container)[p_index].*m_member;
    }

private:
    const Container * m_container;
    MemberPtr m_member;
};

To use this implementation, you would write something like this :

int main() {
    std::vector<Elem> printme = { Elem(1,100), Elem(2,200), Elem(3,300) };
    std::vector<int> order = { 2,0,1 };

    virtual_vector<decltype(printme), decltype(&Elem::a)> X(printme, &Elem::a);
    print_in_order(order, X);
}

This is a bit cumbersome since there is no template argument deduction happening. So lets add a free function to deduce the template arguments.

template<class Container, class MemberPtr>
virtual_vector<Container, MemberPtr>
make_virtual_vector(const Container & p_container, MemberPtr p_member_ptr)
{
    return{ p_container, p_member_ptr };
}

The usage becomes :

int main() {
    std::vector<Elem> printme = { Elem(1,100), Elem(2,200), Elem(3,300) };
    std::vector<int> order = { 2,0,1 };

    auto X = make_virtual_vector(printme, &Elem::a);
    print_in_order(order, X);
}

If you want to support member functions, it's a little bit more complicated. First, the syntax to dereference a data member pointer is slightly different from calling a function member pointer. You have to implement two versions of the operator[] and enable the correct one based on the member pointer type. Luckily the standard provides std::enable_if and std::is_member_function_pointer (both in the <type_trait> header) which allow us to do just that. The member function pointer requires you to specify the arguments to pass to the function (non in this case) and an extra set of parentheses around the expression that would evaluate to the function to call (everything before the list of arguments).

template<class Container, class MemberPtr>
class virtual_vector
{
public:
    virtual_vector(const Container & p_container, MemberPtr p_member_ptr) :
        m_container(&p_container),
        m_member(p_member_ptr)
    {}

    // For mapping to a method
    template<class T = MemberPtr>
    auto operator[](std::enable_if_t<std::is_member_function_pointer<T>::value == true, const size_t> p_index) const
    {
        return ((*m_container)[p_index].*m_member)();
    }

    // For mapping to a member
    template<class T = MemberPtr>
    auto operator[](std::enable_if_t<std::is_member_function_pointer<T>::value == false, const size_t> p_index) const
    {
        return (*m_container)[p_index].*m_member;
    }

private:
    const Container * m_container;
    MemberPtr m_member;
};

To test this, I've added a getter to the Elem class, for illustrative purposes.

struct Elem {
    int a, b;
    int foo() const { return a; }
    Elem(int a, int b) : a(a), b(b) {}
};

And here is how it would be used :

int main() {
    std::vector<Elem> printme = { Elem(1,100), Elem(2,200), Elem(3,300) };
    std::vector<int> order = { 2,0,1 };

    {   // print member
        auto X = make_virtual_vector(printme, &Elem::a);
        print_in_order(order, X);
    }
    {   // print method
        auto X = make_virtual_vector(printme, &Elem::foo);
        print_in_order(order, X);
    }
}


问:
How to set image alpha back to normal
I am trying to have an image of a check mark or an image of a cross appear whether the user got something wrong or right. I then want the image to fade, which I have done to a level that I like, but the problem is, is the image doesn't re-appear after it fades. The code in question is below:

```<code>private void aniCross(){
    cross.setVisibility(View.VISIBLE);
    cross.animate().alpha(0).setDuration(1000);
}
</code>```

Here I call an animate cross method that will set the visibility to visible (I set the image to be invisible at the start of the onCreate), and then it will animate the image. The animation takes the alpha to a value of 0 in a time interval of 1000ms. After the cross becomes invisible, I want it to be able to be displayed again and again for as long as it needs to, but still fading out after each time it is displayed.

I have tried doing things like cross.setAlpha(255) but that didn't seem to help the problem.

答:
```<code>private void aniCross(){
cross.setVisibility(View.VISIBLE);
cross.animate().alpha(0.0).setDuration(1000);}
</code>```

Title: How to set image alpha back to normal

Body:
I am trying to have an image of a check mark or an image of a cross appear whether the user got something wrong or right. I then want the image to fade, which I have done to a level that I like, but the problem is, is the image doesn't re-appear after it fades. The code in question is below:

private void aniCross(){
    cross.setVisibility(View.VISIBLE);
    cross.animate().alpha(0).setDuration(1000);
}

Here I call an animate cross method that will set the visibility to visible (I set the image to be invisible at the start of the onCreate), and then it will animate the image. The animation takes the alpha to a value of 0 in a time interval of 1000ms. After the cross becomes invisible, I want it to be able to be displayed again and again for as long as it needs to, but still fading out after each time it is displayed.

I have tried doing things like cross.setAlpha(255) but that didn't seem to help the problem.


问:
Restart Python Program after user changes
In my program, I have a config file which gets read on initialization and sets certain runtime variables. While the program is running a user can access and change these values in the config file through a menu I've created. Once these values have been modified I need the program to shut down and restart, so that it can run with the new config values.

I'm programming this in python and I am not sure how to go about doing this.

答:
You can either set a method to read the file for the new variables without restarting, or you can use

```<code>def restart_program():
    python = sys.executable
    os.execl(python, python, * sys.argv)
</code>```

as mentioned in this question

Body:
You can either set a method to read the file for the new variables without restarting, or you can use

def restart_program():
    python = sys.executable
    os.execl(python, python, * sys.argv)

as mentioned in this question


问:
TinyMCE: get values from a listbox in a modal window
I'm creating a TinyMCE Plugin for Wordpress. It has a textbox and a listbox field, both staying in a modal window.
Code below:

```<code>(function () {
    tinymce.create('tinymce.plugins.windowdata', {
        init : function(ed, url) {
            ed.addButton('showModal', {
                title: 'Show Modal',
                image: url + '/img/button.png',
                onclick: function () {
                    ed.windowManager.open({
                        title: 'Minestra',
                        body: [
                            {type: 'textbox', name: 'Field', label: 'Number', value: '', tooltip: 'Tooltip', maxLength: 3, classes: 'i1n'}, //textbox
                            {type: 'listbox', label: 'Listbox', classes: 'i1lb', values: [
                                {text: '', value: ''},
                                {text: 'Number', value: 'lone_number'},
                                {text: 'Bar', value: 'bar'},
                            ]}, //listbox
                        ],
                        onsubmit: function () {
                            var n1 = document.getElementsByClassName('mce-i1n')[0].value; //textbox value
                            var t1 = document.getElementsByClassName('mce-i1lb')[0].getElementsByTagName('button')[0].getElementsByClassName('mce-txt')[0].innerHTML; //listbox value

                            ed.execCommand('mceInsertContent', 0, n1+' is of type '+t1) //write contents
                        }
                    })
                }
            });
    }
)
</code>```

My question is about how to get the field values. What i did works very well with the textbox (the n1 var inside the onsubmit() method), but the listbox gets the same text that is shown to TinyMCE user (the text var in each listbox item).

What i want is a way to get the value instead; plus, i suppose i didn't get the right way to do it, not even with textbox. Anyone can help me? Thank you.

答:
Better way to generate content is:</p>

```<code>onsubmit: function (e) {
    // Insert content when the window form is submitted
              e.insertContent('Textbox content: ' + e.data.Field);
              e.insertContent('Listbox content: ' + e.data.Listbox)
}
</code>```

Body:
I'm creating a TinyMCE Plugin for Wordpress. It has a textbox and a listbox field, both staying in a modal window.
Code below:

(function () {
    tinymce.create('tinymce.plugins.windowdata', {
        init : function(ed, url) {
            ed.addButton('showModal', {
                title: 'Show Modal',
                image: url + '/img/button.png',
                onclick: function () {
                    ed.windowManager.open({
                        title: 'Minestra',
                        body: [
                            {type: 'textbox', name: 'Field', label: 'Number', value: '', tooltip: 'Tooltip', maxLength: 3, classes: 'i1n'}, //textbox
                            {type: 'listbox', label: 'Listbox', classes: 'i1lb', values: [
                                {text: '', value: ''},
                                {text: 'Number', value: 'lone_number'},
                                {text: 'Bar', value: 'bar'},
                            ]}, //listbox
                        ],
                        onsubmit: function () {
                            var n1 = document.getElementsByClassName('mce-i1n')[0].value; //textbox value
                            var t1 = document.getElementsByClassName('mce-i1lb')[0].getElementsByTagName('button')[0].getElementsByClassName('mce-txt')[0].innerHTML; //listbox value

                            ed.execCommand('mceInsertContent', 0, n1+' is of type '+t1) //write contents
                        }
                    })
                }
            });
    }
)

My question is about how to get the field values. What i did works very well with the textbox (the n1 var inside the onsubmit() method), but the listbox gets the same text that is shown to TinyMCE user (the text var in each listbox item).

What i want is a way to get the value instead; plus, i suppose i didn't get the right way to do it, not even with textbox. Anyone can help me? Thank you.

Body:
Better way to generate content is:

onsubmit: function (e) {
    // Insert content when the window form is submitted
              e.insertContent('Textbox content: ' + e.data.Field);
              e.insertContent('Listbox content: ' + e.data.Listbox)
}


问:
Use sed/awk to remove the last portion of a delimited-text column
I have a file with rows of values. The first column, a PacBio read ID, is a forward-slash-delimited value. I would like to modify the column by removing the final slash and values beyond it. Ideally the result would be stream-able (sed/awk, etc.) and would not rely on the number of forward slashes (i.e. the solution should work whether there is a single forward slash, or three, as below.) </p>

```<code># example row
m54151_170617_100137/4194626/10117_11723/0_1606 1257    1606

# desired row
m54151_170617_100137/4194626/10117_11723    1257    1606
</code>```

答:
Short sed solution:

```<code>sed 's~/[^/[:space:]]* ~ ~' file
</code>```

The exemplary output:

```<code>m54151_170617_100137/4194626/10117_11723 1257    1606
</code>```

~ - treated as sed subcommand separator

Body:
I have a file with rows of values. The first column, a PacBio read ID, is a forward-slash-delimited value. I would like to modify the column by removing the final slash and values beyond it. Ideally the result would be stream-able (sed/awk, etc.) and would not rely on the number of forward slashes (i.e. the solution should work whether there is a single forward slash, or three, as below.)

# example row
m54151_170617_100137/4194626/10117_11723/0_1606 1257    1606

# desired row
m54151_170617_100137/4194626/10117_11723    1257    1606

Body:
Short sed solution:

sed 's~/[^/[:space:]]* ~ ~' file

The exemplary output:

m54151_170617_100137/4194626/10117_11723 1257    1606

~ - treated as sed subcommand separator


问:
Adding resources with jwt_required?
I've created an API using flask, where the authentication is all working fine using flask_jwt_extended.

However if I add a resource that has a jwt_required decorator I get this error.

```<code>  File "/Library/Python/2.7/site-packages/flask_jwt/__init__.py", line 176, in decorator
    _jwt_required(realm or current_app.config['JWT_DEFAULT_REALM'])
KeyError: 'JWT_DEFAULT_REALM'
</code>```

Example resource:

```<code>class Endpoint(Resource):

    @jwt_required()
    def get(self):
        return {"State": "Success"}
</code>```

Initialising the app:

```<code>app = Flask(__name__)
api = Api(app)
</code>```

Adding the resource:

```<code>api.add_resource(resource_class, "/myEndpoint")
</code>```

The only way I can get it to work is to define the Endpoint class in the same file as the API.

I think I need someway to pass the Realm into the endpoint class and have use the optional parameter on jwt_required to set the Realm.

答:
Discovered the issue, in the resource I was importing the jwt_required:

```<code>from flask_jwt_extended import jwt_required
</code>```

However I needed to import jwt_required from the class that where JWT was initalized.

Title: Adding resources with jwt_required?

Body:
I've created an API using flask, where the authentication is all working fine using flask_jwt_extended.

However if I add a resource that has a jwt_required decorator I get this error.

  File "/Library/Python/2.7/site-packages/flask_jwt/__init__.py", line 176, in decorator
    _jwt_required(realm or current_app.config['JWT_DEFAULT_REALM'])
KeyError: 'JWT_DEFAULT_REALM'

Example resource:

class Endpoint(Resource):

    @jwt_required()
    def get(self):
        return {"State": "Success"}

Initialising the app:

app = Flask(__name__)
api = Api(app)

Adding the resource:

api.add_resource(resource_class, "/myEndpoint")

The only way I can get it to work is to define the Endpoint class in the same file as the API.

I think I need someway to pass the Realm into the endpoint class and have use the optional parameter on jwt_required to set the Realm.

Body:
Discovered the issue, in the resource I was importing the jwt_required:

from flask_jwt_extended import jwt_required

However I needed to import jwt_required from the class that where JWT was initalized.

ContentLicense: CC BY-SA 4.0


问:
Why GIL does not allow underperform threaded code?
Time taken for sequential code(seq.py),

```<code>import time

def countDown(n):
    while n > 0:
        n -= 1

n = 50000000
start = time.time()
countDown(n)
end = time.time()
print(end-start)
</code>```

is,

```<code>$ python3.6 seq.py
 4.209718227386475
$ python3.6 seq.py
 4.007786750793457
$ python3.6 seq.py
 4.0265843868255615
$
</code>```

Time taken for threaded version(usingThreads.py),

```<code>from threading import Thread
import time
def countDown(n):
    while n > 0:
        n -= 1

n = 50000000

t1 = Thread(target=countDown, args=(n//2,))
t1.daemon = True
t2 = Thread(target=countDown, args=(n//2,))
t2.daemon = True

start = time.time()
t1.start()
t2.start()
t1.join()
t2.join()
end = time.time()
print(end-start)
</code>```

is,

```<code>$ python3.6 usingThreads.py
 4.1083903312683105
$ python3.6 usingThreads.py
 4.093154668807983
$ python3.6 usingThreads.py
 4.092989921569824
$ python3.6 usingThreads.py
 4.116031885147095
$
</code>```

```<code>$ nproc
 4
$
</code>```

Python interpreter should not allow CPU bound threads to release GIL.

Expecting usingThreads.py to take more execution time than seq.py, because,

1) Any one thread is executing at a time, despite 4 cores

2) Time taken for failed attempts to acquire GIL from thread1 by thread2(and vice versa) should add delay in execution.

Edit:

With n=500000000

```<code>$ python3.6 seq.py
 40.22602105140686
$ python3.6 seq.py
 40.510098457336426
$ python3.6 seq.py
 40.04688620567322
$
$ python3.6 usingThreads.py
 40.91394829750061
$ python3.6 usingThreads.py
 42.30081081390381
$ python3.6 usingThreads.py
 41.328694581985474
</code>```

Question:

Why usingThread.py performs better than seq.py?

答:
both versions of the code did the same amount of work, so it took almost the same amount of time (both counted 50000000 times).

the gil makes it so they wont run in parallel ( so the threads version is not faster) but the overhead from the context switches is relativly small, so you got almost the same result.

there is an explanation here http://www.dabeaz.com/python/UnderstandingGIL.pdf

he is using the same example as you, and in this presentation he got a slower thread version when he used a computer with more than 1 cpus, and he explains it pretty well, when you use more than 1 cpus, you get more overhead (more attempts to context switch) witch make your program slower

Body:
Time taken for sequential code(seq.py),

import time

def countDown(n):
    while n > 0:
        n -= 1

n = 50000000
start = time.time()
countDown(n)
end = time.time()
print(end-start)

is,

$ python3.6 seq.py
 4.209718227386475
$ python3.6 seq.py
 4.007786750793457
$ python3.6 seq.py
 4.0265843868255615
$

Time taken for threaded version(usingThreads.py),

from threading import Thread
import time
def countDown(n):
    while n > 0:
        n -= 1

n = 50000000

t1 = Thread(target=countDown, args=(n//2,))
t1.daemon = True
t2 = Thread(target=countDown, args=(n//2,))
t2.daemon = True

start = time.time()
t1.start()
t2.start()
t1.join()
t2.join()
end = time.time()
print(end-start)

is,

$ python3.6 usingThreads.py
 4.1083903312683105
$ python3.6 usingThreads.py
 4.093154668807983
$ python3.6 usingThreads.py
 4.092989921569824
$ python3.6 usingThreads.py
 4.116031885147095
$

$ nproc
 4
$

Python interpreter should not allow CPU bound threads to release GIL.

Expecting usingThreads.py to take more execution time than seq.py, because,

1) Any one thread is executing at a time, despite 4 cores

2) Time taken for failed attempts to acquire GIL from thread1 by thread2(and vice versa) should add delay in execution.

Edit:

With n=500000000

$ python3.6 seq.py
 40.22602105140686
$ python3.6 seq.py
 40.510098457336426
$ python3.6 seq.py
 40.04688620567322
$
$ python3.6 usingThreads.py
 40.91394829750061
$ python3.6 usingThreads.py
 42.30081081390381
$ python3.6 usingThreads.py
 41.328694581985474

Question:

Why usingThread.py performs better than seq.py?


问:
TYPO3 cache behaviour with updated models
I have this weird behaviour from Typo3 6.2 LTS.
In my extension I have a Model with a FileReference Property. This property has a vaule != 0. This value does exist in sys_file_reference table.

Not the weird magic happens. If I try to access this file, I do only get a nullvalue instead of a FileReference- / FileObject.

We already cleared our cache (server and browser) but nothing. It's still null.

I appreciate every kind of help!

Greetz, Paddaels

答:
I remember it was always hard to make a 1:1 relation from a domain model to a FileReference. I suggest you to use existing patterns and work with a ObjectStorage for that purpose.

You can copy the neccessary TCA from the existing tca of the tt_content table (field image for example). The Property annotation should look like:

```<code>/**
 * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\Vendor\Extension\Domain\Model\FileReference>
 * @lazy
 * @cascade remove
 */
 protected $propName;
</code>```

Of course you have to create the FileReference Model in your own namespace. But you can extend the Extbase basemodel, so you dont have to write any methods.

To map your model to the sys_file_reference table you have to add some typoscript.

For that purpose create a ext_typoscript_setup.txt in your extensions folder and insert the following code (adjust namespace and modelname)

```<code>config.tx_extbase.persistence.classes {
    Vendor\Extension\Domain\Model\FileReference.mapping {
        tableName = sys_file_reference
    }
}
</code>```

After clearing the caches in the install tool (and making database migrations of course) it should work.

Explanations:

@lazy: Typo3 wont fetch all references at once, only if the property is accessed.

@cascade remove: Extbase will delete all sys_file_reference records related to your domain model once the model is deleted.

Body:
I remember it was always hard to make a 1:1 relation from a domain model to a FileReference. I suggest you to use existing patterns and work with a ObjectStorage for that purpose.

You can copy the neccessary TCA from the existing tca of the tt_content table (field image for example). The Property annotation should look like:

/**
 * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\Vendor\Extension\Domain\Model\FileReference>
 * @lazy
 * @cascade remove
 */
 protected $propName;

Of course you have to create the FileReference Model in your own namespace. But you can extend the Extbase basemodel, so you dont have to write any methods.

To map your model to the sys_file_reference table you have to add some typoscript.

For that purpose create a ext_typoscript_setup.txt in your extensions folder and insert the following code (adjust namespace and modelname)

config.tx_extbase.persistence.classes {
    Vendor\Extension\Domain\Model\FileReference.mapping {
        tableName = sys_file_reference
    }
}

After clearing the caches in the install tool (and making database migrations of course) it should work.

Explanations:

@lazy: Typo3 wont fetch all references at once, only if the property is accessed.

@cascade remove: Extbase will delete all sys_file_reference records related to your domain model once the model is deleted.


问:
Strange edge placement in Graphviz Dot
I have a module that automatically outputs (in dot format) functions written in some kind of assembly language (the IR of my compiler). The nodes are the basic blocks printed using the 'record' shape. The problem is that the edges take a strange route, for example:

```<code>digraph {
node [shape = record];
n0[label="{<name> entry | <body> store i, 0\nstore sum, 0\ngoto test | {<target> target}}"];
n1[label="{<name> test | <body> t2 = load i\nif t4, body,   done | {<true> true | <false> false}}"]
n2[label="{<name> body | <body> t5 = load sum\ngoto test | {<target> target}}"];
n3[color=firebrick3, label="{<name> done | <body> t9 = load sum\nret t9}}"];
n0:target:s -> n1:name:n
n1:true:s -> n2:name:n
n1:false:s -> n3:name:n
n2:target:s -> n1:name:n
}
</code>```

And an image:

What can I do so that the edge from 'target' to 'test' is placed on the left side?

答:
The simplest non-guru way is force that wayward link to attach on the "west" sides.

```<code>n2:target:w -> n1:name:w
</code>```

This might work okay for this case.  A more general way, but takes more thinking and coding, but would allow the edge to attach to the :s and :n if you desire that, is add an invisible node of size zero (color=white, or there might be a visibility attribute) and get from n2 to n1 using two edges.  Have the arrowhead on only one of them.  The invisible node would have to sit to the left of n1 or n2.   Alas, my graphvis-fu is not strong enough to create a working example; maybe someone else can create one.

Title: Strange edge placement in Graphviz Dot

Body:
I have a module that automatically outputs (in dot format) functions written in some kind of assembly language (the IR of my compiler). The nodes are the basic blocks printed using the 'record' shape. The problem is that the edges take a strange route, for example:

digraph {
node [shape = record];
n0[label="{<name> entry |  store i, 0\nstore sum, 0\ngoto test | {<target> target}}"];
n1[label="{<name> test |  t2 = load i\nif t4, body,   done | {<true> true | <false> false}}"]
n2[label="{<name> body |  t5 = load sum\ngoto test | {<target> target}}"];
n3[color=firebrick3, label="{<name> done |  t9 = load sum\nret t9}}"];
n0:target:s -> n1:name:n
n1:true:s -> n2:name:n
n1:false:s -> n3:name:n
n2:target:s -> n1:name:n
}

And an image:

What can I do so that the edge from 'target' to 'test' is placed on the left side?

Body:
The simplest non-guru way is force that wayward link to attach on the "west" sides.

n2:target:w -> n1:name:w

This might work okay for this case.  A more general way, but takes more thinking and coding, but would allow the edge to attach to the :s and :n if you desire that, is add an invisible node of size zero (color=white, or there might be a visibility attribute) and get from n2 to n1 using two edges.  Have the arrowhead on only one of them.  The invisible node would have to sit to the left of n1 or n2.   Alas, my graphvis-fu is not strong enough to create a working example; maybe someone else can create one.

ContentLicense: CC BY-SA 2.5


问:
Validating raw_input inside a for loop
I'm attempting to create a validation loop to check a user input against a defined list, but for some reason the code gets stuck in a loop perpetually asking the user to re-enter the value. I tested by adding a print command into the loop and the input data is being stored to the attributes dictionary, but it never seem to meet the == criteria to trigger the break from the for loop.

Here's my code so far, would really appreciate any suggestions on where I'm going amiss:

```<code>attributes = {'Name': 'None', 'Class': 'None', 'Strength': 3, 'Agility': 3, 'Wounds': 3, 'Intelligence': 3}

attributes['Name'] = raw_input('What is your character\'s name?')
attributes['Class'] = raw_input('Choose your character\'s class, enter Warrior, Mage, Ranger or Thief.')

#this is the section I am struggling with!
for values in attributes:
    if attributes['Class'] != "Warrior" or "Mage" or "Ranger" or "Thief":
        attributes['Class'] = raw_input('Please choose either Warrior, Mage, Ranger or Thief.')
        continue
    elif attributes['Class'] == "Warrior" or "Mage" or "Ranger" or "Thief":
        break

if attributes["Class"] == "Warrior":
    attributes["Strength"] += 1
    attributes["Wounds"] += 1
elif attributes["Class"] == "Mage":
    attributes["Intelligence"] += 2
elif attributes["Class"] == "Ranger":
    attributes["Strength"] += 1
    attributes["Agility"] += 1
elif attributes["Class"] == "Thief":
    attributes["Agility"] += 1
    attributes["Intelligence"] += 1

print
print 'Name: ' + attributes['Name']
print 'Class: ' + attributes['Class']
print 'STR: ' + str(attributes['Strength']), 'AGI: ' + str(attributes['Agility']), 'WOU: ' + str(attributes['Wounds']) ,'INT: ' + str(attributes['Intelligence'])
</code>```

答:
Your OR should be AND in the first IF. You would have to do them as:

```<code>if attributes['Class'] != "Warrior" and attributes['Class'] != "Mage" and attributes['Class'] != "Ranger" and attributes['Class'] != "Thief"
</code>```

An easier way to do this would to look for them in a list:

```<code>for values in attributes:
    if attributes['Class'] not in ["Warrior", "Mage", "Ranger", "Thief"]:
        attributes['Class'] = raw_input('Please choose either Warrior, Mage, Ranger or Thief.')
        continue
    elif attributes['Class'] in ["Warrior", "Mage", "Ranger", "Thief"]:
        break
</code>```

Title: Validating raw_input inside a for loop

Body:
I'm attempting to create a validation loop to check a user input against a defined list, but for some reason the code gets stuck in a loop perpetually asking the user to re-enter the value. I tested by adding a print command into the loop and the input data is being stored to the attributes dictionary, but it never seem to meet the == criteria to trigger the break from the for loop.

Here's my code so far, would really appreciate any suggestions on where I'm going amiss:

attributes = {'Name': 'None', 'Class': 'None', 'Strength': 3, 'Agility': 3, 'Wounds': 3, 'Intelligence': 3}

attributes['Name'] = raw_input('What is your character\'s name?')
attributes['Class'] = raw_input('Choose your character\'s class, enter Warrior, Mage, Ranger or Thief.')

#this is the section I am struggling with!
for values in attributes:
    if attributes['Class'] != "Warrior" or "Mage" or "Ranger" or "Thief":
        attributes['Class'] = raw_input('Please choose either Warrior, Mage, Ranger or Thief.')
        continue
    elif attributes['Class'] == "Warrior" or "Mage" or "Ranger" or "Thief":
        break

if attributes["Class"] == "Warrior":
    attributes["Strength"] += 1
    attributes["Wounds"] += 1
elif attributes["Class"] == "Mage":
    attributes["Intelligence"] += 2
elif attributes["Class"] == "Ranger":
    attributes["Strength"] += 1
    attributes["Agility"] += 1
elif attributes["Class"] == "Thief":
    attributes["Agility"] += 1
    attributes["Intelligence"] += 1

print
print 'Name: ' + attributes['Name']
print 'Class: ' + attributes['Class']
print 'STR: ' + str(attributes['Strength']), 'AGI: ' + str(attributes['Agility']), 'WOU: ' + str(attributes['Wounds']) ,'INT: ' + str(attributes['Intelligence'])

Body:
Your OR should be AND in the first IF. You would have to do them as:

if attributes['Class'] != "Warrior" and attributes['Class'] != "Mage" and attributes['Class'] != "Ranger" and attributes['Class'] != "Thief"

An easier way to do this would to look for them in a list:

for values in attributes:
    if attributes['Class'] not in ["Warrior", "Mage", "Ranger", "Thief"]:
        attributes['Class'] = raw_input('Please choose either Warrior, Mage, Ranger or Thief.')
        continue
    elif attributes['Class'] in ["Warrior", "Mage", "Ranger", "Thief"]:
        break


问:
jquery masonry does not adjust to mobile viewport
I have two installations of Jquery Masonry that as far as I am concerned are identical to each other. One of them adjusts to a mobile viewport and the other one doesn't.

When I do mobile troubleshooting, the styles that are written by Masonry are

The first:

```<code><div id="list_of_albums" style="position: relative; height: 484.656px;" class="masonry">
</code>```

The second:

```<code><div id="post-area" class="masonry" style="position: relative; height: 2424px;">
</code>```

Div structure is the same, Masonry install and initialization is the same, css is the same except for the class names.

```<code>// masonry customization
jQuery(document).ready(function($) {
    var post_area = $('#list_of_albums');
    post_area.imagesLoaded(function(){
        post_area.masonry({
        // options…
        columnWidth:1,
        isAnimated: true,
        animationOptions: {
            duration: 400,
            easing: 'linear',
            queue: false
        }
    });
    });
});
</code>```

I have removed media queries in both and it doesn't make any difference. One layout adjusts to the mobile window size and the other one doesn't.

CSS for the one that doesn't

masonry item:

```<code>.grid-album-item {

  width: 300px;
  float:left;
}
</code>```

CSS for the one that works:
 no styles for the container

style for the masonry item

```<code>#post-area .post {
  width: 300px;
  float: left;

}
</code>```

both can be viewed here -
one that works

one that doesn't

Note: both adjust fine to a narrow long desktop window, both display as one column only. It's just on mobile screens that I see the difference. Again, no media queries are in place for either of them.

Ideas appreciated. Ideas on how to troubleshoot this further is also appreciated.

答:
The answer is </p>

```<code><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
</code>```

Body:
I have two installations of Jquery Masonry that as far as I am concerned are identical to each other. One of them adjusts to a mobile viewport and the other one doesn't.

When I do mobile troubleshooting, the styles that are written by Masonry are

The first:

The second:

Div structure is the same, Masonry install and initialization is the same, css is the same except for the class names.

// masonry customization
jQuery(document).ready(function($) {
    var post_area = $('#list_of_albums');
    post_area.imagesLoaded(function(){
        post_area.masonry({
        // options…
        columnWidth:1,
        isAnimated: true,
        animationOptions: {
            duration: 400,
            easing: 'linear',
            queue: false
        }
    });
    });
});

I have removed media queries in both and it doesn't make any difference. One layout adjusts to the mobile window size and the other one doesn't.

CSS for the one that doesn't

masonry item:

.grid-album-item {

  width: 300px;
  float:left;
}

CSS for the one that works:
 no styles for the container

style for the masonry item

#post-area .post {
  width: 300px;
  float: left;

}

both can be viewed here -
one that works

one that doesn't

Note: both adjust fine to a narrow long desktop window, both display as one column only. It's just on mobile screens that I see the difference. Again, no media queries are in place for either of them.

Ideas appreciated. Ideas on how to troubleshoot this further is also appreciated.

Body:
The answer is

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">


问:
Generic Interfaces Extends?
Hi I have this question on Generic interfaces if someone could explain the answer to me in a detailed way ill be extremely grateful.

Inteface I

```<code>public interface I <T> {
void  f (T a);
}
</code>```

Interface J

```<code>public interface J <T extends I<T>>{
  void g(T b);
}
</code>```

Class A

```<code>public class A<T> implements J<T>{
    public void g(T b) {

    }
}
</code>```

The Code In Class A will give an error.
Could You explain to me why it gives an error?

Class A FIX

```<code>public class A<T extends I<T>> implements J<T>{
    public void g(T b) {

    }
}
</code>```

Could Someone explain to me why this code fixes the error?

Thanks in advance

答:
The reason is J <T extends I<T>>, so when you implement this interface you need to provide it with class T that extends I. But you cannot write it like this A<T> implements J<T extends I<T>>. I guess that it is not what you wanted because it creates unnecessary requirements for class T.

So what I would change is:

First: J <T extends I<T>> change to  J<T> extends I<T>. Now you have simpler type for J. And I think that this is what you need/want anyways.

Second: you should implement all methods, fi(T x) and fj(T x), so just do that.

And here is working example how it is done. Simple and working.

```<code>public class MyClass {

    public static void main(String[] args) throws Exception {
        A a = new A<String>();
        a.fi("foo");
        a.fj("bar");
        return;
    }

    public interface I<T> {
        void  fi(T t);
    }

    public interface J<T> extends I<T> {
      void fj(T t);
    }

    public static class A<T> implements J<T> {
        // it is static only to be accessible from main()
        public A() {
            // default constructor
        }

        public void fi(T t) {
            System.out.println("method from I, arg=" + b.toString());
        }

        public void fj(T t) {
            System.out.println("method from J, arg=" + b.toString());
        }
    }
}
</code>```

Output:

```<code>method from I, arg=foo
method from J, arg=bar
</code>```

Title: Generic Interfaces Extends?

Body:
Hi I have this question on Generic interfaces if someone could explain the answer to me in a detailed way ill be extremely grateful.

Inteface I

public interface I <T> {
void  f (T a);
}

Interface J

public interface J <T extends I<T>>{
  void g(T b);
}

Class A

public class A<T> implements J<T>{
    public void g(T b) {

    }
}

The Code In Class A will give an error.
Could You explain to me why it gives an error?

Class A FIX

public class A<T extends I<T>> implements J<T>{
    public void g(T b) {

    }
}

Could Someone explain to me why this code fixes the error?

Thanks in advance

Body:
The reason is J <T extends I<T>>, so when you implement this interface you need to provide it with class T that extends I. But you cannot write it like this A<T> implements J<T extends I<T>>. I guess that it is not what you wanted because it creates unnecessary requirements for class T.

So what I would change is:

First: J <T extends I<T>> change to  J<T> extends I<T>. Now you have simpler type for J. And I think that this is what you need/want anyways.

Second: you should implement all methods, fi(T x) and fj(T x), so just do that.

And here is working example how it is done. Simple and working.

public class MyClass {

    public static void main(String[] args) throws Exception {
        A a = new A<String>();
        a.fi("foo");
        a.fj("bar");
        return;
    }

    public interface I<T> {
        void  fi(T t);
    }

    public interface J<T> extends I<T> {
      void fj(T t);
    }

    public static class A<T> implements J<T> {
        // it is static only to be accessible from main()
        public A() {
            // default constructor
        }

        public void fi(T t) {
            System.out.println("method from I, arg=" + b.toString());
        }

        public void fj(T t) {
            System.out.println("method from J, arg=" + b.toString());
        }
    }
}

Output:

method from I, arg=foo
method from J, arg=bar


问:
Load multiple images from directory jquery
I want to load multiple images from a web folder into a bootstrap modal. I tried replacing strings in the image src which I succeeded. The issue is that I want to use the same button to load different images, based on the image folder. This is what I tried:

```<code><div class="container">
<h3>Ex1</h3>

<button id="image1" type="button" class="btn btn-info btn-lg" data-
toggle="modal" data-target="#myModal">Open Modal</button>

<h3>Ex2</h3>

<button id="image2" type="button" class="btn btn-info btn-lg" data-
toggle="modal" data-target="#myModal">Open Modal</button>

<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog" style="width:635px">

  <!-- Modal content-->
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal">×</button>
      <h4 class="modal-title">Modal Header</h4>
    </div>
    <div class="modal-body">
      <img src="https://www.jssor.com/demos/img/gallery/980x380/001.jpg" alt="Mountain View" style="width:600px; height: auto">
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    </div>
  </div>

</div>
</div>
 <script>
  $(document).ready(function(){

var img = $(".modal-body img");
var imgSelected;

$("button").click(function(){
if($("button") === $("#image1")){
imgSelected = "002";
}
else{
imgSelected = "003";
}

    img = $(".modal-body img");

    img.attr("src", img.attr("src").replace("001", imgSelected));

});

});
</script>
</div>
</code>```

This way is only showing imgSelected 003

答:
Instead of click event you can use:

show.bs.modal: This event fires immediately when the show instance method is called. If caused by a click, the clicked element is available as the relatedTarget property of the event.

In order to change the image source you need a regex pattern instead of a fixed pattern like 002 or 003 this because the next time you open the modal the src value changed.

Therefore, my proposal is:

$(document).ready(function(){
    $('#myModal').on('show.bs.modal', function(e) {
        var imgSelected;
        if (e.relatedTarget.id == "image1"){
            imgSelected = "002";
        } else {
            imgSelected = "003";
        }
        $(this).find(".modal-body img").attr('src', function(idx, attr) {
            return attr.replace(/(\/)\d+(\.jpg)$/, '$1' + imgSelected + '$2');
        })
        $(this.dataset.target).modal('show');
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="container">
    <h3>Ex1</h3>
    <button id="image1" type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal
    </button>
    <h3>Ex2</h3>

    <button id="image2" type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal
    </button>
    <div class="modal fade" id="myModal" role="dialog">
        <div class="modal-dialog" style="width:635px">

            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">×</button>
                    <h4 class="modal-title">Modal Header</h4>
                </div>
                <div class="modal-body">
                    <img src="https://www.jssor.com/demos/img/gallery/980x380/001.jpg" alt="Mountain View"
                         style="width:600px; height: auto">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>

        </div>
    </div>
</div></code>```

Body:
I want to load multiple images from a web folder into a bootstrap modal. I tried replacing strings in the image src which I succeeded. The issue is that I want to use the same button to load different images, based on the image folder. This is what I tried:

Ex1

<button id="image1" type="button" class="btn btn-info btn-lg" data-
toggle="modal" data-target="#myModal">Open Modal</button>

Ex2

<button id="image2" type="button" class="btn btn-info btn-lg" data-
toggle="modal" data-target="#myModal">Open Modal</button>

      <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

This way is only showing imgSelected 003

Body:
Instead of click event you can use:

show.bs.modal: This event fires immediately when the show instance method is called. If caused by a click, the clicked element is available as the relatedTarget property of the event.

In order to change the image source you need a regex pattern instead of a fixed pattern like 002 or 003 this because the next time you open the modal the src value changed.

Therefore, my proposal is:

$(document).ready(function(){
    $('#myModal').on('show.bs.modal', function(e) {
        var imgSelected;
        if (e.relatedTarget.id == "image1"){
            imgSelected = "002";
        } else {
            imgSelected = "003";
        }
        $(this).find(".modal-body img").attr('src', function(idx, attr) {
            return attr.replace(/(\/)\d+(\.jpg)$/, '$1' + imgSelected + '$2');
        })
        $(this.dataset.target).modal('show');
    });
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="container">
    <h3>Ex1</h3>
    <button id="image1" type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal
    </button>
    <h3>Ex2</h3>

    <button id="image2" type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal
    </button>
    <div class="modal fade" id="myModal" role="dialog">
        <div class="modal-dialog" style="width:635px">

            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Modal Header</h4>
                </div>
                <div class="modal-body">
                    <img src="https://www.jssor.com/demos/img/gallery/980x380/001.jpg" alt="Mountain View"
                         style="width:600px; height: auto">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>

        </div>
    </div>
</div>


问:
Swift - Array to TableView in macOS
I have some data form a JSON file which I have converted into:

```<code>var tempArray = [NSDictionary]()
</code>```

Here is what a sample of this data looks like:

```<code>(
    {
        active = y;
        "campaign_id" = "Sample ID 1";
        description = "Sample Text";
        "end_date_time" = "2017-10-01 00:00:00";
        "on_expiry" = ignore;
        "on_invalid_user" = reject;
        "start_date_time" = "2017-07-01 00:00:00";
        "voucher_code" = SAMPLEON1;
        "voucher_code_id" = "Sample ID 4";
    },
    {
        active = y;
        "campaign_id" = "Sample ID 2";
        description = "Sample Text";
        "end_date_time" = "2017-10-01 00:00:00";
        "on_expiry" = ignore;
        "on_invalid_user" = reject;
        "start_date_time" = "2017-06-02 00:00:00";
        "voucher_code" = SAMPLEOFF1;
        "voucher_code_id" = "Sample ID 5";
    }
)
</code>```

I have a NSTableView outlet set up, and it has columns with identifiers relative to the dictionary above:

```<code>@IBOutlet var voucherTableView: NSTableView!
</code>```

Once I run the voucherTableView.reloadData(); code in my Controller the table populates with the right amount of rows, but the data in the columns is all the same:

Here is my tableView func:

```<code>private func tableView(tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {

        let cellView = voucherTableView.make(withIdentifier: "cell", owner: self) as! NSTableCellView

        cellView.textField!.stringValue = self.values.object(at: row) as! String

        return cellView
    }
</code>```

Does anyone have any insight into how to get the data from my Array into the tableView on the reload command?

答:
If you set the column identifiers to match the keys in your dictionary, you should be able to do this:</p>

```<code>private func tableView(tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
    let cellView = voucherTableView.make(withIdentifier: "cell", owner: self) as! NSTableCellView

    cellView.textField!.stringValue = tempArray[row][tableColumn.identifier] as! String

    return cellView
}
</code>```

Title: Swift - Array to TableView in macOS

Body:
I have some data form a JSON file which I have converted into:

var tempArray = [NSDictionary]()

Here is what a sample of this data looks like:

(
    {
        active = y;
        "campaign_id" = "Sample ID 1";
        description = "Sample Text";
        "end_date_time" = "2017-10-01 00:00:00";
        "on_expiry" = ignore;
        "on_invalid_user" = reject;
        "start_date_time" = "2017-07-01 00:00:00";
        "voucher_code" = SAMPLEON1;
        "voucher_code_id" = "Sample ID 4";
    },
    {
        active = y;
        "campaign_id" = "Sample ID 2";
        description = "Sample Text";
        "end_date_time" = "2017-10-01 00:00:00";
        "on_expiry" = ignore;
        "on_invalid_user" = reject;
        "start_date_time" = "2017-06-02 00:00:00";
        "voucher_code" = SAMPLEOFF1;
        "voucher_code_id" = "Sample ID 5";
    }
)

I have a NSTableView outlet set up, and it has columns with identifiers relative to the dictionary above:

@IBOutlet var voucherTableView: NSTableView!

Once I run the voucherTableView.reloadData(); code in my Controller the table populates with the right amount of rows, but the data in the columns is all the same:

Here is my tableView func:

private func tableView(tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {

        let cellView = voucherTableView.make(withIdentifier: "cell", owner: self) as! NSTableCellView

        cellView.textField!.stringValue = self.values.object(at: row) as! String

        return cellView
    }

Does anyone have any insight into how to get the data from my Array into the tableView on the reload command?

Body:
If you set the column identifiers to match the keys in your dictionary, you should be able to do this:

private func tableView(tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
    let cellView = voucherTableView.make(withIdentifier: "cell", owner: self) as! NSTableCellView

    cellView.textField!.stringValue = tempArray[row][tableColumn.identifier] as! String

    return cellView
}


问:
networkx: set different alpha for each node?
I want to set a different alpha for each node. It's easy to set a different color for each node but alpha only excepts a single value. Anyone know how to do this? </p>

<p>(My goal is to have a color gradient from blue to red. If the value is below the midpoint it's blue and if above it's red. Alpha would set the gradient.)</p>

```<code>nx.draw_networkx_nodes(g,pos=pos,nodelist=nodelist,
node_color=node_color, alpha=1.0)
</code>```

答:
The alpha value will control transparency, not color.

If you are already supplying the node_color parameter, your nodes will be colored.

If you want them to go from blue to red based on those intensities, instead of alpha, use a colormap.  E.g. seismic colormap goes from red to blue.

```<code>nx.draw_networkx_nodes(g, pos=pos, nodelist=nodelist, node_color=node_color, cmp='seismic')
</code>```

EDIT:

I stumbled across some odd behavior trying to dig deeper into this.

I would have thought that networkx's plotting would behave like matplotlib's scatter plot, and accept rgba colors, allowing you to specify particular colors and transparency.  But when I call draw_networkx_nodes with an array of 4-tuples to denote rgba colors, it sets all alpha values to 1.

```<code>rgba_colors = np.zeros((5,4))
rgba_colors[:,0] = np.linspace(1,0,5) #red
rgba_colors[:,2] = np.linspace(0,1,5) #blue
rgba_colors[:,3] = np.linspace(0.1,1,5) #alpha values

plt.scatter([1,2,3,4,5],[1,2,3,4,5], color=rgba_colors)
</code>```

This plots some points with varying color and transparency.  But, if you try plotting with networkx, not only does the resulting plot have no transparency, the variable rgba_colors has actually been modified.

```<code>G = nx.complete_graph(5)
pos = {0: [0,0], 1: [1,1], 2: [2,2], 3: [2,1], 4: [2,3]}
nx.draw_networkx_nodes(G, pos=pos, node_color=rgba_colors)
print(rgba_colors)
</code>```

I'm not sure why this is happening.

Body:
I want to set a different alpha for each node. It's easy to set a different color for each node but alpha only excepts a single value. Anyone know how to do this?

(My goal is to have a color gradient from blue to red. If the value is below the midpoint it's blue and if above it's red. Alpha would set the gradient.)

nx.draw_networkx_nodes(g,pos=pos,nodelist=nodelist,
node_color=node_color, alpha=1.0)

Body:
The alpha value will control transparency, not color.

If you are already supplying the node_color parameter, your nodes will be colored.

If you want them to go from blue to red based on those intensities, instead of alpha, use a colormap.  E.g. seismic colormap goes from red to blue.

nx.draw_networkx_nodes(g, pos=pos, nodelist=nodelist, node_color=node_color, cmp='seismic')

EDIT:

I stumbled across some odd behavior trying to dig deeper into this.

I would have thought that networkx's plotting would behave like matplotlib's scatter plot, and accept rgba colors, allowing you to specify particular colors and transparency.  But when I call draw_networkx_nodes with an array of 4-tuples to denote rgba colors, it sets all alpha values to 1.

rgba_colors = np.zeros((5,4))
rgba_colors[:,0] = np.linspace(1,0,5) #red
rgba_colors[:,2] = np.linspace(0,1,5) #blue
rgba_colors[:,3] = np.linspace(0.1,1,5) #alpha values

plt.scatter([1,2,3,4,5],[1,2,3,4,5], color=rgba_colors)

This plots some points with varying color and transparency.  But, if you try plotting with networkx, not only does the resulting plot have no transparency, the variable rgba_colors has actually been modified.

G = nx.complete_graph(5)
pos = {0: [0,0], 1: [1,1], 2: [2,2], 3: [2,1], 4: [2,3]}
nx.draw_networkx_nodes(G, pos=pos, node_color=rgba_colors)
print(rgba_colors)

I'm not sure why this is happening.


问:
How to call method inside module (same method name in 2 different module) using class object - ruby
Consider i have 2 modules, both contains the function 'foo'. If i need to call the Module1's foo using object of the class which includes it, how i need to call?

Code sample:

```<code>    module Module1
      def foo
        puts 'first one'
      end
    end

    module Module2
      def foo
        puts 'second one'
      end
    end

  class ClassName
      include Module1
      include Module2

      def initialize
        Module1.instance_method(:foo).bind( self ).call
        Module2.instance_method(:foo).bind( self ).call
      end
    end

    cls = ClassName.new
</code>```

How to call the methods foo using the object 'cls' (If i need to call Module1's foo)?

Thanks!

答:
You can always make the modules both mixins (used via include or extend) and able to be called directly:

```<code>module Module1
  def foo
    puts 'first one'
  end

  extend self
end
</code>```

Then you can call Module1.foo whenever you want. Keep in mind when called this way it is in the context of the module, not any class that might have imported it.

That bind(self) trick is some serious hackery that should be avoided. In virtually every case you can re-architect your code to be more naturally expressed in more ordinary Ruby code.

Body:
Consider i have 2 modules, both contains the function 'foo'. If i need to call the Module1's foo using object of the class which includes it, how i need to call?

Code sample:

    module Module1
      def foo
        puts 'first one'
      end
    end

    module Module2
      def foo
        puts 'second one'
      end
    end

  class ClassName
      include Module1
      include Module2

      def initialize
        Module1.instance_method(:foo).bind( self ).call
        Module2.instance_method(:foo).bind( self ).call
      end
    end

    cls = ClassName.new

How to call the methods foo using the object 'cls' (If i need to call Module1's foo)?

Thanks!

Body:
You can always make the modules both mixins (used via include or extend) and able to be called directly:

module Module1
  def foo
    puts 'first one'
  end

  extend self
end

Then you can call Module1.foo whenever you want. Keep in mind when called this way it is in the context of the module, not any class that might have imported it.

That bind(self) trick is some serious hackery that should be avoided. In virtually every case you can re-architect your code to be more naturally expressed in more ordinary Ruby code.


问:
Exception Handling Error
When a method throws an exception, it searches through the call stack to find a handler right? In that sense, why is there an error with exep.second();? even though i've caught the exception in method second(). Here's my code:

```<code>public class Exep {
void first()throws IOException{
    throw new IOException("device error");
}
void second()throws IOException{
    try{
        first();
    }catch(Exception e){
        System.out.println(e);
    }
}
public static void main(String args[]){
    Exep exep = new Exep();
    exep.second();
}
</code>```

}

But the error disappears on adding  throws IOException to the main(). Why?

答:
IOException is a checked exception, and so must be handled in some way.  Adding throws IOException to main suppresses this behavior, but it is not good practice.

In second(), you catch all exceptions from first(), but you still include the throws IOException in the declaration of second().  This is not necessary, because you can guarantee that any exception thrown by first() will be caught and handled in second().

For more reading: Exceptions

Title: Exception Handling Error

Body:
When a method throws an exception, it searches through the call stack to find a handler right? In that sense, why is there an error with exep.second();? even though i've caught the exception in method second(). Here's my code:

public class Exep {
void first()throws IOException{
    throw new IOException("device error");
}
void second()throws IOException{
    try{
        first();
    }catch(Exception e){
        System.out.println(e);
    }
}
public static void main(String args[]){
    Exep exep = new Exep();
    exep.second();
}

}

But the error disappears on adding  throws IOException to the main(). Why?


问:
ARSORT an Array within an Array
How can I arsort the following array in PHP (by value)?

```<code>  $array = array
  (
    "pie" => array
                    (
                      "value" => "183"
                    ),
    "apple" => array
                    (
                      "value" => "032"
                    )
  );
</code>```

How could I sort this array so when I would loop through it and output the code that it would show PIE on the tap and APPLE below? I know how to do it when it's just an array, but I find it difficult to do it whenever I put an array within an array.

答:
Here was the original question.

How could I sort this array so when I would loop through it and output the code that it would show PIE on the tap and APPLE below?

```<code> usort($array, function($a, $b) {
     return $a['value'] - $b['value'];
 });
</code>```

This function should do it. If you need it reversed, just use function($b, $a).

The unknown factor was why he was asking for PIE first, then APPLE, but the sort field is the "value" field, not Pie and Apple. The solution is correct, but since it was unclear about the sort order, the values might have needed to be reversed. No problem - code given.

Title: ARSORT an Array within an Array

Body:
How can I arsort the following array in PHP (by value)?

  $array = array
  (
    "pie" => array
                    (
                      "value" => "183"
                    ),
    "apple" => array
                    (
                      "value" => "032"
                    )
  );

How could I sort this array so when I would loop through it and output the code that it would show PIE on the tap and APPLE below? I know how to do it when it's just an array, but I find it difficult to do it whenever I put an array within an array.

Body:
Here was the original question.

How could I sort this array so when I would loop through it and output the code that it would show PIE on the tap and APPLE below?

 usort($array, function($a, $b) {
     return $a['value'] - $b['value'];
 });

This function should do it. If you need it reversed, just use function($b, $a).

The unknown factor was why he was asking for PIE first, then APPLE, but the sort field is the "value" field, not Pie and Apple. The solution is correct, but since it was unclear about the sort order, the values might have needed to be reversed. No problem - code given.


问:
nth word in a text
how can I find the nth word in a text.

example:

```<code>my_txt("hello to you all" , 3)

all
</code>```

I don't wanna use any built in function ...and this is not a homework :D

答:
The obvious way to do it is:

```<code>"hello to you all".split()[3]
</code>```

The 80's way to do it is - that is, you have to walk the text, keeping note of the state of things you have found - it can become better than this, probably, but that is the idea. Perceive one has to use a lot o "built-in" functions either way. I just avoid the ones that make it straight like above.

```<code>def my_txt(text, target):
    count = 0
    last_was_space = False
    start = end = 0
    for index, letter in enumerate(text):
        if letter.isspace():
            if not last_was_space:
                 end = index
            last_was_space = True
        elif last_was_space:
            last_was_space = False
            count += 1
            if count > target:
                return text[start:end]
            elif count == target:
                start = index
    if count == target:
        return text[start:].strip()
    raise ValueError("Word not found")
</code>```

Title: nth word in a text

Body:
how can I find the nth word in a text.

example:

my_txt("hello to you all" , 3)

all

I don't wanna use any built in function ...and this is not a homework :D

Body:
The obvious way to do it is:

"hello to you all".split()[3]

The 80's way to do it is - that is, you have to walk the text, keeping note of the state of things you have found - it can become better than this, probably, but that is the idea. Perceive one has to use a lot o "built-in" functions either way. I just avoid the ones that make it straight like above.

def my_txt(text, target):
    count = 0
    last_was_space = False
    start = end = 0
    for index, letter in enumerate(text):
        if letter.isspace():
            if not last_was_space:
                 end = index
            last_was_space = True
        elif last_was_space:
            last_was_space = False
            count += 1
            if count > target:
                return text[start:end]
            elif count == target:
                start = index
    if count == target:
        return text[start:].strip()
    raise ValueError("Word not found")


问:
Adobe AIR read .sol file of Flash Player
I have a problem with Shared Objects files when I need read the .sol of the Flash Player with a Adobe AIR application.

The path of the Flash Player Shared Objects is:

```<code>C:/Users/%username%/AppData/Roaming/Macromedia/Flash Player/#SharedObjects/%randomnumber%/localhost/
</code>```

However, the path of the Adobe AIR Shared Objects is:

```<code>C:/Users/%username%/AppData/Roaming/%applicationname%/Local Store/#SharedObjects/#localhost/
</code>```

How can I read a Flash Player Shared Object with Adobe AIR application?

I tried:

Use the FileStream class to open the .sol file with the method readObject, but it does not work.

Copy the .sol file to the Adobe AIR Shared Object path and read with SharedObject, but the Error #2134: Cannot create SharedObject occurs.

What can I do to solve this?

答:
Flash Player/AIR does not have a built in way to read a .sol file directly. Of course the SharedObject class is the way you're supposed to access SO data, but it comes with restrictions and as you noted reads from a specific known path, it cannot be used to parse any .sol file directly. To read a .sol file you would need to use FileStream then parse the ByteArray directly following the .sol format... of course .sol uses AMF to store the data so readObject should work for a portion, but the file format (header, etc) is its own format that must be parsed out. Unfortunately finding good documentation on the format is very hard. There are a bunch of SO readers out there already, you might be able to use one as a reference:

http://blog.sephiroth.it/projects/shared-object-reader/

http://www.perlmonks.org/?node=657620

https://mariani.life/projects/minerva-air/

Body:
I have a problem with Shared Objects files when I need read the .sol of the Flash Player with a Adobe AIR application.

The path of the Flash Player Shared Objects is:

C:/Users/%username%/AppData/Roaming/Macromedia/Flash Player/#SharedObjects/%randomnumber%/localhost/

However, the path of the Adobe AIR Shared Objects is:

C:/Users/%username%/AppData/Roaming/%applicationname%/Local Store/#SharedObjects/#localhost/

How can I read a Flash Player Shared Object with Adobe AIR application?

I tried:

Use the FileStream class to open the .sol file with the method readObject, but it does not work.

Copy the .sol file to the Adobe AIR Shared Object path and read with SharedObject, but the Error #2134: Cannot create SharedObject occurs.

What can I do to solve this?


问:
bootstrap column height different
What I want to achieve using the grid system of Bootstrap 3 is the following:
Image what I imagine.
However, what I get with the normal row and col is the following:
This is what I get.

Is there a ways how I can make the first element of the second row fit exactly the first element of the first row by keeping the different heights and preferably by keeping the order of the elements.

答:
Maybe you are trying to do something like an application named
  Trello.

You can try that application first.

And you can do the styling with this reference : Trello CSS Guide

Title: bootstrap column height different


问:
R getting break values from histogram
When you make a histogram and define the breaks argument, R uses some functions to generate those breaks. I want to obtain the range values for the breaks generated by the histogram such that if I made the following histogram

```<code>hist(df$foo, breaks = 5)
</code>```

I want a list or data.frame that has the value ranges of the breaks:

```<code>list(c("1_lower"="<num>","1_upper"="<num2>","2_lower"="<num3>","2_upper"="<num4>"))
</code>```

I hope this is possible. Any help is greatly appreciated.

答: According to the documentation ?hist - if you set h<-hist(...), then h$breaks will give you the breakpoints.

Title: R getting break values from histogram

Body:
When you make a histogram and define the breaks argument, R uses some functions to generate those breaks. I want to obtain the range values for the breaks generated by the histogram such that if I made the following histogram

hist(df$foo, breaks = 5)

I want a list or data.frame that has the value ranges of the breaks:

list(c("1_lower"="<num>","1_upper"="<num2>","2_lower"="<num3>","2_upper"="<num4>"))

I hope this is possible. Any help is greatly appreciated.


问:
£ symbol encoded as =A3500 in email
I have a python script that parses email sent to a support address and stores it in a database. I got an error in my logs where it does the database insert
Incorrect string value: '\xA3500 w...
When I view the email in thunderbird I see the offending character rendered as a pound symbol £ and I can tell from context that that is indeed what was intended by the sender. But when I look at the raw eml file I see
=A3500 where the pound symbol should be.
The header in the email says  charset="iso-8859-1". I suspect the email as sent really doesn't conform to the spec, but I need to at least try to handle nonconforming emails rather than just erroring out.

Any ideas as to what is happening here and what to do about it? It must be possible to parse the email as intended, since thnderbird is doing it.

答:
I had based my code on the example here
https://docs.python.org/2/library/email-examples.html
of decoding a multipart message. It turns out that after I got a string with
body = part.get_payload(decode=True)
the "deocode" is just removing the content transfer encoding, I needed to add a second decode for the charset
                charset = part.get_content_charset()</p>

```<code>             body = body.decode(charset)
</code>```

Title: £ symbol encoded as =A3500 in email

Body:
I had based my code on the example here
https://docs.python.org/2/library/email-examples.html
of decoding a multipart message. It turns out that after I got a string with
body = part.get_payload(decode=True)
the "deocode" is just removing the content transfer encoding, I needed to add a second decode for the charset
                charset = part.get_content_charset()

             body = body.decode(charset)


问:
Selenium can't find element by id
I'm trying to create a simple test with Selenium. I used this code before and it worked fine. Somehow it stopped working when I changed to a new machine. I tried adding some code to wait until the element is visible, but it didn't work out.

I just try to find an element by its id, move to this element and click it. Somehow the code doesn't find the element at all.

Here is my code:

```<code>import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class SeleniumBasicTest {

  public static void main(String[] args) throws InterruptedException {

    DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
    caps.setCapability("ignoreZoomSetting", true);
    WebDriver driver = new InternetExplorerDriver(caps);

    driver.get("http://www.store.demoqa.com");

    WebDriverWait wait = new WebDriverWait(driver, 20);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("menu-item-33")));

    System.out.println("Successfully opened the website www.Store.Demoqa.com");

    WebElement producCategorytMenu = driver.findElement(By.id("menu-item-33"));

    Actions builder = new Actions(driver);
    builder.moveToElement(producCategorytMenu).perform();
    builder.click(producCategorytMenu).perform();

    Thread.sleep(5000);

    System.out.println("quiting test...");
    driver.quit();
  }

}
</code>```

This is the exception I'm receiving:

```<code>Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to find element with id == menu-item-33 (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 315 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.3.0', revision: 'b526bd5b41', time: '2017-03-07 19:26:04 +0000'
System info: host: 'CMTCLX62137', ip: '53.19.245.167', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_31'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{se:ieOptions={browserAttachTimeout=0, ie.enableFullPageScreenshot=true, enablePersistentHover=true, ie.forceCreateProcessApi=false, ie.forceShellWindowsApi=false, ignoreZoomSetting=true, ie.fileUploadDialogTimeout=3000, ie.useLegacyFileUploadDialogHandling=false, nativeEvents=true, ie.ensureCleanSession=false, elementScrollBehavior=0, ie.browserCommandLineSwitches=, requireWindowFocus=false, initialBrowserUrl=http://localhost:37146/, ignoreProtectedModeSettings=false, enableElementCacheCleanup=true}, browserName=internet explorer, pageLoadStrategy=normal, javascriptEnabled=true, version=11, platform=WINDOWS, unexpectedAlertBehaviour=dismiss}]
Session ID: 1e1740a9-00a2-4b92-814a-1979cfcef8e0
*** Element info: {Using=id, value=menu-item-33}
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:216)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:168)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:638)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:371)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:420)
    at org.openqa.selenium.By$ById.findElement(By.java:218)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
    at com.mytest.SeleniumBasicTest.main(SeleniumBasicTest.java:22)
</code>```

And here is the part of the HTML that has the menu:

```<code>    <nav class="group" id="main-nav">
            <ul id="menu-main-menu" class="menu"><li id="menu-item-15" class="menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-11 current_page_item menu-item-15"><span class="before"> </span><a href="http://store.demoqa.com/"><span></span>Home</a></li>
<li id="menu-item-33" class="menu-item menu-item-type-taxonomy menu-item-object-wpsc_product_category menu-item-has-children menu-item-33 has_children"><span class="before"> </span><a href="http://store.demoqa.com/products-page/product-category/"><span></span>Product Category</a>
<ul class="sub-menu">
    <li id="menu-item-34" class="menu-item menu-item-type-taxonomy menu-item-object-wpsc_product_category menu-item-34"><span class="before"> </span><a href="http://store.demoqa.com/products-page/product-category/accessories/"><span></span>Accessories</a></li>
    <li id="menu-item-35" class="menu-item menu-item-type-taxonomy menu-item-object-wpsc_product_category menu-item-35"><span class="before"> </span><a href="http://store.demoqa.com/products-page/product-category/imacs/"><span></span>iMacs</a></li>
    <li id="menu-item-36" class="menu-item menu-item-type-taxonomy menu-item-object-wpsc_product_category menu-item-36"><span class="before"> </span><a href="http://store.demoqa.com/products-page/product-category/ipads/"><span></span>iPads</a></li>
    <li id="menu-item-37" class="menu-item menu-item-type-taxonomy menu-item-object-wpsc_product_category menu-item-37"><span class="before"> </span><a href="http://store.demoqa.com/products-page/product-category/iphones/"><span></span>iPhones</a></li>
    <li id="menu-item-38" class="menu-item menu-item-type-taxonomy menu-item-object-wpsc_product_category menu-item-38"><span class="before"> </span><a href="http://store.demoqa.com/products-page/product-category/ipods/"><span></span>iPods</a></li>
    <li id="menu-item-39" class="menu-item menu-item-type-taxonomy menu-item-object-wpsc_product_category menu-item-39"><span class="before"> </span><a href="http://store.demoqa.com/products-page/product-category/macbooks/"><span></span>MacBooks</a></li>
</ul>
</li>
<li id="menu-item-16" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-16 has_children"><span class="before"> </span><a><span></span>#0 (no title)</a>
<ul class="sub-menu">
    <li id="menu-item-17" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-17"><span class="before"> </span><a><span></span>#0 (no title)</a></li>
    <li id="menu-item-18" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-18"><span class="before"> </span><a><span></span>#0 (no title)</a></li>
</ul>
</li>
<li id="menu-item-72" class="menu-item menu-item-type-taxonomy menu-item-object-wpsc_product_category menu-item-72"><span class="before"> </span><a href="http://store.demoqa.com/products-page/product-category/"><span></span>All Product</a></li>
</ul>
</code>```

Source: http://store.demoqa.com/

Anyone knows what might be happening?
I've read all the similar questions here on StackOverflow, tried every single option and still it doesn't find an element that is clearly there.

答:
Your code worked fine on my computer also. So my guess is that there is something different in the IE configuration. As you said your issues started when you switched computers. Which means that your current IE might not be configured. Also would be great if you could post your current IE version.

As you are using IE it needs to have set some of the settings before you can run tests on it.

Do you have "Enhanced Protected Mode" disabled in the IE settings? It is under advanced tab and under security. It has to be disabled

You must set the Protected Mode settings for each zone to be the same value.
Enabled protected mode for all 4 zones (Internet, Local Intranet, Trusted sites, Restricted sites)

Title: Selenium can't find element by id

Body:
I'm trying to create a simple test with Selenium. I used this code before and it worked fine. Somehow it stopped working when I changed to a new machine. I tried adding some code to wait until the element is visible, but it didn't work out.

I just try to find an element by its id, move to this element and click it. Somehow the code doesn't find the element at all.

Here is my code:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class SeleniumBasicTest {

  public static void main(String[] args) throws InterruptedException {

    DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
    caps.setCapability("ignoreZoomSetting", true);
    WebDriver driver = new InternetExplorerDriver(caps);

    driver.get("http://www.store.demoqa.com");

    WebDriverWait wait = new WebDriverWait(driver, 20);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("menu-item-33")));

    System.out.println("Successfully opened the website www.Store.Demoqa.com");

    WebElement producCategorytMenu = driver.findElement(By.id("menu-item-33"));

    Actions builder = new Actions(driver);
    builder.moveToElement(producCategorytMenu).perform();
    builder.click(producCategorytMenu).perform();

    Thread.sleep(5000);

    System.out.println("quiting test...");
    driver.quit();
  }

}

This is the exception I'm receiving:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to find element with id == menu-item-33 (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 315 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.3.0', revision: 'b526bd5b41', time: '2017-03-07 19:26:04 +0000'
System info: host: 'CMTCLX62137', ip: '53.19.245.167', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_31'
Driver info: org.openqa.selenium.ie.InternetExplorerDriver
Capabilities [{se:ieOptions={browserAttachTimeout=0, ie.enableFullPageScreenshot=true, enablePersistentHover=true, ie.forceCreateProcessApi=false, ie.forceShellWindowsApi=false, ignoreZoomSetting=true, ie.fileUploadDialogTimeout=3000, ie.useLegacyFileUploadDialogHandling=false, nativeEvents=true, ie.ensureCleanSession=false, elementScrollBehavior=0, ie.browserCommandLineSwitches=, requireWindowFocus=false, initialBrowserUrl=http://localhost:37146/, ignoreProtectedModeSettings=false, enableElementCacheCleanup=true}, browserName=internet explorer, pageLoadStrategy=normal, javascriptEnabled=true, version=11, platform=WINDOWS, unexpectedAlertBehaviour=dismiss}]
Session ID: 1e1740a9-00a2-4b92-814a-1979cfcef8e0
*** Element info: {Using=id, value=menu-item-33}
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:216)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:168)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:638)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:371)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementById(RemoteWebDriver.java:420)
    at org.openqa.selenium.By$ById.findElement(By.java:218)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
    at com.mytest.SeleniumBasicTest.main(SeleniumBasicTest.java:22)

And here is the part of the HTML that has the menu:

 Home

 Product Category

 Accessories

 iMacs

 iPads

 iPhones

 iPods

 MacBooks

 #0 (no title)

 #0 (no title)

 #0 (no title)

 All Product

Source: http://store.demoqa.com/

Anyone knows what might be happening?
I've read all the similar questions here on StackOverflow, tried every single option and still it doesn't find an element that is clearly there.