问:
What are the advantages of using LISP and Haskell? Will they make me a better programmer?
I know Lisp and Haskell are logic and functional programming languages respectively, but what exactly does this mean? How do they differ from other languages? I've heard that learning these will make you a better programmer and improve your logic. Is this true, and if I go learning Lisp or Haskell to a competent level will my programming improve and will I be better at handling any problem in any language? I just wanted to know to see if they are worth the effort of learning. Also are these languages useful in areas such as GUI and graphics or are they just useful for console applications?</p>

答:
It is very much like learning math will improve your analytic skills and learning latin/classic literature will improve your writing skills.

People who designed those languages have thought hard about what does writing a program means. And those languages are the results of those researches.

That said, learning Java will also make you a better programmer. And learning C. The real benefits comes from learning languages with different philosophy. Then you can have your own opinion about the way a program should be written.

Edit

I realize this answer is not so useful for people who have not yet learn haskell and/or lisp. Here are some examples to explain further what I mean

LISP

Lisp believes that syntax should be minimal, and that everything should be either a list or a primitive (Lisp stands for List Processing). Even programs are mainly list containing other lists and symbols. Lisp allows you to manipulate programs as list, and to generate new programs on the fly. Hence the whole code is data and data is code motto.

The direct consequence is that the Lisp languages allows you to define any interface you want. A nice exemple is compojure which is a clojure web framework. Here is what a routing function look like

```<code>(defroutes app-routes
  (GET "/" [] view/page)
  (GET "/api" [] (wrap-aleph-handler api/socket-handler))
  (route/resources "/static")
  (route/not-found "page not found"))
</code>```

Another nice exemple is the hiccup templating framework:

```<code>(html [:ul
  (for [x (range 1 4)]
    [:li x])])
</code>```

As you can see, the result is as terse as in DSL like mustache, but allows you to use the language features such as (for [x (range 1 4)] block). Even nicer, you have all the tools to abstract and structure your code.

In other languages, the syntax is more complex. You cannot read a Java program as a bunch of lists. But by using Lisp, you get a better idea about what an ideal interface should look like, and what in your code can be abstracted away as data. It also helps you to see your favorite language as a big data structure, and to better understand its semantics.

Haskell

Haskell believes in strong static typing and purity. Pure functions are like mathematical functions: they are defined on a set of values, and map them on another set. Function don't have side effects, and values are immutable. Purity is interesting because it is not something a multi-paradigm language can have. A language is either pure or not.

One consequence is that you cannot perform IO action whenever you want (haskellers believes that this is a good thing). IO actions are defined as transactions, which are themselves pure values. The main value of a haskell program is a IO transaction executed when you run the program.

You have to deal explicitly with the data flow in your program. You cannot make two component communicate by writing & reading stuff in a global variable. You have to build and pass values.

Another feature mentioned by Jimmy Hoffa is the rich type system. While other languages have static typing, in haskell you can have things like:

