问:
Is online freelance work viable by American standards?
I've always been curious about trying out online freelance sites... it would be nice to work from home, feel independent, get to choose what I want to work on, get to work on different technologies, lose the PHB, etc.

However I never really gave them a chance because I'm used to American rates and assumed that I would be competing with people from India, Russia, China, etc. that would severely undercut me, and it wouldn't be viable for me.

Am I correct in this assumption or should I give it a shot?  What kind of hourly rate would I be able to expect on short-term programming work?

答:
When I set out to try working freelance, the first thing I did was to make a list of 100 small design and web companies in my area. I put together an informal email introducing myself, saying what I did and explaining that I was local, linking my portfolio site and suggesting that I might be a good person to pick up any spare capacity on a freelance basis.

Before I had got a quarter of the way through my list I got enough work to fill in the gaps between other projects. People liked having someone who was competent and close enough that I could go and meet them in person to demonstrate stuff or talk through projects. You don't need a lot of hits, just a few that can consistently put some work your way.

In the end I quit freelancing because I hated all the stuff that isn't about programming- all the invoicing, accountancy and other necessary administrative elements and I realised I'd be happier contracting or working full time, but if you're in an area where there are a fair number of businesses you can work with and you've got the skills ( and financial cushion ) to do the job, then it's quite feasible.


问:
Past If statements Arrays, loops... Now what?
I gave up on programming a little over a year ago when I kept hitting this wall. I am revisiting the subject because I want to create basic Android application. But I feel that my limited knowledge will not suffice.

Here is my problem.

I have read a few books and watched video tutorials on C#/Java, followed examples, then finished the book. In the end they always seem to leave me dumbfounded as to what to do next.

What a mean is they teach you from your basic "hello world" application all the way up to if's and arrays then seemingly expect you to know how to go out into the world of coding and create anything.

Am I missing something here? I know these are the building blocks of all programs but books that I read never really show me what to do next.

The easy answer I suppose would be to 'start coding', but where? I read "Head First Java" for example; up to the part were they tell you take everything you have learned and create a dog racing game....

"try not to cheat and look at the source code provided, you should be able to do this by now" _ that's not an exact quote but basically that's what I was told.......

Half an hour ago they were just explaining how to do arrays, then without any theory I am meant to create a working game?

The reason I ask this is because I fear that this is all I am supposed to know to at least start coding, yet it feels like I have been given a small toolbox and been told to build a skyscraper.

Thank you for any advice

答:
I agree with Jörg that you should also read some general books on the concepts of programming rather than learning too many details about a particular language at this stage. Regarding the book How to Design Programs, it is used as a reference in this course, which could be of interest for you.

Otherwise, another tool that others have not mentioned is speak a lot with other developers. I remember that for me one of the most effective ways for learning to program was to spend many hours discussing with colleagues or other programmers about aspects of programming, programming languages, techniques, or concrete problems I was facing at that particular moment. Oral transmission of knowledge can still be one of the most effective means for learning new skills.

ContentLicense: CC BY-SA 3.0


问:
Are immutable/stateless singletons bad?
Lately there have been some kind of revolution against singletons, but is there something wrong with them if they are stateless?

I know the overuse talk and all... this applies to everything not just singletons.

答:
It always depends on the usage.
I think the revolution comes from the fact, that every programmer learns this pattern as the object oriented pattern. Most forget to think about where it makes sense and where it doesn't.

This, of course, is true for every pattern. Just by using patterns you don't create good code or good software.

If you have a stateless singleton, why not use a class offering only static methods (or use a static class)?

Here some post regarding global variables and singletons in general.

I wouldn't be as strict as the author but he shows that for most cases where you think you need a singleton, you don't really need it.

Title: Are immutable/stateless singletons bad?


答:
There is nothing an immutable stateless singleton can do that a static class can't.

There is simply no reason to add the extra level of complexity that ->Instance() creates, while plain call to a static method will be clearer, more conservative in terms of resources and probably faster.

It's not that they are wrong. It's that there is a better way to do it. There are scenarios where normal ("stateful") singletons are the right way to go. The evil with singleton is that they are often abused, with same bad results as global variables, but there are specific cases where using a singleton is simply correct. There are none such cases for the stateless ones.

Title: Are immutable/stateless singletons bad?

Body:
Lately there have been some kind of revolution against singletons, but is there something wrong with them if they are stateless?

I know the overuse talk and all... this applies to everything not just singletons.


问:
Root cause analysis in event correlation
I'm to write an event correlator module for the device we produce. When a fault occurs the resulting avalanche of logs about derivative conditions from various modules is readable only to a person skilled in the task - a layman will be utterly lost. The event correlator is supposed to solve this problem - find root cause and present a friendly message guiding the user to the origin of the problem.

I can collect tokenized events from all the modules and observe the internal state of the main module. I can even write history a few seconds back.

Now, the hard part and my actual question: writing the analysis algorithm. I tried the Wikipedia page, but it's awfully sketchy on the specific Root Cause Analysis part, and the RCA article linked is more about a business practice than about something that can be phrased as computer algorithm. The net is full of event correlators as software to be bought or used, but I have trouble finding anything about making one.

So, summarizing:

a history of events and states dumped at the moment of error (the "black box")

a set of rules (preferably in human-editable form in some external file)

a set of root causes, derived from the events according to the rules.

a program interpreting these rules, then processing the black box through them and producing a set of root causes matching.

How do I even approach writing something like that?

What would be the format of the ruleset file and a parser for the rules - lexical parsing alone is easy enough but what would it produce?

How to represent a rule internally? As some kind of object probably, but how would that object look like? How to chain the rules together in a decision tree?

processing black box data through these rules. Seems an awful lot like running data through a script, but the data contains a lot of of noise. How to assure obtaining some results?

Now, some caveats:

I'd prefer to avoid bayesian or other statistical approach - I'd prefer a fully deterministic solution so that given set of conditions will produce the same result in laboratory analysis, and the precise set of rules is fully human-readable and human-editable.

Not all components are directly monitored, and some faults can be derived only indirectly. The root cause will not always be one particular message in the black box. Sometimes it will be something that led to a certain set of logs.

Not always the sequence of events is maintained, as messages sometimes are delayed on the message bus.

If the main power goes out, we're not guaranteed to capture all the data.

Examples:

1.

Module 1 reports halt; blockade line is active.

Module 2 reports halt; blockade line is active.

Module 4 reports halt; blockade line is active.

PSU module reports external power is okay, internal power has been disabled (per blockade line.)

Root cause: Module 3 failed gracefully, serious hardware condition activated the blockade line correctly but it was unable to send its message out.

2.

Module 1 reports halt; blockade line is active.

Module 2 reports halt; blockade line is active.

Module 4 reports halt; blockade line is active.

PSU module reports external power is okay, internal power has been disabled (per blockade line.)

Module 3 reports halt; No power in its output line. Activating the blockade line.

Root cause: Burnt fuse of output line of Module 3

Now Module 3 was mean by sending out its message last, while pulling the blockade line first.

3.

Module 3 reports halt; No power in its output line. Activating the blockade line.

Module 1 reports halt; blockade line is active.

PSU module reports external power is okay, internal power has been disabled (per blockade line.)

Module 2 reports halt; No power in its output line. Activating the blockade line.

Module 4 reports halt; No power in its output line. Activating the blockade line.

Root cause: Main fuse of internal power disengaged. Likely reason: short circuit in the PSU or fuse disengaged manually.

Note how Module 1 got late with detecting lack of power, say, its output was inactive and the capacitors kept it active long enough that it detected blockade line (engaged by other modules) first, before detecting power failure. Also, normally PSU would report a fault condition of internal power going out, but it's simply slower - less sensitive than the output modules, and they will pull the blockade line before it detects power is out, and by then it will assume this is correct behavior. The difference between cases 2. and 3. is only the number of simultaneous "no power" faults: it's extremely unlikely several fuses go out at the same time, while using the main fuse to disable power for service works is the "traditional" approach and it is expectable at least a few modules will detect "power out" if the main fuse is disengaged.

答:
While this is a large and involved topic and hardly answerable as such, let me give you few pointers for your main questions:

What would be the format of the ruleset file and a parser for the rules - lexical parsing alone is easy enough but what would it produce?

The parser entirely depends on your events. Do you have access to in-memory events? do you have to parse the resulting log files? In either case, you can consider this a preparation of  input for the algorithm.

The most precise would be in-memory access to the running software/events, but from what you described, this may probably be impossible due to real-time requirements. On the other hand, if you have to parse the log-files and then derive some meaning from them, you ought to ensure that the logfiles are meaningfully parseable, i.e. developers should know that the log-files will be parsed by a tool and how the log messages should look like. If you want to support arbitrary log messages, you'll get into deep trouble.

Also take care not to bind yourself too close to the actual log message. Keep in mind the amount of change required if someone changes the spelling/wording of a log messages and how that affects your tool. Just think: "Oh btw, there was a typo in the message and I fixed it." - "Oh thanks.. so that's why we're getting the RCA wrong". You don't wanna go there.

How to represent a rule internally? As some kind of object probably, but how would that object look like? How to chain the rules together in a decision tree?

