答:
Consider programming a solution for something you want a solution for, something that motivates you to dig into the problem and solve the software development issues and anything else that comes along. Think of something useful/practical for you or someone you know.

It does not have to be complex. And if an experienced programmer would be able to solve it in 15 minutes, who cares. You will learn to decide on programming language to use, set up a working environment for that language, start writing the code, testing, and possible making it usable for someone else.

If you have no experience with coding GUIs, unittesting, databases etc. Leave them out for now. Make a command-line version of your program. Use print statements for tracking what is going on to home in on where things go wrong.
Read your data from a plain text, so you can use an editor to create the input for the program.

If you know a bit about electronics: consider doing something with an Arduino. I recently implemented a remote control for a waterpump using SMS with that. I have been coding for 25+ years but it was fun and satisfying to have a program doing something concrete as responding to my phone commands. Fun is a great motivator to finish the project and make it a useful learning experience. Whether the project is simple or not does matter that much.

If you have never used a revision control system, no sweat: make copies of your project (source, data) to backup_00, backup_01 etc. So you can go back to something that worked, once you screwed up (you will).

For any element of software development there is always a better solution, even if you already improved it. Finding the balance on where to stop improving is a thing of experience. For now don't worry about improvements and efficiency, just try to get things done. You will learn to improve along the way.

If you know someone who can and is willing help you when you are stuck, ask them if they are willing to. It is a human evolutionary thing to feel satisfied as a human when you cooperate (and that nicely results in feedback on stackexchange website ). If you don't know anyone, see if there is a lively community online, where there are people that are willing to help.

In the end give some feedback on how things went for you. Here or anywhere you asked for help.

Title: Effective way to gain practical knowledge

Body:
I am currently nearing the end of my first year of my CS degree and have been disappointed with the lack of coding I have been asked to do (one unit).

I am basically looking for an effective way to gain practical knowledge but am unsure where to look for experience from a near beginner's perspective.


问:
I can write code... but can't design well. Any suggestions?
I feel that I am good at writing code in bits and pieces, but my designs really suck. The question is, how do I improve my designs - and in turn become a better designer?

I think schools and colleges do a good job of teaching people how to become good at mathematical problem solving, but let's admit the fact that most applications created at school are generally around 1000 - 2000 lines long, which means that it is mostly an academic exercise which doesn't reflect the complexity of real world software - on the order of a few hundred thousand to millions of lines of code.

This is where I believe that even projects like topcoder / project euler also won't be of much help, they might sharpen your mathematical problem solving ability - but you might become an academic programmer; someone who is more interested in the nice, clean stuff, who is utterly un-interested in the day to day mundane and hairy stuff that most application programmers deal with.

So my question is how do I improve my design skills? That is, the ability to design small/medium scale applications that will go into a few thousand of lines of code? How can I learn design skills that will help me build a better html editor kit, or some graphics program like gimp?

答:
Well, there's no golden apple for this kind of question, and I feel perhaps this is for every coder himself to find what's right for him. Here's my take, anyway.

You could read books on the subject. Great books. Fantastic books. But I find that these books only help you once you've tried to build and design an application - and failed.

For me, it's all about experience. When I started as a rookie I read books on how to design. I didn't understand much of the content back then. When I started working and had to design applications myself, I made very messy applications. They worked, but they were a pain to maintain. Then I read those books again - and this time I better understood them.

Now, I continue making new mistakes and learning from the old ones.

ContentLicense: CC BY-SA 3.0


答:
One principle that I find very important for good design is decomposition: if a class is too big (more than, say, 300-400 lines of code) break it up into smaller classes; if a method is too big (say, more than 50 lines of code) decompose it; if a project contains more than 50 classes, decompose it.

The key is to estimate the size of your system and construct several abstraction layers (e.g. subsystem, application, project, module, class, method) that allow you to decompose your code into understandable units with clear relationships between them and few dependencies.

Title: I can write code... but can't design well. Any suggestions?

Body:
I feel that I am good at writing code in bits and pieces, but my designs really suck. The question is, how do I improve my designs - and in turn become a better designer?

I think schools and colleges do a good job of teaching people how to become good at mathematical problem solving, but let's admit the fact that most applications created at school are generally around 1000 - 2000 lines long, which means that it is mostly an academic exercise which doesn't reflect the complexity of real world software - on the order of a few hundred thousand to millions of lines of code.

This is where I believe that even projects like topcoder / project euler also won't be of much help, they might sharpen your mathematical problem solving ability - but you might become an academic programmer; someone who is more interested in the nice, clean stuff, who is utterly un-interested in the day to day mundane and hairy stuff that most application programmers deal with.

So my question is how do I improve my design skills? That is, the ability to design small/medium scale applications that will go into a few thousand of lines of code? How can I learn design skills that will help me build a better html editor kit, or some graphics program like gimp?


答:
The only way to become really good at something is to try, fail spectacularly, try again, fail again a little less than before, and over time develop the experience to recognize what causes your failures so that you can manage potential failure situations later on. This is as true of learning to play a musical instrument, drive a car, or earn some serious PWN-age in your favourite first person shooter, as it is of learning any aspect of software development.

There are no real shortcuts, but there are things you can do to avoid having problems get out of hand while you are gaining experience.

Identify a good mentor. There is nothing better than being able to talk about your issues with someone who has already paid their dues. Guidance is a great way to help fast-track learning.

Read, read some more, practice what you've been reading, and repeat for the entire lifetime of your career. I've been doing this stuff for more than 20 years, and I still get a kick out learning something new every day. Learn not just about up front design, but also emergent design, testing, best practices, processes and methodologies. All have varying degrees of impact on how your designs will emerge, take shape, and more importantly, how they last over time.

Find time to tinker. Either get involved with a skunkwork project through your workplace, or practice on your own time. This goes hand-in-hand with your reading, by putting your new knowledge into practice, and seeing how such things will work. This is also the stuff that makes for a good discussion with your mentor.

Get involved with something technical outside of your workplace. This could be a project, or a forum. Something that will allow you to test out your theories and ideas outside of your immediate circle of peers in order to maintain a fresh perspective on things.

Be patient. Recognize that earning experience takes time, and learn to accept that you need to back off for a while in order to learn why and where you have failed.

Keep a diary or a blog of your tasks, your thoughts, your failures and your successes.  This isn't strictly necessary, however I have found that it can be of great benefit to you to see how you have developed over time, how your skills have grown and your thoughts have changed.  I come back to my own journals every few months and look at the stuff I wrote 4-5 years ago. It's a real eye-opener discovering just how much I'd learned in that time. It's also a reminder that I got things wrong from time to time. It's a healthy reminder that helps me improve.


问:
timers with threads on queue
So I've been asking the wrong questions for the last three days and after searching a lot I think I have an idea of what I need, my question is how to use timers with two threads writing and reading on one queue.
In other words, I have one queue(or any other data structure) and two threads, producer and consumer,
so the producer write values on the queue, with a time for each value(let's say 10 seconds) and the consumer read the queue, both are using lock mechanism, what I need is a timer function that check which value has passed the 10 seconds and remove it from the queue.

I know how to implement the producer/consumer threads, but I don't know where to put this, is it a third thread or what? and do I need to write the time of the value when entered the queue, so the timer function can check it, or just write 10 and the timer function will decrement 1 each second?

答:
First, the structure you want in this case is probably a priority queue. You'll use the expiration time of each item to determine its priority in the queue.

In this case, the consumer thread waits for one of two things to happen: the time of the first item in the queue to come due, or a newly-inserted item ends up at the beginning of the queue.

Title: timers with threads on queue


问:
Effective way to gain practical knowledge
I am currently nearing the end of my first year of my CS degree and have been disappointed with the lack of coding I have been asked to do (one unit).

I am basically looking for an effective way to gain practical knowledge but am unsure where to look for experience from a near beginner's perspective.

答:
Two answers and someone has yet to mention open source projects.

Github and Bitbucket, notably, have projects that range from tiny scripts to monstrous enterprise applications, in a wide variety of languages, using a wide variety of technologies.

My suggestion is to Just Do It. Get involved with a project that piques your interest (try to find one that's well documented and has a decent community - i.e. active IRC channel - especially if you're a near beginner). Yes, it'll be frustrating and you may think that you're over your head on many occasion. But, it's by far the best way to learn imo (not to mention you'll get exposure to team work and distributed source control).

So get in there, fix some bugs ;)


答:
If I understand correctly, you need each item in the queue to expire after a certain amount of time, but you still need items which are not expired to be consumed with observing the FIFO rule.

In this case, you do not necessarily need a timer or a 3rd thread; simply leave the expired items in the queue, and on consume check if the item you get has expired or not (check current time vs. enqueue time + your timeout). If it hasn't, push it to consumer, if it has, dispose of it.

In case you need to dispose resources when items expire, or to raise events to observers, you can create an external data structure which does exactly this (the collector with a priority queue by expire time, as pointed out by Jerry Coffin), but you don't need to connect it in any direct way to your producer-consumer (other than synchronizing to make sure that you don't consume something that's being disposed of).

Title: timers with threads on queue

