问:
Does Lisp still have any special feature which has NOT been adopted by other programming languages?
Does Lisp still have any special feature which has NOT been adopted by other programming languages?

By Lisp, I mean all the Lisp programming languages as a whole. I've been told how amazing Lisp is and know that many languages have been inspired by Lisp. But does Lisp still have any exclusive design feature that just cannot be done in any other language?

The reason I asked the question is that recently, being an amateur programmer myself, I began to learn Clojure just for fun, and the result is that I found lots of Lisp-related posts and comments, saying but one thing: "Lisp is unique", but other modern programming languages have already adopted and stolen lots of ideas from Lisp, like conditionals, recursion, and the function as a first-class citizen. And even metaprogramming can be done by many languages.

Did I miss out something and is "Lisp still different"?

Or I'm lucky because other modern languages have stolen all the good parts from Lisp so that it's not necessary to dig into the parentheses Lisp world, and "Lisp was different".

答:
A canonical reference for this type of question is Paul Graham's What Made Lisp Different. The two remaining key features of Lisp that are not widely available, according to this article at the time of its writing, are:

8. A notation for code using trees of symbols.

9. The whole language always available. There is no real distinction between read-time, compile-time, and runtime. You can compile or run code while reading, read or run code while compiling, and read or compile code at runtime.

The commentary addresses each point and names popular languages where that feature is available.

8, which (with 9) is what makes Lisp macros possible, is so far still unique to Lisp, perhaps because (a) it requires those parens, or something just as bad, and (b) if you add that final increment of power, you can no longer claim to have invented a new language, but only to have designed a new dialect of Lisp ; -)

Note that this article was last revised in 2002, and in the past 11 years there have been a wide variety of new languages, some of which may incorporate all these Lisp features into their design.


答:
Lisp has many dialects, and each of them has its own set of features. My favorite feature that is unlikely to be adopted by any other language is the "spaghetti stack" from Interlisp.

The spaghetti stack is like a closure, but on steroids. It saves not only the current function, but the entire context up to the top of the stack. Something like a co-routine, except that you could create these arbitrarily, resulting in a hierarchy of stack contexts.

ContentLicense: CC BY-SA 3.0

Body:
Does Lisp still have any special feature which has NOT been adopted by other programming languages?

By Lisp, I mean all the Lisp programming languages as a whole. I've been told how amazing Lisp is and know that many languages have been inspired by Lisp. But does Lisp still have any exclusive design feature that just cannot be done in any other language?

The reason I asked the question is that recently, being an amateur programmer myself, I began to learn Clojure just for fun, and the result is that I found lots of Lisp-related posts and comments, saying but one thing: "Lisp is unique", but other modern programming languages have already adopted and stolen lots of ideas from Lisp, like conditionals, recursion, and the function as a first-class citizen. And even metaprogramming can be done by many languages.

Did I miss out something and is "Lisp still different"?

Or I'm lucky because other modern languages have stolen all the good parts from Lisp so that it's not necessary to dig into the parentheses Lisp world, and "Lisp was different".


问:
In reality, a developer also administers DBMS and system?
I really don't know where else to ask. So here it goes.

I'm working at a very tiny company that makes ERP software and websites.

1 developer with + 10 years experience.

2 developers with + 3years experience.

3 developers with + 1 year experience.

That's it.

No team, no DBA, no system admin.

There is no one around here who has expertise in web development, so I happened to be in charge of web development. But I've only got 3 years experience ! as a developer !.

I know in a small company, you are asked to do lots of different things but is it too much,
if I have to do sysadmin, database architecture, software design and development ?
Oh plus I'm asked to do all that across different platforms.

I am currently working with JSP, ASP, MSSQL, MySQL, Oracle, Windows Server, and Linux.

In database, I do from writing queries to backup & recovery.

Server setup, system crash recovery, DB &  Server migration also.

Plush HTML, Javascript and CSS :)

Number of projects that I'm in charge of : 5

I'm not an expert at all of them !

I have to search the Internet, read tutorials and ask questions in StackOverflow to get all that done !

So I ask you, is this normal ?

Is this a normal practice ?

Will I face the same situation whichever small company I go ?

I'm working in South Korea.
 How is it in your country ?

P.S
Thank you all for your opinion. I was going to upvote all of you because all of you helped me see it in a different way, but apparently you need 15 reputation to upvote :(

答:
In my experience, yes, it is perfectly normal for developers in small companies to be expected to cover a broad range of roles. It is certainly normal for a company so small that it only has three developers to not have a specialized DBA or sysadmin.

However, I would find it unusual for such a small company to use such a broad range of technologies. JSP and ASP? Windows and Linux? SQL Server, MySQL and Oracle?? Usually, small companies will focus on one technology platform to avoid spreading themselves too thin.

If your work involved full-stack development on one platform - e.g. ASP.NET + SQL Server + Windows, or Java + Oracle + Linux - would you still feel overwhelmed?

Anyway, if you want to specialize to a greater extent, yes, you should look to larger companies. The bigger the team, the more plausible and beneficial it is to have specialists.


问:
Is rewriting some Java code to C++ using JNI to improve performance a good idea?
I've tried rewriting some Java functions in C++ and called them using JNI. I observed that it takes longer time to execute the native C++ functions as compared to Java functions, due to the JNI overhead.

As it is widely believed that C++ has certain advantages over Java, I wanted to know whether rewriting some Java code to C++, with a view to improve overall performance of the Java application, a good idea?

If yes, then what parts of the application should be rewritten and how can a Java application use it?

答:
I would advise against it; in the latest releases JVM was improved very much and the performance differences are minimal, for typical production code. Moreover JNI itself is not free from the performance POV and overall you would lose performance rather than achieve more (as you have found out in your case). In addition to this, native code is not safe (you may have corrupt memory), is less portable, and is harder to debug.

Try to improve performance by classical techniques (better algorithms and data structures, optimization, reduced I/O overhead etc.) and Java techniques (JVM tuning). Only if you have legacy APIs in native code or you need to perform large computation extensive tasks is JNI recommended.

See also Item 54: Use native methods judiciously in Joshua Bloch's Effective Java (2nd edition) for a more advised reference.


答:
In your enumeration of the tasks a developer has to do, you may also put:

Interaction design,

Visual design,

Usability,

Security,

Requirements gathering,

Testing and QA,

Deployment,

Maintenance,

Project management,

Team management,

etc.

In essence, this is the difference between a programmer and a developer.

The job of a programmer, no matter how skillful, is to write code, eventually thinking a bit about the different approaches (i.e. preliminary design).

The job of a developer is to be able to run a small or a medium-scale project, which requires a much broader (and so at the same time shallower) knowledge.

In order to overcome the fact that a single developer wouldn't be able to know as much as a single person who spent years learning only one thing, projects are done by a team. This is how projects are (or at least should be) organized. Most of the time, a small project doesn't require too much skills in any domain, while larger ones do.

If I screw up, as a developer, with security of an e-commerce website of a tiny company, well, it's bad, because the company may lose a few hundreds or, rarely, thousands of dollars, but not critical. If I screw up with security or a system which controls air traffic, that's really bad.

If the interaction design of the internal accounting software product done for a small company and used by only two accountants who work there is bad, again, this is not too harmful. If the interaction design of a new Apple product is poor, this may have important consequences on the sales and the reputation of the company.

etc.

This means that by working in small companies on small-scale projects, you'll often find yourself doing lots of things. Those companies just can't afford specialists in all of the hundreds of sectors related to IT, so they look for a jack of all trades instead.

Start working on large projects, and you'll see that your role will be narrower, while being deeper at the same time. Your whole work may be to write CSS code, but you'll be required to know any CSS quirk and be able to style a web application very fast, based on the work of a visual designer. You would have no excuse if you can't explain the benefits of Sass compared to LESS or if you don't know what CSS sprites are.

It's up to you to pick what you prefer.

There is nothing bad in being jack of all trades, especially since it allows you to be flexible enough: if there is a demand for system administrators, you have the skills. If, a few years later, nobody needs sysadmins, but now, web developers are paid well, you can apply as well.

There is nothing bad in focusing on a narrow field neither. If you have a deep knowledge of a field, large companies with lots of money can be interested in hiring you, because there would be few specialists of your level of skills.

Title: In reality, a developer also administers DBMS and system?

Body:
I really don't know where else to ask. So here it goes.

I'm working at a very tiny company that makes ERP software and websites.

1 developer with + 10 years experience.

2 developers with + 3years experience.

3 developers with + 1 year experience.

That's it.

No team, no DBA, no system admin.

There is no one around here who has expertise in web development, so I happened to be in charge of web development. But I've only got 3 years experience ! as a developer !.

I know in a small company, you are asked to do lots of different things but is it too much,
if I have to do sysadmin, database architecture, software design and development ?
Oh plus I'm asked to do all that across different platforms.

I am currently working with JSP, ASP, MSSQL, MySQL, Oracle, Windows Server, and Linux.

In database, I do from writing queries to backup & recovery.

Server setup, system crash recovery, DB &  Server migration also.

Plush HTML, Javascript and CSS :)

Number of projects that I'm in charge of : 5

I'm not an expert at all of them !

I have to search the Internet, read tutorials and ask questions in StackOverflow to get all that done !

So I ask you, is this normal ?

Is this a normal practice ?

Will I face the same situation whichever small company I go ?

I'm working in South Korea.
 How is it in your country ?

