问:
How do I get up-to-date on web development technologies?
I'm a regular user here, but linking my screen name to my real identity is dirt simple, and the question I'm about to ask would lead to a very unpleasant conversation with my current employer were they to see it.  So, my apologies for this sock-puppet account; I promise Socky and I won't be voting on each other's stuff, and Socky won't be doing much of anything other than voting on answers to his own questions.

I may have an opportunity to work with somebody I've worked with in the past.  Short, extremely understated summary:  It went well.  This time he's looking to bring me on as a partner to a fledgling web venture.  My job title isn't defined, but I'd basically be "the guy" in terms of the tech side of the company.  One of the first things I'd be doing is fleshing out the current and future requirements of the site and determining the best way to meet them -- overhaul the existing site?  Scrap the existing site entirely and replace it with something like Drupal?  I'd also be tasked with making sure that the site is not only a pleasant user experience, but that it looks and feels like a modern, professional website.

One problem:  I'm not qualified.

At least, not yet.

I wasn't really qualified for the last time we worked together, but I taught myself what I needed to know and ... like I said.  It Went Well.  However, I was a lower-level code wrangler that time around, and a lot of key decisions had already been made.  I had more room for error and time to learn as I was going.

This outing, not so much.  It's been a long damn time since I was completely up-to-date on web programming; my current gig has a healthy dash of web stuff, but the web interface isn't the main business and it's built on old technology.  (Technology it honestly doesn't use particularly well.)  I just don't spend a lot of time playing with new tech when I'm not at work; I generally spend that time on hobbies and passions I don't get paid to do.

But I want this to happen.  And I want to do it right.  So my question is:  what resources would you recommend I use to both get myself up-to-date and stay up-to-date on professional-caliber web programming?

I know I need to beef-up my jQuery-fu; I've been exposed to it a little, and holy crap does it make hard jobs easy.  I also know I need to acquaint myself with Drupal and other content management systems so that I can accurately gauge whether using one as the foundation for the site would be a good idea or a waste of time.  But I'm certain there are other technologies out there that would help me do that job that I don't yet know anything about.  What are some good resources for helping me figure out what I don't know?

Websites, magazines, podcasts, whatever.  I need to figure out how to get back into the game properly.

