问:
Why do Core Data sqlite table columns start with 'Z'?
I was looking at the sqlite table that Core Data generates and noticed that all table columns start with 'Z'. I realize this is an implementation detail, but I was curious as to why that's the case and if there was a design decision involved in this. Anyone happen to know or guess why?

Here's a sample schema output of Core Data sqlite database:

```
sqlite> .schema
CREATE TABLE ZPOST ( Z_PK INTEGER PRIMARY KEY, Z_ENT INTEGER, Z_OPT INTEGER, ZPOSTID INTEGER, ZUSER INTEGER, ZCREATEDAT TIMESTAMP, ZTEXT VARCHAR );
CREATE TABLE ZUSER ( Z_PK INTEGER PRIMARY KEY, Z_ENT INTEGER, Z_OPT INTEGER, ZUSERID INTEGER, ZAVATARIMAGEURLSTRING VARCHAR, ZUSERNAME VARCHAR );
CREATE TABLE Z_METADATA (Z_VERSION INTEGER PRIMARY KEY, Z_UUID VARCHAR(255), Z_PLIST BLOB);
CREATE TABLE Z_PRIMARYKEY (Z_ENT INTEGER PRIMARY KEY, Z_NAME VARCHAR, Z_SUPER INTEGER, Z_MAX INTEGER);
```

答:
It is the naming convention chosen to be used in Core Data SQLite.

There are several reasons why it was chosen. One of the main reasons is Z is one of the least used letters of the alphabet so they surely felt by pre-fixing table names and entity names with Z they open more options for developers to name their own tables with fewer chances of stomping on someones naming conventions already.

Finally by using Z and all caps the Core Data tables are easier to spot and calls the entity objects out. In one comment in the question Mike mentioned that he also names his tables with a z so they sort the bottom. This might also have been a consideration.


问:
Creating a text input simplifaction tool
I have been working on a project for several months now to write a web-based tool that will help me at work. I work at a call center and the CRM software that is used is wretched, we basically have to input all of our information into notepad templates and then paste it in to a description box.

My initial goal was to create a web-interface for the templates so that I didn't have to use notepad anymore. I was just going to write it with HTML5/CSS/JS, both as a learning experience and, if I was fortunate enough, an opportunity for advancement.

As I worked on coding this tool I continuously found myself changing the foundation of the project, attempting to integrate more functionality in my tool. It has gotten to the point where I want the tool to be used alongside the CRM software for every call I receive. I want to be able to simply copy the customer's information off of CRM (simply with Ctrl + A/Ctrl + C), then be able to paste the block of jumbled text into a text box. The program will then pick out the customer's info by looking for keywords in specific positions to fill out a user selected template. The rest of the information is input manually and then the output is generated with the push of a button. The information will also be parsed into a backup text file. The text file will be created automatically based on the date. If the text file for the current date exists, it will simply concatenate the info.

As I wrote my code I found myself getting distracted looking at different coding languages and possibilities. I kept looking back at what I had completed and I was disappointed, I've started over from scratch two times now.

Now for the actual question: I am thinking of starting over, writing my program with AngularJS. I like the idea of a smooth, single page, app-like interface, but I'm scared of hitting more barriers and starting over using something else. Based on my description of how I want my program to run, can anyone suggest how to go about implementing this? Should I look into a different language, or is JS really the way to go these days? I just discovered Dart and am intrigued, but the idea of learning yet another language is discouraging instead of exciting. I feel like I'm missing a pretty big point.

I hope this question is appropriate for this forum. I feel a bit lost with StackExchange, and the last thing I want to do is receive negative attention for a bad post. I'm just feeling a bit lost when it comes to this project, and perhaps even programming in general. Regardless, any feedback will be appreciated. Even direction to a forum for emotionally distraught fledgeling programmers would be a welcome answer. >.<

Thank you.

答:
To me it sounds like you're experiencing scope creep. That is, the scope of your app is expanding without you having "delivered" anything usable at all. If that is the case, you might want to step back and meditate on it.

As your question about languages/frameworks, JS really is the only thing you have to work with on the front-end. Now, that doesn't mean that you have to write "raw" JS: consider using a language that compiles to JS, like CoffeeScript, which is much closer to JS then Dart. It's based on JS with some nice syntactic sugar sprinkled on top.

Good luck!

ContentLicense: CC BY-SA 3.0


问:
What is the most egregious waste of money you have seen, and what did you do about it?
Often we as programmers see large organisations wasting huge sums of money on bloated and inefficient solutions to problems. This pains me greatly because I like organisations to benefit from best of breed solutions. However, my abilities as a programmer are limited when it comes to influencing the key decision makers and often my perspective on the matter is constrained to my own little technical world.

So, my question is this. After encountering an egregious waste of money on some software and/or hardware that really got your goat, what did you do about it to get it fixed or were you doomed to bite the bullet and mutter forever under your breath? I'm interested in hearing your overall experiences and especially what lessons you learned about how to tackle this sort of thing in the future. Let's not name names, the experience of how to tackle the problem is more important than the actual offending product.

答:
Let's see, we once spent well over half a million dollars doing the work to win a million dollar contract. So much for the profit on that one. Some of us on the project proposal development team tried to point this out but it had become a thing of pride for our little company to win over the Fortune 500 companies we were competing with. We did win and lost money hand over fist onteh contract for that and other reasons but we had bragging rights.

As a government contractor once, I was forced to work unpaid overtime because the contract allowed it and the contractor got paid for my overtime. Not only that I was caught up on my work and spent 4 hours every Sunday surfing the Internet with no work to do. Needless to say I moved on very quickly after they started that nonsense.

Buying Clarity as our project management system, a commercial app that is so bad, 100% of the people who use it have begged to go back to our old home grown system (the one guy who liked and chose it has moved on to some other company), people even volunteered to work on their own time to add the reporting they wanted to our old system. But we have invested the money so we are stuck with it. In other words, refusing to ditch something that doesn't work just because it was expensive.

ContentLicense: CC BY-SA 2.5


问:
How to write useful Java programs without using mutable variables
I was reading an article about functional programming where the writer states

```<code>(take 25 (squares-of (integers)))
</code>```

Notice that it has no variables. Indeed, it has nothing more than three functions and one constant. Try writing the squares of integers in Java without using a variable. Oh, there’s probably a way to do it, but it certainly isn’t natural, and it wouldn’t read as nicely as my program above.

Is it possible to achieve this in Java? Supposing you are required to print the squares of first 15 integers, could you write a for or while loop without using variables?

Mod notice

This question is not a code golf contest. We are looking for answers that explain the concepts involved (ideally without repeating earlier answers), and not just for yet another piece of code.

答:
The easiest way to find that out would be feed the following to the Frege compiler, and look at the generated java code:</p>

```<code>module Main where

result = take 25 (map sqr [1..]) where sqr x = x*x
</code>```

Body:
The easiest way to find that out would be feed the following to the Frege compiler, and look at the generated java code:

module Main where

result = take 25 (map sqr [1..]) where sqr x = x*x


问:
Sell code using dynamically linked Open Source GPL code?
I am really confused.

The GPL states that if you start with GPL code, and modify that code, that you must release your code with modifications free of charge also under a GPL.

But what if you simply use the existing GPL code without modifications as a library? Can you then write software to interface with that code, unchanged, that is closed source?

答:
You cannot use GPL code in proprietary software without making your proprietary code become "infected" by the GPL license. Your code would then become GPL code as well. It doesn't matter if you've modified the GPL code or not. If your code uses it, it too becomes GPL code.

Thus, if you're building any kind of software where it's important that your code remain proprietary, then do not use GPL code.

However, this isn't to say that corporate entities cannot make a profit using GPL code.  If you focus on building solutions that help you provide better services to customers or that fill a need that requires your continual involvement in support of the software, then you can charge service fees.  For instance, the Android operating system is open source, yet Google, Amazon, Verizon, AT&T, and other entities make money from it everyday because they bill for services rendered, not for selling the software.

Also, this helps hardware companies like Motorola and Samsung sell their devices, as they use Android as well.

Also, building on the "service" case and what Martin Beckett mentions in the comments, if the code you're using is something that will be used internally only and not distributed to the outside world, you can use GPL code without having to release it to the world.

It's always your choice whether or not to release the product, but if you do release the product, you must release both binaries and code as per the terms of the GPL.


问:
Should you version web applications?
I've recently had a discussion with a coworker about versioning web applications.

I don't think you need it at all, and if you just want a sanity check to confirm your latest release is live, I think a date (YYMMDD) is probably good enough.

Am I off base?  Am I missing the point?  Should I use web application version numbers

答: If you have a dev/test instances it is pretty important for project team members to able to see which build/revision they are testing.</p>

Title: Should you version web applications?