Body:
So I've been asking the wrong questions for the last three days and after searching a lot I think I have an idea of what I need, my question is how to use timers with two threads writing and reading on one queue.
In other words, I have one queue(or any other data structure) and two threads, producer and consumer,
so the producer write values on the queue, with a time for each value(let's say 10 seconds) and the consumer read the queue, both are using lock mechanism, what I need is a timer function that check which value has passed the 10 seconds and remove it from the queue.

I know how to implement the producer/consumer threads, but I don't know where to put this, is it a third thread or what? and do I need to write the time of the value when entered the queue, so the timer function can check it, or just write 10 and the timer function will decrement 1 each second?


答:
I didn't get the whole picture until I took Operating Systems, Database Management Systems, Computer Networks and some programming courses.

Start with learning a programming language of your choice. (I started with C and proceeded to C++, which is very powerful)

Do some simple projects requiring non-trivial algorithms such as the ones at ProjectEuler.

After becoming comfortable with the language and common algorithms, move to GUI programming like Windows Forms, WPF or Qt.

Gain some experience with GUI and event driven applications and learn about cross-platform GUI libraries again such as Qt.

You may want to develop some small games for fun.

Then you want to learn about processes, threads, multi-threading, database programming, network programming and so on. You will learn most of these in your CS courses.

Web development is a great way to expand your skills as it requires both server side development and network information like HTTP.

Just take your time, enjoy coding. Do not get depressed when you see code that you don't understand anything .)


答:
Read about patterns, sure, but first and foremost read about anti-patterns. Recognizing anti-patterns is important, and it's easier to understand why something shouldn't be done in such a way than why it should.

See http://sourcemaking.com/antipatterns/software-development-antipatterns for example.

Write code so that it can be adjusted quickly if requirements changed (which is very common in production environment).

Be super-skeptical about adding "just one more little hack." One more here, one more there, and the code becomes unmaintanable.

Value the open/closed principle.

Write tests (as in TDD). They force you to think your design through even before you actually implement it.

Browse the code of open source projects (reasonably sized ones, that is). I used to be surprised at - usually - seeing so many levels of abstraction. Now I understand it's not art for art's sake, there's a reason why it's done this way.


问:
Was classical BASIC ever used for commercial software development, and if so, how were limitations overcome?
Many of us, including me, started their programming life with programs written on home computers, something like

```<code>10 PRINT "ENTER RADIUS"
20 INPUT R
30 PRINT "CIRCUMFERENCE="; 2 * R * PI
40 PRINT "AGAIN?"
50 INPUT A$
60 IF A$="Y" THEN GOTO 10
70 END
</code>```

Of course, the line-number based BASIC was prone for creating spagetti code, also because most BASIC dialects missed structural statements like WHILE, doing everything but the FOR-loop with IF, GOTO and GOSUB. I'm talking about BASIC dialects before 1991, when QBASIC and Visual Basic appeared.

While BASIC dialects may have promoted bad style amongst aspiring programmers, were there larger commercial projects created in such a BASIC dialect? If so, how did they manage to live with and workaround the obvious shortcomings?

By "serious", I mean:

Not a game (I know some commercial games were written in BASIC, for example, Pimania)

Not freeware

Not trivial, that is, reasonably large (say: at least 1500 LOC)

Sold to several customers (not an in-house development)

"Mission critical" is a plus

答: Look into PICK or any of the other MultiValue databases. They all rely on DataBasic as their main or only language and have a significant vertical market usage. We still run a system I wrote for procurement benchmarking over 20 years ago. Runs to about 50k lines of code.</p>


问:
Licensing doubts
I am quite new to programming and I am now creating my own program as part of my Master Thesis. My program is done in Java and uses several third-party libraries. These libraries come with different licenses, mainly:

LGPL 2.1

GPL 2 + GPL Linking exception

Apache version 2

BSD

I have actually not touched the source code of these libraries, but use them in my program and in some cases create classes that extend classes in those libraries.
 If I decide to make my program publicly available (probably for free) what kind of licence could I use? I have read much about license compatibility (Apache vs GPL vs whatever), derivative works discussions and I am very confused. Comments and explanations would be very helpful.

答:
Informal summary:

GPL: many pages stating all the things that are not allowed to do with it (who said freedom?). Basically, anything using it must become GPL or re-implement things

LGPL: GPL with a little bit of flexibility: your free software can be binary linked to under certain circumstances.

Apache: lots of lawyer mumbo jumbo, but a permissive License nonetheless. Requires derivative works to provide notification of any licensed or proprietary code in a common location.

BSD: sweet and small license: do whatever you want with it

If you use GPL stuff, you basically have to release it under GPL as well. It is the most restrictive license of them all.

If I am not mistaken, BSD, Apache, LGPL can all be used by GPL software but not vice versa. You cannot release something under BSD using GPL code.

Edit:

correction: Apache version 2 is only compatible with GPL v3 but not GPL v2. No idea how it is affected from that linking exception.

Sources:

```<code>http://en.wikipedia.org/wiki/List_of_FSF_approved_software_licenses
http://en.wikipedia.org/wiki/GPL#Compatibility_and_multi-licensing
</code>```

Welcome to the crazy world of licensing and the restrictiveness of GPL! ...I think everyone is lost in all these licenses and clauses anyway.

Title: Licensing doubts

Body:
Informal summary:

GPL: many pages stating all the things that are not allowed to do with it (who said freedom?). Basically, anything using it must become GPL or re-implement things

LGPL: GPL with a little bit of flexibility: your free software can be binary linked to under certain circumstances.

Apache: lots of lawyer mumbo jumbo, but a permissive License nonetheless. Requires derivative works to provide notification of any licensed or proprietary code in a common location.

BSD: sweet and small license: do whatever you want with it

If you use GPL stuff, you basically have to release it under GPL as well. It is the most restrictive license of them all.

If I am not mistaken, BSD, Apache, LGPL can all be used by GPL software but not vice versa. You cannot release something under BSD using GPL code.

Edit:

correction: Apache version 2 is only compatible with GPL v3 but not GPL v2. No idea how it is affected from that linking exception.

Sources:

http://en.wikipedia.org/wiki/List_of_FSF_approved_software_licenses
http://en.wikipedia.org/wiki/GPL#Compatibility_and_multi-licensing

Welcome to the crazy world of licensing and the restrictiveness of GPL! ...I think everyone is lost in all these licenses and clauses anyway.


答:
You are free to choose any licence you like

Here is why:

Apache & BSD — these are permissive, they don't impose any limitations;

LGPL 2.1 — only imposes licensing limitation on distribution of changes to the library itself;

GPL 2 + GPL Linking exception — this is the tricky one. Basically GPL would mean that you have to release whole thing as GPL. However, since it has linking exception, and you do not reuse any part of source code in your source code, your code is exempt from GPL. To clarify, creating a class which extends a class imported from library is not including it's source code in your code, it's only linking to library and using it.

The significant part of the exception:

As a special exception, the copyright holders of this library give you
  permission to link this library with independent modules to produce an
  executable, regardless of the license terms of these independent
  modules, and to copy and distribute the resulting executable under
  terms of your choice, provided that you also meet, for each linked
  independent module, the terms and conditions of the license of that
  module

Title: Licensing doubts

Body:
I am quite new to programming and I am now creating my own program as part of my Master Thesis. My program is done in Java and uses several third-party libraries. These libraries come with different licenses, mainly:

LGPL 2.1

GPL 2 + GPL Linking exception

Apache version 2

BSD

I have actually not touched the source code of these libraries, but use them in my program and in some cases create classes that extend classes in those libraries.
 If I decide to make my program publicly available (probably for free) what kind of licence could I use? I have read much about license compatibility (Apache vs GPL vs whatever), derivative works discussions and I am very confused. Comments and explanations would be very helpful.


问:
First dedicated IDE?
What was the first program that was created as a dedicated IDE? That is, purpose built for coding, rather than simply allowing integration as part of its expansion options.

This is opposed to a text editor that has generic plugin/add-in/shell features that are were not dedicated to development work.

The features I am thinking about that would qualify an editor as an IDE:

Code highlighting

Integrated compiler invocation (with error reporting)

Code navigation features

(optionally) integrated debugger

Sub question - what was the first Visual IDE? (by which I mean with an integrated GUI designer).

答: According to Wikipedia, the first language that was specifically created together with an IDE for that language was Dartmouth BASIC in 1964. However, that probably depends on your definition of "IDE". The way LISP development is done, and LISP is typically implemented, there is really no distinction between the language and the IDE, so I wouldn't be surprised to find examples earlier than that.</p>

Title: First dedicated IDE?


问:
Best practice for creating views in spring and hibernate web application
Hi I am currently developing a web application in Spring and Hibernate where i have several different tables. The Delivery table for example is mapped many-to-one with the Customer table and the Product table.

I am wondering what the best practice is for creating a view function where I display all the columns related to each delivery but exclude the different IDs.

I can think of two ways of doing this:

Create a DTO (data transfer object) with all the columns I wish to display and then in the controller I create a new instance of it and set the different values with setters and services in a for-loop for each Delivery ID. this is the method used in this example. Here is part of the controller code from it:

```<code>@RequestMapping(value = "/list", method = RequestMethod.GET)
public String getRecords(Model model) {
 logger.debug("Received request to show records page");

 // Retrieve all persons
 List<Person> persons = personService.getAll();

 // Prepare model object
 List<PersonDTO> personsDTO = new ArrayList<PersonDTO>();

 for (Person person: persons) {
  // Create new data transfer object
  PersonDTO dto = new PersonDTO();

   dto.setId(person.getId());
   dto.setFirstName(person.getFirstName());
   dto.setLastName(person.getLastName());
   dto.setMoney(person.getMoney());
   dto.setCreditCards(creditCardService.getAll(person.getId()));

  // Add to model list
    personsDTO.add(dto);
    }

 // Add to model
 model.addAttribute("persons", personsDTO);

 // This will resolve to /WEB-INF/jsp/records.jsp
 return "records";
 }
</code>```

the second way I am considering is to create an HQL query that Joins the relevant tables and then displaying that. I'm not sure exactly how to do this yet.

So which of the alternatives is the better way to go? Are there any others that I haven't thought about?

Thank you for the advice,
D

答:
With ORM technologies there are many ways to approach this. I think either of the ways you suggest are adequate, but I'll add the performance concern angle.

If you have performance concerns, then I suggest you look at the SQL produced (show_sql) as well as the network traffic via the JDBC driver (use P6Spy or similar) in both versions and see what impact they have.


答: I'd nominate dBase II which appeared in 1979. It had integrated compilation and code editing/navigation and debugging. No code highlighting though - but I don't regard that as a prerequisite for making something an IDE, personally.</p>

Title: First dedicated IDE?

Body:
What was the first program that was created as a dedicated IDE? That is, purpose built for coding, rather than simply allowing integration as part of its expansion options.

This is opposed to a text editor that has generic plugin/add-in/shell features that are were not dedicated to development work.

The features I am thinking about that would qualify an editor as an IDE:

Code highlighting

Integrated compiler invocation (with error reporting)

Code navigation features

(optionally) integrated debugger

Sub question - what was the first Visual IDE? (by which I mean with an integrated GUI designer).


问:
What is the difference between all-static-methods and applying a singleton pattern?
I am making a database to store information about the users of my website (I am using stuts2 and hence Java EE technology). For the database I'll be making a DBManager. Should I apply singleton pattern here or rather make all its methods static?

I will be using this DBManager for basic things like adding, deleting and updating User profiles. Also, I'll use it for all other querying purposes, for instance to find out whether a username already exists and to get all users for administrative purposes and stuff like that.

My questions:

What is the benefit of singleton pattern?

Which thing is most apt here? All static methods or a singleton pattern?

Please compare both of them.

P.S. The database is bigger than this. Here I am talking only about the tables which I'll be using for storing User Information.

答:
What is the difference between all-static-methods and applying a singleton pattern?

Both have the same effect: you can call a class method without careing how to get an instance of the class that contains the method.

However if you want to implement Unittesting static methods are more problematic because they can not be easily mocked.

From the testing perspective it is easier to rewite code that uses singeltons to make them unittestable with mocks.

The most flexible soulution would be to have Dependency_injection no matter if you are using a di-container-framework (as suggested by @Tazzy531 ) or if you are wireing dependencies by code.

ContentLicense: CC BY-SA 4.0


问:
How to solve installation errors reported by users, on Android?
I've some application on the Google Play, free to download, but I have some people reporting things like:

"There has been problem installing on my htc x."

How do  I help these people? I could reply and ask things like their android version and what not, but this won't really help me debug it, since the error occurs on installation!

Any general ideas on how to handle this? Maybe some tips about general android installation issues, or on how to help the people?

答:
To expand on @XGouchet's answer:

(I realize that this may not be the best approach, but it is a means to an end)

Perhaps it would be better to include aLogCat in a testing version of your apk with an install tie-in to send logs on a timer to a server or something (until this problem has been adequately documented, and make sure you put this fact somewhere in the download description). One approach might be to re-structure your app so that the apkd is actually a wrapper that installs aLogCat and then starts the install for your app. This way the end user has to take no extra steps, and you get much more info on the issue(s) and can fix the problem. _Again, make sure you put a notice somewhere in the download description that you are doing this and only do it as long as it takes to make sure you have the issue identified*._ You will likely be skewered if you do not disclose this fact and loose all creditably in the Play Store if you don't let people know what and why you are doing. Once you have a handle on the possible source, revert back to the unwrappered apk.

Only give the "logging" version to users that have reported the issue and are willing to help with some testing. Would be (mostly) simple for everyone involved, just have the wrappered version on your site somewhere (Again, with the proper disclosure) and direct your testing users to this apk with directions for enabling the "Unknown Sources" option.

At that point, you're on to a whole new question: how to fix it (probably better to ask that question on SO).

*If you let your user's know that you are doing this and why, you are likely to get less emails asking questions, less negative feedback/ratings, and less general bad karma. But some might be turned off by the extra recording so be ready for that; this is why I said to do this only as long as needed! Remember to let your users know that with the logging you might get some sensitive info, let them make an informed decision.


问:
How to work with badly written and formatted code
I was wondering how people deal with working in a project with badly written and formatted code, I'm talking mixed tabs and spaces, unnecessary parentheses and newlines and a whole bunch of warnings appearing on the code from the IDE. For context I have this problem on java projects, where no formatting was agreed upon. Also, in my case they are projects that have not gone public yet.

The possible solutions I can see are:

Try and talk to the team leader/code owner, agree to a formatting and reformat everything in one commit. (my preferred choice)

Format the piece or pieces of code that you have to change, commit, then make the change and commit (second best)

Deal with it, make your changes as minimal as possible, leaving everything else as was.. (worst choice, for me)

答:
A standard should be set for sure, or you will have each team member committing to a project with different code-formatting styles. I would talk to the team leader about this before talking about reformatting code.

If no formatting continues to be the standard for this project, format your code the way you see fit.

OwnerDisplayName: Dale Wijnand


答:
I agree with your choices and their order.  Keep in mind that if you format the code as you go along without an agreed coding guideline, you will most likely end up playing code format ping-pong with your co-workers who are working on the same files.

Also, don't cling to your particular formatting: as long as there is a consistent guideline, the code will be readable (everyone will have to adjust to read/write the code in that format efficiently, but that's the price you have to pay and it is a "one-time" investment up front)

