答:
For the vast majority of day-to-day applications, keeping sessions in databases is fine.  The volume & level of concurrency that a sql server can handle will be more than sufficient.  The key is to keep each entry small in size and purge the unneeded rows with regularity.  And proper indexing, of course.

The file system - I've never seen the need to do that.  I prefer the simplicity of managing rows in tables rather than thousands of little files.  Plus you cant query across files if you want to dig into session statistics.

Keep in mind, with PHP, its easy to swap out session handlers.  So you can start with one storage format, and migrate to another without too much hassle.


问:
emacs keybindings
I read a lot about vim and emacs and how they make you much more productive, but I didn't know which one to pick. Finally when I decided to teach myself common lisp, the decision was straight forward: everybody says that there's no better editor for common lisp, than emacs + slime. So I started with emacs tutorial and immediately I ran into something that seems very unproductive to me. I'm talking about key bindings for cursor keys:

```<code>forward/backward: Ctrl+f, Ctrl+b
up/down: Ctrl+p, Ctrl+n
</code>```

I find these bindings very strange. I assume that fingers should be on their home rows (am I wrong here?), so to move cursor forward or backward I should use my left index finger and for up and down right pinky and right index fingers. When working with any of Windows IDEs and text editors to navigate text I usually place my right hand in a position so that my thumb is on the right ctrl and my index, ring and middle fingers are on the cursor keys. From this position it is very easy and comfortable to move cursor: I can do one-character moves with my 3 right fingers, or I can press ctrl with my right thumb and do word-moves instead. Also I can press shift with my left pinky and do single-character or word selections. Also it is a very comfortable position to reach PgUp, PgDn, Home, End, Delete and Backspace keys with my right hand. So I have even more navigation and selection possibilities. I understand that the decision not to use cursor keys is to allow one to use emacs to connect to remote terminal sessions, where these keys are not supported, but I still find the choice of cursor keys very unfortunate. Why not to use j, k, i, l instead? This way I could use my right hand without much finger stretching. So how is emacs more productive? What am I doing wrong?

答:
Emacs has configurable keybindings.  If you don't like the defaults, change them.