答:
The GPL dictates that derivative works must be released under a GPL compatible license (if  released). That said, there's some ambiguity as to what exactly constitutes a derivative work and technically there are ways to use GPL'ed code in proprietary projects without the project becoming "infected" (emphasis mine):

Can I release a non-free program that's designed to load a GPL-covered plug-in?

It depends on how the program invokes its plug-ins. For instance, if the program uses only simple fork and exec to invoke and communicate with plug-ins, then the plug-ins are separate programs, so the license of the plug-in makes no requirements about the main program.

If the program dynamically links plug-ins, and they make function calls to each other and share data structures, we believe they form a single program, which must be treated as an extension of both the main program and the plug-ins. In order to use the GPL-covered plug-ins, the main program must be released under the GPL or a GPL-compatible free software license, and that the terms of the GPL must be followed when the main program is distributed for use with these plug-ins.

If the program dynamically links plug-ins, but the communication between them is limited to invoking the ‘main’ function of the plug-in with some options and waiting for it to return, that is a borderline case.

Using shared memory to communicate with complex data structures is pretty much equivalent to dynamic linking.

See also the question I am writing free software that uses a non-free library.

Personally, I'd contact the FSF with details of the project and ask for clarifications before using the GPL'ed code. If the FSF attests that you can't use the GPL'ed code, I'd then contact the original author of the code and ask them (really nicely) for a LGPL version of it. The chances are extremely slim, but you never know.

Title: Sell code using dynamically linked Open Source GPL code?

Body:
I am really confused.

The GPL states that if you start with GPL code, and modify that code, that you must release your code with modifications free of charge also under a GPL.

But what if you simply use the existing GPL code without modifications as a library? Can you then write software to interface with that code, unchanged, that is closed source?


问:
What is 'code skew'?
In the O'Reilly book on Scala, I read that copy-pasting of code creates:

... creates issues of code-bloat, maintainability and skew,

I can't see any obvious definitions of the word skew in context. I am aware of the problems of copy-pasting, but I can't make them fit with the word 'skew'. Since this is used in an O'Reilly book I'm guessing it's a real programming term in circulation.

Any pointers?

答:
Skew in its most traditional definition means out of alignment (not parallel). Obviously when code is copied and pasted the two copies are identical and parallel. This is not an invariant. Changes made to one copy is not guaranteed to make it to the other copy (due to carelessness or ignorance). Now there are two versions of code existing in two different places that are skewed (no longer the same). This can lead to weird bugs when behavior seems to work in one place and not in the other. Keep your code DRY (don't repeat yourself).

EDIT/ADDITION: If you have an urge to copy and paste, more than likely what you should do is abstract the code you are copying into a shared superclass (object oriented) or some sort of included utility function (functional).

OwnerDisplayName: Joe

Title: What is 'code skew'?

OwnerDisplayName: Patrick James McDougle


答:
You should version your web application with the build id from your build server and have that  id enclosed in all bug reports.

This will allow you to go  back in time in case you have to fix a bug reported on an older version not currently present in production.

Title: Should you version web applications?

Body:
I've recently had a discussion with a coworker about versioning web applications.

I don't think you need it at all, and if you just want a sanity check to confirm your latest release is live, I think a date (YYMMDD) is probably good enough.

Am I off base?  Am I missing the point?  Should I use web application version numbers


问:
Backquoted symbols, good or bad?
I'm designing a programming language which has three kinds of quoted entities: strings and characters as in C, and symbols (interned strings intended for use as lookup keys and such) which I consider one of the most endearing features of Lisp. Currently I have the following syntax for these:

```<code>"*" // String
'*' // Character
`*` // Symbol
</code>```

which I quite like, but has a couple of potential problems:

I'm told that on some keyboard layouts, backquote is a nuisance to type.

Backquote and ' are not the most visually distinct of characters, and I have a few times found myself typing ' when I meant backquote. On my setup this is not a problem because I have UltraEdit syntax highlighting set up to show backquoted symbols in green so the mistake is instantly apparent, but of course I can't provide syntax highlighting for most of the editors people use, so at least in the early days most users won't have the benefit of that kind of special coloring.

So, given these potential problems, I'd like to get some feedback on which option people consider preferable:

Keep the syntax the way I have it now.

Swap backquote and ', so that ' is used for symbols and backquote is used for character constants.

Use ' for symbols, @"*" for character constants (in e.g. the Linux kernel code, character constants are something like thirty times rarer than string constants, so it's arguably okay to give them slightly more verbose syntax) and backquote for something else, perhaps raw (most escape codes not interpreted) strings.

Use ' for symbols, @"*" for character constants and forswear the use of backquote entirely.

答: Since an instance of the char type is only one character long, do you really need to enclose it in matching marks?  If you bracket symbols in apostrophes, you can use only a single backquote to precede a char.  If the user mixes them up, large syntax error messages follow, like when a C programmer forgets a closing brace. </p>

Title: Backquoted symbols, good or bad?


问:
I'm writing about language syntax. Is there a language out there in which parameters are placed inside method name?
in JavaScript:

function getTopCustomersOfTheYear(howManyCustomers, whichYear) {
   // Some code here.
}
getTopCustomersOfTheYear(50, 2010);
```

<p>in C#:</p>

<pre class="lang-cs prettyprint-override"><code>public List<Customer> GetTopCustomersOfTheYear(int howManyCustomers,
 int whichYear)
{
   // Some code here
}
List<Customer> customers = GetTopCustomersOfTheYear(50, 2010);
</code>```

in PHP:

public function getTopCustomersOfTheYear($howManyCustomers, $whichYear)
{
   // Some code here
}
$customers = getTopCustomersOfTheYear(50, 2010);
```

<p>Is there any language out there which support this syntax:</p>

<pre class="lang-c prettyprint-override"><code>function GetTop(x)CustomersOfTheYear(y)
{
    // Some code here
}
returnValue = GetTop(50)CustomersOfTheYear(2010);
</code>```

Isn't it more semantic, more readable form of writing a function?

Update: The reason I'm asking this question is that, I'm writing an article about a new syntax for a new language. However, I thought that having such syntax for declaring methods could be nicer and more friendly to developers and would decrease learning-curve of the language, because of being more closer to natural language. I just wanted to know if this feature has already been contemplated upon or not.

答:
Inform 7.

```<code>To create (employee - a person) being paid (salary - a number):
    say "Welcome to your new job, [name of employee]!";
    choose a blank row from the table of employees;
    now the paid entry is the salary;
    now the name entry is the name of the employee.
</code>```

And so on.

Body:
Inform 7.

To create (employee - a person) being paid (salary - a number):
    say "Welcome to your new job, [name of employee]!";
    choose a blank row from the table of employees;
    now the paid entry is the salary;
    now the name entry is the name of the employee.

And so on.


问:
Handle invalid text on server or fix on client in Client-Server application
I have developed a protocol for a Client-Server application and developed it in conjunction with another developer.  The client application at this moment is written for the mobile phone.

The protocol uses comma separated fields with start and end deliminators.  Because some of our fields are free form ASCII text we are byte stuffing the fields so that special characters can be handled within and not mess up our data parsing.

The problem is that one field has been byte stuffed when it shouldn't have been.  The field in question was to represent coordinates i.e.

```<code>    <rest of data packet>, <lat>,<lng>,....

where
<lat>:   Latitude coordiantes i.e. -37.6543
<lng>:   Longtitude i.e. 90.8993
</code>```

However what we I recieved on the server was the byte stuffed character for a comma appearing in the dot field i.e. -37^-6543.  This in turn caused the server to ignore the packet and not record the details.

Reason:
When I mentioned this to the phone developer he said it was because the character settings on the phone meant that the user had changed the dot to a comma.  It was his belief that we should handle this on the server.  However I'm not sure.  I have a thought that clients should follow the protocol as in theory there could be different clients connecting and the server doesn't want to have special cases littered in it's code base?