P.S
Thank you all for your opinion. I was going to upvote all of you because all of you helped me see it in a different way, but apparently you need 15 reputation to upvote :(


问:
What are the cases where keeping source code secret is justified?
When I worked as a freelancer, I encountered lots of cases where customers were protecting their ideas and source code of their projects (such as web applications) as much as possible, no matter how unimportant, uninteresting and unoriginal were the projects and the concepts behind.

I've already posted a question about keeping the ideas secret, and received many great answers. Now, my concern is more about source code secrecy.

According to my observations of:

The codebases I had to work on during my career,

My own willingness to keep some of my own source code secret, and:

A few articles like, for example, Open response to Simon Stuart by the popular Programmers.SE contributor Mason Wheeler,

I conclude that source code is kept secret mostly for those reasons:

Because the author is ashamed of the code of such a bad quality, or the company fears losing reputation if somebody sees such bad codebase, or that given the low quality of the codebase, it will not bring anything useful to anybody to open source it: even if somebody would be interested, he would hardly be able to run the solution (or, often, even compile).

Because parts of the code are stolen (mostly from open source projects covered by a license which restricts its usage in a given situation),

Because the code relies on security by obscurity and the author doesn't care about Kerckhoffs's principle.

Because the product is so breakable that showing the code would cause too much harm: if a closed-source app with all those security leaks would withstand a newbie hacker, the same open sourced app would have far smaller chances, because even the beginner hacker would just have to study the code to discover all the holes.

If it's not clear what I'm talking about, here's an example:

```<code>if (credentials.password === 'masterPassword12345')
{
    isLoggedIn = true
    currentUser = credentials.userName
}
else
{
    authenticate(credentials)
}
</code>```

Because the author over-estimated the source code (and his own skills and expertise). Example: believing that a home-made cryptography-related algorithm (which was never reviewed by anybody) is better than any well-known one.

Because the author believes that the idea behind the code is great, and that it would be stolen.

Because of the "It's not perfect enough" syndrome. In other words, the developer is willing to release the source code to public when the code is "good enough", but day after day, there are still things to improve, so the code would never be released.

All of those reasons give a rather negative image of people who are against publishing the source code.

Are there valid cases to not release to the public the high-quality code which follows Kerckhoffs's principle?

答:
Because it was hard to write, and test. And design. And specify. And debug. And ISO 9000. And document. And version control. And get pointy-haired boss out of the way. And whatever makes the job of a software engineer worthwhile.

And you don't want that your competitors just copy-paste your source code instead of putting as much time and money as you in their product.


问:
Is it good practice on server/client systems to automatically install updates?
I'm working on an automated update system for a legacy server/client software package written in Delphi. The way I'm designing it is so the client's (customer's) server machine runs a service which...

periodically checks online for new versions

automatically downloads files

hosts latest version information for all client machines

hosts files for client machines to update

Once this service has downloaded update files, it raises a flag in the database alerting all client machines that updates are available. BUT, the thing is, the server must be installed first. So, an administrator would see this message and approve the update. However, the administrator must schedule a time for it to install. At that scheduled time, the server will update its self. If everything was successful, it will raise another flag in the database for all client machines to also update. If anything happened, it will restore the backup which was made before the install.

My question is... Is this good practice? Of course automated updates is a very good thing... if done right. This software is used in real-time in retail and wholesale environments, so if anything goes wrong during this scheduled installation, people could come to work the next morning to a broken system. The point is, no matter how automated I make this, an administrator still needs to ensure everything went smooth.

Further issues...

client machines must know not only the database server info, but also their update server info.

server machine might be at another location which might require firewall configuration

database changes may give unforeseen results, which aren't known until something bad happens

client machines may be shut down and need to update once it starts

a list full of possible scenarios which may go wrong

So in this situation, would you feel comfortable making a 100% automated updating system for a sensitive software? Because some of our clients have up to 50 client computers which need to be updated to match their server's database.

答:
I would say that giving the sysadmin control over when the update is applied is the best way - this means that an admin can delay updating if he's working at a critical time (say, over christmas) when demand is likely to be high and staff availability low, and also the potential for a screwup to be really damaging is much higher than usual.

So an fully automated system would not be a benefit. However, that said, there are times when a non-automatic update system means the software will simply never get updated.

I would therefore offer an option - manual or automatic, and let the installer decide whether to check that auto option or not (which he will do depending on his circumstances).

the other thing that you do is the rollback mechanism - this is great. Jenkins does it, so if an update doesn't work well, you click a button and it all goes back to the previous state. I wish all applications worked like this. Once you have such a rollback system, then admins are much more likely to apply updates so you might find they use the automatic update option more often. In this case, what would also be a good thing is to make the fact that an update was recently applied to be more visible.


答: You don't hand out the source-code because then when your client needs modifications to a software you built, they will have to go with you and you can charge premium.</p>

Title: What are the cases where keeping source code secret is justified?

Body:
When I worked as a freelancer, I encountered lots of cases where customers were protecting their ideas and source code of their projects (such as web applications) as much as possible, no matter how unimportant, uninteresting and unoriginal were the projects and the concepts behind.

I've already posted a question about keeping the ideas secret, and received many great answers. Now, my concern is more about source code secrecy.

According to my observations of:

The codebases I had to work on during my career,

My own willingness to keep some of my own source code secret, and:

A few articles like, for example, Open response to Simon Stuart by the popular Programmers.SE contributor Mason Wheeler,

I conclude that source code is kept secret mostly for those reasons:

Because the author is ashamed of the code of such a bad quality, or the company fears losing reputation if somebody sees such bad codebase, or that given the low quality of the codebase, it will not bring anything useful to anybody to open source it: even if somebody would be interested, he would hardly be able to run the solution (or, often, even compile).

Because parts of the code are stolen (mostly from open source projects covered by a license which restricts its usage in a given situation),

Because the code relies on security by obscurity and the author doesn't care about Kerckhoffs's principle.

Because the product is so breakable that showing the code would cause too much harm: if a closed-source app with all those security leaks would withstand a newbie hacker, the same open sourced app would have far smaller chances, because even the beginner hacker would just have to study the code to discover all the holes.

If it's not clear what I'm talking about, here's an example:

```<code>if (credentials.password === 'masterPassword12345')
{
    isLoggedIn = true
    currentUser = credentials.userName
}
else
{
    authenticate(credentials)
}
</code>```

Because the author over-estimated the source code (and his own skills and expertise). Example: believing that a home-made cryptography-related algorithm (which was never reviewed by anybody) is better than any well-known one.

Because the author believes that the idea behind the code is great, and that it would be stolen.

Because of the "It's not perfect enough" syndrome. In other words, the developer is willing to release the source code to public when the code is "good enough", but day after day, there are still things to improve, so the code would never be released.

All of those reasons give a rather negative image of people who are against publishing the source code.

Are there valid cases to not release to the public the high-quality code which follows Kerckhoffs's principle?


问:
As a software engineer, who should I be following on Twitter?
Who in the software engineering and software development fields uses Twitter to tweet about relevant happenings in the field?</p>

答:
John Carmack!
@ID_AA_Carmack</p>

ContentLicense: CC BY-SA 2.5

Body:
John Carmack!
@ID_AA_Carmack


答:
Money was spent to solve a problem, or a specific set of problems. If competition then get the answer for these problems for "free", that puts the company that solved the problem at a financial disadvantage - especially if it would be possible for a larger company to "get to market" before the creating company because they have infrastructure in place, or if a competitor spends the money they WOULD HAVE spent on development on marketing.

What's more, it's sometimes possible to get an idea of a company's policies and processes by looking at these things. Again, this information can be used as a stratgic advantage. This is often the bigger issue... the code reveals the company's inner-workings.


问:
How QT Framework handles Events Coming from OS?
When we call QApplication::exec() at the end of our main() function, the application enters Qt's event loop. Conceptually, the event loop looks like this:

```<code>   while (!exit_was_called) {
    while (!posted_event_queue_is_empty) {
        process_next_posted_event();
    }
    while (!spontaneous_event_queue_is_empty) {
        process_next_spontaneous_event();
    }
    while (!posted_event_queue_is_empty) {
        process_next_posted_event();
    }
}
</code>```

First, the event loop processes any posted events until the queue is empty. Then, it processes the spontaneous events until there are none left. Finally, it processes any posted events that were generated during the processing of the spontaneous events.

So A single thread (main() thread in Single threaded GUI application)  can not handle program as well as Event loop(With Event Queue functionality).
Is there any threads other than main created for handling Events in QT?

答:
an event queue is perfectly capable of handling the core program without starving the spontaneous events simply by creating a new event to be handled next and returning back to the loop

in code this is likely:

```<code>Q_INVOKABLE void do_computation(int step=0){
    switch(step)
    {
        case 0:
        //do some computation
            QMetaObject.invokeMethod(this,"do_computation",Qt::QueuedConnection, Q_ARG(int,1));
            break;
        case 1:
        //continue the computation
            QMetaObject.invokeMethod(this,"do_computation",Qt::QueuedConnection, Q_ARG(int,2));
            break;
        default: return;
    }

}
</code>```

using QueuedConnection delays the dispatch until the next time the loop runs; possibly allowing other events to be handled first

for further reading I suggest reading the article on the Qt wiki about threads and events

Body:
an event queue is perfectly capable of handling the core program without starving the spontaneous events simply by creating a new event to be handled next and returning back to the loop

in code this is likely:

Q_INVOKABLE void do_computation(int step=0){
    switch(step)
    {
        case 0:
        //do some computation
            QMetaObject.invokeMethod(this,"do_computation",Qt::QueuedConnection, Q_ARG(int,1));
            break;
        case 1:
        //continue the computation
            QMetaObject.invokeMethod(this,"do_computation",Qt::QueuedConnection, Q_ARG(int,2));
            break;
        default: return;
    }

}

using QueuedConnection delays the dispatch until the next time the loop runs; possibly allowing other events to be handled first

for further reading I suggest reading the article on the Qt wiki about threads and events