Title: How to work with badly written and formatted code

Body:
I was wondering how people deal with working in a project with badly written and formatted code, I'm talking mixed tabs and spaces, unnecessary parentheses and newlines and a whole bunch of warnings appearing on the code from the IDE. For context I have this problem on java projects, where no formatting was agreed upon. Also, in my case they are projects that have not gone public yet.

The possible solutions I can see are:

Try and talk to the team leader/code owner, agree to a formatting and reformat everything in one commit. (my preferred choice)

Format the piece or pieces of code that you have to change, commit, then make the change and commit (second best)

Deal with it, make your changes as minimal as possible, leaving everything else as was.. (worst choice, for me)

OwnerDisplayName: Attila


问:
Dependency injection: How to sell it
Let it be known that I am a big fan of dependency injection (DI) and automated testing. I could talk all day about it.

Background

Recently, our team just got this big project that is to built from scratch. It is a strategic application with complex business requirements. Of course, I wanted it to be nice and clean, which for me meant: maintainable and testable. So I wanted to use DI.

Resistance

The problem was in our team, DI is taboo. It has been brought up a few times, but the gods do not approve. But that did not discourage me.

My Move

This may sound weird but third-party libraries are usually not approved by our architect team (think: "thou shalt not speak of Unity, Ninject, NHibernate, Moq or NUnit, lest I cut your finger"). So instead of using an established DI container, I wrote an extremely simple container. It basically wired up all your dependencies on startup, injects any dependencies (constructor/property) and disposed any disposable objects at the end of the web request. It was extremely lightweight and just did what we needed. And then I asked them to review it.

The Response

Well, to make it short. I was met with heavy resistance. The main argument was, "We don't need to add this layer of complexity to an already complex project". Also, "It's not like we will be plugging in different implementations of components". And "We want to keep it simple, if possible just stuff everything into one assembly. DI is an uneeded complexity with no benefit".

Finally, My Question

How would you handle my situation? I am not good in presenting my ideas, and I would like to know how people would present their argument.

Of course, I am assuming that like me, you prefer to use DI. If you don't agree, please do say why so I can see the other side of the coin. It would be really interesting to see the point of view of someone who disagrees.

Update

Thank you for everyone's answers. It really puts things into perspective. It's nice enough to have another set of eyes to give you feedback, fifteen is really awesome! This are really great answers and helped me see the issue from different sides, but I can only choose one answer, so I will just pick the top voted one. Thanks everyone for taking the time to answer.

I have decided that it is probably not the best time to implement DI, and we are not ready for it. Instead, I will concentrate my efforts on making the design testable and attempt to present automated unit testing. I am aware that writing tests is additional overhead and if ever it is decided that the additional overhead is not worth it, personally I would still see it as a win situation since the design is still testable. And if ever testing or DI is a choice in future, the design can easily handle it.

答:
Perhaps the best thing to do is step back and ask yourself why you want to introduce DI containers? If it's to improve testability then you your first task is to get the team to buy into unit testing. Personally I'd be much more concerned about the lack of unit tests than the lack of a DI container.

Armed with a comprehensive suite or suites of unit tests, you can confidently set about evolving your design over time.  Without them, you face an increasingly fraught struggle to keep your design in-step with evolving requirements, a struggle that eventually many teams lose.

So my advice would be to first champion unit testing and refactoring then, in turn introduce DI and finally DI containers.

Title: Dependency injection: How to sell it


答:
Remember the Boy Scout Rule, leave the code cleaner than the way you found it.

Therefore I'd suggest to get the Team to agree on a code formatting guideline, and then apply 2. You will keep productivity up and you will improve the code as you go.

If you need strong arguments for why code should be kept clean, I do recommend reading the Clean Code book. People need to be able to read and understand the code. The better it is formatted, the faster everyone will be able to read it. Machines (Diff/Merge) also do a heck of a lot better if the code is uniformly formatted.

If there are discussions about what is the best formatting, remember there is no such thing. I fully agree with @Attila here: As a consultant I have moved from team to team and after a few weeks anyone can get used to the same style of code. Most of the strong 'feelings' about code formatting are born out of habit.


问:
How do you handle / what do you charge for documentation, training, warranty, changes in scope etc…
I am working with a client right now that wants me to sign a contact with a warranty for a year for no additional charge. As well as any reasonable changes he wants during the contract that are outside of the guidelines for no additional charge while not affecting deadlines. And lastly documentation and training for all staff for no additional charge.

Red flags are going everywhere in this contract and I wanted to hear from professionals how you guys handle / what you charge for documentation, training, warranty, changes in scope etc...

答:
Your situation sounds quite bad, for several reasons:

Your client seems to be short of money, or at least driving a hard bargain.  This is never a good thing, and if you are offering decent services, your client(s) should be happy to pay you for it.

You seem surprised at the contract.  Even if there was no contract in place before, clearly your expectations didn't match the client's.  At best, you were both slightly naive and there's a large gap in expectations, and at worst, your client maliciously played you on purpose (e.g. if they withhold payment unless you agree to this, and knowingly sprang this on you late).