Question:
So some options I see are (and I'm not sure how to approach this):

Get all clients to send the data as per for the protocol spec and keep the data format black and white so to speak

Have the server handle a variety of options in this case

In conjunction with 2 adjust the protocol document so that data is more flexible in some cases and the server is responsible for handling the different cases

答:
So the question is: should you change the protocol to be more flexible (allowing variations of the format), or should the clients adhere to what you currently have?

I don't think there is a one size fits all solution here, the answer is totally up to the parties involved to negotiate. All have to agree on the protocol (the current one or something more flexible), and then all client applications must implement it correctly otherwise they cannot expect the server to handle malformed requests well.

That said, it seems reasonable to expect clients to implement the -37.6543 format instead of using byte stuffing as -37^-6543. I think the client should handle this and you should keep your current protocol.


问:
Git: rebasing on top of a refactor that affects the target rebase branch
Let's say I have a feature (topic) branch that I keep rebased on top of my development branch. During the course of the project (before merging in my feature branch), I decide that I need to make a large refactor to my project (for example, after updating a 3rd part module).

So I do this large refactoring on my development branch. Now I want to rebase my feature branch so I can take advantages of my refactoring.

The problem

There are still things in my feature branch that need refactored to match the changes I made in my development branch.

Should I:

Go back through my feature branch's history trying to edit commits (with rebase -i) to make the branch look as though all of the work had been done after the refactoring.

The advantage to this is that it keeps the history clean.

The disadvantage is that this can take a whole lot of time if the changes made in the development branch cause a lot of changes to need to be made in the feature branch.

Fix the things that need to be refactored in my feature branch and make a commit for this.

The advantage here is that it will be much easier to identify and fix things that need to be fixed

The disadvantage is that now the tree will have two commits in it for the refactor. One for the refactor done for the entire development branch, and a smaller commit done for the feature branch, once merged in it will look a little funny.

Which strategy should I go with?

An Example

Lets say on the development branch I rename functionA to functionB.

Now In my feature branch I've never modified the file containing functionA (now functionB in development). So when I run rebase development while on my feature branch it rebases cleanly.

The problem is if I've ever made a call to functionA in my feature branch, it's going to fail now since it was renamed functionB.

Now, should I just do a find and replace for functionA -> functionB and make one commit on the feature branch (option 2). Or should I go back through my history, finding where I introduced the call to functionA and rewrite the commit so it is introduced as calling functionB (option 1)?

答:
Basically, you shouldn't be using git branches for feature branches.

http://blog.newrelic.com/2012/11/14/long-running-branches-considered-harmful/

http://martinfowler.com/bliki/FeatureBranch.html

Indeed I see this as the decisive reason why Feature Branching is a bad idea. Once a team is afraid to refactor to keep their code healthy they are on downward spiral with no pretty end.

In the quoted text, Martin Fowler is using 'Feature Branching' specifically to mean 'using dvcs branching to manage large-feature development in a way where one dvcs branch maps to one feature'. Which lots of people do. Some of those people are in an environment where they never really need to refactor anything, some of them haven't been doing it long enough to hit the problems, a few have developed tools or procedures on top of git to work around the problems (http://dymitruk.com/blog/2012/02/05/branch-per-feature/), while others are simply in denial as to how much trouble it is causing them.

Thing is, just because an abstract concept and a tool feature have the same name doesn't make them a good match for each other. As you are finding, there isn't really a good way to use the two together, just a variety of less-bad ways.

So, assuming you do really need feature branches, then look through the features your tooling and platform support and find a better match.

Sticking with git, using forks and pull requests is one increasingly common strategy:

http://hintjens.com/blog:24

Worst case, even the humble if [config-setting] statement (known as a 'feature toggle') is very likely going to be a time-saver and quality-booster compared to where you are now.


问:
Is currying too complex a tool to actually use?
Today I feel like I finally grokked currying (in Javascript), and of course, like any programmer who has learned a new trick, my mind immediately began racing over how to improve my current codebase using it.

And again, like any programmer, the little voice shouting "[new trick] all the things!" was silenced by another saying, "[new trick] is really complex. maybe you shouldn't use it." Curry is sugar, essentially, after all.

I understand that there's nothing wrong with using a feature in moderation, especially one as mind-bending as currying, but for the sake of simplicity should I avoid using it if something equally as efficient is sufficient?

答:
Like all choices in engineering, there is a definite trade-off. What is the benefit of replacing your existing code with your new trick? Is the code easier to maintain, easier to read (which aids in maintainability), is it faster, etc. Also, what are the downsides? Are you working in a team and, if so, does using your knew trick reduce readability for various team members?

In the end, you have to list the pros and cons and determine what you think is best. If it is a issue of skill level within the team, then perhaps you can make efforts to train your team on the new technique and share your insight (your "aha" moment(s)). Then, once your team is better educated on the topic, you can make the decision as a team on how you should approach using this new trick.

If you are working on an open source project, then it could be argued that it is a good thing to stay away from code-uses that could trip up other programmers contributing to the project. Alternatively, it could be argued that you should use such tricks if the project has a good review process where misuse of your new trick could be seen.

And if this is simply a personal project, then do whatever makes you happy!

Hope that this helps! Happy coding!


答: Ever play the game Telephone as a kid? You know, the one where each person whispers a phrase to the next person in line and at the end, the last person says the phrase out loud and everyone laughs at how different it has become from the original? That's skew. When you copy and paste code, you inevitably make small changes in one or more of the copies. And the more often you copy and paste the same code, the more the changes build up and the code gets skewed away from the original. I've seen code with hundreds of copy and pasted blocks, each varying from the other by just a few characters, it's nearly impossible to maintain. If you find yourself wanting to cut and paste a section of code, you should probably at least consider putting it into its own function.</p>

Title: What is 'code skew'?

Body:
In the O'Reilly book on Scala, I read that copy-pasting of code creates:

... creates issues of code-bloat, maintainability and skew,

I can't see any obvious definitions of the word skew in context. I am aware of the problems of copy-pasting, but I can't make them fit with the word 'skew'. Since this is used in an O'Reilly book I'm guessing it's a real programming term in circulation.

Any pointers?


问:
Types in Lisp and Scheme
I see now that Racket has types. At first glance it seems to be almost identical to Haskell typing. But is Lisp's CLOS covering some of the space Haskell types cover? Creating a very strict Haskell type and an object in any OO language seems vaguely similar. It's just that I've drunk some of the Haskell kool-aid and I'm totally paranoid that if I go down the Lisp road, I'll be screwed due to dynamic typing.</p>

答:
CL type system is more expressive than the Haskell one, e.g., you can have a type (or (integer 1 10) (integer 20 30)) for a value 1,2,...9,10,20,21,...,30.

However, Lisp compilers does not force their understanding of type safety down your throat, so you can ignore their "notes" - at your own risk.

This means that you can write Haskell in Lisp (so to speak) by declaring all value types and carefully making sure that all the necessary types are inferred, but then it is easier to use Haskell in the first place.

Basically, if you want strong static typing, use Haskell or OCaml, if you want strong dynamic typing, use Lisp. If you want weak static typing, use C, if you want weak dynamic typing, use Perl/Python. Each path has its advantages (and zealots) and disadvantages (and detractors), so you will benefit from learning all of them.

Title: Types in Lisp and Scheme


答:
TL;DR: No

IMO Your question contains a bad assumption.

Bad assumption

there's nothing wrong with using a feature in moderation

This is the wrong way to look at a language and it's capabilities.  You should use whatever idiom, feature, etc, yields the shortest, most maintainable implementation that has reasonable performance for you/your team.  It should not be driven by how many times you've used it so far.  Programming decisions shouldn't be governed by an arbitrary limitation on the number of time you can use a particular construct on the belief that "this amount is okay, but one more is too much".

The Question

The question is "is currying to complex for you/your team?".  There are certainly many people for whom currying is not complicated and use it all the time. You mentioned you just learned it, so it is a valid question to ask yourself.  However, and this is the important bit, this is a question you must answer.  You should consider any external factors like deadlines, the cost of making mistakes (which will rise anytime you're using something unfamiliar), etc and weigh that against the benefits.

Complexity

Complexity is largely a function of familiarity.  Familiarity drives understanding.  When you are familiar with an concept it isn't any more or less complex than anything else.  Think about the notion of anonymous function, objects and types, and how complex they were when you first came across them. Conversely, if you never gain any familiarity with the concept, it is and will always remain complex.

Average Team Skill Level

The question of not using something because most of the team doesn't understand the concept is something I have considered in the past.  However I have always decided I would rather force people to learn and develop, rather than have everyone program to a "lower" common denominator.  In the past I have had to compromise the best implementation I could give for fear someone else will not be able to maintain/understand it.  Now that I can set policy this doesn't happen.

Title: Is currying too complex a tool to actually use?

Body:
Today I feel like I finally grokked currying (in Javascript), and of course, like any programmer who has learned a new trick, my mind immediately began racing over how to improve my current codebase using it.

And again, like any programmer, the little voice shouting "[new trick] all the things!" was silenced by another saying, "[new trick] is really complex. maybe you shouldn't use it." Curry is sugar, essentially, after all.

I understand that there's nothing wrong with using a feature in moderation, especially one as mind-bending as currying, but for the sake of simplicity should I avoid using it if something equally as efficient is sufficient?


问:
Stored Procedures a bad practice at one of worlds largest IT software consulting firms?
I'm working at a project in one of the world's top 3 IT consulting firms, and was told by a DBA that company best practice's state stored procedures are not a "best practice".  This is so contrary to everything I've learned.

Stored procedures give you code reuse, and encapsulation (two pillars of software development), security (you can grant/revoke permissions on an individual stored proc), protect you from SQL injection attacks, and also help with speed (although that DBA said that starting with SQL Server 2008 that even regular SQL queries are compiled if they are run enough times).

We're developing a complex app using Agile software development methodology.  Can anyone think of good reasons why they wouldn't want to use stored procs?  My guess was that the DBAs didn't want to maintain those stored procs, but there seem to be way too many negatives to justify such a design decision.

答:
I want to cover both some pro- and con- issues with stored procs.  We use them extensively with LedgerSMB, and our rule is, with a few very specific extension, "if it's a query, make it a stored proc."

Our reason for doing this was to facilitate cross-language query reuse. There isn't a better way to do this honestly.

In the end the question is always on the details.  Well used, stored procedures make things a lot easier, and poorly used they make things a lot harder.

So on to the con side.

As traditionally used, stored procedures are brittle.  Used alone they create the possibility of adding bugs to your code in places you didn't expect for no reason other than that the call syntax changed.  Used alone this is a bit of a problem.  There is way too much cohesion between layers and this causes problems.

Yes, it is possible to have intra-sproc sql injection if doing any dynamic sql.  It is a bad thing to be over-confident in this area, and consequently one needs to have significant experience in security in this area.

Changes to interfaces are somewhat problematic with stored procedures for reason #1 above but this can become a very big nightmare if large numbers of client apps are involved.

The above are pretty hard to deny.  They happen.  Everyone, pro-SP and anti-SP has probably had horror stories regarding these.  The problems aren't unsolvable but if you don't pay attention to them you can't solve them (in LedgerSMB we use a service locator to dynamically build SP calls at run-time, avoiding the above issues entirely.  While we are PostgreSQL only, something similar could be done for other db's).

On to the positives.  Assuming you can solve the above problems, you get:

The possibility of enhanced clarity in set operations.  This is particularly true if your query is very large or very flexible.  This also leads to enhanced testability.

If I have a service locator already working in this area, I find stored procedures speed up pace of development because they free up the application developer from db concerns and vice versa.  This has some difficulties in doing right but it is not that hard to do.

Query re-use.

Oh and a few things you should almost never do in an SP:

non-transactional logic.  You sent the email that the order was shipped but the transaction rolled back...  or now you are waiting to continue for the email server to come online.... or worse you roll back your transaction just because you can't reach the email server....

lots of little queries loosely strung together, sprinkled with procedural logic....


问:
"To code quickly, you must quit coding"
First off, not my phrase: http://www.whattofix.com/blog/archives/2010/11/to-code-quickly.php Props to Mr. Markham.

BUT, it got me to thinking about a lot of questions I have seen about being able to get things done.

The approach advocated (setting a timer for a set period, in this case 50 minutes, but I've seen people talk about breaking procrastination by setting times as short as five minutes on tasks that you just cannot bring yourself to do, and then taking a short break) seems to be common sense, but lots of people advocate getting into the "zone" and staying there as long as possible, maybe many hours, rather than break their groove.

I keep trying different approaches and find that each has its own strengths and weaknesses.

What kind of technique do you use to be more EFFECTIVE (i.e., getting work done to the quality level demanded by your client / boss / etc. in the time frame allowed) in your software development and not just to spend more time at the keyboard?

答:
I'm unimpressed with that essay; he spent what, one day trying out his new method?

That said, Pomodoro & similar techniques seem to have a persistent niche popularity. Typically I try to sort my days into "focus days" and "misc days". Focus days I show up in slightly more relaxed clothing, maybe a bit earlier (or stay later). I don't have any meetings those days, so I can basically write my own schedule, which lets me focus better. On the other days, I have meetings, appointments, and so forth. I won't have the time to concentrate, so I try to schedule smaller and easier tasks to fill my time in.

One good way to increase productivity in coding is code generation of any boilerplate bits; refactoring anything that gets duplicated, etc.

Title: "To code quickly, you must quit coding"


问:
How can I deal with a team member who dislikes making comments in code?
One of my team members consistently avoids making comments in his code.

His code is not self-documenting, and other programmers have a difficult time understanding his code.

I have asked him several times to comment his code, however he just gives excuses or claims that he will do it later. His concern is that adding comments will take too much time and delay the projects.

What argument can I present to him to convince him to properly document his code?

On that note, am I wrong to focus on the code comments or is this indicative of a larger problem which should be addressed?

答:
Maybe this guy needs to be given an appreciation of good coding discipline, and why it's important for other people to be able to understand code he's written.

I've worked on some truly awful codebases in my career, ones where the code was so badly organized, variable names were so poor, comments so bad or non existent, that the codebase harmed my productivity.  You can't work to fix or improve a codebase you don't understand, and if it's written in a way that's impenetrable to newcomers then they'll spend more time trying to understand it than actually working on it.

There's no better teacher than harsh experience!

Every codebase has some horrible bits lurking in it, parts of the system nobody wants to touch because they're afraid of breaking something, or they can't do any meaningful work on because whoever wrote the code has long-departed and taken their understanding of the code with them.  If that code is uncommented and not self-documenting then it only makes matters worse.

I suggest you find the bit of your codebase that's like that, and give your troublesome coder responsibility for it.  Give him ownership of it, make it his responsibility, let him learn the true pain of working on code that can't be maintained because it's not well documented or impossible to understand in a short space of time.  After a few months working on it, I'm sure he'll start to come around.


问:
Is changing the type of a variable partway through a procedure in a dynamically typed language bad style?
In Python (and occasionally PHP) where variables do not have fixed types, I'll frequently perform 'type transformations' on a variable part-way through my code's logic. I'm not (necessarily) talking about simple casts, but about functions that change the type of a variable while leaving it basically representing the same value or data.

For example, I might write code like this when doing a web request, using the response variable to store an addurlinfo object, then the string content of that object, and the dictionary returned by parsing the string as JSON:

```<code>response = urlopen(some_url)
assert response.info().type == 'application/json'

response = response.read()
logger.debug('Received following JSON response: ' + response)

response = json.loads(response)
do_something(response)
</code>```

(Okay, it's a slightly contrived example, but I think it demonstrates the idea fine). My feeling is that this is better than using three separate variable names because a) it conveys that the response variable contains basically the same information, just 'transformed' into a different type, and b) it conveys that the earlier objects aren't going to be needed any further down the function, since by reassigning over their variable I've made them unavailable to later code.

The tradeoff, I guess, is that the reader could become confused about what type the variable is at any given moment.

Is this bad style, and should I be using three different variables in the above example instead of reassigning to one? Also, is this standard practice in dynamically typed languages, or not? I haven't seen enough of other people's code to know.

答:
I know that you are reading from a URL in your example, but if you tried the same thing with a file you would not be able to close the file because response is no longer pointing to the file, it is now holding a sting you retrieved from the file.

That is the big danger, you might forget what value it holds because it changes during the life of the program or module. It will be confusing for somebody reading your code because they will never know what value type it is holding.

These are the fun bugs try and squash.


答:
In general, I'd say yes, it is bad style, but that there are cases when it's necessary and useful to reuse a variable; I'd just recommend avoiding casual, lazy use of it.

The problem with your example isn't because of dynamic typing, but because you use the same variable to refer to three different things.  This code is less clear to me because when I read it, I have to think much harder to figure out what response refers to.

You could do something similarly nasty in a statically typed language such as Java (with the restriction that the different things are related through a type hierarchy).  The key point is that using a single variable to point to different objects can be confusing, regardless of type system.

Title: Is changing the type of a variable partway through a procedure in a dynamically typed language bad style?

Body:
In Python (and occasionally PHP) where variables do not have fixed types, I'll frequently perform 'type transformations' on a variable part-way through my code's logic. I'm not (necessarily) talking about simple casts, but about functions that change the type of a variable while leaving it basically representing the same value or data.

For example, I might write code like this when doing a web request, using the response variable to store an addurlinfo object, then the string content of that object, and the dictionary returned by parsing the string as JSON:

```<code>response = urlopen(some_url)
assert response.info().type == 'application/json'

response = response.read()
logger.debug('Received following JSON response: ' + response)

response = json.loads(response)
do_something(response)
</code>```

(Okay, it's a slightly contrived example, but I think it demonstrates the idea fine). My feeling is that this is better than using three separate variable names because a) it conveys that the response variable contains basically the same information, just 'transformed' into a different type, and b) it conveys that the earlier objects aren't going to be needed any further down the function, since by reassigning over their variable I've made them unavailable to later code.

The tradeoff, I guess, is that the reader could become confused about what type the variable is at any given moment.

Is this bad style, and should I be using three different variables in the above example instead of reassigning to one? Also, is this standard practice in dynamically typed languages, or not? I haven't seen enough of other people's code to know.


答:
Internal use only with limited install base?

Or liable to have multiple versions in the wild?

We only have the former so only use the version number for sanity checking post release. We don't have to track many versions in use at the same time.

Title: Should you version web applications?


问:
Distributing cron-like tasks over multiple servers
Currently I'm using something like a master-cron server, which starts the tasks on the slave-worker servers.

But there are so many tasks, that the timing gets lost entirely.

Is there a an algorithm, which eliminates the single master?

答:
You might think about using a framework to run your cron tasks in this fashion. What immediately comes to mind is Capistrano. It is a ruby framework for doing deployments, but the general principal is that you can connect to remote machine via SSH and run arbitrary commands in a transactional way.

So, you could have a master box that has capistrano installed and from there you could setup a cron-task to run your capistrano script which will SSH into the other machines and then execute the command that you would like to run as cron. You could even configure things like pulling the latest copy of the script from a Git repo and then running so that deploying script-updates would be super simple.

You can also write your own extensions for Capistrano to do various things. The only downside is that you have to become familiar with the framework and learn/know Ruby to really be effective with it.

Update

I just realized what you were asking and my answer does not solve that particular problem. However, you can still use the technology to solve your problem by managing multi-server deployments with Capistrano. Rather than have a mastser-slave relationship, just have each server run their own tasks. Capistrano should take care of deploying new or updated scripts and should make the maintenance problem of having all the servers run their tasks dissapear.


问:
Is it possible to modify Lamport's mutual exclusion algorithm to work without a FIFO guarantee?
I'm trying to implement a modified version of the Lamport Mutual Exclusion algorithm. The original algorithm assumes FIFO message ordering between connected systems, but I would like to use <s>UDP</s> a protocol which does not guarantee FIFO. Is it possible to modify this algorithm to work without FIFO?

EDIT: Forget UDP. Just assume it is some protocol where the only problem is that FIFO is not guaranteed. That is the only problem I'm concerned with right now.

答:
Order is the least of your problems.  Not only does UDP not guarantee delivery order, it doesn't guarantee delivery at all.

Lamport's algorithm requires cooperation of all non-requesting processes that would contend for a resource in the form of replies.  The loss of a datagram carrying a request would cause the other processes not to send replies.  That or the loss of a single reply would cause the requester to wait indefinitely for something which never arrives.

The only way to modify the algorithm so it would work over an unreliable channel would be to use the same techniques used to implement reliable channels.  My advice would be to re-evaluate whether you want to re-invent that wheel or simply switch to TCP, which (reliably) does all that work for you.


问:
Why is the use of the STE template no longer recommended for EF5?
I was looking to upgrade my project from EF4.1/Framework 4.0 to EF5/Framework 4.5. After reading up on migrating the t4 templates for STE's (Self-Tracking Entities), I came across this link that indicates that STE's are no longer recommended.

Why is Microsoft no longer recommending the use of STE's?

答:
Just from the readings, the only thing I could find was here: http://msdn.microsoft.com/en-us/data/jj613668 which stated:

Self-Tracking Entities can not be used with Code First models

While that may not be a big deal, MS has put a pretty good investment into this with their Fluent API and is now the recommend approach to modeling your database. This is very much (almost identical) to how all DB work is done in a Rails environment with ActiveRecord and ActiveRecord::Migration.

There are also some advantages to using their Fluent API such as versioning your database changes and being able to standup/migrate changes to a new DB simply by running the update-database commands. So, it might make sense for MS to not recommend something that disallows the use of this new technology.


问:
What are some good assignments for an introductory course, to reach today's students?
I periodically teach an introduction to programming course using Java. I want to give my students some exciting assignments that they can relate to or find interesting. At the very least, I want assignments that make sense and have an internal cohesion (for example, some very bad programming exercises seem contrived just so that you have to use the most recent programming construct covered).

To give you an idea of scope, here's what's being covered:

The assignments must be in Java, using some external library can be done, but it would need to be a simple API and not a full framework

Variables, Primitives and Strings

Console input and output

if, for, while

Arithmetic and logical operators

Simple graphics with line and shape drawing

Static methods

One-dimensional arrays

The students will not go into advanced topics (e.g., no recursion, no emphasis on inheritance). Thus, I'm not looking for complex projects: "Have them write a C compiler. I did it when I was 5 and it was the only way I learned!"

If you have ideas that are more advanced than the scope, please post them on the "Challenging" question linked below, and not this one.

Instead, what I'm looking for are interesting ideas that can be accomplished in a short program. For example:

Students can write a console version of the "Star Wars Name" Generator. This is effectively reading Strings and using substring, but I think it's fun. A similar variation would be a "Mad Libs" program. I used this one five years ago, and perhaps it's already "stale."

Using some trig supplied to them, students can draw regular polygons, and create interesting spiral shapes.

It's also not out of the question to use some simple animation class with most of the code supplied to them. And if you know a Twitter or Facebook service that can be accessed with a simple API, I would be very interested to know.

Please note that this question is different from the "Challenging Java questions for beginners" Question. I'm not looking for challenging per se, just interesting. I think if students work on something where they can easily answer "why would anyone ever want to program that?" then they will learn better.

Even simple problems like computing Miles per Gallon can be good. Although, if there's a way to update it to be more relevant, all the better. If you have an exercise from somewhere else (a book or a website), please cite the source.

To help you think about the typical freshman today, check out the Beloit Mindset list, for many examples that will surely make you feel old.

答: How about using a problem or two from http://projecteuler.net/  Some of these are quite interesting and one could see the benefit of writing a program to solve them.  They are small enough that several can be done as assignments.  Another one that I've like to use is finding $1.00 words.  Each letter in the alaphabet is worth its position in pennies i.e. a = 1, b=2.  How many $1.00 dollar words can you find?  This could involve file i/o (reading in a dictionary), arrays, looping etc.</p>


问:
How can I determine how to charge for supporting SharePoint sites and SharePoint development?
I recently created a site in SharePoint and I need to setup a maintenance/support agreement for the site. In addition to the site, there are some custom modules that were developed that we monitor. What considerations should I be making when determining how much to charge for supporting the SharePoint site and any custom applications developed for the site?</p>

答:
Easy:
The first thing what you need to do is calculate exactly how much it costs you to make the site. Set a minimum wage for yourself also and calculate that in also.

Next, what you need to know is what the market prices are, what are others charging for such a service.

Third, and you won't always find this out, but you can manipulate your customer: what is the actual value of this service, perceived or real to your customer.

Once you got these figures, you can go and calculate a price, you want to make money so the minimum price will be your costs. You don't want to have your customers go to competitors so your maximum price is what a competitor (that your customer knows of) asks for the same thing.

Now you have a min and a max, and if the customers added value is between those numbers, you can go set a price.


问:
How does if/else work internally in all programming languages?
```<code>if(true/false){
     //if condition is true
}else {
     // if condition is false
}
</code>```

Everyone knows about the structure of if-else. But what is if actually? Is it a class method, static method or keyword? I'm little confused about this.

答:
It really depends on the language, of course. Since you're giving a pseudo-C example, I'll stick to how it works in most C-like languages.

A program has to be translated to machine-code in the end, so we have to talk about machine code first.

Let's start with an (imaginary, but that's the idea) very old computer who is able to perform these operations only :

1 : put the value punched in by the operator into register A

2 : put the value punched in by the operator into register B

3 : put the following value into register C

4 : put the content of C into A

5 : put the content of A into C

6 : add A and B and put the result into register A

7 : subtract A and B and...

8 : multiply A and B...

9 : divide A and B and put the quotient into register A

10 : print the value that is in register A on a little piece of paper

So, the following "program" saved on, say, a punched card :

instruction 1 : 1

instruction 2 : 2

instruction 3 : 6

instruction 4 : 10

Would put a number in A, then another in B, add them and put the result in A then print it on a piece of paper. The point is, very old computers did not have any possibility of conditional execution or loops. A program was nothing more than perform this calculation, then this one, then this one, and so one. They were little more than a calculator to which you gave a list of calculations to perform.

That soon became a problem : very often, we want a calculation not to be performed in some situations ; for example, if the current value is 0, I don't want to divide another number by it ! Computers had to be enhanced, and that was a big and (somewhat) complicated improvement : now, your computer has to be aware of where it is in the current program flow and act on it ; just reading the current instruction and going to the next one is not enough.

That means you have to add the following instructions to go forward :

11 : go to instruction #n, n being the value in the next "instruction"

Very good, now you can skip instructions if needed ; for example, you can skip the division instruction if you do not want to perform it. Well, actually, we will always jump, so that's a rather useless statement. Let's rewrite it this way :

11 : go to instruction #n, only if the value in A is 0

Yep, an "if statement", that's where it is actually implemented : in a machine instruction. It's very low level and limited, but that's actually not a problem because you can do anything you want with it. It's hard to use, but high-level languages will deal with that for you. Note that it is really very powerful : you can implement loops with it, too (loops are a jump backward rather than forward).

Let's write the following program : read two numbers, subtract them. If the result is not 0, read a third number, divide it by the result and print the overall result.

instruction 1 : 1

instruction 2 : 2

instruction 3 : 7

instruction 4 : 11

instruction 5 : 7

instruction 6 : 2

instruction 7 : 10

Well, that's rather boring to write programs this way, so assembly languages were invented :

READ-A

READ-B

SUB

JMP-IF-ZERO .endif

DIVIDE
.endif:

PRINT

And, since assembly is dull and error-prone too, we invented high-level languages such as C. The following pseudo-C program is the equivalent as above :

```<code>a = read();
b = read();
a = a - b;

if (a != 0) {
   b = read();
   a = a / b;
}

print(a);
</code>```

The way if is translated by your compiler in machine instructions : the condition after the if keyword is transformed as a test whose result is stored in A, and the number of the instruction where to jump is determined based on where your bracket closes.

Body:
It really depends on the language, of course. Since you're giving a pseudo-C example, I'll stick to how it works in most C-like languages.

A program has to be translated to machine-code in the end, so we have to talk about machine code first.

Let's start with an (imaginary, but that's the idea) very old computer who is able to perform these operations only :

1 : put the value punched in by the operator into register A

2 : put the value punched in by the operator into register B

3 : put the following value into register C

4 : put the content of C into A

5 : put the content of A into C

6 : add A and B and put the result into register A

7 : subtract A and B and...

8 : multiply A and B...

9 : divide A and B and put the quotient into register A

10 : print the value that is in register A on a little piece of paper

So, the following "program" saved on, say, a punched card :

instruction 1 : 1

instruction 2 : 2

instruction 3 : 6

instruction 4 : 10

Would put a number in A, then another in B, add them and put the result in A then print it on a piece of paper. The point is, very old computers did not have any possibility of conditional execution or loops. A program was nothing more than perform this calculation, then this one, then this one, and so one. They were little more than a calculator to which you gave a list of calculations to perform.

That soon became a problem : very often, we want a calculation not to be performed in some situations ; for example, if the current value is 0, I don't want to divide another number by it ! Computers had to be enhanced, and that was a big and (somewhat) complicated improvement : now, your computer has to be aware of where it is in the current program flow and act on it ; just reading the current instruction and going to the next one is not enough.

That means you have to add the following instructions to go forward :

11 : go to instruction #n, n being the value in the next "instruction"

Very good, now you can skip instructions if needed ; for example, you can skip the division instruction if you do not want to perform it. Well, actually, we will always jump, so that's a rather useless statement. Let's rewrite it this way :

11 : go to instruction #n, only if the value in A is 0

Yep, an "if statement", that's where it is actually implemented : in a machine instruction. It's very low level and limited, but that's actually not a problem because you can do anything you want with it. It's hard to use, but high-level languages will deal with that for you. Note that it is really very powerful : you can implement loops with it, too (loops are a jump backward rather than forward).

Let's write the following program : read two numbers, subtract them. If the result is not 0, read a third number, divide it by the result and print the overall result.

instruction 1 : 1

instruction 2 : 2

instruction 3 : 7

instruction 4 : 11

instruction 5 : 7

instruction 6 : 2

instruction 7 : 10

Well, that's rather boring to write programs this way, so assembly languages were invented :

READ-A

READ-B

SUB

JMP-IF-ZERO .endif

DIVIDE
.endif:

PRINT

And, since assembly is dull and error-prone too, we invented high-level languages such as C. The following pseudo-C program is the equivalent as above :

a = read();
b = read();
a = a - b;

if (a != 0) {
   b = read();
   a = a / b;
}

print(a);

The way if is translated by your compiler in machine instructions : the condition after the if keyword is transformed as a test whose result is stored in A, and the number of the instruction where to jump is determined based on where your bracket closes.


问:
What are some famous one-liner or two-liner programs and equations?
I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

```<code>#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}
</code>```

60 characters exactly!

Thanks so much for your wisdom!

答:
For cheap, fast, easy approximation of rotation around the "x" axis:

```<code>d = 0.0001;
y = y + z * d;
z = z - Y * d;
</code>```

It's an approximation, but not one that you'd ever notice the error on

Body:
For cheap, fast, easy approximation of rotation around the "x" axis:

d = 0.0001;
y = y + z * d;
z = z - Y * d;

It's an approximation, but not one that you'd ever notice the error on


问:
How can I explain the usefulness of Inheritance?
When trying to explain the concept of Inheritance in OOP, the common example is often the mammals example. IMHO, this is really a bad example, because it will lead the newbies to use this concept the wrong way. And moreover, it is not a common design that they will face in their day-to-day design job.

So, what will be a nice, simple and concrete problem that is solved using Inheritance ?

Body:
How about a hierarchy of algebraic expressions. Is good because it includes both inheritance and composition:

+--------------------+------------------------+
| Expression         |<------------------+    |
+--------------------+----------+        |    |
| + evaluate(): int  |<---+     |        |    |
+--------------------+    |     |        |    |
          ^               |     |        |    |
          |               |     |        |    |
   +--------------+  +---------------+  +-------------+  ...
   | Constant     |  | Negation      |  | Addition    |
   +--------------+  +---------------+  +-------------+
   | -value: int  |  |               |  |             |
   +--------------+  +---------------+  +-------------+
   | +evaluate()  |  | +evaluate()   |  | +evaluate() |
   | +toString()  |  | +toString()   |  | +toString() |
   +--------------+  +---------------+  +-------------+

   Addition(Constant(5), Negation(Addition(Constant(3),Constant(2))))
   (5 + -(3 + 2)) = 0

With the exception of the root expression Constant, all other expressions are both an Expression and contain one or more expressions.


问:
In-house SMS (using a SIM card) receiving and sending?
My needs are very simple but I don't know the terms I should be Googling for: I need to occasionally send a SMS to a machine and that machine is going to answer with another SMS to the number that did send the first SMS.

I've got no say as to how that machine works: it's closed and all it does is receive SMS and send SMS in reply to SMS received (and uniquely to the number that did send the first SMS) and there's no other way to interface with it.

Upon receiving the "response SMS", I need to update a server / DB (a regular Java webapp server + SQL DB) with the infos contained in the SMS.

There isn't going to be a lot of volume (only a few SMSes daily) and robustness isn't that important (a few SMSes can be missed).

What would be a possible architecture for something like that?

I was thinking about using two or three cheap smartphones and giving them SIM cards and then program them to regularly (once every height hours or so) send an SMS.  Then these smartphones would receive an SMS back from the machine they contacted and I'd intercept that SMS and update my server/DB accordingly. (I'll have physical control on these smartphones so giving any permission needed to any app won't be an issue).

Is this something easily doable?  Technically, if such a solution could work, how can I access the SMS functionalities of the phone?  And how can I have the phone udpate my server/DB?  (the phone can be hooked to the Internet, so I take it I can simply do an HTTP POST to my server).  Or is there already some (preferrably free or open-source) offering a similar functionality? (maybe something not totally unlike what "zapier" of "ifttt" does, where I could create a rule saying: "If I receive a SMS containing the word xxx, then send the SMS using an HTTP POST to the URL yyy").

Note that I did configure the server(s) hosting the Webapp myself and develop the entire webapp myself: so the "programming" part ain't that much of a problem.  My issue is that I don't know how to "create a bridge" between the SMS coming in response to another SMS and my webserver.

I hope I explained the issue simply enough: basically I need some guidance on the architecture to use here (which fits programmers.stackexchange as far as I can tell from just having read its FAQ).

答:
I think it will be far easier for you to just use on of the many services available online for this purpose, e.g. Nexmo. I am not aware whether they are the best in business, but you could google "SMS API" and you'll find plenty of other providers.

This way you can send SMS messages with a single RESTful API call and receive them by providing a callback URL at your own server.

What you gain is that you won't deal with broken phones, etc. and you can focus on your core product.

Even if you don't pick a provider that does this for you, I strongly urge you to at least not do this with Android phones. Not only will you waste money on touchscreen and camera, but a sophisticated OS like Android has a higher chance of a failing component.

I think you'd be far better with a specialized hardware (they are not that expensive) that is designed specifically for the purpose of sending messages. You can search for "GPRS modem" and you'll find proper hardware.

This site has some useful information, although it seems dated: http://www.developershome.com/sms/howToSendSMSFromPC.asp


问:
Implementing chat in 2013
I played a bit with WebSockets and started to implement a tiny chat. Last time I did something like this was when there was no such thing as threads and computers had single core. I started to think how to implement it with todays programming patterns but I didn't come to any final conclusion.

How you implement chat's main functionality in today's technics in higher level?

I now have context Server, Socket and User. User has states Undefined, Connected, InChat, ToBeDisconnected, Disconnected, My main problem is the user maintenance:

If user hasn't said "hello" in 5 seconds after connection was opened -> disconnect

User is not replied to "ping" with "pong" at all or at least 2 minutes -> disconnect

User has been connected over 12 hours -> disconnect

User haven't been assigned profile (nickname and/or other details) after 5 minutes of connect -> disconnect

Some other program specific flag that kicks out user is triggered -> disconnect

My current implementation is like how it was done in olden days. ie. I have

```<code>while(serverRunning)
{
  foreach(socket in allSockets)
  {
    user = allUsers.findUserBySocket(socket);
    doMaintenance(user);
  }
}
</code>```

Now this runs far too many times and locks and blocks allUsers and allSockets way too much.

How this is implemented today? Like this for example?

Socket connects

Add to allSockets

Add to allUsers

Start per-user thread that runs every x seconds and runs user.doMaintenance()?

Or there's per-user queue that gets injected with actions like doPongCheckAction, doProfileTimeoutCheckAction, etc every x seconds (also needs per-user thread which constantly empties user's queue)?

Or there's Maintenance thread that runs every x second after last run and iterates through allUsers (a bit like current implementation)?

Or there's thread that injects actions to all users queues when there's been too long when same kind of action were ran and other thread that iterates through all users and empties user's queue?

Or something else or which is not even based on queues? :)