答:
You're right, most companies don't need to go to any great lengths to keep their code secret, because it's of no use to anyone else. Many internal solutions are tightly linked to other applications and systems as sort of a custom ERP solution.

For some companies, the value of the software is a part of the value of their company. A crappy code base that works for their purposes has value and isn't going to be of a concern to a non-technical buyer. No one wants to buy a company with strings attached. The buyer wants a cut-and-dry answer on who owns the code and are they free to do with it what they please? Who knows, the new company may want to take an internal application and sell it to others in the industry and leverage their purchase. This group will not value a bad code base as high as a solid application. Knowing the code was kept secret (although this could be an illusion) and there are no open source licenses to work around does add value to selling the business.


答:
The question is a difficult one to answer, as someone would have to know all languages in order to know that no other has a particular feature available in Lisp, so the following is based on the languages I have experience with.

Off the top of my head, conditions are something that I haven't seen in any other language.  Think 'exceptions', but where the call stack is not unwound, and where the caller can send a recovery value to the exception site , but without disturbing the call stack in between the handler and the source of the exception.  To be fair, this is really just a special application of continuations, so Ruby and Scheme (at least) can do this.

Lisp's macro system benefits from regularity/homoiconicity, but Scala is planning to incorporate them as a stable feature in 2.12 and Template Haskell claims similar features.  I'd argue that they'll be more syntactically complex than with Lisp, but the compile-time generation of code is there regardless.

Come to think of it, though, straight building of forms is only one kind of macro available in Lisp: I haven't seen an equivalent of compiler or reader macros anywhere else.

The ability of some dialects (e.g. SBCL) to save a complete, resumable process image is cool, but again it isn't unique: Smalltalk has been doing that for decades.

Many other languages allow destructuring assignment on when returning arrays, but the #'values and #'multiple-value-bind/let-values approach still seems to be specific to Common Lisp and Scheme (which can still do 'regular' destructuring as well). Perl's 'wantarray' allows a function to determine whether it's being called in a scalar, list or void context so it can adjust its return value in a similar(-ish) way, but I've not seen 'true' multiple return values outside of Scheme/CL.

In terms of language features, there's probably not much that Lisp can do that other languages can't (Turing completeness being what it is).  What it is, however, is a language where the code is expressed in terms of its own data structures, making the Big Idea™—that code is data—something that's relatively easy to work with.

Title: Does Lisp still have any special feature which has NOT been adopted by other programming languages?


问:
Converting between data and presentation types
I'm quite new to stuff like DI, MVVM and WPF altogether, so it's fairly possible this reads like a giant WTF...

I have defined an interface in my business layer, ISomeEntity; then in my data layer, I have a public class SomeEntity : ISomeEntity entity type. The thing to note here  is that the business layer does not reference the data layer.

In the presentation layer, I can list these items, given that my window's ViewModel has a IEnumerable<ISomeEntity> property (or should it be IEnumerable<SomeEntityViewModel>?).

Now I wanted to be able to mark a list item as "to be deleted", and since I'm eventually going to have a whole bunch of such "deletable" types I created an IDeletable interface.

The SomeEntity type in the data layer doesn't need to know about IDeletable, so I implemented the interface in a SomeEntityViewModel : ISomeEntity, IDeletable class, in the presentation layer (part of me is starting to think it should be defined in the business/domain layer instead).

The problem I'm having, is that my model is spitting out ISomeEntity, which really is SomeEntity from the data layer: I need a way to convert from SomeEntity to SomeEntityViewModel, and given that SomeEntityViewModel is declared in the presentation layer, my only option seems to have my ViewModel class have a constructor like this:

```<code>public SomeEntityViewModel(ISomeEntity poco)
{
    // set the properties from the POCO implementation
}
</code>```

...and then in the class that holds the presentation logic, I can bridge between the two implementations by doing something like this:

```<code>_viewModel.Items = _model.SelectThoseItems() // returns IEnumerable<SomeEntity>
                         .Select(e => new SomeEntityViewModel(e))
                         .ToList();
</code>```

...and it works, but somehow doesn't feel right... or does it? Given ISomeEntity, SomeEntity, SomeEntityViewModel and IDeletable, what would be the "common" or "normal" way of implementing this? Or do I have it all wrong?

答:
You ideally don't want to have to implement the members of ISomeEntity that are irrelevant for the UI. For example if your engine type's interface has .ConnectionString or your UI might want .UserName .Password etc. without any reference of a connection string until the .ToSomeEntity builder is called.