The contract seems to include several items which are very difficult to quantify, meaning a large risk for you.  It doesn't seem reasonable (even without considering the "for free" part), which is never a good sign.

So in general, I agree with most of the other posts, you should take a hard line here and possibly cut your losses, if it comes to that.  Having said that, your post still has some unanswered questions, so I will try to give some insight.

I wanted to hear from professionals how you guys handle / what you charge for documentation, training, warranty, changes in scope etc...

You really have two broad classes of scenarios - either the project is fairly well defined (in terms of requirements), or it isn't.  What I'm going to describe below is for the "well defined" route.  While this seems very "waterfall" / old school, the simple fact is, clients almost always want a fixed quote before work begins.  The simplest alternative would be a "pay-as-you-go" approach where requirements are not fixed, but this doesn't seem to be attractive to clients, and will also make it difficult for you to plan your own availability.

I've always gone with a single hourly rate; this may or may not get communicated to the client (according to their preference for how the project and billing is structured), but it forms the basis of your estimates.  Essentially, I mean that the rate charged for training, documentation, bug fixes, or new features is the same.  The problem then becomes trying to estimate the level of effort required for each.

It is quite common to offer a fixed duration of training - e.g. "4 days of training", with various conditions attached.  Typical conditions might be: specifying that each "day" is 8 hours, whose responsibility it is to set up the training environment, where the training will take place (the client may want you to travel).  You are probably assuming: "I will show up, and train some people for a few hours".  Your client might think "this guy will set up PCs for 20 people, train them, and give them lunch".  It's best to clarify responsibilities early.

Warranty - I have no issue giving a limited warranty; if the scope of the project is clear, with unambiguous requirements.  Use your judgement here.  I also like to keep the warranty period short, as it can interfere with future projects.  E.g. you don't want to be 3 months into your next project when the previous client decides to go live, and starts needing weeks of your time.  I normally go with a 1 month period, along the lines of "anything that doesn't work as per the specifications will be fixed for no additional charge, as long as it is reported within 4 weeks of delivery date".  Offering warranty is also great motivation to keep yourself honest, and the work to high quality, so I actually like to do it.

It's important to note that the warranty is explicitly tied to the requirements (assuming it is their responsibility to provide those).  Don't agree to any requirements that are too ambiguous or broad for you to be comfortable.  Even more importantly, never guarantee anything more than this; it's not your job to ensure that they are financially successful in using your software (e.g. that the requirements were good in the first place).

Changes in scope - this is the difficult one.  I normally classify these into trivial and non-trivial changes.  Trivial changes are things that would take less than 30 minutes to do.  I will often let these slip, and do them without charge, because it'd cause more friction to explain to the client why you are not willing to change 1 label.

Include a few hours in your estimates for these, and you won't feel cheated when they come around.  Non-trivial changes, in general, are not allowed.  If they are critical for the client, they won't mind you whipping up an addendum to your quote (and typically, critical changes will be large enough to warrant an addendum).

Since requirements do tend to change, keep your projects short.  I like to split large projects into roughly 1 month iterations, with defined requirements and a testable, executable deliverable at the end of each.  Any changes arising out during one iteration can be worked into the next - a modification to the quote and a quick approval from the client is all that it takes.  If there's a major ripple effect, the situation is more complicated; but it is in your interest to avoid those.  You need to take a very mature, pragmatic approach to these projects, understanding the requirements intimately, so that you can preempt show-stoppers early on.

To summarise:

What you are doing here is estimating things.  The more you know about yourself and your client, the easier this becomes.  With experience, you will learn to detect problem clients early and avoid them altogether.

When you see risks and unknowns, make sure you pad for them (read up on how to factor risks into your estimates).  If I'm pushed into these situations, I tend to err on the side of caution (this also gives the client incentive to minimise unknowns).  Do communicate with your client about these things - 99% of the time, they would rather clarify a requirement, or narrow the scope of something in the contract, than be thrown with a hugely padded quote.

Never go into anything that poses a severe financial risk for you - unbounded warranties, etc.  When you have a long history with a (reliable) client, you can relax these rules to make things easier, but in general, they still apply.


问:
Python flavor of regular expressions - related to which?
So my copy of the classic book, Mastering Regular Expressions, just arrived, and I'm scanning through it. The cover (third edition) says, "for Perl, PHP, Java, .NET, Ruby, and More!" Well, it does have a full chapter for each of Perl, PHP, Java, and .NET - but no chapter on Ruby, or, more importantly to me, on Python.

Although the index lists a few points of Python's differences (such as how it handles newlines), there's not even a table of them, much less an entire chapter.

Which of the four covered languages, is Python's regex engine most similar to? More importantly, how similar, and what are the major differences?

Note - I don't mean how regexes are used in Python (versus, say Perl) - I know and use the re module. I'm only interested in the syntax differences of the actual regexes.

答:
Definitely check out the re module in Python. It might be (soon be?) outdated, but it's a great starting point for using regex in Python.

In my opinion, if you really want to get a handle on regular expressions, learn some Perl syntax. Regex is one of Perl's killer features, since regex is handled natively. They go hand in hand. Regex syntax is more or less the same across languages, particularly the basics like wildcards, anchors, special characters and substitution. Trust me when I say you can get pretty far on those fundamentals, but the more one knows, the better.

One of the main differences between Perl regex and the re module is that Python's approach is more object-oriented. Where in Perl you might do something procedural like this

```<code>if ($line =~ m/^Forty-two is the answer to [life|universe|everything]/)
{
   print "Don't Panic"
}
</code>```

In Python you work with re objects. Something like this:

```<code>m = re.compile("^Forty-two is the answer to [life|universe|everything]")
if m.match(line):
    print "Dont Panic"
</code>```

The object oriented approach and the non-nativity are a bit tough to get used to if you've worked extensively with Perl's regex syntax but I find that after getting used to it, Python does a really good job with regular expressions.

Body:
Definitely check out the re module in Python. It might be (soon be?) outdated, but it's a great starting point for using regex in Python.

In my opinion, if you really want to get a handle on regular expressions, learn some Perl syntax. Regex is one of Perl's killer features, since regex is handled natively. They go hand in hand. Regex syntax is more or less the same across languages, particularly the basics like wildcards, anchors, special characters and substitution. Trust me when I say you can get pretty far on those fundamentals, but the more one knows, the better.

One of the main differences between Perl regex and the re module is that Python's approach is more object-oriented. Where in Perl you might do something procedural like this

if ($line =~ m/^Forty-two is the answer to [life|universe|everything]/)
{
   print "Don't Panic"
}

In Python you work with re objects. Something like this:

m = re.compile("^Forty-two is the answer to [life|universe|everything]")
if m.match(line):
    print "Dont Panic"

The object oriented approach and the non-nativity are a bit tough to get used to if you've worked extensively with Perl's regex syntax but I find that after getting used to it, Python does a really good job with regular expressions.


问:
How to improve my loop logic in programming?
I know how to do simple loops but I don't know what's going on when many loops are working together.

For example:

```<code>for (var i=0; i <= 9; i++){
     document.write(i);

  for (var m=0; m <= 9; m++){
     document.write(i);
    }
}
</code>```

Is there a way I can learn loops inside out?

答:
It's pretty simple actually...
you have to think step by step.

You enter your first loop with i = 0. The condition is clear, it will not stop to execute what's inside {} while i is inferior or equals 9.

Let's see what comes next... you call document.write(). I guess you know exactly what it does.

Then... HUHO! ANOTHER LOOP! chill out, it's exactly the same thing.