答:
One way to structure your main loop, very similar to what you have, is to use an event driven architecture:

```<code>while(serverRunning)
{
  wait(for something interesting on any of your sockets)
  {
    user = allUsers.findUserBySocket(socket);
    doMaintenance(user);
  }
}
</code>```

The wait() operation could be something like select, epoll, kqueue, or some other kernel-provided function depending on your target OS. Essentially you give the kernel the complete list of sockets which you are interested in, then it (efficiently) waits until something interesting happens on any of those sockets. When the wait operation returns, check to see which socket had the interesting event (data received, socket closed, etc) and act accordingly.

To handle periodic events, you can keep a list in your code of the next events to be fired. When you call select or whatever, you can work out what time the next event should fire, and pass a corresponding timeout value to the waiting function.

Title: Implementing chat in 2013

Body:
One way to structure your main loop, very similar to what you have, is to use an event driven architecture:

while(serverRunning)
{
  wait(for something interesting on any of your sockets)
  {
    user = allUsers.findUserBySocket(socket);
    doMaintenance(user);
  }
}

The wait() operation could be something like select, epoll, kqueue, or some other kernel-provided function depending on your target OS. Essentially you give the kernel the complete list of sockets which you are interested in, then it (efficiently) waits until something interesting happens on any of those sockets. When the wait operation returns, check to see which socket had the interesting event (data received, socket closed, etc) and act accordingly.