So I don't think it's unusual to have separate types for the view that encapsulate your engine types rather than implement them (it's what I do, anyway). This also means that changes to the interface or base class do not necessarily require changes in UI project.


问:
What if my nested class extends another class from another package?
I'm in doubts this design is OK, it may be there is a way to do it better? The case is that I need a class which would be used in one and only class and that's it. But, this class needs to inherit from another one, which is in another package. This doesn't sound right as for me.

```<code>public class User {

private class SpecificParser extends BaseParser {} // BaseParser.java is in another package

}
</code>```

I would simply create SpecificParser as a separate class, but don't want to do that also because the only consumer of it is a User class.

答: I don't think the fact that SpecificParser is a nested class is a problem in itself. What you should think about is whether it is ok in general to have a dependency on the package containing BaseParser. For example, if this would result in a circular dependency between the two packages, that would be bad. From the looks of it, in this case it should not be a problem, since it is unlikely that a parser would ever depend on a user. :)


问:
Incremental seek on MySQL result
When outputting data in a large file, I try to make it a habit to incrementally output data in chunks, to prevent reading the entire large file into memory. As an example to show what I mean:

$fp = fopen('path/to/file.txt', 'r');
while (!feof($fp)) {
    echo fread($fp, 8192);
}
fclose($fp);
```

<p>Would this same practice be possible when fetching values from a database result? If so, how? As far as I'm aware, the ability to fetch unbuffered results from MySQL only applies to a row-by-row basis - and not per column.</p>

<p>A basic example is shown below (I am aware that the mysql extension is deprecated - this is merely for illustrative purposes):</p>

<pre class="lang-php prettyprint-override"><code>$q = mysql_incremental('SELECT `filedata` FROM `large_files` WHERE `id` = 1');
while (!mysql_incremental_eof($q, 'filedata')) {
    echo mysql_fetch_incremental($q, 'filedata');
}
mysql_free_result($q);
</code>```

A possible solution that I thought of is to combine multiple queries for portions of the file, making use of the SUBSTRING() function available in MySQL. I would imagine that although this might be more memory efficient, I'm wondering what the effect would be on network usage as well as disk activity?

答:
if your database contains large files that you do not want to be sent in their entirety, your database has a design flaw.  Depending on how finished your code is, said flaw may not be worth correcting... but since you're taking about saving memory, it's probably a good place to start.

Create a new recordset consisting of the chunks you want for each page from the large_files table.  You can try doing this as a View, or it may be necessary to create a table.

If alerting the database is not an option, write your large file to disk in a temporary location on your php server, and read it as you would any other flat file.

(by and large all of your separation of the file will increase net traffic and/or disk usage, assuming the client wants all of the file.  And if the client DOESN'T always want the entire file, that's another sign of a database design flaw.)

Title: Incremental seek on MySQL result


问:
External sqlite db file from sdcard in android
I just searched for the same but didn't get the answers. What I have is a db file which is around 100MB. I have saved the db file in sdcard .

Through this db file I'm going to populate the contents for the android app. I can read the db file using like below.

```<code>File dbfile = new File("/sdcard/Your_db_File.db" );
SQLiteDatabase  db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
</code>```

What I'm concerned is about the memory. I have read like in assets it has some memory limitations. I'm just worried like will 100MB of db file in sdcard or external memory is a harm or is it OK to have 100MB db file? Or is there any limitations for sqlite db file in external storage as well? Suggestions are appreciated.

答:
SQLite itself has no problem with 100mb databases, as you can see here it can handle upwards of 140TB in a single database file.

As for Android, each system has different constraints since various providers can decide how much physical memory to install along with which apps run at startup, etc.

I imagine there should be little problem with a 100mb database since that is effectively quite small, however the only real way to know would be to test it on a variety of target devices in a variety of scenarios.


答:
There are two issues at hand.  The first being "Is extending a class from another package in a different package bad design" the second dealing with dependencies.

Short version, its fine.

There is nothing fundamentally wrong about extending a class from a different package in another package.   Indeed, sometimes this is the only way to do it.  One cannot extend the HashMap class and place the resulting class in java.util.

Consider the classes in java.lang that get extended into other classes all over the place - Object, Number, Thread.

In many casses from third party frameworks, one will have a sealed jar which prevents one from putting a class into that namespace, yet is intended to be extended in other code.

There is nothing wrong with extending a class from some other package.  That the class is a private inner class makes this even less of an issue (as it is hiding the implementation details within itself).

Dependencies are a nightmare - and one that we have to live with.  There are two parts to this.  There is the 'you have created a dependency from User to BaseParser'.  Given the name of BaseParser, it is fairly clear that it is intended to be extended.  You just have to make sure that you document that dependency and have the appropriate tests to make sure it works the way you want it to.

There will be a dependency one way or the other. It is probably better to have something depending on a BaseSomething than for some random class in another package depending on some specific other class.

You also want to avoid a circular dependency.  It isn't too much of an issue in terms of "never do this because it will break things" but rather "avoid doing this because it creates situations where you will make a change in A that will break something in B, and fixing B will break something else in A.  There is much written on this subject.  Two examples from Stack Overflow:

Dealing with a Circular Dependency

How to remove circular dependency from two classes which are concrete types

Title: What if my nested class extends another class from another package?

Body:
I'm in doubts this design is OK, it may be there is a way to do it better? The case is that I need a class which would be used in one and only class and that's it. But, this class needs to inherit from another one, which is in another package. This doesn't sound right as for me.

```<code>public class User {

private class SpecificParser extends BaseParser {} // BaseParser.java is in another package

}
</code>```

I would simply create SpecificParser as a separate class, but don't want to do that also because the only consumer of it is a User class.


问:
Coding Style for Visually Impaired Programmer
I am visually impaired.  With glasses I see well enough to drive, but at the font size I'm comfortable working at I can only see about 15 lines of 100 characters at a time.  This has affected my coding style.

One thing I do is write shorter functions.  My code tends to get good reviews because these short functions with good names make the higher level functions very readable, but in high performance situations some folks make comments about how much space I'm taking up on the stack by passing variables down several layers for processing.

A second thing I do is divide classes up between files to make shorter files.  This reduces the scrolling distance to get to relevant functions and depending on organization may allow me to put the files up on different monitors to look at them together.

Both of these practices make for more documentable units that most coding styles require I document, which further aggravates the issue by extending the length of my file and the distance between related functions.

I'm currently using Visual Studio, which allows code folding at the function and comment block level (which I use frequently) but does not fold at the bracket level like Notepad++ does.  The editor that offers better code folding doesn't have all the intellisense features of VS.  I could use regions in VS, but this looks very cluttered if used every 10 lines.  Folding is occasionally helpful to get completed code out of view while I'm working on a different feature of the code.

Can anyone recommend better coding practices to help with limited visibility of the code?

答:
Here are a couple suggestions. If you haven't already choose a font from these recommendations that makes it easier for you to see.

Many monitors support a 90 degree rotation. This is much better for reading and will allow you to get more lines on your screen. You can undock all of the VS tools and put them on the second monitor and just have a big code monitor to maximize visibility.


答:
Not as far as I am aware of. Forth is easily as dynamic as Lisp, perhaps more so since dynamic code in Forth looks like regular Forth code while Lisp macros tend to use different features than regular Lisp code (in Clojure at least I have never used syntax quote outside of a macro) and as a result they look really different from regular Lisp code. As an example of how dynamic Forth is, here is a way to implement comments in Forth:</p>

```<code>: (   41 word drop ; immediate
( That was the definition for the comment word. )
( Now we can add comments to what we are doing! )
</code>```

Body:
Not as far as I am aware of. Forth is easily as dynamic as Lisp, perhaps more so since dynamic code in Forth looks like regular Forth code while Lisp macros tend to use different features than regular Lisp code (in Clojure at least I have never used syntax quote outside of a macro) and as a result they look really different from regular Lisp code. As an example of how dynamic Forth is, here is a way to implement comments in Forth:

: (   41 word drop ; immediate
( That was the definition for the comment word. )
( Now we can add comments to what we are doing! )


答:
I've used JNI now and then both in standard Java (desktop) applications and Android applications. Here's the gist of it all:

1 . Your question asks specifically if performance is improved by JNI: mostly, no. There are some very few and specific situations where performance is improved. 98.3% of the time this will not be the case.
Also, adding JNI solely for performance benefits will greatly complicate your project (as compared to just writing it in Java or C/C++):
There are a huge lot of very good tools (IDE, project management tools, libraries, testing tools etc) for Java-only projects (as they are for C and/or C++ -only projects). However there are a lot less (and, IMHO, of lesser quality) such tools that allow to deal with a mixed (Java) + (JNI) +(C and/or C++) project all in one go. More often than not you'll need to bring in separate tools for the Java part of your project, another for the C/C++ part of your project and maybe do a bit of custom tools developement (like scripts and such) for your JNI parts.

Here's an example: I've recently helped a friend with a Java project that had about 90% of its code use the BigDecimal and BigInteger classes. The code did a lot of the common (and some of the more exotic) algebraic operations with these: +-/* but also log, square roots and some I can't remember now. We also tried replacing those parts of the code with JNI and C code that used the MPFR library, after noticing that the features we were using out of Java's BigXXX API were also present in this library. Long story short, in this particular case, the performance gain was of about 10-15 times. Finally we decided to implement the whole module in C and only use Java for the UI along with non-granular JNI calls towards the new C module.

2 . I think the biggest reason why someone would use JNI is if he/she already has a lot of complex C and/or C++ code which needs to be integrated with Java code.
One place where this may apply is when porting an existing video game to the Android platform: Most games are made in C/C++. Android, while at it's core runs on a Linux kernel and deals with C/C++ code, offers in fact a Java API (a Java development environment very similar to the JDK/JVM you get on your PC/Mac). In such a context, doing a thin Java wrapper around existing C++ code in orderto get an old game up and running on Android is a lot faster than converting all the C/C++ code to Java entirely. With the Java thin wrapper approache there is a loss of performance, but it may very well be negligeable, depending on the resource demands of the original game, etc.

Here's a quote from Android's documentation on this:

Before downloading the NDK, you should understand that the NDK will not benefit most apps. As a developer, you need to balance its benefits against its drawbacks. Notably, using native code on Android generally does not result in a noticable performance improvement, but it always increases your app complexity. In general, you should only use the NDK if it is essential to your app—never because you simply prefer to program in C/C++.

(Bad) Example (which illustrates the last point): I've implemented the A* pathfinding algorithim in Java. I've also made a small, simple graphical demonstration of it as an Android application. I then implemented that same algorithm in C. When running separate benchmarks of the Java and C code, C was sometimes 2-3 times faster (especially if there were a lot of GC when running the Java code). So I modified my all-Java Android app to make it use the C code via JNI. While the project got a whole lot more complicated (even when using the excellent Sequoyah Eclipse plugin) the actual performance gain was now more like 10-20%, no where near the 200-300% I was seeing when running the Java and C version of this particular code separately.

How ever (and here I quote from memory) one of the earlier Android books (from the Android version 2 era) gave an advanced example of taking the Quake C++ source code and using JNI to make it into an Android App in like 20 pages (about 2-3 hours of work). If the Quake C++ code was all translated to Java (hundreds of thousants of lines of code) instead, it would take a lot longer than that. And since even the Android devices of that time were able to "hide" the performance penalities that came with JNI calling the Quake game, it made for a good trade-off to use JNI here.

Title: Is rewriting some Java code to C++ using JNI to improve performance a good idea?

Body:
I've tried rewriting some Java functions in C++ and called them using JNI. I observed that it takes longer time to execute the native C++ functions as compared to Java functions, due to the JNI overhead.

As it is widely believed that C++ has certain advantages over Java, I wanted to know whether rewriting some Java code to C++, with a view to improve overall performance of the Java application, a good idea?

If yes, then what parts of the application should be rewritten and how can a Java application use it?


问:
Generic service control interface
I need an interface to a back-end service, mostly for control commands (stop, status, cancel, reload config).  The service might be in Python, Perl, Java, or whatever, and runs continuously.  The interface will let me send infrequent commands to the running process.

A signal handler can tell a process to stop, and USR1 and USR2 signals let it do two more things.  Tomcat sets up a special listener on a fixed port number to get it to shutdown, perhaps due to limitations of Java signal handling.

But I'd like it to respond, not just react.  And I'd like to use this for a service written in any language on any platform.  I'm hoping to avoid middleware or databases to communicate, since it's a simply request/response (Q: "how are you?" / A: "I have been running for 3 hours at peak efficiency").

I glanced at these but they seem like overkill for a simple control interface:

dBus - general interprocess message bus

UPnP - device communciation

Avahi - DNS queries to find services

Hadoop YARN - Distributes work across a network, parallel processing

Each seem compelling, but they feel heavy weight or else require special software to be installed ahead of time, or aren't for every language or every platform.

If I wrote my own, I could write a single-threaded TCP listener with JSON requests/responses.  That seems about as lightweight and universal as you can get, and is small enough for a "hello world" service, and big enough for speaking to any service.  JSON over TCP would be very command-line friendly (curl or netcat), and therefore easily scriptable.  Lots of languages already have a JSON library (C++, Java, etc), in any platform.

A harder approach is adding HTTP semantics to the JSON request/response so you could browse to your application or use curl to control it.  But embedding HTTP seems like a lot of space and complexity when it will only support a few resources (PUT text/plain "true" to /stop to shutdown your app, GET application/json from /status to see how it is running).

Frankly, I'm surprised nobody invented a standard service control interface for simple things like basic control commands.  At work we used CORBA and registered in a naming service and then had to deal with Java/C++ ORB connection issues and it seemed like tons of code for something that should be simple.

答:
TR;DR: Consider Node.js with an app framework that serves JSON

Might seem daunting to learn something new, but I chatted with a 10-year Java programmer at a MeetUp last month, & he said it took him 2 days to learn Node from scratch & had a working test server that gave him JSON data his Java clients.  He was amazed; he confessed in Java it would take him 1-2 weeks in Java to do the same.  Some interesting tutorials & overviews:

http://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/

http://blog.ponyfoo.com/2013/07/12/teach-yourself-nodejs-in-10-steps

(BTW; I am NOT trying to start a Node vs Java war; Java is very good.  Simply passing along another idea from another Java programmer; pick what suits you.)

Title: Generic service control interface


问:
What is the one or the few major changes from Java 6 to Java 7, couldn't JBoss do that already with Java 5?
A buddy said today that one change between v6 and v7 is that v7 will close for instance database connection "automatically" but couldn't JBoss do that already with Java 5? I've seen "JBoss is closing the connection for you." in the JBoss' logs many years ago with Java 5 (or even 4). What do you think? I almost read the same question here but not exactly:

How to justify migration from Java 6 to Java 7?

The answer to the question above does not list the feature we were talking about this morning. What did my buddy mean? What do you think is the one or the few major technical changes? I understand Java 6 has not even support anymore but that is a policy and not the diff analyses  between v6 and v7.

答:
That feature name is automatic resource management of the Project Coin it works for streams and connections:

```<code>static void copy(String src, String dest) throws IOException {
    InputStream in = new FileInputStream(src);
    try {
        OutputStream out = new FileOutputStream(dest);
        try {
            byte[] buf = new byte[8 * 1024];
            int n;
            while ((n = in.read(buf)) >= 0)
                out.write(buf, 0, n);
        } finally {
            out.close();
        }
    } finally {
        in.close();
    }
}
</code>```

Becomes:

```<code>static void copy(String src, String dest) throws IOException {
    try (InputStream in = new FileInputStream(src);
         OutputStream out = new FileOutputStream(dest)) {
        byte[] buf = new byte[8192];
        int n;
        while ((n = in.read(buf)) >= 0)
            out.write(buf, 0, n);
    }
}
</code>```

Body:
That feature name is automatic resource management of the Project Coin it works for streams and connections:

static void copy(String src, String dest) throws IOException {
    InputStream in = new FileInputStream(src);
    try {
        OutputStream out = new FileOutputStream(dest);
        try {
            byte[] buf = new byte[8 * 1024];
            int n;
            while ((n = in.read(buf)) >= 0)
                out.write(buf, 0, n);
        } finally {
            out.close();
        }
    } finally {
        in.close();
    }
}

Becomes:

static void copy(String src, String dest) throws IOException {
    try (InputStream in = new FileInputStream(src);
         OutputStream out = new FileOutputStream(dest)) {
        byte[] buf = new byte[8192];
        int n;
        while ((n = in.read(buf)) >= 0)
            out.write(buf, 0, n);
    }
}


问:
Organisation of $(document).ready
I have some code that looks something like this, except rather than 2 sections, there are about 20, and they have real code in them:

```<code>/*------------
 * Contents:
 *  1. Load slider
 *  2. Check form
/*------------

/*------------
 * 1. Load slider
/*------------

var slider_id = 101;
var num_slides = 10;

$(document).ready(function(){
    // Initiate document ready slider
});

/*------------
 * 2. Check form
/*------------

var fields = {"text","number","textarea"};

$(document).ready(function(){
    // Do some document ready form stuff
});
</code>```

I'm trying to keep everything neat as there is going to be a handover at some stage.

My question is should I do it like I have done, or something like so:

```<code>/*------------
 * 1. Load slider
 * 2. Check form
/*------------

/*------------
 * 1. Load slider
/*------------

var slider_id = 101;
var num_slides = 10;

/*------------
 * 2. Check form
/*------------

var fields = {"text","number","textarea"};

$(document).ready(function(){
    /*------------
     * 1. Load slider
    /*------------

    // Initiate document ready slider

    /*------------
     * 2. Check form
    /*------------

    // Do some document ready form stuff

});
</code>```

So, do I minimise document ready calls, or group associated content together? Just self taught so no idea about these kinds of best practises. Thanks

答:
I'd say the general principle for this kind of thing is to avoid repeating yourself as much as possible.

Since your second example would avoid re-writing the line "$(document).ready(function() {" several times, I'd say that would be the way to go. If the initialization logic is very specific, you could write a number of "init####" methods, and have your sole initialize method call those. Two other notes:

Right now, your var's are going to be global-scope, at least, unless there's code above and below you haven't included. That means if someone else is writing important code for the same page, perhaps for something completely seperate, that also makes a reference to "slider_id", it may use yours. If your entire code is encapsulated inside an anonymous function (that is called either immediately, or on document ready) you can avoid that.

Finally, in general principle, you can replace "$(document).ready(function() {" with "$(function() {" and it should accomplish the same thing.

Title: Organisation of $(document).ready


问:
Optimize database interaction through VPN
I have to develop a batch procedure with VB.NET.
This simple procedure is going to read some data from a MS SQL database, execute some elaborations and the write the results on another Oracle SQL database located to a remote network reached via VPN. The VPN is "always on", we do not need a client to manage the connection because it is created firewall-by-firewall.

The data that I have to write are atomic, so I have to use a transaction.

Can you tell me what happen if the VPN connection fall down when a transaction is open and the COMMIT was not executed?
Do you have some suggestion/best practice to follow to avoid this scenario?

答:
Can you tell me what happen if the VPN connection fall down when a transaction is open and the COMMIT was not executed? Do you have some suggestion/best practice to follow to avoid this scenario?

Two general results may come out:

The roll-back procedure in your sql code ( or sproc, if you use one) will catch the un-committed transaction and prevent the corruption of data.

Or you will end up with corrupted data base, with orphan records.

Long story short, the application does need a good transaction management to roll back un-committed set of transactions.

The roll-back procedure should be in place to handle issues like locking, lost connection, etc. These procedures will prevent a corrupted data entry to the database system, and preserve data integrity of the entire database.

There are number of Oracle books that provide examples on how to roll-back transactions and log the issues. Just verify the version of database that you are using and find specific guidelines for that database.

References from Oracle:

4 Transaction Management

7 Transaction Handling

7.1 Troubleshooting Oracle Microsoft Transaction Server


问:
How to insert a database layer in PHP
I maintain and add features on a freelance basis to a website written in PHP. The application was started in PHP4 by a junior programmer back in 2006, and features some very insecure and unmaintainable ways of doing things, which I am trying to correct as time goes on. If the client agrees, one of the first things I would like to do is add in a proper database layer of some sort.

The current database access looks like this:

```<code>if (!function_exists('my_query')) {
function my_query($query) {

    if ($query=='disabled') return false;

    global $last_insert_id,$dbconn,$dbase;

    $result=mysql_query($query,$dbconn) or die('ERROR: '.mysql_error($dbconn).'<br />'.$query);
    $last_insert_id=mysql_insert_id($dbconn);
    return $result;
}
}
</code>```

There is also a function to make arrays from the data returned.

```<code>if (!function_exists('spawnarray')) {
function spawnarray($result)
{
    $i = 0;
    if ($result != "") {
        if (mysql_num_rows($result) > 0) {
            while($result_obj[$i] = mysql_fetch_object($result)) {
                $sp_result[$i]=$result_obj[$i];
                $i++;
            }
            return $sp_result;
        }
    }
}
}
</code>```

These two functions are basically the database layer, and SQL queries are constructed on the fly for them all over the place.

So my question is, how can I start to introduce database abstraction in to the mix? I would like to move to PDO for security and ease of use reasons, but maybe there is a better way to go?

I have already moved the project to Composer for some of its dependencies (Some are dead projects, which is a different issue) so maybe an ORM like Doctrine would be the way to go? That might mean moving the website to OOP in one go though: a daunting prospect, and a sure no-go from the client.

答:
I would suggest looking to decouple the data layer from the business logic of your application through a pattern like DAO.

Once the persistence layer is properly decoupled (and testable), you can choose the appropriate implementation for your specific needs. As long as the data layer is abstracted, that choice can be deferred and you can always swap it out with a more appropriate implementation if your needs change.

Title: How to insert a database layer in PHP


答: It looks like you lucked out in that the original developer put in a 'wrapper' function to handle mysql_* queries.  This is far better than having 15,000 mysql_query() calls spread through the code.  I'd change those functions ('my_query', 'spawnarray') to use PDO as a first step.  Then, once you are completely off mysql_*, start switching everything over to PDO if its worth the time for you (ie, depending on the importance/expected lifespan of the app in question).</p>

Title: How to insert a database layer in PHP

Body:
I maintain and add features on a freelance basis to a website written in PHP. The application was started in PHP4 by a junior programmer back in 2006, and features some very insecure and unmaintainable ways of doing things, which I am trying to correct as time goes on. If the client agrees, one of the first things I would like to do is add in a proper database layer of some sort.

The current database access looks like this:

```<code>if (!function_exists('my_query')) {
function my_query($query) {

    if ($query=='disabled') return false;

    global $last_insert_id,$dbconn,$dbase;

    $result=mysql_query($query,$dbconn) or die('ERROR: '.mysql_error($dbconn).'<br />'.$query);
    $last_insert_id=mysql_insert_id($dbconn);
    return $result;
}
}
</code>```

There is also a function to make arrays from the data returned.

```<code>if (!function_exists('spawnarray')) {
function spawnarray($result)
{
    $i = 0;
    if ($result != "") {
        if (mysql_num_rows($result) > 0) {
            while($result_obj[$i] = mysql_fetch_object($result)) {
                $sp_result[$i]=$result_obj[$i];
                $i++;
            }
            return $sp_result;
        }
    }
}
}
</code>```

These two functions are basically the database layer, and SQL queries are constructed on the fly for them all over the place.

So my question is, how can I start to introduce database abstraction in to the mix? I would like to move to PDO for security and ease of use reasons, but maybe there is a better way to go?

I have already moved the project to Composer for some of its dependencies (Some are dead projects, which is a different issue) so maybe an ORM like Doctrine would be the way to go? That might mean moving the website to OOP in one go though: a daunting prospect, and a sure no-go from the client.


问:
Why would one transform a checked exception to an unchecked exception?
My buddy told me today that some programmers transform a checked exception (e.g. EJBException, SQLException...) to an unchecked (RuntimeException?)

My buddy explained a call stack where if you change the bottom of the stack you would have to change every method that calls it if you change the bottom (innermost) method.

Can you elaborate and/or examplify with code more in detail or did I misunderstand something? I don't think that I have had that problem since I never wrote throws.

答:
Many programs have a top-level global exception handler which catches and logs all unexpected and uncaught exceptions. This means all uncaught unchecked exceptions are logged uniformly.

In this scenario, when faced with a Checked Exception which you cannot deal with or do not expect to ever occur, your easiest way of dealing with it is to simply throw new RuntimeException(ex);, because if you did throw ex; your method would have to declare it (void foo() throws SQLException), and any other methods which called it and didn't catch the exception would also need this declaration.


答:
you might want to try contacting the Blindenzentrum (Center for visually impaired students) at the University of Applied Sciences Giessen/Germany (bliz@thm.de).
They have specialized in helping students of all subjects including computer-science during their studies.
Maybe they can give you some hints that have been proven in the field.</p>

Title: Coding Style for Visually Impaired Programmer

Body:
I am visually impaired.  With glasses I see well enough to drive, but at the font size I'm comfortable working at I can only see about 15 lines of 100 characters at a time.  This has affected my coding style.

One thing I do is write shorter functions.  My code tends to get good reviews because these short functions with good names make the higher level functions very readable, but in high performance situations some folks make comments about how much space I'm taking up on the stack by passing variables down several layers for processing.

A second thing I do is divide classes up between files to make shorter files.  This reduces the scrolling distance to get to relevant functions and depending on organization may allow me to put the files up on different monitors to look at them together.

Both of these practices make for more documentable units that most coding styles require I document, which further aggravates the issue by extending the length of my file and the distance between related functions.

I'm currently using Visual Studio, which allows code folding at the function and comment block level (which I use frequently) but does not fold at the bracket level like Notepad++ does.  The editor that offers better code folding doesn't have all the intellisense features of VS.  I could use regions in VS, but this looks very cluttered if used every 10 lines.  Folding is occasionally helpful to get completed code out of view while I'm working on a different feature of the code.

Can anyone recommend better coding practices to help with limited visibility of the code?


问:
Geographically Distributed (Data & App) Architecture
Is there any design patterns (or best practices) for implementing a geographically distributed system (mostly a database)?

Description: There is a network of warehouses and a central office. Now I want every warehouse replicates it's data to the central office and the central office replicates just that portion of data related to that warehouse (when it's modified). This I can call a "filtered replication". Our database here is SQL Server 2008 R2. Should I go with another database? How about NoSQL databases?

This is a .NET based solution.

So far I have learnt about Web Synchronization for Merge Replication and I am investigating it; but I did not learnt how to implement filtered replication yet. I am not sure how NoSQL fits for an e-commerce problem (I think I need to use a combination of NoSQL+RDBMS if I should go that way) but I am investigating RavenDB and MongoDB.

Any insight would help a lot; Thanks;

答: Any research on "The CAP Theorem" will give really good insight. In general, it outlines the considerations for distributed file systems, and in researching any of those, you will find numerous solutions that meet your particular requirements..</p>


问:
Releasing open-source software including Apache2 and LGPL libraries?
I am writing software (in Java) using three libraries:

Library A, licensed under MIT license

Library B, licensed under Apache License, Version 2.0

Library C, licensed under LGPLv3

I would like to make my software publicly available under the MIT license.

I'm going to include all libraries in source and binary form (jar), including the their original licenses and copyright notices.

I put a LICENSE file at the root of my project with the MIT license.

I believe this should cover all requirements of MIT and LGPLv3, but I'm wondering about the NOTICE file mentioned in the Apache license.

If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.

http://www.apache.org/licenses/LICENSE-2.0.html

Does this simply mean that I have to include the NOTICE files that come with the library, or do I have to write my own NOTICE file mentioning the libraries and their copyrights?

Second, are there any other requirements that I may have missed?

Finally, let's suppose I'm also using Library D, licensed under GPLv3.
How does that change the situation? I understand that in this case I would have to release my project under GPLv3. Any other implications?

Please understand that I'm a student and I cannot afford a lawyer. :)

答:
If you are releasing your software with source code under the MIT license you should have no trouble including the other packages with it as long as you comply with the various notice requirements in the licenses. If it is important, check with the copyright holders of the libraries to be sure.

If you are thinking about a binary only release you will need to be sure you comply with the requirements of the LGPL that, in effect, you must allow the user to replace the LGPL library with their own version. (This is very simplified but gets to the intent of the LGPL if not the legal specifics)

If you depend on a GPL library your code is probably considered a derived work and therefor must be released under the GPL.  But for certain Java libraries the classpath exception may be relevant


答:
SQL Server and Oracle can handle rolling back transaction.  The VPN connection is going to be an issue. Break up this process to rely on it as little as possible.

Do as much work on the SQL Server data, and place the results in some set of SQL_Staging table(s).

Transfer the data from SQL_Staging to Oracle_Staging. Any breakdown occurs, this can be repeated without doing all calcs over again.

Use local code to import Oracle_Staging data to all the necessary tables with the ability to rollback. This does not require the VPN at all. Trouble-shooting is easier since you won't have to retransfer all the data from SQL Server. Really beneficial if that's not the source of the problem.

Ideally, you'd have a great always on VPN connection and could let both RDBMS handle it, but as a programmer (or are you a DBA?) you probably want a little more control.

Title: Optimize database interaction through VPN

Body:
I have to develop a batch procedure with VB.NET.
This simple procedure is going to read some data from a MS SQL database, execute some elaborations and the write the results on another Oracle SQL database located to a remote network reached via VPN. The VPN is "always on", we do not need a client to manage the connection because it is created firewall-by-firewall.

The data that I have to write are atomic, so I have to use a transaction.

Can you tell me what happen if the VPN connection fall down when a transaction is open and the COMMIT was not executed?
Do you have some suggestion/best practice to follow to avoid this scenario?


问:
After years of working alone, other developers will finally see my (buggy) code. What should I do?
I have been working on a system alone for about four years. I have built it from the ground up. It is not a perfect system. It is very complex, it is buggy, and the business is now becoming aware of this.

After all this time, other developers at the company are getting interested in the project, and they are becoming more involved. I am a bit worried they will blame me for the problems.

Am I being paranoid? Have others experienced a similar situation? How can I soften the glare of the spotlight on my buggy code?

答:
I am now worried that they will find bugs and blame me for the problems. Am I being paranoid or is there some logic in this?

Software never complete

As it goes with an old saying - "Good software is never complete".

Every software needs to evolve and go through iterations before reaching its stable stage. Eventually the frustration builds up enough to kick off another project to cover the gaps between what the product delivers and the current business needs. By the time the project is developed, delivered, and handed off to support there are new gaps, and the cycle continues on and on.

Thus, i would not worry and just lay down current project as is, and mention that it was build on initial assumptions, and it does require improvements and fixes.

Being transparent

For a professional software developer, it is always good to be transparent with your team members, and be open for new things and suggestions. Thus, it is a way to follow for a productive team building. And transparent collaboration of skills and knowledge is a must.


答:
I hope you're not to blame. The company couldn't put the resources needed to make a large and complex application as robust as possible, so they had a jr. dev to it. Maybe the app wasn't expected to be so critical at the time. The fact they want to continue the project probably shows you did something right. Now you can get some help, learn a few things, and refactor a lot of code. Nothing new in this business.

I wish I owned a software company and some middle manager tried to blame an entry programmer on the problems with such a project. "We let him code for 5 years with no help, support or code review, but I thought he was a better programmer." Could I possibly fire the manager fast enough? This is someone who is pretending to be a manager and completly abdicated his/her responsibility to this project.

Title: After years of working alone, other developers will finally see my (buggy) code. What should I do?

Body:
I have been working on a system alone for about four years. I have built it from the ground up. It is not a perfect system. It is very complex, it is buggy, and the business is now becoming aware of this.

After all this time, other developers at the company are getting interested in the project, and they are becoming more involved. I am a bit worried they will blame me for the problems.

Am I being paranoid? Have others experienced a similar situation? How can I soften the glare of the spotlight on my buggy code?


问:
Does Lisp still have any special feature which has NOT been adopted by other programming languages?
Does Lisp still have any special feature which has NOT been adopted by other programming languages?

By Lisp, I mean all the Lisp programming languages as a whole. I've been told how amazing Lisp is and know that many languages have been inspired by Lisp. But does Lisp still have any exclusive design feature that just cannot be done in any other language?

The reason I asked the question is that recently, being an amateur programmer myself, I began to learn Clojure just for fun, and the result is that I found lots of Lisp-related posts and comments, saying but one thing: "Lisp is unique", but other modern programming languages have already adopted and stolen lots of ideas from Lisp, like conditionals, recursion, and the function as a first-class citizen. And even metaprogramming can be done by many languages.

Did I miss out something and is "Lisp still different"?

Or I'm lucky because other modern languages have stolen all the good parts from Lisp so that it's not necessary to dig into the parentheses Lisp world, and "Lisp was different".

答:
After so many decades, I don't think there is anything exclusive to Lisp. But even today, there are many interesting things that are hard to find outside Lisps. A few things that come to mind:

A high-quality object system with sophisticated meta-protocols (i.e. CLOS) is not remotely popular.

multi-methods pop up from time to time somewhere, but most people never heard about them.

As others have pointed out, the condition system is quite sophisticated comparing to popular exception handling mechanisms.

A compact representation of the language's semantics (eval), an empowering approach to define one's language and making it available for straightforward deep adaptations (see SICP) -- "eval" functions of current popular languages simply don't share the same properties.

Finally, there is a lot more to learn from Lisp that is not about the language itself but became part of Lisp history and got lost in time. E.g. Interlisp, Symbolics Genera, etc...if you never put your hands on Genera, see this comp.lang.lisp thread where Kent Pitman describes how "Emacs is only a pale shadow of Genera's Zmacs" -- which was all enabled by having a powerful Lisp system which Zmacs was part of, which ran on a Lisp Machine.


问:
Sleeping Web Server?
Are there any languages or even servers that instead of running a script on page load, (Apache/PHP, Ruby on Rails, ...) actually keep the code loaded and running forever, and when it receives a connection it calls a function of that code? (Like a PageLoad event basically?)

I didn't really know how to call this so I went for Passive Web Server because the code is basically sleeping till an event occurs, instead of fully unloaded or just cached.

答: Node.js scripts typically work that way.  They act as their own web server, essentially, but are a single process that stay loaded between client requests.  This is why its so good at 'real time' communication - it can stack and manage multiple connections and pass data between them.</p>

Title: Sleeping Web Server?


答: Python through WSGI with Apache stays loaded.  Frameworks like Django route the call to the appropriate module / class.</p>

Title: Sleeping Web Server?

Body:
Are there any languages or even servers that instead of running a script on page load, (Apache/PHP, Ruby on Rails, ...) actually keep the code loaded and running forever, and when it receives a connection it calls a function of that code? (Like a PageLoad event basically?)

I didn't really know how to call this so I went for Passive Web Server because the code is basically sleeping till an event occurs, instead of fully unloaded or just cached.


答:
Keep the Atmosphere Positive

Make sure that all the programmers expect to find bugs. Make sure they get praised for resolving problems. Express thanks that you're getting the help you've needed to move on to other interesting problems.

Avoid Being Defensive

Don't say you're sorry. Don't be upset. If there are challenges suggest improved processes to solve them. Maybe you need new testing procedures? Maybe you need better requirements?


问:
How should I unit-test a class that relies on having realistic data?
I have a class that encapsulates the results of a scientific measurement. I’m building in unit tests from the beginning, but I don’t have a lot of experience with unit testing and I’m not sure which behaviors I should be testing and how.

My class does three kinds of things:

Reads measurement data from a file (or a string) into its instance variables

Writes its measurement data out to a file or a string

Performs calculations on its data (e.g. getting the average of a set of numbers)

My approach right now is to include a known-good example data file in my test directory. One test reads the data in from the file, passes it to my class, and makes sure that it meets some basic sanity checks. Another test passes the file’s filename to my class, lets the class read it, and runs the same tests. The remainder of the tests read the data in from the file, pass it to my class, and check that the results of the data-processing methods are correct, given what I know about that data set.

This seems pretty tangled, though. The tests that check (3) implicitly assume that the behaviors of (1) are correct, since it’s the functions in (1) that are being used to populate the class in the first place. And the tests of (1) could benefit from the extensive checks done by the tests for (3). Am I structuring my unit tests poorly, or is this just a natural result of the fact that I need to use a specific dataset in my tests?

答:
I think that your class is difficult to test because it has too many responsibilities. You mention them yourself

Read data from file

Write data to file

Perform calculation

Ideally, a class should have a single responsibility, or a single area of responsibility. In this case, you should definitely have a class containing only the logic for performing the calculations.

If you had that, perhaps you could have a function like this:

```<code>CalculationResult PerformCalculation(Measurement[] measurements)
{ ... }
</code>```

This becomes relatively easy to test, as you can easily supply a series of well defined measurements in a test.

I am assuming here that you read from the file once to get all measurements at once. If you collect new measurements written to the file over time, your class could look like this:

```<code>class Calculator {
    AddMeasurement(Measurement measurement) { ... }

    CalculationResult PerformCalculation() { ... }
}
</code>```

Still easy to test, because you can feed the class with a series of well defined measurements during testing, and read the result, without having dependency to the file system.

A different class could have the responsibility of reading Measurement data from the file. This could again be split into reading data from a file, and parsing the data as Measurement objects, to allow testing the parsing logic separately without dependency to the file system, etc.

If it is difficult to write a unit test, this is often a sign that your "unit" has multiple responsibilities, too many dependencies, or in other ways are not SOLID.

Body:
I think that your class is difficult to test because it has too many responsibilities. You mention them yourself

Read data from file

Write data to file

Perform calculation

Ideally, a class should have a single responsibility, or a single area of responsibility. In this case, you should definitely have a class containing only the logic for performing the calculations.

If you had that, perhaps you could have a function like this:

CalculationResult PerformCalculation(Measurement[] measurements)
{ ... }

This becomes relatively easy to test, as you can easily supply a series of well defined measurements in a test.

I am assuming here that you read from the file once to get all measurements at once. If you collect new measurements written to the file over time, your class could look like this:

class Calculator {
    AddMeasurement(Measurement measurement) { ... }

    CalculationResult PerformCalculation() { ... }
}

Still easy to test, because you can feed the class with a series of well defined measurements during testing, and read the result, without having dependency to the file system.

A different class could have the responsibility of reading Measurement data from the file. This could again be split into reading data from a file, and parsing the data as Measurement objects, to allow testing the parsing logic separately without dependency to the file system, etc.

If it is difficult to write a unit test, this is often a sign that your "unit" has multiple responsibilities, too many dependencies, or in other ways are not SOLID.


答:
Everybody Loves a Good Code Bash / WTF Session

I am now worried that they will find bugs and blame me for the problems.

Of course they will find bugs. You said it yourself: it's buggy (you
already found bugs) and complex (it's very likely to have more).

And yes they'll blame you for it. Because it's a large codebase and
they will, over time, get accustomed to the habit of tracking the
problem down to your code. And it is your code after all.

However, that doesn't mean that everything you did was bad, so
they may (if they are patient and kind enough) come to praise the
bits you did well, or recognize value in particularly well-crafted
areas of the code (assuming these exist).

Am I being paranoid

No, but you seem a bit afraid of criticism, be it fair or not.

or is there some logic in this?

As stated above, it's pretty common and normal. They'll find
problems. Lots of them. You did the thing. It seems logical they'll
blame you, as you are, after all, responsible for the code.

However it's not necessarily your fault for the way things
HAD to be done: the company should have dedicated more resources and
eyeballs to the project earlier on, and conducted more regular
reviews. But from the standpoint of other developers (and damn, are we
the picky and bashing kind...) it will often turn into a case of "oh
great, yet another example of X's famous bad design pattern or
practice".

Add lots of subjectivity into the mix (design decisions, coding
style, etc...) and it's a great recipe for a perpetual code bash.

Does anyone else have a similar experience?

Pretty much anyone who's ever written code that's been maintained by
someone else, or who's maintained code written by someone else. It's
good to have been on both sides of the fence.

Some Advice on Preparing your Hand-Over

Defend your Design Decisions.

Take the time to explain the reasoning behind your design
decisions, both good and bad. You did things one way at that time,
and there were reasons for it. Maybe you'd do it differently now,
and maybe you already knew a different way back then, but you picked
THAT way. Make sure to say WHY. If, however, you can't find a
reason, then...

... Don't Make Excuses.

If something's awful because of you, say so. They'll respect you
more for that. If a piece of the code sucks because you were green
at the time, say so. If it sucks because you didn't know a better
way at the time, say so. If it sucks because you didn't have the
time, say so. We don't care why you didn't have the
time. But it's good to know you couldn't do better at the time.
Don't deflect blame where and when it's deserved.

Remember the 1st Rule of Damage Control

Get it in the open before someone else does.

And we do mean all of it and very early.
What works for politicians, bankers and press and marketing agencies
works for crap code as well (and all aspects of life).

If your screw-ups have to come out (and here they likely will), it's
best that they come out on your terms and you keep the control.

Don't Sweat It

You'll get bashed, and you'll bash other developers over the time of
your career.

Just make sure to keep it light-hearted, positive, and
open. It's a 2-way street, so be kind in dispatching severe but
justified criticism, and be humble in accepting your share of
it.

And whatever you do, steer away from holy wars.

Personal Experience

Personally, I know I've sometimes been very unkind to coworkers or
said unkind things about code that had been written by people before
my time. And while I hope that most of the time my criticism was at
least somewhat founded, I'm sure there were times it wasn't,
for various (probably bad) reasons.

We all do that crap. Don't pretend otherwise, fellow reader frowning
at this. I'm on to you!

I've also been bashed a few times, and I've stood my ground when I
deemed it right (or strategically worth it). But I've also
accepted blame more often than not, because I fucked up. And I
still do on a daily basis. Because, as mentioned, there's usually a
reason for it.

As a consequence of this, it's become a tradition to hold informal
code bashing sessions with co-workers. Not the bad kind (though it's
been debated heartily on this site whether a "good" kind of code bash can exist). Just
the kind where you kick back on a Friday afternoon and sip your coffee
looking at dark areas of your codebase and highlight the best picks of
the week. Then you fix them. And you don't assign blame for them. You
don't even say "what a stupid way of doing X". You just chuckle at it,
refactor it, review it with coworkers so your refactoring is vetted
and history doesn't repeat itself, and you move on.

And you know what? Sometimes you'll even hit some shitty code
somewhere and realize it was yours, and you'll humbly submit it for
bashing. Because you sucked, and what's fair is fair. And you pin it
to a virtual or physical wall for all to see and remember to avoid it
in the future.

For the record, at my company we have formal review meetings required by our
processes, and some informal ones (way more frequent) whenever we feel
we want other people to vet our stuff. And then we have informal code
bashing sessions, which are more for fun. But in the end, they all
have the same outcome: we improve code, and that's what matters.

As Jeff Atwood puts it in What's Wrong with The Daily WTF (emphasis his):

[The Daily WTF] is therapeutic, even educational. But whether the
  code in question is catastrophically stupid or just plain
  ill-advised, we have to do something about it. Until we do, we are
  implicitly perpetuating the painful, costly cycle of bad coders
  writing bad code, ad infinitum. And that hurts all of us.

And in general, if you approach it this way, it comes out as rather
positive. You improve code, and people tend to become more
forgiving. We occasionally fondly remember some out-of-this-world
kind of bug, hack or plainly non-sensical piece of code, but then when
a new co-worker shows up and says something like "hang on, how could
someone have been so crazy/dumb as to do something like THAT?!" when
they run into one of our code bash archives, we just shrug and say
"hey, they probably had a good reason at the time, you know!"

And then you hope people have the same attitude after you're
gone... But you won't be there to know that anyways.

Sure, a constant random number generator or an isEmpty(String)
implementation duplicated across 73 different packages might seem like
utter stupidity. And it is, in a perfect scenario. But, quite
possibly, the guy wasn't in that perfect fairy-tale scenario. The guy
had a reason at the time. Maybe not a good one, but it doesn't
matter. Maybe it was just the wooshing sound of a deadline flying by.

Give him a break. I write shitty code all the time because of more
reasons than I'd care to list. We all do. If your coworkers are worth
2 cents and aren't total jackasses, they'll give you the same benefit
of the doubt.

Nobody Gives a Damn!

But then again... Who gives a damn?

It's your code. Own up to it. Own up to your mistakes.

Side Note: The Case for Open-Source

This is one area where open-source is said to shine. After all,
in someone else's wise words:

Given enough eyeballs, all bugs are shallow.

- Eric S. Raymond's Linus Law, excerpted from The Cathedral and the Bazaar

More eyeballs during development phases means a lesser likelihood that
bugs will creep up during production phases. You shouldn't be afraid
of scrutiny.

You'd think the larger the crowd would imply the stricter the
scrutiny. But strangely enough, in some large corporations, the level
of scrutiny isn't linked to the size of the engineering workforce at
all:

[GREAT] Companies like Google have a single code repository
for most projects, so pretty much anyone can see, review and
comment on anything.

[BAD] Others, for some good and bad reasons, compartmentalize
everything and only a few number of people review code. The result is bugs and duplication.

Open-source encourages the embrace of scrutiny.

Yes, someone will be able to dig up that stupid padding error you did
back in your early days that triggered a memory
allocation that could be exploited to cause a pretty big fat booboo
with severe consequences. So what? It's gone now, because someone
found it. And nobody's to say you'd still do the mistake now. Or maybe
you would, because, well, we all have days where we need coffee. Or
maybe we just still suck. But it doesn't matter, there's a giant herd
of people willing to try your crap code and fix it - if it's worth
anything at all for them to use. You need to take that leap of
faith: accept that people will be generally benevolent and you won't
get scarred for life; And you won't be branded with the seal of the
World's Worst Developer Ever. Quite the countrary, this will help
you to improve over time. The mythical lone developer can get
better, but he won't get the powerful and useful feedback received while working with a team.

If you're afraid of scrutiny, you're in the wrong game.


问:
Help me construct a list of best approaches for new C and C++ developers
Not specific code writing practices. Please also include reasoning.

My start:

use GCC or Clang

gcc because it is unchallenged in the amount of static checking it can do (both against standards and general errors)

clang cause it has such pretty and meaningful error messages

when compiling C code using GCC use -Wall -Wextra -Wwrite-strings -Werror

in 99,99% the warning is a valid error

when compiling C++ code using GCC use -Wall -Wextra -Weffc++ -Werror

you could skip -Weffc++ (cause it can be confusing)

always code against a standard C (C89, C99), C++ (C++98, C++0x)

while compilers change, standards don't, coding against a standard gives at least some level of assurance that the code will also compile in the next version of the compiler or even a different compiler/platform

make sure that the compiler checks your code against standard (-std=c99 -pedantic for C99, -std=ansi -pedantic for C++98 in GCC)

cause automatic checking always good

use valgrind or a similar tool to check for runtime errors (memory, threads, ...)

free bug catching

never duplicate functionality of the standard libraries (if there is a bug in your compiler, make a temporary patch, wrapper, ...)

there is no chance that your code will be better then the code maintained by hundreds of people and tested by tenths of thousands

make sure that you actually fix all bugs that are reported by automatic tools (GCC, valgrind)

the errors might not cause your program to crash now, but they will

never follow recommendations that include "never use feature X"

such recommendations are usually outdated, exaggerated or oversimplified

答:
Learn C++ from a book

Unfortunately, most freely available C++ resources are complete garbage.

Use the "Resource Acquisition Is Initialization" idiom (RAII)

This takes care of 90% of your memory management problems. The other 10% can be taken care of with smart pointers (which themselves depend on RAII). Even though the language is not garbage-collected, I've never had to use a delete statement or some kind of DestroyXXX() or ReleaseXXX() or CloseXXX() function in application code - they're always somewhere deep in library/wrapper code.

It's the reason why std::vector allows for dynamic arrays without new or delete and fstream allows for manipulation of files without needing fopen() or fclose() in application code - it's all been taken care of.

Compile with aggressive optimization when you test

(e.g. GCC's -O3 switch).  This will often uncover bugs arising from subtle things like violation of strict aliasing rules.  By doing so, you become aware of such issues, and your program will work properly in the presence of such optimizations.

Test on a PowerPC (or other big-endian machine) from time to time

Better yet, test on a 64-bit PowerPC if you can get your hands on one.  Things you can learn by doing so:

When reading a binary file, you have to pack/unpack 16-bit, 32-bit, 64-bit, etc. words a byte at a time, or use some sort of endian-aware byte-swapping mechanism.

char is not always signed.  On PowerPC Linux, GCC defaults to unsigned char.  This isn't an endianness issue, but it's a subtlety I picked up on while testing on both x86 and PowerPC.

Big endian won't let you get away with long n = ...; printf("%d", n);

64-bit big endian won't let you get away with:

```<code>curl_easy_setopt(handle, CURLOPT_TIMEOUT, 1);
</code>```

See if you can spot the bug.

Always pay attention to recommendations that say "never use feature X"

Such recommendations are typically based on the experience of lots of skilled people over a significant period of time.

If you choose to disregard such recommendations, make sure that you really understand them and the rationale behind them, before you disregard them.

If you choose to ignore them out of hand, don't be surprised if people criticize your code.

Body:
Learn C++ from a book

Unfortunately, most freely available C++ resources are complete garbage.

Use the "Resource Acquisition Is Initialization" idiom (RAII)

This takes care of 90% of your memory management problems. The other 10% can be taken care of with smart pointers (which themselves depend on RAII). Even though the language is not garbage-collected, I've never had to use a delete statement or some kind of DestroyXXX() or ReleaseXXX() or CloseXXX() function in application code - they're always somewhere deep in library/wrapper code.

It's the reason why std::vector allows for dynamic arrays without new or delete and fstream allows for manipulation of files without needing fopen() or fclose() in application code - it's all been taken care of.

Compile with aggressive optimization when you test

(e.g. GCC's -O3 switch).  This will often uncover bugs arising from subtle things like violation of strict aliasing rules.  By doing so, you become aware of such issues, and your program will work properly in the presence of such optimizations.

Test on a PowerPC (or other big-endian machine) from time to time

Better yet, test on a 64-bit PowerPC if you can get your hands on one.  Things you can learn by doing so:

When reading a binary file, you have to pack/unpack 16-bit, 32-bit, 64-bit, etc. words a byte at a time, or use some sort of endian-aware byte-swapping mechanism.

char is not always signed.  On PowerPC Linux, GCC defaults to unsigned char.  This isn't an endianness issue, but it's a subtlety I picked up on while testing on both x86 and PowerPC.

Big endian won't let you get away with long n = ...; printf("%d", n);

64-bit big endian won't let you get away with:

curl_easy_setopt(handle, CURLOPT_TIMEOUT, 1);

See if you can spot the bug.

Always pay attention to recommendations that say "never use feature X"

Such recommendations are typically based on the experience of lots of skilled people over a significant period of time.

If you choose to disregard such recommendations, make sure that you really understand them and the rationale behind them, before you disregard them.

If you choose to ignore them out of hand, don't be surprised if people criticize your code.


问:
Design decision - why generate
 without
?
tl;dr

Some widely used programs, which generate html, will only generate opening paragraph tags, and not closing ones, assuming that the browser will properly close paragraphs.

On the face of it, it seems to me that the assumption that browsers will properly close paragraphs is not correct. Is my interpretation correct? More generally, what tradeoffs are involved in this kind of decision?

Browsing through moinmoin source code, the following line of code caught my eye:

```<code># We only open those tags and let the browser auto-close them:
_auto_closing_tags = set(['p'])
</code>```

(source)

After reading throug the rest of the implementation, I've convinced myself that yes, indeed, when moinmoin generates html code for one of its pages, it will correctly generate paragraph open tags, where appropriate, while at the same time purposefully avoiding any of the paragraph close tags (despite being able to trivially do so).

For my specific, rather unusual, use case, this behaviour is not correct. I'm tempted to submit a bug report and/or change the behaviour. However, it looks like this design decision was thoughtfully made. I'm not well enough versed in the intricacies of the html standard, or the various browser implementations, to be able to tell if this is correct behaviour in general, and I have the feeling that my instinct to correct/change this behaviour might be misguided.

Is this code making a valid assumption about browser implementations? Is the generated html valid? More generally, what tradeoffs might I be missing here?

答:
The W3C specification for HTML5 specifically states that:

A p element’s end tag may be omitted if the p element is immediately
  followed by an address, article, aside, blockquote, dir, div, dl,
  fieldset, footer, form, h1, h2, h3, h4, h5, h6, header, hr, menu, nav,
  ol, p, pre, section, table, or ul element, or if there is no more
  content in the parent element and the parent element is not an a
  element.

So basically the spec has provided a lot of ways by which the complexity (large or small that it may be) of closing the tag can be avoided.  Any conforming browser implementation would have to accommodate these exceptions.

Title: Design decision - why generate <p> without </p>?