问:
up casting with CRTP using std::unique_ptr
I'm referring to this and use CRTP to track number of objects being created. But I run into compilation issue when I try to up cast Professor or Student class to Person class with std::unique_ptr. Please refer to snippet below, the link is here

```<code>#include <iostream>
#include <vector>
#include <memory>
#include <numeric>
#include <exception>

using namespace std;

template<typename T>
class Person
{
    public:
    Person(string Name="", int Age=0) : name(Name), age(Age)
    {
        ++cur_id;
    }
    virtual ~Person() {}
    virtual void getdata() = 0;
    virtual void putdata() = 0;

    protected:
    string name;
    int age;
    static int cur_id;
};

template<typename T> int Person<T>::cur_id = 0;

class Professor : public Person<Professor>
{
    public:
    Professor(string Name="", int Age=0, int Publications=0);
    ~Professor() {}
    void getdata() override;
    void putdata() override;

    protected:
    bool IsValidInput();

    private:
    int publications;
};

Professor::Professor(string Name, int Age, int Publications) try : Person(Name,Age), publications(Publications)
{
}

// Catch constructor that fails
catch(std::exception & e)
{
    std::cout<<"\n Exception - "<<e.what()<<std::endl;
    exit(1);
}

bool Professor::IsValidInput()
{
    if (name.empty() || (name.length() > 100))
    {
        return false;
    }

    if ( age <= 0 || age > 80 )
    {
        return false;
    }

    if ( publications <= 0 || publications > 1000)
    {
        return false;
    }

    return true;
}

void Professor::getdata()
{
    cout<< "Enter Name age publications" << endl;
    cin >> name >> age >> publications;

    if (!IsValidInput())
    {
        throw std::invalid_argument("wrong arguments");
    }
}

void Professor::putdata()
{
    cout << name << " " << age << " " << publications << " " << cur_id << endl;
}

class Student : public Person<Student>
{
    public:
    Student(string Name="", int Age=0, const vector<int> & Marks = vector<int>());
    ~Student() {}

    void getdata() override;
    void putdata() override;

    protected:
    bool IsValidInput();

    private:
    vector<int> marks;
    static const int TOTAL_MARKS = 5;
};

Student::Student(string Name, int Age, const vector<int> & Marks) try : Person(Name,Age), marks(Marks)
{
}

// Catch constructor that fails
catch(std::exception & e)
{
    std::cout<<"\n Exception - "<<e.what()<<std::endl;
    exit(1);
}

void Student::getdata()
{
    int mark = 0;
    cout<< "Enter Name age marks(5)" << endl;
    cin >> name >> age;

    for (size_t idx = 0; idx < TOTAL_MARKS; ++idx)
    {
        cin >> mark;
        marks.push_back(mark);
    }

    if (!IsValidInput())
    {
        throw std::invalid_argument("wrong arguments");
    }
}

void Student::putdata()
{
    cout << name << " " << age << " " << std::accumulate(marks.begin(),marks.end(),0) << " " << cur_id << endl;
}

bool Student::IsValidInput()
{
    if (name.empty() || (name.length() > 100))
    {
        return false;
    }

    if ( age <= 0 || age > 80 )
    {
        return false;
    }

    for (size_t idx = 0; idx < marks.size(); ++idx)
    {
        if ( marks[idx] < 0 || marks[idx] > 100 )
        {
            return false;
        }
    }
    return true;
}

int main()
{
    int totalObj = 0, type = 0;
    cout<< "Enter total obj : ";
    cin >> totalObj;

    std::vector<std::unique_ptr<Person<int>>> person;

    for (int idx = 0; idx < totalObj; ++idx)
    {
        cout<< "Enter obj type (1 or 2) : ";
        cin >> type;

        switch(type)
        {
            case 1:
            {
                std::unique_ptr<Person<int>> temp(std::make_unique<Professor>());
                temp->getdata();
                person.push_back(std::move(temp));
            }
            break;

            case 2:
            {
                std::unique_ptr<Person<int>> temp(std::make_unique<Student>());
                temp->getdata();
                person.push_back(std::move(temp));
            }
            break;

            default:
            break;
        }
    }

    for (auto itr = person.begin(); itr != person.end(); ++itr)
    {
        (*itr)->putdata();
    }

    return 0;
}
</code>```

The problem is in the switch case 1 and 2. I just use the int for sake instantiating the class Person. when I compile this I get the below errors

```<code>      In function 'int main()':
181:80: error: no matching function for call to 'std::unique_ptr<Person<int> >::unique_ptr(std::_MakeUniq<Professor>::__single_object)'
181:80: note: candidates are:
In file included from /usr/include/c++/4.9/memory:81:0,
                 from 3:
/usr/include/c++/4.9/bits/unique_ptr.h:228:2: note: template<class _Up, class> std::unique_ptr<_Tp, _Dp>::unique_ptr(std::auto_ptr<_Up>&&)
  unique_ptr(auto_ptr<_Up>&& __u) noexcept;
  ^
/usr/include/c++/4.9/bits/unique_ptr.h:228:2: note:   template argument deduction/substitution failed:
181:80: note:   'std::_MakeUniq<Professor>::__single_object {aka std::unique_ptr<Professor, std::default_delete<Professor> >}' is not derived from 'std::auto_ptr<_Up>'
In file included from /usr/include/c++/4.9/memory:81:0,
                 from 3:
</code>```

Please suggest how to upcast the Professor and Student to Person std::unique_ptr.

答:
Your problem is that Student and Professor are not extending Person<int>. In fact, Person<int> has nothing to do with Professor, and every Person<...> are totally different classes with no relation with each other.

If you want to hold all person types in a vector, you will need a polymorphic class that offers an interface on all Person<...>.

The solution for your problem would be to create an abstract person:

```<code>struct AbstractPerson {
    virtual void getdata() = 0;
    virtual void putdata() = 0;
    virtual ~AbstractPerson() = default;
};
</code>```

Then, make Person<T> inherit from that class:

```<code>template<typename T>
struct Person : AbstractPerson {
    // ...
};
</code>```

Then, replace that unrelated std::vector<Person<int>> by that:

```<code>std::vector<std::unique_ptr<AbstractPerson>> person;

// ...

person.emplace_back(std::make_unique<Student>()); // works!
</code>```

Here's a live version of your working, and slightly modernized code: Live on Coliru

Body:
I'm referring to this and use CRTP to track number of objects being created. But I run into compilation issue when I try to up cast Professor or Student class to Person class with std::unique_ptr. Please refer to snippet below, the link is here

#include <iostream>
#include <vector>
#include <memory>
#include <numeric>
#include <exception>

using namespace std;

template<typename T>
class Person
{
    public:
    Person(string Name="", int Age=0) : name(Name), age(Age)
    {
        ++cur_id;
    }
    virtual ~Person() {}
    virtual void getdata() = 0;
    virtual void putdata() = 0;

    protected:
    string name;
    int age;
    static int cur_id;
};

template<typename T> int Person<T>::cur_id = 0;

class Professor : public Person<Professor>
{
    public:
    Professor(string Name="", int Age=0, int Publications=0);
    ~Professor() {}
    void getdata() override;
    void putdata() override;

    protected:
    bool IsValidInput();

    private:
    int publications;
};

Professor::Professor(string Name, int Age, int Publications) try : Person(Name,Age), publications(Publications)
{
}

// Catch constructor that fails
catch(std::exception & e)
{
    std::cout<<"\n Exception - "<<e.what()<<std::endl;
    exit(1);
}

bool Professor::IsValidInput()
{
    if (name.empty() || (name.length() > 100))
    {
        return false;
    }

    if ( age <= 0 || age > 80 )
    {
        return false;
    }

    if ( publications <= 0 || publications > 1000)
    {
        return false;
    }

    return true;
}

void Professor::getdata()
{
    cout<< "Enter Name age publications" << endl;
    cin >> name >> age >> publications;

    if (!IsValidInput())
    {
        throw std::invalid_argument("wrong arguments");
    }
}

void Professor::putdata()
{
    cout << name << " " << age << " " << publications << " " << cur_id << endl;
}

class Student : public Person<Student>
{
    public:
    Student(string Name="", int Age=0, const vector<int> & Marks = vector<int>());
    ~Student() {}

    void getdata() override;
    void putdata() override;

    protected:
    bool IsValidInput();

    private:
    vector<int> marks;
    static const int TOTAL_MARKS = 5;
};

Student::Student(string Name, int Age, const vector<int> & Marks) try : Person(Name,Age), marks(Marks)
{
}

// Catch constructor that fails
catch(std::exception & e)
{
    std::cout<<"\n Exception - "<<e.what()<<std::endl;
    exit(1);
}

void Student::getdata()
{
    int mark = 0;
    cout<< "Enter Name age marks(5)" << endl;
    cin >> name >> age;

    for (size_t idx = 0; idx < TOTAL_MARKS; ++idx)
    {
        cin >> mark;
        marks.push_back(mark);
    }

    if (!IsValidInput())
    {
        throw std::invalid_argument("wrong arguments");
    }
}

void Student::putdata()
{
    cout << name << " " << age << " " << std::accumulate(marks.begin(),marks.end(),0) << " " << cur_id << endl;
}

bool Student::IsValidInput()
{
    if (name.empty() || (name.length() > 100))
    {
        return false;
    }

    if ( age <= 0 || age > 80 )
    {
        return false;
    }

    for (size_t idx = 0; idx < marks.size(); ++idx)
    {
        if ( marks[idx] < 0 || marks[idx] > 100 )
        {
            return false;
        }
    }
    return true;
}

int main()
{
    int totalObj = 0, type = 0;
    cout<< "Enter total obj : ";
    cin >> totalObj;

    std::vector<std::unique_ptr<Person<int>>> person;

    for (int idx = 0; idx < totalObj; ++idx)
    {
        cout<< "Enter obj type (1 or 2) : ";
        cin >> type;

        switch(type)
        {
            case 1:
            {
                std::unique_ptr<Person<int>> temp(std::make_unique<Professor>());
                temp->getdata();
                person.push_back(std::move(temp));
            }
            break;

            case 2:
            {
                std::unique_ptr<Person<int>> temp(std::make_unique<Student>());
                temp->getdata();
                person.push_back(std::move(temp));
            }
            break;

            default:
            break;
        }
    }

    for (auto itr = person.begin(); itr != person.end(); ++itr)
    {
        (*itr)->putdata();
    }

    return 0;
}

The problem is in the switch case 1 and 2. I just use the int for sake instantiating the class Person. when I compile this I get the below errors

      In function 'int main()':
181:80: error: no matching function for call to 'std::unique_ptr<Person<int> >::unique_ptr(std::_MakeUniq<Professor>::__single_object)'
181:80: note: candidates are:
In file included from /usr/include/c++/4.9/memory:81:0,
                 from 3:
/usr/include/c++/4.9/bits/unique_ptr.h:228:2: note: template<class _Up, class> std::unique_ptr<_Tp, _Dp>::unique_ptr(std::auto_ptr<_Up>&&)
  unique_ptr(auto_ptr<_Up>&& __u) noexcept;
  ^
/usr/include/c++/4.9/bits/unique_ptr.h:228:2: note:   template argument deduction/substitution failed:
181:80: note:   'std::_MakeUniq<Professor>::__single_object {aka std::unique_ptr<Professor, std::default_delete<Professor> >}' is not derived from 'std::auto_ptr<_Up>'
In file included from /usr/include/c++/4.9/memory:81:0,
                 from 3:

Please suggest how to upcast the Professor and Student to Person std::unique_ptr.

Body:
Your problem is that Student and Professor are not extending Person<int>. In fact, Person<int> has nothing to do with Professor, and every Person<...> are totally different classes with no relation with each other.

If you want to hold all person types in a vector, you will need a polymorphic class that offers an interface on all Person<...>.

The solution for your problem would be to create an abstract person:

struct AbstractPerson {
    virtual void getdata() = 0;
    virtual void putdata() = 0;
    virtual ~AbstractPerson() = default;
};

Then, make Person<T> inherit from that class:

template<typename T>
struct Person : AbstractPerson {
    // ...
};

Then, replace that unrelated std::vector<Person<int>> by that:

std::vector<std::unique_ptr<AbstractPerson>> person;

// ...

person.emplace_back(std::make_unique<Student>()); // works!

Here's a live version of your working, and slightly modernized code: Live on Coliru


来源: stackexchange

问:
Equals method of a linked list not working
I am having trouble implementing the remove method in the List class. I am first writing the objects out into a file, then I am retrieving those objects and putting them inside a linked list. However, when I try to check for equality by going over the entire linked list I get not matches even though I know for sure that object is in there. I can't even get .equals to work it seems.

```<code>package ProjectOne;

public class List<T> {
    private LLNode<T> list;
    private int numberOfNodes = 0;
    private LLNode<T> location;
    private LLNode<T> previous;
    protected boolean found;
    public List() {
        list = null;
    }
    public void add(T element) {
        if (numberOfNodes == 0) {
            list = new LLNode<T>(element);
            numberOfNodes++;
        }
        else {
        LLNode<T> newNode = new LLNode<T>(element);
        newNode.setLink(list);
        list = newNode;
        }
    }

    public void find(T target) {
        location = list;
        found = false;
        while(location !=null) {
            System.out.println(target.equals(location.getInfo()));
            if(location.getInfo().equals(target)) {
                found = true;
                return;
            }
            else {
                previous = location;
                location = location.getLink();
            }
        }
    }

    public boolean remove(T element) {
        this.find(element);
            if(found) {
                if(list == location) list = list.getLink();
                else previous.setLink(location.getLink());
            }
            return found;
    }

    public LLNode<T> getList() {
        return list;
    }

    public String toString() {
        LLNode<T> currentNode = list;
        String info = "";
        while(currentNode !=null) {
            info +=currentNode.getInfo();
            currentNode = currentNode.getLink();
        }
        return info;
    }

}
</code>```

These are one of many objects I am writing out to the file

```<code> Patient p1 = new Patient("Alex", "1123 metropolitan", new Date("11/20/1997"));
p1.setFirstVisit(new Date("11/20/1997"));
p1.setHeight(72);
p1.setLastVisit(new Date("11/20/1997"));
p1.setWeight(200);
out.writeObject(p1);

Patient p2 = new Patient("John", "200 avenue of americas", new Date("12/20/1999"));
p2.setFirstVisit(new Date("11/11/2005"));
p2.setHeight(5);
p2.setLastVisit(new Date("11/21/2010"));
p2.setWeight(150);
out.writeObject(p2);

Patient p3 = new Patient("Sarah", "Park avenue", new Date("09/07/1960"));
p3.setFirstVisit(new Date("05/11/1977"));
p3.setHeight(75);
p3.setLastVisit(new Date("01/21/2017"));
p3.setWeight(110);
out.writeObject(p3);

Patient p4 = new Patient("Malcolm", "56street", new Date("05/28/1977"));
p4.setFirstVisit(new Date("01/11/1990"));
p4.setHeight(75);
p4.setLastVisit(new Date("8/21/2016"));
p4.setWeight(155);
out.writeObject(p4);
</code>```

However, when I call System.out.println(list.remove(p1));
I get the output
false
false
false
false
false
with the last being the return result of the method and the first four just trying to debug.

答: Make sure that you override equals and hashcode methods in Patient class.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am having trouble implementing the remove method in the List class. I am first writing the objects out into a file, then I am retrieving those objects and putting them inside a linked list. However, when I try to check for equality by going over the entire linked list I get not matches even though I know for sure that object is in there. I can't even get .equals to work it seems.

package ProjectOne;

public class List<T> {
    private LLNode<T> list;
    private int numberOfNodes = 0;
    private LLNode<T> location;
    private LLNode<T> previous;
    protected boolean found;
    public List() {
        list = null;
    }
    public void add(T element) {
        if (numberOfNodes == 0) {
            list = new LLNode<T>(element);
            numberOfNodes++;
        }
        else {
        LLNode<T> newNode = new LLNode<T>(element);
        newNode.setLink(list);
        list = newNode;
        }
    }

    public void find(T target) {
        location = list;
        found = false;
        while(location !=null) {
            System.out.println(target.equals(location.getInfo()));
            if(location.getInfo().equals(target)) {
                found = true;
                return;
            }
            else {
                previous = location;
                location = location.getLink();
            }
        }
    }

    public boolean remove(T element) {
        this.find(element);
            if(found) {
                if(list == location) list = list.getLink();
                else previous.setLink(location.getLink());
            }
            return found;
    }

    public LLNode<T> getList() {
        return list;
    }

    public String toString() {
        LLNode<T> currentNode = list;
        String info = "";
        while(currentNode !=null) {
            info +=currentNode.getInfo();
            currentNode = currentNode.getLink();
        }
        return info;
    }

}

These are one of many objects I am writing out to the file

 Patient p1 = new Patient("Alex", "1123 metropolitan", new Date("11/20/1997"));
p1.setFirstVisit(new Date("11/20/1997"));
p1.setHeight(72);
p1.setLastVisit(new Date("11/20/1997"));
p1.setWeight(200);
out.writeObject(p1);

Patient p2 = new Patient("John", "200 avenue of americas", new Date("12/20/1999"));
p2.setFirstVisit(new Date("11/11/2005"));
p2.setHeight(5);
p2.setLastVisit(new Date("11/21/2010"));
p2.setWeight(150);
out.writeObject(p2);

Patient p3 = new Patient("Sarah", "Park avenue", new Date("09/07/1960"));
p3.setFirstVisit(new Date("05/11/1977"));
p3.setHeight(75);
p3.setLastVisit(new Date("01/21/2017"));
p3.setWeight(110);
out.writeObject(p3);

Patient p4 = new Patient("Malcolm", "56street", new Date("05/28/1977"));
p4.setFirstVisit(new Date("01/11/1990"));
p4.setHeight(75);
p4.setLastVisit(new Date("8/21/2016"));
p4.setWeight(155);
out.writeObject(p4);

However, when I call System.out.println(list.remove(p1));
I get the output
false
false
false
false
false
with the last being the return result of the method and the first four just trying to debug.


问:
creating a webservice that accepts a file (Stream) doesnt want other params
I have a File i want to upload to a Webservice, but it needs additional params, so I create some hidden fields with the associated name:value pairs to get pushed to the server request.  The issue though is the definition of the service.

[Error]

Operation 'NewImage' in contract 'IFormServices' has multiple request body parameters, one of which is a Stream. When the Stream is a parameter, there can be no other parameters in the body.

[interface]

```<code>[OperationContract]
    [WebInvoke(Method = "POST",
        ResponseFormat = WebMessageFormat.Json)]
    string NewImage(Stream data, string server,string datasource, string document, string image_id);
</code>```

[definition]

```<code>public string NewImage(Stream data, string server, string datasource, string document, string image_id)
        {
        //this should, similar to others, need a server, datasource, and some sort of document in which to append the images.
        WebClient wsb = new WebClient();
        string str = "_URL_";
        byte[] byte_data = new byte[data.Length];
        data.Read(byte_data, 0, byte_data.Length);
        byte[] response = wsb.UploadData(str,"POST",byte_data);
        string retVal = Convert.ToString(response);
        //want to return a JSON.serialized dictionary of:  given image_id + id returned from response.
        Dictionary<string, object> retDict = new Dictionary<string, object>();
        retDict["filename"] = image_id;
        retDict["id"] = "";
        //return new JavaScriptSerializer().Serialize(json);
        return "-1";
        }
</code>```

[javascript code]

```<code>var $form = $("<form />").attr({
                method: "POST",
                enctype: "multipart/form-data",
                target: "image_processing",
                action: "webservices/FormServices.svc/NewImage",
                id: "push_image_to_server"
            } ).appendTo( "body" );
            var im_id = $( this ).attr( "image_id" );
            $( this ).appendTo( "form#push_image_to_server" );
            $( "<input type='hidden' />" ).attr( { name: "server", value: BASE_URL } ).appendTo( $form );
            $( "<input type='hidden' />" ).attr( { name: "datasource", value: SELECTED_DATASOURCE } ).appendTo( $form );
            $( "<input type='hidden' />" ).attr( { name: "document", value: SELECTED_DOCUMENT } ).appendTo( $form );
            $( "<input type='hidden' />" ).attr( { name: "image_id", value: im_id } ).appendTo( $form );
            $("iframe#image_processing").bind("load", function (a,b,c) {
                console.log("SUCCESS", arguments);
                $( "iframe#image_processing" ).unbind( "load", function (a,b,c)
                {
                    console.log( arguments );
                    _IMAGE_UPLOADS_[a["filename"]] = a["id"];
                } );
                $( "form#push_image_to_server" ).remove();
            } );
</code>```

So i am trying to figure out a way to send up 4 strings + a file to the server.

How would this be done?

edit: put error code at top.

答:
How about using HttpRequest.QueryString[]?

```<code>[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "NewImage")]
string NewImage(Stream data);
</code>```

you call it through the URL like:

```<code>\NewImage?server={server}&datasource={datasource}&document={doc}&image_id={id}
</code>```

Then in your code:

```<code>public string NewImage(Stream imgStream)
{
    var request = System.Web.HttpContext.Current.Request;

    var server= request.QueryString["server"];
    var datasource = request.QueryString["datasource"];
    var document= request.QueryString["document"];
    var image_id= request.QueryString["image_id"];

    ...
}
</code>```

I'd been looking for something like this for a while, and just stumbled across it today.

Body:
I have a File i want to upload to a Webservice, but it needs additional params, so I create some hidden fields with the associated name:value pairs to get pushed to the server request.  The issue though is the definition of the service.

[Error]

Operation 'NewImage' in contract 'IFormServices' has multiple request body parameters, one of which is a Stream. When the Stream is a parameter, there can be no other parameters in the body.

[interface]

[OperationContract]
    [WebInvoke(Method = "POST",
        ResponseFormat = WebMessageFormat.Json)]
    string NewImage(Stream data, string server,string datasource, string document, string image_id);

[definition]

public string NewImage(Stream data, string server, string datasource, string document, string image_id)
        {
        //this should, similar to others, need a server, datasource, and some sort of document in which to append the images.
        WebClient wsb = new WebClient();
        string str = "_URL_";
        byte[] byte_data = new byte[data.Length];
        data.Read(byte_data, 0, byte_data.Length);
        byte[] response = wsb.UploadData(str,"POST",byte_data);
        string retVal = Convert.ToString(response);
        //want to return a JSON.serialized dictionary of:  given image_id + id returned from response.
        Dictionary<string, object> retDict = new Dictionary<string, object>();
        retDict["filename"] = image_id;
        retDict["id"] = "";
        //return new JavaScriptSerializer().Serialize(json);
        return "-1";
        }