To handle periodic events, you can keep a list in your code of the next events to be fired. When you call select or whatever, you can work out what time the next event should fire, and pass a corresponding timeout value to the waiting function.


问:
Implementing a Service Layer with MVC4 while honoring Single Responsibility
I'm trying to learn some best practices while I ramp up on MVC4. I have a solution with three projects:

Web: MVC stuff

Core: Data Model

Tests: Testing classes

I'm now trying to add:

Services: Business Logic

This will take logic such as "GetFilteredItems()" from my controllers and place them into a Service project, which depends on Core, and upon which Web depends. Nothing to do with HTTP requests.  As I'm beginning to do this, I want to honor single responsibility and create one class per method. My questions:

1) Is this a good approach?

2) Say I need a GetFilteredItems method that takes an ID and returns a List. What's the convention here in terms of naming classes and methods? I can't have a class SampleClass with a method SampleClass() that returns something, right?

答:
I think a better approach would be to a create a service class for each data model entity. This will reduce the coupling that will result if you created one class per service method. Using the single responsibility model would result in several classes with names like: SortUserByFirstName, SortUserByLastName, SortUserByPhoneNumber, etc. Delegate such a responsibility to a single class such as: UserService, and have methods like sortByFirstName, sortByLastName, etc.

To give an example of what might happen, say you change you data entity named User to SuperUser. Now you would have to go through each single responsibility class and change the class name. Using the more cohesive model I suggested, you change the name of the service class only.