Here's some stuff that demonstrates a number of lisp-specific commands for navigating by s-expressions, deleting s-expressions, closing all open parens, etc.  It's been awhile since I edited lisp, but I remember the M-( command (which wraps the next item in parens) being very useful.  If you give it a numerical argument, then it will wrap the next n things in parens.  (You can give a numerical argument to the following command by doing C-u followed by a number, or by holding down Meta (probably Alt) while typing a number.)  It also highlights matching parens, without which editing lisp is a nightmare.

Steve Yegge's effective emacs blog post is good, and item 4 (use incremental search for navigation) is part of why I have a hard time seeing how keybindings for up/down/left/right could matter much.  Incremental search and a few s-expression navigation commands and M-f and M-b (to move forward and backward a word) can take care of the majority of your navigation needs.

The M-/ command will try to autocomplete the current thing you're typing, which is very nice for long variable/function names.  There's also the C-M-% command, and yes it requires you to hold down control and alt and shift at the same time, but it lets you query-replace with regular expressions, which allows for some neat tricks.

Also, the regular cursor keys do still work in emacs (I can't tell from your post whether you noticed that or not) and there is a CUA mode that lets you use windows-style cut-and-paste if you prefer it.

ContentLicense: CC BY-SA 3.0

Title: emacs keybindings


问:
Should I give the answer to a failed interview coding exercise?
We had a senior level interview candidate fail a nuance of the FizzBuzz question12.

I mean, really, utterly, completely, failed the question - not even close.

I even coached him through to thinking about using a loop and that 3 and 5 were really worth considering as special cases.

He blew it.

Just for QA purposes, I gave the same exact question to three teammates; gave them 5 minutes; and then came back to collect their pseudo-code.  All of them nailed it and hadn't seen the question before.  Two asked what the trick was...

On a different logic exercise, the candidate showed some understanding of some of the features available within the language he chose to use (C#).  So it's not as if he had never written a line of code.  But his logic still stunk.

My question is whether or not I should have given him the answer to the logic questions.

He knew he blew them, and acknowledged it later in the interview.

On the other hand, he never asked for the answer or what I was expecting to see.

I know coding exercises can be used to set candidates up for failure (again, see second link from above).  And I really tried to help him home in on answering the core of the question.  But this was a senior level candidate and Fizz-Buzz is, frankly, ridiculously easy even after accounting for interview jitters.

I felt like I should have shown him a way of solving the problem so that he could at least learn from the experience.  But again, he didn't ask.

What's the right way to handle that situation?

1Okay, that's not the link to the actual FizzBuzz question, but it is a good P.SE discussion around FizzBuzz and links to the various aspects of it.

2 To help clarify, this is the nuance of Fizz-Buzz I asked and it's from Project Euler's first problem.  Substitute printing Fizz | Buzz for summing the numbers and you have the same fundamental question.

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.  Write a function that finds the sum of all the multiples of 3 or 5 below 1000.

3 This question attracted more attention than I had expected, and I appreciate all of the replies.  Some of the later answers have really gotten to the core of my question, so I'll allow the community to review and up-vote before assigning "the" answer.

4 I selected "the" answer based upon community votes at that point in time.  And I think Yannis' answer is appropriate for interviews with newer devs.  I think the collective response focusing on the lack of asking for the answer is spot-on as well.

答:
Most of my interviews were with students looking for an internship position, and more often than not they screwed up simple (?) exercises. I wanted an easy and friendly way to communicate their errors, and what I came up with was quite simple: I solved the exercises myself, and showed them my solutions after they finished with theirs.

I had quite a few extremely interesting and revealing discussions with candidates that started by comparing our different approaches to solving the same problem. After a while I even anticipated some of the errors, just by checking which school the candidate was attending (some "professors" are... morons). And, well, in the few instances that a candidate couldn't come up with any solution, I had already given them one for next time.


答:
I typed out fizzbuzz while on the phone with the interviewer during a pre-screen. That's something that, even if everyone hasn't heard of, you should be able to cobble together after a semester of course work but definitely after acquiring "senior" status.

There's really no recovery from not being able to do that. It's one of those necessary nuisances that you need to get out of the way just in case.

I would say that it makes sense to deliver as a pre-screen so you're not wasting everyone's time with bringing them on site for an interview.

Title: Should I give the answer to a failed interview coding exercise?

Body:
We had a senior level interview candidate fail a nuance of the FizzBuzz question12.

I mean, really, utterly, completely, failed the question - not even close.

I even coached him through to thinking about using a loop and that 3 and 5 were really worth considering as special cases.

He blew it.

Just for QA purposes, I gave the same exact question to three teammates; gave them 5 minutes; and then came back to collect their pseudo-code.  All of them nailed it and hadn't seen the question before.  Two asked what the trick was...

On a different logic exercise, the candidate showed some understanding of some of the features available within the language he chose to use (C#).  So it's not as if he had never written a line of code.  But his logic still stunk.

My question is whether or not I should have given him the answer to the logic questions.

He knew he blew them, and acknowledged it later in the interview.

On the other hand, he never asked for the answer or what I was expecting to see.

I know coding exercises can be used to set candidates up for failure (again, see second link from above).  And I really tried to help him home in on answering the core of the question.  But this was a senior level candidate and Fizz-Buzz is, frankly, ridiculously easy even after accounting for interview jitters.

I felt like I should have shown him a way of solving the problem so that he could at least learn from the experience.  But again, he didn't ask.

What's the right way to handle that situation?

1Okay, that's not the link to the actual FizzBuzz question, but it is a good P.SE discussion around FizzBuzz and links to the various aspects of it.

2 To help clarify, this is the nuance of Fizz-Buzz I asked and it's from Project Euler's first problem.  Substitute printing Fizz | Buzz for summing the numbers and you have the same fundamental question.

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.  Write a function that finds the sum of all the multiples of 3 or 5 below 1000.

3 This question attracted more attention than I had expected, and I appreciate all of the replies.  Some of the later answers have really gotten to the core of my question, so I'll allow the community to review and up-vote before assigning "the" answer.

4 I selected "the" answer based upon community votes at that point in time.  And I think Yannis' answer is appropriate for interviews with newer devs.  I think the collective response focusing on the lack of asking for the answer is spot-on as well.


问:
How are requirements determined in open source software projects?
In corporate in-house software development it is common for requirements to be determined through a formal process resulting in the creation of a number of requirements documents. In open source software development, this often seems to be absent. Hence, my question is: how are requirements determined in open source software projects?

By "determining requirements" I simply mean "figuring out what features etc. should be developed as part of a specific software".

答:
I don't know for sure, but once suggestion is to use an Agile-like methodology, where requirements are raised as tickets (or "cards"), using something like JIRA, with each ticket representing a feature or requirement. Each ticket could then be decomposed into other tickets representing smaller units of work.

As for actually figuring out what an application or piece of software should do, the simple answer is "talking to the other developers." :) "Talking" in this case could mean an e-mail distribution list, forum, or even IRC, anything that allows people in different timezones and geographical locations to chat.


答:
I've been following open source since I first heard about linux in about 1995, and I can't remember ever hearing the word 'requirements' used in that context.

Eric Raymond has a good essay, The Cathedral and the Bazaar, in which he talks about 'scratching your own itch'.  If you're trying to solve a problem that you're facing personally, you don't have to refer to requirements documents to figure out if you've solved it or not.

That same essay also talks about listening to your users, which is good advice for everyone, not just open source projects.  Open source projects tend to be meritocratic, so 'he who writes the code, makes the rules', more or less.

Title: How are requirements determined in open source software projects?

Body:
In corporate in-house software development it is common for requirements to be determined through a formal process resulting in the creation of a number of requirements documents. In open source software development, this often seems to be absent. Hence, my question is: how are requirements determined in open source software projects?

By "determining requirements" I simply mean "figuring out what features etc. should be developed as part of a specific software".


问:
C simple arrays and pointers question
So here's the confusion, let's say I declare an array of characters

```<code>char name[3] = "Sam";
</code>```

and then I declare another array but this time using pointers

```<code>char * name = "Sam";
</code>```

What's the difference between the two? I mean they work the same way in a program. Also how does the latter store the size of the stuff that someone puts in it, in this case 3 characters?

Also how is it different from

```<code>char * name = new char[3];
</code>```

If those three are different where should they be used I mean in what circumstances?

答:
The first option only consumes the necessary space in memory for a 3 char string + the termination character.

EDIT: Thanks for pointing that out in the comments. This option will actually give out an error because you only have 3 positions to fill, meaning there is no space for the termination character.

The second option points towards the memory position where the new string starts. This has a variable size and needs to be manually terminated with a \0 character ( the termination character ). This is usually prefered due to its variable size. This means that it will only consume as much memory as you need, unlike with the first option, where if you store a 3 character length string in a 100 position array, you will still have 100 positions reserved in an array.

Using the second option means that you are using pointers instead of arrays, sometimes making it hard to notice where the errors are occurring, so special attention when using this.

Title: C simple arrays and pointers question


答:
In your first variant you have an array of three characters in a variable called name and you can store at most 3 characters in that.

In your second variant, you have declared a character pointer which points to a sequence of three characters, i.e. "sam".

The major difference is that you cannot change the value of the first name pointer (location to which it points), using operators like ++, --, + and -.

But in second option you can change the location to which it points and you can assign it to something with more length later on in the program like:

```<code>char * name= "sam";
/*some code goes here*/
name="hello";
</code>```

In other words, name is constant in your first variant.

In the last variant you are just allocating a space of three characters and assigning the base address to the name pointer.

Title: C simple arrays and pointers question

Body:
So here's the confusion, let's say I declare an array of characters

```<code>char name[3] = "Sam";
</code>```

and then I declare another array but this time using pointers

```<code>char * name = "Sam";
</code>```

What's the difference between the two? I mean they work the same way in a program. Also how does the latter store the size of the stuff that someone puts in it, in this case 3 characters?

Also how is it different from

```<code>char * name = new char[3];
</code>```

If those three are different where should they be used I mean in what circumstances?

Body:
In your first variant you have an array of three characters in a variable called name and you can store at most 3 characters in that.

In your second variant, you have declared a character pointer which points to a sequence of three characters, i.e. "sam".

The major difference is that you cannot change the value of the first name pointer (location to which it points), using operators like ++, --, + and -.

But in second option you can change the location to which it points and you can assign it to something with more length later on in the program like:

char * name= "sam";
/*some code goes here*/
name="hello";

In other words, name is constant in your first variant.

In the last variant you are just allocating a space of three characters and assigning the base address to the name pointer.


答:
Open source projects sometimes have intense streams of user feedback, and sometimes corporations would simply pay to make certain features planned and implemented (by hiring their own developers or the original developers).

If your project has 100 users, you probably can develop whatever is most fun to code.

If your project has 100k users, most probably you already have a list of pain points most users want fixed in the next release, and a list of top N features that users request in your issue tracker and keep asking about on forums.

With this feedback, you can write requirement documents for your core team, create roadmaps to help independent contributors understand your vision, and hope that some of the 100k users will send in patches.


答:
char name[3] = "Sam";

define an array named "name" (of course, you can use name[] rather than [3]), and

name[0] = 'S', name[1] = 'a', name[2] = 'm', name[3] = '\0';

char * name = "Sam";

define a pointer pointed to the address where "Sam" is (it is at the storage location of constant)

char * name = new char[3];

define a pointer pointer to the address which is at the free store or heap, where 3 characters will be saved.

Title: C simple arrays and pointers question


问:
What is a good use case for scala?
In a current project we have setup the build so that we could mix Java and Scala. I would like to use more Scala in our code base to make the code more readable and concise. In the process also learn the language by handing over real features.

So I plan to use Scala for some classes to showcase its benefits and convince other devs to look into using Scala too.

For a rest based web server or a program in general what kind of code structures lend themselves to Scala's functional programming style.

答:
For all, everywhere where it is possible or for nothing, just use Java. This way this will work sane. I were making such experiments long time ago but in later times you rewrite everything to one or two (to you keep some things if that could not be done in another language) languages just for clarity.

If you can declare class shorter in 2 lines of code, that is not advantage you must not use language for this "feature". For example also you can write beautiful functional code in xxx lines and spend yyy time and maybe in the same time you can write it in OOP style in xxx+150 lines in yyy-2hours time with perfomance benefit (who knows). What I want to say is that is not possible to say "this part will be better on Scala" and "this part on Java". In development you must not discover features, in my opinion, you must just develop without mixing and think about general logic instead of implementation in language X or Y that's why, in my opinion, for clarity and productivity you must pick language for project instead of for feature.

Title: What is a good use case for scala?


问:
Is it okay to use a language that isn't supported by your company for some tasks?
I work for a company that supports several languages: COBOL, VB6, C#, and Java. I use those languages for my primary work, but I often find myself coding some minor programs (e.g. scripts) in Python because I find it to be the best tool for that type of task.

For example: an analyst gives me a complex CSV file to populate some DB tables, so I use Python to parse it and create a DB script.

What's the problem?

The main problem I see is that a few parts of these quick and dirty scripts are slowly gaining importance and:

My company does not support Python

They're not version controlled (I back them up in another way)

My coworkers do not know Python

The analysts have even started to reference them in emails ("launch the script that exports..."), so they are needed more often than I initially thought.

I should add that these scripts are just utilities that are not part of the main project; they simply help to get trivial tasks done in less time. For my own small tasks they help a lot.

In short, if I were a lottery winner to be in a accident, my coworkers would need to keep the project alive without those scripts; they would spend more time fixing CSV errors by hand, for example.

Is this a common scenario? Am I doing something wrong? What should I do?

答: I have run into similar problems where I work. I heard "What is PHP?" several years ago. They don't understand or care to learn anything outside of the MS stack. If python is the right tool for the job I'd just tell my supervisors about it and be ready for alot of comparison and explaining as to why python was the right choice. It will be frustrating, but I think most would agree python is a good choice for text manipulation. </p>

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


答: In my (admittedly limited) experience, the use case I've seen most is to use it to get a sense of superiority and smugness over your colleagues who actually ship things, and/or hide your limitations by blaming the "antiquated and inelegant" language you're "forced" to use instead of the new hotness ;)</p>

Title: What is a good use case for scala?

Body:
In a current project we have setup the build so that we could mix Java and Scala. I would like to use more Scala in our code base to make the code more readable and concise. In the process also learn the language by handing over real features.

So I plan to use Scala for some classes to showcase its benefits and convince other devs to look into using Scala too.

For a rest based web server or a program in general what kind of code structures lend themselves to Scala's functional programming style.


问:
Why is NoSQL faster than SQL?
Recently I was asked:

Why is NoSQL faster than SQL?

I didn't agree with the premise of the question... it's just nonsense for me personally. I can't see any performance boost by using NoSQL instead of SQL. Maybe SQL over NoSQL, yes but not in that way.

Am I missing something about NoSQL?

答:
NoSQL databases normally only make sense if you design your data around them.

If you intend to simply use them as a RDBMS replacement, then you might get less performance rather than more, especially if you don't have enough budget to pay for servers with high amounts of RAM.

Look at this article which compares MySQL disk space usage with that of MongoDB: http://blog.trackerbird.com/content/mysql-vs-mongodb-disk-space-usage

Title: Why is NoSQL faster than SQL?


问:
Is it legal and ethical to reverse engineer software to port it to another system?
I love gaming, I love games that allow modding and I love linux. But the fact that most games right now are targeted for windows (consoles aside), most mods and modding tools are also targeted for windows. There is a certain modder called Boris Vorontsov that makes a famous visual overhaul mod series called ENB.

What he does (or I think he does) is he enhances or changes the behavior of classes defined in the d3d9.dll library. Needless to say it almost never works under wine.

Recently I have asked him if he would ever release his version of the library under some open license, and he said "no". Now that I think of it, even if he did release his code, he would have surely faced some legal problems.

Now there is my question. Is it legal and ethical to reverse engineer his version of the library to adapt the wine's open source version of d3d9.dll to be able to run his mods?

答:
Legal? -> ask a lawyer. Anyway, this depends strongly on the country you distribute your adaptation.

Ethical? -> ask the authors. All of them. Some may see this as a tribute, others as a robbery.


答: As other said, the keybindings are more or less mnemonics, and to understand them you have to know that the terminals on which emacs keybindings have been designed hadn't always arrows keys, and were generating only ASCII code (so CTRL-H is the same as backspace, if there was a backspace, CTRL-I as the tabulation, CTRL-J/CTRL-M as enter/return) and the CTRL key was were the CapsLock is now or next to it.</p>

Title: emacs keybindings

Body:
I read a lot about vim and emacs and how they make you much more productive, but I didn't know which one to pick. Finally when I decided to teach myself common lisp, the decision was straight forward: everybody says that there's no better editor for common lisp, than emacs + slime. So I started with emacs tutorial and immediately I ran into something that seems very unproductive to me. I'm talking about key bindings for cursor keys:

```<code>forward/backward: Ctrl+f, Ctrl+b
up/down: Ctrl+p, Ctrl+n
</code>```

I find these bindings very strange. I assume that fingers should be on their home rows (am I wrong here?), so to move cursor forward or backward I should use my left index finger and for up and down right pinky and right index fingers. When working with any of Windows IDEs and text editors to navigate text I usually place my right hand in a position so that my thumb is on the right ctrl and my index, ring and middle fingers are on the cursor keys. From this position it is very easy and comfortable to move cursor: I can do one-character moves with my 3 right fingers, or I can press ctrl with my right thumb and do word-moves instead. Also I can press shift with my left pinky and do single-character or word selections. Also it is a very comfortable position to reach PgUp, PgDn, Home, End, Delete and Backspace keys with my right hand. So I have even more navigation and selection possibilities. I understand that the decision not to use cursor keys is to allow one to use emacs to connect to remote terminal sessions, where these keys are not supported, but I still find the choice of cursor keys very unfortunate. Why not to use j, k, i, l instead? This way I could use my right hand without much finger stretching. So how is emacs more productive? What am I doing wrong?


问:
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!

答:
Reverse of a string recursively

```<code> if ( str.length() <= 1)  { return str; // stopping case }
 else { return reverse(str.substring(1)) + str.charAt(0); // recursion   }
</code>```

Body:
Reverse of a string recursively

 if ( str.length() <= 1)  { return str; // stopping case }
 else { return reverse(str.substring(1)) + str.charAt(0); // recursion   }


问:
Objective C style nil in java?
Objective C has a concept of a nil object which would accept any method call with any parameters without complaining and silently return another nil.

I have used something similar in Java using easymock and mockito for testing. Is there something similar for main line code? Is it even a good idea to have something like this?

One use-case where I am considering using it is with optional metrics. We have codahale metrics counters on which we call mark() every time an event is generated. This is surrounded by an If/then to check for metrics enabled flag. I could just use a nil object as counter and silently accept the mark call if metrics are not enabled.

答:
This is a fundamental part of the Objective-C runtime. On every single method call, the first thing it does is check if the object reference is nil, and immediately returns if so. The Java runtime surely does a similar check, but responds by throwing a NullPointerException. So you're asking how to change the fundamental behaviour of the runtime.

There are a couple of ways to achieve a similar effect in Java:

Create a dummy implementation of your metrics interface that does nothing. Assign this to your metrics object variable.

or: Create a single, static entry point to your metrics class, and pass in the instance as the first argument, and check if it's null before doing anything else. e.g.

.

```<code>public static void doMetrics(Metrics m, otherArgs ...) {
    if (m == null) return;

    ... do stuff with m ...
}
</code>```

Both of these come at the minor performance cost of a pointless method call when metrics are switched off.

Title: Objective C style nil in java?

Body:
This is a fundamental part of the Objective-C runtime. On every single method call, the first thing it does is check if the object reference is nil, and immediately returns if so. The Java runtime surely does a similar check, but responds by throwing a NullPointerException. So you're asking how to change the fundamental behaviour of the runtime.

There are a couple of ways to achieve a similar effect in Java:

Create a dummy implementation of your metrics interface that does nothing. Assign this to your metrics object variable.

or: Create a single, static entry point to your metrics class, and pass in the instance as the first argument, and check if it's null before doing anything else. e.g.

.

public static void doMetrics(Metrics m, otherArgs ...) {
    if (m == null) return;

    ... do stuff with m ...
}

Both of these come at the minor performance cost of a pointless method call when metrics are switched off.


问:
Print all values in a value object
I have to debug an issue which requires me to print all the values of a Value Object that is returned by a web service call. The Value object is a complex object in the sense, it has another object as its member which in turn has another object.

Printing all the values by using get methods is cumbersome. So I was wondering if there is a way to break down the value object by any way to get to a primitive level like String or int or Date and print them all using one API?

I had a look at the below question but my prob is that I don't have access to the source code of the value object. The sources are in obfuscated jar.

https://stackoverflow.com/questions/2413001/how-to-print-values-of-an-object-in-java

答:
You can use recursion to discover subfields structure</p>

```<code>public static void dump(Object o){
    Field[] fields = ReflectUtils.getFields(o.getClass());
    try{
        for(Field field : fields){
            field.setAccessible(true);
            Object value = field.get(o);
            System.out.println(field.getName() + "=" + field.get(o));
        }
    }catch(Exception e){
        e.printStackTrace();
    }
}
</code>```

Title: Print all values in a value object

Body:
You can use recursion to discover subfields structure

public static void dump(Object o){
    Field[] fields = ReflectUtils.getFields(o.getClass());
    try{
        for(Field field : fields){
            field.setAccessible(true);
            Object value = field.get(o);
            System.out.println(field.getName() + "=" + field.get(o));
        }
    }catch(Exception e){
        e.printStackTrace();
    }
}


答:
Java doesn't have this built in - it's a programmer error to call a message on null which causes a runtime exception. However, there is a pattern called the Null Object Pattern, which programmers use to provide their own equivalent.

Imagine that you have some interface, representing a connection to a database. You might define the interface like this:

```<code>public interface DatabaseConnection {
public void connect(String username, String password, URL databaseLocation);
public void disconnect();
public String executeQuery(String query);
}
</code>```

Your Null Object might look like this:

```<code>public class NullDatabaseConnection implements DatabaseConnection {
public void connect(String username, String password, URL databaseLocation) {}
public void disconnect() {}
public String executeQuery(String query) { return ""; }
}
</code>```

The disadvantage of doing this compared with the ObjC approach is that you have to write the above code - you can't automatically get the behaviour by using the nil object. The advantage is that this explicit Null object works as you'd expect in all cases: you can put it into a collection for example, something you can't do with Objective-C's nil.

Title: Objective C style nil in java?

Body:
Objective C has a concept of a nil object which would accept any method call with any parameters without complaining and silently return another nil.

I have used something similar in Java using easymock and mockito for testing. Is there something similar for main line code? Is it even a good idea to have something like this?

One use-case where I am considering using it is with optional metrics. We have codahale metrics counters on which we call mark() every time an event is generated. This is surrounded by an If/then to check for metrics enabled flag. I could just use a nil object as counter and silently accept the mark call if metrics are not enabled.

Body:
Java doesn't have this built in - it's a programmer error to call a message on null which causes a runtime exception. However, there is a pattern called the Null Object Pattern, which programmers use to provide their own equivalent.

Imagine that you have some interface, representing a connection to a database. You might define the interface like this:

public interface DatabaseConnection {
public void connect(String username, String password, URL databaseLocation);
public void disconnect();
public String executeQuery(String query);
}

Your Null Object might look like this:

public class NullDatabaseConnection implements DatabaseConnection {
public void connect(String username, String password, URL databaseLocation) {}
public void disconnect() {}
public String executeQuery(String query) { return ""; }
}

The disadvantage of doing this compared with the ObjC approach is that you have to write the above code - you can't automatically get the behaviour by using the nil object. The advantage is that this explicit Null object works as you'd expect in all cases: you can put it into a collection for example, something you can't do with Objective-C's nil.


问:
Results stored in a session - good idea?
To give a bit of background, lets say it's a generic results page, which is paginated so there are X results per page.

Generally to do this, I have two queries on the page:

to get the total number of results

to get the results, limiting by the correct page's resultset

However, recently I've been trying to cut down on the queries the site is making, and I thought one way to do this would be to only do the query if any parameters to the page have changed (except of course the page number)?

This would then cache all the result id's in a session, which can be sliced when I need to return the correct resultset for that page.

I was trying to look around the net to see if there are downsides of this method, but I've found very little information about it.

Has anyone done this before?
Is it a good idea?

答:
It's a bad idea.

Assuming the default setup for sessions, you'd be replacing calls to the database with calls to the filesystem, you'd be moving from a storage that scales to one that generally doesn't. Sessions are extremely convenient, but they should be used as sparingly as possible, especially the (default) file based flavour. If you use them for caching, you'd be setting yourself for a world of trouble:

PHP writes its session data to a file by default. When a request is made to a PHP script that starts the session (session_start()), this session file is locked. What this means is that if your web page makes numerous requests to PHP scripts, for instance, for loading content via Ajax, each request could be locking the session and preventing the other requests from completing.

The other requests will hang on session_start() until the session file is unlocked. This is especially bad if one of your Ajax requests is relatively long-running.

And why would you want to cut down on the queries the site is making in the first place? If you have identified that the queries are somehow, you should first try to optimize them. Caching your result-sets in addition to optimizing your queries would be great, but do it properly:

MySQL query cache, and/or

memcached

There are various other cache backends that you could try (for example DynamoDB), but memcached should be enough for most common scenarios, and it would certainly be more fitting for pagination results than sessions.


答:
If the resultset can be pretty large and the user most likely never wants to scan through all pages, it's probably a big waste of resources to read and store all the results just in case.

A strategy that worked pretty well for me in the past is cache some results, and to double the cache size the further the user goes into the results. When a user goes past page 2, the system reads pages 3 and 4. If he goes past page 4, pages 5..8 will be read. This way, the number of queries is limited but I wont have to keep a cache with all millions of results.

Title: Results stored in a session - good idea?

Body:
To give a bit of background, lets say it's a generic results page, which is paginated so there are X results per page.

Generally to do this, I have two queries on the page:

to get the total number of results

to get the results, limiting by the correct page's resultset

However, recently I've been trying to cut down on the queries the site is making, and I thought one way to do this would be to only do the query if any parameters to the page have changed (except of course the page number)?

This would then cache all the result id's in a session, which can be sliced when I need to return the correct resultset for that page.

I was trying to look around the net to see if there are downsides of this method, but I've found very little information about it.

Has anyone done this before?
Is it a good idea?


答:
A typical example if you want to illustrate conciseness of functional code could use collections and their operations. E.g. consider a class Customer and a method creating a sorted list of customer names from a list of customers.

Here is the Java implementation:

```<code>class Customer
{
    String name;

    ... // Other attributes.
}

List<String> sortedCustomerNames(List<Customer> customers)
{
    List<String> names = new ArrayList<String>();

    for (Customer customer : customers)
        names.add(customer.name);

    Collections.sort(names);

    return names;
}
</code>```

Scala version:

```<code>class Customer(val name: String, /* ... other attributes */)

def sortedCustomerNames(customers: List[Customer]): List[String] =
  customers.map(c => c.name).sorted
</code>```

NOTE

Conciseness in terms of keystrokes is not always a good measure of code quality and maintainability.

Also, in general I would not advise to switch from Java to Scala just because Scala is newer. If most of the team members are more familiar with Java, the team will be much more productive with Java than with Scala (or any other programming language they don't know well).

I have been learning Scala in my free time for about two years now, and only recently (after attending an online course) I got the feeling I can be more productive in Scala than I am in Java. Before reaching this point, I would not have considered using Scala for production.

Title: What is a good use case for scala?

Body:
A typical example if you want to illustrate conciseness of functional code could use collections and their operations. E.g. consider a class Customer and a method creating a sorted list of customer names from a list of customers.

Here is the Java implementation:

class Customer
{
    String name;

    ... // Other attributes.
}

List<String> sortedCustomerNames(List<Customer> customers)
{
    List<String> names = new ArrayList<String>();

    for (Customer customer : customers)
        names.add(customer.name);

    Collections.sort(names);

    return names;
}

Scala version:

class Customer(val name: String, /* ... other attributes */)

def sortedCustomerNames(customers: List[Customer]): List[String] =
  customers.map(c => c.name).sorted

NOTE

Conciseness in terms of keystrokes is not always a good measure of code quality and maintainability.

Also, in general I would not advise to switch from Java to Scala just because Scala is newer. If most of the team members are more familiar with Java, the team will be much more productive with Java than with Scala (or any other programming language they don't know well).

I have been learning Scala in my free time for about two years now, and only recently (after attending an online course) I got the feeling I can be more productive in Scala than I am in Java. Before reaching this point, I would not have considered using Scala for production.


问:
Automatic generate code: "derived work"?
For example, I've GPL software. I'm the author of this GPL software. This GPL software has, between its code, Doxygen comments. These Doxygen comments are written to generate a CC-BY-SA html page, in order to upload this generated documentation in my project website under CC-BY-SA license.

But, is the Doxygen documentation output a "derivate work"? After all, this documentation is based on my GPL source code. In this case, the documentation must be GPL. But, I want the documentation is CC-BY-SA, because it is documentation. GFDL doesn't help. GPL code can't become GFDL (the opposite yes).

If this output is really a derivate work, I think, creates a strange situation, because, if I distribute my work, recipient users can't legally distribute the generated documentation: while with my work I can do I want, the users don't, thus, they have to distribute any derivated work with the same license I offer them.

What is the solution?

答:
This is really a tricky question (of the ask-your-lawyer kind).

Since you are the author of the software, you can make your intentions clear and avoid any ambiguities by adding a "Doxygen-comments are CC-BY-SA" exception to your license, along the lines of:

```<code>Additional permission under GNU GPL version 3 section 7

In addition, as a special exception, the copyright holders of [name of your program]
give you permission to distribute the Doxygen comments in this source and any work
derived from those comments ("the documentation") under the CC-BY-SA license.
</code>```

Body:
This is really a tricky question (of the ask-your-lawyer kind).

Since you are the author of the software, you can make your intentions clear and avoid any ambiguities by adding a "Doxygen-comments are CC-BY-SA" exception to your license, along the lines of:

Additional permission under GNU GPL version 3 section 7

In addition, as a special exception, the copyright holders of [name of your program]
give you permission to distribute the Doxygen comments in this source and any work
derived from those comments ("the documentation") under the CC-BY-SA license.


问:
Demonstrate bad code to client?
A client has asked me to do a redesign of their website, an ASP.NET Webforms application that was developed by another consultant. It seemed like a relatively straightforward job, but after looking at the code, it's clear that's not the case.

This application was not written well. At all. It is extremely vulnerable to SQL injection attacks, business logic is spread throughout the entire application, there is a lot of duplication, and dead end code that does nothing. On top of that, it keeps throwing exceptions that are being smothered, so site appears to run smoothly.

My job is to simply update the HTML and CSS, but much of the HTML is being generated in business logic and would be a nightmare to sort out. My estimate on the redesign is longer than the client was aiming for. They are asking why so long.

How can I explain to my client just how bad this code is? In their mind, the application is running great and the redesign should be a quick one-off. It's my word against the previous consultant. How can I give simple, concrete examples that a non-technical client will understand?

Update

Thanks for all the responses.
The SQL injection attack demonstration makes sense and I will demo this in a test environment.
That is just one part of many problems in this application. I was looking for ways to explain why other parts (such as html being generated in the data layer)
would need to be replaced with better practices in order for the html and css update to take place.
There are many good suggestions here which I'll piece together when I talk with my client.

答:
Certainly the SQL injection attacks and other functional flaws in the application took precedence, but you can also "demonstrate" bad code quality and practices.
With code metrics tools you can clearly demonstrate how bad is the code and show him how much this will it add up in cost for any future changes and bug fixing.
I'm not familiar with .net environment but I'm sure there are several from which to pick up.</p>

Title: Demonstrate bad code to client?


问:
Why are there so many programming languages? Why are new languages still being made?
Why are there so many programming languages?

And what prompts someone to create a programming languages in spite of the fact that other languages already exist?

答:
new programming languages are built for many different reasons, mostly because there are new programming paradigm, or because of advances in hardware people create new language to take advantage of the new hardware features like multitasking, etc.

in my case, I usually build small compilers( with a new programming language), for specialty reason. if I make allot of games, and I believe that a programming language specifically made for game development will result in smaller faster code and faster development turn around, then I build it. and at then end it turns out that it can also be used for other general purpose programming.

I think most people who create programming languages have a specific purpose in mind, there are those who create them for general purpose from the beginning. but most are not.

By the way, I do think there are way too many programming languages, but hundred of new ones will always come out. some out of fun, some out of a niche purpose, as a school project, or for hundreds of other reasons. and sooner or later a new one will become popular. Its never going to end.


问:
What's the web framework to use on a front-end web application?
What do you consider a good client web framework to use on interface business application? jQuery? YUI!? Another? Some plugins useful?

The application will be use mostly internally replacing a desktop application for data entry and lots of queries/views.

答:
Depends on your budget and the the licensing details, but I've always been a big fan of jQuery + ExtJS. jQuery is a fantastic tool for working with the DOM and a simple AJAX Framework, and throwing ExtJS on top of jQuery beings it all together. ExtJS is the best JavaScript UI kit that I've ever worked with. It's fast, never ran into a bug (but it has its quirks), and commercial support is available - if you need it.

ExtJS has a lot of features that a LOB application would benefit from, such as the desktop and charting. The charts are flash based but its part of the same package.

The fact it is commercial irks some people, but overall it's a well rounded framework that fills a lot of gaps.


问:
Lua and multi-paradigm programming: scope and capabilities
Despite having started learning programming with Pascal and C, after the jump to OO (C++, Java) I lost sense of the structured programming paradigm. I have started learning Lua and I have researched many tutorials, but all of them only cover basic operations and language features and capabilities. They feel more like a reference doc than a programmer's guide.

Now, when trying to work with day to day tasks, how does one go through most common design patterns like observer, or multithreaded programming, creating UI elements and polling system calls for keyboard or sensors? Is it even feasible in this languages or you have to work with the C binding, libraries and low-level programming to get most stuff done? Do I get the Lua scope wrong?

答:
Lua is, in many ways, very similar to Scheme: procedural with first-class and higher-order procedures, block-structured, lexically scoped with lexical closures, proper tail calls, use of a single pervasive data structure (list in Scheme, table in Lua) throughout the entire language.

The Scheme community has produced some extremely high quality programming books and tutorials, which are all more or less directly applicable to Lua.

How to Design Programs – An Introduction to Programming and Computing by Matthias Felleisen, Robert Bruce Findler, Matthew Flatt, and Shriram Krishnamurthi. They are currently working on a second edition, and after that, a second volume (How to Design Components).

Concrete Abstractions - An Introduction to Computer Science Using Scheme by Max Hailperin, Barbara Kaiser, Karl Knight.

The Little Schemer by Daniel P. Friedman and Matthias Felleisen

The Seasoned Schemer by Daniel P. Friedman and Matthias Felleisen

The Reasoned Schemer by Daniel P. Friedman, William E. Byrd and Oleg Kiselyov

Structure and Interpretation of Computer Programs by Gerald Jay Sussman and Guy L. Steele, Jr.

and many many many others.

One important difference between the two languages is that even though both are impure imperative languages, the Scheme community actually prefers a very purely functional, immutable, side-effect-free, declarative programming style than the Lua community. So, if you learn Lua via Scheme, your code might not be fully idiomatic Lua. I don't think that's a bad thing: first of all, functional programming is a good thing, and secondly, you already know imperative programming from your forays into Pascal, C, C++ and Java anyway.


答:
To be a "derivative work", something must first be a work. Under United State law, only a creative process can create a work. An automated process cannot create a derivative work because it cannot create a work that didn't exist before. (Other than a few specific exceptions created by statute.)

If you think about it, it can't be a derivative work. Say you run program A on text B and produce work C. If this is a new derivative work, who holds copyright on it? No human being created it, and a program can't hold copyright.

Non-creative combinations can't create any new work, derivative or not. What mechanical processes can create is an aggregate work. It's legally the same as if I glued two DVDs together (or combined two files on the same storage medium). There's no derivative work, but the two DVDs stapled together are an aggregate of both works.

See 17 USC 103(b): "The copyright in a compilation or derivative work extends only to the material contributed by the author of such work, as distinguished from the preexisting material employed in the work, and does not imply any exclusive right in the preexisting material."

Also see circular 14.

Who would the author of the derivative work be?

Title: Automatic generate code: "derived work"?

Body:
For example, I've GPL software. I'm the author of this GPL software. This GPL software has, between its code, Doxygen comments. These Doxygen comments are written to generate a CC-BY-SA html page, in order to upload this generated documentation in my project website under CC-BY-SA license.

But, is the Doxygen documentation output a "derivate work"? After all, this documentation is based on my GPL source code. In this case, the documentation must be GPL. But, I want the documentation is CC-BY-SA, because it is documentation. GFDL doesn't help. GPL code can't become GFDL (the opposite yes).

If this output is really a derivate work, I think, creates a strange situation, because, if I distribute my work, recipient users can't legally distribute the generated documentation: while with my work I can do I want, the users don't, thus, they have to distribute any derivated work with the same license I offer them.

What is the solution?


问:
Storing translation data as JSON column
We're deciding on how to store translations of some descriptions of database items.

We could go the traditional way and keep a translations table (and a language table and an object_translation linking table) OR we thought it might be better to just have a Description column that contains JSON like the following:

```<code>{
     "EN": "This is the translation in English",
     "EE" : "See on kirjeldus eesti keeles"
}
</code>```

Are there any serious downsides as to why we shouldn't use this? (I haven't seen it being used anywhere else)

答: I see no reason to store JSON directly in the database. As mentioned in a previous thread you cannot query the database directly and the performance gains are insignificant.  Creating JSON programatically from the database will be insignificant compared to the time it takes to actually hit the database and query (whether query for JSON or using standard SQL)</p>

Title: Storing translation data as JSON column


问:
emacs keybindings
I read a lot about vim and emacs and how they make you much more productive, but I didn't know which one to pick. Finally when I decided to teach myself common lisp, the decision was straight forward: everybody says that there's no better editor for common lisp, than emacs + slime. So I started with emacs tutorial and immediately I ran into something that seems very unproductive to me. I'm talking about key bindings for cursor keys:

```<code>forward/backward: Ctrl+f, Ctrl+b
up/down: Ctrl+p, Ctrl+n
</code>```

I find these bindings very strange. I assume that fingers should be on their home rows (am I wrong here?), so to move cursor forward or backward I should use my left index finger and for up and down right pinky and right index fingers. When working with any of Windows IDEs and text editors to navigate text I usually place my right hand in a position so that my thumb is on the right ctrl and my index, ring and middle fingers are on the cursor keys. From this position it is very easy and comfortable to move cursor: I can do one-character moves with my 3 right fingers, or I can press ctrl with my right thumb and do word-moves instead. Also I can press shift with my left pinky and do single-character or word selections. Also it is a very comfortable position to reach PgUp, PgDn, Home, End, Delete and Backspace keys with my right hand. So I have even more navigation and selection possibilities. I understand that the decision not to use cursor keys is to allow one to use emacs to connect to remote terminal sessions, where these keys are not supported, but I still find the choice of cursor keys very unfortunate. Why not to use j, k, i, l instead? This way I could use my right hand without much finger stretching. So how is emacs more productive? What am I doing wrong?

答:
I find these bindings very strange.
   ...
  What am I doing wrong?

You should find them strange, because they are, or they will be until you've taken sufficient time to get accustomed to them.  If you haven't got past the tutorial, what you're doing wrong is not giving yourself time to get settled in with it before making comparisons to things that are already familiar.

Choosing an editor for long-term use is a commitment that is, in many ways, like finding someone to marry.  On the first date, everything is completely unfamiliar and maybe uncomfortable.  As time goes on you'll become more at ease and find the relationship to be a mixture of things you like, things you don't and things you can learn to like or at least tolerate.  If the overall balance is wrong, you end it and go on to whatever's next.  If it's right, you stick with it and you've got a partner for life.  One thing I can guarantee is that drawing comparisons to your ex girlfriend on the first date will cause the relationship not to go well.

After a few years' daily use of vi (25-ish years ago), I started using Emacs and it's been my editor of choice since.  I'm not here to extol the virtues of one over the other (or either over anything else), but I will say my first couple of weeks with both were no picnic.  I needed to keep reference material handy, and my work was clunky and slower until I learned what I needed.  After awhile, the situation improved and now most things I do with are so reflexive that I don't have to think about them.  The same would be true for almost any tool, and the things that are most worth learning have a steeper learning curve.

So how is emacs more productive?

Your metric for productivity appears to be level of comfort with the key bindings, so the answer for Emacs and any other tool you're not using daily would be "it isn't."

My metric for productivity is how long it takes me to do the things I do often and whether or not the tool can be adapted to reduce that time.

Case in point: I frequently need to transform parts of my buffers using command-line filter programs.  Emacs provides shell-command-on-region (bound to M-| by default), which gets me halfway there by running the command and putting the results in a new buffer.  Using that meant I had to go through a bunch of machinations to get the text out of the new buffer and replace what I'd selected.  To make myself more productive, I wrote shell-command-in-region, which is about nine lines of Emacs LISP, bound it to M-# and have used it more times than I can count.

People have written hundreds, if not thousands, of these sorts of add-ons that range from simple things like what I described to interfaces to version control systems to entire applications like the mail reader I've used on a daily basis since the late 1980s.  (I do use others, but this one works great in a terminal.)

On a related note:  A number of answers and comments have suggested that the key bindings in Emacs are customizable.  They are, but I advise against rebinding the basics.  Doing so ties you to your customizations and will leave you fumbling when you have to run Emacs on a system where you can't just dump your .emacs into place.

Title: emacs keybindings


问:
Should I give the answer to a failed interview coding exercise?
We had a senior level interview candidate fail a nuance of the FizzBuzz question12.

I mean, really, utterly, completely, failed the question - not even close.

I even coached him through to thinking about using a loop and that 3 and 5 were really worth considering as special cases.

He blew it.

Just for QA purposes, I gave the same exact question to three teammates; gave them 5 minutes; and then came back to collect their pseudo-code.  All of them nailed it and hadn't seen the question before.  Two asked what the trick was...

On a different logic exercise, the candidate showed some understanding of some of the features available within the language he chose to use (C#).  So it's not as if he had never written a line of code.  But his logic still stunk.

My question is whether or not I should have given him the answer to the logic questions.

He knew he blew them, and acknowledged it later in the interview.

On the other hand, he never asked for the answer or what I was expecting to see.

I know coding exercises can be used to set candidates up for failure (again, see second link from above).  And I really tried to help him home in on answering the core of the question.  But this was a senior level candidate and Fizz-Buzz is, frankly, ridiculously easy even after accounting for interview jitters.

I felt like I should have shown him a way of solving the problem so that he could at least learn from the experience.  But again, he didn't ask.

What's the right way to handle that situation?

1Okay, that's not the link to the actual FizzBuzz question, but it is a good P.SE discussion around FizzBuzz and links to the various aspects of it.

2 To help clarify, this is the nuance of Fizz-Buzz I asked and it's from Project Euler's first problem.  Substitute printing Fizz | Buzz for summing the numbers and you have the same fundamental question.

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.  Write a function that finds the sum of all the multiples of 3 or 5 below 1000.

3 This question attracted more attention than I had expected, and I appreciate all of the replies.  Some of the later answers have really gotten to the core of my question, so I'll allow the community to review and up-vote before assigning "the" answer.

4 I selected "the" answer based upon community votes at that point in time.  And I think Yannis' answer is appropriate for interviews with newer devs.  I think the collective response focusing on the lack of asking for the answer is spot-on as well.

答:
I felt like I should have shown him a way of solving the problem so
  that he could at least learn from the experience. But again, he didn't
  ask. What's the right way to handle that situation?

I don't care what level the interview is for, nor even really if its a "FizzBuzz"-level question or an advanced question. If you ask a candidate to solve a question, and they can't, but don't even bother asking you for the right answer then they aren't worth your time. How in the world could you be so intellectually lazy?!?

And even if you totally stink as a programmer and are just trying to buffalo your way into a job, why wouldn't you at least be so pragmatic as to get the right answer now, so that you know it for the next interview?

So no, you shouldn't "give" the answer, but you should expect to have the candidate insist on hearing the right answer after they fail. If they don't, its a huge red flag in my book.

If someone blew FizzBuzz in a junior level Dev interview because they couldn't remember the modulus operator and just couldn't bring themselves to move on without it, but they then got all passionate about re-doing it once you explained the right answer, or at least talking through the right code with you, then that's almost as good as answering it correctly.


问:
C simple arrays and pointers question
So here's the confusion, let's say I declare an array of characters

```<code>char name[3] = "Sam";
</code>```

and then I declare another array but this time using pointers

```<code>char * name = "Sam";
</code>```

What's the difference between the two? I mean they work the same way in a program. Also how does the latter store the size of the stuff that someone puts in it, in this case 3 characters?

Also how is it different from

```<code>char * name = new char[3];
</code>```

If those three are different where should they be used I mean in what circumstances?

答:
In addition to what others have explained, I would like to illustrate the first example a bit more in detail. As Mohit Sehgal pointed out, in C the declaration

```<code>char name[3] = "Sam";
</code>```

only allocates three bytes for the variable name, and puts no 0 string terminator: name[0] == 'S', name[1] == 'a', name[2] == 'm', name[3] == whatever is contained at the next address after that last (third) byte of name. For example, try out the following program:

```<code>#include <stdio.h>

char s[3] = "abc";
char t[]  = "def";

int main(int argc, char *argv[])
{
  printf("s = '%s'\n", s);
  printf("t = '%s'\n", t);
}
</code>```

The result will be:

```<code>s = 'abcdef'
t = 'def'
</code>```

because t has been allocated right after s and s now points to a string that goes on until the 0 terminator of t is found.

If you declare an array with initialization but without dimension, enough space for all the data in the initialization list will be allocated. Therefore

```<code>#include <stdio.h>

char s[] = "abc";
char t[] = "def";

int main(int argc, char *argv[])
{
  printf("s = '%s'\n", s);
  printf("t = '%s'\n", t);
}
</code>```

will print

```<code>s = 'abc'
t = 'def'
</code>```

I have tested the same declarations in C++ (using the GNU compiler), and

```<code>char name[3] = "Sam";
</code>```

gives a compiler error because the string initializer (which C++ considers of length 4, including the trailing 0) is too long for the variable.

So, both in C and C++, the compiler will not allocate more bytes than are specified in the declaration.

Title: C simple arrays and pointers question

Body:
In addition to what others have explained, I would like to illustrate the first example a bit more in detail. As Mohit Sehgal pointed out, in C the declaration

char name[3] = "Sam";

only allocates three bytes for the variable name, and puts no 0 string terminator: name[0] == 'S', name[1] == 'a', name[2] == 'm', name[3] == whatever is contained at the next address after that last (third) byte of name. For example, try out the following program:

#include <stdio.h>

char s[3] = "abc";
char t[]  = "def";

int main(int argc, char *argv[])
{
  printf("s = '%s'\n", s);
  printf("t = '%s'\n", t);
}

The result will be:

s = 'abcdef'
t = 'def'

because t has been allocated right after s and s now points to a string that goes on until the 0 terminator of t is found.

If you declare an array with initialization but without dimension, enough space for all the data in the initialization list will be allocated. Therefore

#include <stdio.h>

char s[] = "abc";
char t[] = "def";

int main(int argc, char *argv[])
{
  printf("s = '%s'\n", s);
  printf("t = '%s'\n", t);
}

will print

s = 'abc'
t = 'def'

I have tested the same declarations in C++ (using the GNU compiler), and

char name[3] = "Sam";

gives a compiler error because the string initializer (which C++ considers of length 4, including the trailing 0) is too long for the variable.

So, both in C and C++, the compiler will not allocate more bytes than are specified in the declaration.


答: For my money, you can't beat jQuery. It makes working with JavaScript just that much easier. The out-of-the-box GUI side of things is limited, but there are lots of 3rd party extensions for grids and such that may be of help for your views.</p>

Title: What's the web framework to use on a front-end web application?

Body:
What do you consider a good client web framework to use on interface business application? jQuery? YUI!? Another? Some plugins useful?

The application will be use mostly internally replacing a desktop application for data entry and lots of queries/views.


问:
About insertion sort and especially why it's said that copy is much faster than swap?
From Lafore's "Data Structures and Algorithms in Java":
(about insertion sort (which uses copy + shift instead of swap (used in bubble and selection sort)))

However, a copy isn’t as time-consuming as a swap, so for random data
  this algo- rithm runs twice as fast as the bubble sort and faster than
  the selectionsort.

Additionally, the author doesn't mention how time consuming shift is.

It seems that copying is the simplest pointer assignment operation. While swap is 3 pointer assignment operations, which don't take much time. Further, shift of N elements is N pointer assignment operations.

Can someone explain this seeming inconsistency?

答: You aren't doing one swap/copy you are doing roughly n log(n) swaps/copies. So you get 3n log(n) assignments for swapping or n log(n) + n assignments for copy.


问:
What is a good use case for scala?
In a current project we have setup the build so that we could mix Java and Scala. I would like to use more Scala in our code base to make the code more readable and concise. In the process also learn the language by handing over real features.

So I plan to use Scala for some classes to showcase its benefits and convince other devs to look into using Scala too.

For a rest based web server or a program in general what kind of code structures lend themselves to Scala's functional programming style.

答:
I suspect this is a matter of how good the programmers on the team are and how much they are willing to learn new things.

Scala is much more concise and expressive, but equally more complex. Any programmer who can make a good use of the high level abstractions it offers will like it and be more productive in it and will never want to go back to the oversimplified level of Java. But a programmer who is not good at high level abstractions or simply does not want to learn will never get it.

Also I don't think you should use any cases tailored specifically to Scala. Just start writing the prototype in it and you'll see whether it's more productive or not. It should be more productive for everything to be worth switching.

And I definitely wouldn't mix the languages except for using libraries written in the other. Start prototyping in Scala, see how well it goes and choose one or the other.

Title: What is a good use case for scala?


问:
Quality Assurance activities

Possible Duplicate:

  Verification of requirements question

Having asked but deleted the question as it was a bit misunderstood. If Quality Control is the actual testing, what are the commonest true quality assurance activities? I have read that verification (reviews, inspections..) but it does not make much sense to me as it looks more like quality control as mentioned here:

DEPARTMENT OF HEALTH AND HUMAN SERVICES
ENTERPRISE PERFORMANCE LIFE CYCLE FRAMEWORK
Practices guide

Verification - “Are we building the product right?” Verification is a
  quality control technique that is used to evaluate the system or its
  components to determine whether or not the project’s products satisfy
  defined requirements. During verification, the project’s processes are
  reviewed and examined by members of the IV&V team with the goal of
  preventing omissions, spotting problems, and ensuring the product is
  being developed correctly.

  Some Verification activities may include
  items such as: • Verification of requirement against defined
  specifications • Verification of design against defined specifications
  • Verification of product code against defined standards •
  Verification of terms, conditions, payment, etc., against contracts

And the opposite (project management knowledge scope - google result)
Verification is a quality assurance process or technique applied by ...

答:
Quality Assurance is not about the results, but rather the process.  QA is responsible for the process of creating a product.

In a software world, the activities of QA may revolve around:

Audits of the code (the developers said this code is following the coding standards of the company, lets look at it)

Verifying that the process to build the code has the necessary steps and checks in it ("This project has not allocated any time to code reviews - that needs to be corrected")

The tools for tracking ("Excel spreadsheets are not a bug tracking mechanism - they do not meet the minimum acceptable requirements for a bug tracking system")

Checking the schedule ("The last three projects had one week of debugging for every 2 ksloc - this project is estimated at 10 ksloc but only one week of testing is allocated")

Looking at the requirements and deliverables ("The requirements mandate feature XYZ but there are no tests that address this functionality")

In areas where there are defined standards (aircraft, life support, critical infrastructure, etc...), making certain that all of the standards and processes associated from those realms are followed.

QA will also be likely doing things such as ISO standards and mention such words as "Six Sigma."

In theory, the interaction between developers and QA is rare as QAs activities tend to be at a higher level in the management chain.

Title: Quality Assurance activities


问:
Is there an antipattern to describe this method of coding?
I have a codebase where the programmer tended to wrap things up in areas that don't make sense.  For example, given an Error log we have you can log via

```<code>ErrorLog.Log(ex, "friendly message");
</code>```

He added various other means to accomplish the exact same task.  E.G.

```<code>SomeClass.Log(ex, "friendly message");
</code>```

Which simply turns around and calls the first method.  This adds levels of complexity with no added benefit.  Is there an anti-pattern to describe this?

答:
I'm not sure to describe this as an offense to the single responsibility principle, because if there is a change to the ErrorLog method signature (the method that is called by SomeClass), every client code that calls this method will fail.

There is obviously a way to use inheritance (or making classes that needs logging implementing a logging interface) there.


答:
It is only worthwhile to call some bad coding habit an Antipattern if it is reasonably widespread.

The rest we just call "rubbish code" ...

If I was to suggest a name for this particular bad habit, it would be "Obsessive Abstraction Disorder" :-)

Title: Is there an antipattern to describe this method of coding?

Body:
I have a codebase where the programmer tended to wrap things up in areas that don't make sense.  For example, given an Error log we have you can log via

```<code>ErrorLog.Log(ex, "friendly message");
</code>```

He added various other means to accomplish the exact same task.  E.G.

```<code>SomeClass.Log(ex, "friendly message");
</code>```

Which simply turns around and calls the first method.  This adds levels of complexity with no added benefit.  Is there an anti-pattern to describe this?


问:
Am I sending large amounts of data sensibly?
I am about to design a video conversion service, that is scalable on the conversion side.

The architecture is as follows:

Webpage for video upload

When done, a message gets sent out to one of several resizing servers

The server locates the video, saves it on disk, and converts it to several formats and resolutions

The resizing server uploads the output to a content server, and messages back that the conversion is done.

Messaging is something I have covered, but right now I am transferring via FTP, and wonder if there is a better way? is there something faster, or more reliable? All the servers will be sitting in the same gigabit switch or neighboring switch, so fast transfer is expected.

EDIT:

The question goes on the server <-> server side of things. The servers are co-located in same LAN, so the security of the interconnection there is not expected to be the main issue.

答: Instead of sending the files to the servers, I would suggest you to use a partition on the server which is mounted on all the servers. So we dont have to move the file at all.</p>

OwnerDisplayName: Sofus Albertsen

OwnerDisplayName: shamis


问:
What GUI tools are available for which DVCS?
When I worked at Sun, we used a DVC system called Forte SCCS/Teamware, which used the old SCCS file format, but was a true distributed source code revision control system.

One nice feature is that it had strong GUI support:

You could bringover and putback changes by simply clicking and dragging.

It would draw trees/graphs showing how workspaces relate to each other.

You also could have a graph view to display a single file's complete history, which might have had several branches and merges. Allowing you to compare any two points.

It also had a strong visual merge tool, to let you accept changes from one of two conflicting files.

Naturally, many of the current DVCSs have command line support for these operations, but I'm looking for GUI support in order to use this in a lower-level undergraduate course I'll be teaching.

I'm not saying the Forte Teamware solution was perfect, but it did seem to be ahead of the curve. Unfortunately, it's not a viable option to use for my class.

Question: What support do the current DVCSs have with regards to GUIs? Do any of them work on Windows, and not just Linux? Are they "ready for prime-time" or still works in progress? Are these standalone or built as plug-ins, e.g., for Eclipse?

Note: To help keep this discussion focused I'm only interested in GUI tools. And not a meta-discussion if GUI tools should be used in teaching.

答:
The standard distribution of Git for *nix systems includes gitk, which is a simple but featureful GUI for Git. If the Tk UI is not to your liking, Qgit is also fairly nice.

Github has a very good interface for browsing the repository, including a very nice tool for following forks and branches to other users' repositories.

I have never personally needed nor, really, used GUI tools for Git other than that provided by Github, so I can't speak to your needs. But there are several very good tools out there.

I also can't speak to Windows software. I'm only familiar with the Tortoise family in passing.

Edit: I've been using Git-MinGW and TortoiseGit on Windows recently, and I have to say I'm rather impressed by TortoiseGit. It's not the most powerful UI I've seen (by far), but it helps me get the most common tasks done rather easily. I still rely heavily on the command-line, because very little of git-svn is exposed in the context menu.


答: The term "Lasagna Code" comes to my mind, though apparently it means different things to different people. My interpretation has always been "layered for the sake of being layered".</p>


答:
No, it's not a anti pattern but I would raise the following issues.

Violation of Single Responsibility Princple

SRP says that a class should have one reason to change. Adding a logger method means that the class also have to change if the logging logic should be changed.

Violation of a is-a relationship

Base classes are not toolboxes where you can add several convenience methods.

Doing so effectively couples all inherited classes to the implementations that the base class has.

Compare that with composition.


答:
There is nothing stopping you from applying different licenses to the same code.  If I understand you correctly, you have code written and controlled by you that has comments you want to release under a CC license and code you want to release under GPL.  So just do that.  The comments will be released under the GPL and under the CC license, so if people use the comments according to the CC license, they're fine.

The GNU GPL FAQ talks about automatically generated code specifically, so it might answer your question if I misunderstood.  (It also covers a lot of other corner cases.)


答:
To answer your question, no I would not give the answer. If the person wants to be a better software engineer, they will find the answer. If you give them answer you are robbing them of this opportunity.

The more relevant question is when can you call yourself a senior developer? This varies between organizations and countries. For example, a company I worked with considered Software Engineers with 5 years of experience as seniors.  There was no emphasis on the quality of the experience, just the length.

Until we come up with a standard that will categorize all Software Engineers regardless of their language we are left with the individual deciding the level of their skills. And we will continue hearing of "Senior Engineers" failing the most rudimentary skills test.

A couple weeks ago the question was asked "When should you call yourself a Senior Developer". I also wrote a blog post on the topic.

Body:
We had a senior level interview candidate fail a nuance of the FizzBuzz question12.

I mean, really, utterly, completely, failed the question - not even close.

I even coached him through to thinking about using a loop and that 3 and 5 were really worth considering as special cases.

He blew it.

Just for QA purposes, I gave the same exact question to three teammates; gave them 5 minutes; and then came back to collect their pseudo-code.  All of them nailed it and hadn't seen the question before.  Two asked what the trick was...

On a different logic exercise, the candidate showed some understanding of some of the features available within the language he chose to use (C#).  So it's not as if he had never written a line of code.  But his logic still stunk.

My question is whether or not I should have given him the answer to the logic questions.

He knew he blew them, and acknowledged it later in the interview.

On the other hand, he never asked for the answer or what I was expecting to see.

I know coding exercises can be used to set candidates up for failure (again, see second link from above).  And I really tried to help him home in on answering the core of the question.  But this was a senior level candidate and Fizz-Buzz is, frankly, ridiculously easy even after accounting for interview jitters.

I felt like I should have shown him a way of solving the problem so that he could at least learn from the experience.  But again, he didn't ask.

What's the right way to handle that situation?

1Okay, that's not the link to the actual FizzBuzz question, but it is a good P.SE discussion around FizzBuzz and links to the various aspects of it.

2 To help clarify, this is the nuance of Fizz-Buzz I asked and it's from Project Euler's first problem.  Substitute printing Fizz | Buzz for summing the numbers and you have the same fundamental question.

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.  Write a function that finds the sum of all the multiples of 3 or 5 below 1000.

3 This question attracted more attention than I had expected, and I appreciate all of the replies.  Some of the later answers have really gotten to the core of my question, so I'll allow the community to review and up-vote before assigning "the" answer.

4 I selected "the" answer based upon community votes at that point in time.  And I think Yannis' answer is appropriate for interviews with newer devs.  I think the collective response focusing on the lack of asking for the answer is spot-on as well.


答:
Or we could look at this as a "teachable moment" :)

Your developer may be halfway to a good idea.  Suppose you want to have the requirement that all of your business objects are capable of intelligent logging.  You might define:

```<code>   public interface IBusinessObjectLogger
   {
       void Log(Exception ex, string logMessage)
   }
</code>```

Now internal to your objects you can use the ErrorLog object to actually do the logging while SomeClass code adds object specific value to the log message.  You can then further extend your logging APIs to implement file based, db based or message based logging functionality without touching you business objects.

Body:
Or we could look at this as a "teachable moment" :)

Your developer may be halfway to a good idea.  Suppose you want to have the requirement that all of your business objects are capable of intelligent logging.  You might define:

   public interface IBusinessObjectLogger
   {
       void Log(Exception ex, string logMessage)
   }

Now internal to your objects you can use the ErrorLog object to actually do the logging while SomeClass code adds object specific value to the log message.  You can then further extend your logging APIs to implement file based, db based or message based logging functionality without touching you business objects.


问:
How to test Java web applications
So far I haven't been testing or learning how to test my java web applications.

If you do, what are the tools you need, and is it really necessary to test a web application if doesn't need scaling or it won't be handling big traffics and multi transactions?

What things should I test and what approaches should I take to ensure my application works correctly?

答:
As it is your own Java based Web Application, the first and foremost is Unit Testing. Test every method in your application. Ensure that every mehod is meant to do what it actually suppose to do. Check to see whether you have caught exceptions properly and used try-catch whereever required.

Analyze your algorithms if to see if they are well optimized and efficient.

Once Unit Testing is done, then proceed to White Box Testing, Black Box Testing and Integration Testing. Then test the UI. Ensure that all GUI elements are consistent and functioning properly.

Title: How to test Java web applications


答:
I am not going to use any fancy definitions as they will confuse you.

Typically Quality control is a sub set of Quality Assurance.

For a quick and dirty example you will be using term VERIFICATION when you will be  checking your Functional specs for correctness thus

"Are we building the product right?"

Once your product is passed to dedicated Testing teams then validation comes into picture indication of

"Are we building the right product?"

Quality Assurance is a vast process which consist of fulfilling many processes such as Audits, Code Reviews etc and ensuring conformance to standards such as CMMI or ISO.

Title: Quality Assurance activities

Body:
Possible Duplicate:

  Verification of requirements question

Having asked but deleted the question as it was a bit misunderstood. If Quality Control is the actual testing, what are the commonest true quality assurance activities? I have read that verification (reviews, inspections..) but it does not make much sense to me as it looks more like quality control as mentioned here:

DEPARTMENT OF HEALTH AND HUMAN SERVICES
ENTERPRISE PERFORMANCE LIFE CYCLE FRAMEWORK
Practices guide

Verification - “Are we building the product right?” Verification is a
  quality control technique that is used to evaluate the system or its
  components to determine whether or not the project’s products satisfy
  defined requirements. During verification, the project’s processes are
  reviewed and examined by members of the IV&V team with the goal of
  preventing omissions, spotting problems, and ensuring the product is
  being developed correctly.

  Some Verification activities may include
  items such as: • Verification of requirement against defined
  specifications • Verification of design against defined specifications
  • Verification of product code against defined standards •
  Verification of terms, conditions, payment, etc., against contracts

And the opposite (project management knowledge scope - google result)
Verification is a quality assurance process or technique applied by ...


问:
Structure of a correctly implemented JTable with TableModel and Listeners?
I am pretty new to Java and its JTables and this is where I am struggling at the moment.

I need to create a GUI which shows me results of a sql query like SELECT * FROM tblPeople WHERE name='Doe'. My idea was to create a a JFrame which displays a JTable with all found records.

Besides this, I  need to also implement some code to handle when a user is double clicking a record or selecting it by using his arrow keys (additional feature: pressing 12(e.g.) should select the 12th record).

What is the best way to structure my program (what classes do I need and especially where do I store my logic)? I came up with structuring it the following way:

Main.java ("view")

SQLConnection.java

PeopleTableModel.java (only stores and returns data given by the passed ResultSet, "model" inherits from DefaultTableModel)

PeopleTable.java (stores basically all my logic including KeyListener and MouseListener, "controller", inherits from JTable)

Are there better ways to achieve my goals? If so, what are they?

答:
I recommend you to use model-view-controller design pattern. In the class view you will have the GUI components. In the class model you will have the logic of your program. In the controller you choose what data to pass from model to view and vice versa.

I also recommend you to use a class for each table from DB, like in hibernate. And  you will have a class DBAccess, where you access the DB and make queries. Be aware that in Java it is recommended that a class to have a single responsibility. That will make your program more easy to test.


答:
This is a difficult problem.  Many of the "methods" in a web application take a HTTP request as input and produce HTML output with the side effect of using the database and updating some kind of session state somewhere.  This is a worst-case scenario for unit testing.

HTML is tough because you really want to isolate the data that comes specifically from a given method as opposed to the boiler-plate and layout scaffolding which is common to every page.  That boiler plate could change to a new color scheme or something else independent of the logic of your application that could potentially break all your tests.  The database is particularly difficult because a good deal of data often needs to be set up before you can meaningfully test anything but the login screen.

I think the best approach is to use many different kinds of testing and divide and conquer.

For small applications, a manual regression test plan is a good place to start.

When you make components that are truly independent, write JUnit tests for them.

If you are using servlets, you should be able to provide a fake HTTP request or fake parameters and get the output from the servlet directly.  Well formatted XHTML will parse fairly easily with regular expressions.  You can use unit-testing techniques against pre-loaded data in the database.

Set up integration tests with your unit test tools (someone is going to flame me for this).  Make a test that builds up a set of test data in the database using the screens of the system (as in the point above) more or less like a user of the system would.  All your tests will depend on the core test suite which sets up the data for the other tests.  When your regression test gets too big, this is a great alternative to manual testing.

You may be able to use an in-memory database with a tool like Hibernate instead of setting up a complete clone of your production database and masking the data.

Use something like Selenium to test from a browser.

Set your master servlet up to page you whenever an exception is thrown, and remove all catch statements from your code (except those that actually do something meaningful with the exception, like recover from it).  This isn't testing, but it encourages very good testing.

I often find that the most useful testing occurs when the tester explains how the system works to an absolute beginner.  We find the most meaningful bugs when building little video help segments for new features.  But I can do good testing when I explain and demonstrate the details of how the system works to an interested imaginary friend.

I think if you used a tiered approach to building your application with lots of independent layers, you'd have a much easier time testing.  You may need a large team of programmers to get anything done with specialists for the database, the "back end" service layer on top of the database, the business logic layer, and the view layer.  In that scenario, you can use traditional unit-testing techniques with the business logic and to some extent the other layers, but the view will always be a bear.

Edit: I've been thinking about this.  For as long as I can remember MVC being applied to web applications, there has been a debate about what that means.  For the record, I think Ruby/Rails got it most right - that Model really means Data Model.  I like this interpretation because it is most compatible with making a service layer in your application.  I recently read Steve Yegge's Platform Rant that was really eye-opening for me.  Make the service your data model and eat your own dog food.  That way someone else can make your creation into something you never imagined.  The reason I bring it up here (besides the fact that I can't stop thinking about it) is that having divisions in your code makes it easier to test.

Look, I'm not in the layers-make-everything-better camp.  I have to produce, and produce lots of features without a lot of help for a living.  I'm just saying that if your project is mature enough that you aren't changing the database so much any more, consider turning your ORM nightmare into a service layer for Steve Yegge's reasons, but also because the additional interface should make your testing much easier and more effective.

Title: How to test Java web applications

Body:
So far I haven't been testing or learning how to test my java web applications.

If you do, what are the tools you need, and is it really necessary to test a web application if doesn't need scaling or it won't be handling big traffics and multi transactions?

What things should I test and what approaches should I take to ensure my application works correctly?


答:
This is actually pretty common in certain coding styles, and the basics of the line of thought are not, in themselves, an anti-pattern.

It's very probably the result of someone coding by necessity without knowledge of the wider codebase: "OK, this code needs to log an error, but that function is not the code's primary purpose. Therefore, I need a method/class that will do that for me". That's a good way of thinking; but, without knowing ErrorLog existed, they created SomeClass. They then found ErrorLog at some later point, and rather than replace all usages of the method they'd put in, they made their method call ErrorLog. That is where this becomes a problem.


问:
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!

答:
```<code>DO 10 I=1.3
</code>```

This is one of the most expensive bugs in history.  This Fortran statement assigns the float value of 1.3 to the variable named DO10I.

The correct code - the header of the loop repeating statements until the statement labeled 10 and the loop variable I accepting values 1, 2, 3:

```<code>DO 10 I=1,3
</code>```

Body:
DO 10 I=1.3

This is one of the most expensive bugs in history.  This Fortran statement assigns the float value of 1.3 to the variable named DO10I.

The correct code - the header of the loop repeating statements until the statement labeled 10 and the loop variable I accepting values 1, 2, 3:

DO 10 I=1,3


答:
Besides the reference doc (which is a good way to learn a small language IMHO), there's  Programming in Lua (PiL).  It teaches both the language and the common idiomatic patterns.

About scope, Lua is a high level language.  It allows you to quickly express algorithms and create structures.  It's also widely used as an extension language, to be embedded within an application.

There are many C modules available, both to add new capabilities (LPEG, LuaSocket, etc.) and to 'bind' to existing C libraries (databases, XML parsers, etc.), but Lua itself is a complete language, you're not required to write C modules on day-to-day work.

About the "most common design patterns" do you mean the "Gang of Four" design patterns?  (you mention the Observer pattern).  If so,  While really useful and written in a language-agnostic tone, many of these patterns make sense only in statically-typed, heavily OO languages like C++, Java, C# and a few others.  With other platforms, some are unnecessary (like the Command Patterns, which becomes a closure when you have lexically scoped, first class functions), some others are applicable but result in widely different solutions.

About multithreaded programming: Lua itself is mostly single-threaded.  There are several ways around this, but they're not so heavily needed as on other platforms.  A simple coroutine-based scheme is quick and easy to write and works perfectly in many cases.  When not, the exact way to do multithreading depends a lot on your needs.

GUI: this is in the realm of a GUI library and not of the language.  There are several available.  Again, you can pick any one, or none at all.  There are many things to do without GUIs (command line, application extensions, servers, etc)

Hardware integration: depends on the hardware.  In most cases, there should be a C API and so you need a binding library, which is not hard to write (sometimes it's just a 5-20 line C function for each API entry point)

Title: Lua and multi-paradigm programming: scope and capabilities

Body:
Despite having started learning programming with Pascal and C, after the jump to OO (C++, Java) I lost sense of the structured programming paradigm. I have started learning Lua and I have researched many tutorials, but all of them only cover basic operations and language features and capabilities. They feel more like a reference doc than a programmer's guide.

Now, when trying to work with day to day tasks, how does one go through most common design patterns like observer, or multithreaded programming, creating UI elements and polling system calls for keyboard or sensors? Is it even feasible in this languages or you have to work with the C binding, libraries and low-level programming to get most stuff done? Do I get the Lua scope wrong?