[javascript code]

var $form = $("<form />").attr({
                method: "POST",
                enctype: "multipart/form-data",
                target: "image_processing",
                action: "webservices/FormServices.svc/NewImage",
                id: "push_image_to_server"
            } ).appendTo( "body" );
            var im_id = $( this ).attr( "image_id" );
            $( this ).appendTo( "form#push_image_to_server" );
            $( "<input type='hidden' />" ).attr( { name: "server", value: BASE_URL } ).appendTo( $form );
            $( "<input type='hidden' />" ).attr( { name: "datasource", value: SELECTED_DATASOURCE } ).appendTo( $form );
            $( "<input type='hidden' />" ).attr( { name: "document", value: SELECTED_DOCUMENT } ).appendTo( $form );
            $( "<input type='hidden' />" ).attr( { name: "image_id", value: im_id } ).appendTo( $form );
            $("iframe#image_processing").bind("load", function (a,b,c) {
                console.log("SUCCESS", arguments);
                $( "iframe#image_processing" ).unbind( "load", function (a,b,c)
                {
                    console.log( arguments );
                    _IMAGE_UPLOADS_[a["filename"]] = a["id"];
                } );
                $( "form#push_image_to_server" ).remove();
            } );

So i am trying to figure out a way to send up 4 strings + a file to the server.

How would this be done?

edit: put error code at top.

Body:
How about using HttpRequest.QueryString[]?

[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "NewImage")]
string NewImage(Stream data);

you call it through the URL like:

\NewImage?server={server}&datasource={datasource}&document={doc}&image_id={id}

Then in your code:

public string NewImage(Stream imgStream)
{
    var request = System.Web.HttpContext.Current.Request;

    var server= request.QueryString["server"];
    var datasource = request.QueryString["datasource"];
    var document= request.QueryString["document"];
    var image_id= request.QueryString["image_id"];

    ...
}

I'd been looking for something like this for a while, and just stumbled across it today.


问:
Adding a new Extension to my generated certificate
I need to add a new Extension of OID 1.3.6.1.5.5.7.1.26 in my certificate. I got this OID extension in my certificate but with the following error:

Certificate Extensions: 10
  [1]: ObjectId: 1.3.6.1.5.5.7.1.26 Criticality=false

  Extension unknown: DER encoded OCTET string =

  0000: 04 0C 30 0A 13 08 33 39   20 64 63 20 32 62        ..0...

  39 dc 2b

I want this OID to be recognized similar to other extensions like AuthorityInfoAccess, etc.

Do I need to edit the jar of Bouncy Castle X509 class?

Im using ACME4j as a client and Letsencrypt Boulder as my server.

Here is the CSR Builder code for signing up the certificate.

```<code>public void sign(KeyPair keypair) throws IOException {
    //Security.addProvider(new BouncyCastleProvider());
    Objects.requireNonNull(keypair, "keypair");
    if (namelist.isEmpty()) {
        throw new IllegalStateException("No domain was set");
    }

    try {
        GeneralName[] gns = new GeneralName[namelist.size()];
        for (int ix = 0; ix < namelist.size(); ix++) {
            gns[ix] = new GeneralName(GeneralName.dNSName,namelist.get(ix));
        }
        SignatureAlgorithmIdentifierFinder algFinder = new
                DefaultSignatureAlgorithmIdentifierFinder();
        GeneralNames subjectAltName = new GeneralNames(gns);

        PKCS10CertificationRequestBuilder p10Builder = new     JcaPKCS10CertificationRequestBuilder(namebuilder.build(), keypair.getPublic());

        ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
        extensionsGenerator.addExtension(Extension.subjectAlternativeName,     false, subjectAltName);
        //extensionsGenerator.addExtension(Extension.authorityInfoAccess,         true, subjectAltName);
        //extensionsGenerator.addExtension(new ASN1ObjectIdentifier("TBD"),     false, subjectAltName);
        //extensionsGenerator.addExtension(new     ASN1ObjectIdentifier("1.3.6.1.5.5.7.1.24"), false, subjectAltName);
        extensionsGenerator.addExtension(new     ASN1ObjectIdentifier("1.3.6.1.5.5.7.1.26").intern(), false, subjectAltName);
        //extentionsGenerator.addExtension();
            p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,     extensionsGenerator.generate());

        PrivateKey pk = keypair.getPrivate();
        /*JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(
                        pk instanceof ECKey ? EC_SIGNATURE_ALG :     EC_SIGNATURE_ALG);
        ContentSigner signer = csBuilder.build(pk);*/

        if(pk instanceof ECKey)
        {
            AlgorithmIdentifier sigAlg = algFinder.find("SHA1withECDSA");
              AlgorithmIdentifier digAlg = new     DefaultDigestAlgorithmIdentifierFinder().
                    find(sigAlg);
            ContentSigner signer = new     JcaContentSignerBuilder("SHA256with"+pk.getAlgorithm()).setProvider(BOUNCY_CASTL    E_PROVIDER).build(keypair.getPrivate());

            csr=p10Builder.build(signer);
            System.out.println("ZIPED CSR ECDSA: "+csr);
        }
        else
        {
            ContentSigner signer = new     JcaContentSignerBuilder("SHA256with"+pk.getAlgorithm()).build(keypair.getPrivate    ());
            csr = p10Builder.build(signer);
            System.out.println("ZIPED CSR RSA: "+csr);
        }

        //csr = p10Builder.build(signer);
    } catch (Exception ex) {
        ex.printStackTrace();;
    }
}
</code>```

答:
Right now, for testing purpose , Im just passing a string value from my CA Boulder. So to read that, this is the custom ASN1 Object STructure for TNAUthList.

```<code>public class TNAuthorizationList extends ASN1Object implements ASN1Choice{

public static final int spc                     = 0;
public static final int range                   = 1;

private ASN1Encodable obj;
private int           tag;

public TNAuthorizationList(
        int           tag,
        ASN1Encodable name)
    {
        this.obj = name;
        this.tag = tag;
    }

public TNAuthorizationList(
        int       tag,
        String    name)
    {
        this.tag = tag;

        if (tag == spc)
        {
            this.obj = new DERIA5String(name);
        }
        else if (tag == range)
        {
            this.obj = new ASN1ObjectIdentifier(name);
        }
        else
        {
            throw new IllegalArgumentException("can't process String for tag: " + tag);
        }
    }

public static TNAuthorizationList getInstance(
        Object obj)
    {
        if (obj == null || obj instanceof TNAuthorizationList)
        {
            return (TNAuthorizationList)obj;
        }

        if (obj instanceof ASN1TaggedObject)
        {
            ASN1TaggedObject    tagObj = (ASN1TaggedObject)obj;
            int                 tag = tagObj.getTagNo();

            switch (tag)
            {
            case spc:
                return new TNAuthorizationList(tag, DERIA5String.getInstance(tagObj, false));
            }
        }

        if (obj instanceof byte[])
        {
            try
            {
                return getInstance(ASN1Primitive.fromByteArray((byte[])obj));
            }
            catch (IOException e)
            {
                throw new IllegalArgumentException("unable to parse encoded general name");
            }
        }

        throw new IllegalArgumentException("unknown object in getInstance: " + obj.getClass().getName());
    }

public static TNAuthorizationList getInstance(
        ASN1TaggedObject tagObj,
        boolean          explicit)
    {
        return TNAuthorizationList.getInstance(ASN1TaggedObject.getInstance(tagObj, true));
    }

    public int getTagNo()
    {
        return tag;
    }

    public ASN1Encodable getSpc()
    {
        return obj;
    }

    public String toString()
    {
        StringBuffer buf = new StringBuffer();

        buf.append(tag);
        buf.append(": ");
        switch (tag)
        {
        case spc:
            buf.append(DERIA5String.getInstance(obj).getString());
            break;
        default:
            buf.append(obj.toString());
        }
        return buf.toString();
    }

/**
*TNEntry ::= CHOICE {
*       spc   [0] ServiceProviderCodeList,
*       range [1] TelephoneNumberRange,
*       one       E164Number
*       }
*/
@Override
public ASN1Primitive toASN1Primitive() {
    // TODO Auto-generated method stub
    return new DERTaggedObject(false, tag, obj);
}
</code>```

}

As You suggested I have passed the OID value to X509Util class and printed the Output.

```<code>ASN1Object o = X509ExtensionUtil.fromExtensionValue(cert.getExtensionValue("1.3.6.1.5.5.7.1.26"));
    System.out.println("ASN1 Object: "+o);
    System.out.println("get Class "+o.getClass());
</code>```

and the O/P is

```<code>ASN1 Object: [SPID : 39 dc 2b]
get Class class org.bouncycastle.asn1.DLSequence
</code>```

Is this fine. How do i parse this with my custom ASN1 Structure?

Body:
I need to add a new Extension of OID 1.3.6.1.5.5.7.1.26 in my certificate. I got this OID extension in my certificate but with the following error:

Certificate Extensions: 10
  [1]: ObjectId: 1.3.6.1.5.5.7.1.26 Criticality=false

  Extension unknown: DER encoded OCTET string =

  0000: 04 0C 30 0A 13 08 33 39   20 64 63 20 32 62        ..0...

  39 dc 2b

I want this OID to be recognized similar to other extensions like AuthorityInfoAccess, etc.

Do I need to edit the jar of Bouncy Castle X509 class?

Im using ACME4j as a client and Letsencrypt Boulder as my server.

Here is the CSR Builder code for signing up the certificate.

public void sign(KeyPair keypair) throws IOException {
    //Security.addProvider(new BouncyCastleProvider());
    Objects.requireNonNull(keypair, "keypair");
    if (namelist.isEmpty()) {
        throw new IllegalStateException("No domain was set");
    }

    try {
        GeneralName[] gns = new GeneralName[namelist.size()];
        for (int ix = 0; ix < namelist.size(); ix++) {
            gns[ix] = new GeneralName(GeneralName.dNSName,namelist.get(ix));
        }
        SignatureAlgorithmIdentifierFinder algFinder = new
                DefaultSignatureAlgorithmIdentifierFinder();
        GeneralNames subjectAltName = new GeneralNames(gns);

        PKCS10CertificationRequestBuilder p10Builder = new     JcaPKCS10CertificationRequestBuilder(namebuilder.build(), keypair.getPublic());

        ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
        extensionsGenerator.addExtension(Extension.subjectAlternativeName,     false, subjectAltName);
        //extensionsGenerator.addExtension(Extension.authorityInfoAccess,         true, subjectAltName);
        //extensionsGenerator.addExtension(new ASN1ObjectIdentifier("TBD"),     false, subjectAltName);
        //extensionsGenerator.addExtension(new     ASN1ObjectIdentifier("1.3.6.1.5.5.7.1.24"), false, subjectAltName);
        extensionsGenerator.addExtension(new     ASN1ObjectIdentifier("1.3.6.1.5.5.7.1.26").intern(), false, subjectAltName);
        //extentionsGenerator.addExtension();
            p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,     extensionsGenerator.generate());

        PrivateKey pk = keypair.getPrivate();
        /*JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(
                        pk instanceof ECKey ? EC_SIGNATURE_ALG :     EC_SIGNATURE_ALG);
        ContentSigner signer = csBuilder.build(pk);*/

        if(pk instanceof ECKey)
        {
            AlgorithmIdentifier sigAlg = algFinder.find("SHA1withECDSA");
              AlgorithmIdentifier digAlg = new     DefaultDigestAlgorithmIdentifierFinder().
                    find(sigAlg);
            ContentSigner signer = new     JcaContentSignerBuilder("SHA256with"+pk.getAlgorithm()).setProvider(BOUNCY_CASTL    E_PROVIDER).build(keypair.getPrivate());

            csr=p10Builder.build(signer);
            System.out.println("ZIPED CSR ECDSA: "+csr);
        }
        else
        {
            ContentSigner signer = new     JcaContentSignerBuilder("SHA256with"+pk.getAlgorithm()).build(keypair.getPrivate    ());
            csr = p10Builder.build(signer);
            System.out.println("ZIPED CSR RSA: "+csr);
        }

        //csr = p10Builder.build(signer);
    } catch (Exception ex) {
        ex.printStackTrace();;
    }
}