问:
Parallelization: Choice of communication model
Disclaimer: If you're not into parallelization (on clusters), this question is probably not interesting to you and probably not worth a read.

TL;DR: I search for a communication model (preferably compatible with MPI) that efficiently assures that each data line is processed once. Read the next paragraph as well to know what I mean by data line.

Consider the following problem: An algorithm takes a data line (in my case, an array of integers with fixed size) and produces various data lines which then need to be processed by the same algorithm. Each unique data line only needs to be processed once, since the outcome is purely deterministic. The set of unique data lines is finite, so after a finite number of recursive calls of this algorithm it produces the whole set. The goal is to find this set.

I've already implemented the algorithm and I've also implemented a parallelization. Obviously, since we need to process each unique data line, at each time all currently unprocessed data lines may be processed by different processors in parallel.

On the other hand, parallelization introduces the problem of keeping the different processors from doing redundant work.

A trivial implementation would send data lines to processors, collect all results and distribute again. This may be inefficient since the (possibly large) result lists have to be merged before any further work may be done. If all lists are returned around the same time, the master is overwhelmed by the sheer amount of data while all slaves idle until all merging is done.

My (as far as I think, improved) communication model is still basically Master-Slave:

This is what the Master does:

```<code>Distribute initial chunk of data lines to slaves
While there is at least one active slave
  for each active slave
    Request data line
    if slave doesn't have a data line
      set slave inactive, break
    else
      if the data line was previously processed
        break
      endif
      if there is an inactive slave
        send the data line to inactive slave and mark that slave as active
        send the sending slave a notification to not process the data line
      else
        notify the slave to process the data line it just sent
      endif
    endif
  endfor
endwhile
</code>```

