答:
I started with a VB6 project a few years ago (company's custom ERP system) and I've slowly been migrating it to .NET.  It's somewhere around half-done.

First of all, converting from VB6 to VB.Net is almost always a bad idea (and I did a lot of research on that).  There's just too much different.  Also, if your boss thinks that VB.Net is "just like VB6" then he's completely mistaken and you have to change his outlook fast.

My strategy was to keep the two code-bases separate and maintain them separately and then slowly move entire modules from VB6 to .NET but only when there was a significant change about to happen to that module, so we could amortize some of the cost.  Even so, rewriting is a big expensive and risky task.

There are two ways to integrate existing VB6 with new .NET code (and you'll probably be doing that for a very long time, so you'd better get used to the idea).  The first way I went about it was to start writing small modules in .NET and then have the main VB6 application launch the .NET executable passing in some command line parameters.  This worked, but be warned that .NET has a start-up time hit of 4 to 10 seconds, so you're limited in what you can do this way.

Once it started to get really painful, I flipped the strategy and used the method from this CodeProject article to display the existing VB6 forms in my main .NET application.  Once I went down this route, I was able to incur only one .NET startup time hit, and use ClickOnce for deployment, which was a godsend compared to how the VB6 app was deployed previously.

That said, here are the advantages I find in .NET over VB6:

Better persistence frameworks (NHibernate, EntityFramework, Linq2Sql etc.)

LINQ (I can't stress enough how important this is)

Generics!

Lambda syntax (solves a whole class of problems like "hole in the middle" elegantly)

Similarly Action and Func types

Reflection (something that you rarely use, but when you do it's huge)

Much better unit testing support (of course, I doubt you'll convince your other employees to unit test, but you should)

ReSharper (and other refactoring/profiling tools) (10x better than MZ-Tools)

ClickOnce and/or Setup/Installer Projects

Windows Service Projects

True object-oriented support (VB6 is based on COM and is really bad in this dept.)

Static typing

Baked in XML support

WPF and Windows Forms (VB6's controls are very limiting)

WCF

Much more example code online

Exceptions (VB6's error handling is absolutely terrible by comparison)

Visual Studio's source control integration

Decimal type (VB6 never had a first class decimal type, even though it has CDec)

First class support for Guid

First class support for 64-bit integers

Better collection libraries

ReportViewer

Multithreading, task parallel library

Disadvantages of VB6:

You will notice a performance it.  It might not be enough to worry about, but trust me, you'll notice it.  VB6 compiles to native code after all.

To be fair, here are some disadvantages of maintaining a combined VB6/.NET solution:

Maintaining two data access layers (assuming your VB6 app actually has one)

Extra wiring to expose services/forms/etc. from one side to the other

Twice as much complexity/architecture to keep in your head

Now, as you've hinted at, you really ought to rebuild your architecture from the ground up if you start writing code in .NET.  However, it sounds like none of the people at your company are familiar with either the .NET and/or Java programming world, which is where a lot of the patterns and practices that are common to big enterprise frameworks come from.

If you take someone who's used to dragging a button on a form, double clicking on it, and writing some SQL strings directly in the click event handler, and that's been working for them, it's really hard to make them see an advantage to following SOLID design principles.  On the other hand, if you bite the bullet and decide that all new code is going to be covered 90% or greater by automated unit tests, then you'll quickly realize that's really hard to do unless you adopt the SOLID design principles.

So you need to take a really hard look at the reality of the situation.  In my case, I was the only programmer, and I was determined to have all new code be unit tested, even though I had no experience with it.  I can't stress enough how much this negatively impacted what I could get done in the first week, even first months.  Still, I was determined to do it, and I had buy-in from management.  Most people don't have that luxury.  Now I have lots of code and I just finished a major refactoring with almost no issues.

Realistically, you're not going to be doing unit tests, which means it's harder to justify principles like dependency injection to your team-mates.  You're going to have to sell .NET on the merits other than architectural benefits.  You have to focus on better library support and better tools.  That's the only thing that will resonate.  I would suggest the following in your demo:

Create a Windows Forms project (stay away from WPF and xaml - it's too startling)

Connect to a SQL database (some test database)

Use Linq2Sql or EntityFramework to generate a data model for it

Create a repository class that has a method to return some list of entities

Write a query in that method using linq, point out the intellisense

Point out that linq works on all objects, not just entities

Show that if you change the database and regenerate the model, you get a compile error

Drop a DataGridView on the main window

Demonstrate databinding by populating the grid with the entities from the repository

Point out all the cool stuff about the grid that's so much better than VB6

Create an .rdlc file (report)

Make a simple report inside Visual Studio

Drop a report viewer on the window and render the report inside the report viewer

(Obviously you need ReportViewer installed and have practiced all this first)

Come up with a "hole in the middle" problem and then demonstrate solving it by creating a method that takes an Action as a parameter.  Do this first by passing another method as the parameter, and then blow their mind by passing an anonymous delegate using lambda syntax

Demonstrate generics by using the List<T> and Dictionary<T1,T2> collection classes and show how it creates strongly typed code (VB6 has similar stuff, but it's dynamically typed)

Write a foreach loop that's embarrassingly parallel, use System.Diagnostics.Stopwatch to measure the time it takes to execute, then use the task parallel library to change the loop into a Parallel.Foreach loop and demonstrate the speed-up, assuming you're on a multi-core machine.

Demonstrate the ability to add a global exception handler (this is something that VB6 can't do)

That's what I would do.


问:
Firefighting allocation problem
I'm trying to develop a model to work on an assignment problem in the firegifhter area. Given n firefighters, m trucks and z ongoing fires, each with a danger level, try and allocate the resources in the best way.

Is there some work on this i can read to try and understand how should i formulate my problem (costs, and so on)?

EDIT:

I have more details on the model. For each danger level there is a minimum number of firefighter that should be guaranteed, giving priority to the higher levels. Trucks have capacity and firefighters can only be allocated if there is a truck to take them to the fire.
There's also a constraint saying that a fire can be abandoned if one with 2 or more levels above doesn't have the minimum number. Does this look like knapsack?

EDIT 2:

I am adding this because it might be of help to someone facing a similar problem. I opted to solve this using a tree. If you would like details feel free to contact and i can explain the algorithm in detail.

Disclaimer: i am familiar with assignment algorithms, like the Hungarian, for instance, and what i am looking here is not help with the algorith per se but with the formulation.

答:
Here's a couple of solutions to the knapsack problem, which seems like the best fit for your allocation problem, as FrustratedWithFormsDesigner mentions above.

University of Glasgow - Knapsack problem - includes algorithm discussion, pseudocode and java source.

Princeton - Knapsack.java - using a dynamic programming approach, by Robert Sedgewick and Kevin Wayne.

ContentLicense: CC BY-SA 3.0

Title: Firefighting allocation problem


问:
Why aren't there other programming languages that compile to Python bytecode?
In Java, there are multiple languages that compile to Java bytecode and can run on the JVM -- Clojure, Groovy, and Scala being the main ones I can remember off the top of my head.

However, Python also turns into bytecode (.pyc files) before being run by the Python interpreter.  I might just be ignorant, but why aren't there any other programming languages that compile to python bytecode?

Is it just because nobody bothered to, or is there some kind of inherent restriction or barrier in place that makes doing so difficult?

答: Simple - last time I checked, Python had no formal specification, including its bytecode. CPython is the spec, and bytecode portability is IIRC not required. Thus, it's a moving, undocumented target designed for a specific language.</p>


问:
Recommend Stanford Online Database Class?
I am taking the Stanford Online Machine Learning class which is outstanding. http://ml-class.org

Is anyone taking the Stanford Online Database class: http://www.db-class.org? Does it seem useful if you have a few years of fairly simple database experience, but no formal education in the area? Or is it mostly academic and not relevant to developing and maintaining databases in the "real world"?

答:
I sat in on all three of the Stanford courses last year, thinking AI was going to be awesome and Databases the one I'd drop if I ran out of time because I've dabbled in databases as a quaternary function of my job.  It turned out quite the opposite.  While AI felt like I was watching Sebastian Thrun's hand draw exercises, nearly everything in the Jennifer Widom's class was useful.

She covers a broad overview of database-related technologies (list posted above by another person).  The material consists of video lectures (with ungraded, in-video quizzes), exercises and programming assignments.  The exercises and programming assignments are designed to let you retake them (within the scheduled time window).  The material certainly has some academic treatment, but what I found most useful, were the hands-on exercises with a variety of technologies.  Their test harness was great, and I learned a lot from debugging my stuff.

There are optional "screenside chats," which I found entertaining.  The forums were helpful when I was really stuck on relational algebra, but the signal to noise ratio is a bit discouraging - there are a lot of people whining about credit on the exercises or the certificate of achievement, as if learning wasn't a prime goal.

One word of caution: There are several exercises due at the end of the course that take a non-trivial amount of time to work through.  It is thus important that you pace yourself, even being ahead of schedule through the fourth week.

To recap: the course was very useful and I've already applied some of the things I've learned.  I'd definitely encourage you to take it.


问:
Is this an example of a pattern or an algorithm?
I feel like I have a reusable "something" here and I'm not sure whether to think of it as a pattern or an algorithm (or neither).

It's characterized by having an unknown amount of work to accomplish a task because the subtasks can encounter various conditions which cause them to add "Issues" to a global queue.

Then, the command is run repeatedly coupled with a round of "Issue Fixing" until either there are no issues left or the number of issues does not change.

I'm just putting enough code here to show what I'm talking about - there's a bit more to it (let me know if I should post more).

```<code>        public void FindNewCampaigns()
        {
            var findNewCampaigns = Locator.Get<ICommand<IEnumerable<Campaign>>>("FindNewCampaigns");
            var campaigns = findNewCampaigns.Execute();
            var issues = Locator.Get<ICollection<Issue>>("CommandIssues");
            while (issues.Count > 0)
            {
                int before = issues.Count;
                FixIssues(issues);
                issues.Clear();
                campaigns = findNewCampaigns.Execute();
                int after = issues.Count;
                if (before == after)
                {
                    System.Console.WriteLine("No issues got fixed, quitting ({0}/{1}).", before, after);
                    break;
                }
            }
            if (issues.Count == 0)
            {
                CreateCampaigns(campaigns);
            }
        }

        private void FixIssues(ICollection<Issues.Issue> issues)
        {
            foreach (var issue in issues)
            {
                System.Console.WriteLine("ISSUE: " + issue.GetType().Name + " - " + issue.ToString());

                if (issue is AdvertiserDoesNotExist)
                {
                    var specificIssue = (AdvertiserDoesNotExist)issue;
                    var command = Locator.Get<ICommand<string, DirectAgents.SynchService.Model.EomDatabase.Advertiser>>("CreateAdvertiser");
                    command.Execute(specificIssue.AdvertiserName);
                }
                else if (issue is AccountManagerDoesNotExist)
                {
                    var specificIssue = (AccountManagerDoesNotExist)issue;
                    var command = Locator.Get<ICommand<string, DirectAgents.SynchService.Model.EomDatabase.AccountManager>>("CreateAccountManager");
                    command.Execute(specificIssue.AccountManagerName);
                }
                else if (issue is AdManagerDoesNotExist)
                {
                    var specificIssue = (AdManagerDoesNotExist)issue;
                    var command = Locator.Get<ICommand<string, DirectAgents.SynchService.Model.EomDatabase.AdManager>>("CreateAdManager");
                    command.Execute(specificIssue.AdManagerName);
                }
                else if (issue is MediaBuyerDoesNotExist)
                {
                    var specificIssue = (MediaBuyerDoesNotExist)issue;
                    var command = Locator.Get<ICommand<string, DirectAgents.SynchService.Model.EomDatabase.MediaBuyer>>("CreateMediaBuyer");
                    command.Execute(specificIssue.MediaBuyerName);
                }
            }
        }
</code>```

Here's the code for FindNewCampaigns.  It adds issues as it finds them.  An Issue is supposed to be something that needs to happen before a new campaign is able to actually get created in a target store.

```<code>    public class FindNewCampaigns : Command<IEnumerable<Campaign>>
    {
        private IFactory<CakeEntities> cakeEntities;
        private IFactory<DADatabase> eomDatabase;

        public FindNewCampaigns(IFactory<CakeEntities> cakeEntities, IFactory<DADatabase> eomDatabase)
        {
            this.cakeEntities = cakeEntities;
            this.eomDatabase = eomDatabase;
        }

        public override IEnumerable<Campaign> Execute()
        {
            using (var eom = eomDatabase.Create())
            using (var cake = cakeEntities.Create())
            {
                // Get EOM campaigns
                var campaigns = eom.Campaigns.Select(c => c.pid).ToList();
                // Get Cake offers
                var offers = cake.CakeOffers.Select(c => c.Offer_Id).ToList();
                // Get Cake offers that don't match to EOM campaigns
                var newOffers = offers.Except(campaigns).ToList();
                // Get default values
                int accountManagerID = DefaultAccountManagerId(eom);
                int adManagerID = DefaultAdManagerId(eom);
                int advertiserID = DefaultAdvertiserID(eom);
                int campaignStatusID = DefaultCampaignStatus(eom);
                // Create new campaigns in memory
                var newCampaigns = (from offer in cake.CakeOffers
                                    where newOffers.Contains(offer.Offer_Id)
                                    select new
                                    {
                                        Offer = offer,
                                        Campaign = new Campaign {
                                            pid = offer.Offer_Id,
                                            campaign_name = offer.OfferName,
                                            campaign_status_id = campaignStatusID,
                                            account_manager_id = accountManagerID,
                                            ad_manager_id = adManagerID,
                                            advertiser_id = advertiserID,
                                        }
                                    }).ToList();
                // Set campaign status
                var campaignStatus = eom.CampaignStatus.ToDictionary(c => c.name, c => c.id);
                campaignStatus.Add("Private", campaignStatus["Active"]);
                campaignStatus.Add("Apply To Run", campaignStatus["Active"]);
                campaignStatus.Add("Inactive", campaignStatus["default"]);
                foreach (var item in newCampaigns)
                {
                    string statusName = item.Offer.StatusName;
                    if (campaignStatus.ContainsKey(statusName))
                    {
                        item.Campaign.campaign_status_id = campaignStatus[statusName];
                    }
                    else
                    {
                        AddIssue(new CampaignStatusDoesNotExist(statusName));
                    }
                }
                // Set advertiser
                var cakeAdvertisers = cake.CakeAdvertisers.ToDictionary(c => c.Advertiser_Id);
                foreach (var item in newCampaigns)
                {
                    int offerAdvertiserID = int.Parse(item.Offer.Advertiser_Id);
                    var offerAdvertiser = cake.CakeAdvertisers.FirstOrDefault(c => c.Advertiser_Id == offerAdvertiserID);
                    string offerAdvertiserName = offerAdvertiser.AdvertiserName;
                    var eomAdvertiser = eom.Advertisers.FirstOrDefault(c => c.name == offerAdvertiserName);
                    if (eomAdvertiser != null)
                    {
                        item.Campaign.advertiser_id = eomAdvertiser.id;
                    }
                    else
                    {
                        AddIssue(new AdvertiserDoesNotExist(offerAdvertiserName));
                    }
                }
                // Set account manager
                foreach (var item in newCampaigns)
                {
                    int offerAdvertiserID = int.Parse(item.Offer.Advertiser_Id);
                    var offerAdvertiser = cake.CakeAdvertisers.FirstOrDefault(c => c.Advertiser_Id == offerAdvertiserID);
                    string offerAccountManager = offerAdvertiser.AccountManagerName;
                    if (offerAccountManager != null)
                    {
                        AccountManager am = eom.AccountManagers.ToList().SingleOrDefault(c => c.NameIsEquivalentTo(offerAccountManager));
                        if (am != null)
                        {
                            item.Campaign.account_manager_id = am.id;
                        }
                        else
                        {
                            AddIssue(new AccountManagerDoesNotExist(offerAccountManager));
                        }
                    }
                    else
                    {
                        AddIssue(new OfferHasNoAccountManager(item.Offer.OfferName));
                    }
                }
                // Set ad manager
                foreach (var item in newCampaigns)
                {
                    int offerAdvertiserID = int.Parse(item.Offer.Advertiser_Id);
                    var offerAdvertiser = cake.CakeAdvertisers.FirstOrDefault(c => c.Advertiser_Id == offerAdvertiserID);
                    string offerAdManager = offerAdvertiser.AdManagerName;
                    if (offerAdManager != null)
                    {
                        AdManager ad = eom.AdManagers.ToList().SingleOrDefault(c => c.NameIsEquivalentTo(offerAdManager));
                        if (ad != null)
                        {
                            item.Campaign.ad_manager_id = ad.id;
                        }
                        else
                        {
                            AddIssue(new AdManagerDoesNotExist(offerAdManager));
                        }
                    }
                    else
                    {
                        AddIssue(new OfferHasNoAdManager(item.Offer.OfferName));
                    }
                }
                return newCampaigns.Select(c => c.Campaign).ToList();
            }
        }
</code>```

答:
Not sure what answer your are looking for, but your code appears to implement a basic work item queue. I guess this would fall more under algorithm category. There's a lot of code out there that implements similar idea but I think it's too simple to declare "reusable". The overhead of having to manage this code might exceed its value of being used in multiple places.

The one problem with the code above (I guess this would fall under code review rather than programmers SE) is that it isn't very reusable/extensible as long as your FixIssues() method has a long if-else if-else if-else if-... else if-else chain.  It violates open-close principle of OOD because every time you add a new issue type, you have to go back and modify the same function over and over. I'd suggest you use a factory pattern and have an external class decide which command to instantiate for a given issue type.  You can use .NET's reflection to avoid having to build log if-else chains (or switch statements) and it will dynamically update whenever you add issue/command classes to your assembly, provided you assign them some unique custom attribute.

From clarity point of view, I would expect a method named "FindNewCampaigns" to do whatever work necessary to find the new campaigns and put them into some kind of collection. However, upon reading code details, that method appears to be fixing issues?? that doesn't seem to be same thing as "finding", so maybe a better name would be appropriate?


问:
Is it better to use a Database or a data structure for network stack?
I've built a multi threaded messaging application in C and I'm currently using a MySQL Memory table to save the session ID, but I'm not sure whether this was a good decision or not.

It works like this, the application sends a message and saves the source session ID in the MySQL table. When the application gets the success response it will remove the session's ID from the MySQL table, or if it received an error response then it will keep the ID to be retried later.

I've built it this way so that I don't need to care about building a data structure by myself, and the Database provides flexibility when it comes to querying it.

Do you think this is appropriate or do I need to use something else? Please note that the application is expecting to handle a large number of transactions/sec.

答: If the application is expecting to handle a large number of transactions and the only purpose of the code is processing the session ID, I would suggest you to use hash table. MySQL is so heavy in this situation. In addition, users should install MySQL first when they want to use your application, this will impair your application's user-friendly feature.</p>


问:
Build functionality around the design, or the other way around?
When you build an application, is it better to design the UI first (in Photoshop or whatever), then implement the functionality following the UI you just designed, or do the programming and build the design as you go?

Advantages I see using UI as reference:

the app will end up very UI-friendly :)

like pdr mentioned, if working for a client, he gets exactly what he imagined

Disadvantages:

the programming will get more complicated, so development time increases

any others? :D

答:
I'm a web UI dev and I actually think, unless it's a very basic throw-away one-off content site with a minimum of specialized behavior, that creating and approving a mockup with the intent to build an exact duplicate without having touched any of the underlying back-end/model-controller/data, or whatever concerns you're throwing under somewhat general term of "functionality" is the worst way to go.

There are three reasons for this.

It is all too easy for clients and just as easy for project managers and bosses and execs and yes, devs too, to get way over-invested in the UI and forget about the problems the app was supposed to solve in the first place.

Nobody is going to foresee all problems/challenges inherent in the general app scope right off the bat. When you have a very specific UI expectation set, you may be in for a lot of unnecessary work due to complications if you're dealing with inflexible corporate types who know more about dots on Is and crosses on Ts then they do actually solving problems when a simple non-UX-impacting change could have meant the difference between days and weeks.

You could be missing major opportunities to find a better way of doing things that simply don't avail themselves without something to actually get your hands on and play with. When do we decide what is good and bad UI or what might be better? When we're using apps, not when our noses are in Photoshop.

If you are in the blessed position of having some control over the dev process, do a bit of planning and then knock out that first prototype in its crudest most basic form possible ASAP. Sure comboBoxes are nice but a select box will do. Modals with ajaxed content are neat-o but reloading the page isn't going to kill anybody on the first run. Just get the problem solved first. THEN start fussing with the UI.

Read up on concepts like MVC. If you're familiar with the client-side separation of concerns on the web, the concept won't be that totally foreign to you. Then separate concerns as you see fit (but don't sweat dogmatic application of any pattern - that's missing the point). At the end of the day, UI should be nothing more than a mask that you fit onto an underlying app that already gives you a means of accessing the data and communication methods you need but when you start with the UI with no underlying plan or full understanding of the problem, it's easy to get concerns twisted. Get your data and communication problems solved first with basic, ugly UI. Then get fancy.


问:
What is the connection between literate programming and the semantic web?
I was (casually) researching semantic / ontology based approaches to technical documentation, when I stumbled upon this gem:

Literate Programming and the Semantic Web are ideas from different times, which do have a connection.

The linked paper, Literate Programming in XML by Norman Walsh, discusses XML technologies that are central to semantic web, however I fail to see the conceptual connection between literate programming and the semantic web or ontology based documentation. Help?

答:
Literate programming and the semantic web are both concerned with meaning.

The semantic web seeks to make the Internet more intelligent by adding what I call "conceptual metadata" (i.e. topical information) to web pages.  Pages so annotated become more than just randomly linked bits of text; they become conceptual frameworks of information (i.e. ontologies).

Literate programming seeks to develop software in programming languages that more closely models the thought process of humans, rather than the thought process of machines.  The "declarative over imperative" movement is part of this gestalt; rather than telling the machine how to do something, you tell it what you want done, and the machine figures out the how.


答:
It feels like a weak connection at best. The key to the semantic web is strict adherence to the idea that HTML's primary role is to describe and model content. By (almost) completely separating your behavior and presentation layers in different languages (JS, CSS), HTML acts like a springboard for the other two to act on, I suppose.

But in web dev, HTML is more the focal point where everything comes together, including back end technologies. Literate programming sounds more like a way of describing a wide variety of application concerns in XML (edit: or other declarative language) and then having compatible frameworks sort out the details of actually programming the app. They're almost diametrically opposed. One isolates a specific concern. The other establishes a plan for an entire app.

No offense, but I find the idea clumsy and horrifying.

Title: What is the connection between literate programming and the semantic web?

Body:
I was (casually) researching semantic / ontology based approaches to technical documentation, when I stumbled upon this gem:

Literate Programming and the Semantic Web are ideas from different times, which do have a connection.

The linked paper, Literate Programming in XML by Norman Walsh, discusses XML technologies that are central to semantic web, however I fail to see the conceptual connection between literate programming and the semantic web or ontology based documentation. Help?


问:
Source control workflow for managing a software platform
I'm in charge of a software platform, written in C, that is used to provide a variety of projects to clients.  I am trying to improve the workflow for people using this platform, and looking at whether source code control (Mercurial being the most likely candidate) can help.

The platform is only used internally for ~10 projects / year.  It's got a wide range of functionality, and lots of bits that are unused on most projects.  As a result, there are plenty of bugs hidden away.

I'm wondering if anyone has similar experience, either managing or using a constantly updated platform in this way.

The current situation

Platform development is done with a mercurial repository, but the releases of the platform are not done through mercurial.  For a release, the platform files are put into a tarball on a central server.  For any system connected to the core, the start of the build process copies the updated tarball and unpacks it into the application source code.  Application programmers can't edit the core files (various commands are aliased through shell scripts, and they get an error if they try).

What I'm after

It seems like it should be possible to somehow use Mercurial to manage this.  We could easily maintain a release branch of the platform, and have projects clone the release branch as their starting points.

But I'm not sure where it would go after that.  On a project, the functionality is completely up to the client.  If the core files are unlocked, people will immediately start editing them, even when there is a better way (this is what happened before the lockdown).  This is going to mean merging in new core changes becomes difficult, and I suspect will result in a lot of teams not bothering.

The draconian solution of locking the core files, and forcing automatic updates to all projects was really quite successful: we get more complaints and problems from the projects that are disconnected, than the ones receiving the forced updates.  However, as soon as projects go into testing, they have to be disconnected.  After that, short of manual merging, they get no more platform updates.

答:
You could try git

Linux kernel project is using it, github is using it, ... is using it.

For the core files that application programmers cannot edit, you could use:

```<code>git update-index --assume-unchanged file\\*
</code>```

When these flags are specified, the object names recorded for the paths are not updated. Instead, these options set and unset the "assume unchanged" bit for the paths. When the "assume unchanged" bit is on, git stops checking the working tree files for possible modifications, so you need to manually unset the bit to tell git when you change the working tree file. This is sometimes helpful when working with a big project on a filesystem that has very slow lstat(2) system call (e.g. cifs).

This option can be also used as a coarse file-level mechanism to ignore uncommitted changes in tracked files (akin to what .gitignore does for untracked files). You should remember that an explicit git add operation will still cause the file to be refreshed from the working tree. Git will fail (gracefully) in case it needs to modify this file in the index e.g. when merging in a commit; thus, in case the assumed-untracked file is changed upstream, you will need to handle the situation manually.

Body:
You could try git

Linux kernel project is using it, github is using it, ... is using it.

For the core files that application programmers cannot edit, you could use:

git update-index --assume-unchanged file\\*

When these flags are specified, the object names recorded for the paths are not updated. Instead, these options set and unset the "assume unchanged" bit for the paths. When the "assume unchanged" bit is on, git stops checking the working tree files for possible modifications, so you need to manually unset the bit to tell git when you change the working tree file. This is sometimes helpful when working with a big project on a filesystem that has very slow lstat(2) system call (e.g. cifs).

This option can be also used as a coarse file-level mechanism to ignore uncommitted changes in tracked files (akin to what .gitignore does for untracked files). You should remember that an explicit git add operation will still cause the file to be refreshed from the working tree. Git will fail (gracefully) in case it needs to modify this file in the index e.g. when merging in a commit; thus, in case the assumed-untracked file is changed upstream, you will need to handle the situation manually.


问:
I have one afternoon to extol the benefits of .NET over VB6... what do I say?
My company is a small twenty-man engineering firm. All the application programming here is done in VB6 by two people, who have taught themselves VB6 from an assembly background while working here for the past 25+ years, and myself.

As a result, the VB6 code is riddled with horrendous code smells, like tons of stringly typed variables, terribly long functions, hundreds of public global variables (some of which are preferred over passing around arguments and returning values,) and not a single object class. Refactoring is nigh impossible, and any changes require too much digging through code, and once made, always seem to introduce more holes.

My boss is realizing that VB6 is a dead technology, and is willing to listen to my pleas of moving to .NET for new development. We are moving forward to .NET, but he sees it as a way to keep up compatability with the newer Windows OS's, not as a way to write better code.

How can I best explain the benefits of .NET language over VB6, beyond mere up-to-date-ness? What can I say to best emphasize that the move to .NET is a good move but also that it means our current programming paradigm should also begin to change? As soon as my boss hears that Visual Basic .NET looks just like VB6, I know that his first instinct will be to simply convert our old code mess to .NET.

I understand that it will be impossible to change anyone's mindset in a single afternoon, but how can I at least convince my assembly-toting boss that things like strongly-typed variables, custom classes, and private fields aren't a total waste of time and energy?

答: Tell your bosses to write two want ads. One for C# developers. One for VB6 experts. Put 'em out there. Compare results.</p>


问:
Is it considered bad practice to run different JavaScript for IE
Is it considered bad practice (and how bad) to run different JavaScript for IE? Currently im writing some JavaScript and the simplist way to work arround IE quirks seems to be to check for browser version and run different code

```<code>var browserName = navigator.appName;

if (browserName == "Microsoft Internet Explorer") {
  //Do some stuff
}
else
{
//Do other stuff
}
</code>```

It's quick and works well but does lead to duplication of code and feels "hacky".

答:
Well, assuming you're actually interested in learning JavaScript, the best practice is this: Prefer testing by absence/existence of methods and write normalizing functions. So a totally lame example but it hits three principles:

```<code>if(!document.getElementsByClassName){
    document.getByClass = function(){ //look at all elements, check for class etc...
}
else { document.getByClass = document.getElementsByClassName }
</code>```

Don't browser sniff.

You might as well eliminate a little bit of the DOM cruft as you go. The DOM API's purpose is to be explicit, not to go easy on your carpal tunnel if you've failed to notice how freakishly flexible JS is. The barely-eliminates-any factor is what makes the example lame.

Cache to a new function. Don't do the method test every time it's called.

The advantage is that you can never 100% trust browser sniffing and you never know when some other library being linked to didn't actually add an equivalent method back in for you.

Whether you're just trying to get stuff done or want to learn more, I recommend JQuery. It does a bang-up job of eliminating DOM API cruft and maintaining a high level of cross-platform normalization but it's also something you can learn a fair bit from studying under the hood. More importantly, if you bother to continue actually learning core JS, it doesn't become useless like so many other JS frameworks and libraries and you'll continue to benefit from being able to de-soupify your JQuery junk with your mad OOP-ish skills.

Also, check out quirksmode.org to understand why Microsoft should be truly despised for all IEs prior to 9 on the JS front and a lot of nitty gritty details on exactly how much is wrong with their proprietary DOM API and suggestions for working around it.

Body:
Well, assuming you're actually interested in learning JavaScript, the best practice is this: Prefer testing by absence/existence of methods and write normalizing functions. So a totally lame example but it hits three principles:

if(!document.getElementsByClassName){
    document.getByClass = function(){ //look at all elements, check for class etc...
}
else { document.getByClass = document.getElementsByClassName }

Don't browser sniff.

You might as well eliminate a little bit of the DOM cruft as you go. The DOM API's purpose is to be explicit, not to go easy on your carpal tunnel if you've failed to notice how freakishly flexible JS is. The barely-eliminates-any factor is what makes the example lame.

Cache to a new function. Don't do the method test every time it's called.

The advantage is that you can never 100% trust browser sniffing and you never know when some other library being linked to didn't actually add an equivalent method back in for you.

Whether you're just trying to get stuff done or want to learn more, I recommend JQuery. It does a bang-up job of eliminating DOM API cruft and maintaining a high level of cross-platform normalization but it's also something you can learn a fair bit from studying under the hood. More importantly, if you bother to continue actually learning core JS, it doesn't become useless like so many other JS frameworks and libraries and you'll continue to benefit from being able to de-soupify your JQuery junk with your mad OOP-ish skills.

Also, check out quirksmode.org to understand why Microsoft should be truly despised for all IEs prior to 9 on the JS front and a lot of nitty gritty details on exactly how much is wrong with their proprietary DOM API and suggestions for working around it.


问:
Do DVCSes discourage continuous integration?
Say there is a team of ten agile developers. Every day they each pick a task from the board, commits several changes against it, until (by the end of the day) they have completed the task. All developers check in directly against trunk (Google-style, every commit is a release candidate, using feature toggles etc).

If they were using a centralized CVS like SVN, every time one of them commits, the build server will integrate and test their changes against the other nine developers' work. The build server will be pretty much running continuously all day.

But if they were using a DCVS like git, the developer may wait until they complete the task before pushing all their local commits together up to the central repository. Their changes will not be integrated until the end of the day.

In this scenario, the SVN team is continuously-integrating more frequently, and discovering integration problems much faster than the git team.

Does this mean DVCSs are less suitable for continuous teams than older centralized tools? How do you guys get around this deferred-push issue?

答:
Disclaimer: I work for Atlassian

DVCS does not discourage Continuous Integration as long as the developer pushes remotely on a regular basis to their own branch and the CI server is setup so that it builds the known active branches.

Traditionally there are two problems with DVCS and CI:

Uncertainty of integration state - unless the developer has been merging regularly from master and running the build, you don't know what the state of the combined changes are. If the developer has to do this manually, chances are it won't be done often enough to pick up problems early enough.

Duplication and drift of build configuration - if the build configuration has to be copied from a 'master' build to create a branch build, the configuration for the branch can quickly become out of sync with the build it was copied from.

In Bamboo, we introduced the ability for the build server to detect new branches as they are created by developers and automatically setup builds for the branch based off the build configuration for master (so if you change masters build config, it also changes the branches config to reflect the change).

We also have a feature called Merge Strategies that can be used to either update the branch with changes from master before the branch build runs or automatically push the changes in a successful build branch to master, ensuring changes between branches are tested together as soon as possible.

Anyhow, if your interested in learning more, see my blog post "Making Feature Branches effective with Continuous Integration"

ContentLicense: CC BY-SA 4.0


答:
Functionality is not the same as UI except for some very trivial applications.

Functions, such as:-

Keep a history of transactions.

Keep a sum of sales tax for reporting to VAT monsters.

Validate paypal payment.

Cross check paypal balance.

Find nearest FedEx Office from googleMaps

Cannot be expressed in a UI.

Furthermore a good UI is as much about the sequence an flow of events as it is about appearance and layout. Use Use Cases to capture the essence of the users interaction before you start in on designing any screens.

So you are on the right lines. But try to get a list of functions, and, a set of use cases before you start on the UI design. You will be surprised how much this approach can simplify your design.

Title: Build functionality around the design, or the other way around?

Body:
When you build an application, is it better to design the UI first (in Photoshop or whatever), then implement the functionality following the UI you just designed, or do the programming and build the design as you go?

Advantages I see using UI as reference:

the app will end up very UI-friendly :)

like pdr mentioned, if working for a client, he gets exactly what he imagined

Disadvantages:

the programming will get more complicated, so development time increases

any others? :D


答:
My experience is the exact opposite, teams using svn would not push for days, because the code they were working on would cause the trunk to not compile for everyone else without wasting time on manual merging. Then near the end of the sprint, everyone would commit, merging madness would take place, things would get over-written and lost and have to be recovered. The CI system would go RED and finger pointing would ensue.

Never had this problem with Git/Gitorious.

Git lets you pull and merge other peoples changes at your convenience, not because someone else checked something and you want to check in but you have 20 mins of manual merging to do.

Git also lets you pull everyone else's commits, merge your code in and then push a working version to everyone else so they don't have to guess at what they should have to merge based on what you changed.

Having something like Gitorious as a mediator for code reviews via merge requests makes managing many branches and many contributors very painless.

Setting up Jenkins/Hudson to track all the active branches in a Git repository is very easy as well. We got more traction with CI and more frequent feedback about the state of the repositories when we moved to Git from SVN.

Title: Do DVCSes discourage continuous integration?

Body:
Say there is a team of ten agile developers. Every day they each pick a task from the board, commits several changes against it, until (by the end of the day) they have completed the task. All developers check in directly against trunk (Google-style, every commit is a release candidate, using feature toggles etc).

If they were using a centralized CVS like SVN, every time one of them commits, the build server will integrate and test their changes against the other nine developers' work. The build server will be pretty much running continuously all day.

But if they were using a DCVS like git, the developer may wait until they complete the task before pushing all their local commits together up to the central repository. Their changes will not be integrated until the end of the day.

In this scenario, the SVN team is continuously-integrating more frequently, and discovering integration problems much faster than the git team.

Does this mean DVCSs are less suitable for continuous teams than older centralized tools? How do you guys get around this deferred-push issue?


答:
I recently observed on about 19 projects that used Mercurial over SubVersion (I was a subversion geek): developers started to become really individualists by working on their own branch and integrating only after serveral days or weeks. This caused serious integration troubles and concerns.

Another problem we faced is with the continuous integration server. We were notified of problems (failing test for instance), only when the sync of commits were made to the server.

It seems that Martin Fowler wrote about it on his site.

That said, some of the project I mention did a sync at least once a day reducing the problems. So to answer your question, I do think that DVCS may discourage continuous integration and increase individualism. However, DVCS is not the direct cause.

Developer is still in charge regardless the VCS they use.


问:
How can I apply OOP concepts to building a simple, but real-world, web app?
I've been trying now for a long time to wrap my head around OOP. I see its advantages. I've read many, many tutorials and watched an equal amount of videos on the subject. I get the animal/cat/dog examples, I get the car/drive examples. What I'm struggling with is how to apply these concepts in a real-world application. So, I've set out to build one using OOP.

I am not asking for help with syntax or writing specific code — I can find that myself in documentation and by searching forums etc.. What I really need is some guidance, and a push in the right direction every now and then. Are there any seasoned programmers willing to mentor me?

As my learning project I would like to build a simple classifieds "web app". Something similar to Craigslist but way watered down in terms of scope. I would like to use PHP5 and MySQL, because I am familiar with them.

Let's say there are only these 2 use cases:

Posting something for sale

Browsing/searching for something to buy

What "things" should be objects? I can imagine that each item could be an object, but at what point? And why?

So for example, the user fills out the "post item for sale" form, should that form get turned into an object which gets passed to another object which inserts the values into a database?

What about when another user is browsing and requests to see all items of category C? Does it make sense that whenever the app has to connect to its database it creates a database object and then gets a bunch of item objects and displays them on the page? …writing this out certainly makes me realize how clueless I still am about OOP. Please help me fix that.

If in your opinion this is not a good project to start wading into OOP with, please feel free to suggest another idea!

答:
As mentioned by Explosion Pills, in a complex application most of the objects are relating to application components (e.g. database connection pools, commands, data structures such as hashmaps) rather than real world entities (such as a boarding pass, invoice, or mp3 file). There are many good books on design patterns that show you ways that people have solved a lot of recurring problems in this area. The GOF book as it is known is thorough but very dry, Head First Design Patterns may be more accessible.

In terms of real world analysis and design. It is often helpful to think in terms of nouns and verbs. For example a video lending library (are these obsolete now?) may have these things/nouns:

Video

Borrower

In terms of verbs:

A Borrower can take out a video for a length of time

A Borrower can return a video to the store
etc.

These can then be turned into classes with operations (it's a long time since I've done any PHP so I'll avoid it):

```<code>class Borrower
{
  public void borrow(Video video, int daysToBorrow)
  {
     ...
  }

  public void returnVideo(Video video, boolean calculateFine)
  {
     ...
  }
}
</code>```

It all takes a LOT of practice and playing around. The best thing to do is get stuck in and learn from failed designs. In my opinion OO is something that you can continue to learn and develop over your lifetime (it is not easy and there are no perfect solutions to anything). Good design is often iterative, so expect to try out a few different ideas for your "Craig's List" webapp.

OwnerDisplayName: Bern

Body:
As mentioned by Explosion Pills, in a complex application most of the objects are relating to application components (e.g. database connection pools, commands, data structures such as hashmaps) rather than real world entities (such as a boarding pass, invoice, or mp3 file). There are many good books on design patterns that show you ways that people have solved a lot of recurring problems in this area. The GOF book as it is known is thorough but very dry, Head First Design Patterns may be more accessible.

In terms of real world analysis and design. It is often helpful to think in terms of nouns and verbs. For example a video lending library (are these obsolete now?) may have these things/nouns:

Video

Borrower

In terms of verbs:

A Borrower can take out a video for a length of time

A Borrower can return a video to the store
etc.

These can then be turned into classes with operations (it's a long time since I've done any PHP so I'll avoid it):

class Borrower
{
  public void borrow(Video video, int daysToBorrow)
  {
     ...
  }

  public void returnVideo(Video video, boolean calculateFine)
  {
     ...
  }
}

It all takes a LOT of practice and playing around. The best thing to do is get stuck in and learn from failed designs. In my opinion OO is something that you can continue to learn and develop over your lifetime (it is not easy and there are no perfect solutions to anything). Good design is often iterative, so expect to try out a few different ideas for your "Craig's List" webapp.


问:
What are the advantages of Ceylon over Java?
Looking for the recent and powerful upcoming programming languages over net, I came across Ceylon. I dropped in at ceylon-lang.org and it says:

Ceylon is deeply influenced by Java. You see, we're fans of Java, but we know its limitations inside out. Ceylon keeps the best bits of Java but improves things that in our experience are annoying, tedious, frustrating, difficult to understand, or bugprone.

What are the advantages of Ceylon over Java?

答:
Ceylon seems like a nice fun language but I'd argue it has relatively few "advantages" over Java.

I think it has a nicer syntax and some more "modern" language features - though this is subjective and I'd argue should be relatively minor factors in choosing a programming language.

Much more important factors when choosing a language / platform for a serious project:

Does it enable you to develop in a better paradigm for your given problem? (no - Ceylon is clearly yet another language in the over-crowded statically-typed Java-like OOP space. Contrast with e.g. Clojure which is targeting the functional language space or Groovy which is a very dynamic OOP JVM language so they are addressing different niches)

Has it got a better library ecosystem? (no chance.... Java is unmatched in this regard. At best you'd probably just end up using the Java libraries from Ceylon)

Can you get more skilled developers? (unlikely, few people are currently using Ceylon and even if they did there would be a big learning curve to climb)

Has it got better tools? (no - Java tooling is very comprehensive and mature)

Does it make you more productive? (debatable - it has some nice productive language features, but combined with learning curve and tooling effects it might actually end up behind)

Does it provide better performance? (no - the JVM is extremely well optimised for Java, it's a tough call for any other JVM language to beat it. Scala comes close, but that's after many years of fine-tuning...)

Does it support more target platforms? (no - it's a JVM language so exactly the same as Java)

Is the code going to be more maintainable? (probably not - Java has stood the test of time here precisely because it is relatively stable, mature and doesn't have a lot of advanced language features that might confuse future maintainers)

Is there a large, active and helpful community? (no, at least not compared to Java or the other big JVM languages like Scala, Clojure, Groovy etc.)

Overall I'd certainly encourage people to experiment with Ceylon and have fun with it from a learning perspective.

But I don't currently see any compelling advantages that would make large numbers of people want to switch to it (or choose it ahead of other JVM languages like Clojure, Scala, JRuby or Groovy).


问:
Business trying to make technical decisions
We've often run across scenarios where the business will promise a client a new feature.  The business will promise that the feature be implemented in a specific way.  These technical details promised by the business are usually poor.  Unfortunately, client is now set and want this feature to be implemented in the way described by the business.

In the end, the business just wants this feature to be completed without regard to quality and maintainability.  Is there a good way to push back?  How can we explain to the business that providing technical details before the requirements have been gathered is a bad idea?

答:
That's an organizational issue.  If the higher-ups don't understand this, there's not much you can do.  Try to explain the issue to your non-technical bosses, but don't be surprised when you get nowhere.

It's is a common problem for developers working in non-development companies that, for whatever reason, sell software.

It's not a pleasant tactic, but you can just bludgeon them with evidence.  At the start of a project, write down exactly why it's going to fail (because technical details were poor) and email it to relevant people.  Keep emailing them throughout, and when the project eventually ends up a disaster with pissed off customers, cite those emails you sent at every opportunity.  It may generate some ill will, but there's really no good way to try to fix a systemic issue like that.

ContentLicense: CC BY-SA 2.5


问:
Are there any situations where having a "data model" in which all your entities are instances of a Map<String, Object>
Are there any situations where having a "data model" in which all of the entities are instances of a Map<String, Object> would make any sense?

How do you explain to someone why having such a "data model" is not such a good idea? It seems like it's an absurd approach to me, could I be missing something?

答: If you're mapping Maps then sure.  But generally you want to ask what is it a Map of that you're modelling?  A Map of Cats?  a Map of Nodes? etc.</p>


答: It isn't necessarily a bad idea to have a data model that's a map of key strings to values. However it often is a good idea to abstract that behind something domain specific, both to give some meaning to the strings and objects and to offer somewhere to impose any constraints that aren't evident from the underlying data structures.

Title: Are there any situations where having a "data model" in which all your entities are instances of a Map<String, Object>

Body:
Are there any situations where having a "data model" in which all of the entities are instances of a Map<String, Object> would make any sense?

How do you explain to someone why having such a "data model" is not such a good idea? It seems like it's an absurd approach to me, could I be missing something?


问:
Testing for object equality by comparing the toString() representations of objects
Following on from this question - how do you explain to someone that this is just crazy!:

```<code>boolean someMethod(Map<String, Object> context) {
    Object object = context.get("someProperty")
    Object another = context.get("anotherProperty")

    return object.toString().equals(another.toString());
}
</code>```

Apparently the reason for why Object.equals(...) is not used is that "what's contained in the Map is not concretely known, but is definitely known to be one of the primitive wrappers i.e. String, Double, Boolean, etc... and that Boolean.TRUE is required to be equal(...) to the String "TRUE"".

答:
It's just crazy, because it can go wrong, because string representations are not canonical:</p>

```<code>Double zeroDouble = new Double(0);
Integer zeroInteger = new Integer(0);
zeroDouble.doubleValue() == zeroInteger.doubleValue(); // true
zeroDouble.toString().equals(zeroInteger.toString());  // false ("0.0" vs "0")

File file1 = new File("file.txt");
File file2 = new File("FILE.TXT");
file1.equals(file2);            // true in windows, false in unix
file1.toString().equals(file2); // false ("file.txt" vs. "FILE.TXT")
</code>```

Body:
It's just crazy, because it can go wrong, because string representations are not canonical:

Double zeroDouble = new Double(0);
Integer zeroInteger = new Integer(0);
zeroDouble.doubleValue() == zeroInteger.doubleValue(); // true
zeroDouble.toString().equals(zeroInteger.toString());  // false ("0.0" vs "0")

File file1 = new File("file.txt");
File file2 = new File("FILE.TXT");
file1.equals(file2);            // true in windows, false in unix
file1.toString().equals(file2); // false ("file.txt" vs. "FILE.TXT")


问:
How can this deterministic linear time selection algorithm be linear?
I'm trying to understand the basic concepts of algorithms through the classes offered at Coursera (in bits and pieces), I came across the deterministic linear time selection algorithm that works as follows:

Select(A,n,i)

If n = 1 return A[1].

p = ChoosePivot(A, n)

B = Partition(A, n, p)

Suppose p is the jth element of B (i.e., the jth order statistic of A). Let the “ﬁrst part of B” denote
its ﬁrst j − 1 elements and the “second part” its last n − j elements.

If i = j, return p.

If i < j, return Select(1st part of B, j − 1, i).

Else return Select(2nd part of B, n − j, i − j).

And sorts the array internally in the ChoosePivot subroutine to calculate the median of median using a comparison based sorting algorithm. But isnt the lower bound on comparison based sorting O(nlogn)? So how would it be possible for us to acheive O(n) for the entire algorithm then?
Am I missing something here?

答:
And sorts the array internally in the ChoosePivot subroutine to calculate the median of median using a comparison based sorting algorithm.

This is the incorrect premise (you are right that if we did do a comparison-based sort, we couldn't be linear). The point of median-of-medians is that it is linear - you don't need to sort the whole set if all you want is the median. See proof of O(n) running time on wikipedia for more detail.


答:
I think you will find such kind of algorithms when you google for keywords like event dispatching or  event queue. Lots of event driven systems have such a loop at its core.

Only difference to your case is that typically in such systems new events can also come "from outside" in an asynchronous manner.

Title: Is this an example of a pattern or an algorithm?

Body:
I feel like I have a reusable "something" here and I'm not sure whether to think of it as a pattern or an algorithm (or neither).

It's characterized by having an unknown amount of work to accomplish a task because the subtasks can encounter various conditions which cause them to add "Issues" to a global queue.

Then, the command is run repeatedly coupled with a round of "Issue Fixing" until either there are no issues left or the number of issues does not change.

I'm just putting enough code here to show what I'm talking about - there's a bit more to it (let me know if I should post more).

```<code>        public void FindNewCampaigns()
        {
            var findNewCampaigns = Locator.Get<ICommand<IEnumerable<Campaign>>>("FindNewCampaigns");
            var campaigns = findNewCampaigns.Execute();
            var issues = Locator.Get<ICollection<Issue>>("CommandIssues");
            while (issues.Count > 0)
            {
                int before = issues.Count;
                FixIssues(issues);
                issues.Clear();
                campaigns = findNewCampaigns.Execute();
                int after = issues.Count;
                if (before == after)
                {
                    System.Console.WriteLine("No issues got fixed, quitting ({0}/{1}).", before, after);
                    break;
                }
            }
            if (issues.Count == 0)
            {
                CreateCampaigns(campaigns);
            }
        }

        private void FixIssues(ICollection<Issues.Issue> issues)
        {
            foreach (var issue in issues)
            {
                System.Console.WriteLine("ISSUE: " + issue.GetType().Name + " - " + issue.ToString());

                if (issue is AdvertiserDoesNotExist)
                {
                    var specificIssue = (AdvertiserDoesNotExist)issue;
                    var command = Locator.Get<ICommand<string, DirectAgents.SynchService.Model.EomDatabase.Advertiser>>("CreateAdvertiser");
                    command.Execute(specificIssue.AdvertiserName);
                }
                else if (issue is AccountManagerDoesNotExist)
                {
                    var specificIssue = (AccountManagerDoesNotExist)issue;
                    var command = Locator.Get<ICommand<string, DirectAgents.SynchService.Model.EomDatabase.AccountManager>>("CreateAccountManager");
                    command.Execute(specificIssue.AccountManagerName);
                }
                else if (issue is AdManagerDoesNotExist)
                {
                    var specificIssue = (AdManagerDoesNotExist)issue;
                    var command = Locator.Get<ICommand<string, DirectAgents.SynchService.Model.EomDatabase.AdManager>>("CreateAdManager");
                    command.Execute(specificIssue.AdManagerName);
                }
                else if (issue is MediaBuyerDoesNotExist)
                {
                    var specificIssue = (MediaBuyerDoesNotExist)issue;
                    var command = Locator.Get<ICommand<string, DirectAgents.SynchService.Model.EomDatabase.MediaBuyer>>("CreateMediaBuyer");
                    command.Execute(specificIssue.MediaBuyerName);
                }
            }
        }
</code>```

Here's the code for FindNewCampaigns.  It adds issues as it finds them.  An Issue is supposed to be something that needs to happen before a new campaign is able to actually get created in a target store.

```<code>    public class FindNewCampaigns : Command<IEnumerable<Campaign>>
    {
        private IFactory<CakeEntities> cakeEntities;
        private IFactory<DADatabase> eomDatabase;

        public FindNewCampaigns(IFactory<CakeEntities> cakeEntities, IFactory<DADatabase> eomDatabase)
        {
            this.cakeEntities = cakeEntities;
            this.eomDatabase = eomDatabase;
        }

        public override IEnumerable<Campaign> Execute()
        {
            using (var eom = eomDatabase.Create())
            using (var cake = cakeEntities.Create())
            {
                // Get EOM campaigns
                var campaigns = eom.Campaigns.Select(c => c.pid).ToList();
                // Get Cake offers
                var offers = cake.CakeOffers.Select(c => c.Offer_Id).ToList();
                // Get Cake offers that don't match to EOM campaigns
                var newOffers = offers.Except(campaigns).ToList();
                // Get default values
                int accountManagerID = DefaultAccountManagerId(eom);
                int adManagerID = DefaultAdManagerId(eom);
                int advertiserID = DefaultAdvertiserID(eom);
                int campaignStatusID = DefaultCampaignStatus(eom);
                // Create new campaigns in memory
                var newCampaigns = (from offer in cake.CakeOffers
                                    where newOffers.Contains(offer.Offer_Id)
                                    select new
                                    {
                                        Offer = offer,
                                        Campaign = new Campaign {
                                            pid = offer.Offer_Id,
                                            campaign_name = offer.OfferName,
                                            campaign_status_id = campaignStatusID,
                                            account_manager_id = accountManagerID,
                                            ad_manager_id = adManagerID,
                                            advertiser_id = advertiserID,
                                        }
                                    }).ToList();
                // Set campaign status
                var campaignStatus = eom.CampaignStatus.ToDictionary(c => c.name, c => c.id);
                campaignStatus.Add("Private", campaignStatus["Active"]);
                campaignStatus.Add("Apply To Run", campaignStatus["Active"]);
                campaignStatus.Add("Inactive", campaignStatus["default"]);
                foreach (var item in newCampaigns)
                {
                    string statusName = item.Offer.StatusName;
                    if (campaignStatus.ContainsKey(statusName))
                    {
                        item.Campaign.campaign_status_id = campaignStatus[statusName];
                    }
                    else
                    {
                        AddIssue(new CampaignStatusDoesNotExist(statusName));
                    }
                }
                // Set advertiser
                var cakeAdvertisers = cake.CakeAdvertisers.ToDictionary(c => c.Advertiser_Id);
                foreach (var item in newCampaigns)
                {
                    int offerAdvertiserID = int.Parse(item.Offer.Advertiser_Id);
                    var offerAdvertiser = cake.CakeAdvertisers.FirstOrDefault(c => c.Advertiser_Id == offerAdvertiserID);
                    string offerAdvertiserName = offerAdvertiser.AdvertiserName;
                    var eomAdvertiser = eom.Advertisers.FirstOrDefault(c => c.name == offerAdvertiserName);
                    if (eomAdvertiser != null)
                    {
                        item.Campaign.advertiser_id = eomAdvertiser.id;
                    }
                    else
                    {
                        AddIssue(new AdvertiserDoesNotExist(offerAdvertiserName));
                    }
                }
                // Set account manager
                foreach (var item in newCampaigns)
                {
                    int offerAdvertiserID = int.Parse(item.Offer.Advertiser_Id);
                    var offerAdvertiser = cake.CakeAdvertisers.FirstOrDefault(c => c.Advertiser_Id == offerAdvertiserID);
                    string offerAccountManager = offerAdvertiser.AccountManagerName;
                    if (offerAccountManager != null)
                    {
                        AccountManager am = eom.AccountManagers.ToList().SingleOrDefault(c => c.NameIsEquivalentTo(offerAccountManager));
                        if (am != null)
                        {
                            item.Campaign.account_manager_id = am.id;
                        }
                        else
                        {
                            AddIssue(new AccountManagerDoesNotExist(offerAccountManager));
                        }
                    }
                    else
                    {
                        AddIssue(new OfferHasNoAccountManager(item.Offer.OfferName));
                    }
                }
                // Set ad manager
                foreach (var item in newCampaigns)
                {
                    int offerAdvertiserID = int.Parse(item.Offer.Advertiser_Id);
                    var offerAdvertiser = cake.CakeAdvertisers.FirstOrDefault(c => c.Advertiser_Id == offerAdvertiserID);
                    string offerAdManager = offerAdvertiser.AdManagerName;
                    if (offerAdManager != null)
                    {
                        AdManager ad = eom.AdManagers.ToList().SingleOrDefault(c => c.NameIsEquivalentTo(offerAdManager));
                        if (ad != null)
                        {
                            item.Campaign.ad_manager_id = ad.id;
                        }
                        else
                        {
                            AddIssue(new AdManagerDoesNotExist(offerAdManager));
                        }
                    }
                    else
                    {
                        AddIssue(new OfferHasNoAdManager(item.Offer.OfferName));
                    }
                }
                return newCampaigns.Select(c => c.Campaign).ToList();
            }
        }
</code>```


问:
How do I improve my coding skills?
Here's a bit information about me, before starting with the question.

I am a Computer Science Undergraduate, Java being my primary coding language.

The basic problem in my University are the teaching standards. No one is concerned about teaching coding knowledge to students, rather than just theoretical knowledge.

The effect being, most of my fellow college mates don't understand programming at all.

Even I haven't been able to come out of the traditional programming environment, which limits my coding to an extent.

What are the possible ways by which I can develop and expand my programming/coding skills.

Also, can you suggest the sources for the same?

Edited:
Sources suggesting development of coding skills.

答:
Jump in the water, it might be cold at first and you'll be tempted to get out but soon your body will get used to it and become warm again and as you become comfortable in the water you can then swim around maybe go into the deep end.

I just finished college a couple of months ago where i studied Java. Same as you i didnt have a clue on how to code properly. About a month ago i wanted to build a web app in PHP. I didn't know what i was doing but just went for it. It was intimidating and overwhelming at first but as you practice it becomes natural. I even wrote the application many times, every time simplifying it even more. Now im working on the app from scratch but this time im figuring out how to do it objected oriented and using PEAR and its module quickform which is another hurdle i've to get through but determined and excited nonetheless.

So practice. Jump in the water! Best of luck :)

Title: How do I improve my coding skills?


答:
It's wrong because there is no contract (not even an informal expectation!) for toString() that guarantees that any subclass of Object will define it in a way compatible with an equivalence relationship (read the javadoc for Object.equals() to see what I mean).

It may work for a class where you know that toString() is compatible with equals, but this is not the case for the values in Map<String, Object>!

For an obvious example where almost certainly the method doesn't do what you would expect, imagine a subclass of Object that does not override toString(). In that case, the String representation of your instance is a function of the class name and the object's hashCode. Almost certainly not what you want to use to test for equality.

Title: Testing for object equality by comparing the toString() representations of objects

Body:
Following on from this question - how do you explain to someone that this is just crazy!:

```<code>boolean someMethod(Map<String, Object> context) {
    Object object = context.get("someProperty")
    Object another = context.get("anotherProperty")

    return object.toString().equals(another.toString());
}
</code>```

Apparently the reason for why Object.equals(...) is not used is that "what's contained in the Map is not concretely known, but is definitely known to be one of the primitive wrappers i.e. String, Double, Boolean, etc... and that Boolean.TRUE is required to be equal(...) to the String "TRUE"".


问:
Should I still make my site work in non-javascript capable browsers?
Apparently less than 1% had javascript off in 2010:
http://developer.yahoo.com/blogs/ydn/posts/2010/10/how-many-users-have-javascript-disabled/

So is it worth it to still support browsing without javascript?

For example:

Form submissions. Normally I would set up click or change events on form elements and just update the current page HTML from the response.
But if the user has js disabled, the form cannot be submitted, and it won't work.

If I have to take into consideration that the user has JS off, then I need to wrap my input elements within <FORM>, add a submit button and add additional mark-up on the current page to handle the form submission results...
Anyway there's a lot of extra work to do in this case.

Another example - replacing generic form elements with DIVS that you style to look like cooler input elements, and make them behave like generic inputs trough JS. Again, users without js won't be able to do anything with them.

Or a different example, the UI created by JS on page load.
Besides the fact that non-js browser won't display the UI, there's also a small problem with JS-capable browsers which will show a ugly UI until the page is full loaded and the JS gets to be executed.

Are these drawbacks important enough to take into consideration, when less than 1% of your visitors are affected by them?

答:
First of all; I'd put some question marks on that 1% figure. How did they measure this in the first place? Most usage statistics are collected client-side, using (drum roll) javascript. Disabling javascript completely means you're not counting those users. Furthermore, most of the script-aware users use things like NoScript, which is far more sophisticated than a simple "turn all javascript off"; instead, there's a whitelist, a blacklist, and a per-case decision for the gray area. I use NoScript myself, and more often than not, I only allow those scripts on a site that it needs to function, while Analytics and other tracking sites are tossed on the blacklist. So I probably count as "javascript enabled", even though I default to "javascript off", and serving me something that looks broken until I enable Javascript makes a bad impression - enough to make me close the page within a second unless I know it has what I need.

But let's assume the 1% figure is accurate. The fact that some users browse scriptlessly isn't your biggest concern. You should also consider the following:

Accessibility. While you can write accessible javascript, it is very hard to get it right, and you need to test on a wide array of user agents and configurations. If, however, your site is written in clear semantic HTML and functions well without Javascript enabled, it is typically easy to get accessibility right.

SEO. Most search engine spiders don't execute Javascript, and if they do, they don't typically go all the way. So basically all content that you generate or pull in using Javascript is invisible to search engines.

Integration with third-party tools. One of the great things about HTML is that it is a well-defined, standardized textual data format. Thousands of tools can process it to perform all sorts of tasks, and the ability to transform and accumulate your content adds value to your site. If you rely on javascript to display it, most of these tools will break.

Security. While Javascript is not inherently insecure, moving application logic to the client has important security consequences, and it's easy to overlook issues.

Mobile devices. Not all smartphones have the processing power to run your javascript as smoothly as you'd need it; many mobile browsers don't even support the full feature set of a desktop browser's javascript engine; and the very nature of the device (small screen, limited input devices, touch screen rather than a mouse) may break quite a few javascript / DOM features you might take for granted.


答:
Idea you base your reasoning on is very shaky, softly speaking. It is the matter of team / management / process that developer may wait until they complete the task.

Doing it one way or another, "wait" or "hurry", shared trunk or isolated branch, is known as branching strategy, and if you study information available online, you'll find out that choosing particular strategy has basically nothing to do with VCS being centralized or distributed.

Say, for distributed VCS like Mercurial, you can easily find strong recommendation for frequent merges:

First, merge often! This makes merging easier for everyone and you find out about conflicts (which are often rooted in incompatible design decisions) earlier...

Studying recommendations like above, one can easily find out that these appeal to considerations having nothing to do with Mercurial being distributed.

Now, let's look at the situation at side of centralized VSC, Subversion. Studying online information, one can find among top popular strategies so called stable trunk and unstable trunk - each having opposite impact on frequency of merges. You see, people choose one or other way of doing things without even paying attention to VCS being centralized.

I've seen severely delayed merges happening (even encouraged by lame management) with centralized VCS, as well as frequent merges done with DVCS when team/management just thought that it's the right way. I've seen that nobody cares if VCS is distributed or centralized at deciding one way or another.

Given above, it looks like the right answer to Do DVCSes discourage continuous integration? would be Mu.

VCS being distributed or not does not have a substantial impact on that.


问:
Experiments correlating code metrics to bug density
I'm wondering if someone has done some experiments correlating code metrics (SLOC, Cyclomatic Complexity, etc) with bug density in Object Oriented applications.

I'm not looking for experiments that only prove or disprove a correlation, but on both. I'm not trying to find a silver bullet as I believe that the bug density of a project might correlate to one or more metrics for a given project or team and the correlation can change during the lifetime of the project / team.

My goal is to

Measure all interesting metrics for 2-3 months (we already have quite a few from sonar).

Find one metric that correlates with the number of new bugs.

Do a root-cause analysis to check why this happens (e.g. Do we lack a certain design skill?).

Improve the skill and measure change for a couple of itereations.

Rinse and repeat from 2.

If you don't have any experience on this, but remember seeing a paper / blog on this subject, I would appreciate if you can share it.

So far I've found the following links with some information about this subject

Do Bugs Reside in Complex Code? - just the slides from a presentation.

Changes and Bugs: Mining and Predicting Development Activities - Just slides frmm a presentation. Bottom line the more dependencies, the higher the chances of bugs (I think this is quite a general rule).

Failure is a four-letter word - A parady about the correlation between bugs and metrics.

答:
Whenever I hear of attempts to associate some type of code-based metric with software defects, the first thing that I think of is McCabe's cyclomatic complexity. Various studies have found that there is a correlation between a high cyclomatic complexity and number of defects. However, other studies that looked at modules with a similar size (in terms of lines of code) found that there might not be a correlation.

To me, both number of lines in a module and cyclomatic complexity might serve as good indicators of possible defects, or perhaps a greater likelihood that defects will be injected if modifications are made to a module. A module (especially at the class or method level) with high cyclomatic complexity is harder to understand since there are a large number of independent paths through the code. A module (again, especially at the class or method level) with a large number of lines is also hard to understand since the increase in lines means more things are happening. There are many static analysis tools that support computing both source lines of code against specified rules and cyclomatic complexity, it seems like capturing them would be grabbing the low hanging fruit.

The Halstead complexity measures might also be interesting. Unfortunately, their validity appears to be somewhat debated, so I wouldn't necessary rely on them. One of Halstead's measures is an estimate of defects based on effort or volume (a relationship between program length in terms of total operators and operands and program vocabulary in terms of distinct operators and operators).

There is also a group of metrics known as the CK Metrics. The first definition of this metrics suite appears to be in a paper titled A Metrics Suite for Object Oriented Design by Chidamber and Kemerer. They define Weighted Methods Per Class, Depth of Inheritance Tree, Number of Children, Coupling Between Object Classes, Response for a Class, and Lack of Cohesion in Methods. Their paper provides the computational methods as well as a description of how to analyze each one.

In terms of academic literature that analyze these metrics, you might be interested in Empirical Analysis of CK Metrics for Object-Oriented Design Complexity: Implications for Software Defects, authored by Ramanath Subramanyam and M.S. Krishna. They analyzed three of the six CK metrics (weighted methods per class, coupling between object classed, and depth of inheritance tree). Glancing through the paper, it appears that they found these are potentially valid metrics, but must be interpreted with caution as "improving" one could lead to other changes that also lead to a greater probability of defects.

Empirical Analysis of Object-Oriented Design Metrics for Predicting High and Low Severity Faults, authored by Yuming Zhou and Hareton Leung, also examine the CK metrics. Their approach was to determine if they can predict defects based on these metrics. They found that many of the CK metrics, except for depth of inheritance tree and number of children) had some level of statistical significance in predicting areas where defects could be located.

If you have an IEEE membership, I would recommend searching in the IEEE Transactions on Software Engineering for more academic publications and IEEE Software for some more real-world and applied reports. The ACM might also have relevant publications in their digital library.


答:
Both concepts appear to target the point where human reading meets computer execution.

In literate programming, human readable part is represented by the idea of writing programs like in an ordinary human language, much like the text of an essay. Respective part in semantic web is that it targets human-readable web pages.

Computer execution aspect in literate programming is that, unlike the classic text, it is targeted also at computer execution. Respective part in semantic web is represented by the notion of data that can be processed directly and indirectly by machines

The connection looks quite profound, like approaching the same target, only from different angles.

 The guy who groked this seems pretty smart. Connection looks clear to me now that it was laid out right before my nose but I'll be damned if I've seen that connection before. Another striking point about this observation is that it helped me better understand both concepts (have to admit I had trouble with that before).

references

Literate programming - Wikipedia article

The literate programming paradigm, as conceived by Knuth, represents a move away from writing programs in the manner and order imposed by the computer, and instead enables programmers to develop programs in the order demanded by the logic and flow of their thoughts. Literate programs are written as an uninterrupted exposition of logic in an ordinary human language, much like the text of an essay, in which macros which hide abstractions and traditional source code are included.

  ...

  Literate programming tools are used to obtain two representations from a literate source file: one suitable for further compilation or execution by a computer, the "tangled" code, and another for viewing as formatted documentation, which is said to be "woven" from the literate source.[3] While the first generation of literate programming tools were computer language-specific, the later ones are language-agnostic and exist above the programming languages.

Semantic Web - Wikipedia article

Semantic Network Model... a form to represent semantically structured knowledge. It extends the network of hyperlinked human-readable web pages by inserting machine-readable metadata about pages and how they are related to each other, enabling automated agents to access the Web more intelligently and perform tasks on behalf of users.

  ...

  Tim Berners-Lee... oversees the development of proposed Semantic Web standards. He defines the Semantic Web as "a web of data that can be processed directly and indirectly by machines."


答:
tdammers hits a number of key issues.  Here are a few more.

Who is in that 1% of non-users?  Given that JS is enabled by default, they went in and turned it off on purpose.  That implies a degree of technology knowledge and sophistication.  Quite possibly, those are the alphas (early adopters) and near-alphas that you need to adopt your site for it to grow.

How many mobile browsers have JS enabled or will continue to do so?  Ignoring that demographic can also be very perilous to your site's health.

Finally, question those numbers and question them hard.  They found that 2% of US users in 2010 who visited Yahoo had JS disabled.  What about the people who NEVER visit Yahoo?  What security vulnerabilities have been found between now and then?  The answer to those two questions can dramatically shift the number of people you're excluding by requiring JS to be enabled.

You need to know who your target audience is and what their behavioral patterns are.  Relying on Yahoo statistics for this decision is a bit dodgy.

Title: Should I still make my site work in non-javascript capable browsers?

Body:
Apparently less than 1% had javascript off in 2010:
http://developer.yahoo.com/blogs/ydn/posts/2010/10/how-many-users-have-javascript-disabled/

So is it worth it to still support browsing without javascript?

For example:

Form submissions. Normally I would set up click or change events on form elements and just update the current page HTML from the response.
But if the user has js disabled, the form cannot be submitted, and it won't work.

If I have to take into consideration that the user has JS off, then I need to wrap my input elements within <FORM>, add a submit button and add additional mark-up on the current page to handle the form submission results...
Anyway there's a lot of extra work to do in this case.

Another example - replacing generic form elements with DIVS that you style to look like cooler input elements, and make them behave like generic inputs trough JS. Again, users without js won't be able to do anything with them.

Or a different example, the UI created by JS on page load.
Besides the fact that non-js browser won't display the UI, there's also a small problem with JS-capable browsers which will show a ugly UI until the page is full loaded and the JS gets to be executed.

Are these drawbacks important enough to take into consideration, when less than 1% of your visitors are affected by them?


问:
What popular "best practices" are not always best, and why?
"Best practices" are everywhere in our industry.  A Google search on "coding best practices" turns up nearly 1.5 million results.  The idea seems to bring comfort to many; just follow the instructions, and everything will turn out fine.

When I read about a best practice - for example, I just read through several in Clean Code recently - I get nervous.  Does this mean that I should always use this practice?  Are there conditions attached?  Are there situations where it might not be a good practice?  How can I know for sure until I've learned more about the problem?

Several of the practices mentioned in Clean Code did not sit right with me, but I'm honestly not sure if that's because they're potentially bad, or if that's just my personal bias talking.  I do know that many prominent people in the tech industry seem to think that there are no best practices, so at least my nagging doubts place me in good company.

The number of best practices I've read about are simply too numerous to list here or ask individual questions about, so I would like to phrase this as a general question:

Which coding practices that are popularly labeled as "best practices" can be sub-optimal or even harmful under certain circumstances?  What are those circumstances and why do they make the practice a poor one?

I would prefer to hear about specific examples and experiences.

答:
Over generalization.

The square block does NOT fit into the circle hole!


答:
The answer is both yes, and no.

The difference here is between committing directly to the central CI-viewed repo, and pushing your changes to the central CI-viewed repo. The 'problem' you might find is that DVCS users may not actually perform that push regularly.

I'd say this is an inherent design feature of a DVCS, it's not designed to push your changes to the central server all the time - if it were, you might as well use a CVCS instead. So the answer is to enforce a better workflow amongst your developers. Tell them to push changes every night. Simples!

(and if your SVN users are not committing every night, tell them to - its the exact same problem).


问:
Why is the folder name "bin" used in some frameworks and languages?
I have been learning Java. And still after a prolonged time I don't know why the name of the folder is "bin" where one find all the tools for java?

Is there is any logical reason behind that?

I have also noticed the same in .Net framework also.

答:
bin is short for binary. It generally refers to the built applications (also know as binaries) that do something for a specific system.

To quote from ChrisF's answer on Stack Overflow:

You usually put all the binary files for a program in the bin directory. This would be the executable itself and any dlls (dynamic link libraries) that the program uses.


问:
How can I write HTML, CSS, and JavaScript to make back-end developers work easier?
When I get a design from a designer, I get it as a PSD (Photoshop) file. I always expect proper layer and folder names, basically a clean and managed PSD. From this desigbn I develop HTML, CSS and JavaScript and deliver it to the back-end developers. To make it easy for them to understand, I

write semantic code,

keep JavaScript and CSS in external files,

add useful comments in HTML, CSS and JS files,

use CSS sprites (though developers don't like it),

use HTML5 boiler plate,

use jQuery for JavaScript,

try to use new HTML5 tags and CSS3 whenever possible and

sent a Zip file containing the HTML, CSS, JS and images.

I expect that if small changes will need to be made to the layout, the developers can handle that.

I would like to hear from back-end developers and other CSS ninjas what more one could do in terms of organization of files and mark-up to make the integration with back-end systems easier (i.e. back-end technologies, PHP, .NET, Ruby etc.) Different client uses different systems.

答:
Flexibility for you is flexibility for them typically. All those best practices you're following are wins on both sides of the app.

One critical and often missed point, however is writing robust UI. Far too many UI components are overly anchored to one context or an overly exacting set of HTML and they have CSS set up to fail.

If you have a dropdown, for instance, it's far less JS work to anchor an absolute-positioned dropping component inside a relative-set (no coords necessary) clicked container than it is to pull out the JQuery hammer and get the coordinates to hover it over the element and just stick it in place. It's also much less likely to break in cases where the page shifts or some new browser feature throws positioning info off. The more you rely on HTML/CSS skills to avoid JS work, the more robust your UI will typically be.

As a general rule, I try to make sure the only thing my UI components need is an HTML tag to live in with an appropriate ID or class. The more things you can do with that container without the UI inside breaking or with the container actually accomodating  like expanding/shrinking to fit as container dimensions change, the more it can be easily implemented on any part of the app without needing a client-side expert. All they have to do is stick a class on it.

Prefer event delegation on ui containers to assigning listeners directly to end point nodes like buttons. That UI component might work with static HTML now but you never know when somebody is going to want to be able to rip out and rewrite the HTML inside with innerHTML or something. If the container is intact and all events are delegated (see the jquery 'on' method) you don't have to worry about that and they might never learn the hard way that replacing HTML breaks listeners.

In the interest of keeping delegation around as an option, don't use stopPropagate anywhere but end-point nodes and send hate-mail to idiot framework developers who spam it all over the place.

As far as layout, keep the HTML minimal, semantic, and avoid div wrappers. The less HTML there is, the easier layout problems are for layout rookies to diagnose.

Use self-explanatory class names for utility CSS. A "row" class is likely to be more clear to CSS noobs than "clearfix."

Always give unique sectional elements, unique IDs. It makes it much easier to identify where stuff specific to a section is happening, it's easier to override stuff, and it can also be a legibility and performance JS win.

Obviously it's bad news to get excessive with a class scheme but the more a back end dev can set simply by adding the right classes to things, the easier it's going to be for them to make alterations to existing page.

And of course at the beginning of the project get them to agree on at least this one thing: Back and front end connect via HTML and JSON only. Don't let them use stuff that "writes the JavaScript for you!" It's a bloody mess and a maintenance nightmare.

As with all things development-related, prefer DRY, and minimalism.