Why reinent the wheel? There are several industry-strength rule engines available, which have that already covered pretty well (f.ex. JBoss' Drools Expert). Of course, you still need to do the usual evaluation-cycle to find out if a rule engine is suitable for your project's specific needs.

A completely different approach would be to use a programming language that is already based on rules. However, this requires that you/your team/your organisation is open-minded towards polyglot programming. Also bear in mind, that these languages are not exactly mainstream. We're talking about things like Prolog, Datalog, or CHR here.

processing black box data through these rules. Seems an awful lot like running data through a script, but the data contains a lot of of noise. How to assure obtaining some results?

First off, rule engines are not the most performant things. They are supposed to work on a very high abstraction level, so it makes sense to filter the input first. As mentioned above, you shouldn't work with black box data, because it simply is way too complex (think: full blown natural language processing!). There needs to be some order or structure to the data you have to process.

It will be part of the input preparation to ensure that you filter out ineligible or otherwise uninteresting parts of the data. You may also want to consider an intermediate language where the log message / event data is represented in a standardized way that is fully under your control. In that case, changes to the original data only need to be adapted in the original parser and your tool's core remains unaffected.


问:
I made an HTML5/Javascript game. Do I have to license it?
So I created an HTML5/Javascript online game. I host it on my website for anyone to play for free. I am still currently working on it. Do I need to license my game? And if so, what license do you recommend? I was looking at some open source licenses like GPLv3, but i'm not sure if I even need a license?

If I need a license, I need one that allows:

my game to be totally free to play

my game to be embedded on other websites

no one else can re-distribute my game, unless it is under my name and not theirs

Also, if I need a license, where do I include it? Do I just have to state somewhere that the game is licensed under "xxxxx license"? Or do I have to include a link to the license file hosted on my server? OR even include the license file in my game (i.e. in the games javascript file, or under a game menu, etc.)?

答:
Having a license is always good even if your license gives complete freedom to other people, because people will know your intentions with the software.

A while ago I saw this video on how to use GNU GPL v3 licencing, it's not that good but will give you the idea of this license:

OwnerDisplayName: Jacob


问:
Could Ruby on Rails have been created in another language?
Could Ruby on Rails have been created in another language like PHP, or are there some functions in the Ruby language that make the difference?</p>

答:
There aren't many things that one could do in Ruby more than in other languages - certainly Python is pretty similar in general and since Rails was released many other languages have implemented a railsalike framework from direct ports to tools like ASP.Net MVC.

What was different about Rails when it came out was the conceptual jump that lead to a framework that did so much of the basic legwork for you but left everything easily changed and kept out of your way once it was working. That kind of thinking is something that you might expect to come from the Ruby community because Ruby itself is designed to be very developer-friendly. It was that philosophy extended to web development that was the foundation for the Rails platform.


问:
What are the advantages of expressing information in the simplest possible format?
I want to apologize in advance if my headline is not specific enough, but I think this is a general question, although I have a very concrete example:

In my team we maintain a test specification which we use every time we release software. The specification is written in Word and, as a consequence, we occasionally have compatibility problems, wrong formatting in some parts of the document and sometimes people use the heading levels incorrectly. Nothing major, but annoyances none the less. But essentially our specification consists of test cases which can be described simply as a headline with some numbered instructions.

I think we would be a lot happier with using a lightweight markup language (e.g. AsciiDoc or Markdown) since it would be sufficient to describe the content. We would have other concrete benefits (add it to git, use diff tools, easily convert to other formats, not needing Word).

This made me think - are there any advantages, in general terms, to expressing information in the simplest possible format?

答:
In a sense you answered your own question. There are a few main advantages of conveying the information in the simplest format possible:

Ease of transport (or portability)

Clarity

Searchable

What I mean by ease of transport is the ability to use that information in as many places as possible. Using plain text for instance gives you incredible portability from one system to another. However, without formatting it might not be as clear.

Clarity is where the information conveyed is easy to understand and get across. While using something like Word can make the information very clear through advanced formatting as soon as you need that information somewhere else, the formatting can get mangled or lost. Thus clarity is lost and a simple information format with transportable formatting helps.

Simple information formats tend to be more information dense. That is what information is recorded in the format is actually appropriate information rather than lots of meta information used to handle things such as formatting. This tends to make the information more searchable with better hits. Most systems can search Word text with no problem and this is rarely an issue these days, you will still get more bang for your buck searching through simpler formatted documents.

I prefer to use Markdown myself where possible. Most of our information is kept in a wiki for this reason where it is mostly just plain text and simple formatting markers. This makes the information searchable, clear, and portable.


问:
Is this "anti-pattern" and should I stop using it or is this clever design?
I've basically stared to do the following when creating a REST service:

HTML is requested

service returns the desired web page but without the requested "resource", eg. data

web page contains JavaScript that issues AJAX request to the same service (different content-type)

service then returns the actual data (JSON) and the page displays it

On one side it seems inefficient (2 requests) but then were I used this, "performance is of no concern", meaning low traffic internal app and the web sites are simple and load fast.

The reason I ended up with this is that the web page can then be almost pure Html + JavaScript and almost no server-side stuff is required, especially no loops, to create tables and stuff like that (which I think is very ugly compared to things like slickgrid), e.g. separation of data and view.

Now before I get to using this, is this a good idea or should I just stop doing it?

答: This is a good practice. And it's done all the time, althogugh as @JanHudec points out, calling it a REST service is wrong.  But many websites do exactly this for exactly the reasons you point out.


问:
Why does Java MessageDigest.getInstance() have a String as a parameter?
I presume it's that way so it could be extended with custom algorithms, but wouldn't it be more convenient to apply, let's say, factory method pattern here and avoid the whole NoSuchAlgorithmException thing?

Something like:

```<code>MessageDigest.getMD5Algorithm();
</code>```

or

```<code>MessageDigest.getInstance(DigestAlgorithmFactory.getMD5Algorithm())
</code>```

I'm guessing there's a bigger picture here, but I just can't see it.

答:
MethodDigest.getInstance(String algorithm) is a factory method.

The algorithm param is required. A digest is an abstract concept, there is no default concrete digest but there are lots of different digest implementations.

I presume it's that way so it could be extended with custom algorithms

Yes, these are done by writing and registering security providers, such as Bouncy Castle. Note that MessageDigest itself knows nothing of the implementations, it simply looks at what security providers are available to see if one of them supports the given algorithm. It may be the case that no provider supports the algorithm, hence why it throws NoSuchAlgorithmException.


问:
What is a 'Null Terminated String' ?
I have just started reading C++, and I came across a term "Null Terminated String", I read about it but couldn't understand what it actually stands for.

I also want to know what is the difference between a c-string(also referred as "Null terminated String") and a c++ string.

答:
In computer programming, a null-terminated string is a character string stored as an array containing the characters and terminated with a null character ('\0', called NUL in ASCII).

http://en.wikipedia.org/wiki/Null-terminated_string

Title: What is a 'Null Terminated String' ?


问:
What is the difference between "recursion" and "self-reference"?
The wikipedia articles are too advanced for me to understand, could someone give me a simple explanation please?</p>

答:
Recursions, mostly useful ones, are expected to terminate after certain number of procedures in a sense that there is some initial value. unless you have a bad recursion that is useless.

Self References, are by themselves not exactly recursions but can be shown to have recursion in which case they generally never terminate.


答:
Short answer:  a null terminated string is a char array with a null value (0x00) after the last valid character in the string.

Long Answer:

It's important to remember that not every C and C++ compiler will initialize values for you.  AFAIK, most don't.

A basic string in C or C++ (without STL) is simply an array of characters.

char myString[25];

At this point in time, we have no idea what's within that string.  It could be empty; it could have garbage characters (most likely); or it could have meaningful information.  It all depends upon what was in that memory segment before the array was declared.

Note that we have 24 characters of storage here, and the null will take the 25th character.

It's common practice to pre-fill and clear a string with nulls to get rid of any garbage.

memset(myString, 0x00, 25);

Note that in this case I'm using a hexadecimal declaration of 0 to indicate NULL.  Some compilers and / or libraries have a NULL value or similar defined.

Many of the basic string functions like strcmp, strcat, etc... rely upon null terminated strings to indicate the end of the string.  If you don't have it terminated then the string function can run off the end of the string and not act as you would expect.

The C++ STL string is an actual object and takes care of some of those initialization / termination concerns for you.

Title: What is a 'Null Terminated String' ?

Body:
I have just started reading C++, and I came across a term "Null Terminated String", I read about it but couldn't understand what it actually stands for.

I also want to know what is the difference between a c-string(also referred as "Null terminated String") and a c++ string.


问:
Git-friendly spreadsheet format?
We're trying to move our project documentation process from Google Documents to a set of self-hosted Git repositories.

Text documents are Git-friendly enough, since we usually do not need any fancy formatting, we'll just convert everything to, say, multimarkdown with an option to embed LaTeX for complex cases.

But spreadsheets are quite different story... Is there a spreadsheed(-like) format that is friendly to version control systems (and, preferably, is as human-readable as Markdown)?

"Friendly format": Git works well with the format (it doesn't with XML) and it generates human-readable diffs (extra configuration involving external tools is OK).

Obviously, Markdown flavors allow one to build static tables, but I'd like to be able to use stuff like SUM() etc... (Note that CSV has the same problem.) No WYSIWYG is OK, but decent editor/tool support would be nice.

Update: Linux-friendly answers only, please. No MS Office stuff.

答:
I know that Microsoft Office 2007 and higher default to a propitiatory xml format when they save.  So that should be friendly for Git.  Open office also saves to a xml format if you are wanting to use a more open source solution.  Since a XML is a text format git should be able to handle it fairly well

Since you are moving it from Google Documents you can download them has open documents which are xml based.

Edit

Since you are wanting a non Microsoft/XML solution you could always save has a CSV in open office though I am not sure how much functionality  you lose by saving to this format.

Title: Git-friendly spreadsheet format?


问:
What are the differences between algorithms using data structures and algorithms using databases?

The General Question

What are the differences between algorithms using data structures and algorithms using databases?

Some Context

This is a question that has been bugging me for some time, and I have not been able to come up with a convincing answer for it.

Currently, I am working on strengthening my understanding of algorithms that, of course, heavily involve data structures.  These are basic structures such as Bag, Queue, Stack, Priority Queue, and Heap.

I also use databases on a daily basis to store the data that has been processed and submitted by the end-user or processed by the program.  I retrieve and submit the data through a DAL, which has data structures of its own that are generated based on the tables in the database.

My questions come when I have the option to sort the data using the database to send it back to me ordered in either an ascending/descending fashion or retrieve and load the data into my logic, process this data in a priority queue, and heap sort all of it.  Or another one would be to search for records using the database rather than loading a subset of the records and using something like binary search to find the record or records I am interested in.

In my mind, I would try to have as many operations take place on the database-end before sending it over because communication is expensive.  This also makes me wonder when do you use algorithms and data structures strictly defined within your own logic rather to process data than that of the database's?

So here are the questions...

Questions

What are the differences between data structures and databases?

When do we use algorithms that use data structures defined solely within your own logic and not that of the database's?

@Harvey post: When do the methods in the database become less efficient to use than methods in your own logic?

@mirculixx post: What makes a method efficient?

@Harvey post: How is processing data with data structures faster than doing it in the database?

Clarifications

@Grant post: The databases I normally work with are relational, and these questions are coming out of working with them.  However, I do think these questions are applicable to any persistence framework (when I say framework, I mean it in the most general sense).

I know answers without a specific context are difficult.  Food-for-thought, advice, or discussion points are mainly what I'm looking for and would be most appreciated!

答:
Disk access is primarily what is most expensive in this operation, more often so than network access (http://serverfault.com/questions/238417/are-networks-now-faster-than-disks).  Unless your database is not located on at least a 1 Gbps network and the same network as your web\application server, network performance will not matter as much as disk performance for larger datasets.  Or if your data happens to reside on very fast solid state disks which will be faster then typical network access.  Also, databases usually provide an IPC mechanism like named pipes instead of using TCP/IP if the database resides on the same server as your application server.

If you can keep most of\the enire data structure in memory between requests then this will generally be your fastest bet.  If you can't, then it is hard to beat a good database structure with normalized tables and proper indices for search and update performance on anything other than small sets of records, especially in a system with millions of records.

Relational Databases typically use a B+ tree or a variant thereof under the hood and have many optimizations like data alignment on disk and buffer pools for frequently accessed records.  This makes them excel at processing large datasets quickly, especially if aggregation or filtering is involved.


问:
Multi-platform Mobile Development?
So my question is this:

Is there any easy way for a single developer to release an app on iOS and Android?

I am a web developer that primarily plays in PHP, Node, Ruby, AS, and JS. I have dabbled a tiny, tiny bit in Objective-C and Java. Basically I am looking for a good way to release a fairly simple app on both Android and iOS and have a uniform UI that is fairly easy to maintain. The app's main purpose is a well designed visual interface (with animation to help convey actions) to a simple backend API.

Currently I was looking at using Flex, but want to find out other options if they exist. Thank you!

答:
VisionMobile has done extensive research (97 pages) on this in their Cross-Platform Tools 2012 report. It's available for free after registration. They've found over a 100 different tools and written detailed profiles of the 15 major players. Those are:

Adobe PhoneGap (Apache Cordova) - JS apps with HTML/CSS/JS UI inside a webview

Adobe Air / Flex -

Ansca Corona

Appcelerator Titanium - write JS instead of instead of Obj-C or Java, Titanium did the webview thing similar to Phonegap in older versions

Seregon DragonRad

IBM Worklight - basically a commercial enterprise version of Phonegap

Ideaworks 3D Marmalade

MoSync

Rhodes and Motorola Solutions RhoMobile - Ruby with webview

NetBiscuits BiscuitML

RunRev LiveCode

Digia Qt

Sencha Touch - JS/CSS UI framework

Unity - game engine, probably not what you're looking for

Xamarin MonoTouch and Mono for Android - write C# instead of Obj-C or Java

I'm looking into this currently for Ruby on Rails shop that wants a mobile app as well. We're looking at Rhodes but also at RubyMotion, Ruboto and MobiRuby, which instead of webviews allow Ruby to be used to code the UI instead of Objective-C or Java.

Whether you want a webview-based solutions or nod depends on your requirements and the used UI framework, such as jQuery Mobile, Sencha Touch, Zepto, etc etc. Facebook famously dropped webview (because it was slow and buggy) in favor of 100% native apps, but Sencha showed it could be done properly with their framework.

And depending on the used tool, it may or may not have the ability to write platform native code and/or UI if the framework doesn't offer the needed capabilities. Suffice it to say that there are many roads leading to Rome, and each roadmaker has its own way of doing things :)

Title: Multi-platform Mobile Development?


问:
Feature organization / authentication?
Let's say I have a product that has different features, or different feature access depending on things (i.e Premium User, Beta, Demo, Logged-in User, etc..).

What's the best way to organize a system to where it's not a set of static checks (i.e a bunch of if statements, for example)?

The platform isn't important, I'm precisely asking for design principles / general design.

答: I would start by creating a model, of couse. Create your business logic, data access, create some base classes, etc... Keep it loosly coupled for when you see that the design could be better.</p>

Title: Feature organization / authentication?


答:
The Proxy design pattern may be an interesting starting point. One of the variations described in Design Patterns: Elements of Reusable Object-Oriented Software is called the protection proxy, which is designed for access control when different objects should have different access rights. The Decorator pattern may also be interesting, especially since a "protection proxy might be implemented exactly like a decorator".

I'm assuming that you are representing your User as an object. A protection proxy to perform authentication or a decorator to add additional rights/privileges seems like a natural solution. But without knowing how you are representing your user and how it interacts with other aspects of your system, it's hard to say anything more concrete.

Title: Feature organization / authentication?

Body:
Let's say I have a product that has different features, or different feature access depending on things (i.e Premium User, Beta, Demo, Logged-in User, etc..).

What's the best way to organize a system to where it's not a set of static checks (i.e a bunch of if statements, for example)?

The platform isn't important, I'm precisely asking for design principles / general design.


问:
how do you seperate from designing question to programming questions?
As i try to program a solution to a request arise. I can't separate the difference between implementation problems and design problems.

How do you specifically express the design problem?

答:
Design problems are a subset of implementation problems since technically everything is an implementation.

Design problems have the distinct bonus of requiring you to change large sections of code in order to make it work.  If you're having to rewire half your program due to this request, it's a design problem.  Pray it isn't.

ContentLicense: CC BY-SA 2.5


答:
There are two general approaches to solving this problem

providing specific modules to enable features

using a license key (or similar authorization mechanism) to control feature access

Based upon your mentioning of different features for beta users, you might want to consider organizing the features into separate modules.  That will allow you to control which functionality is received without having to duplicate code paths (old path, new path) in the newer modules.

Using a license key to enable beta functionality would work if the functionality was brand new to the application.

Title: Feature organization / authentication?


答:
You can also use libreOffice/open-office-spreadsheet-non-zip-xml-fileformat "*.fods" which is plain xml.
@glenatron s comment applies to this format, too.

The standard open ofice spreadsheet format "*.ods" is zipped xml and not so suitable for git (similar to @Egryan/@emuddudley answer).

Title: Git-friendly spreadsheet format?

Body:
We're trying to move our project documentation process from Google Documents to a set of self-hosted Git repositories.

Text documents are Git-friendly enough, since we usually do not need any fancy formatting, we'll just convert everything to, say, multimarkdown with an option to embed LaTeX for complex cases.

But spreadsheets are quite different story... Is there a spreadsheed(-like) format that is friendly to version control systems (and, preferably, is as human-readable as Markdown)?

"Friendly format": Git works well with the format (it doesn't with XML) and it generates human-readable diffs (extra configuration involving external tools is OK).

Obviously, Markdown flavors allow one to build static tables, but I'd like to be able to use stuff like SUM() etc... (Note that CSV has the same problem.) No WYSIWYG is OK, but decent editor/tool support would be nice.

Update: Linux-friendly answers only, please. No MS Office stuff.


问:
Representing a rule in a ruleset
How to represent rules for a rule engine as objects?

A rule would be

if (booleanExpression(input)) then a chain of generic actions" else next rule

...where the generic actions might be e.g. passing the input to a different chain of rules, returning a conclusion (terminating analysis with result), or gathering additional data - though probably other actions might prove necessary too.

Now the problem of parsing arbitrary boolean conditions aside (let's assume we have a fully working booleanExpression class available), how would such a Rule object look like, and specifically, how would the Ruleset object containing orderly, interconnected grid of these look like, in particular in a structure that will be possible to process by the actual engine. (if the data structures don't make it obvious how such engine should process them, maybe a hint about it too?)

This will be written in C++ but a language-agnostic answer is most welcome too.

This is derivative of my question about Event Correlator, which seems to be unanswerable simply because it's too broad to tackle in one answer, so I'm trying to split the problem into smaller, bite-sized chunks.

答:
This is somewhat oblique to your question, but it sounds to me as though what you are talking about in this case is actually the creation of a Domain Specific Language- if you start researching those you will find all kinds of interesting articles. Martin Fowler provides a good starting point.

DSLs are a very useful area to be conscious of and something that I think we will be seeing a lot more of over the next few years.

Title: Representing a rule in a ruleset


答:
To answer the second question first, a C++-string is an instance of the class std::string that is part of the C++ standard library.

A c-string (or c-style string, or NUL-terminated string) is a sequence of characters that ends at the first '\0' (ASCII NUL) character.

One important difference is that a std::string can contain embedded NUL characters within its contents, but a C-style string by definition can not (as it ends at the first NUL character).

So, the term 'NUL terminated string' (often "misspelled" as null-terminated) comes from the fact that such a string ends in (is terminated by) a NUL ('\0') character.

Title: What is a 'Null Terminated String' ?


答:
Null-terminated strings are not like strings in most other languages. They are the standard way to represent strings in C, as nothing more than an array of characters in sequential order. In a language like C++, a string is an actual object with parameters and stuff.

The problem with this array of characters is, how do you know when to stop reading, where the end of the string is? Since the null character isn't used for anything else, it's used to terminate the string, i.e. mark the endpoint.

Title: What is a 'Null Terminated String' ?


答:
```<code>  > Are immutable/stateless singletons bad?
</code>```

No if they do not depend on other external Systems.

Example: A Stringutility that escapes html inside a string.

Reason: In unittests there is no need to replace this with a mock/simulator.

Yes if your immutable/stateless singleton depend on other external Systems/Services and if you want to do unittesting (testing in Isolation)

Example: a Service that depends on an External Tax-Calculator-Webservice.

Reason: In order to do unittests with this Service (in isolation) you need to simulate/mock the external Systems/Services.

For more details see the-onion-architecture

Singleton-s can make unit-testing (in isolation) more difficuilt/impossible and

hidden dependecies/coupling can be sees as a problem as explained by @yBee

I donot see other reasons why not using Singletons.

Title: Are immutable/stateless singletons bad?

Body:
  > Are immutable/stateless singletons bad?

No if they do not depend on other external Systems.

Example: A Stringutility that escapes html inside a string.

Reason: In unittests there is no need to replace this with a mock/simulator.

Yes if your immutable/stateless singleton depend on other external Systems/Services and if you want to do unittesting (testing in Isolation)

Example: a Service that depends on an External Tax-Calculator-Webservice.

Reason: In order to do unittests with this Service (in isolation) you need to simulate/mock the external Systems/Services.

For more details see the-onion-architecture

Singleton-s can make unit-testing (in isolation) more difficuilt/impossible and

hidden dependecies/coupling can be sees as a problem as explained by @yBee

I donot see other reasons why not using Singletons.


答:
A null-terminated string is a sequence of characters with a trailing 0-valued character.  So a string like "Hi" is represented as the sequence {72, 105, 0} (ASCII).  The 0 is a sentinel value that indicates the end of the string.  The C string library functions (strcmp, strcpy, etc.) rely on the presence of that 0 byte to operate correctly.

This is different from Pascal or old-school BASIC strings that stored the string length in the leading byte ({2, 72, 105}).

In C, strings are stored in arrays of char.

The C++ string class uses null-terminated strings under the hood (at least in the implementations I'm familiar with), but its interface is such that you don't normally have to worry about that level of detail.

Title: What is a 'Null Terminated String' ?


答:
Well, how will you invoke this thing?

I would assume it's something like this:

```<code>for (auto rule: ruleset) {
    if (rule.matches(context)) {
        if (rule.execute() == Stop)
            break # so rules can stop early
        # else: default action is to continue
    }
}
</code>```

So, you have an object with with two methods

```<code>bool Rule::matches(Context const& input) { return booleanExpression(input); }
void execute() {
    for (auto action: actions) action.execute();
}
</code>```

Is that the sort of thing you're looking for? This trivially works for a simple linear ruleset (a bit like iptables, though even that needs branching), but for a decision tree, one of the available actions needs to be "recursively evaluate this nested subtree". It'll be easier to demonstrate with a small sample ruleset, if you have one.

Title: Representing a rule in a ruleset

Body:
How to represent rules for a rule engine as objects?

A rule would be

if (booleanExpression(input)) then a chain of generic actions" else next rule

...where the generic actions might be e.g. passing the input to a different chain of rules, returning a conclusion (terminating analysis with result), or gathering additional data - though probably other actions might prove necessary too.

Now the problem of parsing arbitrary boolean conditions aside (let's assume we have a fully working booleanExpression class available), how would such a Rule object look like, and specifically, how would the Ruleset object containing orderly, interconnected grid of these look like, in particular in a structure that will be possible to process by the actual engine. (if the data structures don't make it obvious how such engine should process them, maybe a hint about it too?)

This will be written in C++ but a language-agnostic answer is most welcome too.

This is derivative of my question about Event Correlator, which seems to be unanswerable simply because it's too broad to tackle in one answer, so I'm trying to split the problem into smaller, bite-sized chunks.

Body:
Well, how will you invoke this thing?

I would assume it's something like this:

for (auto rule: ruleset) {
    if (rule.matches(context)) {
        if (rule.execute() == Stop)
            break # so rules can stop early
        # else: default action is to continue
    }
}

So, you have an object with with two methods

bool Rule::matches(Context const& input) { return booleanExpression(input); }
void execute() {
    for (auto action: actions) action.execute();
}

Is that the sort of thing you're looking for? This trivially works for a simple linear ruleset (a bit like iptables, though even that needs branching), but for a decision tree, one of the available actions needs to be "recursively evaluate this nested subtree". It'll be easier to demonstrate with a small sample ruleset, if you have one.


问:
Working with clients who don't know what they want
I have recently started a job that has me working on an existing system. It requires tweaks and updates as well as new code. I have done several maintainance/feature adding projects now, and several of them have ended up being significantly different from what was actually requested. So, I had to program the item several times to get it to where the requester wanted.

Now, I don't mind reprogramming the feature if that's what needs to be done. However, I would like to decrease turnaround time on my projects. The bottleneck seems to be in the requester's perception of what needs to be done. Do you have any ideas on what I could do to figure out what the requester needs more quickly?

答:
After many annoying rewrites, I now operate what I call full disclosure.

So after discussing the customers requirements and desires, I will always write up what I perceive they want and how I will proceed to fulfil that requirement. I will then send them what I've written and wait until they reply in the affirmative before beginning work.

If its a large project (more than say 5 days work) I'll prototype as well. This gives them a chance to change their mind without massive code changes at my end.

It doesn't always work, but at least I am in a position where the client knows it is them changing their mind and not me implementing incorrectly.


答:
Given that you have already defined what a rule is, the corresponding data structure would be straightforward (pseudo-code):

```<code>class Rule {
  Condition condition;
  ActionSet positiveActions, negativeActions
}
</code>```

However, as you indicated by your reference to a ruleset, the interesting part of rule engines is the process of rule selection and their execution strategy. I'm afraid that there are as many variants as you believe there might be - plus some.

Typically though, a rule engine's rules - at least for about the dozen rule engines I've seen - do not contain an "else" part. The idea of rules being that they have some condition on when they apply, but if they do not apply, then they simply are not applied. Hence, the engine development comes down to two core tasks:

Determine which rules are applicable

Numerous research papers are available on this one. The selection of applicable rules depends highly on the data structure used to represent your rules. If you truly want to allow arbitrary boolean conditions, then clearly, nothing can be determined unless the condition is evaluated on all possible inputs. Hence, most rule engines have some objects/predicates/constraints/whatever-the-things-are-called, which you have to use for the part of the rule that makes it applicable. This allows the engine to intelligently (read: efficiently) select from all rules and inputs the applicable ones.

Here's a more concrete example of how something like this could look like in f.ex. Prolog:

MySignal(_, true, false) :- do_something

MySignal(_, true, true) :- do_something_else

Clearly an implementation can abuse the fact that these rules only apply to MySignal and only in case of the second argument being true. Hence, it is possible to improve the rule lookup with a dedicated lookup table for MySignal.

Note that in addition to the rules there is one very important other aspect, namely the input or more generally, the data on which these rules are supposed to operate. In most rule engines, it is furthermore possible to modify this data by the application of rules (i.e., you start with something, then the rules add new things to that data). In this example, the input would need to be stored such that one can efficiently determine if there is a MySignal input (again some kind of lookup table could be envisioned).

This input handling also needs a connection to your rules. In rule engines this is either performed via the above-mentioned objects/predicates/etc., or via logical variables. In other words: the actions that your rule has to perform will typically depend on the input, and as such, the input needs to be passable to the actions in some way. More concretely consider the following example:

MySignal(X, false, false) :- print(X)

Determine execution strategy of applicable rules

Most engines fall back to a trivial top-to-bottom strategy here, as in, the textually first rule in the rules file that matches the input is applied. You can go arbitrarily complex here as well. Just a few examples of different possible strategies:

Prolog adds backtracking to the rule execution strategy such that a failure leads to another rule being used during the backtracking.

Priority annotations made to rules can be used to derive a priority and from that the execution order.

Probabilities can be annotated as well, leading to a probabilistic rule engine that selects from the applicable rules via a PRNG.

Simple strategies are also possible, like simply executing the first rule found or all rules that are applicable (the latter only works if the rules do not consume the input).

So essentially your question boils down to which way you want to go: either full-blown rule engine, or a simple filter-map combination.

Just for the sake of completeness, here's a faked rule-engine approach that might be applicable to your case (functional pseudo-code, without else-part but that should be clear). In this case, the rule selection is simply to check that the input satisfies the condition and the execution strategy is to apply all applicable rules in their textual order:

```<code>let I be the list of inputs
let R be a list of rules
I map (i => R filter ( r => r.condition(i) == true ) map ( r => r.action(i) )
</code>```

Obviously, the runtime complexity is very bad with increasing number of rules due to the need of having to check each combination of condition and input. After all, a prime feature of rule engines is that they provide some means to deal with this combinatorial explosion.

In case you are interested on the proper rule engines, here are a few additional keywords to get you started on your quest on how to implement these: rule-based operational semantics, RETE, unification

Title: Representing a rule in a ruleset

Body:
Given that you have already defined what a rule is, the corresponding data structure would be straightforward (pseudo-code):

class Rule {
  Condition condition;
  ActionSet positiveActions, negativeActions
}

However, as you indicated by your reference to a ruleset, the interesting part of rule engines is the process of rule selection and their execution strategy. I'm afraid that there are as many variants as you believe there might be - plus some.

Typically though, a rule engine's rules - at least for about the dozen rule engines I've seen - do not contain an "else" part. The idea of rules being that they have some condition on when they apply, but if they do not apply, then they simply are not applied. Hence, the engine development comes down to two core tasks:

Determine which rules are applicable

Numerous research papers are available on this one. The selection of applicable rules depends highly on the data structure used to represent your rules. If you truly want to allow arbitrary boolean conditions, then clearly, nothing can be determined unless the condition is evaluated on all possible inputs. Hence, most rule engines have some objects/predicates/constraints/whatever-the-things-are-called, which you have to use for the part of the rule that makes it applicable. This allows the engine to intelligently (read: efficiently) select from all rules and inputs the applicable ones.

Here's a more concrete example of how something like this could look like in f.ex. Prolog:

MySignal(_, true, false) :- do_something

MySignal(_, true, true) :- do_something_else

Clearly an implementation can abuse the fact that these rules only apply to MySignal and only in case of the second argument being true. Hence, it is possible to improve the rule lookup with a dedicated lookup table for MySignal.

Note that in addition to the rules there is one very important other aspect, namely the input or more generally, the data on which these rules are supposed to operate. In most rule engines, it is furthermore possible to modify this data by the application of rules (i.e., you start with something, then the rules add new things to that data). In this example, the input would need to be stored such that one can efficiently determine if there is a MySignal input (again some kind of lookup table could be envisioned).

This input handling also needs a connection to your rules. In rule engines this is either performed via the above-mentioned objects/predicates/etc., or via logical variables. In other words: the actions that your rule has to perform will typically depend on the input, and as such, the input needs to be passable to the actions in some way. More concretely consider the following example:

MySignal(X, false, false) :- print(X)

Determine execution strategy of applicable rules

Most engines fall back to a trivial top-to-bottom strategy here, as in, the textually first rule in the rules file that matches the input is applied. You can go arbitrarily complex here as well. Just a few examples of different possible strategies:

Prolog adds backtracking to the rule execution strategy such that a failure leads to another rule being used during the backtracking.

Priority annotations made to rules can be used to derive a priority and from that the execution order.

Probabilities can be annotated as well, leading to a probabilistic rule engine that selects from the applicable rules via a PRNG.

Simple strategies are also possible, like simply executing the first rule found or all rules that are applicable (the latter only works if the rules do not consume the input).

So essentially your question boils down to which way you want to go: either full-blown rule engine, or a simple filter-map combination.

Just for the sake of completeness, here's a faked rule-engine approach that might be applicable to your case (functional pseudo-code, without else-part but that should be clear). In this case, the rule selection is simply to check that the input satisfies the condition and the execution strategy is to apply all applicable rules in their textual order:

let I be the list of inputs
let R be a list of rules
I map (i => R filter ( r => r.condition(i) == true ) map ( r => r.action(i) )

Obviously, the runtime complexity is very bad with increasing number of rules due to the need of having to check each combination of condition and input. After all, a prime feature of rule engines is that they provide some means to deal with this combinatorial explosion.

In case you are interested on the proper rule engines, here are a few additional keywords to get you started on your quest on how to implement these: rule-based operational semantics, RETE, unification


答:
I would suggest you try to go away using actual boolean expressions and figure out what actions or events you're doing to the "system" that you're developing. If you're using if-statements you might as well use a scripting language.

Once upon a time I've created a DSL in JSON format that defined rules as actions or events instead of using boolean expressions. I chose JSON because the DSL code was generated from a web backend and was going to be used in a javascript web front end.

Consider a series of options one user can take in a designer UI, all individually identifiable by a name. The designer UI for the example below will be cars that the user can select. The DSL basically looked like this:

```<code>// an array of rules
"rules": [
    // rule number 1
    {
        // the originating option of the event or action
        "source": "car_1",

        // the option(s) that receives of the action or event
        "destination": ["color_yellow", "color_blue"],

        // the event or action that should happen
        // in this case the destination should be disabled
        "action": "disable",

        // what to roll back to if the destination was selected
        "instead": "color_red"
    },
    // rule number 2, same as above but used to
    // demonstrate chaining
    {
        "source": "roof_sunroof",
        "destination": "color_red",
        "action": "disable",
        "instead": "color_green"
    },
    ... and so on
]
</code>```

In this example, in the first rule: if the user selected the option "car_1" the color options "color_yellow" and "color_blue" will be disabled (because that particular car does not come in yellow and blue colors). In the second rule, if the user selects "roof_sunroof", then the option of "color_red" is disabled.

Meanwhile the front-end would take this JSON file and create all the options on the User Interface and use the rules array to determine which events to set up.

The actions and events were implemented in such extend that they were chainable by the rule set, so if one source would disable and the roll back option was also disabled, the event would look up what to roll back to instead. In the example above if the option "roof_sunroof" was selected and then "car_1", the application would first try to rollback to "color_red" (which is disabled) and then to "color_green". If there was any circular dependencies, it would most likely be a bug in the DSL rather in the designer UI. Note that the events enforce the rules without the need to build a complex tree.

On the back-end side, it's easier to represent the rules as objects if they're definitions for a DSL. Sure if you go the if-statement route, you could persist the rule as a text script.

Title: Representing a rule in a ruleset

Body:
I would suggest you try to go away using actual boolean expressions and figure out what actions or events you're doing to the "system" that you're developing. If you're using if-statements you might as well use a scripting language.

Once upon a time I've created a DSL in JSON format that defined rules as actions or events instead of using boolean expressions. I chose JSON because the DSL code was generated from a web backend and was going to be used in a javascript web front end.

Consider a series of options one user can take in a designer UI, all individually identifiable by a name. The designer UI for the example below will be cars that the user can select. The DSL basically looked like this:

// an array of rules
"rules": [
    // rule number 1
    {
        // the originating option of the event or action
        "source": "car_1",

        // the option(s) that receives of the action or event
        "destination": ["color_yellow", "color_blue"],

        // the event or action that should happen
        // in this case the destination should be disabled
        "action": "disable",

        // what to roll back to if the destination was selected
        "instead": "color_red"
    },
    // rule number 2, same as above but used to
    // demonstrate chaining
    {
        "source": "roof_sunroof",
        "destination": "color_red",
        "action": "disable",
        "instead": "color_green"
    },
    ... and so on
]

In this example, in the first rule: if the user selected the option "car_1" the color options "color_yellow" and "color_blue" will be disabled (because that particular car does not come in yellow and blue colors). In the second rule, if the user selects "roof_sunroof", then the option of "color_red" is disabled.

Meanwhile the front-end would take this JSON file and create all the options on the User Interface and use the rules array to determine which events to set up.

The actions and events were implemented in such extend that they were chainable by the rule set, so if one source would disable and the roll back option was also disabled, the event would look up what to roll back to instead. In the example above if the option "roof_sunroof" was selected and then "car_1", the application would first try to rollback to "color_red" (which is disabled) and then to "color_green". If there was any circular dependencies, it would most likely be a bug in the DSL rather in the designer UI. Note that the events enforce the rules without the need to build a complex tree.

On the back-end side, it's easier to represent the rules as objects if they're definitions for a DSL. Sure if you go the if-statement route, you could persist the rule as a text script.


问:
Why is reverse debugging rarely used?
gdb implemented support for reverse debugging in 2009 (with gdb 7.0). I never heard about it until 2012. Now I find it extremely useful for certain types of debugging problems. I wished that I heard of it before.

Correct me if I'm wrong but my impression is that the technique is still rarely used and most people don't know that it exists. Why?

Do you know of any programming communities where the use of reverse debugging is common?

Background information:

Stackoverflow: How does reverse debugging work?

gdb uses the term "reverse debugging" but other vendors use other terms for identical or similar techniques:

Microsoft calls it IntelliTrace or "Historical Debugging"

There's a Java reverse debugger called Omniscient Debugger, though it probably no longer works in Java 6

There are other Java reverse debuggers

OCaml's debugger (ocamldebug) calls it time travel

答:
For one, running in debug mode with recording on is very expensive compared to even normal debug mode; it also consumes a lot more memory.

It is easier to decrease the granularity from line level to function call level. For example, the standard debugger in eclipse allows you to "drop to frame," which is essentially a jump back to the start of the function with a reset of all the parameters (nothing done on the heap is reverted, and finally blocks are not executed, so it is not a true reverse debugger; be careful about that).

Note that this has been available for several years now and works hand in hand with hot-code replacement.

Title: Why is reverse debugging rarely used?


答:
What about pyspread? It's powerful and comes with a nice GUI.

According to the First Steps page:

The pys file format has changed in version 0.2.0. It now is a bzip2-ed
  Text file with the following structure:

[Pyspread save file version]

0.1

[shape]

1000 100 3

[grid]

7 22 0 'Testcode1'

8 9 0 'Testcode2'

[attributes]

[] [] [] [] [(0, 0)] 0 'textfont' u'URW Chancery L'

[] [] [] [] [(0, 0)] 0 'pointsize' 20

[row_heights]

0 0 56.0

7 0 25.0

[col_widths]

0 0 80.0

[macros]

Macro text

The fact that it is bzip2-ed does not help but at least you can access a quite readable text.

Licence is GPLv3.

Title: Git-friendly spreadsheet format?


问:
Is there a synonym for "Blittable" that is more common?
Is there a more common name for a "Blittable" data type?  In my software there is a distinction between a variable sized structure and a fixed size structure that has a similar behavior to "blittable" but I have only seen the name used in Microsoft software.</p>

答:
World Engineer's answer is quite fine, and gives a good historical perspective. To actually answer the question you asked though:

Is there a synonym for “Blittable” that is more common?

Yes. In C# such types are properly called unmanaged types. Section 18.2 of the specification recursively defines an "unmanaged type" as:

sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool.

Any enum type.

Any pointer type.

Any user-defined struct type that contains fields of unmanaged types only.


问:
Is a degree needed for low-level/embedded programming jobs?
I know that it is possible to get into software development without a degree in computer science, but is it possible (or rather, common) to be able to get an embedded programming job without the computer science degree (or any engineering degree as well)?</p>

答:
As noted by Neil, in a lot of cases, a Bachelors degree in computer science is going to be more about getting your foot in the door with an entry level job than anything else. Likewise, it is also one of the check boxes that HR departments are going to be looking at when they are filtering applications and at some companies, the degree is mandatory for the given job, but they usually aren't software companies.

In terms of getting your foot in the door without a degree, some sort of proof that you know what you are doing is going to be needed so it might be a good idea to look around to see if there is some sort of class that you can take on the subject. This would give you some formal training that you can list on your resume and would also give you a chance to interact with people that know the subject so they can point out some things that might take you longer to come across on your own. Also, you might want to look into user groups that are in your area and start attending meetings so. The networking opportunities that such meeting get your name out there if you get a chance to do a demo at one of the meetings.


答:
CSV (Comma Separated Values)

If you're just working with data it's probably the simplest and most commonly supported format.

Should make life easy if you want to diff between versions.

Oh, and Google Docs fully supports CSV import/export.

Update:

Then just write a Google Apps Script to stringify the formulas on export and do the reverse on import. You'll need to use some ingenuity because the format you're looking for doesn't exist.

Title: Git-friendly spreadsheet format?


问:
Are there any advantages of SASS over LESS?
I'm trying to do research on these css preprocessors.

Are there any advantages of using sass over less as a css preprocessor? Factors that i'm looking for include community size, software project maturity, etc.

I know there was another question related to this, but it was not constructively written and closed.

Update

Looks like bootstrap now has gone over to use Sass

答:
I do believe that your choice may depend at least a tiny bit on what you're doing or using; I work primarily with Rails and it supports Sass for its CSS to the point that it is actively included upon creating a new project. If you want to use something like the ever-popular Bootstrap, which utilizes Less by default, you don't have to fear, because there are many popular gems such as bootstrap-sass which enable you to use it in your project.

This is strictly anecdotal, but every impression I have personally had is that Sass has a larger community and more support, and quite frankly the official documentation for Sass is much more detailed and lengthy than that of Less (increasing the font size and padding for everything does not a longer piece of text make). If you want to go into specifics, although I am not entirely familiar with Less, based strictly on looking at both languages, Sass is the only one with selector inheritance. I am sure that there are other difference which people can elaborate on.

In the end, everyone has their preferences and if you find that one suits you better than the other, you should by all means use it if it can do what you need it to. However, in my time using Sass, I have certainly enjoyed its clarity and effectiveness, particularly considering that I am in the Rails domain.


问:
Is it necessary to add the default case while using switch cases?
During a recent code review I was asked to put default cases in all the files wherever switch block is used, even if there is nothing to do in default. That means I have to put the default case and write nothing in it.

Is this the right thing to do?
What purpose would it serve?

答: I would also add that it depends on the philosophy of the language you are using. In Erlang for example, where it is a common approach to 'let it crash', you would not define a default case but let your case statement raise an error if a situation occurs that was not catered for.


答:
I am not sure if Less has anything comparable, but one of the main advantages of Sass is the Compass library, which provides you with many common CSS idioms, standard hacks needed for older browsers and CSS3 functionalities without the need of browser prefixing, not to mention automatic generation of CSS for sprite images.

Another advantage - at least for me - is that Sass allows a Python-like syntax that I find much more readable.

Title: Are there any advantages of SASS over LESS?

Body:
I'm trying to do research on these css preprocessors.

Are there any advantages of using sass over less as a css preprocessor? Factors that i'm looking for include community size, software project maturity, etc.

I know there was another question related to this, but it was not constructively written and closed.

Update

Looks like bootstrap now has gone over to use Sass


答:
Chris Coyier has an awesome rundown of SASS vs LESS over at css-tricks.com. It's definitely worth the read.

As for some of your specific questions:

Community

I work entirely with SASS/Compass, so I'm not intimately familiar with LESS's community, but nor have I really needed SASS's community. Their documentation is fantastic and has solved any problems I've run into thus far.

For what it's worth, though, here are the SASS vs LESS statistics that Chris has in his post, which I've updated for current numbers:

Number of open issues on LESS: 121

  Number of open issues on Sass: 87

Pending pull requests on LESS: 13

  Pending pull requests on Sass: 8

Number of commits in the last month in LESS: 49

  Number of commits in the last month in Sass: 7

To note, these numbers were roughly flip-flopped as of Chris' writing in May, 2012. This says to me that they're both pretty equal with regards to development activity.

Maturity

Technically speaking, Sass is older. It came out in 2007, while LESS came out in 2009. That said, the comparisons I've seen put both of them at pretty much the same level of "maturity" in regards to features and whatnot.

Both also have frameworks that bring more tools to them. LESS has Less Framework, and Centage (additionally, the Twitter Bootstrap is built with LESS). Sass has Compass, Gravity, and Susy. Both probably have more, if you dig for them, but those are some of the first that come up when you search.

So are there any real differences?

When it comes to writing it, not really. If you use the CSS-like SCSS syntax in Sass (instead of the more Python-like SASS syntax), you have only the typical minor syntax differences (@ vs $), but for the most part, they're basically the same.

The two biggest differences in coding I found were a) how they handle units when doing math, and b) how they handled inheritance. When given something like 20px + 2em, LESS will drop the second unit and assume you mean the first (yeilding 22px), while Sass will throw an error (basically, type mismatch). With inheritance, LESS treats it like a mixin (I can't really explain it well, so see the inhertance section of this Tuts+ article for details).

Whether one is superior over the other kind of depends on how you'd prefer it to handle things.

The other biggest difference I know of is how and where each one compiles by default. Sass uses Ruby and compiles on the server, allowing you to store and send the compiled CSS file to the client. LESS, on the other hand, defaults to using the less.js script to compile the CSS on the fly. However, with the use of Node.js, LESS can compile on the server side in the same way that Sass does.

Which One?

So, if they're basically the same, which one should you use? Well, unless you really love the Python-like SASS syntax, or really think that client-side compilation is the way to go, or you greatly prefer one's inheritance calling over the other, it's going to matter more whether you prefer to have (or already have) Ruby or Node.js installed.


问:
Represent actions(verbs) in REST URI
I have a print operation to perform for my customer documents.
I need the other standard operations to be performed as well, like add,update, delete.
so, I have following:

For creating new customer:
URI = /customer/{id}, type = POST,
Methodname = CreateCustomer()

For updating:
URI: /customer/{id}, type = PUT, method =
UpdateCstomer()

For Delete customer:
URI = /customer/{id}, type =
DELETE, Methodname = DeleteCustomer()

For View:
URI: /customer/{id}, type = GET, method = GetCustomer()

Now, if I need to print a document for that customer, I need a print function.
My URI may look like this: /customer/{id}, type = POST , method = PrintCustomer().
But I have used that URI and POST type for CreateCustomer.
I wanted the URI to look like this:
/customer/Print/{id}, type = POST , method = PrintCustomer().

But I cannot have "Print" verb in my URI. Whats the best way to do this?
I thought about /customer/document/{id} as the URI... but I will run into the same issue.
I would have the CRUD operations on the "document". So, again I run out of what I would used for "print".
Please advise.

答:
POST doesn't mean "create", it means "process". You can create a new resource by posting a suitable request to an existing resource (i.e. post to /customers to create a new customer). But you can also use POST to fill in all of the other actions which don't correspond to a neat CRUD paradigm.

In the case of printing, you should consider the act of printing as a resource itself. You're asking the system to create a "print job" for you. This means you can have a prints/ resource which acts as the container for all prints requested. When you want to print something you POST a document to this resource which contains all the information about the print-out you want to create, identifying the resources you want to print with links to them.

As a JSON document, it could look like this:

```<code>{
   contents: ["http://site/customers/12345"],
   paper-size: "A4",
   duplex: "true"
}
</code>```

Obviously, you need to customise this to be relevant to what you want to do. The key thing is that you're identifying other resources to print by specifying their URL.

In response to the request, you could simply return a 200 OK or a 204 No-Content and treat it as a fire-and-forget process. However, if you wanted to enhance it, you could return 201 Created and specify the URL of the newly created print job, e.g. /prints/12345.

A user could then perform a GET on the resource to see the status of their print job (pending, in-progress, etc), or could request the job be cancelled by issuing a DELETE.

Once you rephrase the problem in terms of resource, the RESTful design should come naturally and give you opportunity to expand and enhance in ways you may not have immediately considered.

Title: Represent actions(verbs) in REST URI

Body:
POST doesn't mean "create", it means "process". You can create a new resource by posting a suitable request to an existing resource (i.e. post to /customers to create a new customer). But you can also use POST to fill in all of the other actions which don't correspond to a neat CRUD paradigm.

In the case of printing, you should consider the act of printing as a resource itself. You're asking the system to create a "print job" for you. This means you can have a prints/ resource which acts as the container for all prints requested. When you want to print something you POST a document to this resource which contains all the information about the print-out you want to create, identifying the resources you want to print with links to them.

As a JSON document, it could look like this:

{
   contents: ["http://site/customers/12345"],
   paper-size: "A4",
   duplex: "true"
}

Obviously, you need to customise this to be relevant to what you want to do. The key thing is that you're identifying other resources to print by specifying their URL.

In response to the request, you could simply return a 200 OK or a 204 No-Content and treat it as a fire-and-forget process. However, if you wanted to enhance it, you could return 201 Created and specify the URL of the newly created print job, e.g. /prints/12345.

A user could then perform a GET on the resource to see the status of their print job (pending, in-progress, etc), or could request the job be cancelled by issuing a DELETE.

Once you rephrase the problem in terms of resource, the RESTful design should come naturally and give you opportunity to expand and enhance in ways you may not have immediately considered.


答:
A degree isn't needed for any programming job but it certainly helps get you through the door.

I'm guessing that there may be ways to work your way up within a company or ways to get a role based on stuff you've done in your spare time but I'd imagine that 95% of people in IT in all areas have degrees.  Maybe not Comp Sci degrees (I don't - mine is electronic engineering and I've worked with historians who were good coders), but degrees in something.

But if for one reason or another you don't want to or can't go to university there will be alternatives, you just need to work out what they are.

Title: Is a degree needed for low-level/embedded programming jobs?

Body: I know that it is possible to get into software development without a degree in computer science, but is it possible (or rather, common) to be able to get an embedded programming job without the computer science degree (or any engineering degree as well)?</p>


答:
Recursion implies action.

Examples:

a function that calls itself

a regex performing a * or + (ie repetitive) match

Technically, recursion should have an exit state but it's not a requirement.

Self-reference implies structure.

Ex. An instance method referencing the object it's attached to.

Title: What is the difference between "recursion" and "self-reference"?

Body: The wikipedia articles are too advanced for me to understand, could someone give me a simple explanation please?</p>


问:
is this javascript property defaulting pattern a code smell?
In some javascript code I'm working on refactoring I've handled cases where I wanted to default an object property to true without having to go through the code-base and add the property to every instance of the object by doing something like this:

```<code>if(typeof(thisBool) === 'undefined' || thisBool) {
    //do cool stuff here;
}
</code>```

so for existing instances I only had to fix up the model in cases where I wanted to set thisBool to some value calculated somewhere else, or to set it to false; if it was unset then this code treated it as true.

The objects are built dynamically when used - they're not defined classes, but are "instantiated" something like this:

```<code>var thing1 = {
    Name: 'thing No 1',
    HasCat: false,
    [thisBool: true]
};
</code>```

and thing1 is passed into the function

Is this a terrible idea? I'm updating that code (and all of the instances) so now is the time to fix this, if it's a code smell.

For my own part I would rather be more explicit, but I also see the value in not having to supply a thisBool: true in hundreds of places, where by default thisBool should be true. Is there a better way to achieve this?

答:
Assuming this is a function argument there is no need to use typeof as the variable will always exist. The easiest and cleanest way to make it default to true is this:

```<code>if(thisBool === undefined || thisBool)
</code>```

Of course that could be done a bit more explicit:

```<code>if(thisBool === undefined) {
    thisBool = true;
}

if(thisBool) { ... }
</code>```

Body:
Assuming this is a function argument there is no need to use typeof as the variable will always exist. The easiest and cleanest way to make it default to true is this:

if(thisBool === undefined || thisBool)

Of course that could be done a bit more explicit:

if(thisBool === undefined) {
    thisBool = true;
}

if(thisBool) { ... }


问:
Developing with confidence without a real development environment
I've recently been hired for a project that involves working with and around several third-party "enterprise" systems. Due to what I imagine would be the astronomical cost and effort required to build a sufficiently faithful replica of the production environment, the prospect of having a real development environment seems vanishingly slim.

This is of course not ideal. On the bright side, I imagine there must be people out there safely testing and deploying software into unreplicable environments like this, and I can probably follow in their footsteps.

How those who effectively deal with these kinds of situations do it?

答:
Our system works with a number of large external systems. We combine the following approaches when testing them if we do not have a complete end-to-end setup:

Record-replay real data. Record real data (requests/responses from real external systems), parametrize it if necessary and replay

Build or buy a simulator that acts as an external system

DSL for test-data generation. For data-driven systems, write high-level DSL for generating test data.


问:
Streaming data from a microcontroller to a server?
Edit *We have a heart monitor hooked up to to an msp430 with a roving networks wifi module. I would like to connect send some type of a datastream to a webserver so that someone could watch it offsite. I would like to have a datastreaming connection or something to the webserver because I was thinking it is more natural than trying to do a post request every .5 seconds. (I know this isn't super specific but this is the level I am at right now.)

I'm trying to figure out how to stream data (not video or anything big) from a microcontroller to a webserver and forward it to an iOS app. My buddy has a wifi module for our MCU and he claims we just write UART and the wifi module broadcasts our UART signal. So I want to stream that data to a webserver (php). Is there any type of wifi protocol for sending a stream of data to the server?
What is the protocol for establishing a datastream connection on the MCU end?
What kind of server side code do I need to recieve the datastream?

答:
Since you're sending data to a web server, the easiest protocol to use would be an HTTP POST.  Wifi modules send Ethernet packets.  You'd have to add IP, TCP, and HTTP layers on top of that.  The TCP/IP stack is often either provided for a microcontroller, or possibly built-in to the wifi module.  You would format a POST packet and send it to the TCP stack.  Here's a slightly modified example POST request from this page:

```<code>POST /path/script.php HTTP/1.0
From: frog@jmarshall.com
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32

home=Cosby&favorite+flavor=flies
</code>```

You wrap that in a TCP header, then an IP header, then an Ethernet header, then write it to the UART, some or all of which you should be able to use existing libraries for.  The web server then processes it like a standard POST request from a web browser.  In PHP on the server side, the /path/script.php file would get executed and you would access the data with $_POST["home"] and $_POST["favorite flavor"].

The Roving Networks wifi modules have a built-in http client, which makes things a whole lot easier.  You set it up by sending $$$ to enter command mode, then send the following commands:

```<code>set ip proto 18 // Turn on HTTP mode = 0x10 and TCP mode = 0x2
set dns name www.webserver.com // Set the web server name
set ip host 0 // Turn on DNS
set ip remote 80 // Set the web server port, 80 is standard
set com remote GET$/userprog.php?DATA= // Sample server application
set uart mode 2 // Automatically connect using data trigger mode
exit // exit command mode
</code>```

When the serial UART data comes in, the module automatically connects to the web server, and sends:

```<code>GET /userprog.php?DATA= <users serial data> \n\n
</code>```

For more information, read the "Built-In HTML Client Modes" section of the manual.  There are other configurations that may fit your needs better.

Body:
Since you're sending data to a web server, the easiest protocol to use would be an HTTP POST.  Wifi modules send Ethernet packets.  You'd have to add IP, TCP, and HTTP layers on top of that.  The TCP/IP stack is often either provided for a microcontroller, or possibly built-in to the wifi module.  You would format a POST packet and send it to the TCP stack.  Here's a slightly modified example POST request from this page:

POST /path/script.php HTTP/1.0
From: frog@jmarshall.com
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32

home=Cosby&favorite+flavor=flies

You wrap that in a TCP header, then an IP header, then an Ethernet header, then write it to the UART, some or all of which you should be able to use existing libraries for.  The web server then processes it like a standard POST request from a web browser.  In PHP on the server side, the /path/script.php file would get executed and you would access the data with $_POST["home"] and $_POST["favorite flavor"].

The Roving Networks wifi modules have a built-in http client, which makes things a whole lot easier.  You set it up by sending $$$ to enter command mode, then send the following commands:

set ip proto 18 // Turn on HTTP mode = 0x10 and TCP mode = 0x2
set dns name www.webserver.com // Set the web server name
set ip host 0 // Turn on DNS
set ip remote 80 // Set the web server port, 80 is standard
set com remote GET$/userprog.php?DATA= // Sample server application
set uart mode 2 // Automatically connect using data trigger mode
exit // exit command mode

When the serial UART data comes in, the module automatically connects to the web server, and sends:

GET /userprog.php?DATA= <users serial data> \n\n

For more information, read the "Built-In HTML Client Modes" section of the manual.  There are other configurations that may fit your needs better.


问:
What are the advantages of expressing information in the simplest possible format?
I want to apologize in advance if my headline is not specific enough, but I think this is a general question, although I have a very concrete example:

In my team we maintain a test specification which we use every time we release software. The specification is written in Word and, as a consequence, we occasionally have compatibility problems, wrong formatting in some parts of the document and sometimes people use the heading levels incorrectly. Nothing major, but annoyances none the less. But essentially our specification consists of test cases which can be described simply as a headline with some numbered instructions.

I think we would be a lot happier with using a lightweight markup language (e.g. AsciiDoc or Markdown) since it would be sufficient to describe the content. We would have other concrete benefits (add it to git, use diff tools, easily convert to other formats, not needing Word).

This made me think - are there any advantages, in general terms, to expressing information in the simplest possible format?

答:
To separate data from implementation.

The more simple the data format, the more flexible its use becomes. The more complex the data format, the less flexible and more susceptible it's contained data will be to bit rot.

Take database data. While it's possible to transfer the data in it's native format, that data will not be understood by any other system and, in some cases, different versions of the same system.

On the opposite end of the spectrum is CSV. It's practically ubiquitous for storing and transferring data in plaintext but the disadvantage of using it for database backups is you lose the structural rules.

Structure is useful too and, in some cases could be represented as it's own data format. For example, SQL stores database structure, CSS stores layout and design structure, config files store implementation structure, XML schemas store XML format structure, all of which use plaintext as the universal medium.

While not new, it's becoming more common to see data formats and even platforms (ex MVC) fundamentally designed to separate data and implementation. The reason being, data in it's true form is timeless whereas implementations are in constant flux. It just makes sense to store data in a format that presents the lowest barrier of entry to use in current and future implementations.

Even formats like Markdown present implementation specific issues but their simplicity makes them much easier to adapt than a more complex format (ex Word). Especially considering that the Markdown format itself is designed with conversion (ie to HTML) in mind.


问:
Advice: Developing two projects where one is an extension of the other

The Two Projects

I work at a pretty small software company, and I'm currently in a situation where I'm at the end of development for "Project A", about to start development for "Project B". Project B is supposed to be an "extension" of Project A (both are primarily web apps).

In Project B, the plan is to not only add brand new features, but modify some of the existing things from Project A; for example, some of the web pages. The difficulty is that we still want to be able to distribute Project A, without any of the features from Project B, but with any "A"-related bug fixes that we end up doing while we work on "B".

Method 1: Branching

The way I'm thinking about it is that Project A is like the "stable" branch and Project B is like the "dev" branch, but "dev" never gets merged back into "stable". We have concerns with this approach because it seems like it will require a lot of discipline to make sure that bug-fix changes are always committed to the Project A branch and then merged up to the Project B branch (as opposed to fixes being implemented on the Project B branch and needing to manually copy them back into the Project A branch).

Method 2: Plugin Architecture

Alternatively, we could start turning things into sort of "plugins" wherever there needs to be a "difference" between Project A and B. This way also seems like it could turn into a tangled mess, since we don't yet know exactly what changes will be needed.

The Choice

Right now, I see it as a choice between the lesser of two evils (read 'difficulties'). Based on your experience, do you have any advice that will help with my choice? Are there any other ways to manage the split between the two projects that I might have overlooked?

答:
For your scenario Method 2 i.e Plugin based seems better solution. Its going to be pain to make code modular and extensible for first time but one you have successfully done it, and further development will be easier.

If you plan to go for Method 2, first of all you need to clearly state out purpose for both the apps and figure out common ground and how can entire thing be bifurcated into different modules. Be really clear on defining boundaries for you modules based on their purpose as if done properly can speed your development.


答:
Regardless of the used SCM, Branch-based method is faster in implementing, simpler in management and just better, especially if you'll follow "Branch per task" workflow

"Project A" is long-term branch

"Project B" is long-term branch also, created at some moment from "Project A"

Each task (feature or bugfix or ...) is separate short-term branch, which, after finishing, can be (have to be) merged into one or more targets

Title: Advice: Developing two projects where one is an extension of the other

Body:
The Two Projects

I work at a pretty small software company, and I'm currently in a situation where I'm at the end of development for "Project A", about to start development for "Project B". Project B is supposed to be an "extension" of Project A (both are primarily web apps).

In Project B, the plan is to not only add brand new features, but modify some of the existing things from Project A; for example, some of the web pages. The difficulty is that we still want to be able to distribute Project A, without any of the features from Project B, but with any "A"-related bug fixes that we end up doing while we work on "B".

Method 1: Branching

The way I'm thinking about it is that Project A is like the "stable" branch and Project B is like the "dev" branch, but "dev" never gets merged back into "stable". We have concerns with this approach because it seems like it will require a lot of discipline to make sure that bug-fix changes are always committed to the Project A branch and then merged up to the Project B branch (as opposed to fixes being implemented on the Project B branch and needing to manually copy them back into the Project A branch).

Method 2: Plugin Architecture

Alternatively, we could start turning things into sort of "plugins" wherever there needs to be a "difference" between Project A and B. This way also seems like it could turn into a tangled mess, since we don't yet know exactly what changes will be needed.

The Choice

Right now, I see it as a choice between the lesser of two evils (read 'difficulties'). Based on your experience, do you have any advice that will help with my choice? Are there any other ways to manage the split between the two projects that I might have overlooked?


问:
Should a database table(s) structure match its intended data structure(s) in the logic?
This question branches out of this question, What are the differences between algorithms using data structures and algorithms using databases?.

The General Question

Should a database table(s) structure match its intended data structure(s) in the logic?

Some Context

The simplest example (and it may be oversimplified) of what I am thinking about is a database table whose columns match the properties of a linked list data structure.  So the properties I think of for a linked list are the following:

Linked List

Node identity.

Item/Content in node.

Next node.

In regards to the general question, the database table columns that I think of getting mapped are the following:

Linked List > Database Table

Node Identity > Primary Key Column(s).

Item/Content in node > Column(s) containing data that is to be persisted.

Next node > Column containing a reference to the record that is to follow it in the same table.

An application I can think of that represents the above is to say, keep track of a trail of points you have been to on a map.  So I can imagine saving the coordinates of point A then putting in the mapped Next node column, the coordinates of point B.  Letting my imagination run a little further, then retrieve this data and load it into a linked list, use its properties to do the traversal, and draw these points on a map again at a later point in time.

Questions

I can see how creating a mapping like this simplifies thinking about the data, but I also feel it restricts you to thinking about the data in only this way.  How conforming do you make your database tables to data structure(s), if at all?

Should databases be viewed as realms of raw data that are to be shaped and molded (translated) to data structures selected dependent on the program's purpose?

I restate what I said in the last post.  I know answers without a specific context are difficult.  Food-for-thought, advice, or discussion points are mainly what I'm looking for and would be most appreciated!  I did try to give a more specific context in this post.

答:
Square Peg, Round Hole

I can see how creating a mapping like this simplifies thinking about the data, but I also feel it restricts you to thinking about the data in only this way. How conforming do you make your database tables to data structure(s), if at all?

I don't conform the database, at all. Assuming the benefits to be gained from a particular data structure in code can be mapped directly to the database is a failure to understand the strengths of databases.

It's a good idea to represent data in it's truest form, stripped of implementation because the implementation will most likely change over time.

The simple rule is,"separate data from implementation".

Should databases be viewed as realms of raw data that are to be shaped and molded (translated) to data structures selected dependent on the program's purpose?

Ask yourself this. Would you duplicate all of the functionality of a database in code (including indexing, primary keys, foreign keys, etc)? Of course not, because in the context of the program they don't add any value.

All you want is data matching the parameters you input.

It's best to model the structure of the database in the best possible manner for storage retrieval, and model the data structures in the application in the best manner for how they will be used in code.

You won't understand how to build an ideal database until you gain a firm understanding of what databases are designed to accomplish.

The point is, there is no 1-1 mapping from DB to any data structure. The database could be considered it's own type of higher level special purpose data structure based on a whole collection of lower level data structures.


答:
A branching strategy for versions would probably be best in a scenario like this. Sure, it requires discipline, but so do most aspects of software development.

Here is an example strategy to give you some ideas (despite the name...it is not really SCM specific, but does contain some helpful info for DVCS).

A plugin architecture would really only apply if plugins are part of the functionality of the application (something like the architecture of Drupal). They do have their place, but their place is not project versioning.