问:
Apache SSL Configuration and Browsers <GRIPE>
Of course, I should be more diligent to ensure that the server name in my Apache HTTPD.conf file match the certificate.  But the browser is clearly unhappy when the certificate doesn't match the HTTP response.

One user was alerted that "Security certificate problems may indicate an attempt to fool you or intercept any data that you send to the server."  My customer is complaining that my misconfiguration damaged her reputation, and I can see her point.

Have browser vendors concluded that if the message were less alarming and acknowledged the possibility of a misconfiguration that the floodgates of social engineering would be overwhelming?

Seems like a common mistake.  Anyone else experience similar fallout?

答:
Many proxy servers operate the same way as man-in-the-middle attackers.  Lots of network security depends on these proxy servers and your proposal would make it more difficult to implement a common security practice.  Also, the check does not protect users against the obvious attack of a forged URL whose "authenticity" is validated with a matching certificate.

This design might be effective against a brute force certificate forging attack that sends millions of random forgeries.  But otherwise, it seems unlikely that the mismatch is caused by the forgery attempt of an attacker.  As far as I know, certificate forgery is practically impossible.


来源: stackexchange

问:
mongo single replicate which was converted using Ops Manager automation need oplog?
I have converted standalone to single replica set using Ops Manager Automation and activated backup so its working fine. when I see .conf file I do not OplogsizeMB parameter, so my question is do we need add oplogsizemb parameter to have continuos oplog slice backups of mongodb to Ops Manager or not.

Thanks

答:
No, you don't need to add it - it's an optional parameter.

If you don't set it, then the mongod process will automatically allocate a fixed amount of space for the oplog: typically 5% of available disk space.

ContentLicense: CC BY-SA 3.0


问:
Make Django build contenteditable div for TextField instead of textarea
In my Django 1.10 project, I have a model:

```<code>class Contact(models.Model):
    notes = models.TextField()
</code>```

...and ModelForm:

```<code>class ContactForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control input-sm plain'
            if field.required == True:
                field.widget.attrs['required'] = ''

    class Meta:
        model = Contact
        fields = ('notes',)
</code>```

I have two questions regarding this:

Can I make Django render the notes field as div with contenteditable=true rather than textarea?

If yes, how do I automate the form.save() method?

The second question is a bit vague, so I would be grateful for a hint regarding the first question. I have read through the doc, but couldn't find relevant section :(

答:
First one can be done by using jquery. Since django will load the textarea with id='id_notes'. So after that you can select the element and do whatever you want to.

And in second one you can redefine the save method by writing you own save function in forms.py Here is an example for a url shortener.
Save method basically, defines what you want to execute when something is being committed to database.

Body:
In my Django 1.10 project, I have a model:

class Contact(models.Model):
    notes = models.TextField()

...and ModelForm:

class ContactForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control input-sm plain'
            if field.required == True:
                field.widget.attrs['required'] = ''

    class Meta:
        model = Contact
        fields = ('notes',)

I have two questions regarding this:

Can I make Django render the notes field as div with contenteditable=true rather than textarea?

If yes, how do I automate the form.save() method?

The second question is a bit vague, so I would be grateful for a hint regarding the first question. I have read through the doc, but couldn't find relevant section :(


问:
Boost foreach conflicts with Q_FOREACH (Qt) and moc generation?
I have a program edited in Vs 2008 using some libraries such as Qt and Point Cloud Library (PCL).

PCL has a 3rd party library which contains boost.

However, some errors appeared after compiling:

1>C:\Program Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/sequenced_index.hpp(926)
  : error C3083: 'Q_FOREACH': the symbol to the left of a '::' must be a
  type 1>C:\Program Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/sequenced_index.hpp(926)
  : error C2039: 'tag' : is not a member of 'boost' 1>C:\Program
  Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/sequenced_index.hpp(926)
  : error C2061: syntax error : identifier 'tag' 1>C:\Program Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/ordered_index.hpp(1399) : error C3083: 'Q_FOREACH': the symbol to the left of a '::' must be a
  type 1>C:\Program Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/ordered_index.hpp(1399) : error C2039: 'tag' : is not a member of 'boost' 1>C:\Program
  Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/ordered_index.hpp(1399) : error C2061: syntax error : identifier 'tag' 1>C:\Program Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/hashed_index.hpp(1254) : error C3083: 'Q_FOREACH': the symbol to the left of a '::' must be a
  type 1>C:\Program Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/hashed_index.hpp(1254) : error C2039: 'tag' : is not a member of 'boost' 1>C:\Program
  Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/hashed_index.hpp(1254) : error C2061: syntax error : identifier 'tag' 1>C:\Program Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/random_access_index.hpp(1012)
  : error C3083: 'Q_FOREACH': the symbol to the left of a '::' must be a
  type 1>C:\Program Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/random_access_index.hpp(1012)
  : error C2039: 'tag' : is not a member of 'boost' 1>C:\Program
  Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/random_access_index.hpp(1012)
  : error C2061: syntax error : identifier 'tag'

For the first problem, the error location in the source file is:

```<code>template<typename SuperMeta,typename TagList>
inline boost::mpl::true_* boost_foreach_is_noncopyable(
  boost::multi_index::detail::random_access_index<SuperMeta,TagList>*&,
  boost::foreach::tag) // <-------------error here for the first compile error.
{
  return 0;
}
</code>```

I think maybe this indicates that the Q_FOREACH conflicts with the boost foreach.

But I do not know how to solve this problem?