This is scary as hell, but it also feels like it could be a huge step forward in my career.  (Assuming it's not a step into a pool filled with laser sharks.)  My thanks in advance for any assistance anybody can offer in curing my ignorance.

答:
I recently got into Chrome extension development and not only making them is very interesting by itself, I feel that it improved my knowledge of the latest bells and whistles of web development (client side) quite a bit. It's basically 99% regular javascript+html+css and 1% chrome specific javascript api (you can also make C++ plugins if you want).

Why it is great:

You don't need to worry about hosting, and often design

All latest HTML5 toys and technologies are at your disposal

No need to worry about cross-browser compatibility (it's like heaven)

There are no cross domain limitations for javascript, you can read any remote webpage or a file and then process it in javascript, so basically javascript can do almost anything your server side script can in this sence (you can read and parse binary files if you want)

You can use jquery or any framework you like

Making something that other people find useful is satisfying. You also get instant feedback - rating, comments.

If you go to this page, they have a nice list of all current hot technologies that Chrome supports, so you can just go through the list and play with them.


问:
Do I lose anything by coding in c# and using free online vb.net code convertors?
The company I work for uses vb.net since there are many programmers who moved up from vb6 to vb.net. Basically more vb.net resources in the company for support/maintenance vs c#. I am a c# coder and was wondering if I could just continue coding in c# and just use the many online free c# to vb.net code convertors. That way, I will be more productive and also be more marketable since there are more c# jobs compared to vb.net jobs. I have done vb6 many years ago and I am comfortable debugging vb.net code. It's just the primary coding language. I am more comfortable in c#. Will I lose anything if I use this approach. (code conversion). Based on what i read online the future of vb.net is really "Dim". Please advise. thank you</p>

答:
I don't know about the converter's and if it's gonna make you lose anything(performance wise).

But I am sure about one thing, learning a new language would not hurt your resume.

It's always good in my opinion to learn something new and considering your case:

The company's major language is VB, you'll get along with the whole work environment far better.

It shows you can adapt to changes quite easily if you just pick the language and start working with it.

ContentLicense: CC BY-SA 3.0


问:
Unit testing time-bound code
I'm currently working on an application that does a lot of time-bound operations. That is, based on long now = System.currentTimeMillis();, and combined with an scheduler, it will calculate periods of time that parametrize the execution of some operations. e.g.:

```<code>public void execute(...) { // executed by an scheduler each x minutes
    final int now = (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
    final int alignedTime = now - now % getFrequency() ;
    final int startTime = alignedTime - 2 * getFrequency();
    final int endTimeSecs = alignedTime - getFrequency();
    uploadData(target, startTime, endTimeSecs);
}
</code>```

Most parts of the application are unit-tested independently of time (in this case, uploadData has a natural unit test), but I was wondering about best practices for testing time-bound parts that rely on System.currentTimeMillis() ?

答: Instead of calling System.currentTimeMillis() directly, I would wrap that in your own class and inject it into your code dynamically. What this gives you is the ability to mock your wrapper object to return a fixed time in the context of tests. This means that your test code will never actually call System.currentTimeMillis(), but rather get a fixed time to work with that you can predict.

Title: Unit testing time-bound code


答: Do not use System.currentTimeMillis(), but program everything using time against an interface returning time. During unit-testing, mock the interface, else you simply cannot test anything using time reliably. This also has the benefit that if you decide currentTimeMillis is not accurate enough, you can replace it with another method in one single spot and everything will now use that other method.

Title: Unit testing time-bound code

Body:
I'm currently working on an application that does a lot of time-bound operations. That is, based on long now = System.currentTimeMillis();, and combined with an scheduler, it will calculate periods of time that parametrize the execution of some operations. e.g.:

```<code>public void execute(...) { // executed by an scheduler each x minutes
    final int now = (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
    final int alignedTime = now - now % getFrequency() ;
    final int startTime = alignedTime - 2 * getFrequency();
    final int endTimeSecs = alignedTime - getFrequency();
    uploadData(target, startTime, endTimeSecs);
}
</code>```

Most parts of the application are unit-tested independently of time (in this case, uploadData has a natural unit test), but I was wondering about best practices for testing time-bound parts that rely on System.currentTimeMillis() ?


问:
Is 'Protection' an acceptable Java class name
This comes from a closed thread at stack overflow, where there are already some useful answers, though a commenter suggested I post here.  I hope this is ok!

I'm trying my best to write good readable, code, but often have doubts in my work!

I'm creating some code to check the status of some protected software, and have created a class which has methods to check whether the software in use is licensed (there is a separate Licensing class).

I've named the class 'Protection', which is currently accessed, via the creation of an appProtect object. The methods in the class allow to check a number of things about the application, in order to confirm that it is in fact licensed for use.

Is 'Protection' an acceptable name for such a class?

I read somewhere that if you have to think to long in names of methods, classes, objects etc, then perhaps you may not be coding in an Object Oriented way. I've spent a lot of time thinking about this before making this post, which has lead me to doubt the suitability of the name!

In creating (and proof reading) this post, I'm starting to seriously doubt my work so far. I'm also thinking I should probably rename the object to applicationProtection rather than appProtect (though am open to any comments on this too?). I'm posting non the less, in the hope that I'll learn something from others views/opinions, even if they're simply confirming I've "done it wrong"!

EDIT:

Thanks for all the responses, which have been all been helpful.  I think 'Protector' fits the bill perfectly, as the class checks the license, and acts accordingly.

答: Your class looks like a Singleton Pattern, so SingleLicence.class may interest you</p>


答:
I think you might be overanalyzing this. Be wary of analysis paralysis.

So I suggest you stick with the name for now. You can always change it later. Besides, most entities tends to change name a couple of times while developing, so you don't need to worry.

Title: Is 'Protection' an acceptable Java class name

Body:
This comes from a closed thread at stack overflow, where there are already some useful answers, though a commenter suggested I post here.  I hope this is ok!

I'm trying my best to write good readable, code, but often have doubts in my work!

I'm creating some code to check the status of some protected software, and have created a class which has methods to check whether the software in use is licensed (there is a separate Licensing class).

I've named the class 'Protection', which is currently accessed, via the creation of an appProtect object. The methods in the class allow to check a number of things about the application, in order to confirm that it is in fact licensed for use.

Is 'Protection' an acceptable name for such a class?

I read somewhere that if you have to think to long in names of methods, classes, objects etc, then perhaps you may not be coding in an Object Oriented way. I've spent a lot of time thinking about this before making this post, which has lead me to doubt the suitability of the name!

In creating (and proof reading) this post, I'm starting to seriously doubt my work so far. I'm also thinking I should probably rename the object to applicationProtection rather than appProtect (though am open to any comments on this too?). I'm posting non the less, in the hope that I'll learn something from others views/opinions, even if they're simply confirming I've "done it wrong"!

EDIT:

Thanks for all the responses, which have been all been helpful.  I think 'Protector' fits the bill perfectly, as the class checks the license, and acts accordingly.


答:
You should DEFINITELY arrange to mock-out the system clock. I've worked in C++, and either I make the object take a 'clock interface' object, or I use an internal interface or function pointer inside the class that I then replace when doing test code.

I've actually had experience with NOT mocking out the system clock and believe me when I tell you - it never ends well.

There are actually several problems with doing unit tests that rely on the real system clock. The first is that it's simply hard to do (you end up grabbing the clock, then doing stuff, then grabbing the clock again to verify), but it's also annoying because your test times become limited by real-time (if you are testing something that's 30 seconds, then it's 30+ seconds to run the test).

The most important problem, though, is that it makes your tests VERY BRITTLE.

Your tests will start to fail randomly due to server loading issues. They'll fail randomly, and you'll send time checking the failures over and over.

It's not worth it - use an interface for the system clock and mock it out in the test code.

Title: Unit testing time-bound code


问:
How is the JVM and Java's WORA different from other high level languages?
In the Java world, we often talk about the JVM, and when Java was new it had the supposedly killer feature of "Write Once, Run Anywhere."

From the way people talk and write, this seems different from the way that Python, for example, works.  Yet I've not been aware of any way that Python code that I've written would work differently on another machine.  (Though I haven't written that much Python.)

So what am I missing?  How is the JVM different from a Python interpreter?  Is there a way that Python lacks Java's platform independence?  Or is this just a cultural difference?

答:
Topically and just from a language runtime, there is little difference.  The JVM in particular is designed not just as an interpreter but also a runtime compiler, code inference, an instrumental virtualization layer that can have dynamic hooks applied, various GC semantics and the ability to describe virtualization ergonomics, to name a few.  Python can run in a JVM?  Can Java run in a Python interpreter?

Most interpreters are runtime language/token interpreters, JVMs (and others) as you know interpret/compile/run intermediate code.  IBM for instance has been doing this for decades outside of Java, it is nothing new.  Even VB ran in intermediate code for some time I believe?

The WORA is mostly passé now as many interpreted languages run just about anywhere unchanged.

ContentLicense: CC BY-SA 2.5


答: The noun you use to name an object usually comes out of what that object represents. What the object represents is a function of its member variables and its methods. So, what are they? :-)</p>


问:
What is the correct way to implement Auth/ACL in MVC?
I am looking into making a correctly laid out MVC Auth/ACL system. I think I want the authentication of a user (and the session handling) to be separate from the ACL system. (I don't know why but this seems a good idea from the things I've read.)

What does MVC have to do with this question you ask? Because I wish for the application to be well integrated with my ACL. An example of a controller (CodeIgniter):

```<code><?php
class forums extends MX_Controller
{
    $allowed = array('users', 'admin');
    $need_login = true;

        function __construct()
        {
        //example of checking if logged in.
            if($this->auth->logged_in() && $this->auth->is_admin())
        {
            echo "you're logged in!";
        }
    }
    public function add_topic()
    {
        if($this->auth->allowed('add_topic')
        {
            //some add topic things.
        }
        else
        {
            echo 'not allowed to add topic';
        }
    }
}
?>
</code>```

My thoughts

$this->auth would be autoloaded in the system.  I would like to check the $allowed array against the user currently (not) logged in and react accordingly.

Is this a good way of doing things? I haven't seen much literature on MVC integration and Auth. I want to make things as easy as possible.

答:
I tried to come-up with my own explanations, but i found a really comprehensive post in the middle of compiling my answer. Hopefully you will find more than you asked in this post - PHP ACL implementation

Edir: Basically, idea behind the post suggest to use  use decorator pattern (look at Wiki for more info). In simple concept this pattern recommend to take your object, and place it inside another object, which will act like a protective shell. In this way, your code would not be required to extend the original class.


答:
Despite both languages running on the .NET Framework, they have some differences that can make certain things easier or even possible in VB that aren't in C#, and vice versa.

Some things off the top of my head:

The VB version of the Application class has a SplashScreen property. When set to a Form in the main method, that Form will show when Application.Run() is called, until the main form is ready to show. In C# this isn't available, so to provide similar functionality you have to "roll your own" using the main form's Load handler; your VB colleagues will look at the translated code and say "why didn't you just use what the language gives you?"

Related: Event handlers (MulticastDelegates) in VB have built-in null checking; you can raise an event in VB without having to worry if anyone's actually listening. This isn't so in C#; you have to perform a null check first (and technically, as the listeners can change while the event is being handled, the best practice in threaded applications is to "clone" the collection of handlers and run that instead). When translated, the resulting code would be redundant.

Casting and conversion work differently in both languages. C# requires a defined implicit conversion between two types in order to convert. VB by contrast will "coerce" the type whenever it sees ANY valid cast between the actual type and the expected type, which can lead to unexpected behavior when VB coerces the type and thus picks a different overload or code branch than the same code in C#.

For more differences, see http://en.wikipedia.org/wiki/Comparison_of_C_Sharp_and_Visual_Basic_.NET#Language_features

So, I would recommend learning VB syntax and the language differences, and whether you use the converter on a daily basis or not, I would at least recognize situations where the purpose of the C# code you are writing would be more easily accomplished in straight VB, or where the C# code won't translate ("unsafe" blocks, "checked"/"unchecked" blocks, partial class declarations, etc).

Title: Do I lose anything by coding in c# and using free online vb.net code convertors?

Body: The company I work for uses vb.net since there are many programmers who moved up from vb6 to vb.net. Basically more vb.net resources in the company for support/maintenance vs c#. I am a c# coder and was wondering if I could just continue coding in c# and just use the many online free c# to vb.net code convertors. That way, I will be more productive and also be more marketable since there are more c# jobs compared to vb.net jobs. I have done vb6 many years ago and I am comfortable debugging vb.net code. It's just the primary coding language. I am more comfortable in c#. Will I lose anything if I use this approach. (code conversion). Based on what i read online the future of vb.net is really "Dim". Please advise. thank you</p>


问:
Are scheduled job servers the right choice for a time sensitive game engine?
I am currently architecting and designing an exciting new web application that will be entering into some areas that I have very little experience in, game development.

The application is not necessarily a game, but there are some very time sensitive tasks and scheduled jobs that a server will need to run to perform game related activities (Eg. New match up starts at noon every day for a 12 day tournament, updating scoreboards at 5pm every day, etc...)

In the past I have typically used cron jobs with the Quartz Scheduler running within a web application server, but I know that this isn't likely a scalable solution for the truly massive userbase that management is telling me to expect (Granted they are management and are probably highly optimistic about this) and also for how important the role of these tasks are in this web application.

The other important thing I want to consider is that I want to avoid SPOF (Single Point Of Failure).  If the primary job server goes down, another job server should be able to successfully run the job in its place.  I suppose this can be done appropriately record locking and database transactions.

My question is if scheduled jobs like CRON running on a web application server are a wise design choice given the time sensitive game tasks of this application, or is there something more appropriate for running a scalable game engine parallel to the web application servers?

答:
I don't know why you are discarding Quartz as a possible option. Quartz has a clustered deployment configuration that gets you a cluster-singleton redundant scheduler (One node of the cluster will run the job with certain warranties). It uses the db lock technique you mention to achieve cluster-wide locking. See Quartz cluster configuration.

What is not clear from your 'load' requirements is whether a single node in the cluster should be responsible of running the scheduled task (cluster singleton) or whether every node in the cluster should execute said task at a given point in time. The former can be achieved with the clustering options I mentioned. The latter is possible by using independent Quartz instances on every node, running the same configuration and NTP to ensure time-sync across nodes. (There are other options, like sending a trigger message to clustered topic).

The only point where a clustered Quartz with a SQL store does not scale well is when you want to schedule sub-second jobs sequentially, but from your description, that's not the case.


问:
How can test users access an unpublished iOS app?
I am considering outsourcing the development of an iOS app to various independent developers. I will have have various testers of the app. We all work for separate companies. Some of these testers will be customers, who I would like feedback from. As there are multiple developers involved I expect there to be a new release on a daily basis.

How can this be done? Would each of the testers need to buy some sort of license to avoid having to go through the app approval process? Is there any smooth way to do this so that it will not be a hassle for our friendly customers, who are willing to test our app?

答:
Any developer who wants to build and test their code on their own iOS device without needing to send the app to another developer to codesign the app for them (or using their company's certificates) needs to enroll in Apple's iOS Developer program ($99/annum).

For company teams using less than 100 max total iOS devices, only the company or team leader needs to pay and enroll, but then that one person needs to handle all the accounting and management (registering everybody's device, renewing and sending out certificates and provisions to everybody else on the development team, submitting apps to Apple, etc.).  Test devices belonging to testers can be among those 100 max total device.  See Apple's documentation on Ad Hoc distribution.


答: If you were asked to code in Java then I could understand your concern...knowing that VB.Net is almost identical to C# but in the syntax, why not trying to learn those small differences and add to your skills and values?!</p>


问:
Automated tests for differencing algorithm
We are designing a differencing algorithm (based on Longest Common Subsequence) that compares a source text and a modified copy to extract the new content (i.e. content that is only in the modified copy). I'm currently compiling a library of test case data.

We need to be able to run automated tests that verify the test cases, but we don't want to verify strict accuracy. Given the heuristic nature of our algorithm, we need our test pass/failures to be fuzzy. We want to specify a threshold of overlap between the desired result and the actual result (i.e. the content that is extracted).

I have a few sketches in my mind as to how to solve this, but has anyone done this before? Does anyone have guidance or ideas about how to do this effectively?

答:
It seems you have a hard constraint to produce a correct set of differences, and a goal to produce a minimal set of differences.

To verify the constraint, you need to merge the differences into one of the inputs and see if you obtain the other input.  Fortunately, this has already been done.  All you have to do is output the differences in the format expected by GNU patch.

To test the second, you just need to ensure that the output is not getting unacceptably large.  Since you can change the program so that one set of differences gets smaller while another gets larger, it will be up to you to define a measure of goodness and a threshold of acceptability.


问:
Should I expose IObservable<T> on my interfaces?
My colleague and I have dispute. We are writing a .NET application that processes massive amounts of data. It receives data elements, groups subsets of them into blocks according to some criterion and processes those blocks.

Let's say we have data items of type Foo arriving some source (from the network, for example) one by one. We wish to gather subsets of related objects of type Foo, construct an object of type Bar from each such subset and process objects of type Bar.

One of us suggested the following design. Its main theme is exposing IObservable objects directly from the interfaces of our components.

```<code>// ********* Interfaces **********
interface IFooSource
{
    // this is the event-stream of objects of type Foo
    IObservable<Foo> FooArrivals { get; }
}

interface IBarSource
{
    // this is the event-stream of objects of type Bar
    IObservable<Bar> BarArrivals { get; }
}

/ ********* Implementations *********
class FooSource : IFooSource
{
    // Here we put logic that receives Foo objects from the network and publishes them to the FooArrivals event stream.
}

class FooSubsetsToBarConverter : IBarSource
{
    IFooSource fooSource;

    IObservable<Bar> BarArrivals
    {
        get
        {
            // Do some fancy Rx operators on fooSource.FooArrivals, like Buffer, Window, Join and others and return IObservable<Bar>
        }
    }
}

// this class will subscribe to the bar source and do processing
class BarsProcessor
{
    BarsProcessor(IBarSource barSource);
    void Subscribe();
}

// ******************* Main ************************
class Program
{
    public static void Main(string[] args)
    {
        var fooSource = FooSourceFactory.Create();
        var barsProcessor = BarsProcessorFactory.Create(fooSource) // this will create FooSubsetToBarConverter and BarsProcessor

        barsProcessor.Subscribe();
        fooSource.Run(); // this enters a loop of listening for Foo objects from the network and notifying about their arrival.
    }
}
</code>```

The other suggested another design that its main theme is using our own publisher/subscriber interfaces and using Rx inside the implementations only when needed.

```<code>//********** interfaces *********

interface IPublisher<T>
{
    void Subscribe(ISubscriber<T> subscriber);
}

interface ISubscriber<T>
{
    Action<T> Callback { get; }
}

//********** implementations *********

class FooSource : IPublisher<Foo>
{
    public void Subscribe(ISubscriber<Foo> subscriber) { /* ...  */ }

    // here we put logic that receives Foo objects from some source (the network?) publishes them to the registered subscribers
}

class FooSubsetsToBarConverter  : ISubscriber<Foo>, IPublisher<Bar>
{
    void Callback(Foo foo)
    {
        // here we put logic that aggregates Foo objects and publishes Bars when we have received a subset of Foos that match our criteria
        // maybe we use Rx here internally.
    }

    public void Subscribe(ISubscriber<Bar> subscriber) { /* ...  */ }
}

class BarsProcessor : ISubscriber<Bar>
{
    void Callback(Bar bar)
    {
        // here we put code that processes Bar objects
    }
}

//********** program *********
class Program
{
    public static void Main(string[] args)
    {
        var fooSource = fooSourceFactory.Create();
        var barsProcessor = barsProcessorFactory.Create(fooSource) // this will create BarsProcessor and perform all the necessary subscriptions

        fooSource.Run();  // this enters a loop of listening for Foo objects from the network and notifying about their arrival.
    }
}
</code>```

Which one do you think is better? Exposing IObservable and making our components create new event streams from Rx operators, or defining our own publisher/subscriber interfaces and using Rx internally if needed?

Here are some things to consider about the designs:

In the first design the consumer of our interfaces has the whole power of Rx at his/her fingertips and can perform any Rx operators. One of us claims this is an advantage and the other claims that this is a drawback.

The second design allows us to use any publisher/subscriber architecture under the hood. The first design ties us to Rx.

If we wish to use the power of Rx, it requires more work in the second design because we need to translate the custom publisher/subscriber implementation to Rx and back. It requires writing glue code for every class that wishes to do some event processing.

答:
First of all, it's worth noting that IObservable<T> is part of mscorlib.dll and the System namespace, and thus exposing it would be somewhat equivalent to exposing IComparable<T> or IDisposable. Which is equivalent to picking .NET as your platform, which you seem to have done already.

Now, instead of suggesting an answer, I want to suggest a different question, and then a different mindset, and I hope (and trust) that you'll manage from there.

You're basically asking: Do we want to promote scattered use of Rx operators all across our system?. Now obviously that's not very inviting, seeing as you probably conceptually treat Rx as a 3rd party library.

Either way, the answer doesn't lie in the basal designs you two proposed, but in the users of those designs. I recommend breaking your design down to abstraction levels, and making sure that the use of Rx operators is scoped in just one level. When I talk about abstraction levels, I mean something similar to the OSI Model, only in the same application's code.

The most important thing, in my book, is to not take the design standpoint of "Let's create something that's going to be used and scattered all across the system, and so we need to make sure we do it just once and just right, for all the years to come". I'm more of a "Let's make this abstraction layer produce the minimal API necessary for other layers to currently achieve their goals".

About the simplicity of both of your designs, it's actually hard to judge since Foo and Bar don't tell me much about use cases, and hence readability factors (which are, by the way, different from one use case to another).


问:
Why is it called Just In Time?
I know what the JIT compiler is but how about why is it called that, it obviously catches exceptions Just in Time, but how and why should it be called this?

Sorry if this sounds a bit vague.

答:
Code is compiled when called. It is compiled just in time, or just before it is called if you prefer.

This apply to methods. If a method is never called, it is never compiled.

Title: Why is it called Just In Time?


答:
It doesn't have anything to do with exceptions.

The name reflects the fact that the software is not compiled into machine code until it is about to be executed. This allows you deploy an application to multiple computers and have machine-specific optimizations applied at runtime.

Title: Why is it called Just In Time?

Body:
I know what the JIT compiler is but how about why is it called that, it obviously catches exceptions Just in Time, but how and why should it be called this?

Sorry if this sounds a bit vague.


答: The Just-In-Time compiler doesn't have anything to do with exceptions. It refers to when code is compiled. Some languages, like Java, are translated from the language that you program in with your favorite editor into byte code. At runtime, some byte code might be further compiled into native code just prior to execution (hence the name, just-in-time). This is in contrast to some languages, like C, that are compiled into native machine code at the time when you invoke the compiler.</p>

Title: Why is it called Just In Time?


问:
Company PC refresh, laptop or desktop?
My company is getting PC refreshes with a choice of to have a desktop or laptop.  Each one seems to have its pros and cons. Would you want the flexibility and freedom of the laptop but take the risk of working extra hours at home? Or a desktop limited to one place, but not having to worry about taking work home and disrupting home time?

I'm not asking what would be better for coding, but more for convenience and productivity.  I currently have a desktop and work about 8 to 9 hours a day, with only coming in on the weekends for when we get behind on major deadlines. I love developing but I also have quite a busy life after work. I feel that having a work laptop will only haze the line of work and home.

答:
If you work as a programmer (or do you have any other computing-intensive task) the only option is a powerful desktop (or let call it a workstation).

A laptop, even if powerful, is usually limited in the number of HDD it can mount, it will be slower, less ergonomic, will overheat... They are improving and reducing the gap to a good desktop, but for any serious work they aren't enough.

If you have mobility needs, the laptop should be an addition to the desktop, and not an alternative.

Title: Company PC refresh, laptop or desktop?


问:
How to maintain Motivation and enthusiasm once you have figured out the solution needed
I am currently undertaking a software project on my own time. When I first got the project I put in many hours working out how to do the "tricky" parts of the solution. I spent many hours googling and reading up on classes available on MSDN that I could use for the project. I was madly excited and passionate about doing this work.

However once, I got a working samples of how I could get around the "tricky" parts and got to the part where all that I needed to do was "grunt" work to finish the project, I lost all interest and desire to work on he project. Suddenly instead of looking forward to sitting down and working on this project it became a chore and a major hassle to motivate myself.

I am now fast approaching the deadline and I am getting the work done now, but it is under very high pressure as I have left it almost too close to the deadline! I will manage to get it done but it will involve several all-nighters. (BTW I completely despise doing these all-nighters and would love to eliminate these by maintaining my motivation and working at the project continuously.)

So my questions are is this normal? Does everyone else notice such spikes and troughs in their enthusiasm for projects?

Anyone more experienced have any advice on how to keep the motivation going?

Or am I just not designed to work on a full project lifecycle, should i and people like me being doing an R&D type role where I can do the fun figuring out part of the projects and leave it for someone else to finish the "les interesting/mundane" coding?

答:
Did you heard about the flow?

[...] those who find pleasure and lasting satisfaction in activities that bring about a state of "flow."

As you can see in the following illustration, the challenge must be high as well as the skill level. I suspect that you skill level became too high for the remaining challenge in you fell into apathy.

So what to do?

I personally try to delegate all tasks I'm not skilled at or task in which challenge is far to low. I will try to avoid doing repetitive administrative tasks for example. But when you are alone like you, it is not easy to do.

Therefore, you must use a strategy that will somewhat force you to advance. Something that won't necessarily put you in the flow, but in a sufficient productivity state.

I use a list.

Everything I must do is on the list. The list is ordered so an item always provide more value that the next item (with some rare exceptions).

When I feel the negative emotion that comes with apathy, boredom or worry, I pick the first item in the list and I start to work on it. I tell to myself something like : "how you feel now is transient".

Usually, 5 to 10 minutes after, you are so focused on the task that you do that you don't feel the wrong emotions anymore.

Hopefully, sometimes, the next task will be more challenging and you'll experience the flow again.

As a long term strategy, I would build a cross-functional team. As a side note, I would say that not everyone is affected by what you describe.


答: In .Net, say when a C# program is compiled, it is compiled into what is called "Microsoft intermediate language" (MSIL) Code, this code is machine independent. The MSIL Code is not directly executable as is. It must be converted (and optimized) to code that can be executed by the target OS (and CPU). That conversion occurs when you request a .Net program to run and is performed by the Just In Time (JIT) compiler, the JIT produces executable that is specific to OS (and CPU) you are running the application on. So the name Just In Time, indicates that the compilation from MSIL to native OS code only occurs when you request the code to execute. For more information see Compiling MSIL to Native Code.</p>

Title: Why is it called Just In Time?


答:
The name comes from the "just in time" manufacturing methodology, wherein parts are delivered "just in time" to be installed. In manufacturing, it costs a lot of money to keep parts and supplies in inventory, and producing and delivering them as they're needed makes a process cheaper/more efficient.

The Java JIT compiler works in a way that's analogous to JIT manufacturing: instead of compiling code beforehand and keeping it around, it compiles code as its needed. This gives you short development cycles and immediate feedback of an interpreted language and the speed of a compiled language.

Title: Why is it called Just In Time?


问:
Does it make sense to use ORM in Android development?
Does it make sense to use an ORM in Android development or is the framework optimized for a tighter coupling between the UI and the DB layer?

Background: I've just started with Android development, and my first instinct (coming from a .net background) was to look for a small object-relational mapper and other tools that help reduce boilerplate clode (e.g. POJOs + OrmLite + Lombok).

However, while developing my first toy application I stumbled upon a UI class that explicitly requires a database cursor: AlphabetIndexer. That made me wonder if maybe the Android library is not suited for a strict decoupling of UI and DB layer and that I will miss out on a lot of useful, time-saving features if I try to use POJOs everywhere (instead of direct database access).

Clarification: I'm quite aware of the advantages of using ORM in general, I'm specifically interested in how well the Android class library plays along with it.

答:
Android does not play as nicely with other frameworks as it could. Its recommended style of development assumes you build everything from its API, without other libraries. The UI layer is very tightly coupled to the model. This style is ideal for writing smaller, modular apps, not for complex applications.

You need to give some thought as to whether you will want any of Android's functionality; if you don't need it, then you have nothing to lose by using an ORM. If this is not the case, you may need to settle for a hybrid. Use an ORM for all you can, but give yourself hooks to Cursors and any other low-level objects you require. If the ORM you choose requires DAOs (I'm not familiar with the one you mentioned), then this layer is probably the best place for them.

Alternatively, you may need to use no external ORM at all. If your needs are straightforward you can write a simple data access layer that meets them. Most apps database requirements are not great. If you have only a couple of tables, just write a couple access classes and the model objects and call it good.

YAGNI and KISS are the keywords to success here. I suggest you spend a few days prototyping. Don't be afraid to throw out the simple test apps. Try out all your ideas alone, then decide if any or all will work for your project.


答:
Protection is too generic ( protection from what? ).

I would try to use a more specific name. Its very hard to say what the name of the class is without knowing what it is intended for. If it is checking a licence, you can use LicenseChecker.

I prefer having real nouns as Class names. There is lot of debate on this so I won't claim I'm 100% right - it is just my preference. Although LicenseChecker is a noun, it feels wrong to me - because it is still emphasizes on the verb ( check ).  What I would have is a License object with a isValid() method which checks whether license is valid. Your License object can be obtained from your Licensing class, using Licensing.getLicense()


答:
As @kevin cline has pointed out there are two different constraints. I'll call these the accuracy and the efficiency constraints.

Checking the accuracy constraint should be straightforward. Basically, all you need to do is test that you can recreate the original data. That should be straightforward as you can use tools like Patch as kevin suggests.

But the efficiency constraint is trickier. I think that setting a threshold is a bad idea. Suppose that you set the thresholds at 10% lower the the algorithms current performance.

What happens if the algorithm's efficiency  drops by 1% as a result of a change? Your tests won't tell you about it.

What if the algorithm's efficiency is increase by 1%, will you notice?

What happens if the algorithm is improved by 20%, and then degraded by 10%, you are still well above your initial thresholds, so the test won't help you.

The problem is that the efficiency constraints is not a pass/fail concern. Trying to force it into a pass/fail test with a threshold is not a good idea.

I think you should treat this like performance testing. For each revision, run all the tests and collect the efficiency data. Plot all the data on a graph showing the changing efficiency with different revisions. Whenever the efficiency on a test declines, automatically send an e-mail to someone who can make the judgement call on whether its acceptable or not.

Title: Automated tests for differencing algorithm

Body:
We are designing a differencing algorithm (based on Longest Common Subsequence) that compares a source text and a modified copy to extract the new content (i.e. content that is only in the modified copy). I'm currently compiling a library of test case data.

We need to be able to run automated tests that verify the test cases, but we don't want to verify strict accuracy. Given the heuristic nature of our algorithm, we need our test pass/failures to be fuzzy. We want to specify a threshold of overlap between the desired result and the actual result (i.e. the content that is extracted).

I have a few sketches in my mind as to how to solve this, but has anyone done this before? Does anyone have guidance or ideas about how to do this effectively?


答:
When Java was new, WORA was something to boast about - specifically, that you could compile on one platform and run that (compiled bytecode) on other platforms.

Of course, interpreted languages run pretty much similarly regardless on what platform the interpreter runs on (as long as the interpreter is available for that platform). However, file systems, permission issues, encodings, line endings and countless other small but irritating issues can cause headaches. Some platform-dependent things aren't easy to abstract away.

Title: How is the JVM and Java's WORA different from other high level languages?

Body:
In the Java world, we often talk about the JVM, and when Java was new it had the supposedly killer feature of "Write Once, Run Anywhere."

From the way people talk and write, this seems different from the way that Python, for example, works.  Yet I've not been aware of any way that Python code that I've written would work differently on another machine.  (Though I haven't written that much Python.)

So what am I missing?  How is the JVM different from a Python interpreter?  Is there a way that Python lacks Java's platform independence?  Or is this just a cultural difference?


问:
Dynamic Fields/Columns
What is the best way to allow for dynamic fields/database columns? For example, let's say we have a payroll system that allows a user to create unique salary structures for each employee. How could/should one handle this scenario? I thought of using a "salary" table that hold the salary component fields and joining these columns to a "salary_values" table that hold the actual values. Does this make sense?

Example Salary Structures:

Notice how the components of the salary can be shared or unique.

-- Jon's Salary --

```<code>Basic           100
Annual Bonus    25
Tel. Allowances 15
</code>```

-- Jane's Salary --

```<code>Basic             100
Travel Allowances 10
Bi-annual Bonus   30
</code>```

答:
The best way is to go vertically instead of horizontally.  For example, a commission-based system that increases the commission based on number of units sold could be a table structured like this:</p>

```<code>Units    Commission
10         .01
100        .02
300        .05
1000       .10
</code>```

Title: Dynamic Fields/Columns

Body:
The best way is to go vertically instead of horizontally.  For example, a commission-based system that increases the commission based on number of units sold could be a table structured like this:

Units    Commission
10         .01
100        .02
300        .05
1000       .10


答:
It will depend on the specifics of your case, but it might be best to take a metadata approach, where you have a salary_properties table which stores key-value pairs to let you flexibly give each employee a unique salary structure. This will be very flexible, but you can probably already tell that this table could get very large and unwieldly. Indexing can also be a problem. You may also want to read up on the Entity-Attribute-Value pattern, if you really think you need this kind of flexibility. EAV is not without issues though.

Based on your example, I don't think metadata or EAV is really necessary. I think a stand-alone salary table might be enough.

```
Salary
------
   employeeID
   salaryID
   base_amt
   bonus_pct
   bonus_type (annual or bi-annual)
   travel_expense_amt
   tel_expense_amt
   ...
```

I suppose if you had many types of expenses, you might want to break that out to a separate salary_expenses table, and if the types of expenses, then you might want to have a salaray_expense_type_id that refers to a salary_expense_types table, but otherwise, Keep It Simple!

Title: Dynamic Fields/Columns

Body:
What is the best way to allow for dynamic fields/database columns? For example, let's say we have a payroll system that allows a user to create unique salary structures for each employee. How could/should one handle this scenario? I thought of using a "salary" table that hold the salary component fields and joining these columns to a "salary_values" table that hold the actual values. Does this make sense?

Example Salary Structures:

Notice how the components of the salary can be shared or unique.

-- Jon's Salary --

```<code>Basic           100
Annual Bonus    25
Tel. Allowances 15
</code>```

-- Jane's Salary --

```<code>Basic             100
Travel Allowances 10
Bi-annual Bonus   30
</code>```

Body:
It will depend on the specifics of your case, but it might be best to take a metadata approach, where you have a salary_properties table which stores key-value pairs to let you flexibly give each employee a unique salary structure. This will be very flexible, but you can probably already tell that this table could get very large and unwieldly. Indexing can also be a problem. You may also want to read up on the Entity-Attribute-Value pattern, if you really think you need this kind of flexibility. EAV is not without issues though.

Based on your example, I don't think metadata or EAV is really necessary. I think a stand-alone salary table might be enough.

Salary
------
   employeeID
   salaryID
   base_amt
   bonus_pct
   bonus_type (annual or bi-annual)
   travel_expense_amt
   tel_expense_amt
   ...

I suppose if you had many types of expenses, you might want to break that out to a separate salary_expenses table, and if the types of expenses, then you might want to have a salaray_expense_type_id that refers to a salary_expense_types table, but otherwise, Keep It Simple!


答:
Everyone's different, but I would look to one of the following points/suggestions for motivation:

Knowing that once you get through the "grunt" work, you'll enjoy
seeing your research and hard work and in action.

Look for existing libraries that can cut out some of that grunt work.
Finding one could save you time and make coding more enjoyable.

Break up your coding tasks into smaller definable chunks.  Make a
list, then once you finish a chunk of work you can check it off and
visibily see your progress.

Find out what's killing your motivation and try to reduce it.  For
example, you say you're not looking forward to all-nighters, but
maybe if you could get an extension on the deadline you would be more
motivated.

Think about how you can translate your research into code in the
most elegant way possible.  Once you start coding, it might not be as
mundane as you thought!

Title: How to maintain Motivation and enthusiasm once you have figured out the solution needed

Body:
I am currently undertaking a software project on my own time. When I first got the project I put in many hours working out how to do the "tricky" parts of the solution. I spent many hours googling and reading up on classes available on MSDN that I could use for the project. I was madly excited and passionate about doing this work.

However once, I got a working samples of how I could get around the "tricky" parts and got to the part where all that I needed to do was "grunt" work to finish the project, I lost all interest and desire to work on he project. Suddenly instead of looking forward to sitting down and working on this project it became a chore and a major hassle to motivate myself.

I am now fast approaching the deadline and I am getting the work done now, but it is under very high pressure as I have left it almost too close to the deadline! I will manage to get it done but it will involve several all-nighters. (BTW I completely despise doing these all-nighters and would love to eliminate these by maintaining my motivation and working at the project continuously.)

So my questions are is this normal? Does everyone else notice such spikes and troughs in their enthusiasm for projects?

Anyone more experienced have any advice on how to keep the motivation going?

Or am I just not designed to work on a full project lifecycle, should i and people like me being doing an R&D type role where I can do the fun figuring out part of the projects and leave it for someone else to finish the "les interesting/mundane" coding?


答:
In your example good approach would be separating Salary from Employee.

A Salary does not describe a Employee and should not be stored in the Employee table. Details of Salary should be stored in a Salary table, in which you could also record extra information about the salary , like when the salary was made, and what the salary commission rate, etc.

There are also some common database design mistakes to avoid that are nicely compiled in this post - Ten Common Database Design Mistakes

Edit: The detailed summary items need to be kept in a separate SalarayItem table. With a s one to many relationship between Salary->SalaryItem

Title: Dynamic Fields/Columns


问:
Can't understand example using continuations
I'm reading the r6rs Scheme report and am confused by the explanation of continuations (I find it to be too dense and lacking of examples for a beginner).

What is this code doing and how does it evaluate to 4?  Why does call/cc want an argument that's a function of one argument?  How is call/cc's argument used?

```<code>(+ 1 (call-with-current-continuation
       (lambda (escape)
         (+ 2 (escape 3)))))
          =⇒ 4
</code>```

This example is from section 1.11 - Continuations.

答:
Chris' answer is great, but now that I've figured it out I'd like to add a bit more explanation from the perspective of a beginner to continuations.

call/cc examples

I've done (define call/cc call-with-current-continuation) and will use hop (in the manner of "The Seasoned Schemer") to represent the continuation.

ignoring the parameter:  normal evaluation

```<code>(call/cc
  (lambda (hop)
    (+ 2 3)))
=> 5
</code>```

hopping the entire expression:  also normal evaluation

```<code>(call/cc
  (lambda (hop)
    (hop (+ 2 3))))
=> 5
</code>```

hopping the operator:

```<code>(call/cc
  (lambda (hop)
    ((hop +) 2 3))))
=> #<procedure:+>
</code>```

hopping an operand:

```<code>(call/cc
  (lambda (hop)
    (+ 2 (hop 3))))
=> 3
</code>```

hopping the hopper:

```<code>(call/cc
  (lambda (hop)
    (hop hop)))
=> #<continuation>
</code>```

Basically, using call/cc gives us a way to 'hop' out of an expression, immediately aborting the computation with the specified return value.

There are many more sophisticated ways to use call/cc that I don't understand, but they're not relevant to the OP.

Body:
Chris' answer is great, but now that I've figured it out I'd like to add a bit more explanation from the perspective of a beginner to continuations.

call/cc examples

I've done (define call/cc call-with-current-continuation) and will use hop (in the manner of "The Seasoned Schemer") to represent the continuation.

ignoring the parameter:  normal evaluation

(call/cc
  (lambda (hop)
    (+ 2 3)))
=> 5

hopping the entire expression:  also normal evaluation

(call/cc
  (lambda (hop)
    (hop (+ 2 3))))
=> 5

hopping the operator:

(call/cc
  (lambda (hop)
    ((hop +) 2 3))))
=> #<procedure:+>

hopping an operand:

(call/cc
  (lambda (hop)
    (+ 2 (hop 3))))
=> 3

hopping the hopper:

(call/cc
  (lambda (hop)
    (hop hop)))
=> #<continuation>

Basically, using call/cc gives us a way to 'hop' out of an expression, immediately aborting the computation with the specified return value.

There are many more sophisticated ways to use call/cc that I don't understand, but they're not relevant to the OP.


答:
The "salary structures" you give as examples can probably be replicated using a structure similar to what I think you're describing, with a "salary" table that is the "point of access" for one or more components, which can be described in terms of type, amount and frequency:

```<code>Salary
   salaryId int PK

SalaryItem
   salaryItemId int PK
   salaryId int FK Ref(Salary.salaryId)
   description varchar(50)
   frequency int //maps to an enum in code, maybe also a FK to a lookup table
   amount money //or decimal(12,2)
</code>```

You then have rules (which may or may not be persisted in the DB) that determine whether a particular SalaryItem should be applied to the person's paycheck depending on the "frequency" value to be applied; they should be applied on the first actual disbursement date that is equal to or greater than the function of the preceding disbursement date by which the frequency is defined. This is probably the trickier part; defining the function that determines the dates on which each frequency falls, and (if necessary) tracking the last day on which that frequency occurred.

Title: Dynamic Fields/Columns

Body:
The "salary structures" you give as examples can probably be replicated using a structure similar to what I think you're describing, with a "salary" table that is the "point of access" for one or more components, which can be described in terms of type, amount and frequency:

Salary
   salaryId int PK

SalaryItem
   salaryItemId int PK
   salaryId int FK Ref(Salary.salaryId)
   description varchar(50)
   frequency int //maps to an enum in code, maybe also a FK to a lookup table
   amount money //or decimal(12,2)

You then have rules (which may or may not be persisted in the DB) that determine whether a particular SalaryItem should be applied to the person's paycheck depending on the "frequency" value to be applied; they should be applied on the first actual disbursement date that is equal to or greater than the function of the preceding disbursement date by which the frequency is defined. This is probably the trickier part; defining the function that determines the dates on which each frequency falls, and (if necessary) tracking the last day on which that frequency occurred.


问:
Open source Projects which pays the developers?
Are there any Java open source projects that Pays the developers?

I came across this from a book : Programming Interviews Exposed.   Page #25

Are open-source projects preferable?

The vast majority of programming jobs have usually involved
  proprietary, closed-source projects, which some programmers find
  objectionable. There’s been a small shift in favor of more open
  software development, which provides more opportunities for people
  like yourself to participate in open-source projects and still be paid
  for that participation.

答:
I don't think that quotation is referring to the project paying people to support it.

It appears to be referring to companies that pay engineers to contribute to open source projects as part of their normal duties. I have seen job posts to this effect. A company might provide paid time to staff to provide contributions back to open-source projects that it uses, typically to fix defects, add enhancements, or create documentation that the company needs or finds valuable.

Another possible meaning could be companies that release some of their products as open source software. Companies like Google and Facebook have done this. These products are not their core products, but were started internally to support a core product (often not released as an open source project) and then released to the public. Someone on the staff might be responsible for overseeing the open source project and even contributing to it, and would be getting paid for this work.


问:
Pending and Approval process
So let's say I have a DB table with 8 columns, one is a unique auto-incrementing used as ID.  So I have a page that pulls in the info for each row based on query string ID.  I want to give my users the ability to propose changes.  Kinda like a wiki setup.  So I was thinking I should just have another duplicate table or maybe database altogether (without the auto-incrementing column and maybe with a date edited column) that keeps all proposed changes in queue and then when I approve them, the script can move the row from the proposed DB to the real DB.

Does this sound good or is there a better process for this?

答:
You have the right idea, but I would make the suggested edit table a bit differently. Your suggested edit table should include an auto increment key because there is no good reason not have one one as at least part of a key for any table. It should also have the key to the other table as a FK and a column for each of the columns users would be allowed to suggest edits to. Finally, there should be some audit columns, created date, modified date, created by, modified by, and a suggestion status column (accepted,rejected,pending). So your suggested edit table would look like:

```<code>PK | FK | other 7 columns | createdBy | CreatedDate | modifiedBy | modifieddate | Status
</code>```

This will allow you to keep a detailed record of who suggested what and when and what gets approved/rejected and when. This also makes it trivial to create a script to update the table used for display with the edited columns when they become approved.

Title: Pending and Approval process

Body:
You have the right idea, but I would make the suggested edit table a bit differently. Your suggested edit table should include an auto increment key because there is no good reason not have one one as at least part of a key for any table. It should also have the key to the other table as a FK and a column for each of the columns users would be allowed to suggest edits to. Finally, there should be some audit columns, created date, modified date, created by, modified by, and a suggestion status column (accepted,rejected,pending). So your suggested edit table would look like:

PK | FK | other 7 columns | createdBy | CreatedDate | modifiedBy | modifieddate | Status

This will allow you to keep a detailed record of who suggested what and when and what gets approved/rejected and when. This also makes it trivial to create a script to update the table used for display with the edited columns when they become approved.


问:
Is there any reason to use varchar over text columns in a database?
Is varchar just a remnant from before text came around, or are there use cases where you would want to use a varchar?  (Or char for that matter..)

(I use Postgres and MySQL (MyISAM) daily, so those are what I'm most interested in, but answers for other databases are of course welcome.  ^_-)

答: text, varchar and char are all used for different reasons. There are of course implementation differences (how much size they occupy .. etc), but also there are usage and intent considerations. What type you use also tells you something about the kind of data that will be stored in it (or we'd all use text for everything). If something has a fixed length, we use char. If it has variable length with a well defined upper limit then use varchar. If it's a big chunk of text that you have little control over then text would be probably your best bet.


答:
I would do this with two tables. The database is better normalized, and it allows for expansion easily if needed.

EmployeeSalaries table: (1 is Jon; 2 is Jane)

```
EmployeeId    SalaryTypeId    Amount    Frequency
1             1               100       1
1             2               25        1
1             4               15        1
2             1               100       1
2             3               10        1
2             2               30        .5
```

SalaryTypes table

```
Id   Description
1    Base Salary
2    Bonus
3    Travel Allowance
4    Telephone Allowance
```

If there are many different types of "Allowances", I would consider making a single "Allowance" salary type, and adding a Description or Note column to the EmployeeSalaries table

Title: Dynamic Fields/Columns

Body:
I would do this with two tables. The database is better normalized, and it allows for expansion easily if needed.

EmployeeSalaries table: (1 is Jon; 2 is Jane)

EmployeeId    SalaryTypeId    Amount    Frequency
1             1               100       1
1             2               25        1
1             4               15        1
2             1               100       1
2             3               10        1
2             2               30        .5

SalaryTypes table

Id   Description
1    Base Salary
2    Bonus
3    Travel Allowance
4    Telephone Allowance

If there are many different types of "Allowances", I would consider making a single "Allowance" salary type, and adding a Description or Note column to the EmployeeSalaries table


问:
Facebook App EULA & Restrictions: What can't they do that my web app can?
I have written a nifty little web app (in Java/GWT/JS) and have been experimenting with the idea of making it available through Facebook as a Facebook App as well.

After spending some time reading Facebook's developer docs, it seems like I can just create a Facebook App to point at any URL I want and use that as the app/canvas. It accomplishes this via iframes.

So, my tentative plan is to just point it towards my (existing) web app so that I don't have to totally re-write it.

But then that got me thinking: Facebook must regulate what sorts of things can be done through a Facebook App, vs. what an app can't do.

For instance, I can't imagine I can point a Facebook App to point at a URL for a web app that accepts e-commerce payments (that would by-pass Facebook altogether and not allow them to take a cut from the ecom transaction!). Also, I can't imagine that Facebook allows developers to point their Facebook Apps to just any old URL without some sort of a scan, otherwise that would open Facebook up to the horrors of every security threat knownst to humanity.

I know for a fact that when you write an iOS native app and put it up on the Apple App Store, that Apple actually scans your source code for violations of their EULA.

So my question: does Facebook do the same? If so, what are their terms & conditions for what a Facebook app can/can't do? Suprisingly, I can't find this anywhere!! Thanks in advance!

答:
You're looking for the Facebook Platform Policies.

They do have a lot of rules, but most of them are related to protecting the Facebook® brand, protecting user data, and preventing spam/scams (they also have standard third-party hosting EULA terms, like no apps about gambling, porn, drugs, alcohol, and the like). Basically, if you are not using/abusing the Facebook brand in any way or trying to steal data or do anything shady, and your app is family-friendly, it's probably okay (but of course, never assume this—read the full policy!).

They have a subsection entitled "Enforcement" where they say that they can remove your app for any reason. They use both automated and manual testing for compliance, but don't divulge many details, so it's impossible to tell how extensive their automated checks are; they certainly don't make a claim to your source code, but probably do some sort of automated scan of your public-facing html/javascript. The full text of this sub-section is reproduced here:

We can take enforcement action against you and any or all of your
  applications if we determine in our sole judgment that you or your
  application violates Facebook Platform Terms and Policies. Enforcement
  action is both automated and manual, and can include disabling your
  application, restricting you and your application's access to Platform
  functionality, terminating our agreements with you, or any other
  action as we in our sole discretion deem appropriate.

Communication with developers takes place via an email sent from the
  facebook.com or facebookmail.com domain to the contact email address
  registered to the application. To stay in touch, please ensure that
  your email address is current and that you do not filter out any such
  messages.

Regarding your question about payments, they have an entire sub-policy covering just payments—the Facebook Developer Payments Terms. The gist of it is that yes, they want to use only their proprietary payments platform (called "Facebook Payments" and often using a virtual currency called "Facebook Credits"), and they take a 30% cut. But if your app is going to implement a payments system, don't make any assumptions—read the full policy!


问:
De-facto standards for customer information record
I'm currently evaluating a potential new project that involves creating a DB for typical customer information (userid, pwd, first & last name, email, adress, telfnr ...). At this point, requirements are only roughly defined.

The customer DB is expected in the O(millions) of records. In order to calculate some back-of-the-envelope numbers for DB sizing and evaluate potential DB options & architectures, I'm looking for some de-facto standards for these kind of records. In particular, the std size of every field (first name, last name, address,...) or typical avg for a simple customer record would be great info.

With so many e-commerce websites out there, there should be some kind of typical config that can be reused and avoid re-inventing the wheel.

Any ideas?

---- edit ----

The answers seems to be steering towards adopting an standard customer record vs designing your own. I would like to stress that the focus of this question is to locate a reference for field sizing for a customer object, and avoid figuring that out on my own.(I've emphasized that part on the original text -now in bold-)

答: The Open Applications Group publishes a set of open standards for application implementation and interoperability.  They're mostly XML-oriented, but they do specify a standard customer record with individual fields and sizes (look for CustomerPartyMaster in the document standards list).


问:
How is the JVM and Java's WORA different from other high level languages?
In the Java world, we often talk about the JVM, and when Java was new it had the supposedly killer feature of "Write Once, Run Anywhere."

From the way people talk and write, this seems different from the way that Python, for example, works.  Yet I've not been aware of any way that Python code that I've written would work differently on another machine.  (Though I haven't written that much Python.)

So what am I missing?  How is the JVM different from a Python interpreter?  Is there a way that Python lacks Java's platform independence?  Or is this just a cultural difference?

答:
Java does a very good job on isolating you from the underlying OS and gives you the same exact tools on most platforms it works on to talk to things in the underlying OS.

Python on the other hand does not do as good of a job in isolating you from the underlying OS, It does not have a standard way of handling between process communications (look at the differences in the sys module and os module between a windows and *nix implementation of Python for example.)

I have written code in python that would only work on a *NIX box or Windows box using just Python available API calls, where in Java it would be very difficult to write code that was just Java API that would not work the same on both a Windows box or *NIX box


答:
Existing International Standards

There are quite a few standards, but specific to certain fields, with varying requirements for each of them depending on their data collection needs.

For instance, but not limited to (and talking from experience with both of these):

Software dealing with patient data and medical records if you plan on being certified for certain specs.

Uniform Data Standards for Capturing Patient Medical Record Information at the Point of Care (presents a list of different standards for medical records)

Eletronic Medical Records and their Technical Standards

the wider field of Electronic Health Records and their Technical Standards

software dealing with mobile operators' call data records and service data records (not exactly as a standard, but for interoperability between partner networks).

Some of the above link to fairly detailed documents, listing even requirements for health and formatting of fields (for instance, HL7 uses well-defined data-types). At lot of them do not go in this much detail though.

Government-Driven Standards for Internal Records

Governments, national or local, often have a strong need to record and store personal information for public offices, and obviously have come up with own "standards", which they implement across their organizations (with varying levels of success and interoperability with partner organizations).

An example could be this Data Formats for Identity Records Standard from the Government of New Zealand.

De-Facto Standards in Software

You could take inspiration from these, or use the source of known open-source CRM software to use as best-practices and guidelines for the data specifications of your customer data.

See the Top 10 Open-Source Business and Social CRM Software list, for which you could look up their data-models yourself.

Title: De-facto standards for customer information record

Body:
I'm currently evaluating a potential new project that involves creating a DB for typical customer information (userid, pwd, first & last name, email, adress, telfnr ...). At this point, requirements are only roughly defined.

The customer DB is expected in the O(millions) of records. In order to calculate some back-of-the-envelope numbers for DB sizing and evaluate potential DB options & architectures, I'm looking for some de-facto standards for these kind of records. In particular, the std size of every field (first name, last name, address,...) or typical avg for a simple customer record would be great info.

With so many e-commerce websites out there, there should be some kind of typical config that can be reused and avoid re-inventing the wheel.

Any ideas?

---- edit ----

The answers seems to be steering towards adopting an standard customer record vs designing your own. I would like to stress that the focus of this question is to locate a reference for field sizing for a customer object, and avoid figuring that out on my own.(I've emphasized that part on the original text -now in bold-)


问:
What if globals make sense?
I've got a value that many objects need. For example, a financial application with different investments as objects, and most of them need the current interest rate.

I was hoping to encapsulate my "financial environment" as an object, with the interest rate as a property. But, sibling objects that need that value can't get to it.

So how do I share values among many objects without over-coupling my design? Obviously I'm thinking about this wrong.

答:
I've got a value that many objects need.

This is a design smell. It's uncommon that many objects need to know about something. That said, the current interest rate is a fairly good example of exceptional circumstances. One thing to worry about is that there's rarely the interest rate. Different financial instruments use different rates. At the very least, different locales use different 'standard' rates. Further, to aid in testing and reporting, you'll usually want to pass in a rate since you don't want to use the current rate there. You want to use the 'what if' or 'as of reporting date' rate.

So how do I share values among many objects without over-coupling my design?

By sharing them, not having them all refer to a single instance. Passing the same thing around is still coupling to a degree, but not over coupling since something like the current interest rate is needed as input to a variety of calculations.

Title: What if globals make sense?


答:
In this particular instance I would use the Singleton Pattern.  The FinancialEnvironment would be the object all the other class libraries are aware of, but would be instantiated by the Singleton.  Ideally you would then send that instantiated object to the various class libraries.

For example:

Service Layer (class library) - Instantiates the FinancialEnvironment object via a singleton

Business Logic Layer (class library) - Accepts the FinancialEnvironment object from the service layer

Data Access Layer (class library) - Accepts the FinancialEnvironment object from the service layer (or depending on your architecture the Business Logic Layer).  Or maybe the Singleton invokes the Data Access Layer to get information, such as interest rate, from a repository (database/web service/WCF service) whatever.

Entities (or DTOs if you want to call it that) class library - Where the FinancialEnvironment object lives.  All other class libraries have a reference to the Entities class library.

The other classes are only tied together through the Entities class library, they accept an instantiated FinancialEnvironment object.  They don't care how it was created, only the service layer does, all they want is the information.  The singleton could also be smart enough to store several FinancialEnvironment objects, depending on the rules for the local as @Telastyn pointed out.

On a side note, I am not a huge fan of the Singleton Pattern, I consider it a code smell, as it can be misused very easily.  But in some cases you need it.

Update:

If you absolutely, positively must have a global variable then implementing the Singleton Pattern as described above would work.  However, I am not a big fan of this, and based on the comments from my original post, several other people are not either.  As something as volatile as a InterestRate, a Singleton may not be the best solution.  Singletons work best when the information doesn't change.  For example, I used a Singleton in one of my applications to instantiate performance counters.  Because if they do change then you must have logic in place to handle the data being updated.

If I were a betting man I would bet the interest rate was stored somewhere in a database, or it was retrieved via a web service.  In that case a Repository (data access layer) would be recommended to retrieve that information.  To avoid unnecessary trips to the database (I am not sure how often interest rates change, or other information in the FinancialInformation class), caching could be used.  In the C# world Microsoft's Caching Application Block library works very well.

The only thing that would change from the example above, would be the various classes in the service layer that need the FinancialInformation would retrieve from the Data Access Layer instead of the Singleton instantiating the object.

Title: What if globals make sense?

Body:
I've got a value that many objects need. For example, a financial application with different investments as objects, and most of them need the current interest rate.

I was hoping to encapsulate my "financial environment" as an object, with the interest rate as a property. But, sibling objects that need that value can't get to it.

So how do I share values among many objects without over-coupling my design? Obviously I'm thinking about this wrong.


答:
I'm speaking from the experience of one who has about a month of maintenance on  a good sized (~50k LOC) project that we just released.

I can tell you that you probably don't really want a global object. Introducing that sort of cruft provides many more opportunities for abuse than it does help.

My initial suggestion is that if you have several different classes that need a current interest rate then you probably want to just have them implement an IInterestRateConsumer or something. Inside that interface you'll have a SetCurrentInterestRate(double rate) (or whatever makes sense), or maybe just a property.

Passing an interest rate around is not actually coupling - If your class needs an interest rate, that's part of its API. It's only coupling if one of your classes starts worrying about exactly how the other class uses that interest rate.

Title: What if globals make sense?


问:
Do you think that storing a variable length encoding in std::string or std::wstring is OK and do you do it?
I'm kind of horrified that people actually suggest using UTF-8 inside a std::string and are OK with UTF-16 std::wstring.

Do you actually do this? Do you think that it is OK?

答:
Well, let's say that many programmers still don't know that UTF-16 is a multibyte encoding (they still think that 16-bit wide char is enough to represent all the Unicode characters, but actually they are stuck with the old UCS-2).

However, there's no real drawback in using a wstring for storing UCS-16 text, but you should know that its length doesn't necessarily represent the number of text symbols that will be printed.


答:
Bounties & Rewards

Many open source projects offer bounties for fixing certain bugs:

Chromium's Vulnerability Reward Program (sponsored by Google, and expanded several times)

Ubuntu (sponsored by Canonical) (appears to be closed now)

Others are sponsored by individual donations or 3rd-parties:

The FOSS Factory

Open-Source Commercial and Non-Commercial Software Positions

Some open-source projects (open-source does not imply free software) are sponsored and managed and they have full-time employees working on these. These could include:

RedHat (Linux, some Java-related development like GCJ contributions, past contributions from their members to known open-source projects for internal work, etc...)

Sun/Oracle (OpenJDK, MySQL, and many related community projects)

Google (many of their open-source libraries have full-time teams, Chromium, Android...)

While this may not why you originally had in mind, they are indeed open-source projects, and they do have people being paid to work on them.

Title: Open source Projects which pays the developers?

Body:
Are there any Java open source projects that Pays the developers?

I came across this from a book : Programming Interviews Exposed.   Page #25

Are open-source projects preferable?

The vast majority of programming jobs have usually involved
  proprietary, closed-source projects, which some programmers find
  objectionable. There’s been a small shift in favor of more open
  software development, which provides more opportunities for people
  like yourself to participate in open-source projects and still be paid
  for that participation.


问:
Do I lose anything by coding in c# and using free online vb.net code convertors?
The company I work for uses vb.net since there are many programmers who moved up from vb6 to vb.net. Basically more vb.net resources in the company for support/maintenance vs c#. I am a c# coder and was wondering if I could just continue coding in c# and just use the many online free c# to vb.net code convertors. That way, I will be more productive and also be more marketable since there are more c# jobs compared to vb.net jobs. I have done vb6 many years ago and I am comfortable debugging vb.net code. It's just the primary coding language. I am more comfortable in c#. Will I lose anything if I use this approach. (code conversion). Based on what i read online the future of vb.net is really "Dim". Please advise. thank you</p>

答:
Unless you run it by your manager first, the thing you are most likely to loose by doing that is your job....and if you do run it by your manager, the most likely outcome is you not being assigned to any VB.net projects.

Automated conversions give you a starting point, not a finished product.


问:
What are some ways to be more productive with Emacs?
I've used Emacs quite a bit, and I'm comfortable with the most basic commands/shortcuts, but I know Emacs has a lot more to offer than what I'm using. What are some of the lesser known features of emacs that can help me become a more productive programmer?</p>

答:
The great Steve Yegge has written a very nice blog post 10 Specific Ways to Improve Your Productivity With Emacs. It includes tricks and habits like

keyboard configuration (Swap Caps-Lock and Control, rebinding M-X)

Deleting word with backspace (if you are fast enough typer, getting rid of the whole word and retyping it is more convenient than continuously hitting backspace until your typo is erased)

Navigation by incremental searching

Using temporary buffers and learn to navigate buffers efficiently

Getting rid of navigation by mouse, menus and other GUI things

Learning to use the help system

Learning the power of regular expressions

He also lists some useful emacs modes and mentions many other tricks that make people wait in anticipation for future updates to the blog post.


答:
Why not put the interest rate data in a central cache?

You can use one of several cache libraries, whichever suits you requirements best, something like memcached solves all you concurrency and code management problems and will allow your application to scale to multiple processes.

Or go the whole hog and store them in a database, which will allow you to scale to multiple servers.

Title: What if globals make sense?


答:
In addition to @haylem's fairly comprehensive answer, there's also the contribution of academics to open-source development, where the University they work for - or grant support - pays for the development of software and often encourages or mandates that the developed software be made publicly available in some form.

R, for example, has a tremendous amount of open-source support from academics writing software, as do the scientific computing portions of the greater Python ecosystem.


问:
What is the use of Spring's init-method and destroy-method?
While learning Spring framework, I found that Spring framework provides init-method and destroy-methods which can be used to initialize some properties or to do housekeeping stuff.

We can do all those things in the bean's constructor so why do Spring provides these things and in the real world what is the actual use of these two things?

答:
The argument is one that continually happens in spring/java circles. Here's a few blog posts which illuminate most of the important points:

Setter injection vs Constructor injection

Constructor injection vs Setter injection

Yet another Constructor injection vs Setter injection

Primary arguments for constructor injection:

Constructor injection ensures all mandatory properties have been satisfied, and it is simply not possible to instantiate an object in an invalid state

Enforces the order of initialization and prevents circular dependencies


问:
WWDC 2012 announced features on iOS 5?
I am relatively new to iOS development, so after watching a bunch of WWDC videos announcing new awesome features for the iPhone SDK, I still got a few questions regarding their support for older devices. Specifically:

Do the new compiler features (such as literals support, auto-synthesize, etc) require iOS 6 on the target device, or can the new style code be deployed to iOS 5 devices?

Auto-layout for iOS, same question. Will it only be supported on iOS 6, or 5 as well? If it's 6 only, what kind of fallback are we expected to implement?

Would really appreciate if someone could clarify this for me, as I'm thinking about rewriting my older unfinished project and I would love to use some of that improved SDK functionality.

答:
So I’ve tried this out myself, by running a test app with some new SDK features in the iOS 5 simulator, and the findings are practically as expected though still somewhat disappointing.

The compiler features, such as literals and auto-synthesize, work fine and good. However, if the app tries to access an IB file that contains some auto-layout stuff, the app will crash with this error:

```<code>*** Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: 'Could not instantiate class named NSLayoutConstraint'
</code>```

So, although it’s not really surprising, it is now confirmed that auto-layout won’t work on iOS versions prior to 6. I don’t believe there have been any official recommendations on what to use instead and how to provide proper fallbacks, but I believe it’d have to be separate older-iOS-specific XIBs along with same good ol’ manual layouting code.

Title: WWDC 2012 announced features on iOS 5?

Body:
So I’ve tried this out myself, by running a test app with some new SDK features in the iOS 5 simulator, and the findings are practically as expected though still somewhat disappointing.

The compiler features, such as literals and auto-synthesize, work fine and good. However, if the app tries to access an IB file that contains some auto-layout stuff, the app will crash with this error:

*** Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: 'Could not instantiate class named NSLayoutConstraint'

So, although it’s not really surprising, it is now confirmed that auto-layout won’t work on iOS versions prior to 6. I don’t believe there have been any official recommendations on what to use instead and how to provide proper fallbacks, but I believe it’d have to be separate older-iOS-specific XIBs along with same good ol’ manual layouting code.


问:
How common is meta-programming?
How often do you or have you seen meta-programming be used in projects? In uni I've never seen this be applied, but I've seen this on my previous job (when I saw it I was blown away of how effective it was).

But how common is it? Is it used all the time, or just occasionally?

答:
If you consider reflection a kind of meta-programming, it is relatively common. For some people even generic programming (templates and generics) is a form of meta-programming, so that's even more common.

In my opinion, however, meta-programming is something more complex, that involves actual code generation, and therefore quite uncommon, even in scripting languages.

Title: How common is meta-programming?


问:
Challenges in multi-player Android Game Server with RESTful Nature
I'm working on an Android Game based on Contract Bridge, as a part of my college Summer Internship project. The game will be multi-player such that 4 Android devices can play it, so there's no BOT or CPU player to be developed. At the time of getting project, I realized that most of the students had already worked on the project but none of their works is reusable now (for variety of reasons like, undocumented code and design architecture, different platform implementation).

I have experience working on several open source projects and hence I emphasis to work out on this project such that components I make become reusable as much as possible. Now, as the game is multi-player and entire game progress will be handled on server, I'm currently working on Server's design, since I wanted to make game server reusable such that any client platform can use it, I was previously confused in selecting Socket or REST for Game Server's design, but later finalized to work on REST APIs for the server.

Now, since I have to keep all players in-sync while they make movements in game, on server I've planned to use Database which will keep all players' progress, specific for each table (in Bridge, 4 players play on single table, and server will handle many such game tables).

I don't know if its an appropriate decision to use database as shared medium to track progress of each game table (let me know if there's an appropriate or better option). Obviously, when game is completed for the table, data for that table on server's database is discarded.

Now the problem is that, access to REST service is an HTTP call, so as long as client doesn't make any request, server will remain idle, and consider a situation where

A player has played a card on his device and the device requests to apply this change on the server.

Now, I need to let rest of the three devices know that the player has played a card, and also update view on their device.

AFAIK, REST cannot provide a sort-of Push-notification system, since the connection to the server is not persistent.

One solution that I thought was to make each device constantly poll the server for any change (like every 56 ms) and when changes are found, reflect it on the device. But I feel this is not an elegant way, as every HTTP request is expensive. (and I choose REST to make game play experience robust since, a mobile device tends to get disconnected from Internet, and if there's Socket-like persistent connection then entire game progress is subject to lost. Also, portability on client-end is important)

Also, imagining a situation where 10 game tables are in progress and 40 players are playing, a server must be capable to handle flooded HTTP requests from all the devices which make it every 56 ms. So I wonder if the situation is assumed as DoS attack.

So, explaining the situation, am I going on the right track for the server design? I wanted to be sure before I proceed much further with the code.

答:
checkout jWebSockets, An android implementation of websocket protocol.
having something like socket.io on the server and a websocket client on the mobile device should make life easy for you.

You will beon bi-directional TCP sockets and wont require push.


问:
How do game programmers design their classes to reuse in AI, network and play and pass mode?
For a two player game where, your opponent could be on the network, CPU itself or near you where you would play turn by turn on the same machine.

How do people design classes for re-use  ?
I am in a similar situation and have no experience in making such complex games.

But here is what I have thought,

If I am a player object , I should only be interacting with the GameManager or GameEngine Singleton , from which I will get various notifications about the game status.

I dont care where and who my opponent is, this GameManager depending upon the game mode, will interact with gameNetworkManager , or AI tell me what the opponent played.

I am not sure about the scenario where we play and pass [turn by turn on same machine].

Hoping for a brief but clear explanation or at least a link to a similar resource.:)

答:
There is no clear-cut answer, and class design for games is a very broad topic. I can hint you at two very common pitfalls though:

It is tempting to use inheritance to model polymorphism on your game entities, so that you have a BaseEntity, a PlayerCharacter, etc., and give them a dozen or so methods to model how they move, draw, decide what to do, and interact with the rest of the world. However, this makes for quite tight coupling and doesn't exactly favor reuse. A better approach is composition: make your Entity class non-polymorphic, but give it a bunch of polymorphic members to describe different aspects, e.g. a Brain (which determines their behavior; this can be a HumanPlayerBrain, an AIBrain, a NetworkBrain, etc.), an Appearance (which takes care of selecting the right models / sprites and animating them as needed), a Physics (describing properties of the entity's physics model). Each of these has its own class hierarchy, but they are otherwise mostly independent from each other, and you can mix and match them as needed.

It is also tempting to write self-updating entities, and many introductory game tutorials even recommend this. A ball that updates its own position every time you call its tick() method sounds like an elegant solution, but as soon as interactions become more complex, you'll face nasty problems - what if a hundred entities of different types are moving at the same time? Who is responsible for checking for collisions, and when one is found, which of the two objects is the 'active' one and which the 'passive'? Is it a.collideWith(b), or b.collideWith(a)? The solution is to make all your entities mostly passive; they simply expose accessors to query and update their physical properties (position, size, mass, inertia, etc.), and an overall GamePhysics object is responsible for checking all your objects and updating them. The collision handler is now world.collide(a, b), perfectly straightforward.

And then another word of caution: Making the game state a singleton seems like a logical decision, but it locks you down into no more than one game state at a time. This has two important disadvantages:

If you want a client/server architecture, the server will only ever be able to run one game at a time.

Unit-testing anything that depends on the game state is going to be harder.

Personally, I prefer passing the game state around as just another object. An additional advantage of this is that I can pass only parts of the game state to objects that have no business fiddling with the rest, e.g., an object's render() method is not supposed to modify the game logic at all, so I can pass it as const; the physics part is not supposed to do anything graphics-related, so I don't pass it a reference to the resource manager. This keeps the potential number of cross-dependencies low, which in turn leads to less complexity.


问:
Ways to have a history of changes of database entries
What are ways to allow the versioning of database entries (data)?

Think of the content-managment-systems abilities to revert back changes of articles.

What are their pros/cons?

答:
There are basically two approaches: an audit table, with all previous values stored in it, or include a start/end date as part of the table, and all updates create a new record while closing out the old one.

Update: SQL SERVER 2016 supports this as a design pattern/table type — https://docs.microsoft.com/en-us/sql/relational-databases/tables/temporal-tables?view=sql-server-2017

ContentLicense: CC BY-SA 4.0


问:
test coverage reality
I am NOT doing test driven development and I write my test classes after the actual code is written. In my current project I have a test coverage (Line coverage) of 70% for 3000 lines of Java code. I am using JUnit, Mockito and Sonar for testing. But I feel that I am not actually covering and catching 70% of the problems that can occur.

So my question is in theory is it possible to have a 100% Line coverage, but in reality it is meaningless because of low quality of the test code and maybe a 40% well written test code is much better than a bad 100% coverage? Or we can always say line coverage more or less gives the percentage of all covered issues?

答:
I don't think there's a general correlation between coverage and bugs left. However, if you didn't execute a line, you didn't test it, so 100% line coverage can't hurt if you don't let it lull you into a false sense of security.

In the end, unless you're writing a system with extremely high reliability requirements, I wouldn't sweat too much about raw coverage. First, test the most important paths through the program. Then, for every issue that crops up, write a unit test before fixing it. That way, you will get decent coverage in a reasonable time and will be quite safe from regressions.

Title: test coverage reality