Each slave does this:

```<code>while true
 wait for request
 if data line available
   send it
   wait for master to say if the line should be processed here
   process if necessary
   go back to beginning
 else
   notify master
   wait for master to send a data line
   process the received line
   go back to beginning
 endif
</code>```

The slave manages its own local list of processed and unprocessed data lines. For each request, one element of the unprocessed ones is moved to the processed ones. Only unique entries among both lists are stored.

In conclusion: Only the master knows about the full set of processed lines. a slave processes a data line if and only if the master says that it wasn't previously processed. The Master doesn't know about the results for each data line until it has requested all available lines from each slave.

As far as I can think, this model of communicating the list of processed data lines is pretty efficient, but I'm new to the world of parallelization, especially in the world of parallelization on a cluster.

What are other ways of efficiently communicating data lines among several processors to assure that each data line is processed exactly once?

This question is basically not bound to the combination of C++ and MPI, though any answer reflecting the way the Message Passing Interface works are greatly appreciated.

答:
Disclaimer: I do not have any real MPI / clustering experience.

Also beware of my possibly incorrect use of terminology.

My basic idea is to apply a hash function to the input and output data lines. Compute an integer K (between 1 and NumSlaves) from the hash to decide which one (K) of the slave (NumSlaves) should process this data line.

Each slave will have a hash-range. A data line will be processed by the slave if the data line's hash falls into that slave's hash-range.

This basic scheme requires slaves to communicate directly with each other. The master will act as a journal keeper, which receives a copy of computed outputs from each node but do not participate in task assignment.

When a slave derives one or more output data lines from one input data line, it will compute this hash function on each output data line and decide for each one a slave that will process it.

This basic scheme does not provide fault tolerance or changing number of slaves at run-time; unless some other distributed processing techniques (e.g. consistent hashing, etc) are used.

Each slave must cache all of the data lines that fall into its hash-range, to avoid re-computation.

This scheme may require more communication than your current scheme, but might be better at preventing duplicated work.


问:
Making things just work and then improve them, or attempt to make them "perfect" from the beginning?
I don't have any experience working as a programmer - I just code as a hobby so far. Some years ago, I heard a programmer say that I should focus on making my code just work despite being slow (it was for a game, so it was more noticeable if my code was slow or not) and then I would spend my time improving it to make it fast and better.

I wonder how often is that advice applied in actual working environments. Do you make something that (barely) works and then spend the rest of the time improving it, or do you make it "perfect" (or acceptable) from the very beginning without looking back?

I'm assuming that the difference between these is that one is more about writing the first solution that comes to your mind, and the other is about carefully planning and thinking what you're going to write - supposing that the latter is, well, significantly slower than the former.

答:
You have heard only part of the idea. Several iterative methods, such as Test-Driven Development (TDD), recommend that you should make your code work (for TDD: pass the tests) as early as possible. The point is that you can gain feedback earlier in the programming process and adapt your design to the real needs.