答:
The problem is that Qt defines a foreach macro (#define foreach Q_FOREACH) which conflicts with the boost::foreach namespace.

The easiest ways to solve it is to either include Boost before Qt or simply undefine the Qt's macro before including the boost's header file. I prefer the second since it won't need extra  documentation (// remember to include Boost before Qt), and it is easier to manage in nested header files and if you use precompiled headers.

```<code>#undef foreach
#include <boost/foreach.hpp>
</code>```

This option is less invasive than disabling Qt's keywords (compilation flag -DQT_NO_KEYWORDS) and can be applied only in the affected files if wanted. It won't affect the use of Q_FOREACH (obviously if you use the Qt's foreach it will fail). It also works independently that Qt is included before or after <boost/foreach.hpp>.

Body:
I have a program edited in Vs 2008 using some libraries such as Qt and Point Cloud Library (PCL).

PCL has a 3rd party library which contains boost.

However, some errors appeared after compiling:

1>C:\Program Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/sequenced_index.hpp(926)
  : error C3083: 'Q_FOREACH': the symbol to the left of a '::' must be a
  type 1>C:\Program Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/sequenced_index.hpp(926)
  : error C2039: 'tag' : is not a member of 'boost' 1>C:\Program
  Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/sequenced_index.hpp(926)
  : error C2061: syntax error : identifier 'tag' 1>C:\Program Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/ordered_index.hpp(1399) : error C3083: 'Q_FOREACH': the symbol to the left of a '::' must be a
  type 1>C:\Program Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/ordered_index.hpp(1399) : error C2039: 'tag' : is not a member of 'boost' 1>C:\Program
  Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/ordered_index.hpp(1399) : error C2061: syntax error : identifier 'tag' 1>C:\Program Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/hashed_index.hpp(1254) : error C3083: 'Q_FOREACH': the symbol to the left of a '::' must be a
  type 1>C:\Program Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/hashed_index.hpp(1254) : error C2039: 'tag' : is not a member of 'boost' 1>C:\Program
  Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/hashed_index.hpp(1254) : error C2061: syntax error : identifier 'tag' 1>C:\Program Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/random_access_index.hpp(1012)
  : error C3083: 'Q_FOREACH': the symbol to the left of a '::' must be a
  type 1>C:\Program Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/random_access_index.hpp(1012)
  : error C2039: 'tag' : is not a member of 'boost' 1>C:\Program
  Files\PCL
  1.5.1\3rdParty\Boost\include\boost/multi_index/random_access_index.hpp(1012)
  : error C2061: syntax error : identifier 'tag'

For the first problem, the error location in the source file is:

template<typename SuperMeta,typename TagList>
inline boost::mpl::true_* boost_foreach_is_noncopyable(
  boost::multi_index::detail::random_access_index<SuperMeta,TagList>*&,
  boost::foreach::tag) // <-------------error here for the first compile error.
{
  return 0;
}

I think maybe this indicates that the Q_FOREACH conflicts with the boost foreach.

But I do not know how to solve this problem?

Body:
The problem is that Qt defines a foreach macro (#define foreach Q_FOREACH) which conflicts with the boost::foreach namespace.

The easiest ways to solve it is to either include Boost before Qt or simply undefine the Qt's macro before including the boost's header file. I prefer the second since it won't need extra  documentation (// remember to include Boost before Qt), and it is easier to manage in nested header files and if you use precompiled headers.

#undef foreach
#include <boost/foreach.hpp>

This option is less invasive than disabling Qt's keywords (compilation flag -DQT_NO_KEYWORDS) and can be applied only in the affected files if wanted. It won't affect the use of Q_FOREACH (obviously if you use the Qt's foreach it will fail). It also works independently that Qt is included before or after <boost/foreach.hpp>.


问:
Displaying user input html with newlines
I have comments section in my application where users enter input in a text area. I want to prevent the line breaks they enter but also display html as a string. For example, if comment.body is

```<code>Hello, this is the code: <a href='foo'>foo</a>

Bye
</code>```

I want it to be displayed just as above. The same with anything else, including iframe tags.

The closest I got is:

```<code>= simple_format(comment.body)
</code>```

but it sanitizes html code and it's not displayed. Example: foo biz bar is displayed as:

```<code>foo biz bar
</code>```

What should I do to achieve what I want?

答:
Having done something similar in the past, I think you must first understand why HTML is sanitized from user input.

Imagine I wrote the following into a field that accepted HTML and displays this to the front page.

```<code><script>alert('Hello')</script>
</code>```

The code would execute for anyone visiting the front-page and annoyingly trigger a JS alert for every visitor.

Maybe not much of an issue yet, but imagine I wrote some AJAX request that sent user session IDs to my own server. Now this is an issue... because people's sessions are being hijacked.

Furthermore, there is a full JavaScript based exploitation framework called BeEF that relies on this type of website exploit called Cross-site Scripting (XSS).

BeEF does extremely scary stuff and is worth taking a look at when considering user generated HTML.

http://guides.rubyonrails.org/security.html#cross-site-scripting-xss

So what to do? Well if you checked in your DB you'd see that the tags are actually being stored, but like you pointed out aren't displayed.

You could .html_safe the content, but again I strongly advise against this.

Maybe instead you should write an alternative .html_safe method yourself, something like html_safe_whitelisted_tags.

As for removing newlines, you say you want to display as is. So replacing /n with
, as pointed out by Michael, would be the solution for you.

```<code>comment.body.gsub('\n', '<br />').html_safe_whitelisted_tags
</code>```

Body:
I have comments section in my application where users enter input in a text area. I want to prevent the line breaks they enter but also display html as a string. For example, if comment.body is

Hello, this is the code: foo

Bye

I want it to be displayed just as above. The same with anything else, including iframe tags.

The closest I got is:

= simple_format(comment.body)

but it sanitizes html code and it's not displayed. Example: foo biz bar is displayed as:

foo biz bar

What should I do to achieve what I want?

Body:
Having done something similar in the past, I think you must first understand why HTML is sanitized from user input.

Imagine I wrote the following into a field that accepted HTML and displays this to the front page.

<script>alert('Hello')</script>

The code would execute for anyone visiting the front-page and annoyingly trigger a JS alert for every visitor.

Maybe not much of an issue yet, but imagine I wrote some AJAX request that sent user session IDs to my own server. Now this is an issue... because people's sessions are being hijacked.

Furthermore, there is a full JavaScript based exploitation framework called BeEF that relies on this type of website exploit called Cross-site Scripting (XSS).

BeEF does extremely scary stuff and is worth taking a look at when considering user generated HTML.

http://guides.rubyonrails.org/security.html#cross-site-scripting-xss

So what to do? Well if you checked in your DB you'd see that the tags are actually being stored, but like you pointed out aren't displayed.

You could .html_safe the content, but again I strongly advise against this.

Maybe instead you should write an alternative .html_safe method yourself, something like html_safe_whitelisted_tags.

As for removing newlines, you say you want to display as is. So replacing /n with <br>, as pointed out by Michael, would be the solution for you.

comment.body.gsub('\n', '<br />').html_safe_whitelisted_tags


问:
An example of template subclassing
I was reading SEQAN  documentation. In Getting Started section, they mentioned "Template Subclassing" as a method to overcome runtime polymorphism overhead.

OOP vs. Generic Programming:
  In SeqAn, we use a technique called template subclassing which is based on generic programming. This technique provides polymorphism into C++ programs at compile time using templates. Such static polymorphism is different from runtime polymorphism which is supported in C++ using subclassing and virtual functions. It comes at the cost of some additional typing but has the advantage that the compiler can inline all function calls and thus achieve better performance. An example will be given in the section “From OOP to SeqAn” in the First Steps Tutorial.

Unfortunately there is no example to illustrate its usage yet. I really appreciate if anyone provide a simple example.

I wrote simple template class but I am not sure if this what they meant by template subclassing!

```<code>struct Base {
    virtual void nockNock() {
        std::cout << "I am Base class." << std::endl;
    }
};

template<typename T>
class Derived: public Base {
public:

    void anotherNock() {
        std::cout << "It's me the Derived class." << std::endl;
    }
    void nockNock() {
        std::cout << "I am Derived class." << std::endl;
        anotherNock();
    }

public:
    Derived(){};
};

int main() {
    Base* myArray[10];

    myArray[0] = new Derived<int>;

    myArray[0]->nockNock();

    return 0;
}
</code>```

答:
After a brief look at SeqAn manual I came up with the following example:

```<code>namespace Tags {
struct Noone {};
struct Someone {};
}

template <typename T, typename U>
class Base {
public:
  using KindOfThing = U;

  // implement algorithm
  bool knock() {
    static_cast<T*>(this)->knockKnock();
    static_cast<T*>(this)->listen();
    static_cast<T*>(this)->knockKnock();
    static_cast<T*>(this)->tellName("Johnny");
    return static_cast<T*>(this)->knockKnock();
  }
};

template <typename T>
class Base<T, Tags::Noone> {
public:
  using KindOfThing = Tags::Noone;

  void work() {
    static_cast<T*>(this)->makeSounds();
    static_cast<T*>(this)->doJob();
  }
};

class WashingMachine : public Base<WashingMachine, Tags::Noone> {
public:
  void makeSounds(){};

  void doJob(){};
};

class Meow : public Base<Meow, Tags::Someone> {
public:
  Meow() : meows(0) {}

  //implement Base interface
  void listen() { std::cout << "..." << std::endl; }

  //implement Base interface
  bool knockKnock() {
    std::cout << "Meow..." << std::endl;
    return meows++ > 3;
  }

  void tellName(std::string const& name) { (void)name; }

  int meows;
};

class WhoIsThere : public Base<WhoIsThere, Tags::Someone> {
public:
  //implement Base interface
  void listen() { std::cout << "<Steps>..." << std::endl; }

  //implement Base interface
  bool knockKnock() {
    std::cout << "WhoIsThere?" << std::endl;
    return isDone;
  }

  void tellName(std::string const& name) {
    isDone = true;
    std::cout << name + " is here))!" << std::endl;
  }

  bool isDone;
};

template <typename T, typename U>
void performKnocking(T&& item, U) {
  std::cout << "......" << std::endl;
  while (!item.knock())
    ;
}

template <typename T>
void performKnocking(T&& item, Tags::Noone) {
  std::cout << "Noone" << std::endl;
}

template <typename... TArgs>
void performKnockingToEveryone(TArgs&&... sequence) {
  int dummy[] = {(performKnocking(sequence, typename TArgs::KindOfThing()), 0)...};
}

int main() {
  performKnockingToEveryone(
    Meow(), WashingMachine(), WhoIsThere(), Meow(), WashingMachine());
  return 0;
}
</code>```

The point is that the design that SeqAn is telling is moving from the realm of usual OOP programming (with polymorphism, type abstractions and etc.) to C++ template programming (more precisely see Item 1 in Effective C++). The same like there are zellions of books on OOP design, not less, if not more, there are material on Template C++ programming (see The Definitive C++ Book Guide and List for both kinds of programming techniques and more).

In this example, I show two techniques of designing that the SeqAn documentation emphasizes.

There is a base implementing some kind of operation that has several steps common for other subclasses. The base provide kind of Template Method (there is nothing related to C++ templates there, it is purely OOP pattern, just the name has the same word) from operations - setting an interface (not OOP interface, but C++ Template interface) for the deriving classes. Those subclasses, in their turn, implement those operations. You get static (resolved at compile time behaviour) polymorphism (type that has an interface that has different behavior from one instance to another). There is no runtime polymorphism because for runtime (OOP realm) those all are different types, they are all different for compile time as well. This polymorphism exists in C++ templates (templates parameters and templates declarations). Example: Boost Iterator Facade.

Tag dispatching technique employs function overloading resolution depending on the argument(s) type(s). It helps when you have free function as part of your API and chose necessary one to call depending on situation (example STL Iterators iterator_tag(s) and iterator free functions). For exmaple, consider OOP Visitor Pattern and you have AbstractVisitor and KnockingVisitor. You take a vector of Base* and call accept on each, that calls visit and your KnockingVisitor does the knocking. With tag dispatching you use tags. This might be a lame comparation between OOP techniques and tag dispatching, but it is just one of many possible examples. Like with OOP design where and what pattern to use, with C++ Templates techniques you need experience.

This example is quite primitive, because there is no actual task behind it is design, however, when you have an ambitious goal that gets more interesting and complicated. C++ Templates might be one of the choices to archive it.

Title: An example of template subclassing

Body:
I was reading SEQAN  documentation. In Getting Started section, they mentioned "Template Subclassing" as a method to overcome runtime polymorphism overhead.

OOP vs. Generic Programming:
  In SeqAn, we use a technique called template subclassing which is based on generic programming. This technique provides polymorphism into C++ programs at compile time using templates. Such static polymorphism is different from runtime polymorphism which is supported in C++ using subclassing and virtual functions. It comes at the cost of some additional typing but has the advantage that the compiler can inline all function calls and thus achieve better performance. An example will be given in the section “From OOP to SeqAn” in the First Steps Tutorial.

Unfortunately there is no example to illustrate its usage yet. I really appreciate if anyone provide a simple example.

I wrote simple template class but I am not sure if this what they meant by template subclassing!

struct Base {
    virtual void nockNock() {
        std::cout << "I am Base class." << std::endl;
    }
};

template<typename T>
class Derived: public Base {
public:

    void anotherNock() {
        std::cout << "It's me the Derived class." << std::endl;
    }
    void nockNock() {
        std::cout << "I am Derived class." << std::endl;
        anotherNock();
    }

public:
    Derived(){};
};

int main() {
    Base* myArray[10];

    myArray[0] = new Derived<int>;

    myArray[0]->nockNock();

    return 0;
}

Body:
After a brief look at SeqAn manual I came up with the following example:

namespace Tags {
struct Noone {};
struct Someone {};
}

template <typename T, typename U>
class Base {
public:
  using KindOfThing = U;

  // implement algorithm
  bool knock() {
    static_cast<T*>(this)->knockKnock();
    static_cast<T*>(this)->listen();
    static_cast<T*>(this)->knockKnock();
    static_cast<T*>(this)->tellName("Johnny");
    return static_cast<T*>(this)->knockKnock();
  }
};

template <typename T>
class Base<T, Tags::Noone> {
public:
  using KindOfThing = Tags::Noone;

  void work() {
    static_cast<T*>(this)->makeSounds();
    static_cast<T*>(this)->doJob();
  }
};

class WashingMachine : public Base<WashingMachine, Tags::Noone> {
public:
  void makeSounds(){};

  void doJob(){};
};

class Meow : public Base<Meow, Tags::Someone> {
public:
  Meow() : meows(0) {}

  //implement Base interface
  void listen() { std::cout << "..." << std::endl; }

  //implement Base interface
  bool knockKnock() {
    std::cout << "Meow..." << std::endl;
    return meows++ > 3;
  }

  void tellName(std::string const& name) { (void)name; }

  int meows;
};

class WhoIsThere : public Base<WhoIsThere, Tags::Someone> {
public:
  //implement Base interface
  void listen() { std::cout << "<Steps>..." << std::endl; }

  //implement Base interface
  bool knockKnock() {
    std::cout << "WhoIsThere?" << std::endl;
    return isDone;
  }

  void tellName(std::string const& name) {
    isDone = true;
    std::cout << name + " is here))!" << std::endl;
  }

  bool isDone;
};

template <typename T, typename U>
void performKnocking(T&& item, U) {
  std::cout << "......" << std::endl;
  while (!item.knock())
    ;
}

template <typename T>
void performKnocking(T&& item, Tags::Noone) {
  std::cout << "Noone" << std::endl;
}

template <typename... TArgs>
void performKnockingToEveryone(TArgs&&... sequence) {
  int dummy[] = {(performKnocking(sequence, typename TArgs::KindOfThing()), 0)...};
}

int main() {
  performKnockingToEveryone(
    Meow(), WashingMachine(), WhoIsThere(), Meow(), WashingMachine());
  return 0;
}

The point is that the design that SeqAn is telling is moving from the realm of usual OOP programming (with polymorphism, type abstractions and etc.) to C++ template programming (more precisely see Item 1 in Effective C++). The same like there are zellions of books on OOP design, not less, if not more, there are material on Template C++ programming (see The Definitive C++ Book Guide and List for both kinds of programming techniques and more).

In this example, I show two techniques of designing that the SeqAn documentation emphasizes.

There is a base implementing some kind of operation that has several steps common for other subclasses. The base provide kind of Template Method (there is nothing related to C++ templates there, it is purely OOP pattern, just the name has the same word) from operations - setting an interface (not OOP interface, but C++ Template interface) for the deriving classes. Those subclasses, in their turn, implement those operations. You get static (resolved at compile time behaviour) polymorphism (type that has an interface that has different behavior from one instance to another). There is no runtime polymorphism because for runtime (OOP realm) those all are different types, they are all different for compile time as well. This polymorphism exists in C++ templates (templates parameters and templates declarations). Example: Boost Iterator Facade.

Tag dispatching technique employs function overloading resolution depending on the argument(s) type(s). It helps when you have free function as part of your API and chose necessary one to call depending on situation (example STL Iterators iterator_tag(s) and iterator free functions). For exmaple, consider OOP Visitor Pattern and you have AbstractVisitor and KnockingVisitor. You take a vector of Base* and call accept on each, that calls visit and your KnockingVisitor does the knocking. With tag dispatching you use tags. This might be a lame comparation between OOP techniques and tag dispatching, but it is just one of many possible examples. Like with OOP design where and what pattern to use, with C++ Templates techniques you need experience.

This example is quite primitive, because there is no actual task behind it is design, however, when you have an ambitious goal that gets more interesting and complicated. C++ Templates might be one of the choices to archive it.


问:
MySQL JOIN query giving different results on different databases
I'm running an query on my database locally installed on my machine and getting a result different to one when ran on my AWS RDS database.
I am running:

```<code>SELECT SUM(Hours) AS 'TotalHours', Username, Name, Project_Name, Project_Ref, (37.5-SUM(Hours)) AS 'Missing'
FROM bookings b
JOIN projects p ON b.Project_ID=p.Project_ID
RIGHT JOIN users u ON b.User_ID=u.User_ID
WHERE  ((Date BETWEEN '2017-07-01' AND '2017-07-30') OR Date IS NULL)
GROUP BY u.User_ID
</code>```

When ran on local I get back every entry from the users table, even if they haven't made a booking on the bookings table.

When ran on my server database I only get back users who have made a booking, not ever entry like expected when doing a right join.

答:
Try using LEFT JOIN instead of RIGHT JOIN, and put the Date criteria in the ON clause:

```<code>SELECT SUM(Hours) AS 'TotalHours', Username, Name, Project_Name, Project_Ref, (37.5-SUM(Hours)) AS 'Missing'
FROM users AS u
LEFT JOIN bookings AS b ON b.User_ID = u.User_ID AND b.DATE BETWEEN '2017-07-01' AND '2017-07-30'
LEFT JOIN projects AS p ON b.Project_ID=p.Project_ID
</code>```

I suspect the problem is related to the INNER JOIN with projects in between the users and bookings table.

Body:
I'm running an query on my database locally installed on my machine and getting a result different to one when ran on my AWS RDS database.
I am running:

SELECT SUM(Hours) AS 'TotalHours', Username, Name, Project_Name, Project_Ref, (37.5-SUM(Hours)) AS 'Missing'
FROM bookings b
JOIN projects p ON b.Project_ID=p.Project_ID
RIGHT JOIN users u ON b.User_ID=u.User_ID
WHERE  ((Date BETWEEN '2017-07-01' AND '2017-07-30') OR Date IS NULL)
GROUP BY u.User_ID

When ran on local I get back every entry from the users table, even if they haven't made a booking on the bookings table.

When ran on my server database I only get back users who have made a booking, not ever entry like expected when doing a right join.

Body:
Try using LEFT JOIN instead of RIGHT JOIN, and put the Date criteria in the ON clause:

SELECT SUM(Hours) AS 'TotalHours', Username, Name, Project_Name, Project_Ref, (37.5-SUM(Hours)) AS 'Missing'
FROM users AS u
LEFT JOIN bookings AS b ON b.User_ID = u.User_ID AND b.DATE BETWEEN '2017-07-01' AND '2017-07-30'
LEFT JOIN projects AS p ON b.Project_ID=p.Project_ID

I suspect the problem is related to the INNER JOIN with projects in between the users and bookings table.


问:
View not displaying from controller
I have a basic controller:

```<code>using System.Web Mvc;

namespace MainProject.Controllers
{
   public class Main : Controllers
   {
      public ActionResult Index()
      {
           return View();
      }
   }
}
</code>```

with a view:

View/
    Main/
        Index.cshtml

And yet it doesn't return the page, it just the resource cannot be found. What am I missing here?

localhost:60555/Main/Index

答:
try the below changed code it will surely work for you

your code:

```<code>using System.Web Mvc;
    namespace MainProject.Controllers
    {
       public class Main : Controllers
       {
          public ActionResult Index()
          {
               return View();
          }
       }
    }
</code>```

Changed code :

```<code>  using System.Web Mvc;
    namespace MainProject.Controllers
    {
        public class MainController : Controller
        {

            public ActionResult Index()
            {
                return View();
            }

    }
</code>```

Hope it was helpful

Thanks

Karthik

Title: View not displaying from controller

Body:
I have a basic controller:

using System.Web Mvc;

namespace MainProject.Controllers
{
   public class Main : Controllers
   {
      public ActionResult Index()
      {
           return View();
      }
   }
}

with a view:

View/
    Main/
        Index.cshtml

And yet it doesn't return the page, it just the resource cannot be found. What am I missing here?

localhost:60555/Main/Index

Body:
try the below changed code it will surely work for you

your code:

using System.Web Mvc;
    namespace MainProject.Controllers
    {
       public class Main : Controllers
       {
          public ActionResult Index()
          {
               return View();
          }
       }
    }

Changed code :

  using System.Web Mvc;
    namespace MainProject.Controllers
    {
        public class MainController : Controller
        {

            public ActionResult Index()
            {
                return View();
            }

    }

Hope it was helpful

Thanks

Karthik


问:
Hide/Show 2 forms in winform
I have two Forms, Login and Form1. When I click btnLogin_Click on the Login form, it opens Form1 with this code:

```<code>private void btnLogin_Click(object sender, EventArgs e)
{
    Form1 pu = new Form1(label2.Text);
    pu.Show();
    pu.FormClosing += Pu_FormClosing;
    Hide();
}

private void Pu_FormClosing(object sender, FormClosingEventArgs e)
{
    this.Show();
}
</code>```

And when I click btnExit_Click on Form1, it closes the form and opens the Login form by using this code:

```<code>private void btnExit_Click(object sender, EventArgs e)
{
    this.Close();
}
</code>```

Now what I want is to find a way that, when I click btnExit it Hides Form1 and opens the Login form, and when I click the login button on the Login Form, it shows Form1 instead of creating a new instance.

答:
One way to handle this is to create a class-level variable for the Form1 instance:

```<code>public partial class Login : Form
{
    private Form1 pu;

    // code continued below...
</code>```

And then in the button click event we will hide the login form, ensure that the pu instance is not null (which it could be if the user closes the form instead of clicking the button that hides the form), and show our pu form instance.

If the instance IS null, then it will create a new one and hook up the event handlers. We will hook up both the VisibleChanged and FormClosing events to methods that will show our login form. Note that in the FormClosing event, we actually Cancel the close and hide the form instead:

```<code>    private void btnLogin_Click(object sender, EventArgs e)
    {
        Hide();

        if (pu == null)
        {
            pu = new Form1(label2.Text);
            pu.VisibleChanged += Pu_VisibleChanged;
            pu.FormClosing += Pu_FormClosing;
        }

        pu.Show();
    }

    private void Pu_VisibleChanged(object sender, EventArgs e)
    {
        // Only show the login form if the form1 is NOT visible
        if (!pu.Visible) Show();
    }

    private void Pu_FormClosing(object sender, FormClosingEventArgs e)
    {
        // Set cancel to true to prevent the form from closing, then hide the form instead
        e.Cancel = true;
        pu.Hide();
        this.Show();
    }
}
</code>```

Then the only other change you need to do is to make the form1 button Hide the form instead of closing it:

```<code>public partial class Form1 : Form
{
    private void btnExit_Click(object sender, EventArgs e)
    {
        Hide();
    }

    // rest of class code omitted...
}
</code>```

Title: Hide/Show 2 forms in winform

Body:
I have two Forms, Login and Form1. When I click btnLogin_Click on the Login form, it opens Form1 with this code:

private void btnLogin_Click(object sender, EventArgs e)
{
    Form1 pu = new Form1(label2.Text);
    pu.Show();
    pu.FormClosing += Pu_FormClosing;
    Hide();
}

private void Pu_FormClosing(object sender, FormClosingEventArgs e)
{
    this.Show();
}

And when I click btnExit_Click on Form1, it closes the form and opens the Login form by using this code:

private void btnExit_Click(object sender, EventArgs e)
{
    this.Close();
}

Now what I want is to find a way that, when I click btnExit it Hides Form1 and opens the Login form, and when I click the login button on the Login Form, it shows Form1 instead of creating a new instance.

Body:
One way to handle this is to create a class-level variable for the Form1 instance:

public partial class Login : Form
{
    private Form1 pu;

    // code continued below...

And then in the button click event we will hide the login form, ensure that the pu instance is not null (which it could be if the user closes the form instead of clicking the button that hides the form), and show our pu form instance.

If the instance IS null, then it will create a new one and hook up the event handlers. We will hook up both the VisibleChanged and FormClosing events to methods that will show our login form. Note that in the FormClosing event, we actually Cancel the close and hide the form instead:

    private void btnLogin_Click(object sender, EventArgs e)
    {
        Hide();

        if (pu == null)
        {
            pu = new Form1(label2.Text);
            pu.VisibleChanged += Pu_VisibleChanged;
            pu.FormClosing += Pu_FormClosing;
        }

        pu.Show();
    }

    private void Pu_VisibleChanged(object sender, EventArgs e)
    {
        // Only show the login form if the form1 is NOT visible
        if (!pu.Visible) Show();
    }

    private void Pu_FormClosing(object sender, FormClosingEventArgs e)
    {
        // Set cancel to true to prevent the form from closing, then hide the form instead
        e.Cancel = true;
        pu.Hide();
        this.Show();
    }
}

Then the only other change you need to do is to make the form1 button Hide the form instead of closing it:

public partial class Form1 : Form
{
    private void btnExit_Click(object sender, EventArgs e)
    {
        Hide();
    }

    // rest of class code omitted...
}


问:
Class Library shared between an UWP app and a Bot Framework chatbot
I want to create a Class Library .dll that I want to include in my UWP app and my Bot Framework chatbot, that includes newtonsoft json dependencies. From what I can see this is just not possible. If I create it with .NetFramework and the bot reference it fine but the UWP app shows an error:

If I create it as a Class Library of type .NET Core, I can reference it in both projects, but there is a problem with the newtonsoft dependencies inside the library.
I don't want to start digging into this NuGet creation process, because it brings me no benefit at this point. I want to use dll.

Is it even possible to create a shared lib? I cannot believe it's that stupid

答:
According to this doc: https://learn.microsoft.com/en-us/dotnet/standard/library

if you want to target UWP apps, your .NET Core dll must be on .NET Standard 1.4 or less.

Just edit your .csproj file and change the NetStandard target framework :

<TargetFramework>netstandard1.4</TargetFramework>

EDIT: Also check the "Which .NET Standard version to target" section for best practices about using .NET Standard.


问:
oracle regular expression with number matching
I have a table which contains a column 'col1' having values like

```<code>    0.23
    0.0123
   90.013
   23.31
    0.87
  100.013
</code>```

How to get the records whole values matching with any number followed by 0.01 followed by any number in Oracle? I.e.

```<code>  0.0123
 90.013
100.013
</code>```

答:
Using Number Functions

Principle:
 reduce number to the whole number and whole number with first two decimals and perform a comparison.

```<code>SCOTT@dev>  --.01 match
      32   SELECT
     33      val,
     34      floor(val) whole_num,
     35      trunc(
     36          val,
     37          2
     38      ) whole_num_with_dec
     39  FROM
     40      smple
     41  WHERE
     42      trunc(
     43          val,
     44          2
     45      ) - floor(val) =0.01;

val     whole_num      whole_num_with_dec

0.0123     0               0.01
90.013    90              90.01
100.013  100             100.01
</code>```

for the 0.01 match, I just shift the decimal to the left one digit and perform the same evaluation:

```<code> 32   SELECT
 33      val,
 34      floor(val / 10) mod_whole_num,
 35      trunc(
 36          val / 10,
 37          3
 38      ) mod_whole_num_with_dec
 39  FROM
 40      smple
 41  WHERE
 42      trunc(
 43          val / 10,
 44          3
 45*     ) - floor(val / 10) =0.001;

val     mod_whole_num  whole_num_with_dec

0.0123   0              0.001
90.013   9              9.001
100.013  10             10.001
</code>```

Body:
I have a table which contains a column 'col1' having values like

    0.23
    0.0123
   90.013
   23.31
    0.87
  100.013

How to get the records whole values matching with any number followed by 0.01 followed by any number in Oracle? I.e.

  0.0123
 90.013
100.013

Body:
Using Number Functions

Principle:
 reduce number to the whole number and whole number with first two decimals and perform a comparison.

SCOTT@dev>  --.01 match
      32   SELECT
     33      val,
     34      floor(val) whole_num,
     35      trunc(
     36          val,
     37          2
     38      ) whole_num_with_dec
     39  FROM
     40      smple
     41  WHERE
     42      trunc(
     43          val,
     44          2
     45      ) - floor(val) =0.01;

val     whole_num      whole_num_with_dec

0.0123     0               0.01
90.013    90              90.01
100.013  100             100.01

for the 0.01 match, I just shift the decimal to the left one digit and perform the same evaluation:

 32   SELECT
 33      val,
 34      floor(val / 10) mod_whole_num,
 35      trunc(
 36          val / 10,
 37          3
 38      ) mod_whole_num_with_dec
 39  FROM
 40      smple
 41  WHERE
 42      trunc(
 43          val / 10,
 44          3
 45*     ) - floor(val / 10) =0.001;

val     mod_whole_num  whole_num_with_dec

0.0123   0              0.001
90.013   9              9.001
100.013  10             10.001


问:
Java downloading file: "Connection timed out: connect"
When I'm downloading file (35MB) using below code. It gives me the output as:

Connection timed out: connect

Below is my java codes for file downloading process. How can I fix this issue?

//download file
public void download(String url, File destination) throws IOException {
    URL website = new URL(url);
    ReadableByteChannel rbc = Channels.newChannel(website.openStream());
    FileOutputStream fos = new FileOutputStream(destination);
    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}

public void parserAction() throws Exception {
    // InputStream is = new FileInputStream("en-parser-chunking.bin");
    File modelFile = new File("en-parser-chunking.bin");

    if (!modelFile.exists()) {
        System.out.println("Downloading model.");
        download("file://E:/Final Project/Softwares and tools/en-parser-chunking.bin", modelFile);

    }
    ParserModel model = new ParserModel(modelFile);
    Parser parser = ParserFactory.create(model);
    Parse topParses[] = ParserTool.parseLine(line, parser, 1);
    for (Parse p : topParses) {
        //p.show();
        getNounPhrases(p);
    }
}
```

答:
Use following codes to set a time out for the connection manually and see which time will be long enough to let the file being uploaded successfully:

```<code>            String url;

         try{
         HttpURLConnection Conn = (HttpURLConnection) new URL( url ).openConnection();

                                      Conn.setConnectTimeout(2000);
                                      Conn.setReadTimeout(2000);

             }
     catch (java.lang.ClassCastException|ConnectException|java.lang.IllegalArgumentException|java.net.MalformedURLException  ex) { }  //catch the possible exception.
     catch (SSLHandshakeException |SocketException | SocketTimeoutException | UnknownHostException ex)
</code>```

Times are in milliseconds by the way.

Body:
Use following codes to set a time out for the connection manually and see which time will be long enough to let the file being uploaded successfully:

            String url;

         try{
         HttpURLConnection Conn = (HttpURLConnection) new URL( url ).openConnection();

                                      Conn.setConnectTimeout(2000);
                                      Conn.setReadTimeout(2000);

             }
     catch (java.lang.ClassCastException|ConnectException|java.lang.IllegalArgumentException|java.net.MalformedURLException  ex) { }  //catch the possible exception.
     catch (SSLHandshakeException |SocketException | SocketTimeoutException | UnknownHostException ex)

Times are in milliseconds by the way.


问:
Structurizing files without db
Basically i have simple form which user uses for files uploading. Files should be stored under /files/ directory with some subdirectories for almost equally splitting files. e.g. /files/sub1/sub2/file1.txt

Also i need to not to store equal files (by filename).

I have own solution. Calculate sha1 from filename. Take first 5 symbols - abcde for example and put file in /files/a/b/c/d/e/ this works well, but gives situation when one folder contains 4k files, 2nd 6k files. Is there any way to make files count be more closer to each other? Max files count can be 10k or 10kk.

Thanks for any help.

P.S. May be i explained something wrong, so once again :) Task is simple - you have only html and php (without any db) and files directory where you should store only uploaded files without any own data. You should develop script that can handle storing uploads to files directory without storing duplicates (by filename) and split uploaded files by subdirectories by files count in each directory (optimal and count files in each directory should be close to each other).

答:
I have no idea why you want it taht way. But if you REALLY have to do it this way, iI would suggest you set a limit how many bytes are stored in each folder. Everytime you have to save the data you open a log with

the current sub

the total number of bytes written to that directory

If necesary you create a new sub diretory(you coulduse th current timestempbecause it wont repeat) and reset the bytecount
Then you save the file and increment the byte count by the number of bytes written.

I highly doubt it is worth the work, but I do not really know why you want to distribute the files that way.

ContentLicense: CC BY-SA 2.5

Title: Structurizing files without db


问:
Export CSV from Mainframe DB2 in batch mode
how can I export in a CSV file the result of a SELECT query from Mainframe DB2 in Batch mode?
I have tried the FILE MANAGER online mode and it works but I need to use the batch mode for a better performance.
I can also use ISQL but I don't know which parameters I have to use to create a CSV file.
Thanks</p>

答: On iserie you have the CPYTOIMPF command, may be on zos too</p>


问:
Accessing internal storage in Android
I'm developing an Android app that needs to display images from the default camera folder. My problem is that I do not know how to find what is the internal default storage folder for camera photos.

When I look for it connecting the phone to the PC (it is a Samsung Galaxy S7 without SD card), I see that the pictures are stored in DCIM/Camera. However, this does not work. Doing: files = new File("DCIM/Camera/"); results in the app saying there is nothing there.

How can I find the default internal storage folder for camera photos?

答:
Firstly, you need to understand Android.

Internal storage is the app private storage

External storage is the publically accessible storage area

External storage in Android means the public storage and means internal storage as in device memory and SD card. Saving to external storage means device internal and SD card, while saving to itnernal storage means app private storage.

So, the images are stored in the external storage or the app public storage where any app can save, load and manage files. The images are publically available and thus not in internal storage by developer definition.

Now, you need the WRITE_EXTERNAL_STORAGE permission and if you target API 23 you also need to request it because it is a dangerous permission.

To access the images, you need to create a new file:

```<code>storageDir = new File(
    Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES
    ),
    "album name here, or remove this part to save or load directly into DCIM"
);
</code>```

This can be used to save or load images, but remember to index the directory to find the image before loading to prevent IOException

Title: Accessing internal storage in Android

Body:
Firstly, you need to understand Android.

Internal storage is the app private storage

External storage is the publically accessible storage area

External storage in Android means the public storage and means internal storage as in device memory and SD card. Saving to external storage means device internal and SD card, while saving to itnernal storage means app private storage.

So, the images are stored in the external storage or the app public storage where any app can save, load and manage files. The images are publically available and thus not in internal storage by developer definition.

Now, you need the WRITE_EXTERNAL_STORAGE permission and if you target API 23 you also need to request it because it is a dangerous permission.

To access the images, you need to create a new file:

storageDir = new File(
    Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES
    ),
    "album name here, or remove this part to save or load directly into DCIM"
);

This can be used to save or load images, but remember to index the directory to find the image before loading to prevent IOException


问:
C#: Access Enum from another class
I know I can declare an enum directly in the Namespace so everyone can access it being in the same namespace.

But can I declare it in a class to access from other class:

public class Class1
{
    public enum Mode { Selected, New }
}

public class Class2
{
    var class1 = new ();
    // Set the Mode
    class1.Mode = Mode.Selected;
}
```

Is it possible to use enums without declaring it in the namespace?

答:
You can declare an enum outside of a class:

```<code>namespace MyNamespace
{
    public enum MyEnum
    {
        Entry1,
        Entry2,
    }
}
</code>```

And then you can add using MyNamespace; where it needs to be used.

ContentLicense: CC BY-SA 4.0

Title: C#: Access Enum from another class

Body:
I know I can declare an enum directly in the Namespace so everyone can access it being in the same namespace.

But can I declare it in a class to access from other class:

public class Class1
{
    public enum Mode { Selected, New }
}

public class Class2
{
    var class1 = new ();
    // Set the Mode
    class1.Mode = Mode.Selected;
}

Is it possible to use enums without declaring it in the namespace?

Body:
You can declare an enum outside of a class:

namespace MyNamespace
{
    public enum MyEnum
    {
        Entry1,
        Entry2,
    }
}

And then you can add using MyNamespace; where it needs to be used.


问:
Imgur api ajax : No image data was sent to the api
I am trying to upload image to imgur through ajax.
I am using base64 encoded image.
Its showing that no data was sent even though i can see the base64 data in the console .

The error i get is :-

```<code>{"data":{"error":"No image data was sent to the upload api","request":"\/3\/image","method":"POST"},"success":false,"status":400}
</code>```

Should replace "data/jpeg" or  "data/png" with blank string ??

My code :-

```<code>$(document).ready(function(){

function upload_to_imgur(img)
{
      // $('body').text(img) ;
      var data = new FormData() ;
      data.append("image",img) ;

      $.ajax({
        url: "https://api.imgur.com/3/image",
        type: "POST",
        headers: {
          "Authorization": "Client-ID a867bb291ca25d3" ,
        },
        dataType:"json" ,
        contentType : "multipart/form-data;boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
        processData:false,
        data :data,
        success: function(response) {
          var photo = response.data.link;
          $('body').text(photo) ;
        }
      });
}

function base64_image(img)
{
    var reader = new FileReader() ;
    reader.onload = function(e){
        base64data = e.target.result ;
        upload_to_imgur(base64data) ;
    }
    reader.readAsDataURL(img)
}

$('#submit_button').click(function(){

    upload_to_imgur(document.getElementById('p_img_link1').files[0])

    query_string = " \
                INSERT INTO `cm_db_mg`.`products` (`p_list_img`, `p_img_link_1`, `p_img_link_2`, `p_title`, `p_c_s_id`, `p_description`, `p_tags`, `p_listPrice`, `p_mrp`, `p_publishStatus`, `p_publishType`, `p_sem`, `p_s_id`, `p_b_id`, `p_c_id`, `p_u_id_seller`, `p_cat_uniq`, `p_not_listed_cmnt`, `p_disclaimer`, `p_condition`, `p_return_allowed`, `created`, `updated`) \
                VALUES ('', '', 'te', '', NULL, '', '', '', '-1', '', '', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', 'First Hand', 'F', '', '');"

}) ;
</code>```

})  ;

答:
```<code>function upl_im(t) {
    var file = t.files[0];
    var fd = new FormData();
    fd.append("image", file);
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "https://api.imgur.com/3/image.json");
    xhr.onload = function() {
        var link_src=JSON.parse(xhr.responseText).data.link;
        document.getElementById('res').style.backgroundImage = 'url('+link_src+')';
    }
   xhr.setRequestHeader('Authorization', 'Client-ID a867bb291ca25d3');
    xhr.send(fd);
}
</code>```

See

Body:
I am trying to upload image to imgur through ajax.
I am using base64 encoded image.
Its showing that no data was sent even though i can see the base64 data in the console .

The error i get is :-

{"data":{"error":"No image data was sent to the upload api","request":"\/3\/image","method":"POST"},"success":false,"status":400}

Should replace "data/jpeg" or  "data/png" with blank string ??

My code :-

$(document).ready(function(){

function upload_to_imgur(img)
{
      // $('body').text(img) ;
      var data = new FormData() ;
      data.append("image",img) ;

      $.ajax({
        url: "https://api.imgur.com/3/image",
        type: "POST",
        headers: {
          "Authorization": "Client-ID a867bb291ca25d3" ,
        },
        dataType:"json" ,
        contentType : "multipart/form-data;boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
        processData:false,
        data :data,
        success: function(response) {
          var photo = response.data.link;
          $('body').text(photo) ;
        }
      });
}

function base64_image(img)
{
    var reader = new FileReader() ;
    reader.onload = function(e){
        base64data = e.target.result ;
        upload_to_imgur(base64data) ;
    }
    reader.readAsDataURL(img)
}

$('#submit_button').click(function(){

    upload_to_imgur(document.getElementById('p_img_link1').files[0])

    query_string = " \
                INSERT INTO `cm_db_mg`.`products` (`p_list_img`, `p_img_link_1`, `p_img_link_2`, `p_title`, `p_c_s_id`, `p_description`, `p_tags`, `p_listPrice`, `p_mrp`, `p_publishStatus`, `p_publishType`, `p_sem`, `p_s_id`, `p_b_id`, `p_c_id`, `p_u_id_seller`, `p_cat_uniq`, `p_not_listed_cmnt`, `p_disclaimer`, `p_condition`, `p_return_allowed`, `created`, `updated`) \
                VALUES ('', '', 'te', '', NULL, '', '', '', '-1', '', '', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '', 'First Hand', 'F', '', '');"

}) ;

})  ;

Body:
function upl_im(t) {
    var file = t.files[0];
    var fd = new FormData();
    fd.append("image", file);
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "https://api.imgur.com/3/image.json");
    xhr.onload = function() {
        var link_src=JSON.parse(xhr.responseText).data.link;
        document.getElementById('res').style.backgroundImage = 'url('+link_src+')';
    }
   xhr.setRequestHeader('Authorization', 'Client-ID a867bb291ca25d3');
    xhr.send(fd);
}

See


问:
Memory allocation for multiple inheritance with non-default constructors
I'm struggling a bit to understand multiple-inheritance. Apparently I chose to solve a very complicated problem that has multiple inheritance and also the diamond problem. Even if I I have found a couple of cases that are similar to my problem, for example this one, my question is is on memory more than order of execution.

Suppose I have the following:

```<code>class Matrix {
public:
  Matrix(int rows, int Cols) {
    // Build matrix of zeros
  }
};

class Symmetric : public virtual Matrix {
public:
  // It's enough to call Matrix constructor using the same number of rows and cols
  Symmetric(int size) : Matrix(size, size) {}
};

class PosDef : public virtual Matrix {
public:
  // We need different constructor, matrix of zeros is not pos def
  PosDef(int size) {
    // Build matrix of ones
  }
};

class SymmPosDef : public Symmetric, public PosDef {
public:
  // We basically want to use the PosDef constructor that gives symmetric matrix
  SymmPosDef(int size) : Matrix(size, size), Symmetric(size), PosDef(size) {}
};
</code>```

Because I have given non-default constructors the only way to initialise a SymmPosDef object is with the complicated chain SymmPosDef(int size) : Matrix(size, size), Symmetric(size), PosDef(size) {} and my question is how many matrices am I building?

Am I allocating space once for Matrix, once for Symmetric (which would be the same zero elements) and once for PosDef or am I reusing the same space?

Because the size of the matrices could be large I want to do the least possible work.

答:
Matrix is initialized (from initalizer list) only once, in the most derived class.
But all constructor body will be called.

With:

```<code>class SymmPosDef : public Symmetric, public PosDef {
public:
  SymmPosDef(int size) : Matrix(size, size), Symmetric(size), PosDef(size) {}
};
</code>```

You would have:

Matrix(size, size)

(Symmetric(int size) : Matrix(size, size) skipped)

Symmetric(int size) body (/*Empty*/).

(PosDef(int size) : Matrix(size, size) skipped)

PosDef(int size) body ( /* Build matrix of ones */ )

SymmPosDef(int size) body (/*Empty*/).

Body:
I'm struggling a bit to understand multiple-inheritance. Apparently I chose to solve a very complicated problem that has multiple inheritance and also the diamond problem. Even if I I have found a couple of cases that are similar to my problem, for example this one, my question is is on memory more than order of execution.

Suppose I have the following:

class Matrix {
public:
  Matrix(int rows, int Cols) {
    // Build matrix of zeros
  }
};

class Symmetric : public virtual Matrix {
public:
  // It's enough to call Matrix constructor using the same number of rows and cols
  Symmetric(int size) : Matrix(size, size) {}
};

class PosDef : public virtual Matrix {
public:
  // We need different constructor, matrix of zeros is not pos def
  PosDef(int size) {
    // Build matrix of ones
  }
};

class SymmPosDef : public Symmetric, public PosDef {
public:
  // We basically want to use the PosDef constructor that gives symmetric matrix
  SymmPosDef(int size) : Matrix(size, size), Symmetric(size), PosDef(size) {}
};

Because I have given non-default constructors the only way to initialise a SymmPosDef object is with the complicated chain SymmPosDef(int size) : Matrix(size, size), Symmetric(size), PosDef(size) {} and my question is how many matrices am I building?

Am I allocating space once for Matrix, once for Symmetric (which would be the same zero elements) and once for PosDef or am I reusing the same space?

Because the size of the matrices could be large I want to do the least possible work.

Body:
Matrix is initialized (from initalizer list) only once, in the most derived class.
But all constructor body will be called.

With:

class SymmPosDef : public Symmetric, public PosDef {
public:
  SymmPosDef(int size) : Matrix(size, size), Symmetric(size), PosDef(size) {}
};

You would have:

Matrix(size, size)

(Symmetric(int size) : Matrix(size, size) skipped)

Symmetric(int size) body (/*Empty*/).

(PosDef(int size) : Matrix(size, size) skipped)

PosDef(int size) body ( /* Build matrix of ones */ )

SymmPosDef(int size) body (/*Empty*/).


问:
Why JPA entity refresh is required despite disabling shared cache?
I'm using Eclipselink for JPA, and has a webapp which reads the tables in a configured interval. The database is modified externally by a tool to publish some data. Now my webapp makes a getAll() on an Entity and gets the result as a list. However, each time I get the same result list as it was from the first query. Surprisingly, new entries and deleted entries are reflected as expected in the result list. If I update an entry it still gets the original/old result.

From my search, most of the answers in stackoverflow points to JPA level cache, and can be summarized to these

Disable shared cache by settings <shared-cache-mode>NONE</shared-cache-mode>

Optionally, selectively disable cache on entities by using @Cacheable(false)

Evict cache by doing em.getEntityManagerFactory().getCache().evictAll()

There are some other/old/pre-JPA 2.0 and vendor specific solutions which sets some properties in persistence.xml

However, none of these solutions work in my case. The closest answers I came across was this, which says that

Any IDs that are already present in the Session cache are matched up to known entities, while any IDs that are not are populated based on database state. The previously known entities are not refreshed from the database at all.

Although this is in the context of Hibernate, I hit the same issue in Eclipselink. So after introducing a refresh on the list I get the expected result.

```<code>T objects = getAll();
for (T objects : object)
    em.refresh(object)

List<T> getAll() {
  EntityManager em = entityManagerFactory.createEntityManager();
  return  em.createQuery(em.getCriteriaBuilder().createQuery(type)).getResultList();
}
</code>```

Can someone explain this Session cache in the context of Eclipselink, and explain why shared-cache configuration has no impact on this ? Does a transaction transparently solve this problem (read transaction)? Is there an elegant solution/JPA configuration than doing refresh on object each time ?

答: Everything you've mentioned refers to the shared cache, but there are 2 levels of caching in JPA.  The shared cache (2nd level) and EntityManager managed entity cache (1st level).  EntityManagers are meant to represent transactional workspaces.  You should obtain new Entitymanager instances where appropriate rather than use a single one for everything, or call em.clear() on it to release resources.</p>

Body:
I'm using Eclipselink for JPA, and has a webapp which reads the tables in a configured interval. The database is modified externally by a tool to publish some data. Now my webapp makes a getAll() on an Entity and gets the result as a list. However, each time I get the same result list as it was from the first query. Surprisingly, new entries and deleted entries are reflected as expected in the result list. If I update an entry it still gets the original/old result.

From my search, most of the answers in stackoverflow points to JPA level cache, and can be summarized to these

Disable shared cache by settings <shared-cache-mode>NONE</shared-cache-mode>

Optionally, selectively disable cache on entities by using @Cacheable(false)

Evict cache by doing em.getEntityManagerFactory().getCache().evictAll()

There are some other/old/pre-JPA 2.0 and vendor specific solutions which sets some properties in persistence.xml

However, none of these solutions work in my case. The closest answers I came across was this, which says that

Any IDs that are already present in the Session cache are matched up to known entities, while any IDs that are not are populated based on database state. The previously known entities are not refreshed from the database at all.

Although this is in the context of Hibernate, I hit the same issue in Eclipselink. So after introducing a refresh on the list I get the expected result.

T objects = getAll();
for (T objects : object)
    em.refresh(object)

List<T> getAll() {
  EntityManager em = entityManagerFactory.createEntityManager();
  return  em.createQuery(em.getCriteriaBuilder().createQuery(type)).getResultList();
}

Can someone explain this Session cache in the context of Eclipselink, and explain why shared-cache configuration has no impact on this ? Does a transaction transparently solve this problem (read transaction)? Is there an elegant solution/JPA configuration than doing refresh on object each time ?


问:
How to architect two level inheritance hierarchy?
I assume a class which has more than one inheritance hierarchies it can be broken down into:
Assume that a class airplane has 4 combinations:

```<code>1.  Subsonic & commercial
2.  Subsonic & jet fighter
3.  Supersonic & commercial
4.  Supersonic & jet fighter
</code>```

Now my non-object oriented class looks like this

```<code>Class Airplane {

   Void SubsonicAndCommercial {
       print
    }

    void subsonicAndJet  {

   }

  void supersonicAndCommercial {

  }

  void supersonicAndJet {

 }

}
</code>```

Now I need to break the plane class into subclasses. What’s the most common approach ?
Will this be a 2 level hierarchy ?
Ie
Iface           Plane
Iface           Subsonic, supersonic extends Plane

4-Subclass      Jet extends supersonic, jet extends Subsonic.. etc

答:
In Java, classes can never extend more than one class, so this looks like a job for interfaces. You should make interfaces for Subsonic, Supersonic, Commercial and Fighter. Then you can implement them like so

```<code>public class SubCommercialPlane implements Subsonic, Commercial

public class SuperCommercialPlane implements Supersonic, Commercial

public class SubFighterPlane implements Subsonic, Fighter

public class SuperCommercialPlane implements Supersonic, Fighter
</code>```

This is probably the best way to accomplish this with simple java hierarchies. If you wanted to tackle this in a more complex way, look into the Entity-Component Model which is explained well in this wikipedia article:

https://en.wikipedia.org/wiki/Entity%E2%80%93component%E2%80%93system

Body:
I assume a class which has more than one inheritance hierarchies it can be broken down into:
Assume that a class airplane has 4 combinations:

1.  Subsonic & commercial
2.  Subsonic & jet fighter
3.  Supersonic & commercial
4.  Supersonic & jet fighter

Now my non-object oriented class looks like this

Class Airplane {

   Void SubsonicAndCommercial {
       print
    }

    void subsonicAndJet  {

   }

  void supersonicAndCommercial {

  }

  void supersonicAndJet {

 }

}

Now I need to break the plane class into subclasses. What’s the most common approach ?
Will this be a 2 level hierarchy ?
Ie
Iface           Plane
Iface           Subsonic, supersonic extends Plane

4-Subclass      Jet extends supersonic, jet extends Subsonic.. etc

Body:
In Java, classes can never extend more than one class, so this looks like a job for interfaces. You should make interfaces for Subsonic, Supersonic, Commercial and Fighter. Then you can implement them like so

public class SubCommercialPlane implements Subsonic, Commercial

public class SuperCommercialPlane implements Supersonic, Commercial

public class SubFighterPlane implements Subsonic, Fighter

public class SuperCommercialPlane implements Supersonic, Fighter

This is probably the best way to accomplish this with simple java hierarchies. If you wanted to tackle this in a more complex way, look into the Entity-Component Model which is explained well in this wikipedia article:

https://en.wikipedia.org/wiki/Entity%E2%80%93component%E2%80%93system


问:
Did the author make a mistake in explaining stack and heap in C++ or am I misreading something?
Here is the code:

```<code>int main()
{
    using namespace std;
    int nights = 1001;
    int * pt = new int; // allocate space for an int
    *pt = 1001;         // store a value there

    cout << "nights value = ";
    cout << nights << ": location " << &nights << endl;
    cout << "int ";
    cout << "value = " << *pt << ": location = " << pt << endl;

    double * pd = new double; // allocate space for a double
    *pd = 10000001.0; // store a double there

    cout << "double ";
    cout << "value = " << *pd << ": location = " << pd << endl;
    cout << "location of pointer pd: " << &pd << endl;
    cout << "size of pt = " << sizeof(pt);
    cout << ": size of *pt = " << sizeof(*pt) << endl;
    cout << "size of pd = " << sizeof pd;
    cout << ": size of *pd = " << sizeof(*pd) << endl;

    return 0;
}
</code>```

Now here is the author's note about the code:

Another point to note is that typically new uses a different block of memory than do the ordinary variable definitions that we have been using. Both the variable nights and pd have their values stored in a memory region called the stack, whereas the memory allocated by the new is in a region called the heap or free store.

Initial Question:

Now my concern is this: the variable pd was create by the keyword new, so it should be stored in the region called heap just like the variable pt, since they were both created by the keyword new.

Am I missing something here? Thank you very much in advance for your inputs.

Revised Question/Follow-up based on the hold:

This question was put on hold by 5 people because they couldn't understand what I was asking. I believe that my question has already been answered but for those who are still not sure about what I was initially asking please read along:

I was unclear about the author's explanation about where the variables and their values were stored in memory. Up to the author explanation, I had a belief that any memory created dynamically (or should I say during runtime after compiling) by using the keyword new gets stored in the heap not the stack.

So, it confused me when he wrote that the variable pd has is value
  stored in the stack, but again how is that possible if the variable
  was create during "runtime" with the keyword new, so it should be
  in the heap, not the stack.

Please try to use the code above as the reference and in particular the **variables (nights, pd, and pt) in your answer so that I can understand it from that code's perspective.

答:
Pictures will help.

```<code>Automatic storage (stack)                      Dynamic storage (heap)
-------------------------                      ----------------------

Item        Address        Value               Address        Value
----        -------        -----               -------        -----
nights      0xff001000     1001
    pt      0xff001004     0x00b0fff0 ------>  0x00b0fff0     1001
    pd      0xff00100c     0x00b0fff4 ------>  0x00b0fff4     10000001.0
</code>```

The objects nights, pt, and pd all have auto storage duration.  On most implementations, this means they are allocated from the runtime stack.  The object nights lives at address 0xff0010001 and stores the value 1001.  The object pt lives at address 0xff0010004 and stores the address of a dynamic object created by new, which is 0x00b0fff0.  The object pd lives at address 0xff00100c and stores the address of another dynamic object created by new, which is 0x00b0fff4.

The heap objects at addresses 0x00b0fff0 and 0x00b0fff4 store the values 1001 and 10000001.0, respectively.

Edit

FWIW, I wrote a dumper utility some time ago that dumps out object addresses and contents; given the code

```<code>#include <cstdio>
#include "dumper.h"

using namespace std;

int main( void )
{
  int nights = 1001;
  int *pt = new int;
  *pt = 1001;
  double *pd = new double;
  *pd = 1000001.0;

  char *names[] = { "nights", "pt", "pd", "*pt", "*pd" };
  void *addrs[] = { &nights, &pt, &pd, pt, pd };
  size_t sizes[] = { sizeof nights, sizeof pt, sizeof pd, sizeof *pt, sizeof *pd };

  dumper( names, addrs, sizes, 5, stdout );

  return 0;
}
</code>```

I get the output

```<code>       Item         Address   00   01   02   03
       ----         -------   --   --   --   --
     nights  0x7fff9efe7c6c   e9   03   00   00    ....

         pt  0x7fff9efe7c60   10   20   50   00    ..P.
             0x7fff9efe7c64   00   00   00   00    ....

         pd  0x7fff9efe7c58   30   20   50   00    0.P.
             0x7fff9efe7c5c   00   00   00   00    ....

        *pt        0x502010   e9   03   00   00    ....

        *pd        0x502030   00   00   00   00    ....
                   0x502034   82   84   2e   41    ...A
</code>```

In this case, the addresses are real.  On my system (x86_64/Linux SLES-10), stack addresses start high and grow "downwards" (towards lower addresses), while heap addresses start low and grow "upwards" (towards higher addresses).

x86 is little endian, meaning the addressed byte is the least significant byte; multi-byte objects need to be read from right to left.

 All addresses are made up out of thin air and are not meant to represent any real-world implementation or architecture.

Body:
Here is the code:

int main()
{
    using namespace std;
    int nights = 1001;
    int * pt = new int; // allocate space for an int
    *pt = 1001;         // store a value there

    cout << "nights value = ";
    cout << nights << ": location " << &nights << endl;
    cout << "int ";
    cout << "value = " << *pt << ": location = " << pt << endl;

    double * pd = new double; // allocate space for a double
    *pd = 10000001.0; // store a double there

    cout << "double ";
    cout << "value = " << *pd << ": location = " << pd << endl;
    cout << "location of pointer pd: " << &pd << endl;
    cout << "size of pt = " << sizeof(pt);
    cout << ": size of *pt = " << sizeof(*pt) << endl;
    cout << "size of pd = " << sizeof pd;
    cout << ": size of *pd = " << sizeof(*pd) << endl;

    return 0;
}

Now here is the author's note about the code:

Another point to note is that typically new uses a different block of memory than do the ordinary variable definitions that we have been using. Both the variable nights and pd have their values stored in a memory region called the stack, whereas the memory allocated by the new is in a region called the heap or free store.

Initial Question:

Now my concern is this: the variable pd was create by the keyword new, so it should be stored in the region called heap just like the variable pt, since they were both created by the keyword new.

Am I missing something here? Thank you very much in advance for your inputs.

Revised Question/Follow-up based on the hold:

This question was put on hold by 5 people because they couldn't understand what I was asking. I believe that my question has already been answered but for those who are still not sure about what I was initially asking please read along:

I was unclear about the author's explanation about where the variables and their values were stored in memory. Up to the author explanation, I had a belief that any memory created dynamically (or should I say during runtime after compiling) by using the keyword new gets stored in the heap not the stack.

So, it confused me when he wrote that the variable pd has is value
  stored in the stack, but again how is that possible if the variable
  was create during "runtime" with the keyword new, so it should be
  in the heap, not the stack.

Please try to use the code above as the reference and in particular the **variables (nights, pd, and pt) in your answer so that I can understand it from that code's perspective.

Body:
Pictures will help.

Automatic storage (stack)                      Dynamic storage (heap)
-------------------------                      ----------------------

Item        Address        Value               Address        Value
----        -------        -----               -------        -----
nights      0xff001000     1001
    pt      0xff001004     0x00b0fff0 ------>  0x00b0fff0     1001
    pd      0xff00100c     0x00b0fff4 ------>  0x00b0fff4     10000001.0

The objects nights, pt, and pd all have auto storage duration.  On most implementations, this means they are allocated from the runtime stack.  The object nights lives at address 0xff0010001 and stores the value 1001.  The object pt lives at address 0xff0010004 and stores the address of a dynamic object created by new, which is 0x00b0fff0.  The object pd lives at address 0xff00100c and stores the address of another dynamic object created by new, which is 0x00b0fff4.

The heap objects at addresses 0x00b0fff0 and 0x00b0fff4 store the values 1001 and 10000001.0, respectively.

Edit

FWIW, I wrote a dumper utility some time ago that dumps out object addresses and contents; given the code

#include <cstdio>
#include "dumper.h"

using namespace std;

int main( void )
{
  int nights = 1001;
  int *pt = new int;
  *pt = 1001;
  double *pd = new double;
  *pd = 1000001.0;

  char *names[] = { "nights", "pt", "pd", "*pt", "*pd" };
  void *addrs[] = { &nights, &pt, &pd, pt, pd };
  size_t sizes[] = { sizeof nights, sizeof pt, sizeof pd, sizeof *pt, sizeof *pd };

  dumper( names, addrs, sizes, 5, stdout );

  return 0;
}

I get the output

       Item         Address   00   01   02   03
       ----         -------   --   --   --   --
     nights  0x7fff9efe7c6c   e9   03   00   00    ....

         pt  0x7fff9efe7c60   10   20   50   00    ..P.
             0x7fff9efe7c64   00   00   00   00    ....

         pd  0x7fff9efe7c58   30   20   50   00    0.P.
             0x7fff9efe7c5c   00   00   00   00    ....

        *pt        0x502010   e9   03   00   00    ....

        *pd        0x502030   00   00   00   00    ....
                   0x502034   82   84   2e   41    ...A

In this case, the addresses are real.  On my system (x86_64/Linux SLES-10), stack addresses start high and grow "downwards" (towards lower addresses), while heap addresses start low and grow "upwards" (towards higher addresses).

x86 is little endian, meaning the addressed byte is the least significant byte; multi-byte objects need to be read from right to left.

 All addresses are made up out of thin air and are not meant to represent any real-world implementation or architecture.


问:
Change the Connecting string of the C# windows form application to it in another computer
I have a C# windows form application and I connect it to the SQL server in my computer. Now I going to deliver the software to a user. So, what can I do to change the connection string to the user SQL server? Is there any way to do the connection string computer independent? Kindly help me

Regards.

答: I'm assuming you're hard-coding connection strings into your code.  You need an application config file.  </p>


问:
Npm does not install packages
I Have strange behavior on my npm

This a little part of my package.json

```<code>  "devDependencies": {
    ....
    "css-loader": "^0.23.1",
    "del": "^2.2.1",
    "gulp-autoprefixer": "^3.1.0",
    "gulp-clean-css": "^2.0.10",
    "gulp-concat": "^2.6.0",
    "gulp-rename": "^1.2.2",
    "gulp-replace": "^0.5.4",
     ....
   }
</code>```

When i run npm i everything is installed.

Immediate afterward i hit npm i gulp-clean-css@2.0.10.

The same package that was installed but the strange things that i get more packages installed  when i expect to receive that everything is up to date.

Any idea why npm behave so?

Without the specific npm i gulp-clean-css@2.0.10 i get my build broken and got fixed after the specific install.

答:
Thats because you're specifying your package versions in your package.json using the ^ character, which only restricts the MAJOR version number (the first number in x.x.x). See https://github.com/npm/node-semver#caret-ranges-123-025-004

When you are running your specific package installation command you're specifying a specific version strictly (without ^) meaning that it will fetch that package version exactly.

Title: Npm does not install packages

Body:
I Have strange behavior on my npm

This a little part of my package.json

  "devDependencies": {
    ....
    "css-loader": "^0.23.1",
    "del": "^2.2.1",
    "gulp-autoprefixer": "^3.1.0",
    "gulp-clean-css": "^2.0.10",
    "gulp-concat": "^2.6.0",
    "gulp-rename": "^1.2.2",
    "gulp-replace": "^0.5.4",
     ....
   }

When i run npm i everything is installed.

Immediate afterward i hit npm i gulp-clean-css@2.0.10.

The same package that was installed but the strange things that i get more packages installed  when i expect to receive that everything is up to date.

Any idea why npm behave so?

Without the specific npm i gulp-clean-css@2.0.10 i get my build broken and got fixed after the specific install.


问:
Numbers bigger than 8 bytes in C
I am writing some code to deal with numbers in C which are bigger than 8 bytes in size (don't fit into unsigned long). In this example I will use 16 bytes (128 bits) as the width. The numbers are unsigned and integers (no decimal places). They are stored as an array of unsigned chars eg:

```<code>unsigned char n[16];
</code>```

I have managed to get addition to work (it works like an unsigned number in C so if you had a number which was 0xffffffffffffffffffffffffffffffff (2**128) and you were to add 1 you would get 0. I have managed to get addition to work, but I cannot get subtraction to work. I would assume it would be similar code to addition, but I don't seem to be able to get it to work.

Addition code:

```<code>//a and b are numbers
unsigned char *add(unsigned char *a, unsigned char *b){
    unsigned char *c = malloc(NUM_SIZE);
    //d is the carry and c is the output number
    unsigned short d = 0;

    if(!c){
        return NULL;
    }
    for(int i = 0; i < NUM_SIZE; i++){
        c[i] = 0;
    }
    for(int i = NUM_SIZE * 2 - 1; i >= 0; i--){
        d += a[i % NUM_SIZE] + b[i % NUM_SIZE];
        c[i % NUM_SIZE] = d % 256;
        d >>= 8;
    }
    return c;
}
</code>```

NUM_SIZE is defined as 16 (the width of the number in bytes)

What I have tried:

```<code>//changing the signs to minuses
d -= a[i % NUM_SIZE] - b[i % NUM_SIZE];

//changing the some signs to minuses
d -= a[i % NUM_SIZE] + b[i % NUM_SIZE];
//or
d += a[i % NUM_SIZE] - b[i % NUM_SIZE];

//looping through the number backwards
for(int i = 0; i < NUM_SIZE * 2; i++)
</code>```

答:
NUM_SIZE * 2 does not make sense with malloc(NUM_SIZE); ... for(int i = NUM_SIZE * 2 - 1.  Only a loop of NUM_SIZE iterations is needed.

Repaired code

```<code>#define NUM_SIZE 8
//a - b
unsigned char *sub(const unsigned char *a, const unsigned char *b) {
  unsigned char *c = malloc(NUM_SIZE);
  if (!c) {
    return NULL;
  }

  // zeroing `c[]` not needed.  Retain that code if desired

  int d = 0;  // Use signed accumulator to save the "borrow"

  // drop *2
  for (int i = NUM_SIZE - 1; i >= 0; i--) {
    d += a[i] - b[i];                // Perform the subtraction
    c[i] = d;                        // Save the 8 least significant bits in c[]
    d = (d - c[i]) / (UCHAR_MAX+1);  // Form the "borrow" for the next loop
  }
  // If d<0 at this point, b was greater than a
  return c;
}
</code>```

Various performance improvements can be made, but important to get functionality correct first.

Title: Numbers bigger than 8 bytes in C

Body:
I am writing some code to deal with numbers in C which are bigger than 8 bytes in size (don't fit into unsigned long). In this example I will use 16 bytes (128 bits) as the width. The numbers are unsigned and integers (no decimal places). They are stored as an array of unsigned chars eg:

unsigned char n[16];

I have managed to get addition to work (it works like an unsigned number in C so if you had a number which was 0xffffffffffffffffffffffffffffffff (2**128) and you were to add 1 you would get 0. I have managed to get addition to work, but I cannot get subtraction to work. I would assume it would be similar code to addition, but I don't seem to be able to get it to work.

Addition code:

//a and b are numbers
unsigned char *add(unsigned char *a, unsigned char *b){
    unsigned char *c = malloc(NUM_SIZE);
    //d is the carry and c is the output number
    unsigned short d = 0;

    if(!c){
        return NULL;
    }
    for(int i = 0; i < NUM_SIZE; i++){
        c[i] = 0;
    }
    for(int i = NUM_SIZE * 2 - 1; i >= 0; i--){
        d += a[i % NUM_SIZE] + b[i % NUM_SIZE];
        c[i % NUM_SIZE] = d % 256;
        d >>= 8;
    }
    return c;
}

NUM_SIZE is defined as 16 (the width of the number in bytes)

What I have tried:

//changing the signs to minuses
d -= a[i % NUM_SIZE] - b[i % NUM_SIZE];

//changing the some signs to minuses
d -= a[i % NUM_SIZE] + b[i % NUM_SIZE];
//or
d += a[i % NUM_SIZE] - b[i % NUM_SIZE];

//looping through the number backwards
for(int i = 0; i < NUM_SIZE * 2; i++)

Body:
NUM_SIZE * 2 does not make sense with malloc(NUM_SIZE); ... for(int i = NUM_SIZE * 2 - 1.  Only a loop of NUM_SIZE iterations is needed.

Repaired code

#define NUM_SIZE 8
//a - b
unsigned char *sub(const unsigned char *a, const unsigned char *b) {
  unsigned char *c = malloc(NUM_SIZE);
  if (!c) {
    return NULL;
  }

  // zeroing `c[]` not needed.  Retain that code if desired

  int d = 0;  // Use signed accumulator to save the "borrow"

  // drop *2
  for (int i = NUM_SIZE - 1; i >= 0; i--) {
    d += a[i] - b[i];                // Perform the subtraction
    c[i] = d;                        // Save the 8 least significant bits in c[]
    d = (d - c[i]) / (UCHAR_MAX+1);  // Form the "borrow" for the next loop
  }
  // If d<0 at this point, b was greater than a
  return c;
}

Various performance improvements can be made, but important to get functionality correct first.


问:
PHP - highlight text from a string containing HTML
So I'm making a search function for comments. Someone else here helped me with the SQL query.
What I also want to do is to highlight the search query text in the results.

The results are stored as HTML inside a $variable.
How can I wrap the search query text inside a  tag for example, without messing up the html.

for eg. the search query can be foo bar and the output can look like:

```<code><p>bla bla foo bar bla</p>
</code>```

so it should be something like:

```<code><p>bla <span class="highlight">foo bar</span> bla bla</p>
</code>```

答:
If you make sure that the search term itself does not contain any HTML, you can go straight ahead and wrap it it in "" with the help of str_replace().

Note that this is one of the very rare occasions where dealing with HTML via string functions is not bad per se.

If the search term can contain HTML (i.e. the highlight can span over tag borders), things get a lot more complicated and you won't get away with a clever shortcut like the one above.

Body:
So I'm making a search function for comments. Someone else here helped me with the SQL query.
What I also want to do is to highlight the search query text in the results.

The results are stored as HTML inside a $variable.
How can I wrap the search query text inside a  tag for example, without messing up the html.

for eg. the search query can be foo bar and the output can look like:

bla bla foo bar bla

so it should be something like:

bla foo bar bla bla

Body:
If you make sure that the search term itself does not contain any HTML, you can go straight ahead and wrap it it in "<span>" with the help of str_replace().

Note that this is one of the very rare occasions where dealing with HTML via string functions is not bad per se.

If the search term can contain HTML (i.e. the highlight can span over tag borders), things get a lot more complicated and you won't get away with a clever shortcut like the one above.


问:
How to make sure docker's time syncs with that of the host?
I have dockers running on Linode servers. At times, I see that the time is not right on the dockers. Currently I have changed the run script in every docker to include the following lines of code.

```<code>yum install -y ntp
service ntpd stop
ntpdate pool.ntp.org
</code>```

What I would ideally like to do however is that the docker should sync time with the host. Is there a way to do this?

答:
You can add your local files (/etc/timezone and /etc/localtime) as volume in your Docker container.

Update your docker-compose.yml with the following lines.

volumes:
    - "/etc/timezone:/etc/timezone:ro"
    - "/etc/localtime:/etc/localtime:ro"
```

Now the container time is the same as on your host.

Body:
I have dockers running on Linode servers. At times, I see that the time is not right on the dockers. Currently I have changed the run script in every docker to include the following lines of code.

yum install -y ntp
service ntpd stop
ntpdate pool.ntp.org

What I would ideally like to do however is that the docker should sync time with the host. Is there a way to do this?

Body:
You can add your local files (/etc/timezone and /etc/localtime) as volume in your Docker container.

Update your docker-compose.yml with the following lines.

volumes:
    - "/etc/timezone:/etc/timezone:ro"
    - "/etc/localtime:/etc/localtime:ro"

Now the container time is the same as on your host.


答:
One approach is to define interfaces for Subsonic, Supersonic, Commercial and Military. Then define classes that implement the appropriate pair of interfaces.

This lets you define methods, for example, that accept a Supersonic interface, that work regardless whether it's Commercial or Military.

You can define an interface like this:

```<code>public interface IAirplane {
   // Method declarations appropriate for all planes.
}

public interface ISupersonic extends IAirplane {
   // Method declarations specific to Supersonic aircraft.
}
</code>```

After defining similar interfaces for Subsonic, Commercial and Military, you can define classes that implement the appropriate interfaces. For example:

```<code>public class SupersonicJetFighter implements ISupersonic, IMilitary {
   // Implementations of methods in IAirplane, ISupersonic and IMilitary
}
</code>```

If some code is common between multiple IAirplane implementations, you could introduce an abstract class.

```<code>public abstract class AbstractAirplane implements IAirplane {
   // Common methods.
}

public class SupersonicJetFighter
extends AbstractAirplane
implements ISupersonic, IMilitary {
   // Implementations of undefined methods in IAirplane, ISupersonic and IMilitary
}
</code>```

Title: How to architect two level inheritance hierarchy?

Body:
One approach is to define interfaces for Subsonic, Supersonic, Commercial and Military. Then define classes that implement the appropriate pair of interfaces.

This lets you define methods, for example, that accept a Supersonic interface, that work regardless whether it's Commercial or Military.

You can define an interface like this:

public interface IAirplane {
   // Method declarations appropriate for all planes.
}

public interface ISupersonic extends IAirplane {
   // Method declarations specific to Supersonic aircraft.
}

After defining similar interfaces for Subsonic, Commercial and Military, you can define classes that implement the appropriate interfaces. For example:

public class SupersonicJetFighter implements ISupersonic, IMilitary {
   // Implementations of methods in IAirplane, ISupersonic and IMilitary
}

If some code is common between multiple IAirplane implementations, you could introduce an abstract class.

public abstract class AbstractAirplane implements IAirplane {
   // Common methods.
}

public class SupersonicJetFighter
extends AbstractAirplane
implements ISupersonic, IMilitary {
   // Implementations of undefined methods in IAirplane, ISupersonic and IMilitary
}


问:
PHP Session not passing multiple post form data through multiple pages
I am trying to take form input from the user and pass that information to another page with another form then take input again and pass that plus the previous data to another page that will display the input from both forms.

On the first page, the user will enter information, click submit, and open the second page which will display their input from the first page and ask them to enter more information. They will enter information on the second page and click submit again which will bring them to a third page displaying all their input from the previous pages.

When I run my code, it does not carry the post values from the form to the next page.

I know there are multiple questions about issues such as this, but all of the answers I have looked over and tried did not fix my problem.

Here is my code:

page1.php

```<code><?php
session_start();
echo 'session id: ';
echo session_id();
$_SESSION['test1'] = $_POST['test1'];
?>

<html>
<body>
    <p>Page 1 Form</p>
    <form action="page2.php" method="post">
        <input type="text" name="test1"/>
        <input type="submit" name="submit1" value="Submit!" />
    </form>
</body>
</html>
</code>```

page2.php

```<code><?php
session_start();
echo 'page2.php<br />';
echo 'session id: ';
echo session_id();
echo '<br />';
echo 'input from page1.php: ';
echo $_SESSION['test1'];
$_SESSION['test2'] = $_POST['test2'];
?>

<html>
<body>
    <p>Page 2 Form</p>
        <form action="page3.php" method="post">
            <input type="text" name="test2"/>
            <input type="submit" name="submit2" value="Submit!" />
        </form>
</body>
</html>
</code>```

page3.php

```<code><?php
session_start();
echo 'page3.php<br />'
echo 'session id: ';
echo session_id();
echo '<br />';
echo $_SESSION['test1'];
echo $_SESSION['test2'];
?>
</code>```

答:
you should field the value after value is parsing.
i think u have an empty session is because,

```<code>1. $_SESSION['test1'] = $_POST['test1'];
</code>```

but your action going to "page2.php", and you field the session before form is submit so you get an empty value, the better way is you should field $_SESSION['test1'] on page2.php

```<code>2. $_SESSION['test2'] = $_POST['test2'];
</code>```

your action going to "page3.php", you should field $_SESSION['test2'] on page3.php

so, the complete code should look like this.

pages 1

```<code><?php
session_start();
echo 'session id: ';
echo session_id();
?>

<html>
<body>
    <p>Page 1 Form</p>
    <form action="page2.php" method="post">
        <input type="text" name="test1"/>
        <input type="submit" name="submit1" value="Submit!" />
    </form>
</body>
</html>
</code>```

pages 2

```<code><?php
session_start();
echo 'page2.php<br />';
echo 'session id: ';
echo session_id();
echo '<br />';
echo 'input from page1.php: '.$_POST['test1'];
$_SESSION['test1'] = $_POST['test1'];
?>

<html>
<body>
    <p>Page 2 Form</p>
        <form action="page3.php" method="post">
            <input type="text" name="test2"/>
            <input type="submit" name="submit2" value="Submit!" />
        </form>
</body>
</html>
</code>```

pages 3

```<code><?php
session_start();
echo 'page3.php<br />'
echo 'session id: ';
echo session_id();
echo '<br />';
$_SESSION['test2'] = $_POST['test2'];
echo $_SESSION['test1'];
echo $_SESSION['test2'];
?>
</code>```

Body:
I am trying to take form input from the user and pass that information to another page with another form then take input again and pass that plus the previous data to another page that will display the input from both forms.

On the first page, the user will enter information, click submit, and open the second page which will display their input from the first page and ask them to enter more information. They will enter information on the second page and click submit again which will bring them to a third page displaying all their input from the previous pages.

When I run my code, it does not carry the post values from the form to the next page.

I know there are multiple questions about issues such as this, but all of the answers I have looked over and tried did not fix my problem.

Here is my code:

page1.php

<?php
session_start();
echo 'session id: ';
echo session_id();
$_SESSION['test1'] = $_POST['test1'];
?>

Page 1 Form

    <form action="page2.php" method="post">
        <input type="text" name="test1"/>
        <input type="submit" name="submit1" value="Submit!" />
    </form>

page2.php

<?php
session_start();
echo 'page2.php
';
echo 'session id: ';
echo session_id();
echo '
';
echo 'input from page1.php: ';
echo $_SESSION['test1'];
$_SESSION['test2'] = $_POST['test2'];
?>

Page 2 Form

        <form action="page3.php" method="post">
            <input type="text" name="test2"/>
            <input type="submit" name="submit2" value="Submit!" />
        </form>

page3.php

<?php
session_start();
echo 'page3.php
'
echo 'session id: ';
echo session_id();
echo '
';
echo $_SESSION['test1'];
echo $_SESSION['test2'];
?>

Body:
you should field the value after value is parsing.
i think u have an empty session is because,

1. $_SESSION['test1'] = $_POST['test1'];

but your action going to "page2.php", and you field the session before form is submit so you get an empty value, the better way is you should field $_SESSION['test1'] on page2.php

2. $_SESSION['test2'] = $_POST['test2'];

your action going to "page3.php", you should field $_SESSION['test2'] on page3.php

so, the complete code should look like this.

pages 1

<?php
session_start();
echo 'session id: ';
echo session_id();
?>

<html>
<body>
    <p>Page 1 Form</p>
    <form action="page2.php" method="post">
        <input type="text" name="test1"/>
        <input type="submit" name="submit1" value="Submit!" />
    </form>
</body>
</html>

pages 2

<?php
session_start();
echo 'page2.php<br />';
echo 'session id: ';
echo session_id();
echo '<br />';
echo 'input from page1.php: '.$_POST['test1'];
$_SESSION['test1'] = $_POST['test1'];
?>

<html>
<body>
    <p>Page 2 Form</p>
        <form action="page3.php" method="post">
            <input type="text" name="test2"/>
            <input type="submit" name="submit2" value="Submit!" />
        </form>
</body>
</html>

pages 3

<?php
session_start();
echo 'page3.php<br />'
echo 'session id: ';
echo session_id();
echo '<br />';
$_SESSION['test2'] = $_POST['test2'];
echo $_SESSION['test1'];
echo $_SESSION['test2'];
?>