length :: [a] -> Int (function from a list of a's to an int)

map :: (a -> b) -> [a] -> [b] (function that takes a a to b transform and a list of a's, and returns a list of b's)

The nice thing is that I don't need to explain what those function actually do: you already understand their behavior. What's more, functions with those signatures cannot really anything but compute the length of a list and map a transformation over a list.

In other typed languages, class hierarchies combined with the mutability make dealing with those types a nightmare. You have to understand things like covariance and contravariance, which are impossible to get right from a language perspective (ie simple, powerful and safe).

Either you take the safe path (like scala) and end up with a really complex language, or you take the simple path and get something which is either limited (google go generics limited to list and maps) or unsafe (dart generics which are always covariant).

By using haskell, you mainly learn about the benefits of purity, and how to write pure code.

Body:
It is very much like learning math will improve your analytic skills and learning latin/classic literature will improve your writing skills.

People who designed those languages have thought hard about what does writing a program means. And those languages are the results of those researches.

That said, learning Java will also make you a better programmer. And learning C. The real benefits comes from learning languages with different philosophy. Then you can have your own opinion about the way a program should be written.

Edit

I realize this answer is not so useful for people who have not yet learn haskell and/or lisp. Here are some examples to explain further what I mean

LISP

Lisp believes that syntax should be minimal, and that everything should be either a list or a primitive (Lisp stands for List Processing). Even programs are mainly list containing other lists and symbols. Lisp allows you to manipulate programs as list, and to generate new programs on the fly. Hence the whole code is data and data is code motto.

The direct consequence is that the Lisp languages allows you to define any interface you want. A nice exemple is compojure which is a clojure web framework. Here is what a routing function look like

(defroutes app-routes
  (GET "/" [] view/page)
  (GET "/api" [] (wrap-aleph-handler api/socket-handler))
  (route/resources "/static")
  (route/not-found "page not found"))

Another nice exemple is the hiccup templating framework:

(html [:ul
  (for [x (range 1 4)]
    [:li x])])

As you can see, the result is as terse as in DSL like mustache, but allows you to use the language features such as (for [x (range 1 4)] block). Even nicer, you have all the tools to abstract and structure your code.

In other languages, the syntax is more complex. You cannot read a Java program as a bunch of lists. But by using Lisp, you get a better idea about what an ideal interface should look like, and what in your code can be abstracted away as data. It also helps you to see your favorite language as a big data structure, and to better understand its semantics.

Haskell

Haskell believes in strong static typing and purity. Pure functions are like mathematical functions: they are defined on a set of values, and map them on another set. Function don't have side effects, and values are immutable. Purity is interesting because it is not something a multi-paradigm language can have. A language is either pure or not.

One consequence is that you cannot perform IO action whenever you want (haskellers believes that this is a good thing). IO actions are defined as transactions, which are themselves pure values. The main value of a haskell program is a IO transaction executed when you run the program.

You have to deal explicitly with the data flow in your program. You cannot make two component communicate by writing & reading stuff in a global variable. You have to build and pass values.

Another feature mentioned by Jimmy Hoffa is the rich type system. While other languages have static typing, in haskell you can have things like:

length :: [a] -> Int (function from a list of a's to an int)

map :: (a -> b) -> [a] -> [b] (function that takes a a to b transform and a list of a's, and returns a list of b's)

The nice thing is that I don't need to explain what those function actually do: you already understand their behavior. What's more, functions with those signatures cannot really anything but compute the length of a list and map a transformation over a list.

In other typed languages, class hierarchies combined with the mutability make dealing with those types a nightmare. You have to understand things like covariance and contravariance, which are impossible to get right from a language perspective (ie simple, powerful and safe).

Either you take the safe path (like scala) and end up with a really complex language, or you take the simple path and get something which is either limited (google go generics limited to list and maps) or unsafe (dart generics which are always covariant).

By using haskell, you mainly learn about the benefits of purity, and how to write pure code.


问:
What are examples of automating BDD specifications through the UI layer?
I understand it is better to automate BDD specifications below the user interface whenever possible.

For example and quoting from Gojko Adzic's book: Specification by Example:

Don't check business logic through the user interface

My question is then: What are the specific use cases when using the UI layer does make sense in the context of BDD?

答:
My opinion is that BDD verification in the UI makes a lot of sense if the person writing the test isn't the person who wrote the application.  Or if you just want more thorough testing to prove that when a user goes to your application, it will actually work and you really want to know that a relative path to an ajax service is absolutely not broken (or similar things unit testing/BDD in the backend can never find).  This can make deployments a lot easier because you aren't sitting there wondering if hundreds of pages actually work after you push to the server.

You asked for a specific example, so here goes.

My old colleague made a web application called a "robot parts" store that is available on github

https://github.com/BobPalmer/RobotParts

It is tested in just about every way you could test an application.  He has some coded UI tests in there that are very BDD (although not using a BDD specific framework)

And he does test the back-end with BDD (specflow)

Looking through this application may be helpful for you to see where the lines are drawn between UI/backend and unit tests/BDD.

Here are a few tests where the UI is tested in a BDD manner

ContentLicense: CC BY-SA 3.0


答:
tl;dr Learning new stuff can only make you a better programmer, but being a better programmer is not about the languages you can write code in.

What are the advantages of using LISP and Haskell?

LISP:

Homoiconic code. This allows structured self-modifying code.

Syntax-aware macros. They allow rewriting of boilerplate code.

Pragmatism. CL is designed to get stuff done by working professionals. Most functional languages aren't, as a rule.

Flexibility. It can do a lot of different things, all at reasonable speeds.

Wartiness. The real world is messy. Pragmatic coding winds up having to either use or invent messy constructs. Common Lisp has
  sufficient wartiness that it can get stuff done.

Arguably the only real reasons to choose against CL is that the
  standard libraries are dated.

I will go out on a limb and say that in the general case, syntax
  should not be an issue to a professional software worker.

From: Why is Lisp useful?

Haskell:

Haskell is a computer programming language. In particular, it is a
  polymorphically statically typed, lazy, purely functional language,
  quite different from most other programming languages. The language is
  named for Haskell Brooks Curry, whose work in mathematical logic
  serves as a foundation for functional languages. Haskell is based on
  the lambda calculus, hence the lambda we use as a logo.

You can read there a description of Functional vs imperative

From: http://www.haskell.org/haskellwiki/Introduction

Will they make me a better programmer?

Yes, of course, knowing more languages and paradigms can only make you a better programmer, but get this straight:

There is not a single tool, a single book, a single programming paradigm that will make you a better programmer.

Learning different programming languages with different paradigms definitely help you to be a better programmer, learning to solve problems with different aproaches also benefit your logical thinking greatly.

Being a good programmer is not much about the language, but about having the ability to solve any problem in any language. And when you don't know the language, the ability to learn that language quickly and use it effectively.

I think, that the more global your thinking is, the better developer
  you are.

For example, you may add useful comments to your code, care about the
  readability of your code, the maintainability. Pay attention to the
  little details. Think before typing!. Learn about desing patterns.
  Follow good practices.

Disclosure: This is shameless advertising of the worst kind, because it is from my blog.

Title: What are the advantages of using LISP and Haskell? Will they make me a better programmer?

Body: I know Lisp and Haskell are logic and functional programming languages respectively, but what exactly does this mean? How do they differ from other languages? I've heard that learning these will make you a better programmer and improve your logic. Is this true, and if I go learning Lisp or Haskell to a competent level will my programming improve and will I be better at handling any problem in any language? I just wanted to know to see if they are worth the effort of learning. Also are these languages useful in areas such as GUI and graphics or are they just useful for console applications?</p>


问:
Greenfield vs. brownfield revenue? (attempting to get an idea of measure of effort expended on the two)
The big question I have in my mind: how many developers are brownfield ("enterprise") compared to greenfield (all new code, from the ground up).

I'm constantly reading breathless articles about the latest technology, only to find out that It Just Won't Work On Our Enterprise Software codebase.  People aren't ready for automated testing (because the logic is in the click-handlers and/or database).  People aren't ready for ORM tools because we have horrendous amount of logic in stored procs and triggers.  People aren't ready for WPF because our existing stuff is all WinForms.  We can't get the latest version of Reactive Extensions because existing code used RX 1.0 and there are breaking changes that will require more testing effort than is justified by the return.  Etc., etc., etc.

Very few articles seem to be oriented toward the brownfield developer, for whatever reason (can't sell ads for articles that start off with "you probably can't use this, but..."?).

So, I'm truly wondering:  is the software development industry just chock full of greenfield developers, developing new projects for clients which are then released and enjoy a short existence until complete replacement for whatever reason?  Or are there hordes of brownfield programmers silently laboring away in the ADO.NET T/SQL VB.NET software mines, looking wistfully up at the sunshine of Entity Framework 5.0 and Haskell, et cetera?

How do we even measure that?  Salaries (wages?) paid to software engineers* in the two categories?  How do we measure THAT?  Maybe... revenue generated from selling said software?  (There's an assumption that the crappy old software sold by XYZ Corp. actually has maintainers).

My question: Does anybody have any numbers that speaks to how much of the industry is green field vs. brown field?

答:
In terms of revenue, pure Green Field development is probably close to 0.0% of revenue generated from development.

Why?

Development is almost always building on earlier code, doing rewrites of part of a design, bringing out new and improved version 4.0 etc... I can think of very few commercial situations where a new product is designed completely in isolation and then generates substantial revenue.

Even in start-ups, by the time the product is actually being used by paying customers, it probably been in development for so many months that it doesn't feel like greenfield code any more.


问:
Ruby Sinatra best practices for project structure
Many people praise Sinatra's ability to create simple projects in a single file.  This is great and all but what if I want to use Sinatra for slightly larger project?

I'm fairly new to Ruby as a whole but have already found a couple ways to create a Sinatra application with separate models files, partitioning different groups or URLs into individual files, etc... But is there any best practice for this?

答:
The step to take is to partition the application into multiple parts at the file level. Instead of having all of the routes in one file, split them up into logically separated files with different functionality groups in different files, which are all then require'd back into the main Sinatra application/Rackup file.

Although this makes your file structure prettier, it does not implement any true compartmentalization or organization beyond superficial divisions. The solution to this that seems to have garnered the most popularity and acceptance is the Padrino framework, which runs on top of and expands upon the Sinatra core to add controllers (for compartmentalization) and a bunch of Django-like features (drop-in authentication, administration, etc.).

ContentLicense: CC BY-SA 2.5


问:
Is blocking an entire web-client due to compatibility a reasonable request?
A little bit of background, we've made an electronic POS system for registered vendors of items of a well known brand. The vendors are required to login to use the system.

Recently, IE has been giving us lots of painful maintenance problems than before. Our boss is getting worried about running into further maintenance problems, so he has asked me to find out a way to automatically install & launch chrome if they try to login with any other browsers (For the record, nearly all of the issues are related to some feature working fine on FF/Chrome/Opera/Safari but doesn't on IE).

Let us put aside the ridiculousness of running an external .exe from Javascript, which is practically impossible (And rightfully, I told him so. But he insisted it was possible, so whatever).

So my questions are:

Is this request technically viable? Is there a guaranteed way to block requests from all browsers except for allowed ones?

Is this request reasonable? IMO, From the standpoint of users, limiting accessibility does more harm than good, but maintenance issue is definitely a valid business concern.

Has there ever been a case like this where other websites explicitly blocked certain browsers?

Edit: Thanks for the answers. We're supporting IE 7+ at the moment and indeed, 7/8 were the ones that caused most of the grief. Just dropping those two will make maintenance significantly easier but my boss thinks the problem has to do with IE itself, not necessarily the versions. I'm going to try to see if I can convince him, but I have a strong feeling he's going to stick by what he thinks.

答:
Is this request technically viable?

No, not least because technical users will be able to spoof the requests - that said those users that are capable or walking round the limitations are more likely to be using a browser that doesn't cause you problems.

Is this request reasonable?

Maybe - but I refer to my earlier answer, the users that can easily change their browsers are unlikely to be the ones that are having problems.

Has there ever been a case like this where other websites explicitly blocked certain browsers?

Sadly yes, still persists and is very irritating (once it was genuinely about supported capabilities but from IE9 that's marginal). Call me peverse but I like IE - I've been using it since it was in beta (at which point it was refreshingly better than netscape) - but equally I use IE9/10/11 and here is where things get fun.

Firstly you need to be clear about what specific version of IE are causing you grief - and why. If its 6 and 7 then yes, you need to encourage your users to use something better because its not reasonable to have to support them. 9 or better - then there's a case to argue that the problems need to be resolved in your (by replacing browser sniffing with capability detection and appropriate polyfills) 8... 8 is the nasty edge case. IE 11 doesn't even report itself as IE any more to try and stop sites that have no reason not to work deciding that they don't want to play.

Hmm end rant.

The simple answer is to define versions of IE that you don't support and to explain why and to then express that clearly to your users - but you ought to support at least 9 or better...


问:
Design: multiple algorithms on the same large data sets
I have several algorithms that I would like to test against the same data sets to compare their results. I don't know how to design it so there is maximum readability and maximum efficiency.

I have considered creating a class for each algorithm, and giving it a copy of the data to work with, but it doesn't seem that that is the right answer:

Each data set is fairly large (10,000 float numpy array), so I don't want to copy each one ~30 times.

Many of the algorithms have similar pre-processing routines (thus repeating them for each algorithm seems wasteful)

Some algorithms have nearly identical code, except a few parameters which are different.

At the same time, having one function call per algorithm also seems wrong: as per (2), many will call the same preprocessing functions, and then it becomes very difficult to tell who is calling who.

I want to be able to allow the user (which will be me) to easily call a variety of algorithms on the data, while keeping the code as clear as possible.

I just keep thinking I need the inverse of a class; where each objects of a class will have the same methods but different data, I need something where each member will have the same data but different methods.

答:
Basically you want to create the large data once and cache it between invocations of your different algorithms.

For this to work, the data you want to share should not be altered by the algorithms you run.

How about a caching factory and some dependency injection?

```<code>class DataFactory(object):

  def __init__(self, ...):
    self._raw_data = None  # will be lazy-loaded and cached
    self._preprocessed_with_foo = None  # ditto
    self._preprocessed_with_bar = None  # ditto

  @propery
  def raw_data(self):
    if not self._raw_data:
      self._raw_data = loadDataSomehow(...)
    return self._raw_data

  @propery
  def foo_data(self):
    if not self._preprocessed_with_foo:
      self._preprocessed_with_foo = fooTransform(self.raw_data)
    return self._preprocessed_with_foo

  # etc

class Algo1(object):

  def __init__(self, data_factory):
    self.data_factory = data_factory

  def calculateOne(self):
    return someAlgorithm(self.data_factory.raw_data)

  def calculateFooOne(self):
    return anotherAlgorithm(self.data_factory.foo_data)

class Algo2(...): ...  # by the same pattern
</code>```

It works like this:

```<code>factory = DataFactory(...)  # nothing much happens

algo1 = Algo1(factory)  # dependency on factory is injected into algo1

print aglo1.calculateOne()  # factory loads raw data
print algo1.calculateFooOne() # factory reuses raw data, calculates foo data

algo2 = Algo2(factory)  # note: the same factory

print algo2.calculateTwo()  # assumedly reuses raw data
print algo2.calculateFooTwo()  # reuses both raw data and foo data
</code>```

Body:
Basically you want to create the large data once and cache it between invocations of your different algorithms.

For this to work, the data you want to share should not be altered by the algorithms you run.

How about a caching factory and some dependency injection?

class DataFactory(object):

  def __init__(self, ...):
    self._raw_data = None  # will be lazy-loaded and cached
    self._preprocessed_with_foo = None  # ditto
    self._preprocessed_with_bar = None  # ditto

  @propery
  def raw_data(self):
    if not self._raw_data:
      self._raw_data = loadDataSomehow(...)
    return self._raw_data

  @propery
  def foo_data(self):
    if not self._preprocessed_with_foo:
      self._preprocessed_with_foo = fooTransform(self.raw_data)
    return self._preprocessed_with_foo

  # etc

class Algo1(object):

  def __init__(self, data_factory):
    self.data_factory = data_factory

  def calculateOne(self):
    return someAlgorithm(self.data_factory.raw_data)

  def calculateFooOne(self):
    return anotherAlgorithm(self.data_factory.foo_data)

class Algo2(...): ...  # by the same pattern

It works like this:

factory = DataFactory(...)  # nothing much happens

algo1 = Algo1(factory)  # dependency on factory is injected into algo1

print aglo1.calculateOne()  # factory loads raw data
print algo1.calculateFooOne() # factory reuses raw data, calculates foo data

algo2 = Algo2(factory)  # note: the same factory

print algo2.calculateTwo()  # assumedly reuses raw data
print algo2.calculateFooTwo()  # reuses both raw data and foo data


答:
It is a well-known fact that most software development effort is spent maintaining existing software, not writing new software.

Why?  Because the first version of a program is only written once.  Every subsequent version builds on the original, and steady revenue comes from steadily maintaining, promoting and upgrading an existing product, not from constantly creating brand new inventions.

The life cycle of a software product can vary greatly.  Some software systems written for banking on mainframes have life cycles measured in decades, while other programs only have an effective life of a few years (or less).  For that reason, any attempt to quantify the relative percentage of effort on greenfield vs brownfield development would not be representative of the industry as a whole.

Title: Greenfield vs. brownfield revenue? (attempting to get an idea of measure of effort expended on the two)

Body:
The big question I have in my mind: how many developers are brownfield ("enterprise") compared to greenfield (all new code, from the ground up).

I'm constantly reading breathless articles about the latest technology, only to find out that It Just Won't Work On Our Enterprise Software codebase.  People aren't ready for automated testing (because the logic is in the click-handlers and/or database).  People aren't ready for ORM tools because we have horrendous amount of logic in stored procs and triggers.  People aren't ready for WPF because our existing stuff is all WinForms.  We can't get the latest version of Reactive Extensions because existing code used RX 1.0 and there are breaking changes that will require more testing effort than is justified by the return.  Etc., etc., etc.

Very few articles seem to be oriented toward the brownfield developer, for whatever reason (can't sell ads for articles that start off with "you probably can't use this, but..."?).

So, I'm truly wondering:  is the software development industry just chock full of greenfield developers, developing new projects for clients which are then released and enjoy a short existence until complete replacement for whatever reason?  Or are there hordes of brownfield programmers silently laboring away in the ADO.NET T/SQL VB.NET software mines, looking wistfully up at the sunshine of Entity Framework 5.0 and Haskell, et cetera?

How do we even measure that?  Salaries (wages?) paid to software engineers* in the two categories?  How do we measure THAT?  Maybe... revenue generated from selling said software?  (There's an assumption that the crappy old software sold by XYZ Corp. actually has maintainers).

My question: Does anybody have any numbers that speaks to how much of the industry is green field vs. brown field?


答:
While support ends in Jan. 2014, I'd still consider Google Chrome Frame to be the best solution to this problem. It's not "installing and launching Chrome", but its about as close as you can get while still being secure.

http://www.google.com/chromeframe

It basically runs Chrome inside of IE, doesn't need system administrator access, and can be triggered to install (via a prompt) on page load.

Another alternative would be to bundle your application in a single-site browser, using something like TideSDK or Node-Webkit.

Then you could make your POS work as a desktop app on some platforms, and limit the environments you spend time supporting.

Title: Is blocking an entire web-client due to compatibility a reasonable request?

Body:
A little bit of background, we've made an electronic POS system for registered vendors of items of a well known brand. The vendors are required to login to use the system.

Recently, IE has been giving us lots of painful maintenance problems than before. Our boss is getting worried about running into further maintenance problems, so he has asked me to find out a way to automatically install & launch chrome if they try to login with any other browsers (For the record, nearly all of the issues are related to some feature working fine on FF/Chrome/Opera/Safari but doesn't on IE).

Let us put aside the ridiculousness of running an external .exe from Javascript, which is practically impossible (And rightfully, I told him so. But he insisted it was possible, so whatever).

So my questions are:

Is this request technically viable? Is there a guaranteed way to block requests from all browsers except for allowed ones?

Is this request reasonable? IMO, From the standpoint of users, limiting accessibility does more harm than good, but maintenance issue is definitely a valid business concern.

Has there ever been a case like this where other websites explicitly blocked certain browsers?

Edit: Thanks for the answers. We're supporting IE 7+ at the moment and indeed, 7/8 were the ones that caused most of the grief. Just dropping those two will make maintenance significantly easier but my boss thinks the problem has to do with IE itself, not necessarily the versions. I'm going to try to see if I can convince him, but I have a strong feeling he's going to stick by what he thinks.


问:
How long is a typical modern microprocessor pipeline?
I learnt some about pipelining but those were 4-stage and 5-stage and I think that modern pipelining typical is much longer and more complicated in practice. How long are typical pipelines and how much can we expect them to increase and where is the point of reaching diminshing returns in performance gains for longer pipelines?</p>

答:
Regarding other modern processors:

ARM up to 7: 3 stages (still widely used is simpler devices)

ARM 8-9:  5 stages;

ARM 11: 8 stages;

Cortex A7: 8-10 stages;

Cortex A8: 13 stages;

Cortex A15: 15-25 stages.

From Wikipedia.


答:
Forcing an install is not possible.  You can block them & strongly recommend that they install a new browser but you can't force them to do anything - doing so would be a massive security hole waiting to happen.

More importantly, if you're writing business software, why the hell aren't you targeting IE?  Chrome & Firefox have great market penetration on consumer systems but business systems are still primarily IE and, in many cases, the user can't install a new browser even if they want to - they flat-out do not have permissions to do so.


问:
Parsing Text Tokens in Script Files
My team is wanting to migrate away from compiled code to dynamic code. We have a wide variety of customers and each has different business rules. Instead of having a single compiled code base, we are considering having different templated script files for each customer. However we have a lot of compiled code, so for now we are wanting to keep most of our current code and shell the script files like ruby my.rb or node my.js.

In addition, we need to get data into the scripts. So, we are thinking we will have variable declarations in the script, and those variables will be set to some character sequence that we will treat as a token. Then with another app, we'll process the document looking for the tokens replacing them with the actual data.

I have some concerns and am not sure what to think of all this, but I'm wondering if someone with more experience can shed some light on the quality of this solution and what some other alternatives might be.

EDIT:
I hope this helps explain my scenario.

Some of the motivation of this is our clients are not always accessible. In addition, we have services running on the client that would need to be stopped to install new versions of .dlls or .jars. Also, our clients get fragmented on versions of software despite attempts to keep them together. The thought is the script files will ship on demand with the other files and data to which that script is valid, and the compiled software will change less often.

答:
The problems you cite have nothing to do with complied code versus scripts.  It has more to do with software design.  If they think that multiple code bases will solve their problems, they and the organization would be better off if you let them go so they could find employment elsewhere and learn from a professional.  Your organization should hire at least one person who can mentor and understands issues.

It is hard for me to enumerate the reasons why this idea is so bad, it is kind of like explaining why 2+2 = 4.

If I were in charge, at your place I would work towards developing a design that is highly cohesive and loosely coupled.  There would be modules that were written such that they could be used by all customers.  There would be some modules that would be used by only some customers.  Some code would be only used by one customer.

These various parts could be assembled at compile time by some smart build/deployment scripts or by configuration files.

It is good to know that your senses are correct, however, it is a really crummy situation that you are in.  Frankly you have "heavy weights" that want to play Russian roulette with 6 bullets in the chamber.

And yes, I could come up with something better.  I have done so many times in my career.

Title: Parsing Text Tokens in Script Files


答:
When you learn languages that are outside of the paradigm that you usually operate, it will open your mind to alternative solutions in your day to day and may even help you understand some features in your language of choice better. Just knowing those languages aren't going to make you a better programmer unless you can take the lessons you learned from those languages and apply it to situations you see everyday.

That being said, it isn't limited to languages. When you read up on various data structures that you haven't seen or used before, it can help broaden the scope of you knowledge so the next time you encounter a problem you have one more possible solution.


问:
Modern web application development! Is flash and silverlight still relevant?
When building an application one considers the appropriate technology of choice for best long term impact and scalability. If building a media streaming application for mobile and desktop should one still use flash or silverlight, or html5 and javascript? How does one select the right technology?</p>

答:
You could ignore Flash and Silverlight entirely if your only concern was the long term. Both Microsoft and Adobe have expressed that their respective RIA technologies will enter maintenance mode and give way to HTML5/JS. </p>

<p>We never get to actually build applications purely for the long term; we have to make them work in the short term far more. The real question as to whether you should use HTML5 or one of the RIA providers is who your current audience is and what their restrictions are. If you can safely assume an up-to-date browser that provides the features you need, then HTML 5 is an excellent choice. Most of us write applications that at least need to work in corporate-land where browser updates run behind and Flash/Silverlight is disabled. </p>

Body:
You could ignore Flash and Silverlight entirely if your only concern was the long term. Both Microsoft and Adobe have expressed that their respective RIA technologies will enter maintenance mode and give way to HTML5/JS.

We never get to actually build applications purely for the long term; we have to make them work in the short term far more. The real question as to whether you should use HTML5 or one of the RIA providers is who your current audience is and what their restrictions are. If you can safely assume an up-to-date browser that provides the features you need, then HTML 5 is an excellent choice. Most of us write applications that at least need to work in corporate-land where browser updates run behind and Flash/Silverlight is disabled.


答:
Well the overall quality is, um, not good.

The things that seem most clearly wrong (since almost everything that is usually wrong has the odd case where it makes sense) are the idea of splitting into multiple code-bases and the idea of passing data into a script by putting in meta-tokens and then replacing those with data literals.

The multiple code-base issue is far more serious.  It will probably work great for a short time, then steadily turn into a disaster as issues common to multiple customers have to be solved by making the same change in multiple separate code-bases.  As they drift apart, the same logical change will more often become a different code change, so it will no longer be a tedious cut and paste, but more and more like writing the code multiple times - with attendant opportunities for multiple bugs.  You may well end up having to put the code back into a single code-base, which will be far harder than it was to split them.  At that point, more likely you won't, which will be worse.

If somehow you change code so infrequently that you never reach the point where this approach has more cost than benefit then I guess it could make sense.  It's a bit hard to imagine a plausible scenario where it's a good idea though - perhaps if the code really is pretty close to unique for each customer and the rest of the code is shared among all the customers.

Having a lot of special behavior on a customer by customer basis is very common.  The usual solution is to factor out as much common behavior as you can (this is where engineering skill comes in, but even bad engineering will probably beat the separate code-base design).  If all else fails you can break up the customer specific behavior into logical pieces, and have a configuration flag for each piece, rather than testing the customer ID in the code (i.e., use feature detection, not browser sniffing).  Then when a new customer wants some of those features you don't have to dig through the code to pull out features.

As far as idea of compiling values into common scripts - it's strange and seems harder than it needs to be for no real benefit, but even at worst it won't ruin your life.  Generally passing variables via command line arguments, or putting them in a configuration file (possibly a configuration database) is how people would do this.

As far as the issue of stopping a service - interpreted code may help, but have you thought about what happens if files are swapped out while a process is running?  If file Q has dependencies on N, O, and P, and while Q is executing an update swaps in new versions of N, O, and P, will your code work properly?  Will you QA this?  How do you plan to do that?  If incorrect program behavior isn't a big issue this may be acceptable, but if incorrectness has serious consequences you may well end up implementing the equivalent of taking down a service running compiled code.  Which kills your original motivation for using interpreted code in the first place.

Edit - I feel I should mention that multiple code-bases are acceptable in some sense - loosely coupled modules working together to make an application where each module could do something useful even in isolation is quite O.K.  Copying the same code among multiple code-bases then letting them evolve individually is very rarely a good idea.

Title: Parsing Text Tokens in Script Files

Body:
My team is wanting to migrate away from compiled code to dynamic code. We have a wide variety of customers and each has different business rules. Instead of having a single compiled code base, we are considering having different templated script files for each customer. However we have a lot of compiled code, so for now we are wanting to keep most of our current code and shell the script files like ruby my.rb or node my.js.

In addition, we need to get data into the scripts. So, we are thinking we will have variable declarations in the script, and those variables will be set to some character sequence that we will treat as a token. Then with another app, we'll process the document looking for the tokens replacing them with the actual data.

I have some concerns and am not sure what to think of all this, but I'm wondering if someone with more experience can shed some light on the quality of this solution and what some other alternatives might be.

EDIT:
I hope this helps explain my scenario.

Some of the motivation of this is our clients are not always accessible. In addition, we have services running on the client that would need to be stopped to install new versions of .dlls or .jars. Also, our clients get fragmented on versions of software despite attempts to keep them together. The thought is the script files will ship on demand with the other files and data to which that script is valid, and the compiled software will change less often.


答:
Just to start off, one should never pre-optimize code; code which is easier to understand and more logical is preferable 98% of the time. But since you're bringing it up I suspect you are having problems with it.

Since you're doing a benchmark, you should have one:

```<code>class Benchmark(object):
    def __init__(self, data):
        self.data = data
    def __call__(self, algos):
        return (algo.test(self.data) for algo in algos)

benchmark = Benchmark(get_data())
benchmark([Algo1(), Algo2(), ..]
</code>```

However, I realize upon reading the question again that you would prefer to have something more interactive.

When it comes to the common code between algorithms, you should have proper inheritance to sort all of them out (It's normally bad practice to copy code at all, so work against that by pushing as much code as possible high up in the tree). For the "some algorithms" being identical with changed parameters, one could inject via the constructor like this:

```<code>[Algo1(n_states=16), Algo1(n_states=8), Algo2(), ..]
</code>```

If you want to make a new class out of it you could do

```<code>from functools import partial
Algo1a = partial(Algo1, n_states=16)
</code>```

It's hard to give tips on the problem with common code without more knowledge on your particular algorithms.

For the particular problem where the preprocessing is common for almost all algorithms, I still don't have a straight answer: it depends a bit on your code. But each class should have the responsibility to choose how to do the preprocessing (Single responsibility principle), although a DataFactory is effective.

I wouldn’t ruin a logical code to gain speed by not recomputing the preprocessing, but then again I don't know your particular problem.

Title: Design: multiple algorithms on the same large data sets

Body:
I have several algorithms that I would like to test against the same data sets to compare their results. I don't know how to design it so there is maximum readability and maximum efficiency.

I have considered creating a class for each algorithm, and giving it a copy of the data to work with, but it doesn't seem that that is the right answer:

Each data set is fairly large (10,000 float numpy array), so I don't want to copy each one ~30 times.

Many of the algorithms have similar pre-processing routines (thus repeating them for each algorithm seems wasteful)

Some algorithms have nearly identical code, except a few parameters which are different.

At the same time, having one function call per algorithm also seems wrong: as per (2), many will call the same preprocessing functions, and then it becomes very difficult to tell who is calling who.

I want to be able to allow the user (which will be me) to easily call a variety of algorithms on the data, while keeping the code as clear as possible.

I just keep thinking I need the inverse of a class; where each objects of a class will have the same methods but different data, I need something where each member will have the same data but different methods.

Body:
Just to start off, one should never pre-optimize code; code which is easier to understand and more logical is preferable 98% of the time. But since you're bringing it up I suspect you are having problems with it.

Since you're doing a benchmark, you should have one:

class Benchmark(object):
    def __init__(self, data):
        self.data = data
    def __call__(self, algos):
        return (algo.test(self.data) for algo in algos)

benchmark = Benchmark(get_data())
benchmark([Algo1(), Algo2(), ..]

However, I realize upon reading the question again that you would prefer to have something more interactive.

When it comes to the common code between algorithms, you should have proper inheritance to sort all of them out (It's normally bad practice to copy code at all, so work against that by pushing as much code as possible high up in the tree). For the "some algorithms" being identical with changed parameters, one could inject via the constructor like this:

[Algo1(n_states=16), Algo1(n_states=8), Algo2(), ..]

If you want to make a new class out of it you could do

from functools import partial
Algo1a = partial(Algo1, n_states=16)

It's hard to give tips on the problem with common code without more knowledge on your particular algorithms.

For the particular problem where the preprocessing is common for almost all algorithms, I still don't have a straight answer: it depends a bit on your code. But each class should have the responsibility to choose how to do the preprocessing (Single responsibility principle), although a DataFactory is effective.

I wouldn’t ruin a logical code to gain speed by not recomputing the preprocessing, but then again I don't know your particular problem.


答:
I've been through this recently, and the decision path was fairly straightforward:

Q1: Do the rights-holders of the media you will be streaming demand that you use DRM?

If yes, you must choose your DRM provider, by a mix of technical consideration, pricing, and negotiation with your content providers. This will then force you to use Flash or HTML5 DRM on the desktop, and a native application on iOS. You are unlikely to cover all target browsers with a single technology.

(This answer was originally submitted in 2013 when Silverlight was a feasible option for DRM. Silverlight plugin support has been removed from Chrome, and HTML5 DRM is now widely available.)

Q2: If no to Q1, do you need to support low-latency streaming for specialised applications such as auctions or gaming?

If yes, you'll probably need a custom browser plugin.

Q3: If no to Q2, do you need to support older desktop browsers?

If yes, you will need to provide a Flash fallback.

Q4: Congratulations. You should use HTML5.

Title: Modern web application development! Is flash and silverlight still relevant?

Body: When building an application one considers the appropriate technology of choice for best long term impact and scalability. If building a media streaming application for mobile and desktop should one still use flash or silverlight, or html5 and javascript? How does one select the right technology?</p>


问:
May non-GPL-compatible scripts be linked at runtime to a GPLv3 library, by that (GPL) library itself?
First of all, pardon the title, as it's not very clear. I have an application I am writing that is GPLv3, and is in Java, which means that classfiles are generated and linked to for general operation. I am also using a scripting engine which, for performance, links any scripts it runs to my program's scripting libraries(which are class files) at runtime.

Given that a script must be linked at runtime, can a GPLv3-incompatible script be run on the application? Can I legally force the script to be interpreted instead? Just to clarify I'm trying to involve the GPLv3 in restricting non-GPL-compatible licenses to scripts.

The question is whether a technical linking operation functionally equivalent(except in performance) to parsing is actually linking in the legal sense.

Clarification: Scripts will be transmitted to interacting instances of the application. Scripts are loaded from a textual representation in ECMAScript/JavaScript, tokenized and parsed for syntax and then linked. This is what is confusing me. Given the conveyance, is the script being compiled and linked? Or interpreted and the parser actually runtime linking itself?

答:
In general, GPL'd and proprietary (non-GPL'd, closed-source) code can only be used together when they can be reasonably considered to be separate applications.  In practice, what this means is that:

The two applications must communicate at arms length with each other and

Each application must be capable of running without the other.

So if I write a program that processes a Word document in some way, I don't bind Word to the GPL because I still meet the above two requirements.  Similarly, if I write a Unix-style test-processing program that you can put in a stdin stout pipe, I can make it GPL without binding any other text processing programs, but still use it in the pipe.

However, if I write a proprietary program that statically links to a GPL'd library, I'm probably not in compliance because my program does not communicate at arms length with the library.  If I communicate with the library at arms length (say, with a text-based command interface or maybe dynamic linking), I could still be in violation if my program will not work without the GPL library.

Further Reading

http://www.gnu.org/licenses/old-licenses/gpl-2.0-faq.html#TOCGPLInProprietarySystem

https://stackoverflow.com/a/1394867

Is running an executable as a child process the same as linking a library?

When does independently developed software have to be licensed under the GPL?


问:
How to elegantly work with a lot of print functions?
I'm working on a Python project that is executed on a terminal (or console) for which I am planning to implement a GUI.

I did not major in CS so I really have no idea how to effectively design a terminal GUI such that:

the user interface looks good

in GUI, it is directed to a certain widget, let's say, a text label, or a bottom bar, or a hide-able frame.

Do you have any suggestions?

Currently, I am using the print function to provide essential information on STDOUT during execution, so a lot of print calls are distributed here and there in the code.

I'm thinking of using macro-like variables such as 'FILE_NOT_EXISTS_MESSAGE' for printing, and all of them and their values would be defined in one file.

Is that a standard way to do this?

Should I introduce a logging system?

In summary, I'm looking for a pattern for handling console output that is effective and adaptable.

答:
I think it depends on how reusable you want your code to be. At its simplest you could just replace all of the print statements you have with a function of your own that works out what to do. You could implement a logging system with different log levels, but I'm sure there already is one.

One of the useful things about wrapping print is that you can also turn certain messages off if you want to.

Not sure if this matters to you but the semantics of print differ between the newest Python and what we had before, so writing your own wrapper could make the transition much easier.


问:
Should I fork for a major re-write that uses a small amount of the original code?
I'm writing a library. It's a completely rewritten version of another one, to suit my needs (PCL compatibility, mainly). However, the API will be completely rewritten, as I'll need to change a lot of stuff around for PCL compliance. Also, as it is a rewrite, I won't be able to just start from the library and just change it bit by bit, as I typically see with forks. I tried that, but it just didn't work.

So what should I do? Should I fork here or should I make a new library?

答:
Do you have tests? If so, how tightly are they bound to the code rather than the behaviour? I'd work through the tests if they work at the behaviour level.

If you don't have tests then (please) write some and use that to drive out what you need. It sounds like a rewrite, so apart from reusing ideas it might be better to say that it's a "major release number" and therefore a new version altogether.


问:
Is Pair Programming also used to train less experienced developers and bring them up to speed?
I am familiar with Agile and Pair Programming (http://en.wikipedia.org/wiki/Pair_programming).  I thought Pair Programming was used if there was a complex requirement i.e. two sets of eyes is better than one.

Is Pair Programming also used to train less experienced developers and bring them up to speed?

Also, how often is it used e.g. all the time i.e. the two developers will work together at one screen permanently or perhaps one day per week? I have read an Agile book, which talks about this concept but it does not mention frequency of use.

答:
As with most things Agile, I feel the answer is "It Depends".

Is the less experienced person attempting to learn a new language (or other base skills) or do they already have the requisite skills and just need to learn a new application?  If they are attempting to learn a new language or skill, I would argue mentorship may be more appropriate.  If you are on-boarding someone new to the team who has the skills, then paired would be the way I go.

I agree with the point regarding not pairing a master with a new green developer, however I disagree that they should be the same skill level.  I think the key is pairing people who are close to the same skill level.

As far as frequency of use, I think your team members should be able to help you with that one.  Perhaps there is a story that is particularly tricky that the developers will want to pair on, other times there may be a story that is pretty straight forward that someone wants to do on their own to have time to decompress.

One final thought, when pairing, try to have the least experience person on the keyboard.  If the more experienced person drives, then there is a tendency for that person to write a whole bunch of code, with the explanation of "I will explain that in a minute, just hang on".  If the less experienced person is driving, then the conversation around what to do / how to move the code forward, tends to happen in a more timely manner.

Cheers!


问:
Do I need to learn Javascript to make decent websites?
Hello I have been using C++ and Java for years. For better or for worse, I have always looked at JavaScript as not as powerful as these languages and therefore probably not worth my time and effort to learn.

However, I have recently been more interested in web development. I have researched Rails, MySQL databases, Html5, etc. I have been working a lot with GWT. I like GWT, but I have read that people feel too constrained by Google and that you probably have to know JavaScript anyway for making anything worthwhile.

I don't have any specific kinds of websites in mind at the moment, just learning as much as I can. I really want to become proficient with setting up and querying databases, and using them to provide user generated content to a webpage.

My question is, can I get away with not learning JavaScript, or do I have to bite the bullet? I know I am being lazy, but there are just so many tools out there that it is hard to know which are worth learning sometimes.

I have also been researching languages like DART, but since it also compiles to JScript, and currently only Google implements it, I can't see a great reason to learn it.

Sorry my question is so long, and thank you.

答:
In a word, yes.

In more words: I think this question could be reworded to apply less specifically to your particular situation, however, broadly speaking I would say "yes", if doing web development without solid understanding of JavaScript you will probably be more ignorant of the "full picture" of what's going on in the browser than you should be.

JS is, for better or worse, the de facto language of the web browser, and via node.js is becoming increasingly popular on the backend, and is one way to introduce oneself to functional programming. It therefore seems reasonable to conclude, that although JS has "issues", there are enough reasons to develop a capability with it until something comes along to displace it.


问:
How to lock a script or web application to be used for the licenced user?
I built a web application using PHP. Now, I want to sell this web application online for customers but I want to guarantee that only one customer (only one website) use this. Is there a way to make the script under a license (which I provide)?</p>

答:
The simplest thing you could do is provide each user with a

```<code>$token = hash("WHIRLPOOL",$uniquely_identifying_string);
</code>```

and ask for that token before actually serving your app to anyone. Picture that as a proof-of-buying, and treat it like so (enabling users to renew their token, for instance, whenever they find it appropiate)

EDIT Oh sorry I understood you wanted to sell your application as a service (pretty much the only sane way to charge for a script-language-based application).

In case you want to actually try to ship this to other people and have them be the only enabled user, you would need to make sure that

Generate this token for every single download and have it inserted all throughout every module of your app in different, difficult to grep manners

Dial home at as many points in your code as possible, carrying your token to make sure from your own log analysis that all requests with that token come from a single domain

Require this token to provide app support

Leave other types of code signatures you can easily search for so that you can recognize pirated copies

Add logic bombs only exploitable with your private key (and make sure that remains true or noone will use your software due to soon-to-be-known exploits). This way you will be able to deactivate infringing websites.

And that would still not be 100% adequate.

You cannot realistically assume that your code will not be used ilegitimally anywhere as long as all the logic is sitting in cleartext in front of your client (and such is always the case in PHP, no matter how much you obfuscate things you´re only making the unencoding marginally more annoying for the cracker)

Body:
The simplest thing you could do is provide each user with a

$token = hash("WHIRLPOOL",$uniquely_identifying_string);

and ask for that token before actually serving your app to anyone. Picture that as a proof-of-buying, and treat it like so (enabling users to renew their token, for instance, whenever they find it appropiate)

EDIT Oh sorry I understood you wanted to sell your application as a service (pretty much the only sane way to charge for a script-language-based application).

In case you want to actually try to ship this to other people and have them be the only enabled user, you would need to make sure that

Generate this token for every single download and have it inserted all throughout every module of your app in different, difficult to grep manners

Dial home at as many points in your code as possible, carrying your token to make sure from your own log analysis that all requests with that token come from a single domain

Require this token to provide app support

Leave other types of code signatures you can easily search for so that you can recognize pirated copies

Add logic bombs only exploitable with your private key (and make sure that remains true or noone will use your software due to soon-to-be-known exploits). This way you will be able to deactivate infringing websites.

And that would still not be 100% adequate.

You cannot realistically assume that your code will not be used ilegitimally anywhere as long as all the logic is sitting in cleartext in front of your client (and such is always the case in PHP, no matter how much you obfuscate things you´re only making the unencoding marginally more annoying for the cracker)


问:
What is the most obscure sorting algorithm you know?
I just read about cyclesort via a sortvis.org blog post.
This is probably the most obscure one I have heard of so far, since it uses maths that I am not familiar with (detecting cycles in permutations of integer sets).

What is the most obscure one you know?

答:
Knuth Volume 31, in the answer to one of the exercises, gives an implementation of a nameless sorting algorithm that's basically an ancient code golf -- the shortest sort you can write in MIX assembly language. The short code does comes at the oh-so-minor price of O(N3) complexity though...

1At least in the older editions. Given the modifications to MIXAL for the new edition, I'm not sure whether it's still there, or even makes the minuscule bit of sense in did in the original MIXAL.


答:
We have a wide variety of customers and each has different business rules. Instead of having a single compiled code base, we are considering having different templated script files for each customer.

I'd say that the premise for this is kind of flawed.  You are after some sort of modular coding.  This can be done with other languages too.  Define the modules, create a Factory that serves the one you want and use that.  It is probably a lot simpler than trying to do multiple temptation of the source itself.

In addition, we need to get data into the scripts. So, we are thinking we will have variable declarations in the script, and those variables will be set to some character sequence that we will treat as a token. Then with another app, we'll process the document looking for the tokens replacing them with the actual data.

This is where things get ugly.

You've got some data in some file, and some preprocessor (lets pretend its gnu m4 - if you do find yourself following down this path you might as well use a good one - the associated SO tag m4) which reads the file, identifies the template macros and modifies the source, which is then deployed out to the customer.

So now you've got something like

```<code>site = "_SITE_"
print site, "\n"
</code>```

as some ruby code and then a macro file

```<code>define(`_SITE_',`programmers.SE')
</code>```

and then you run it through the m4 application

$ m4 main.m4 main.rb

site = "programmers.SE"

print site, "\n"

Now you start getting a lot of moving parts in there.  You've got to make sure that each file parses correctly, that some site didn't include something like a " which would be valid macro, but an invalid variable (will you catch that before it goes to the client site?).

Most of all, you had better hope that the code doesn't diverge.  Once you've got something more than just running a macro against the code, but replacing the code it gets ugly.  You've got to be very strict with naming conventions so that the values used in one part of the templates class don't collide with the other ones... and that you don't even use the values from one part of the template in another one (you pull just that part of the template in without the template part that sets up the data).  It just gets UGLY.

Worst of all, and the thing that will burn you in the end with this, you cannot unit test the code you write.  You can test the code that is generated (will you?  really?), but you won't be able to actually test the code you write is doing what it should.

The fundamental flaw in this thought is mixing the data and the code.  Essentially, the code you are writing in this model is data for a macro processor that spits out new code.

If you want template variables, read those out of a property file of some sort.

Store the data as data and load it as data.  For example store it out in a JSON object and load it in to an object with the appropriate library (ruby python).

Then you're just deploying the different data to the different sites (with all the same code base) that indicate the values that are different between them.  You will use the values in the data to call the proper factory method (that works fine on its own without any templates and can be unit tested).

Title: Parsing Text Tokens in Script Files

Body:
We have a wide variety of customers and each has different business rules. Instead of having a single compiled code base, we are considering having different templated script files for each customer.

I'd say that the premise for this is kind of flawed.  You are after some sort of modular coding.  This can be done with other languages too.  Define the modules, create a Factory that serves the one you want and use that.  It is probably a lot simpler than trying to do multiple temptation of the source itself.

In addition, we need to get data into the scripts. So, we are thinking we will have variable declarations in the script, and those variables will be set to some character sequence that we will treat as a token. Then with another app, we'll process the document looking for the tokens replacing them with the actual data.

This is where things get ugly.

You've got some data in some file, and some preprocessor (lets pretend its gnu m4 - if you do find yourself following down this path you might as well use a good one - the associated SO tag m4) which reads the file, identifies the template macros and modifies the source, which is then deployed out to the customer.

So now you've got something like

site = "_SITE_"
print site, "\n"

as some ruby code and then a macro file

define(`_SITE_',`programmers.SE')

and then you run it through the m4 application

$ m4 main.m4 main.rb

site = "programmers.SE"

print site, "\n"

Now you start getting a lot of moving parts in there.  You've got to make sure that each file parses correctly, that some site didn't include something like a " which would be valid macro, but an invalid variable (will you catch that before it goes to the client site?).

Most of all, you had better hope that the code doesn't diverge.  Once you've got something more than just running a macro against the code, but replacing the code it gets ugly.  You've got to be very strict with naming conventions so that the values used in one part of the templates class don't collide with the other ones... and that you don't even use the values from one part of the template in another one (you pull just that part of the template in without the template part that sets up the data).  It just gets UGLY.

Worst of all, and the thing that will burn you in the end with this, you cannot unit test the code you write.  You can test the code that is generated (will you?  really?), but you won't be able to actually test the code you write is doing what it should.

The fundamental flaw in this thought is mixing the data and the code.  Essentially, the code you are writing in this model is data for a macro processor that spits out new code.

If you want template variables, read those out of a property file of some sort.

Store the data as data and load it as data.  For example store it out in a JSON object and load it in to an object with the appropriate library (ruby python).

Then you're just deploying the different data to the different sites (with all the same code base) that indicate the values that are different between them.  You will use the values in the data to call the proper factory method (that works fine on its own without any templates and can be unit tested).


问:
My client's QA folks are shafting me. What can I do?
Backstory:

  As the single developer with experience in the chosen technology, a month ago I drafted a component that for all extents and purposes worked within acceptable levels according to the demos that were had.

Four weeks and assorted developers later (that´d be more or less last Thursday), the feature entered QA and since then I´ve been given 8 showstopper bugs, around 25 critical ones, 47 majors and a single minor one.

I´m beginning to harbor a grudge against this people, but then, they're making their best to actually improve the quality of the product, so I really shouldn´t. At the same time, I also think I have a right to sleep/eat without having nightmares of showstoppers appearing on my inbox.

What´s a polite way of handling this situation? I´ve gotten most of the former developers on board with this, but the QA folk continue to report all their bugs to me and upper management keeps asking me what I´m doing about them, so I´m growing considerably more anxious each day that passes by.

More details:  About one in thirteen bug reports are actually addressable by me (about one in three of those is actually caused by code I wrote), the rest of them lay in code that is honestly foreign to me at all. Yet I´m the one getting the reports and being ad-hoc in charge of distributing them to the right developers.  I´m not the team lead.
Judging by the amount of work I´ve been given someone seems to think I´m actually a team of people under my name. All jokes aside, the actual team lead is on extended leave without an explicit replacement, and the most senior dev in the project is actually spearheading another module for the project, and I´ve made it abundantly clear that I´ve had 0 involvement in the project for about four weeks already. The reason I´m posting this is because I´m running out of options for reals, not just imagining things.

答:
I think the problem is not that you're swamped with work, but actually a good process is missing.  For you to be able to sort this out, have a response mechanism/process for each kind of bug you have described.

For example, showstopper bugs are dealt with according to gravity of the situation (not as they arrive).  Critical bugs are of higher priority in fixing over major bugs.  Your QA folks should be able to properly tag and categorize the bugs and order them by need of fixing.

Also, it is worth considering, that you have a finite time at working on this.  You can reach to a bargain with your upper management that you may work overtime for showstoppers / critical bugs outside of your working hours for a possible extra overtime pay.  Otherwise, suggest that you need another hand for temporary bug fixing.


答:
There are two distinct cases that might fall under the category of "using the UI" that you mentioned above, and they have different cases when it would make sense to use them:

1: specifying something using the UI concepts, language or elements - specific use cases that would justify this would be important rendering logic (think about twitter's link display - eg if the entire link is less than 100 chars, display the link, else shorten it, or positioning elements on the screen depending on how many links an article has etc) or critical/highly risky user interface specific workflows (navigation, dynamic menus etc). "critical/highly risky" is the crucial thing here, because it's very easy to think about the UI and one of the biggest problems new teams typically have with BDD style specs is to overdo them from the UI, describing stuff that's not that important long term

2: just automating tests through the UI while the spec is still talking about underlying functionality - eg the spec talks about free delivery, but the underlying test automation uses selenium to open a browser, load the web site, purchase books, go to checkout etc (similar to what I've described in the Three Layers pattern http://gojko.net/2010/04/13/how-to-implement-ui-testing-without-shooting-yourself-in-the-foot-2/). Specific use cases that justify this are where the system is designed in such a way that the risk is spread across the user interface, and testing below the UI would not provide enough confidence to stakeholders. This is mostly a legacy system design issue, and I've used this approach when retrofitting BDD-style tests to a legacy system before an important change, or when extending a legacy system that contains a lot of risk or important logic in the user interface layer. If you have to do this on a new system, that's typically a sign of risk not being localised and might point to problems with the system design.

Outside the scope of BDD, but related to tools that people often use for BDD, writing tests (not specs in the spec-by-example sense, but just automating regression tests) through the user interface also makes sense in the cases where the risk is spread across the different layers, so excluding the UI from the test would not provide enough confidence, or when you want to automate a small number of selected face-saving tests that additionally de-risk critical workflows throughout all components. As an example, a major media company had roughly 10 such tests for their primary web site. These tests were automated using cucumber, because that is what developers could maintain easily, and they were very flaky - almost any UI change broke them, but because there was just 10 of them the maintenance costs weren't that high. Those tests were described in UI terms and they executed through the UI to ensure the widest possible coverage. They were used by developers as a quick check they had to do before saying that they are done with a piece of work, in addition to the technical unit tests and BDD-style .

As you mentioned, generally it makes a lot of sense to avoid coupling the user interface and business logic (not just for spec or testing purposes, but for maintainability as well - the UI tends to be the most volatile part of the system).

Title: What are examples of automating BDD specifications through the UI layer?

Body:
I understand it is better to automate BDD specifications below the user interface whenever possible.

For example and quoting from Gojko Adzic's book: Specification by Example:

Don't check business logic through the user interface

My question is then: What are the specific use cases when using the UI layer does make sense in the context of BDD?


答:
To some extent you can think of JavaScript as the "assembly language for the web". That is, it forms the foundation for most client-side web programming.

But like assembly language, you don't always need to code directly in JavaScript. You have several good options for languages that compile to JavaScript, e.g.

ClojureScript

CoffeeScript

DART

Java (e.g. via Vaadin / GWT)

Still, even if you use one of these languages, you'll need to understand some JavaScript in order to make use of the underlying JavaScript libraries. So my practical recommendation is to learn some JavaScript anyway - even if you move to one of the "higher level" languages, this knowledge will serve you well.

Title: Do I need to learn Javascript to make decent websites?

Body:
Hello I have been using C++ and Java for years. For better or for worse, I have always looked at JavaScript as not as powerful as these languages and therefore probably not worth my time and effort to learn.

However, I have recently been more interested in web development. I have researched Rails, MySQL databases, Html5, etc. I have been working a lot with GWT. I like GWT, but I have read that people feel too constrained by Google and that you probably have to know JavaScript anyway for making anything worthwhile.

I don't have any specific kinds of websites in mind at the moment, just learning as much as I can. I really want to become proficient with setting up and querying databases, and using them to provide user generated content to a webpage.

My question is, can I get away with not learning JavaScript, or do I have to bite the bullet? I know I am being lazy, but there are just so many tools out there that it is hard to know which are worth learning sometimes.

I have also been researching languages like DART, but since it also compiles to JScript, and currently only Google implements it, I can't see a great reason to learn it.

Sorry my question is so long, and thank you.


问:
Converting a DFA to an NFA
I have an assignment to convert various language descriptions into NFAs and DFAs.

Having graduated with my CompSci B.S. years ago and not touching the topic until my M.S. program, I am racking my brain on one of the questions. I can easily construct a DFA, but the answer must be an NFA that is not also a DFA.

I am not looking for the answer to my homework. I just need guidance on how to construct such a thing.

The question basically states "if a string contains pattern A, it must also contain pattern B" where the order of the two is irrelevant. λ is also acceptable.

My DFA has two branches. Branch 1 looks for pattern A, then does not accept until it encounters pattern B. Branch 2 looks for pattern B, then accepts anything.

I am not sure how to add nondeterministic behavior into this DFA to satisfy the requirements of the assignment. Googling it turns up debates about the complexity/memory tradeoffs of the two approaches, as well as theorems to prove it is possible. But no examples, and that is how I learn best.

答:
I believe you're having issues because your DFA does not actually solve the problem posed. It accepts AB or B, where the question asks for an automaton that matches AB, BA and ~A (not A).

Since you need both patterns A and B, you can do it like this:

From the initial state q0, our NFA can branch into either of three separate deterministic automata, DFA 1, DFA 2 and DFA 3 with an epsilon-transition.

DFA 1- try matching pattern A, then search for pattern B. If you can match B, accept.

DFA 2- search for pattern B, then search for pattern A. If you can match A, accept.

DFA 3 - search for pattern A, and do not accept if you match A. Accept if you don't match A.

From the initial state, non-deterministically choose between epsilon-transitioning to DFA 1 or DFA 2 or DFA 3.

The main thing about an NFA is that if any of its branches accepts the input, then the input is accepted by the NFA. So, if it matches AB in that order, we accept per branch 1. If it matches BA in that order, we also accept per branch 2. If it doesn't match A, we accept per branch 3.

Title: Converting a DFA to an NFA


问:
As a senior project manager, should I still keep learning new skill in programming?
If I'm a senior project manager, should I still keep learning new technology?

For example, every month every year, most language updates themselves, and a lot of new programming concepts become popular. Many new frameworks and patterns are created and make things easily.

But you have to spend a lot of time to keep up with. If there's language which is proved more efficient and you aren't familiar with it, will you plan to learn it and let team members take this language to develop the project?

If there's new framework, most people say that it's helpful to our project, but you know nothing about it, would you learn it and decide it?

But as a PM, you should be a senior level or maybe busier than before. Are you willing to learn something 'not so senior'??

答:
Let my try to answer this from the viewpoint of a developer (team) : There are two types of managers that can manage a developer team: technical and administrative managers.

The answer to your question is pretty clear for each of those individually: if you are only responsible for the administrative parts (resources, schedules, etc.), then do everyone a favor and stay out of technology. You're not going to be able to keep up anyways, but you will fall into the trap of talking to the developers on a tech-level on which they out-smart you easily. In other words: this undermines your own position and does no good to anyone.

On the other hand, if you are in a technical manager role, you are responsible for the technological roadmap of the company and as other comments pointed out, you damn better know what you're talking about in that case. Then again, you should not even need to ask that question, because your very job definition should include (at least indirectly) that you must have up to date technology knowledge.

Unfortunately, we live in that thing called "real world", where things aren't black and white.. err.. admininistrative and technological. I have encountered several managers, who had the bad luck of being responsible for both aspects. I say bad luck, because most of them tried to be good at both, but none succeeded.

Stepping only half-way into our tech world as a manager is dangerous, but as far as it gets towards an actual answer, I'd argue that you should not go deeper than the overview level. Do not make decisions based on your technical knowledge, unless you are a tech-manager and know that your knowledge is sound and complete. In all other cases, I wholeheartedly disagree with Mark Bernstein in that you will never ever know more about coding than your best developer. Heck, he spends all his working hours on that subject - and as we know from the best - a lot of his freetime as well. There is just no way on earth that you can possibly keep up with that amount of dedication - nor should you.

Get a grip on the major subjects, so that you can understand enough of the tech talk to understand the gist of a problem, but do not try - or pretend - to know all the ins and outs. The latter just leads to dangerous territory and in the view of developers voids your credibility as a manager faster than you can say 'oops'.


答:
Based on your comments, the real problem is that the project team has been redeployed prematurely and you don't have the resources to deal with all of the bugs that are being reported.

It is not the QA folks' fault.  They are just doing their job as they have been directed.  Don't blame them.  It appears that the fault lies with your management and their decision to pull resources from the project too soon1.  (Or maybe on the previous project lead who swept too many problems under the carpet in his haste to call the project "finished".)

1 - Or maybe it is management's fault for saying "it is done" to the client too soon, or for a signing a contract that allowed the client to raise fault reports against stuff they previously signed off.

What can you do?

Well,  I think you need to bring the problem to management's attention, and get them to get involved with solving the problem.  I would suggest that there are only two rational approaches:

Management needs to redirect resources back to the project.

Management needs to assist you to manage your workload by doing such things as:

negotiating with the client to reclassify and reprioritize the bug list,

pushing back on unrealistic client deadlines to get bugs fixed, and/or

negotiating with the client's QA folks to alter their quality goals.

Another answer suggests that you should get management to approve (paid) overtime.  I'm not sure that's a good idea.  IMO, you'd be better off if the pressure on you was relieved, one way or another.  (But if you do have to do overtime to deal with this mess, you should be paid for it!)

Title: My client's QA folks are shafting me. What can I do?

Body:
Backstory:

  As the single developer with experience in the chosen technology, a month ago I drafted a component that for all extents and purposes worked within acceptable levels according to the demos that were had.

Four weeks and assorted developers later (that´d be more or less last Thursday), the feature entered QA and since then I´ve been given 8 showstopper bugs, around 25 critical ones, 47 majors and a single minor one.

I´m beginning to harbor a grudge against this people, but then, they're making their best to actually improve the quality of the product, so I really shouldn´t. At the same time, I also think I have a right to sleep/eat without having nightmares of showstoppers appearing on my inbox.

What´s a polite way of handling this situation? I´ve gotten most of the former developers on board with this, but the QA folk continue to report all their bugs to me and upper management keeps asking me what I´m doing about them, so I´m growing considerably more anxious each day that passes by.

More details:  About one in thirteen bug reports are actually addressable by me (about one in three of those is actually caused by code I wrote), the rest of them lay in code that is honestly foreign to me at all. Yet I´m the one getting the reports and being ad-hoc in charge of distributing them to the right developers.  I´m not the team lead.
Judging by the amount of work I´ve been given someone seems to think I´m actually a team of people under my name. All jokes aside, the actual team lead is on extended leave without an explicit replacement, and the most senior dev in the project is actually spearheading another module for the project, and I´ve made it abundantly clear that I´ve had 0 involvement in the project for about four weeks already. The reason I´m posting this is because I´m running out of options for reals, not just imagining things.


问:
Greenfield vs. brownfield revenue? (attempting to get an idea of measure of effort expended on the two)
The big question I have in my mind: how many developers are brownfield ("enterprise") compared to greenfield (all new code, from the ground up).

I'm constantly reading breathless articles about the latest technology, only to find out that It Just Won't Work On Our Enterprise Software codebase.  People aren't ready for automated testing (because the logic is in the click-handlers and/or database).  People aren't ready for ORM tools because we have horrendous amount of logic in stored procs and triggers.  People aren't ready for WPF because our existing stuff is all WinForms.  We can't get the latest version of Reactive Extensions because existing code used RX 1.0 and there are breaking changes that will require more testing effort than is justified by the return.  Etc., etc., etc.

Very few articles seem to be oriented toward the brownfield developer, for whatever reason (can't sell ads for articles that start off with "you probably can't use this, but..."?).

So, I'm truly wondering:  is the software development industry just chock full of greenfield developers, developing new projects for clients which are then released and enjoy a short existence until complete replacement for whatever reason?  Or are there hordes of brownfield programmers silently laboring away in the ADO.NET T/SQL VB.NET software mines, looking wistfully up at the sunshine of Entity Framework 5.0 and Haskell, et cetera?

How do we even measure that?  Salaries (wages?) paid to software engineers* in the two categories?  How do we measure THAT?  Maybe... revenue generated from selling said software?  (There's an assumption that the crappy old software sold by XYZ Corp. actually has maintainers).

My question: Does anybody have any numbers that speaks to how much of the industry is green field vs. brown field?

答:
I think the crux of your problems is that most of the "new technologies" you mention are development tools or development methods.

So simply cannot apply a new development methodology to software that has already been developed.

I would also question whether some of these "new" technologies are better. In particular I have never seen the benefit or ORM frameworks. They turn an 1980s relational database technology back into a 1970s hierarchical database. And generate hundreds of lines of code whilst doing so.

Another point is that many/most of these "old" technologies are pretty good at what they do. Just ask yourself what would be the business benefit of replacing and existing working winforms application with a WPF based system that did the same thing.

Most of the value of a system is NOT in its technology but in the business rules and processes which it supports.


问:
Are there areas where TDD provides a high ROI and other areas where the ROI is so low that it is not worth following?
Test driven development. I get it, like it.

But writing tests does require overhead. So should TDD be used universally throughout the code base, or are there areas where TDD provides a high ROI and other areas where the ROI is so low that it is not worth following.

答:
I'd say avoid TDD in places where the code is likely to change structurally a lot.  Ie, it's great to have a pile of tests for a method whose signature changes rarely but gets refactored internally more frequently, but it sucks to have to fix your tests every time a highly volatile interface changes dramatically.

The apps I've been working on recently have been data-driven webapps built on a Gui->Presenter->BusinessLogic->Data Access Layer-based architecture.  My data access layer is tested like nobody's business.  The business logic layer is pretty well tested.  The Presenters are only tested in the more stable areas, and the GUI, which is changing hourly, has almost no tests.


问:
Object Oriented Programming Concepts and Interviews
I'm an Object Oriented Programming fanatic. I have always believed in modelling solutions in terms of objects. It is something that comes to me naturally. I work with a services start up that essentially works on application development using OOP languages. So I tend to test understanding of OOP in the candidate being interviewed.

To my shock, I found very very few developers who really understood OOP. Most candidates brainlessly spit out definitions they mugged up from some academic book on object oriented programming but they don't know squat about what they are saying. Needless to say I reject these candidates. However, over the course of time, I ended up rejecting almost 98% of the candidates. Now this gets me thinking if I'm being over critical about their OOP skills. I still believe OOP is fundamental and every programmer MUST GET it. Language knowledge and experience is secondary.

Do you think I'm being over critical or do I just get to interview bad programmers unfortunately?

EDIT:

I usually interview programmers with 2 to 5 years of experience. The position that I usually interview for is Ruby/Ruby on Rails application developer.

答:
OOP is merely one way of coding. There are many Multi Paradigm Programming Languages that does not necessary need OOP to work. In fact, you also need to see what nature of the job is. For example, System Analysts that do little programming can not know OOP, but do well in his/her job.

On the other hand, there's proof (read it somewhere, can't remember where - probably on Stack Overflow blog or Joel on Software) that there are many graduates or freshmen in the industry that hardly know OOP or good programming practices. These people are probably the black sheeps in your team who will code poorly, have bad documentation and poor understanding of the code.


答:
Yes you can ship your software with a license which disallows non permitted usage, but we know that out there are lots of people who copy and redistribute your software against the law and your license.

When adding some kind of domain and license verification to your application you have one problem - the php source code is open when you distribute it. So everyone can easily read and edit your source code and null the application in this way. Also the end of the story is redistributing the application...

But there is one way you could go.

ionCube Encoder encodes your PHP source code in unreadable fragments which can be only decoded and executed with an matching license key.

You can also use your own license scheme like an algorithmus which converts an user installed license token to the domain on which the application is allowed to execute. If the domain mismatches exit() the script execution.

But always keep in mind that there is no software and no license which protects your source code up to 100%. So write an application which is exciting, which is so good that your customer loves you and has no problem with giving you the money for good work ;-)

Title: How to lock a script or web application to be used for the licenced user?

Body: I built a web application using PHP. Now, I want to sell this web application online for customers but I want to guarantee that only one customer (only one website) use this. Is there a way to make the script under a license (which I provide)?</p>


问:
Design: multiple algorithms on the same large data sets
I have several algorithms that I would like to test against the same data sets to compare their results. I don't know how to design it so there is maximum readability and maximum efficiency.

I have considered creating a class for each algorithm, and giving it a copy of the data to work with, but it doesn't seem that that is the right answer:

Each data set is fairly large (10,000 float numpy array), so I don't want to copy each one ~30 times.

Many of the algorithms have similar pre-processing routines (thus repeating them for each algorithm seems wasteful)

Some algorithms have nearly identical code, except a few parameters which are different.

At the same time, having one function call per algorithm also seems wrong: as per (2), many will call the same preprocessing functions, and then it becomes very difficult to tell who is calling who.

I want to be able to allow the user (which will be me) to easily call a variety of algorithms on the data, while keeping the code as clear as possible.

I just keep thinking I need the inverse of a class; where each objects of a class will have the same methods but different data, I need something where each member will have the same data but different methods.

答:
you say you want to "test" different algorithms.
If you want to test them to pick the "best" one, I would keep one class per object. At first, some of the code will be duplicated, but at the same time, modifying one algorithm won't have any impact on the other algorithms, and separating them at the end will only be easier as well as adding new algorithms to your test.

If certain algorithm share the same pre processing by design, there's no reason you could not use inheritance for that family of algorithms and cache the result of that preprocessing. It would slightly flaw the comparison between this family of algorithms and other completely unrelated algorithms (memory consumption, CPU cost of caching...).

Now, I say "best" and I don't know what it means. If it's just a matter of performances, an array copy is probably going to be much cheaper than running the algorithm on the whole dataset. And that's something you probably won't have to do once you've selected your best one.

Also, you say you don't want to copy the dataset 30 times. If you don't modify it in your algorithm (which you should not), you don't have to copy it in the first place.


答:
```<code>> a = np.random.randn(10000)
> %timeit a.copy()
100000 loops, best of 3: 3.9 us per loop
</code>```

So copying that 30 times takes an imperceptible amount of time. While I would like more information about what these algorithms are (and heartily recommend %timeit, along with the rest of ipython), I doubt that the copies will be the largest of your concerns.

While it is tempting to share initialization blocks, you already say you have most of the meaningful code separated out already. I would suggest writing each algorithm as straightforwardly as possible, above almost any other consideration.

Body:
> a = np.random.randn(10000)
> %timeit a.copy()
100000 loops, best of 3: 3.9 us per loop

So copying that 30 times takes an imperceptible amount of time. While I would like more information about what these algorithms are (and heartily recommend %timeit, along with the rest of ipython), I doubt that the copies will be the largest of your concerns.

While it is tempting to share initialization blocks, you already say you have most of the meaningful code separated out already. I would suggest writing each algorithm as straightforwardly as possible, above almost any other consideration.