In actual working environments, this pattern of making a workable but imperfect implentation, gaining information with it, and then improving and gaining new information is used heavily when you do any Agile programming. The crucial point is that you don't do it for the sake of rework, but because the requirements are not clear at the project start and there is simply no way to get an acceptable result from the start because "acceptable" isn't defined yet.

The concept has very little to do with less careful planning and thinking. It just acknowledges that planning and thinking are often quite useless when you and the user's cannot see the half-finished product and get feedback early.


问:
Open Source code bounties
I have a library for R (open source statistics package) mapped out on paper. I have started coding the different functions but I realize that I don't have the time needed to finish this in a reasonable amount of time. I know I can just throw the code up on a repo and call for others to help fill in the blanks. But I'd like to incentivize things a bit. I'm thinking about putting a bounty on each function of, say, $5-$20. There's no way that $20 would be a fair return on time for a developer to code each function. But my thought is that the cash (or Amazon gift certificates) would be an inventive for people to actually work on the project. And it would allow me to put higher bounties on the functions I am most interested in.

I have a few questions related to this:

Good idea?

I going to make
the development work faster, or
slower? I've read Predictably
Irrational and I'm concerned
that by offering menial pay for
functions I might actually
disincentive developers.

Are
there sites devoted to this type of
activity? Can you recommend one based on personal experience?

Would you recommend a totally different approach? I'm open to ideas!

答:
https://www.bountysource.com

From the about page:

BountySource was originally created in 2004 with the hope of increasing and improving development in open-source software communities. The first iteration of BountySource provided a variety of tools that allowed for easy management of open-source projects. Some of these tools included a Task Tracker, an SVN Code Repository, and a Content Management System.

BountySource was way ahead of its time...we'd like to think of it as a predecessor to GitHub.

After a lengthy hiatus, we're back with the same vision - overall improvement in open-source software development - but a completely different system.

We're shifting our focus from project hosting - repositories, issue tracking and all - to the crowdfunding aspect of BountySource's original idea.

Title: Open Source code bounties


问:
How to pick a great working team?
I've just finished my master and I'm starting to dig into the laboral world, i.e. learning how programming teams and technology companies work in the real world.
I'm starting to design the idea of my own service or product based on free software, and I will require a well coupled, enthusiast and fluid team to build and the idea. My problem is that I'm not sure which would be the best skills to ask for a programming team of 4-5 members.

I have many friends and acquaintances, with whom I've worked during my studies. Must of those ones I have in mind are very capable and smart people, with a good logic and programming base, although some of them have some characteristics that I believe that could influtiate negatively in the group: lack of communication, fear to debate ideas, hard to give when debating, lack of structured programming (testing, good commenting, previous design and analysis).

Some of them have this negative characteristics, but must of them have a lot of enthusiasm, nice working skills (from an individual point of view), and ability to see the whole picture.

The question is: how to pick the best team for a large scale project, with a lot of programming? Which of these negative skills do you think are just too influential? Which can be softened with good leadership? Wich good skills are to be expected? And any other opinion about social and programming skills of a programming team.

答:
Joel Spolsky said:

In principle, it’s simple. You’re
  looking for people who are

Smart, and

Get things done.

Title: How to pick a great working team?


问:
Context class in Strategy pattern
I'm trying to understand the strategy pattern and asking myself: is the context class must-have or can I leave it out without compromising pattern's purpose ?

I was under the impression I needed some kind of switch for reading different types of files but didn't want to just hack something and later deal with refactoring (although, of course it always happens that code can be refactored but the idea was: try to be as smart as possible in the design beforehand...):

Image taken from wikimedia

Can the client delegate directly to the Strategy interface or is there something I just missed to understand about the context class?

```<code>interface Reader {
    // read information from file and fill data list field of Client
    readFile();
}
class ExcelReader implements Reader{ /* */ }
class PdfReader implements Reader{ /* */}

class Client{
    // strategic choice
    Reader r;

    // data list field
    List<Data> data;

    // Client Constructor
    public Client(){
        if(<file ends in .xls>)
            r = new ExcelReader();
        else
            r = new PdfReader();
        r.readFile();
    }
}
</code>```

So, above depicted is the context class missing. Does the code adhere to the strategy pattern?

答:
Certainly. Patterns are just guidelines. You will still need to adapt and apply them correctly for the problem at hand. Personally, I rarely ever allow the strategy to be set at runtime; more often it is specified on construction or spun up in a factory.

Though it could also be argued that setStrategy is private and my injection is just using the pattern as shown.

Title: Context class in Strategy pattern


答:
My quick advise would be that, if you can, try to be the closest as possible from the second choice.

Though, if you are new to something, if you can get it to work first, it's already great I guess.

Why do I discourage the 'as long as it works!' way of thinking? Well … most of the time, you are the one who will have to maintain your code, to understand it even in six month without having touched to it for months, etc. So if you have to spend hours, get some headaches, just to understand your code again (and then only you'll be able to work on it again), that's a bit dumb. How way more pleasant it is when you have taken a bit more time to make something better and then you'll no longer loose your time when you'll have to work on it, etc.

And even though, it wouldn't be you who would have to work on it in the future, think to the others, as it is even harder to understand someone else's code.

And yes, coding properly is also often opposed to 'get it to work and that's it'.
If your code isn't easy to understand (maybe thanks to some comments in addition) then it's more likely that it isn't that well coded at all.

Title: Making things just work and then improve them, or attempt to make them "perfect" from the beginning?

Body:
I don't have any experience working as a programmer - I just code as a hobby so far. Some years ago, I heard a programmer say that I should focus on making my code just work despite being slow (it was for a game, so it was more noticeable if my code was slow or not) and then I would spend my time improving it to make it fast and better.

I wonder how often is that advice applied in actual working environments. Do you make something that (barely) works and then spend the rest of the time improving it, or do you make it "perfect" (or acceptable) from the very beginning without looking back?

I'm assuming that the difference between these is that one is more about writing the first solution that comes to your mind, and the other is about carefully planning and thinking what you're going to write - supposing that the latter is, well, significantly slower than the former.


问:
Code Reviews, what are the advantages?
In my team, we don't do formal code reviews. We tend to think that it's enough with pair programming and rotating pairs often.

Should we consider doing formal code reviews?
What would be the advantages?

答:
For me the main advantage of code reviews is that it makes people write better code.

Knowing that your code will be read and reviewed makes you more conscious of readability and the "correct"ness of your code. When you know the code is going straight into the repository and no one else will read it unless they are defect fixing you tend to let things slip like not re-factoring field names when their usage changes, leaving unused methods hanging around in case they might be factored back in etc. etc.

Title: Code Reviews, what are the advantages?


问:
Algorithm Identification [ String & Dictionary ]
I recently heard of an interview question:

```<code> Given a string and a dictionary. Break the string into meaningful words
</code>```

and I remember solving this before with dynamic programming fairly quickly (maybe O(n) time? ) in one of my old algorithm classes but I can not remember the name of the algorithm. Could someone point me in the right direction?

答: Your instincts are on the money though as suggested in this Stack Overflow question, tries (prefix trees) are also a valid solution. The process is called "Word Segmentation".</p>


答:
Steve Yegge liked that principle and expanded on it a bit with Done and Gets Things Smart.

I've managed teams for 5 years now, after 15 years of development.  My own principle is much like Spoelsky's only not as elegantly worded.  Programmers are problem solvers who use software to solve the problems.  In that sense, a good programmer will use whatever tool is the best for the job, although that often means one of the handful they know best (good luck finding a .Net developer who believes Lisp is the best tool for a job).

While all of my interviews do have some development specific questions, they tend to be generic and not toolset based.  I would rather have people who understand OO (our current app suite is OO), and show an ability to understand, learn, and embrace.

All of that said, they do need to show they have the ability to write sound logic in some language.  I've come across way too many developers who can talk the talk but can't walk the walk.

Title: How to pick a great working team?

Body:
I've just finished my master and I'm starting to dig into the laboral world, i.e. learning how programming teams and technology companies work in the real world.
I'm starting to design the idea of my own service or product based on free software, and I will require a well coupled, enthusiast and fluid team to build and the idea. My problem is that I'm not sure which would be the best skills to ask for a programming team of 4-5 members.

I have many friends and acquaintances, with whom I've worked during my studies. Must of those ones I have in mind are very capable and smart people, with a good logic and programming base, although some of them have some characteristics that I believe that could influtiate negatively in the group: lack of communication, fear to debate ideas, hard to give when debating, lack of structured programming (testing, good commenting, previous design and analysis).

Some of them have this negative characteristics, but must of them have a lot of enthusiasm, nice working skills (from an individual point of view), and ability to see the whole picture.

The question is: how to pick the best team for a large scale project, with a lot of programming? Which of these negative skills do you think are just too influential? Which can be softened with good leadership? Wich good skills are to be expected? And any other opinion about social and programming skills of a programming team.