Body:
Right now, for testing purpose , Im just passing a string value from my CA Boulder. So to read that, this is the custom ASN1 Object STructure for TNAUthList.

public class TNAuthorizationList extends ASN1Object implements ASN1Choice{

public static final int spc                     = 0;
public static final int range                   = 1;

private ASN1Encodable obj;
private int           tag;

public TNAuthorizationList(
        int           tag,
        ASN1Encodable name)
    {
        this.obj = name;
        this.tag = tag;
    }

public TNAuthorizationList(
        int       tag,
        String    name)
    {
        this.tag = tag;

        if (tag == spc)
        {
            this.obj = new DERIA5String(name);
        }
        else if (tag == range)
        {
            this.obj = new ASN1ObjectIdentifier(name);
        }
        else
        {
            throw new IllegalArgumentException("can't process String for tag: " + tag);
        }
    }

public static TNAuthorizationList getInstance(
        Object obj)
    {
        if (obj == null || obj instanceof TNAuthorizationList)
        {
            return (TNAuthorizationList)obj;
        }

        if (obj instanceof ASN1TaggedObject)
        {
            ASN1TaggedObject    tagObj = (ASN1TaggedObject)obj;
            int                 tag = tagObj.getTagNo();

            switch (tag)
            {
            case spc:
                return new TNAuthorizationList(tag, DERIA5String.getInstance(tagObj, false));
            }
        }

        if (obj instanceof byte[])
        {
            try
            {
                return getInstance(ASN1Primitive.fromByteArray((byte[])obj));
            }
            catch (IOException e)
            {
                throw new IllegalArgumentException("unable to parse encoded general name");
            }
        }

        throw new IllegalArgumentException("unknown object in getInstance: " + obj.getClass().getName());
    }

public static TNAuthorizationList getInstance(
        ASN1TaggedObject tagObj,
        boolean          explicit)
    {
        return TNAuthorizationList.getInstance(ASN1TaggedObject.getInstance(tagObj, true));
    }

    public int getTagNo()
    {
        return tag;
    }

    public ASN1Encodable getSpc()
    {
        return obj;
    }

    public String toString()
    {
        StringBuffer buf = new StringBuffer();

        buf.append(tag);
        buf.append(": ");
        switch (tag)
        {
        case spc:
            buf.append(DERIA5String.getInstance(obj).getString());
            break;
        default:
            buf.append(obj.toString());
        }
        return buf.toString();
    }

/**
*TNEntry ::= CHOICE {
*       spc   [0] ServiceProviderCodeList,
*       range [1] TelephoneNumberRange,
*       one       E164Number
*       }
*/
@Override
public ASN1Primitive toASN1Primitive() {
    // TODO Auto-generated method stub
    return new DERTaggedObject(false, tag, obj);
}

}

As You suggested I have passed the OID value to X509Util class and printed the Output.

ASN1Object o = X509ExtensionUtil.fromExtensionValue(cert.getExtensionValue("1.3.6.1.5.5.7.1.26"));
    System.out.println("ASN1 Object: "+o);
    System.out.println("get Class "+o.getClass());

and the O/P is

ASN1 Object: [SPID : 39 dc 2b]
get Class class org.bouncycastle.asn1.DLSequence

Is this fine. How do i parse this with my custom ASN1 Structure?


问:
How to follow a list of links to get data from pages in scrapy?
I have a web page to scrape.  On the page, is a list of links in a
.  I'm trying to use the rules section to ask Scrapy to go through the links, and get data on the pages the links target.  Below is my code:

```<code>class ToScrapeSpiderXPath(scrapy.Spider):
    name = 'coinmarketcap'
    start_urls = [
        'https://coinmarketcap.com/currencies/views/all/'
    ]

    rules = (
        Rule(LinkExtractor(allow=(), restrict_xpaths=('//tr/td[2]/a/@href',)), callback="parse", follow= True),
    )

    def parse(self, response):
        print("TEST TEST TEST")
        BTC = BTCItem()
        BTC['source'] = str(response.request.url).split("/")[2]
        BTC['asset'] = str(response.request.url).split("/")[4],
        BTC['asset_price'] = response.xpath('//*[@id="quote_price"]/text()').extract(),
        BTC['asset_price_change'] = response.xpath('/html/body/div[2]/div/div[1]/div[3]/div[2]/span[2]/text()').extract(),
        BTC['BTC_price'] = response.xpath('/html/body/div[2]/div/div[1]/div[3]/div[2]/small[1]/text()').extract(),
        BTC['Prct_change'] = response.xpath('/html/body/div[2]/div/div[1]/div[3]/div[2]/small[2]/text()').extract()
        yield (BTC)
</code>```

My problem is that Scrapy is not following the links. It just takes the link at attempts to extract data from that link.  What am I missing?

UPDATE #1:
Why crawl vs scrape?

```<code>2017-03-28 23:10:33 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://coinmarketcap.com/currencies/pivx/> (referer: None)
2017-03-28 23:10:33 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://coinmarketcap.com/currencies/zcash/> (referer: None)
2017-03-28 23:10:33 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://coinmarketcap.com/currencies/bitcoin/> (referer: None)
2017-03-28 23:10:33 [scrapy.core.scraper] DEBUG: Scraped from <200 https://coinmarketcap.com/currencies/nem/>
</code>```

答:
You need to inherit from a CrawlSpider class for the link extractor to work:

```<code>from scrapy.spiders import CrawlSpider
from scrapy.spiders import Rule
from scrapy.contrib.linkextractors import LinkExtractor

class ToScrapeSpiderXPath(CrawlSpider):
    name = 'coinmarketcap'
    start_urls = [
        'https://coinmarketcap.com/currencies/views/all/'
    ]

    rules = (
        Rule(LinkExtractor(restrict_xpaths='//tr/td[2]/a'), callback="parse_table_links", follow= True),
    )

    def parse_table_links(self, response):
        print(response.url)
</code>```

Note that you need to fix the restrict_xpaths value - it should point to an a element and not the @href attribute of an element. And, you may define it as a string instead of a tuple.

Also, the allow argument is optional.

Body:
I have a web page to scrape.  On the page, is a list of links in a
.  I'm trying to use the rules section to ask Scrapy to go through the links, and get data on the pages the links target.  Below is my code:

class ToScrapeSpiderXPath(scrapy.Spider):
    name = 'coinmarketcap'
    start_urls = [
        'https://coinmarketcap.com/currencies/views/all/'
    ]

    rules = (
        Rule(LinkExtractor(allow=(), restrict_xpaths=('//tr/td[2]/a/@href',)), callback="parse", follow= True),
    )

    def parse(self, response):
        print("TEST TEST TEST")
        BTC = BTCItem()
        BTC['source'] = str(response.request.url).split("/")[2]
        BTC['asset'] = str(response.request.url).split("/")[4],
        BTC['asset_price'] = response.xpath('//*[@id="quote_price"]/text()').extract(),
        BTC['asset_price_change'] = response.xpath('/html/body/div[2]/div/div[1]/div[3]/div[2]/span[2]/text()').extract(),
        BTC['BTC_price'] = response.xpath('/html/body/div[2]/div/div[1]/div[3]/div[2]/small[1]/text()').extract(),
        BTC['Prct_change'] = response.xpath('/html/body/div[2]/div/div[1]/div[3]/div[2]/small[2]/text()').extract()
        yield (BTC)

My problem is that Scrapy is not following the links. It just takes the link at attempts to extract data from that link.  What am I missing?

UPDATE #1:
Why crawl vs scrape?

2017-03-28 23:10:33 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://coinmarketcap.com/currencies/pivx/> (referer: None)
2017-03-28 23:10:33 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://coinmarketcap.com/currencies/zcash/> (referer: None)
2017-03-28 23:10:33 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://coinmarketcap.com/currencies/bitcoin/> (referer: None)
2017-03-28 23:10:33 [scrapy.core.scraper] DEBUG: Scraped from <200 https://coinmarketcap.com/currencies/nem/>

Body:
You need to inherit from a CrawlSpider class for the link extractor to work:

from scrapy.spiders import CrawlSpider
from scrapy.spiders import Rule
from scrapy.contrib.linkextractors import LinkExtractor

class ToScrapeSpiderXPath(CrawlSpider):
    name = 'coinmarketcap'
    start_urls = [
        'https://coinmarketcap.com/currencies/views/all/'
    ]

    rules = (
        Rule(LinkExtractor(restrict_xpaths='//tr/td[2]/a'), callback="parse_table_links", follow= True),
    )

    def parse_table_links(self, response):
        print(response.url)

Note that you need to fix the restrict_xpaths value - it should point to an a element and not the @href attribute of an element. And, you may define it as a string instead of a tuple.

Also, the allow argument is optional.


问:
Materialize grid do 5 columns
I have div s12, how I can do in Materialize 5 columns?

My code:

```<code><div class="col s12">
  <div class="col s12 l2"></div>
  <div class="col s12 l2"></div>
  <div class="col s12 l4"></div>
  <div class="col s12 l2"></div>
  <div class="col s12 l2"></div>
</div>
</code>```

Please help do 5 same columns. 12/5 not entirely share.

答:
Materialize 5 Column Responsive Layout

The below is compatible with Materialize 0.98.1 and above as it uses the newly introduced xl media breakpoint.

Add the following CSS to your global stylesheet, The above CSS is compatible with other Materialize .col classes too. For example, if you want 5 equal columns on medium and above, and half width columns on small and below, use the following:

.s5ths,
.m5ths,
.l5ths,
.xl5ths {
  margin-left: auto;
  left: auto;
  right: auto;
}

.row .col.s5ths {
  width: 20%;
}

@media only screen and (min-width: 601px) {
  .row .col.m5ths {
    width: 20%;
  }
}

@media only screen and (min-width: 993px) {
  .row .col.l5ths {
    width: 20%;
  }
}