You start your second loop with m = 0 and won't stop while m is inferior or equals 9.
Then you write what's inside i using document.write()
You're at the end of your second loop context so you re-evaluate what's inside m. m is now equals to m+1 (due to the m++). m equals 1 and as 1 is inferior or equal to 9 it will loop again (it will then write again what's inside i, then add 1 to m). Now m is equals to m+1 (2)... etc. etc.

When m will equal 10 then m will not be inferior or equal to 9 anymore so you will stop looping in your second loop, and continue your first loop execution.

So now i is equals to 1 (due to i++), i is inferior or equal to 9 so you will execute your first loop again. Inside your first loop there is the document.write() call but there is the second loop.
You enter your second loop with m set to 0... and it goes on and on...

But as you always write what's inside of i, you will have ten 0 displayed, then a linebreak then ten 1 displayed, then a linebreak... and so on until 10.


答: getting more familiar with nested loops involves using them more first of all, which can be tricky because it best to avoid nesting loops when you can. Other things that help are using better (more descriptive) names for your loop variables. Taking time to manually step through code can really help increase your understanding of code, go through line by line and figure out what each variable will be at the time and write what any output would be.</p>

Title: How to improve my loop logic in programming?

Body:
I know how to do simple loops but I don't know what's going on when many loops are working together.

For example:

```<code>for (var i=0; i <= 9; i++){
     document.write(i);

  for (var m=0; m <= 9; m++){
     document.write(i);
    }
}
</code>```

Is there a way I can learn loops inside out?


问:
Should you fix preexisting defects while working on something else?
Conundrum:  During the course of working on a new feature or fixing a defect, you find a legacy problem in code.  What should you do?  Fix it and risk altering the behavior of the code. It has either been working up until now by some fluke, or else the defect has not been detected or worth anyone's time to report.  Should you leave it alone and allow the problem to make the code harder to work with later?  Fixing the problem will only add to the time of your original task and force you to regression test. Few will appreciate the work. Fixing it, however, seems right somehow. Code with fewer problems is easier to refactor and build upon.

I've been finding myself in this situation time and time again as we work to modernize a web application. I can't tell if I'm being obsessive or honorable when I go off-tangent working on these old bugs.  How do you handle these situations?

Thanks,
Corey

答:
Well document the observations first, and decide whether to fix it later.

Have some formal discussion (e.g, in the regular meeting) or informal discussion (e.g., during the lunch) with your colleagues, and make the changes after you gain more confidence on the behavior of the codes you are going to fix.

Although it seems a bug/defect to you, it may actually be a "feature" this time. It could be a poorly implemented solution to get around some corner cases at the last minute of the previous release, and your "clean fix" may revive some previously resolved issues.

ContentLicense: CC BY-SA 2.5


问:
What are the things that you consider in reviewing an iOS source code?
We're going to do some peer reviews for our iOS projects. We're kind of inexperienced at reviewing each other's codes. The iOS developers attending the reviews will be from other projects, since generally one person handles one client project in the company.

I know there are some questions on SO about the things you're looking for when you're reviewing someone else's code. I want to ask this question specifically for iOS projects. I mean, besides the general points for code quality, what are the things that you consider when reviewing an iOS code?

答:
Make sure you have a workflow put in place to catch as many problems as possible before you review code. So, as a minimum, make sure show warnings as errors is set on, and the static analyzer runs every time they compile.

If you're expecting certain standards in the code, put together a house coding style that devs should adhere to. For example, that all iVars should have a @property declared, and @synthesize iVar = _iVar

For iOS code, lack of understanding of memory management is an issue with inexperienced developers, so pay particular attention to that. E.g. are all retained properties released in the dealloc?

Do they understand Cocoa design patterns? Is there proper separation of model, view, controller? Have they implemented delegate protocols where appropriate?

This one's a particular bugbear, but if I see [[UIApplication sharedApplication] delegate] anywhere in the code it would raise a red flag!

I'll add more as I think of them!!


答:
The best way to learn about loops without doubt is debugging. Just observe your loop variables such as counters and conditions.

Observe the process step by step, check conditions and follow counters. You will get it very quickly.


答: You say you understand simple loops; well break the nested loop into simple loops. Think of the inner loop as a function call. So what's the outer loop do? Call that function for each iteration of the loop. Now think of that 'function' - it's just another simple loop. So for each call to that 'function', you run that loop then 'return' from the function. Now you're back in your simple outer loop...  etc. etc.</p>


问:
Is this the best way to approach this design? Is this an example of MVC?
I am designing a WinForms application in C# and wanted to get a design check by you guys. I am fairly new to programming and have been reading some material, so please excuse my mis-usage of words or 'computer science' terminology if need be.

The Design

I have a MDI application with MAIN as my parent form and various other CHILD forms. Now whenever an exception occurs, whether in MAIN or a CHILD form, it needs to be logged into a LOG window, which itself is a child form of MAIN.

Reading material over the web, a lot is said to have loosely coupled classes. Now my thinking is that I will have a non-form class, called Log Collector Class which will basically be the "middle man" between all non-log window forms and the window form. Any exception, or update in general to the log window, will need to go through this middle man class. In turn, there will be a custom event in which if this Log Collector Class is updated, the listener, aka the Log Window, will update whatever control it needs to update to display the exception.

An image for visual people:

Any comments on this would be great, especially if I am doing things correctly (or in-correctly).

答:
That's a pretty good approach. You can have as many objects as you like raising exceptions, informing your middle-man, and as many listeners as you like waiting for an event to be raised. And no object needs to know about the full structure of any other object, they just need a thin interface by which to communicate. This is good decoupling.

But it's not an example of MVC. It is an example of the mediator pattern.


问:
Ways to version user generated documents
I have an online document which essentially gets stored to the database as XML string.

I'm thinking about a way to implement versioning of the document for the user.  So that user can go back to previous versions of the document.

update In my case it's a web application with hundreds of thousands of users.  A user can store unlimited amount of documents. The XML for document is stored in MySQL blob field so it's not small.  Eventually I need to cap the limits somehow but that is a different topic all together.

Is there a standard way to approach this? Should I store only the differences between versions? What are other things that I need to consider?

答:
Since you're doing this in a database, the easiest way to version your XML string would be to create a new History table with the following columns:

History ID

New XML string (optional column)

Old XML string

Insert timestamp

Insert a row to this History table before you update the row on the XML string table.


问:
What is the point of having every service class have an interface?
At the company I work at, every service class has a corresponding interface.

Is this necessary?

Notes:

Most of these interfaces are only used by a single class

We are not creating any sort of public API

With modern mocking libraries able to mock concrete classes and IDEs able to extract an interface from a class with two or so clicks, is this just a holdover from earlier times?

答:
Your company is following the SOLID principles and targeting an interface rather than concrete class adds zero overhead to the program.  What they're doing is a very moderate amount of extra work that can pay back volumes when the assumptions that you are making end up being false...and you can never tell what assumption that's going to be.  What you're recommending while slightly less work, can cost many, many, many hours of refactoring that could have just been done ahead of time by simply following basic OO design principles.

You should be learning from these guys and consider yourself lucky. Wish I worked in such an environment where solid design was a priority goal.


问:
At which point do you "know" a technology enough to list it on a resume
I recently had a programmer in for an interview, who listed Python, PHP, Rails and ASP as a few of their skills. In the interview however, they interviewee didn't enough know what control structures and basic logic were, they had only followed a few demo tutorials.

So my question is this: At which point can you add a technology to your resume accurately. Is it when you can demonstrate all basic concepts, write a useful program in it, or are just comfortable using it without having to refer to the documentation every 30 seconds.

I don't believe this is overly subjective, a baseline should easily be established based on feedback.

答:
I'm not sure it is exactly determinable. In my opinion, it should be on a case to case basis. What I mean - let me explain on an example:

Job ad 1 - wanted candidate with knowledge of: Python, PHP, Rails, ASP, Assembler.

(and usually it can be somewhat determined from the ad which skills are more important than others - which are just there "in case")

In this case I would put on my resume Python, PHP ... only if I really well know them. Assembler, for example, I know very little, but I'd put it still, for it can't have a major impact in combination with the rest of the above.

Job ad 2 - wanted candidate with knowledge of: Assembler, C/C++, Kernel ..., Python, PHP, ...

This case is different. Here it is (is it?) obvious that they're looking for a different kind of candidate, and that they'll (probably) disregard the lack of knowledge of PHP for example, if the candidate posseses these other skills.

So it depends really.

As a general rule, to put something on a resume, IMO, one should know how to "find his way" around code, basic syntax, and have at least a few small sized projects behind him using that particular language. He doesn't of course have to know the libraries & help by heart ... but should how & where to get help should he need it.

There can be counter examples to this rule - I've noticed that people who (really) know a lot of languages tend to get confused sometimes "depending on which one they're stuck in currently" - for example: using IF/loops/...other syntax elements in a correct way, but with an incorrect syntax (which actually fits some other language then the one they're currently thinking about). So that is not really a necessary true test of abilities.


问:
What is the name for a NON-self-calling function?
I have a collection of normal functions and self-calling functions within a javascript file. In my comments i want to say something along the lines of "This script can contain both self-calling and XXX functions", where XXX is the non-self-calling functions.

"Static" springs to my mind, but feel that would be incorrect because of the use of static methods in PHP, which is something completely different.

Anyone any ideas? Thanks!

答: Maybe it's the self-calling functions that should be called something different, such as "recursive". Perhaps something along the lines of "This script can contain both recursive and non-recursive functions."</p>


答:
Revised Answer

OK, I see what you mean.  I wouldn't call those "self-calling functions" -- the first thing that comes to mind is "immediately invoked functions".  "Module" would also work, but I'm not sure how readily it would be understood.

Rather than talking about "self-calling" and "non-self-calling" functions, I'd document the script by explaining what members it adds into the global namespace.

For example, if your immediately invoked functions set up some objects, describe those objects.  Basically, describe what the world looks like after your script has run, not how your script gets it to that point.

Original Answer

Since "self-calling" usually means "recursive", I would just say:  "This script can contain both recursive and non-recursive functions."

Title: What is the name for a NON-self-calling function?

Body:
I have a collection of normal functions and self-calling functions within a javascript file. In my comments i want to say something along the lines of "This script can contain both self-calling and XXX functions", where XXX is the non-self-calling functions.

"Static" springs to my mind, but feel that would be incorrect because of the use of static methods in PHP, which is something completely different.

Anyone any ideas? Thanks!


答:
Java interfaces aren't just about mockability (though of course, that is a factor). An interface exposes a public contract for your service, without implementation details such as private methods or attributes.

Note that "public" when using internal services (as in your case) refers to the actual users of said services, including -- but not limited to -- other programmers and internal services!

Title: What is the point of having every service class have an interface?

Body:
At the company I work at, every service class has a corresponding interface.

Is this necessary?

Notes:

Most of these interfaces are only used by a single class

We are not creating any sort of public API

With modern mocking libraries able to mock concrete classes and IDEs able to extract an interface from a class with two or so clicks, is this just a holdover from earlier times?


答: Why not use a source control repository?  It will take less storage space, does everything you currently want, and would easily let you extend the concept further into branches, tags, etc...all the stuff you get from an RCS.  Why reinvent the wheel?</p>

Title: Ways to version user generated documents

Body:
I have an online document which essentially gets stored to the database as XML string.

I'm thinking about a way to implement versioning of the document for the user.  So that user can go back to previous versions of the document.

update In my case it's a web application with hundreds of thousands of users.  A user can store unlimited amount of documents. The XML for document is stored in MySQL blob field so it's not small.  Eventually I need to cap the limits somehow but that is a different topic all together.

Is there a standard way to approach this? Should I store only the differences between versions? What are other things that I need to consider?


答:
IBM's Interactive System Productivity Facility (ISPF).

Copying from wikipedia:

ISPF primarily provides an IBM 3270 terminal interface with a set of panels. Each panel may include menus and dialogs to run tools on the underlying Time Sharing Option (TSO). Generally, these panels just provide a convenient interface to do tasks—most of them execute modules of IBM mainframe utility programs to do the actual work. ISPF is frequently used to manipulate z/OS data sets via its Program Development Facility named ISPF/PDF, where PDF refers to Program Development Facility.

SPF was developed and sold in the late 1970's. ISPF was sold in the early 1980's. I think the minicomputer emulators of ISPF mentioned in Wikipedia, like SPFPC, were sold in the late 1980's. The first time I actually used ISPF was 1982. Before that, I worked with minicomputers in the oil and gas industry.

Title: First dedicated IDE?


答:
Is there a standard way to approach this?

For a standards-based approach, take a look at the Delta-V extension to WebDAV (itself a widely supported extension to HTTP). Delta-V adds versioning to WebDAV and is described in RFC 3253.


答:
You should be able to defend/explain each and every word you put in your resume. Kind of like you dissertation/thesis. I have seen many candidates rejected with the reason "could not justify what he had put in his resume".

One approach is to follow Google's self questionnaire. Rate each skill on a scale of 10. That way we can project how relatively comfortable we are with various technologies.

1 means you can read others code with plenty of googling.

5 maybe for implementing modules in the technology. Etc.

8 for plenty of experience and comfortable with designing and implementing large projects in that technology.

9 for architectural knowledge with moderate understanding of what's under the hood.

10 means you have written a book on it or invented it.

I have seen resumes which have bar graphs indicating relative proficiency in various technology.

Another option is to group skills as "strong understanding", "moderate proficiency" and "familiar with".

Edit:

I tried to put this as a comment, but didn't look due to lack of formatting.

For a reference, here is what Google defines the rates in their Self Evaluation

0 – You have no experience

1 to 3 – You are familiar with this
area but would not be comfortable
implementing anything in it.-

4 to 6 – You are confident in this
area and use it daily.-

7 – 9 You are extremely proficient to
expert and have deep technical
expertise in the subject and feel
comfortable designing any project in
it.-

10 – Reserved for those who are
recognized industry experts, either
you wrote a book in it or invented
it.

Title: At which point do you "know" a technology enough to list it on a resume

Body:
I recently had a programmer in for an interview, who listed Python, PHP, Rails and ASP as a few of their skills. In the interview however, they interviewee didn't enough know what control structures and basic logic were, they had only followed a few demo tutorials.

So my question is this: At which point can you add a technology to your resume accurately. Is it when you can demonstrate all basic concepts, write a useful program in it, or are just comfortable using it without having to refer to the documentation every 30 seconds.

I don't believe this is overly subjective, a baseline should easily be established based on feedback.


问:
Best way to set sys.path for "hot library" development in Python?
I have my Python source structured as follows:

```<code>+-branchname/
  +-dst/
  +-src/
  | +-library/
  | | +-cleese/
  | | | +-test/
  | | | | +-__init__.py
  | | | | +-test_cleese.py
  | | | +-__init__.py
  | | | +-cleese.py
  | | +-palin/
  | |   +-test/
  | |   | +-__init__.py
  | |   | +-test_palin.py
  | |   +-__init__.py
  | |   +-palin.py
  | +-productline/
  |    +-circus/
  |    | +-test/
  |    | | +-__init__.py
  |    | | +-test_circus.py
  |    | +-__init__.py
  |    | +-circus.py
  |    +-grail/
  |      +-test/
  |      | +-__init__.py
  |      | +-test_grail.py
  |      +-__init__.py
  |      +-grail.py
  +-branch_root_marker
</code>```

Entry points are in circus/ and grail/, as well as (possibly) each of the test/ directories, depending on how testing is implemented.

I have multiple copies of this source tree present on local storage at any one point in time (corresponding to various maintenance and feature branches), so I cannot set PYTHONPATH in my shell without some pain. (I would need to remember to change it each time I switched to work on a different branch, and I am very forgetful)

Instead, I have some logic that walks up the file tree, starting at the "current" file location, moving from leaf towards root, looking for branch_root_marker. Once the root directory of the current working copy is found, it adds library/ and productline/ to sys.path. I call this function from each entry-point in the system.

```<code>"""Add working copy (branch) to sys.path"""

import os
import sys

def _setpath():
    """Add working copy (branch) to sys.path"""

    markerfile = "branch_root_marker"
    path = ""
    if ("__file__" in locals() or globals()) and __file__ != "__main__":
        path = __file__
    elif sys.argv and sys.argv[0] and not sys.argv[0] == "-c":
        path = sys.argv[0]
    path = os.path.realpath(os.path.expandvars(path))
    while os.path.exists(path):
        if os.path.exists(os.path.join(path, markerfile)):
            break
        else:
            path = os.path.dirname(path)
        errormsg = " ".join(("Could not find", markerfile))
        assert os.path.exists(path) and path != os.path.dirname(path), errormsg

    path = os.path.join(path, "src")
    (_, subdir_list, _) = os.walk(path).next()
    for subdir in subdir_list:
        if subdir.startswith("."):
            continue
        subdir_path = os.path.join(path, subdir)
        if subdir_path in sys.path:
            continue
        sys.path.append(subdir_path)
_setpath()
</code>```

Currently, I need to keep a separate but identical copy of this function in each entry point. Even though it is quite a short function, I am quite distressed by how fragrantly the DRY principle is being violated by this approach, and would love to find a way to keep the sys.path modification logic in one place. Any ideas?

Note:- One thing that springs to mind is to install the sys.path modifying logic into a common location that is always on PYTHONPATH. Whilst this is not a terrible idea, it means introducing an installation step that needs to be carried out each time I move to a fresh environment; another thing to remember (or, more likely, forget), so I would like to avoid this if at all possible.

答:
Ok, so I went with the gateway script. At the moment it only has minimal functionality, no cacheing of paths, no virtualenv control etc.. but it works and will form the basis for something that will grow over time.</p>

```<code>import os
import sys
import fnmatch

OK = 0
ERROR = 1

_EXCLUDE_FROM_SYSPATH = [".svn", ".hg", ".", ".."]

# -----------------------------------------------------------------------------
def _root_path_of_repo_branch():
    """Returns working copy root path."""

    branch_root_marker = "branch_root_marker"

    path = ""
    if ("__file__" in locals() or globals()) and "__main__" != __file__:
        path = __file__
    elif sys.argv and sys.argv[0] and not sys.argv[0] == "-c":
        path = sys.argv[0]
    path = os.path.realpath(os.path.expandvars(path))
    while os.path.exists(path):
        if os.path.exists(os.path.join(path, branch_root_marker)):
            break
        else:
            path = os.path.dirname(path)
    assert os.path.exists(path), " ".join("Could not find", branch_root_marker)
    return path

# -----------------------------------------------------------------------------
def _pythondirs_in_branch(root_path_of_branch):
    """Find pythondirs in the specified branch."""

    srcpath = os.path.join(root_path_of_branch, "src")
    srctree = os.walk(srcpath)

    pythondirs = list()
    for (dirpath, dirnames, filenames) in srctree:
        for name in _EXCLUDE_FROM_SYSPATH:
            if name in dirnames:
                dirnames.remove(name)
        if any((fnmatch.fnmatch(name, "*.py") for name in filenames)):
            pythondirs.append(dirpath)
    return pythondirs

# -----------------------------------------------------------------------------
def _add_dirs_to_syspath(dirlist):
    """Adds specified directories to the sys path."""

    for dirname in dirlist:
        sys.path.append(dirname)

# -----------------------------------------------------------------------------
def _add_pythondirs_in_branch_to_syspath():
    """Adds pythondirs in the current branch to the sys path"""

    branch_path = _root_path_of_repo_branch()
    pythondirs = _pythondirs_in_branch(branch_path)
    _add_dirs_to_syspath(pythondirs)

# -----------------------------------------------------------------------------
def main(argv=None):
    """Read config & start app."""

    if argv is None:
        argv = sys.argv[1:]

    command_name = argv[0]
    if "test" in command_name:
        pass

    _add_pythondirs_in_branch_to_syspath()

    try:
        command = __import__(command_name)
    except ImportError, err:
        print "IMPORT ERROR : " + err.message
        return ERROR

    return command.main(argv)

if __name__ == "__main__":
    sys.exit(main())
</code>```

Body:
Ok, so I went with the gateway script. At the moment it only has minimal functionality, no cacheing of paths, no virtualenv control etc.. but it works and will form the basis for something that will grow over time.

import os
import sys
import fnmatch

OK = 0
ERROR = 1

_EXCLUDE_FROM_SYSPATH = [".svn", ".hg", ".", ".."]

# -----------------------------------------------------------------------------
def _root_path_of_repo_branch():
    """Returns working copy root path."""

    branch_root_marker = "branch_root_marker"

    path = ""
    if ("__file__" in locals() or globals()) and "__main__" != __file__:
        path = __file__
    elif sys.argv and sys.argv[0] and not sys.argv[0] == "-c":
        path = sys.argv[0]
    path = os.path.realpath(os.path.expandvars(path))
    while os.path.exists(path):
        if os.path.exists(os.path.join(path, branch_root_marker)):
            break
        else:
            path = os.path.dirname(path)
    assert os.path.exists(path), " ".join("Could not find", branch_root_marker)
    return path

# -----------------------------------------------------------------------------
def _pythondirs_in_branch(root_path_of_branch):
    """Find pythondirs in the specified branch."""

    srcpath = os.path.join(root_path_of_branch, "src")
    srctree = os.walk(srcpath)

    pythondirs = list()
    for (dirpath, dirnames, filenames) in srctree:
        for name in _EXCLUDE_FROM_SYSPATH:
            if name in dirnames:
                dirnames.remove(name)
        if any((fnmatch.fnmatch(name, "*.py") for name in filenames)):
            pythondirs.append(dirpath)
    return pythondirs

# -----------------------------------------------------------------------------
def _add_dirs_to_syspath(dirlist):
    """Adds specified directories to the sys path."""

    for dirname in dirlist:
        sys.path.append(dirname)

# -----------------------------------------------------------------------------
def _add_pythondirs_in_branch_to_syspath():
    """Adds pythondirs in the current branch to the sys path"""

    branch_path = _root_path_of_repo_branch()
    pythondirs = _pythondirs_in_branch(branch_path)
    _add_dirs_to_syspath(pythondirs)

# -----------------------------------------------------------------------------
def main(argv=None):
    """Read config & start app."""

    if argv is None:
        argv = sys.argv[1:]

    command_name = argv[0]
    if "test" in command_name:
        pass

    _add_pythondirs_in_branch_to_syspath()

    try:
        command = __import__(command_name)
    except ImportError, err:
        print "IMPORT ERROR : " + err.message
        return ERROR

    return command.main(argv)

if __name__ == "__main__":
    sys.exit(main())


问:
Governance models for multi-institution open source projects
I'm working on an open source project that has full time professional developers from several universities, plus a couple of other organisations. The product has something like a dozen deployments, various variations, plugins, related components etc. Generally development so far has been driven by institutions "scratching their own itch", but with an effort to merge improvements back to a central code base.

As it's starting to mature, I'm interested in possible models of open source governance to follow. (So this question isn't "what are some good things to do", it's specifically "what existing, tested models are worth looking at and possibly following")

Specific aspects that such models might cover:

How decisions about big-impact changes are made (and what happens if someone makes big changes without discussing them first)

Who manages the product's public image (product marketing, for want of a better term)

Who represents the product in any comparisons with "competing" products

Whether enhancements become "core", "plugins", "related products" etc

Whether and how roadmaps are created and published

How variations on the product are handled (in this case, versions for different academic disciplines)

Expectations and obligations of participants in the project

Expectations and obligations of the institutions for which those developers work

We'll be looking for something as lightweight and informal as practical.

答:
A good structure would be to have several lead developers (maybe one from each university/org) manage a repository that is easy to manage and control (GitHub is a good choice). Contributor releases would be done as pull-requests and then accepted by the lead developers.  There should be some basic rules posted to avoid debate.  An example rule would be that releases must have tests or require evidence of how the code was tested. Those rules should be published in the ReadMe.

A contributor or lead could be named the "marketing guy" and submit pull requests to the ReadMe and updates to the Wiki and be responsible for the roadmap, etc.

For versioning use a standard as much as possible that conveys minor changes versus breaking changes. Semantic versioning is a good model that is increasingly accepted for open source project.

Variations can be handled as branches and/or private forks and GitHub makes this easy as well.  This post discusses a nice model for branching using Git.

This may be too specific on the tooling but certainly these tools have been successful in maintaining many open source projects that are highly collaborative with multiple contributors.


问:
Convert list of 24-hour-precipitation values into total-by-hour
Let's say I have a list of precipitation values by hour, each showing how much rain happened in the prior 24 hours, ordered by date.  For example:

```<code>{
    '2012-05-24 12:00': 0.5, // .5" of rain from 5/23 12:00 - 5/24 11:59
    '2012-05-24 11:00': 0.6, // .6" of rain from 5/23 11:00 - 5/24 10:59
    '2012-05-24 10:00': 0.6, // .6" of rain from 5/23 10:00 - 5/24 09:59
    ...
    '2012-05-23 10:00': 0
}
</code>```

Is there a strategy/algorithm to determine how much rain fell in each of the hours?  I can't seem to wrap my head around this. I know that it's not as straightforward as just summing the diffs.

Visualization of Dataset

```<code>P(N)    [.....======================]
P(N-1)  [....======================.]
P(N-2)  [...======================..]
P(N-3)  [..======================...]
I want  [..........................=]
</code>```

Many thanks for any help.

答:
P(n) - P(n-1) Bounded to >= 0

Where P() is the amount of precipitation recorded for the 24 hours prior to n.

... should give you the amount of rain in the hour prior to P(n).


答:
First, the "self-calling functions" aren't actually self-calling. I know that's what people in the Javascript community call them, but it's really misleading; the functions never reference themselves, and in fact a lot of the time there's no way to call that particular function more than once. If they were actually self-calling functions, then recursive functions would have been the best way to name them.

What you really have are (usually) immediately executed lambdas whose results are stored in a variable in order to limit the scope of their internals. "IEL" isn't as catchy as "self-calling functions", so I guess that's why the real name never caught on.

The thing is though, that's entirely too low-level; it's an implementation detail that nobody cares about (it's like saying "here be for loops"). Generally, when you're using those immediate-execution functions, the reason why you're using them is because you're making some sort of a module, which needs its own namespace.

If that's the case, then instead of saying "self-executing functions", you should say "this script contains modules that do <stuff>". Otherwise, you should figure out what you're trying to do with the functions, and say that's what's in your script.

Now, the reason why you use modules in Javascript is because otherwise everything goes into the global scope. Those other functions you're writing, that aren't going to be inside the modules (or whatever you decide they are), are going to end up there. So use that - "this script file contains both modules that do <stuff> and global functions that do <more stuff>".


问:
Design: Sharing a class between multiple forms
This question relates to a question I asked earlier, which can be used for reference here:
Is this the best way to approach this design? Is this an example of MVC?

While coding, I came across a realization that I am not creating 'loose coupling'. The way I am trying to solve the problem right now is creating an instance of the Log Collector Class in MAIN and passing it around to each form classes constructor.

Now, in theory, the Log Collector Class needs to be instantiated only once for the whole program run-time. I was thinking about using a Singleton Pattern for this class, but than thought that if two forms need to update this class at the same time, there would be an issue.

What would be the best way to have the Log Collector Class be shared via multiple forms without instantiating a new version of the Log Collector Class each time?

I've done some research before posting this question and have read some people say using a static class for this type of design. However, this doesn't seem like loose coupling to me.

Another Question

Would an Interface for the Log Collector Class be best used here for all forms wanting to communicate with it? For example:

```<code>public interface LogCollectorInterface
{
    void SendLogMessage(string logMessage);
}
</code>```

Now when all forms want to communicate with the Log Collector Class, this is the only function they really need to use, SendLogMessage. Would instantiating the interface rather than the Log Collector Class be the best way to go about it?

FWIW, I am not sure if 'loose coupling' is the best direction is the way to go. It's one of those things I have caught on to while reading questions answered related to OOP. Being a new OOP programmer, it makes the most sense to me for both as an organizational standpoint and testing standpont.

Edit:
This will not be a multi-threading application so no two forms can update the log collector class at the same time.

答:
if two forms need to update this class at the same time, there would be an issue

Two forms can't update the same log collector object at exactly the same time unless they're in different threads. If you've got forms running in different threads but all sharing the same log collector object (or any other object), you need to think carefully about how to keep the log collector in a consistent state. That could get pretty complicated.

One common solution to this type of problem involve using a mutex to prevent two threads from both making changes at once. Another is to have the threads post messages to a queue that the log collector can then process in sequence. Before you jump into trying to solve the problem, though, read up on multithreaded programming. It's easy to go wrong here, and notoriously difficult to debug thread interaction problems.


答:
you need to iterate through the data until you find a 0 precipitation period  then you calculate forward from that point as SnOrus describes. If no data point is 0 then I don't think this can be solved unless you define the earliest entry to be 1 hour after the beginning of time so points earlier than that are undefined.

it would also be possible to calculate backwards in time from a 0 reading, doing the same thing in reverse (though you will get at least 24 0s in a row.

Title: Convert list of 24-hour-precipitation values into total-by-hour

Body:
Let's say I have a list of precipitation values by hour, each showing how much rain happened in the prior 24 hours, ordered by date.  For example:

```<code>{
    '2012-05-24 12:00': 0.5, // .5" of rain from 5/23 12:00 - 5/24 11:59
    '2012-05-24 11:00': 0.6, // .6" of rain from 5/23 11:00 - 5/24 10:59
    '2012-05-24 10:00': 0.6, // .6" of rain from 5/23 10:00 - 5/24 09:59
    ...
    '2012-05-23 10:00': 0
}
</code>```

Is there a strategy/algorithm to determine how much rain fell in each of the hours?  I can't seem to wrap my head around this. I know that it's not as straightforward as just summing the diffs.

Visualization of Dataset

```<code>P(N)    [.....======================]
P(N-1)  [....======================.]
P(N-2)  [...======================..]
P(N-3)  [..======================...]
I want  [..........................=]
</code>```

Many thanks for any help.


答:
Assuming that the data set always consists of consecutive 24-hour windows (i.e., the first data point isn't a 1 hour window)...

This is not a solvable problem at least in the general case because there exists a counterexample where at least two rain patterns map to one data set.

Case 1: It rains 24" at 12:30 a.m. every day forever.

Case 2: It rains 1" at 30 minutes past every hour forever.

In both cases, your P(N) = 24" for all N.

Since there is no one scenario that can be derived from this one data set, the problem is not solvable in the generic sense.

As an aside, we can also demonstrate that it's not necessarily true that the problem is always unsolvable. Most simply, if P(N) = 0" for all N, there is only one possible rain pattern to account for it: zero inches of rain at every hour.

It is therefore the more interesting problem to identify what characteristics about the data set make the problem solvable. Trivially, if you have a data set with at least one N such that P(N) = 0", then you have a solution.

I would not be surprised if there were other properties that would make the problem solvable for a given data set. Finding those should be a fun challenge. At the same time, proving that none can exist is equally entertaining.


答:
To my way of thinking, the focus on specific technologies is a mistake. I still list my Rexx experience, not because I think anyone today would be looking for it, but because I want to highlight my capacity to move fluidly in different languages, even after 19 years in I.T.

No, I probably could not fluently white-board some of the languages I list. But, give me half a day, and I could write the same script in any 3 of them (your choice).

To me, the real question is, can you take advantage of the tech in front of you (whatever that may be), to put good ideas into action in a way that benefits the company, and makes your job challenging and enjoyable?

That's a tough question to answer, just based on reading a list of "what you already know".


答:
This isn't a full answer, I'm at work and have already spent a bunch of time on it...further I'd need more data to see if my hunch is correct.

Let's call P(x) the 24 hour measure at time x.

Considder the following overlap scenario:

```<code>|H1|H2|H3.............|H23|H24|H25|H26 ................ |H46|H47|H48|
|-----------------P(X)--------|-----------------P(X-24)-------------|
   |----------------------P(X-1)--|
</code>```

P(X) - P(X-1) + H25 = H1.

Thus you need to calculate H25.  I believe that the solution is going to rest somewhere in a system created from P(X), P(X-1), and P(X-24).

Body:
This isn't a full answer, I'm at work and have already spent a bunch of time on it...further I'd need more data to see if my hunch is correct.

Let's call P(x) the 24 hour measure at time x.

Considder the following overlap scenario:

|H1|H2|H3.............|H23|H24|H25|H26 ................ |H46|H47|H48|
|-----------------P(X)--------|-----------------P(X-24)-------------|
   |----------------------P(X-1)--|

P(X) - P(X-1) + H25 = H1.

Thus you need to calculate H25.  I believe that the solution is going to rest somewhere in a system created from P(X), P(X-1), and P(X-24).


答:
While coding, I came across a realization that I am not creating 'loose coupling'. The way I am trying to solve the problem right now is creating an instance of the Log Collector Class in MAIN and passing it around to each form classes constructor.

This is the best way to go.

A singleton will work, but carries with it all sorts of risks as your application grows, especially if you intend to implement unit tests.

The biggest problem with a singleton is it will be available to every single class in your application, not just the ones you've allowed access to it. And, as you'll see below, you can no longer segregate access to certain functionality by interface.

but than thought that if two forms need to update this class at the same time, there would be an issue.

This applies whether it's a Singleton or a single instance held by each form. But, if it's the form sending the message then, even in a multi-threaded application, this will all take place in the UI thread, so it isn't an issue.

If there's any danger whatsoever then a simple lock() will solve the problem for you.

Would an Interface for the Log Collector Class be best used here for all forms wanting to communicate with it?

Yes. Definitely. Even if you extend your mediator later to receive multiple messages from each form, have multiple interfaces and hold the same object in each field.

eg. (notice how a singleton isn't so attractive now?)

```<code>public class FooForm : Form
{
    private ILogCollector _logCollector;
    private IDataRequestor _dataRequestor;

    public FooForm (FormMediator mediator)
    {
        _logCollector = mediator;
        _dataRequestor = mediator;
    }

    // Stuff here
}
</code>```

This way, if another form can only log exceptions and not request data, you needn't expose that functionality to the form.

This is the "I" in SOLID: Interface Segregation Principle.

Title: Design: Sharing a class between multiple forms

Body:
This question relates to a question I asked earlier, which can be used for reference here:
Is this the best way to approach this design? Is this an example of MVC?

While coding, I came across a realization that I am not creating 'loose coupling'. The way I am trying to solve the problem right now is creating an instance of the Log Collector Class in MAIN and passing it around to each form classes constructor.

Now, in theory, the Log Collector Class needs to be instantiated only once for the whole program run-time. I was thinking about using a Singleton Pattern for this class, but than thought that if two forms need to update this class at the same time, there would be an issue.

What would be the best way to have the Log Collector Class be shared via multiple forms without instantiating a new version of the Log Collector Class each time?

I've done some research before posting this question and have read some people say using a static class for this type of design. However, this doesn't seem like loose coupling to me.

Another Question

Would an Interface for the Log Collector Class be best used here for all forms wanting to communicate with it? For example:

```<code>public interface LogCollectorInterface
{
    void SendLogMessage(string logMessage);
}
</code>```

Now when all forms want to communicate with the Log Collector Class, this is the only function they really need to use, SendLogMessage. Would instantiating the interface rather than the Log Collector Class be the best way to go about it?

FWIW, I am not sure if 'loose coupling' is the best direction is the way to go. It's one of those things I have caught on to while reading questions answered related to OOP. Being a new OOP programmer, it makes the most sense to me for both as an organizational standpoint and testing standpont.

Edit:
This will not be a multi-threading application so no two forms can update the log collector class at the same time.

Body:
While coding, I came across a realization that I am not creating 'loose coupling'. The way I am trying to solve the problem right now is creating an instance of the Log Collector Class in MAIN and passing it around to each form classes constructor.

This is the best way to go.

A singleton will work, but carries with it all sorts of risks as your application grows, especially if you intend to implement unit tests.

The biggest problem with a singleton is it will be available to every single class in your application, not just the ones you've allowed access to it. And, as you'll see below, you can no longer segregate access to certain functionality by interface.

but than thought that if two forms need to update this class at the same time, there would be an issue.

This applies whether it's a Singleton or a single instance held by each form. But, if it's the form sending the message then, even in a multi-threaded application, this will all take place in the UI thread, so it isn't an issue.

If there's any danger whatsoever then a simple lock() will solve the problem for you.

Would an Interface for the Log Collector Class be best used here for all forms wanting to communicate with it?

Yes. Definitely. Even if you extend your mediator later to receive multiple messages from each form, have multiple interfaces and hold the same object in each field.

eg. (notice how a singleton isn't so attractive now?)

public class FooForm : Form
{
    private ILogCollector _logCollector;
    private IDataRequestor _dataRequestor;

    public FooForm (FormMediator mediator)
    {
        _logCollector = mediator;
        _dataRequestor = mediator;
    }

    // Stuff here
}

This way, if another form can only log exceptions and not request data, you needn't expose that functionality to the form.

This is the "I" in SOLID: Interface Segregation Principle.


问:
Who created the idea(s) of the first loop constructs?
```<code>while (1) {
      if (1+1==2) {
             print "Yes, you paid attention in Preschool!";
      } else {
             print "Wait... I thought 1+1=2";
      }
 }
</code>```

As a developer, we all have to use loops very frequently. We know that. What I was wondering was, who thought of the idea to have loops? What language introduced loops? What was the first loop construct? Was it a while loop? A for loop? etc?

答:
Assuming you mean modern text computer programming languages.

Algol60 has "FOR", "DO", "UNTIL" and "WHILE", so it was before 1960.

The Retro Computing Museum has a few languages pre 1960.

Kvikkalkul, the language from the '50s for programming Swedish nuclear subs only has GOTO. (However, Kvikkalkul is almost certainly a hoax from the '90s, not a real historical language.)

Plankalkül by Konrad Zuse is the earliest I could find. It has a "für" construct.


答:
For two consecutive hours n (now) and n-1 (the hour before now), you have the twenty-four hour precipitation sum (T) made up of 24 hourly precipitation numbers (P):

```<code>T(n) = P(n) + P(n-1) + P(n-2) + ... + P(n-22) + P(n-23)
T(n-1) = P(n-1) + P(n-2) + P(n-3) +... + P(n-23) + P(n-24)
</code>```

So:

```<code>T(n) - T(n-1) = P(n) - P(n-24)
</code>```

(Terms P(n-1)...P(n-23) are duplicated in both T(n) and T(n-1), so subtracting them gives 0.)
Rearranging, you get:

```<code>P(n) = T(n) - T(n-1) + P(n-24)
</code>```

Now, you can't figure out what P(n) is unless you know what P(n-24) is. You can go further back in the data to calculate P(n-24), but to get that you need P(n-25) and so on ad infinitum. What you need, then, is the precipitation value for any single hour that's longer ago than 24 hours. If you have that, you can calculate the hourly precipitation for all the subsequent hours.

Body:
For two consecutive hours n (now) and n-1 (the hour before now), you have the twenty-four hour precipitation sum (T) made up of 24 hourly precipitation numbers (P):

T(n) = P(n) + P(n-1) + P(n-2) + ... + P(n-22) + P(n-23)
T(n-1) = P(n-1) + P(n-2) + P(n-3) +... + P(n-23) + P(n-24)

So:

T(n) - T(n-1) = P(n) - P(n-24)

(Terms P(n-1)...P(n-23) are duplicated in both T(n) and T(n-1), so subtracting them gives 0.)
Rearranging, you get:

P(n) = T(n) - T(n-1) + P(n-24)

Now, you can't figure out what P(n) is unless you know what P(n-24) is. You can go further back in the data to calculate P(n-24), but to get that you need P(n-25) and so on ad infinitum. What you need, then, is the precipitation value for any single hour that's longer ago than 24 hours. If you have that, you can calculate the hourly precipitation for all the subsequent hours.


问:
How close have we gotten to automating code writing?
And I don't mean Autocomplete or automatic code snippets as inserted by modern day editors, or polymorphic code. But what is the state-of-the-art in programs that can go through given inputs and types and information of the desired outputs and output a valid piece of code in a language of choice. I am aware of Genetic Programming, Gene Expression Programming but I don't know of any other efforts. Also googling doesn't turn up much.

Is anyone aware of any advancements on this front?

Edit: When i say "output a valid piece of code", I mean an AI or something similar working out the logic and the flow of control and implement it in an imperative language. Imperative language only, since that's the tough part. Nevertheless, if you know of any new languages being developed to support this kind of idea, please do mention, as maybe our current set of languages are not suitable for the kind of early AI we may first chance upon.

答:
We're already there! All what we need is a language with today called homo-iconic character and decades earlier "code is data". Define your own environment by bottom-up programming instead designing top-down. You could for instance build your own DSLs inside Lisp. With the approach of Stacking you could putting as much DSLs (layers) on top of each other as you would need for your specific problem. This approach brings you from a very low level representation of S-expressions up to the most complex data abstraction you can ever think of.
So, what is automatic code writing, if not stacking one language on another?</p>