@media only screen and (min-width: 1201px) {
  .row .col.xl5ths {
    width: 20%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="row">
      <div class="col m5ths s6">Column 1</div>
      <div class="col m5ths s6">Column 2</div>
      <div class="col m5ths s6">Column 3</div>
      <div class="col m5ths s6">Column 4</div>
      <div class="col m5ths s6">Column 5</div>
    </div></code>```

Here is a working example of the above. Resize the window to see it in action.

If you're using SASS in your project, I highly recommend using the SASS media queries that Materialize provides.

ContentLicense: CC BY-SA 4.0

Title: Materialize grid do 5 columns

Body:
I have div s12, how I can do in Materialize 5 columns?

My code:

Please help do 5 same columns. 12/5 not entirely share.

Body:
Materialize 5 Column Responsive Layout

The below is compatible with Materialize 0.98.1 and above as it uses the newly introduced xl media breakpoint.

Add the following CSS to your global stylesheet, The above CSS is compatible with other Materialize .col classes too. For example, if you want 5 equal columns on medium and above, and half width columns on small and below, use the following:

.s5ths,
.m5ths,
.l5ths,
.xl5ths {
  margin-left: auto;
  left: auto;
  right: auto;
}

.row .col.s5ths {
  width: 20%;
}

@media only screen and (min-width: 601px) {
  .row .col.m5ths {
    width: 20%;
  }
}

@media only screen and (min-width: 993px) {
  .row .col.l5ths {
    width: 20%;
  }
}

@media only screen and (min-width: 1201px) {
  .row .col.xl5ths {
    width: 20%;
  }
}

    <div class="row">
      <div class="col m5ths s6">Column 1</div>
      <div class="col m5ths s6">Column 2</div>
      <div class="col m5ths s6">Column 3</div>
      <div class="col m5ths s6">Column 4</div>
      <div class="col m5ths s6">Column 5</div>
    </div>

Here is a working example of the above. Resize the window to see it in action.

If you're using SASS in your project, I highly recommend using the SASS media queries that Materialize provides.


问:
How to set vertical align to middle in my case?
I am trying to modify htmls element to achieve two things:

Vertical align two glyphicons and texts to middle.
(vertical align middle doesn't work)

Modify css to have a small gap between text "thanks" and glyphicons to become something like <icon><thanks><icon> instead of  <icon>   <thanks>   <icon>

I have created a jsfiddle:
https://jsfiddle.net/vwdhd1wy/

It seems odd that it created two gap without any additional css. Can someone help me about it?

答:
Working Code: https://jsfiddle.net/vwdhd1wy/4/

For 1. Vertical align two glyphicons and texts to middle. (vertical align middle doesn't work).

You can really tidy up the CSS as you don't want repeated code. Add vertical-align: top; to all span elements to ensure they are all starting at the same position as inline-block elements next to each other can get messy depending on their contents.

There is some inherited code for .glyphicon which is setting line-height: 1 and  top: 1px; so you need to override this with div > span.glyphicon { line-height: 30px; top: 0px; }. The rest is just setting height: 30px; and the line-height: 30px; (line-height for placing it in the middle).

```<code>div > span {
  display: inline-block;
  vertical-align: top;
}

div > span, div > span.glyphicon {
  height: 30px;
  line-height: 30px;
  top: 0px;
}

.left, .right {
  background-color: red;
}

.middle {
  background-color: grey;
}
</code>```

For 2. Modify css to have a small gap between text "thanks" and glyphicons to become something like  instead of

As @ryantdecker said, remove the whitespace after all the span elements to remove the extra space that's showing. You get this whitespace due to it being treated as an "inline" (text) element when set to inline-block so whenever there is a space between inline elements, it also includes that when rendering the HTML.

Solution:

```<code><span class="left glyphicon glyphicon-forward"></span><span class="middle">Thansk</span><span class="right glyphicon glyphicon-backward"></span>
</code>```

Body:
Working Code: https://jsfiddle.net/vwdhd1wy/4/

For 1. Vertical align two glyphicons and texts to middle. (vertical align middle doesn't work).

You can really tidy up the CSS as you don't want repeated code. Add vertical-align: top; to all span elements to ensure they are all starting at the same position as inline-block elements next to each other can get messy depending on their contents.

There is some inherited code for .glyphicon which is setting line-height: 1 and  top: 1px; so you need to override this with div > span.glyphicon { line-height: 30px; top: 0px; }. The rest is just setting height: 30px; and the line-height: 30px; (line-height for placing it in the middle).

div > span {
  display: inline-block;
  vertical-align: top;
}

div > span, div > span.glyphicon {
  height: 30px;
  line-height: 30px;
  top: 0px;
}

.left, .right {
  background-color: red;
}

.middle {
  background-color: grey;
}

For 2. Modify css to have a small gap between text "thanks" and glyphicons to become something like  instead of

As @ryantdecker said, remove the whitespace after all the span elements to remove the extra space that's showing. You get this whitespace due to it being treated as an "inline" (text) element when set to inline-block so whenever there is a space between inline elements, it also includes that when rendering the HTML.

Solution:

<span class="left glyphicon glyphicon-forward"></span><span class="middle">Thansk</span><span class="right glyphicon glyphicon-backward"></span>


问:
javascript - how to use a text box input in a for loop
I am trying to write a solution for a javascript application that takes a number input & depending on that number is how many times it runs a specific function. I am using a text box for input field & a button to process the number of times the user wants the function to run. It is for a game of dice game. User enters how many games he wants to play and clicks button to run the roll_dice function that many times. I'm not sure if I am going the right way with using a for loop to take users numeric input and loop through its value until it ends for example</p>

```<code>function games() {
        var num = document.getElementById("inp").vale;
        var i;

        for (i = 0; i < num; i++) {
            roll_dice();
        }
}
</code>```

答:
```<code>   function games() {

    var num = document.getElementById("inp").value;
    var i;

    for (i = 0; i < Number(num); i++) {
        roll_dice();
    }
}
</code>```

Body:
I am trying to write a solution for a javascript application that takes a number input & depending on that number is how many times it runs a specific function. I am using a text box for input field & a button to process the number of times the user wants the function to run. It is for a game of dice game. User enters how many games he wants to play and clicks button to run the roll_dice function that many times. I'm not sure if I am going the right way with using a for loop to take users numeric input and loop through its value until it ends for example

function games() {
        var num = document.getElementById("inp").vale;
        var i;

        for (i = 0; i < num; i++) {
            roll_dice();
        }
}


问:
ActiveMQ producer sending message from content inside PostgreSQL's table
Is anyone have a reference for me for a ActiveMQ producer coding to sending messages from content inside a table in PostgreSQL, but i wish i can send all rows on the table become one-by-one message...
I got a reference from someone that telling just same as i want above, but it tells how to get all the messages from content inside a .txt file...
here the referance

So far i got this:

```<code>package testMQDB;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ProducerDB {

   public static void ProducerDB(String[] args){
       Connection c = null;
       Statement stmt = null;
       try {
       Class.forName("org.postgresql.Driver");
         c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/"TestDB, "admin", "admin");
         c.setAutoCommit(false);
         System.out.println("----------------------------");

         stmt = c.createStatement();
         ResultSet rs = stmt.executeQuery( "SELECT * FROM MESSAGES;" );
         while ( rs.next() ) {
            String  message = rs.getString("MESSAGE");
            System.out.println( "Message = " + message );
            if (message.equals(true)){
                // write the ActiveMQ code here?
            }
         }
         rs.close();
         stmt.close();
         c.close();
       } catch ( Exception e ) {
         System.err.println( e.getClass().getName()+": "+ e.getMessage() );
         System.exit(0);
       }
       System.out.println("----------------------------");
       System.out.println("Message sent successfully");
   }
}
</code>```

答:
Got the answer...</p>

```<code>package TestMQDB;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class ProducerDB {

    public static void ProducerDB(String[] args){
        ConnectionFactory factory = null;
        javax.jms.Connection connection = null;
        Session session = null;
        Destination destination = null;
        MessageProducer producer = null;
        Connection c = null;
        Statement stmt = null;
        try {
        Class.forName("org.postgresql.Driver");
        c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/"TestDB, "admin", "admin");
        c.setAutoCommit(false);
        System.out.println("----------------------------");

        stmt = c.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM MESSAGES;");
        while (rs.next()) {
            String  message = rs.getString("MESSAGE");
            System.out.println("Message = " + message);
                try {
                    factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL);
                    connection = factory.createConnection();
                    connection.start();
                    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                    destination = session.createQueue("TestQueue");
                    producer = session.createProducer(destination);
                    TextMessage mssg = session.createTextMessage(message);
                    System.out.println("Sent: " + mssg.getText());
                    producer.send(mssg);
                }
                catch (JMSException e) {
                    e.printStackTrace();
                }

        }
        rs.close();
        stmt.close();
        c.close();
        }
        catch (Exception e) {
            System.err.println(e.getClass().getName()+": "+ e.getMessage());
        }
        System.out.println("----------------------------");
        System.out.println("Message sent successfully");
    }
}
</code>```

Body:
Is anyone have a reference for me for a ActiveMQ producer coding to sending messages from content inside a table in PostgreSQL, but i wish i can send all rows on the table become one-by-one message...
I got a reference from someone that telling just same as i want above, but it tells how to get all the messages from content inside a .txt file...
here the referance

So far i got this:

package testMQDB;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ProducerDB {

   public static void ProducerDB(String[] args){
       Connection c = null;
       Statement stmt = null;
       try {
       Class.forName("org.postgresql.Driver");
         c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/"TestDB, "admin", "admin");
         c.setAutoCommit(false);
         System.out.println("----------------------------");

         stmt = c.createStatement();
         ResultSet rs = stmt.executeQuery( "SELECT * FROM MESSAGES;" );
         while ( rs.next() ) {
            String  message = rs.getString("MESSAGE");
            System.out.println( "Message = " + message );
            if (message.equals(true)){
                // write the ActiveMQ code here?
            }
         }
         rs.close();
         stmt.close();
         c.close();
       } catch ( Exception e ) {
         System.err.println( e.getClass().getName()+": "+ e.getMessage() );
         System.exit(0);
       }
       System.out.println("----------------------------");
       System.out.println("Message sent successfully");
   }
}

Body:
Got the answer...

package TestMQDB;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class ProducerDB {

    public static void ProducerDB(String[] args){
        ConnectionFactory factory = null;
        javax.jms.Connection connection = null;
        Session session = null;
        Destination destination = null;
        MessageProducer producer = null;
        Connection c = null;
        Statement stmt = null;
        try {
        Class.forName("org.postgresql.Driver");
        c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/"TestDB, "admin", "admin");
        c.setAutoCommit(false);
        System.out.println("----------------------------");

        stmt = c.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM MESSAGES;");
        while (rs.next()) {
            String  message = rs.getString("MESSAGE");
            System.out.println("Message = " + message);
                try {
                    factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL);
                    connection = factory.createConnection();
                    connection.start();
                    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                    destination = session.createQueue("TestQueue");
                    producer = session.createProducer(destination);
                    TextMessage mssg = session.createTextMessage(message);
                    System.out.println("Sent: " + mssg.getText());
                    producer.send(mssg);
                }
                catch (JMSException e) {
                    e.printStackTrace();
                }

        }
        rs.close();
        stmt.close();
        c.close();
        }
        catch (Exception e) {
            System.err.println(e.getClass().getName()+": "+ e.getMessage());
        }
        System.out.println("----------------------------");
        System.out.println("Message sent successfully");
    }
}


问:
Seeing the active css element outline style in chrome developer tooling?
In chrome the below button will retain it's outline after it has been clicked.  If I looked at the buttons css settings after selecting the :active checkbox in chrome's developer tools I still can't see what the CSS values are for the outline.  It appears to be about 1px in width and grey visually, but I don't see these values.  Is there a way to see them?

  <button style="background-color: aquamarine; margin-top: 50px; margin-left: 50px;">HI</button>
```
</div>
</div>
</p>

<p>In other words google chrome does add this style (As indicated by one of the answer below):</p>

``` :focus {
     outline: -webkit-focus-ring-color auto 5px;
 }
```

However when I click the focus checkbox in order to be able to see all the CSS that is triggered by focus, I don't see that style in the developer tooling pane ... Is it a google developer tooling bug or do other people see it?

答:
There are actually two different styles that are automatically applied through through the user agent stylesheet to buttons; the pseudo-classes :focus and :active:

```<code>:focus {
    outline: -webkit-focus-ring-color auto 5px;
}
button:active {
    border-style: inset;
}
</code>```

The :focus only applies to Chrome, and is responsible for the blue border you are seeing. Overriding this fixes the problem:

button:focus {
    outline: none; /* Remove the outline */
}
button.active: {
    border-style: none; /* Remove the border */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <button style="background-color: aquamarine; margin-top: 50px; margin-left: 50px;">HI</button>
</body></code>```

You can see that the :focus is getting added in the Developer Console through the user agent stylesheet (just below the inline elements in this screenshot):

Hope this helps! :)

Body:
In chrome the below button will retain it's outline after it has been clicked.  If I looked at the buttons css settings after selecting the :active checkbox in chrome's developer tools I still can't see what the CSS values are for the outline.  It appears to be about 1px in width and grey visually, but I don't see these values.  Is there a way to see them?

  <button style="background-color: aquamarine; margin-top: 50px; margin-left: 50px;">HI</button>

In other words google chrome does add this style (As indicated by one of the answer below):

 :focus {
     outline: -webkit-focus-ring-color auto 5px;
 }

However when I click the focus checkbox in order to be able to see all the CSS that is triggered by focus, I don't see that style in the developer tooling pane ... Is it a google developer tooling bug or do other people see it?

Body:
There are actually two different styles that are automatically applied through through the user agent stylesheet to buttons; the pseudo-classes :focus and :active:

:focus {
    outline: -webkit-focus-ring-color auto 5px;
}
button:active {
    border-style: inset;
}

The :focus only applies to Chrome, and is responsible for the blue border you are seeing. Overriding this fixes the problem:

button:focus {
    outline: none; /* Remove the outline */
}
button.active: {
    border-style: none; /* Remove the border */
}

<body>
  <button style="background-color: aquamarine; margin-top: 50px; margin-left: 50px;">HI</button>
</body>

You can see that the :focus is getting added in the Developer Console through the user agent stylesheet (just below the inline elements in this screenshot):

Hope this helps! :)


问:
Multiple Aggregates Pivot Table
I have a few columns of data I am wanting to put into a Pivot table. This is what the data currently looks like once the following query is ran:

```<code>SELECT
    t.clinic,
    t.fiscal_year,
    t.total,
    n.new_pats,
    (t.total - n.new_pats) AS active
FROM (SELECT DISTINCT
    clinic,
    fiscal_year,
    COUNT(DISTINCT patient_id) AS total
FROM transactions t
JOIN period p
    ON (t.date_entered BETWEEN p.period_start AND p.period_end)
GROUP BY clinic, fiscal_year) t
JOIN (SELECT DISTINCT
    clinic,
    per.fiscal_year,
    COUNT(DISTINCT patient_id) AS new_pats
FROM patient pat
JOIN period per
    ON (pat.first_visit_date BETWEEN per.period_start AND per.period_end)
GROUP BY clinic, fiscal_year) n
    ON (t.clinic = n.clinic AND t.fiscal_year = n.fiscal_year)
</code>```

And I would like the data to be broken up by the three aggregates in their own rows and the years being the columns where it looks something like this:

This could also be broken into 3 separate columns per aggregate per year, but this is what I'm ideally aiming for. I haven't put together a Pivot table within SQL before and am at a loss. Is there a better way to go about formatting this data in the desired way?

答:
Try this:</p>

```<code>CREATE TABLE #ActualData
(
   Clinic varchar(50),
   fiscal_year int,
   total int,
   new_pats int,
   active int
)

INSERT INTO #ActualData VALUES ('A', 2016, 3538,1787,1751), ('A', 2017, 1218,373,845), ('B', 2009, 1,2,3), ('B', 2010, 1,2,3)

SELECT * FROM #ActualData ad

;WITH temps AS
   (
      SELECT Clinic, fiscal_year, aggregateF, Number FROM
      (
         SELECT ad.Clinic, ad.fiscal_year, ad.total,ad.new_pats,ad.active FROM #ActualData ad
      ) src
      UNPIVOT
      (
         Number FOR aggregateF IN (total,new_pats ,active)
      ) unpvt
   )
SELECT Clinic, aggregateF, [2009],[2010],[2016],[2017]
FROM
(
   SELECT t.Clinic, t.aggregateF, t.fiscal_year, t.Number FROM temps t
) src
PIVOT
(
   MIN (Number) FOR fiscal_year IN ([2009],[2010],[2016],[2017])
) pvt
ORDER BY pvt.Clinic, pvt.aggregateF DESC

DROP TABLE #ActualData
</code>```

Title: Multiple Aggregates Pivot Table

Body:
I have a few columns of data I am wanting to put into a Pivot table. This is what the data currently looks like once the following query is ran:

SELECT
    t.clinic,
    t.fiscal_year,
    t.total,
    n.new_pats,
    (t.total - n.new_pats) AS active
FROM (SELECT DISTINCT
    clinic,
    fiscal_year,
    COUNT(DISTINCT patient_id) AS total
FROM transactions t
JOIN period p
    ON (t.date_entered BETWEEN p.period_start AND p.period_end)
GROUP BY clinic, fiscal_year) t
JOIN (SELECT DISTINCT
    clinic,
    per.fiscal_year,
    COUNT(DISTINCT patient_id) AS new_pats
FROM patient pat
JOIN period per
    ON (pat.first_visit_date BETWEEN per.period_start AND per.period_end)
GROUP BY clinic, fiscal_year) n
    ON (t.clinic = n.clinic AND t.fiscal_year = n.fiscal_year)

And I would like the data to be broken up by the three aggregates in their own rows and the years being the columns where it looks something like this:

This could also be broken into 3 separate columns per aggregate per year, but this is what I'm ideally aiming for. I haven't put together a Pivot table within SQL before and am at a loss. Is there a better way to go about formatting this data in the desired way?

Body:
Try this:

CREATE TABLE #ActualData
(
   Clinic varchar(50),
   fiscal_year int,
   total int,
   new_pats int,
   active int
)

INSERT INTO #ActualData VALUES ('A', 2016, 3538,1787,1751), ('A', 2017, 1218,373,845), ('B', 2009, 1,2,3), ('B', 2010, 1,2,3)

SELECT * FROM #ActualData ad

;WITH temps AS
   (
      SELECT Clinic, fiscal_year, aggregateF, Number FROM
      (
         SELECT ad.Clinic, ad.fiscal_year, ad.total,ad.new_pats,ad.active FROM #ActualData ad
      ) src
      UNPIVOT
      (
         Number FOR aggregateF IN (total,new_pats ,active)
      ) unpvt
   )
SELECT Clinic, aggregateF, [2009],[2010],[2016],[2017]
FROM
(
   SELECT t.Clinic, t.aggregateF, t.fiscal_year, t.Number FROM temps t
) src
PIVOT
(
   MIN (Number) FOR fiscal_year IN ([2009],[2010],[2016],[2017])
) pvt
ORDER BY pvt.Clinic, pvt.aggregateF DESC

DROP TABLE #ActualData


问:
how to define schema for custom address type for multiple addresses in mongodb
For multiple addresses in mongodb, we generally store address in array.

```<code>address:[
{
"type" : "home",
"primary" : false,

"streetaddress" : "Some",

"locality" : "Farnborough",
"region" : "England",
"formatted" : "Farnborough, United Kingdom",
"country" : "United Kingdom",
"location" : [
-0.752615,
51.2868939
]
},
{
"type" : "business",

"locality" : "London",
"region" : "England",
"formatted" : "The Gherkin, London, United Kingdom",
"primary" : false,
"streetaddress" : "30 St Mary Axe",
"country" : "United Kingdom",
"location" : [
-0.08030649999999999,
51.51449179999999
]
}
]
</code>```

But to fetch specific address by key eg. home or business, we need to  loop through array. Is there any alternative way other than defining as below

```<code>{
      home_address:
              {
                "streetaddress" : "Some",

                "locality" : "Farnborough",
                "region" : "England",
                "formatted" : "Farnborough, United Kingdom",
                "country" : "United Kingdom",
                "location" : [
                              -0.752615,
                              51.2868939
                             ]
            },
    business_address : {
               "locality" : "London",
               "region" : "England",
               "formatted" : "The Gherkin, London, United Kingdom",
               "primary" : false,
               "streetaddress" : "30 St Mary Axe",
               "country" : "United Kingdom",
               "location" : [
                              -0.08030649999999999,
                              51.51449179999999
                           ],
            },
    primary_address : "home_address"

    }
</code>```

答:
Generally, if you know exactly you're going to query a certain value of an array and you know the said value, it is good to turn it into a sub-document with the value as the key.

Similar to what you have above:

```<code>"address": {
    "type_home": { "street": ... },
    "type_business": {"street": ...},
    "primary": "type_home",
    "available": ["type_home", "type_business"]
}
</code>```

Flexible schema is part of MongoDB features, and you should utilise this to help optimise your application usage. The above schema would help to query a particular address faster than looping over an array.

You may be benefited from seeing more of data models examples

Body:
For multiple addresses in mongodb, we generally store address in array.

address:[
{
"type" : "home",
"primary" : false,

"streetaddress" : "Some",

"locality" : "Farnborough",
"region" : "England",
"formatted" : "Farnborough, United Kingdom",
"country" : "United Kingdom",
"location" : [
-0.752615,
51.2868939
]
},
{
"type" : "business",

"locality" : "London",
"region" : "England",
"formatted" : "The Gherkin, London, United Kingdom",
"primary" : false,
"streetaddress" : "30 St Mary Axe",
"country" : "United Kingdom",
"location" : [
-0.08030649999999999,
51.51449179999999
]
}
]

But to fetch specific address by key eg. home or business, we need to  loop through array. Is there any alternative way other than defining as below

{
      home_address:
              {
                "streetaddress" : "Some",

                "locality" : "Farnborough",
                "region" : "England",
                "formatted" : "Farnborough, United Kingdom",
                "country" : "United Kingdom",
                "location" : [
                              -0.752615,
                              51.2868939
                             ]
            },
    business_address : {
               "locality" : "London",
               "region" : "England",
               "formatted" : "The Gherkin, London, United Kingdom",
               "primary" : false,
               "streetaddress" : "30 St Mary Axe",
               "country" : "United Kingdom",
               "location" : [
                              -0.08030649999999999,
                              51.51449179999999
                           ],
            },
    primary_address : "home_address"

    }

Body:
Generally, if you know exactly you're going to query a certain value of an array and you know the said value, it is good to turn it into a sub-document with the value as the key.

Similar to what you have above:

"address": {
    "type_home": { "street": ... },
    "type_business": {"street": ...},
    "primary": "type_home",
    "available": ["type_home", "type_business"]
}

Flexible schema is part of MongoDB features, and you should utilise this to help optimise your application usage. The above schema would help to query a particular address faster than looping over an array.

You may be benefited from seeing more of data models examples


问:
What is the best way to convert a pdf file into base64Binary?
Using python, I want to convert a pdf file into base64Binary

My logic(not python) is reading the contents of the file into a byte array and then use something like Convert.ToBase64String() method to get the Base64 string:

```<code>byte[] pdfBytes = File.ReadAllBytes(pdfPath);
string pdfBase64 = Convert.ToBase64String(pdfBytes);
</code>```

Please let me know what is the right approach to convert a pdf file into base64Binary in python

答:
its easy as this

```<code>import base64

with open("book.pdf", "rb") as pdf_file:
    encoded_string = base64.b64encode(pdf_file.read())
</code>```

source: Encoding an image file with base64

Body:
Using python, I want to convert a pdf file into base64Binary

My logic(not python) is reading the contents of the file into a byte array and then use something like Convert.ToBase64String() method to get the Base64 string:

byte[] pdfBytes = File.ReadAllBytes(pdfPath);
string pdfBase64 = Convert.ToBase64String(pdfBytes);

Please let me know what is the right approach to convert a pdf file into base64Binary in python

Body:
its easy as this

import base64

with open("book.pdf", "rb") as pdf_file:
    encoded_string = base64.b64encode(pdf_file.read())

source: Encoding an image file with base64


问:
Ruby on Rails Tutorial (Michael Hartl) Chapter 2 Exercise 2.3.3.1 "Edit the user show page to display the content of the user’s first micropost."
Full descriptions of task sounds:
Edit the user show page to display the content of the user’s first micropost. (Use your technical sophistication (Box 1.1) to guess the syntax based on the other content in the file.) Confirm by visiting /users/1 that it worked.

My first idea was to update app/views/users/show.html.erb into

```<code><p id="notice"><%= notice %></p>

<p>
  <strong>Name:</strong>
  <%= @user.name %>
</p>

<p>
  <strong>Email:</strong>
  <%= @user.email %>
</p>

<p>
  <strong>Content:</strong>
  <%= @micropost.content %>
</p>

<%= link_to 'Edit', edit_user_path(@user) %> |
<%= link_to 'Back', users_path %>
</code>```

But seems I haven't got idea behind task? Any suggestions from what I should start from?
Biggest thanks for your responses)

答:
I also added @user.id because without it you don't know which user to add the microposts to for testing.  Then you need to test to see if there is a microposts in order not break the code trying to display nil.</p>

```<code><p>
  <strong>ID:</strong>
  <%= @user.id %>
</p>

<% if @user.microposts.first %>
<p>
  <strong>First Post:</strong>
  <%= @user.microposts.first.content %>
</p>
<% end %>
</code>```

Body:
Full descriptions of task sounds:
Edit the user show page to display the content of the user’s first micropost. (Use your technical sophistication (Box 1.1) to guess the syntax based on the other content in the file.) Confirm by visiting /users/1 that it worked.

My first idea was to update app/views/users/show.html.erb into

<%= notice %>

  Name:
  <%= @user.name %>

  Email:
  <%= @user.email %>

  Content:
  <%= @micropost.content %>

<%= link_to 'Edit', edit_user_path(@user) %> |
<%= link_to 'Back', users_path %>

But seems I haven't got idea behind task? Any suggestions from what I should start from?
Biggest thanks for your responses)

Body:
I also added @user.id because without it you don't know which user to add the microposts to for testing.  Then you need to test to see if there is a microposts in order not break the code trying to display nil.

<p>
  <strong>ID:</strong>
  <%= @user.id %>
</p>

<% if @user.microposts.first %>
<p>
  <strong>First Post:</strong>
  <%= @user.microposts.first.content %>
</p>
<% end %>


问:
Setting A Callback Function To A Timer
I'm so close to finishing this program and I can't figure out this last piece. I have my webpage reaching out to a server to grab a randomly generated number, which it then plots onto a graph. I need to set it so it plots the data points every 2 seconds and I can't figure out how to set up my setInterval command. I can get it to work with a for loop, but this obviously isn't timed. It also crashes when I set the limit past a certain threshold, which may indicate a problem when trying to use the timer. I'll post my code along with some of the things I've tried.

Code first:

```<code>function plotData(dataSet)
{
var x = xScale+20; // 20 = margin length
var y = 260;    //origin of graph

context.strokeStyle="#0000FF";
context.beginPath();

for (i = 1; i <= 10; i++)
{
  getRequest(function(random)
  {
    var diff = (dataSet[0]*100) - (dataSet[1] * 100);
    diff = diff/5;
    y = y+(diff*23);

    context.lineTo(x, y);
    context.moveTo(x, y);
    context.stroke();

    x=x+xScale;
    console.log("dataSet = "+dataSet[0]+", "+dataSet[1]);
    dataSet[0] = dataSet[1];
  });
}
}
</code>```

I have it set to a loop for debugging purposes right now.

The callback function reaches to an XMLHttpRequest to grab the random number (I can post this code too if needed).

What I was trying to do was implement setInterval along with some booleans to stop the function upon a second function call.

Something like this:

```<code>var isRunning = false;

function plotData(dataSet)
{
 if (isRunning == false)
 {
  isRunning = true;
 }

 if (isRunning == true)
 {
  isRunning = false;
  myTimer = clearInterval();
 }
var myTimer;
var x = xScale+20; // 20 = margin length
var y = 260;    //origin of graph

context.strokeStyle="#0000FF";
context.beginPath();

 while (isRunning == true)
 {
  myTimer = setInterval(function()
  {
   getRequest(function(random)
   {
    var diff = (dataSet[0]*100) - (dataSet[1] * 100);
    diff = diff/5;
    y = y+(diff*23);

    context.lineTo(x, y);
    context.moveTo(x, y);
    context.stroke();

    x=x+xScale;
    console.log("dataSet = "+dataSet[0]+", "+dataSet[1]);
    dataSet[0] = dataSet[1];
   });
  }, 2000);

 }
}
</code>```

I added a global boolean isRunning for handling purposes.

I set isRunning to true if it was previously false (indicating that it is now in progress).

I set isRunning to false if it was previously true then proceed to clearInterval to stop it.

And lastly set up a while loop for the callback function to execute while isRunning == true

All this did was crash my program. How can I use the setInterval function correctly in this case?

答:
Perform the check isRunning == true inside the callback passed to setInterval(). Try something like this,

myTimer = setInterval(function(){
  if(isRunning == true) {
    /* clear the timer */
  }
  /* Else perform the request */
}, 2000)```

When isRunning evaluates to true, the timer will be cleared stopping subsequent setInterval.

Title: Setting A Callback Function To A Timer

Body:
I'm so close to finishing this program and I can't figure out this last piece. I have my webpage reaching out to a server to grab a randomly generated number, which it then plots onto a graph. I need to set it so it plots the data points every 2 seconds and I can't figure out how to set up my setInterval command. I can get it to work with a for loop, but this obviously isn't timed. It also crashes when I set the limit past a certain threshold, which may indicate a problem when trying to use the timer. I'll post my code along with some of the things I've tried.

Code first:

function plotData(dataSet)
{
var x = xScale+20; // 20 = margin length
var y = 260;    //origin of graph

context.strokeStyle="#0000FF";
context.beginPath();

for (i = 1; i <= 10; i++)
{
  getRequest(function(random)
  {
    var diff = (dataSet[0]*100) - (dataSet[1] * 100);
    diff = diff/5;
    y = y+(diff*23);

    context.lineTo(x, y);
    context.moveTo(x, y);
    context.stroke();

    x=x+xScale;
    console.log("dataSet = "+dataSet[0]+", "+dataSet[1]);
    dataSet[0] = dataSet[1];
  });
}
}

I have it set to a loop for debugging purposes right now.

The callback function reaches to an XMLHttpRequest to grab the random number (I can post this code too if needed).

What I was trying to do was implement setInterval along with some booleans to stop the function upon a second function call.

Something like this:

var isRunning = false;

function plotData(dataSet)
{
 if (isRunning == false)
 {
  isRunning = true;
 }

 if (isRunning == true)
 {
  isRunning = false;
  myTimer = clearInterval();
 }
var myTimer;
var x = xScale+20; // 20 = margin length
var y = 260;    //origin of graph

context.strokeStyle="#0000FF";
context.beginPath();

 while (isRunning == true)
 {
  myTimer = setInterval(function()
  {
   getRequest(function(random)
   {
    var diff = (dataSet[0]*100) - (dataSet[1] * 100);
    diff = diff/5;
    y = y+(diff*23);

    context.lineTo(x, y);
    context.moveTo(x, y);
    context.stroke();

    x=x+xScale;
    console.log("dataSet = "+dataSet[0]+", "+dataSet[1]);
    dataSet[0] = dataSet[1];
   });
  }, 2000);

 }
}

I added a global boolean isRunning for handling purposes.

I set isRunning to true if it was previously false (indicating that it is now in progress).

I set isRunning to false if it was previously true then proceed to clearInterval to stop it.

And lastly set up a while loop for the callback function to execute while isRunning == true

All this did was crash my program. How can I use the setInterval function correctly in this case?

Body:
Perform the check isRunning == true inside the callback passed to setInterval(). Try something like this,

myTimer = setInterval(function(){
  if(isRunning == true) {
    /* clear the timer */
  }
  /* Else perform the request */
}, 2000)

When isRunning evaluates to true, the timer will be cleared stopping subsequent setInterval.


问:
Javascript: How to convert exif date time data to timestamp?
In javascript, while using exif-js to extract metadata of an image file, I am getting date time format as 2017:03:09 14:49:21.

The value in the DateTimeOriginal property is formatted as YYYY:MMY:DD HH:MM:SS. When I use var d = new Date(2017:03:09 14:49:21), it returns NaN. It's the colons in between the YYYY, MM, and DD which causes problem.

How to solve this problem?

Thanks in advance.

答:
My recommendation would be to use Moment (http://momentjs.com/docs/), as it provides clean parsing of dates. With Moment, what you want is this:</p>

```<code>var tstamp = moment("2017:03:09 14:49:21", "YYYY:MM:DD HH:mm:ss");
var date = tstamp.toDate();
</code>```

Body:
My recommendation would be to use Moment (http://momentjs.com/docs/), as it provides clean parsing of dates. With Moment, what you want is this:

var tstamp = moment("2017:03:09 14:49:21", "YYYY:MM:DD HH:mm:ss");
var date = tstamp.toDate();


问:
Conversion of numpy 2d array to ENVI binary file through gdal
I have SAR CEOS format files which consist of data file, leader file, null volume directory file and volume directory file.

I am reading the data file using gdal ReadAsArray and then I am doing operations on this 2d Array and now I want to save this 2d array as an ENVI binary file.

Kindly guide how to do this in Python 3.5.

答:
Find help for Tutorial Website: https://pcjericks.github.io/py-gdalogr-cookbook/

Such as the example of

```<code>import gdal, ogr, os, osr
import numpy as np

def array2raster(newRasterfn,rasterOrigin,pixelWidth,pixelHeight,array):
    cols = array.shape[1]
    rows = array.shape[0]
    originX = rasterOrigin[0]
    originY = rasterOrigin[1]

    driver = gdal.GetDriverByName('ENVI')
    outRaster = driver.Create(newRasterfn, cols, rows, 1, gdal.GDT_Byte)
    outRaster.SetGeoTransform((originX, pixelWidth, 0, originY, 0, pixelHeight))
    outband = outRaster.GetRasterBand(1)
    outband.WriteArray(array)
    outRasterSRS = osr.SpatialReference()
    outRasterSRS.ImportFromEPSG(4326)
    outRaster.SetProjection(outRasterSRS.ExportToWkt())
    outband.FlushCache()

def main(newRasterfn,rasterOrigin,pixelWidth,pixelHeight,array):
    reversed_arr = array[::-1] # reverse array so the tif looks like the array
    array2raster(newRasterfn,rasterOrigin,pixelWidth,pixelHeight,reversed_arr) # convert array to raster

if __name__ == "__main__":
    rasterOrigin = (-123.25745,45.43013)
    pixelWidth = 10
    pixelHeight = 10
    newRasterfn = 'test.tif'
    array = np.array([[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
                      [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
                      [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1],
                      [ 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1],
                      [ 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1],
                      [ 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1],
                      [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1],
                      [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
                      [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
                      [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])

    main(newRasterfn,rasterOrigin,pixelWidth,pixelHeight,array)
</code>```

Body:
Find help for Tutorial Website: https://pcjericks.github.io/py-gdalogr-cookbook/

Such as the example of

import gdal, ogr, os, osr
import numpy as np

def array2raster(newRasterfn,rasterOrigin,pixelWidth,pixelHeight,array):
    cols = array.shape[1]
    rows = array.shape[0]
    originX = rasterOrigin[0]
    originY = rasterOrigin[1]

    driver = gdal.GetDriverByName('ENVI')
    outRaster = driver.Create(newRasterfn, cols, rows, 1, gdal.GDT_Byte)
    outRaster.SetGeoTransform((originX, pixelWidth, 0, originY, 0, pixelHeight))
    outband = outRaster.GetRasterBand(1)
    outband.WriteArray(array)
    outRasterSRS = osr.SpatialReference()
    outRasterSRS.ImportFromEPSG(4326)
    outRaster.SetProjection(outRasterSRS.ExportToWkt())
    outband.FlushCache()

def main(newRasterfn,rasterOrigin,pixelWidth,pixelHeight,array):
    reversed_arr = array[::-1] # reverse array so the tif looks like the array
    array2raster(newRasterfn,rasterOrigin,pixelWidth,pixelHeight,reversed_arr) # convert array to raster

if __name__ == "__main__":
    rasterOrigin = (-123.25745,45.43013)
    pixelWidth = 10
    pixelHeight = 10
    newRasterfn = 'test.tif'
    array = np.array([[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
                      [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
                      [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1],
                      [ 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1],
                      [ 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1],
                      [ 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1],
                      [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1],
                      [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
                      [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
                      [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])

    main(newRasterfn,rasterOrigin,pixelWidth,pixelHeight,array)


答:
You have a typo. It's .value.

You can convert a string to a number by using * 1.

Something like this:

function games() {

  var num = document.getElementById("inp").value * 1; // Convert the string value a number.
  var i;

  for (i = 0; i < num; i++) {
    roll_dice();
  }
}

function roll_dice() {
  console.log("Test.");
}

var btnRun = document.getElementById("btnRun");
btnRun.onclick = function() {
  games();
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="inp" type="text" />
<button id="btnRun" type="button">Run</button></code>```

Title: javascript - how to use a text box input in a for loop

Body:
I am trying to write a solution for a javascript application that takes a number input & depending on that number is how many times it runs a specific function. I am using a text box for input field & a button to process the number of times the user wants the function to run. It is for a game of dice game. User enters how many games he wants to play and clicks button to run the roll_dice function that many times. I'm not sure if I am going the right way with using a for loop to take users numeric input and loop through its value until it ends for example

function games() {
        var num = document.getElementById("inp").vale;
        var i;

        for (i = 0; i < num; i++) {
            roll_dice();
        }
}

Body:
You have a typo. It's .value.

You can convert a string to a number by using * 1.

Something like this:

function games() {

  var num = document.getElementById("inp").value * 1; // Convert the string value a number.
  var i;

  for (i = 0; i < num; i++) {
    roll_dice();
  }
}

function roll_dice() {
  console.log("Test.");
}

var btnRun = document.getElementById("btnRun");
btnRun.onclick = function() {
  games();
};

<input id="inp" type="text" />
<button id="btnRun" type="button">Run</button>


问:
How to specifying generic return type in PyCharm + python2.7
How to define the docstring in following function?

```<code>def get_object(klass, **kwargs):
    """
    :rtype: ???
    """
    # perform some tasks
    return klass(**kwargs)
</code>```

I've tried klass, type(klass), klass.__class__,
they all didn't work in separated module files:

```<code>from sample.utils import get_object
from sample.models import User

u = get_object(User, name='test')
u.  # no PyCharm hint here
</code>```

I also tried :type klass: T and :rtype: T, also not working :(

Can PyCharm support these kind of syntax in docstring?
How to document it?

答:
Try something like this:

```<code>def get_obj(klass, **kwargs):
"""
:type klass: ((object) -> T) | T
:type kwargs: object
:rtype: T
"""
</code>```

Class can be a lambda of its __init__, so you can use lambda's return type as the instance type of a class

Body:
How to define the docstring in following function?

def get_object(klass, **kwargs):
    """
    :rtype: ???
    """
    # perform some tasks
    return klass(**kwargs)

I've tried klass, type(klass), klass.__class__,
they all didn't work in separated module files:

from sample.utils import get_object
from sample.models import User

u = get_object(User, name='test')
u.  # no PyCharm hint here

I also tried :type klass: T and :rtype: T, also not working :(

Can PyCharm support these kind of syntax in docstring?
How to document it?

Body:
Try something like this:

def get_obj(klass, **kwargs):
"""
:type klass: ((object) -> T) | T
:type kwargs: object
:rtype: T
"""

Class can be a lambda of its __init__, so you can use lambda's return type as the instance type of a class


问:
Cannot process argument transformation on parameter 'machine'. Cannot convert value to type System.String
I'm very new to Powershell. Im basically just using my C# logic and .net experience along with google to create this script. I dont understand why im getting the error:

Cannot process argument transformation on parameter 'machine'. Cannot convert value to type System.String

```<code>function IterateThroughMachineSubkeys{
(
    [Parameter()]
    [string]$machine,
    [Microsoft.Win32.RegistryKey]$subKey
)

    foreach($subKeyName in $subKey.GetSubKeyNames())
    {
        Write-Host -Object ([System.String]::Format("Machine: {0} Module: {1} Version: {2}",
                            $machine.ToString(), $subKeyName.ToString(),
                            $subKey.OpenSubKey([string]$subKeyName).GetValue("Version", "Not found", [Microsoft.Win32.RegistryValueOptions]::None)))
    }
}
</code>```

This is where im calling the function:

```<code>switch -CaseSensitive (ValidateConsoleInput((Read-Host).ToString()))
{
   "E"
   {
    IterateThroughMachineSubkeys($machine.ToString(), $subKey)
   }
   "C"
   {
    Write-Host -Object "Enter the module name to be queried in the registry:"
    GetSpecificSubkey($machine, $subkey, [string](Read-Host))
   }

}
</code>```

答:
There are a couple of issues with your code.

1) The function parameters are not specified correctly; it should be:

```<code>function IterateThroughMachineSubkeys([string]$machine, [Microsoft.Win32.RegistryKey]$subKey)
{
  ...
}
</code>```

2) The function call is incorrect; it should be:

```<code>IterateThroughMachineSubkeys -machine $machine.ToString() -subKey $subKey
</code>```

Here is the function in full:

```<code>function IterateThroughMachineSubkeys([string]$machine, [Microsoft.Win32.RegistryKey]$subKey)
{
    foreach($subKeyName in $subKey.GetSubKeyNames())
    {
        Write-Host -Object ([System.String]::Format("Machine: {0} Module: {1} Version: {2}",
                            $machine.ToString(), $subKeyName.ToString(),
                            $subKey.OpenSubKey([string]$subKeyName).GetValue("Version", "Not found", [Microsoft.Win32.RegistryValueOptions]::None)))
    }
}

$testKey = get-item "HKCU:\Software"
IterateThroughMachineSubkeys -machine . -subKey $testKey
</code>```

Or using PowerShell cmdlets:

```<code>$key = get-item "hkcu:\Software\Google\Chrome"
$key | get-childitem | foreach-object {
    write-host "Machine: $machine Module: $($_.PSChildName) Version: " `
    $key.OpenSubKey($_.PSChildName).GetValue("Version", "Not found", [Microsoft.Win32.RegistryValueOptions]::None)
}
</code>```

Body:
I'm very new to Powershell. Im basically just using my C# logic and .net experience along with google to create this script. I dont understand why im getting the error:

Cannot process argument transformation on parameter 'machine'. Cannot convert value to type System.String

function IterateThroughMachineSubkeys{
(
    [Parameter()]
    [string]$machine,
    [Microsoft.Win32.RegistryKey]$subKey
)

    foreach($subKeyName in $subKey.GetSubKeyNames())
    {
        Write-Host -Object ([System.String]::Format("Machine: {0} Module: {1} Version: {2}",
                            $machine.ToString(), $subKeyName.ToString(),
                            $subKey.OpenSubKey([string]$subKeyName).GetValue("Version", "Not found", [Microsoft.Win32.RegistryValueOptions]::None)))
    }
}

This is where im calling the function:

switch -CaseSensitive (ValidateConsoleInput((Read-Host).ToString()))
{
   "E"
   {
    IterateThroughMachineSubkeys($machine.ToString(), $subKey)
   }
   "C"
   {
    Write-Host -Object "Enter the module name to be queried in the registry:"
    GetSpecificSubkey($machine, $subkey, [string](Read-Host))
   }

}

Body:
There are a couple of issues with your code.

1) The function parameters are not specified correctly; it should be:

function IterateThroughMachineSubkeys([string]$machine, [Microsoft.Win32.RegistryKey]$subKey)
{
  ...
}

2) The function call is incorrect; it should be:

IterateThroughMachineSubkeys -machine $machine.ToString() -subKey $subKey

Here is the function in full:

function IterateThroughMachineSubkeys([string]$machine, [Microsoft.Win32.RegistryKey]$subKey)
{
    foreach($subKeyName in $subKey.GetSubKeyNames())
    {
        Write-Host -Object ([System.String]::Format("Machine: {0} Module: {1} Version: {2}",
                            $machine.ToString(), $subKeyName.ToString(),
                            $subKey.OpenSubKey([string]$subKeyName).GetValue("Version", "Not found", [Microsoft.Win32.RegistryValueOptions]::None)))
    }
}

$testKey = get-item "HKCU:\Software"
IterateThroughMachineSubkeys -machine . -subKey $testKey

Or using PowerShell cmdlets:

$key = get-item "hkcu:\Software\Google\Chrome"
$key | get-childitem | foreach-object {
    write-host "Machine: $machine Module: $($_.PSChildName) Version: " `
    $key.OpenSubKey($_.PSChildName).GetValue("Version", "Not found", [Microsoft.Win32.RegistryValueOptions]::None)
}


问:
Odoo template page doesn't update when xml changes
Just started Odoo for a client, and I have a major problem with a template.

a simple template that has some divs and headers.
I also have a record for it to show in the main menu.

Everything works when i first create it.
However if it happens that i want to add or change some html, those changes don't show on the website page (even after I refresh/upgrade the theme).
The website builder allows me to change the text and whatnot, but that's not what I need. I want to be able to change the html structure from the XML. But as soon as the page is created the first time... I'm not allowed to. The page will only display the page as first created.

Hope it's clear and thank you in advance for any help.

Joe

答: Delete your template from the front end then update your module and check it up.</p>