问:
Storing archived index data
We use RavenDB as our data store for transactional information, and it works well for data that is currently "in use".

We also collect audit events as people use our application, where each event looks something like:

Type, date, summary, etc. - pretty standard

Related document IDs (could be one, could be 5)

As a document store, Raven does a great job of indexing these so that we can ask questions like "find all events related to document XYZ".

Unfortunately as the data builds up over time, these audit events can account for 90% of the data stored in our database - and it's rarely used. We'd like to get this data out of Raven, and into some kind of storage that might be better suited.

What other storage solutions exist for storing hundreds of thousands of audit-type events? We're happy to sacrifice speed to save storage and indexing costs.

答:
SQLite + JSON.NET

Using SQLite provides fast, robust, indexed storage, while JSON.NET maintains compatibility between model types in archive storage and Raven. Deserialize from Raven, re-serialize, store in SQLite.

You can use SQLite columns and indexes to speed up access by selecting before parsing JSON.

Henrik (Andersson) pointed out there's a .NET wrapper for SQLite used in Akavache: https://github.com/akavache/Akavache/blob/akavache4-master/Akavache.Sqlite3/SQLite.cs

SQLite definitely doesn't seem excessively limited for this: http://sqlite.org/limits.html

Title: Storing archived index data


问:
Will this "wireless" syntax for my framework make for good code structure / design?
I'm at the point where I'm getting into the freelance development of some complex web apps, and I would like to develop a light weight framework for my personal use, but I'd like to get some advice from more experienced programmers first about one aspect of my big-picture design for the framework.

It's heavily prototype / OOP based. The framework is set up to know how to handle each prototype, and to know that certain objects for example, a socketIO construct, can utilize  other specific objects, the IP of a server for example, and also the socketPort of that server.

It facilitates this practice with the programmer's own functionality as well, helping to keep all code decoupled, object oriented, and "wireless".

The outcome of this is code that looks "wireless" -- What I mean by that, is instead of passing data as function parameters, the framework's objects know which objects to look for and read from. The developer can pass an object in as the parameter, but if he doesn't the framework will search for it and find it if it exists within the appropriate scope.

Is what I have described a good programming practice/design?

I like the code structure that it helps me to achieve more quickly, but it's important to me that I don't spend time on something that is broken (a bad model).

I want to know if this practice where the data isn't visually passed around / transferred is an acceptable approach to development.

My concern is that the communication between related objects "behind the scenes" may confuse programmers who aren't privy to the design of the framework.

Here's some "mock" client side engine code that would work after the completion of the this framework that I'm currently calling Air JS.
It's commented to explain itself, because it's my blueprint, of sorts, so feel free to skim through it without bothering with every detail.

```<code>App.Engine = new engine({

    /*

    Air JS's Engine Model
    ---------------------

    When developing web apps, the engine
    gets complex quickly, both on the
    client and server side. Without a
    framework promoting the use of good
    JS OOP coding patterns, the code can
    very quickly become a tangled mess!

    By utilizing object prototypes, Air
    JS accesses relevant objects and will
    find things like IPs, Ports,
    extensions, and other information
    relevant to a specific task, without
    the developer needing to manually
    connect things. For example, when
    creating a socket.IO connection, if
    a server object exists that owns a
    socketPort object, Air will find the
    port! No strings attached.

    */

    Server : new server({

    /*

    The server constructor allows all
    relevant server information to be
    gathered into one place. Sky JS
    objects such as:

        socketIO object
        AJAX object

    that utilize server information
    will dynamically locate and utilize
    the information "wireless", without
    the need to be passed in.

    */

        location : new location({

            url     : new URL("www.website.com"),
            IP      : new IP("1.2.3.4.5"),
            ports   : new portList({

                default     : new defaultPort("8080"),
                socket      : new socketPort("4545")

            }),
            paths   : new pathList({

                app         : "App",
                login       : "Login",
                register    : "Register",
                getData     : "Get"

            });

        }),

        auth : new authentication({

            username    : new username(App.Client.Username),
            password    : new password(App.Client.Password)

        }),

    }),

    "Socket" : new socketIO({

        open : new socketListener("open", function(){

            // handle event

        }),

    }),

    /*

    The socketIO object expects an object
    containing socketListeners as its first
    parameter.

    The SocketIO object accepts a server object,
    portList, socketPort, or port string / int
    as its second parameter:

        App
        Server
        App.Engine
        App.Engine.Server
        App.Engine.Server.ports
        App.Engine.Server.ports.socket

        "4545"
         4545

    This is an example of how Air.JS works
    "wireless" -- If the relevant object exists
    within the same engine, it will be found,
    without the developer passing the object or
    information in as a parameter. This is called
    wireless association in Air JS.

    Wireless association will be discussed later
    on in this program, and is the primary proponent
    of the clean, de-coupled code that Air JS
    promotes.

    In this situation, the relevant object is a
    socketPort. If a server object exists that
    owns a portList containing a socketPort,
    it will grab the port.

    If there are multiple server objects, the
    framework will choose the first one that owns
    a portList and / or a socketPort.

    If no socketList object is found in a server
    object, the framework will search the main
    scope of the server object. If no socketPort
    object is found in a server object, or no
    server object is found in the engine object,
    the framework will check for a socket object
    in the engine object's main scope.

    Ultimately,
    if no socketObject exists, and the developer
    does not provide the port via parameters, an
    error will be thrown, pointing to the missing
    data.

    */

});

App.init();
</code>```

The functionality demonstrated here are object prototypes assigned within the framework, as shortcuts. For programmer models of new engine pieces/components, the framework would facilitate the use of objects that "know" certain prototypes. For example, the user creates the prototype Car and lists carDoor as one of its related objects, so a Car instance will look for any carDoors, without the developer feeding it a carDoor through parameters.

答:
This is essentially a dependency injection framework. They are very commonly used in server-side development. Spring and Guice are two frameworks used in the Java world. Grails uses a similar convention as you have defined, specifically injecting ovjects

Dependency injection supports the Inversion of Control principle. This is important for modularity and testability.  It promotes self-contained elements that declare the components they depend on, making them easy to mock or stub out for tests as well as making the structure easier to understand.

You've highlighted what, in my opinion, in the greatest weakness of framework driven dependency injection: Programmers unfamiliar with the patterns may have a hard time understanding what's going on, and may start directly instantiating components rather than injecting them. This isn't a problem at my shop since everyone is familiar with the concept. Older versions of Spring used XML to wire objects together rather than annotations to call for components to be injected; this was nice for being able to see the structure of the system but made it difficult to understand individual components.

I recommend you take a look at Angular and Ember, two Javascript frameworks that heavily use dependency injection. If they may meet your needs exactly, you should strongly consider using them to make it easier for other programmers since they have documentation and define their own conventions. This will keep you from having to train as many people on a custom framework.

ContentLicense: CC BY-SA 3.0


问:
Persistent storage for Apache Mesos
Recently I've discovered such a thing as a Apache Mesos.

It all looks amazingly in all that demos and examples. I could easily imagine how one would run for stateless jobs - that fits to the whole idea naturally.

Bot how to deal with long running jobs that are stateful?

Say, I have a cluster that consists of N machines (and that is scheduled via Marathon). And I want to run a postgresql server there.

That's it - at first I don't even want it to be highly available, but just simply a single job (actually Dockerized) that hosts a postgresql server.

How would one organize it?

Constraint a server to a particular cluster node? Use some distributed FS?

答:
Short answer: Apache Mesos doesn't provide distributed FS.

So, apps have to work with local FS on slaves or you may run any distributed FS alongside Mesos. Mesos is typically deployed together with HDFS, and most of the frameworks that run on top of Mesos can work with HDFS (Hadoop, Spark, Storm, etc.)

And in case your app doesn't support any distributed fs, it has to work with local FS on each slave.

I run ElasticSearch on top of Mesos: I specified local directories for ES data in the config file that each mesos slave take when I start framework. So if I restart ES framework, each ES slave will use the specified directories, and if there's some data, that data will be used. I run multiple instances of ES, and they replicate data between each other, so I don't need to worry about losing data.

However, there may be a problem at some point: let's say, I have 4 mesos slaves, I run ES on 2 of them. Then I stop ES framework and start some other framework on 2 slaves, then I start ES framework again on 2 slaves, but mesos doesn't guaranty that 2 new slaves are the same 2 slaves that I was running ES on previously. So there'll be no previous copy of data.

I run ES on majority of Mesos slaves and I never stop the framework, so I've never encountered this problem.

Title: Persistent storage for Apache Mesos


答:
I used to work in a project which has audit capability for all SQL tables. However, the audit data is much smaller than the actual data because main data is rarely changed.

For your particular case and usage, I have seen people do one thing that may be appropriate to your situation. What they did is they moved part of the archived data (auditing data in this case) into either a new DB or a flat file. The audit system only supports auditing recent data.

For the archived audit data, you can either set up in a new DB which has the benefit of ease of use OR you can setup your own data-diff storing facility and store in flat file manner with indexed access.

Title: Storing archived index data

Body:
We use RavenDB as our data store for transactional information, and it works well for data that is currently "in use".

We also collect audit events as people use our application, where each event looks something like:

Type, date, summary, etc. - pretty standard

Related document IDs (could be one, could be 5)

As a document store, Raven does a great job of indexing these so that we can ask questions like "find all events related to document XYZ".

Unfortunately as the data builds up over time, these audit events can account for 90% of the data stored in our database - and it's rarely used. We'd like to get this data out of Raven, and into some kind of storage that might be better suited.

What other storage solutions exist for storing hundreds of thousands of audit-type events? We're happy to sacrifice speed to save storage and indexing costs.


问:
OpenSSL Client model for half duplex communication over socket
I have read in this SO question that OpenSSL socket communication can be only half duplex in a single thread.

Assuming what I have read is true, I am wondering if I can apply philosopher's dining problem to send SSL_write() and receive SSL_read() on a non-blocking socket in a single thread that communicates with a OpenSSL TCP Server. Both server and client are non-blocking.

Would that be a good model? Or should I always set priority to read SSL_read()? What would be the best approach to code?

I am using C++ to code this single threaded non-blocking socket model (without BOOST or other libraries).

答:
From the comments I see that your "half-duplex" refers to the fact, that you should not operate on the same SSL object from different threads at the same time (or use explicit locking) and thus cannot use SSL_read and SSL_write at the same time from different threads.

While most protocols are request/response and thus don't need parallel read and write the usual way to reach what you want is with non-blocking I/O and select. This works similar to non-blocking I/O with normal sockets. There are two major differences:

There might be SSL handshakes inside SSL_read and SSL_write, so a SSL_read might need to write data and SSL_write might need to read data. So you need to check for the ERROR_SSL_WANT_READ and ERROR_SSL_WANT_WRITE conditions. Same with SSL_connect and SSL_accept.

SSL_read returns only the amount of data you ask for, but there might be more data in the SSL frame. In this case the data are buffered internally inside the SSL object and you will not get from a call to select that there are more data (because they've already read from the socket). You need to check for this case with SSL_pending, or make sure that you always try to read the maximum amount of data which fits into an SSL frame (16k).

And for your dining philosophers: You have this kind of problem only with threads. With single-threaded you don't need locking and thus have no locking problems (which often makes the code faster too because of no lock contention).


问:
How can I cancel all running MySQL queries in a web application?
I am running a web application which has to scan (MySQL query on a particular column) a huge MySQL table, which has over 100,000 records.

The problem is that when a user requests another page from the same web application while the results are being fetched from the scan, the browser takes a long time to display the page.

How can I cancel the scan (or the MySQL query) while the new page is being requested?

答: You can't.... easily.  Think about this from the user's point of view - why should their query be terminated because someone else is making another request? Fix your query to run faster so the system doesn't grind to a halt when somebody does something unexpected.</p>


问:
What are the causes that lead to an overbloated software?
Today I decided to perform a clean install for Creative Sound Blaster drivers, as they always start glitching all by themselves after some time. And that meant I had to go through the whole cleanup procedure. And that took me almost 2 hours..

And honestly, I can't see a reason why?! And although Creative, IMHO, is an absolute 1st place winner for producing poor quality software that never works, the bloat problem is not exclusive to them.

PC with Canon digital camera driver will have around 10 Canon entries that are interconnected with all sorts of connections. Visual Studio is also a prime example, there is around 50 or so entries for full install, and repairing that thing is only possible with complete nuking. And once it even managed to ruin the whole OS install when I was upgrading from VS2k8 to VS2k8SP1 or something. As it turns out 5GB of free space was not enough for 300Mb patch...

So this really seem to be a widespread problem. Almost every application nowadays usually contains unpackers, multiple spywarish "friends" that are installed, drivers are usually around 600Mb for everything including printers and so on.

But why? Is it developer fault? Applications like that are nightmare to support, they never work 100% nowadays, and almost all users I know are very negative about all that bloat they get as a mandatory driver install for USB thumb drive/Printer/Camera/Sound Card/Browser.

It seems that NSIS from Nullsoft is the only clean setup system that is not bloated, from what I know, for example, Firefox install. Clean, pretty much xcopy based install without any problems.

So why people are not using simple setups and applications that are not rooted over 30 layers of interconnection? Is it because developers are lazy? Use of codegen tools? Is it because corporations force heavyweight apps as something users will love? What's the cause, and is there a hope software will return back to basics someday? What are the steps to avoid writing bloat when you start new application from scratch?

答:
An engineer tried to optimze a module but introduced several customer issues. Then, his manager said no. Then, the engineer decided to not "make trouble" until trouble troubles him.

For a complex system, the vendor already added many patches and fixed thousands of bugs to make it stable in the customer's environment. It does not have good quality from software's point of view but it works. No one wants to rewrite it to fix the same amount of bugs again.

for backward compatibility reasons, even if a feature is not popular in the market, we need to keep it there.


问:
Is it okay if we use an arbitrary string as UUID?
I found the tutorial of client (android) and server (pc) bluetooth tutorial from here.

But my question is about the UUID.

Is that okay if we define it randomly without the proper format? Because I heard UUID is generally for ID for each devices just like IP address used right?

For example like this, instead of the following code:

```<code>UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
</code>```

I define my own UUID

```<code>UUID.fromString("myDeviceName009");
</code>```

Is it okay? I mean is it if i tested on both android device using the above code, they could communicate each other?

答:
No. A UUID has a particular, standardised format.

From the wiki article on the subject:

In its canonical form, a UUID is represented by 32 lowercase hexadecimal digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 alphanumeric characters and four hyphens).


答:
Its invariably laziness, that's what causes the bloat. (or the mud as in the seminal article on this subject, the Big Ball of Mud)

For example, where I work we have a "legacy" C++ application that's nevertheless quite well designed, The clients talk to an API that talk to a server that does DB work. All sensibly done. Recently we needed an additional module, but rather than implement it correctly the dev decided to implement this in .NET, and worse, he decided that accessing data via the API was too difficult (its not but...) he would make DB connections directly. So you see how this kind of mess happens. (and all with the agreement of the TA who put "quick" over "good")

I've seen this kind of thing before too - at an old place, a small part of the GUI was html, as some dev thought it a good idea to write the data in html and have the GUI display that. So 1 small part does something different to the rest.

In short, laziness is bad, and consistency is good (regardless of the technology used). I'd rather have an all-MFC application than one that is part MFC and part Winforms and part WebGL with many different back-end architectures tying it all together.

Title: What are the causes that lead to an overbloated software?

Body:
Today I decided to perform a clean install for Creative Sound Blaster drivers, as they always start glitching all by themselves after some time. And that meant I had to go through the whole cleanup procedure. And that took me almost 2 hours..

And honestly, I can't see a reason why?! And although Creative, IMHO, is an absolute 1st place winner for producing poor quality software that never works, the bloat problem is not exclusive to them.

PC with Canon digital camera driver will have around 10 Canon entries that are interconnected with all sorts of connections. Visual Studio is also a prime example, there is around 50 or so entries for full install, and repairing that thing is only possible with complete nuking. And once it even managed to ruin the whole OS install when I was upgrading from VS2k8 to VS2k8SP1 or something. As it turns out 5GB of free space was not enough for 300Mb patch...

So this really seem to be a widespread problem. Almost every application nowadays usually contains unpackers, multiple spywarish "friends" that are installed, drivers are usually around 600Mb for everything including printers and so on.

But why? Is it developer fault? Applications like that are nightmare to support, they never work 100% nowadays, and almost all users I know are very negative about all that bloat they get as a mandatory driver install for USB thumb drive/Printer/Camera/Sound Card/Browser.

It seems that NSIS from Nullsoft is the only clean setup system that is not bloated, from what I know, for example, Firefox install. Clean, pretty much xcopy based install without any problems.

So why people are not using simple setups and applications that are not rooted over 30 layers of interconnection? Is it because developers are lazy? Use of codegen tools? Is it because corporations force heavyweight apps as something users will love? What's the cause, and is there a hope software will return back to basics someday? What are the steps to avoid writing bloat when you start new application from scratch?


问:
Is reading+modifying existing code better than making your own?
I'm an inexperienced programmer. I have been assigned to develop a Firefox plugin with no prior experience. So I followed the tutorial at MDN. I learned so many things, it's exciting and overwhelming at the same time.

When I finally started programming, I ended up using extension the tutorial gave me, and modify it. And after realizing there are tons of code out there which pretty much does everything my extension has to do, I ended up analyzing these codes and implant them to mine with some modifications to suit my own needs....

So yeah, basically what I'm asking is: Will spending a lot of your time observing people's code and modifying them instead making my own improve my skill as a programmer in general?

答:
Reading other people's code is in fact a very good habit, since it's the best way to understand what's out there and what the programmer community will presumably be familiar with. Your code has to be understandable by you and by everyone else who will ever have to maintain it, so it's important to acquire an understanding of what is and isn't readable - even if you read really bad code it still serves as a counter-example.

As for reusing vs. implementing your own: reading other people's code and copying it without understanding, in the hope that it may fulfill your requirements, is bad, because it doesn't result in you learning something.

But detecting existing code that does do what you want and reusing it is good, because it's more efficient than writing your own version, and by finding it and determining that it does in fact do the desired thing, you have proven that you could, in principle, rewrite the solution on your own if you had to. The result is that you save time and don't miss out on learning. In fact, researching existing solutions may even be the critical point that teaches you how to do something, so that you learn something new and save time simultaneously.

The litmus test for copying someone else's code is this: do I understand what the code does and reuse it in order to save time, or am I simply throwing one version after another at the problem until I hit on something that works?


答:
Reading and using other peoples code is an excellent way to learn, however it can also be a trap. You don't want to turn into a Cargo Cult Programmer:

http://en.wikipedia.org/wiki/Cargo_cult_programming

The term cargo cult programmer may apply when an unskilled or novice
  computer programmer (or one inexperienced with the problem at hand)
  copies some program code from one place and pastes it into another
  place, with little or no understanding of how the code works, or
  whether it is required in its new position.

The key test is whether you understand the code you are using. If after taking and modifying the code could you if you needed to write it again from scratch without referring back to the code you copied?

I don't mean if you could write out the exact same code again, I mean could you apply the same algorithm in the same or a better way and achieve the same results.

So long as you properly understand the code then learning from others is an excellent thing to do. But you absolutely need to understand every line of code as you insert it into your program. Understand what it does, how it does it, and most importantly why it is there.

Title: Is reading+modifying existing code better than making your own?

Body:
I'm an inexperienced programmer. I have been assigned to develop a Firefox plugin with no prior experience. So I followed the tutorial at MDN. I learned so many things, it's exciting and overwhelming at the same time.

When I finally started programming, I ended up using extension the tutorial gave me, and modify it. And after realizing there are tons of code out there which pretty much does everything my extension has to do, I ended up analyzing these codes and implant them to mine with some modifications to suit my own needs....

So yeah, basically what I'm asking is: Will spending a lot of your time observing people's code and modifying them instead making my own improve my skill as a programmer in general?


答:
In "The Psychology of Computer Programming" Gerald M. Weinberg has written that programming is a form of writing. What do novelists do to become better novelists? They read a lot of books that have been written by very good writers, so that they can learn. The author is surprised by the fact that so little code is read by programmers.

As was written in other answers, understanding the code that we read is essential to gain knowledge about it.

A good source to find high quality code to read are the various open source projects found for example on github or google code. Beware: not all open source projects contain clean, well-written code. Of course, the quantity of those projects strongly depends on the language in which we write.


问:
Locking database records
What I have right now:

A table with lot of records.

About 200 users can select a record according to some rules based on the data in each record.

There is a high chance that 2 or more users will select the same record.

A user updates the record then saves it back to the db. That record won't be selected again (soft deleted).

Optimistic locking was tried and the performance wasn't accepted by the PO.

Our solution was once a user selects a records it updates a "lock" field in the record.

The problems:

Collision is still occurring as users are still selecting the same record. I need to prevent 2 users from selecting the same record.

We need to release the lock manually if the user takes no action for a long time.

I searched and it seems Amazon SQS was a good solution, but it had a problem that I can't search the Queue.

Is there a good technology to solve my problem? I need to implement a searchable queue where messages are locked when selected and the lock expires after a certain amount of time.

答:
You can allow the user to atomically select and "softly" lock the record by adding a timestamp to the record with when it was locked or when it will be unlocked. You prevent locked records being accessible by excluding them based on the time at locking and the lock field.

Manual unlock (for a rollback/cancel) can be implemented by setting the timestamp to back to epoch.

Title: Locking database records


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答:
I'm forced to have XML documentation for all classes and class members. Including private.
I'm encuraged to use default ghostdoc comments.</p>

```<code>public class User
{
    /// <summary>
    /// the _userID
    /// </summary>
    private int _userID;
}
</code>```

Body:
I'm forced to have XML documentation for all classes and class members. Including private.
I'm encuraged to use default ghostdoc comments.

public class User
{
    /// <summary>
    /// the _userID
    /// </summary>
    private int _userID;
}

ContentLicense: CC BY-SA 2.5


答:
Actually it is a good practice to look for existing solutions. In the business world what matters: did you solve the problem? And if you did, how much time it took? Is it a good solution?

As for good (here: legal) solution like told in this comment, always be careful with what is copyrighted, licensed, and what isn't. The tutorials exist for giving examples of the usage of a code, and as you apply, it will serve as base of your program.

Copying existing solutions is an essential method to accelerate your work. Also if you don't do it, you will end up constantly reinventing the wheel.

As you get experience you will notice that some sort of works can be generated, automatized, generalized, etc... there is nothing bad in copying existing code if it is efficient, nice. As others said, it is vital to understand what you do copy, and you might be able to optimize on it. As you understand what you are really doing, you will be able to make generalization and you will avoid the "Copy Paste Programming" which you most probably fear of.

It is important to point out, finding the correct APIs for your work is part of a programmers' job. Actually to use an API and copy a code are similar work methods in this point of view.

It is matter of resource management, I doubt anybody would say, to use an API and solve a problem in 2 days and write a new code (generally doing the same as the API) in 30 days are indifferent.


答:
You will find that almost 80% of the things you want to do are already done. There is a saying about this, "Do not re-invent the wheel. Unless you can do it better."

A large part of programming is not writing code, but studying behavior. Your users behavior, your behavior, your vendors behavior, your workplace behavior. Code review is a key part in this.

As a programmer, it is not your job to know how to code (that is certainly a necessity, but it isn't the core of the job) - the core of the job as a programmer is to be a researcher. To know how to read documentation. To know how to solve a problem. You'll find that you spend less time in your IDE coding than you do on google reading through blogs and tutorials, I suspect.

So no, I do not think this is a bad habit.


问:
What does 'stage' mean in git?
I find git hard to understand as I could not find the meaning of the words used for the actions. I have checked the dictionary for the meaning of 'stage' and none of the meanings were related to source control concepts.

What does 'stage' mean in the context of git?

答:
Staging is a step before the commit process in git. That is, a commit in git is performed in two steps: staging and actual commit.

As long as a changeset is in the staging area, git allows you to edit it as you like (replace staged files with other versions of staged files, remove changes from staging, etc.).

Broken metaphor time:

Consider a scenario where you call the movers to get your stuff from your old appartment to your new appartment. Before you do that, you will go through your stuff, decide what you take with you and what you throw away, pack it in bags and leave it in the main hallway. The movers simply come, get the (already packed) bags from the hallway and transport them.
In this example, everything until the movers get your stuff, is staging: you decide what goes where, how to pack it and so on (e.g. you may decide that half your stuff will be thrown away before the movers even get there - that's part of staging).

From a technical point of view, staging also supports transactional commits, by splitting all operations into what can fail (staging) and what cannot fail (commit):

The commit in git is implemented transactionally, after the staging is sucessfull. Several steps in the staging can fail (for example, you need to commit, but your HDD is 99.9999% full, and git has no space to perform a commit). This will fail in staging (your repository will not be corrupted by a partial commit) and the staging process doesn't affect your commit history (it doesn't corrupt your repository in case of an error).

Title: What does 'stage' mean in git?


问:
An algorithm for reconstructing a graph from its shortest path information?
I have some shortest path data for a graph. Can I reconstruct the graph itself from this data?

More precisely, I have a boolean (0/1) matrix for each vertex v in graph (V, E). Matrix element [s,d] is equal to 1 iff v is in the shortest path from source vertex s to destination vertex d. All edges in the graph have the same length.

For example, for the graph

```<code>(V1) -- (V2) -- (V3)
</code>```

the three matrices would be:

V1:

```<code>1 1 1
1 0 0
1 0 0
</code>```

V2:

```<code>0 1 1
1 1 1
1 1 0
</code>```

V3:

```<code>0 0 1
0 0 1
1 1 1
</code>```

My questions:

1) is there an algorithm to reconstruct the set of edges E from these matrices?

2) is solution always unique? (this is more of a personal curiosity than a real requirement)

3) can the algorithm be generalized to nonuniform edge lengths?

答:
you can extract the adjacency matrix by from the path matrices by using the following property.

There is a edge between 2 vertexes s and d if and only if the shortest path between them contains only s and d.

For non-uniform length you will only get the unique solution if the triangle inequality holds. Otherwise a graph with d(p1,p2)=1 d(p2,p3)=2 and d(p1,p3)=4 will show the shortest path between p1 and p3 as through p2 instead of the direct connection. Which means that the edge [p1,p3] will never be part of any shortest path.


问:
Can a version of Python's shelve module that knows when its entries have been modified be written in any programming language?
shelve is a Python module that makes it easy to persist a Python dictionary to disk (under the right conditions).

The documentation for shelve gives this example to demonstrate one of the pitfalls of using a shelf:

```<code>import shelve

d = shelve.open(filename)

# ...snip...

# as d was opened WITHOUT writeback=True, beware:
d['xx'] = range(4)  # this works as expected, but...
d['xx'].append(5)   # *this doesn't!* -- d['xx'] is STILL range(4)!
</code>```

The documentation explains:

Because of Python semantics, a shelf cannot know when a mutable persistent-dictionary entry is modified. By default modified objects are written only when assigned to the shelf (see Example).

To say that shelves behave this way "because of Python semantics" seems to me to be measuring Python via a high bar! It would be hard to for shelve to know whether any object contained in a shelf has a reference to something which has been mutated (or a reference to something that has a reference to something that has been mutated). Can this be done in any programming language?

答:
It's perfectly doable, even in Python.  The trick is in returning a wrapper instead of the original stored object.

in your example:

```<code>d['xx'] = range(4)
d['xx'].append(5)
</code>```

the second line can be extended into a retrieve and an operation:

```<code>d['xx'] = range(4)
t = d['xx']
t.append(5)
</code>```

and it's obvious that t doesn't notify d about the .append() operation.

but if you return an object wrapper w that keeps a reference to d and the 'xx' key, it could follow any operation with the appropriate notification.

something like (untested!):

```<code>class wrapper():
  def __init__(self, container, key):
    self.container = container
    self.key = key
    self.value = container[key]

  def __getattr__(self, name):
    attr = getattr(self.value, name)
    if hasattr(attr, '__call__'):     # is callable?
      def f(*args, **kwargs):
        rv = attr(*args, **kwargs)   # do the call
        self.container[self.key] = self.value    # re-store the (modified?) value)
      return f
    return attr
</code>```

Body:
It's perfectly doable, even in Python.  The trick is in returning a wrapper instead of the original stored object.

in your example:

d['xx'] = range(4)
d['xx'].append(5)

the second line can be extended into a retrieve and an operation:

d['xx'] = range(4)
t = d['xx']
t.append(5)

and it's obvious that t doesn't notify d about the .append() operation.

but if you return an object wrapper w that keeps a reference to d and the 'xx' key, it could follow any operation with the appropriate notification.

something like (untested!):

class wrapper():
  def __init__(self, container, key):
    self.container = container
    self.key = key
    self.value = container[key]

  def __getattr__(self, name):
    attr = getattr(self.value, name)
    if hasattr(attr, '__call__'):     # is callable?
      def f(*args, **kwargs):
        rv = attr(*args, **kwargs)   # do the call
        self.container[self.key] = self.value    # re-store the (modified?) value)
      return f
    return attr


问:
How to define item level permissions in a relational database
I need to model a database design to provide item level permissions to users based on the user's role access. I am using asp.net with sql server 2012
I am looking at similar experience on how SharePoint provides the security trimming when we access the resources with a SharePoint site (including search results)

Is it a best practice to model this in the database or the application programming? (I have seen SharePoint implement this, but haven't gone in to figuring out how they have done it)

I will also be using lucene.net for integrating with search. So even the search results should be security trimmed.

Are there any best practices/resources available to suggest how to model this permission?

/Sharath

答:
Item level permissions will require both database modelling and application enforcement.

Essentially, You'll want to create an "item security" table that relates the RowIDs and PermissionIDs to each other.  The application will then have to determine if the current user has the right permissions to view the item that they requested.  The database can also leverage stored procedures to filter the rows returned for a particular table based on the permissions.

This kind of system can easily get complex very quickly.  Make sure you plan ahead and do plenty of modelling and use-case testing of the model before moving forward.

Also, if SharePoint is a good fit for this application, you may consider just using SharePoint instead of reinventing the wheel.

EDIT: I had some free time, so I modeled up a schema that I've used in the past for this type of scenario:

You would want to check the user's permissions against the item they request on your site in your application code.  If the user's permissions don't match, they don't have access. You may also want to implement some form of "admin" access where if a user has the "admin" permission they can access all items.

You can pass the user's ID in any stored procedures you use to check their permissions and to filter list results to only the items they have permission to access.


答:
I'll do an analogy, how do you learn a spoken/written language better, learning all of possible words and structures or reading/listening?

How do the best writers learn? Possibly reading other great or not so great writers.

And the third and last question, what a kind of programming books have you read? I don't know you but me, books with examples.


答:
A UUID is a standardised representation of a 128-bit number.  As noted by AndyBursh, the representation is 32 hexadecimal digits, split into groups and separated by dashes.  Nothing else is a proper UUID, it would just be a string.

The point of a UUID is that it's "universally unique".  If I just pick a string that I like the look of, then there's no guarantee that somebody else won't pick the same string.

RFC 4122 defines a number of ways of generating UUIDs so that is is extremely unlikely that two computers will ever generate the same one.  This makes it good for device IDs, and almost anything else where you need to attach a unique serial number to something.

Microsoft's GUID is one implementation of a UUID.

Title: Is it okay if we use an arbitrary string as UUID?

Body:
I found the tutorial of client (android) and server (pc) bluetooth tutorial from here.

But my question is about the UUID.

Is that okay if we define it randomly without the proper format? Because I heard UUID is generally for ID for each devices just like IP address used right?

For example like this, instead of the following code:

```<code>UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
</code>```

I define my own UUID

```<code>UUID.fromString("myDeviceName009");
</code>```

Is it okay? I mean is it if i tested on both android device using the above code, they could communicate each other?


问:
When to use default access modifier?
I want to understand, from design point of view, in what situations I should use default access modifier, and when I shouldn't.

I found this related question, that provides some basic explanations, how ever I am searching for an answer that will target encapsulation and single reason of change principles, and address it in more professional way.

答:
The default access is otherwise known as package level private or protected... your choice, it doesn't really have a term, but its useful to think of it that way.

If you dig within the source for java.lang you will often see it - allowing other classes within java lang to be able to access some of the internals of this class without exposing those internals to all of the world.

Just glancing, an example of this is the sizeTable within java.lang.Integer (grepcode) that allows there to be a single point where this information is stored.  As this is associated with stringSize (just below it) that is likely used within java.lang.String it means that one doesn't have to have two copies of it or expose it.  Other methods in the area also show more of this Integer/String relationship.

Thinking about this more, you've got Integer.toString(int i) and String.valueOf(int i) - both of which do very similar things.  While its debatable if you want to have the ability to do the same thing in two classes... if you do, you only want to have the code in one place - which again points you to having a package level encapsulation.

Putting things within the same package is supposed to be an important part of encapsulation.  The classes within a package are supposed to work closely with each other.   It means these classes should be able to look at each other's internals and work with them.  It avoids having java.lang.FunkyStringConstatns sitting out there for all the world to see... and once the world sees it as something public, it means that one can't go and change it.

This has less meaning when one works on the entire project from start to finish and there is no public API.  Its more a 'yea, its there' then.  But if you are working on public APIs, you will want times to be able to share data without sharing it with the world.

Title: When to use default access modifier?


答: The default access modifier makes the member visible throughout the entire package. This makes using it on a member that's mutable in any way only marginally better than a global variable. The only possible use I can think of for it is to create constants that you can use as an implementation detail within a package. If you later decide to get rid of or change the constants, no code outside that package will break.</p>

Title: When to use default access modifier?

Body:
I want to understand, from design point of view, in what situations I should use default access modifier, and when I shouldn't.

I found this related question, that provides some basic explanations, how ever I am searching for an answer that will target encapsulation and single reason of change principles, and address it in more professional way.


答:
Your question is generic, so the answer is when it helps. However, I can name two cases where I find myself using default modifiers often.

Firstly, they are handy when you want to test a private method but don't want to make it available for child classes or outside of package.

Another use case is to refactor a nested class into a separate file while keeping private parent class members accessible for it.

UPDATE: I'm aware that my examples go against best practice (test interface, not implementation), but I believe these shortcuts are acceptable when under pressure to deliver quickly and the code base is of moderate size.

Title: When to use default access modifier?


问:
Best Development Methodology for One Person?
I spend a lot of time working on projects in which I am the sole developer, project manager, designer, QT person (Yes, I know... Bad!), and sometimes I'm even the client.

I've tried just about everything for planning projects and managing myself, from just sitting and working freestyle until the project is done however long it takes, to a single-person version of scrum in which I held a progress meeting with myself over a one-man burn down chart every morning (not kidding).

For those of you who spend much time working alone, what is the best way to organize yourself, manage large (for one person) projects, and keep productivity as high as possible?

答:
If you are working solo. Here are the advices:

Do as little low-level work as possible. Use as much library and tools as you possibly can including things you think you can easily code (don't do it, just use the library).

Take the top-down approach. Only code things that you really need.

When you see a problem in abstract term, search on google and use research papers from academic community which has been proved already. You only need to code their algorithm.

Design your system so that you can freely change things as much as possible. (including copy and paste some code from here to there). The purpose is to save you time when you realize you made a mistake. Try to minimize the amount of work you have to throw away when you make a mistake. A piece of code that has to be thrown away (instead of copy-paste from here and there) is the equivalence of time you lost writing that code.

Have lot of automated tests so you can regularly do regression tests each time you make a change

Separate the responsibilities of your design (i.e. reduce coupling). Make things as modular as possible

Use a debugger to debug and use binary search to find defect.

Constantly refactor your code to reduce (explicit) coupling and public methods exposure (implicit coupling).

Nothing really. This is here just in case I can come up with something new :P

OwnerDisplayName: Eli


问:
Is Haskell appropriate for Signal Processing, Communication Systems and Information Theory?
I have been working on Software-Defined Radio projects for almost a year. This is an area which requires lots of signal processing (digital filters and FFTs), communication theory (modulation, equalization and synchronization) and information theory (specifically, coding theory, as Huffman, Linear and Convolutional codes). I program mostly in Matlab (for simulations) and C++ and Python (for practical applications using GNURadio and the USRP).

As you can see, those areas require lots of mathematical concepts. As I've been studying Haskell, I see that it is a good programming language for applications that involve heavy math.It seemed a good idea to program in Haskell for problems in the area I have been working on.

On the other hand, there doesn't seem to be a lot of people doing this. There seems to be a Haskell DSP library, but there aren't many projects using it available on the web. I've also found a thesis where Haskell was used to implement a Viterbi coder/decoder and it seems quite an elegant solution.

But it seems to me that people in the communication industry and research still don't use a lot of Haskell in their codes. Maybe this coulde be because many of them still haven't heard about Haskell.

What would be upsides and downsides of applying Haskell to those kind of problems? What will be key benefits of doing SDR in Haskell? What about Haskell would make it a bad choice for SDR? Should I expect severe pain points using Haskell for SDR (what are they?).

答:
How will anyone use the result of your efforts? If you intend others to use your result, you either have to provide a library that can be used from the mainstream programming languages, or work in that language. If you don't care, I suppose there is no point in asking the question, except that others may find your code harder to read, or they will not bother to read it. Certainly Haskell software is easier to reuse than Matlab software.

The only pain points for the language would be garbage collection delays and ensuring you have the correct data types for mathematical precision and speed.


问:
What's a good way to make sure that locally serialized data can be deserialized in newer code?
Context: I'm working on an HTML 5 game without persisted state.  Every time you refresh the page, you start at the beginning.  People are requesting that they can start where they left off if they leave the page.  I plan to implement this as Local Storage.  The thing that makes apprehensive about this is a new kind of bug I'll have to consider:  If you come back and there's a newer code, it may not be able to deserialize the storage.

As an example, the state when serialized may have looked like this:

```<code>{
  foo: "bar"
}
</code>```

But when the player tries the game next month, that field doesn't even exist anymore and has been broken up into two fields with a completely different type.

This is bound to happen, and I think I know how to fix this:  I'll put a version number in the data, and when I release version y of the app, I'll have to write code to migrate from version x state to version y state.  If I release version z of the app, I'll have to write code to migrate from version y to version z.  I'll probably call this logic after deserialization.

But that's not what this question is about (although if there's a flaw in my approach, I'd want to hear it).  What I want to know is: How do I automate something (possibly a test) that tells me when I need to write a migration script and when I need to change the data's version number?

I feel automation is the key here, because things will go very wrong if I make a mistake  and remembering to change a version number / write a migration script will be the last thing on my mind when I just finished that shiny new feature I want others to see.

An interesting (but perhaps irrelevant) realization: All these issues go away if I store the data on my server in a database with a schema.  That lets me confidently know that all the data is in the right state (if my schema is good).  The problem with persisting locally is I lose control of the data and when it gets migrated.

This question is similar but different to this one.  The difference is I'm concerned primarily with automation and s/he's not and we're using different languages (seeing how the accepted answer is a Java library, that makes it irrelevant to me).

答:
How do I automate something (possibly a test) that tells me when I need to write a migration script and when I need to change the data's version number?

When your automated unit tests fail while importing old data into a newer model, that's one very clear indicator that you need to write a migration script/process.


答: Every time you make a code change that touches your serialization, you must add a new test case in your automated test suite that uses the new fields, or reads the old fields, etc. Over time you'll accumulate more and more coverage for your version transitions. As long as you run your test suite whenever you make changes you'll get notified when you stop being able to read something that used to work.</p>

Title: What's a good way to make sure that locally serialized data can be deserialized in newer code?

Body:
Context: I'm working on an HTML 5 game without persisted state.  Every time you refresh the page, you start at the beginning.  People are requesting that they can start where they left off if they leave the page.  I plan to implement this as Local Storage.  The thing that makes apprehensive about this is a new kind of bug I'll have to consider:  If you come back and there's a newer code, it may not be able to deserialize the storage.

As an example, the state when serialized may have looked like this:

```<code>{
  foo: "bar"
}
</code>```

But when the player tries the game next month, that field doesn't even exist anymore and has been broken up into two fields with a completely different type.

This is bound to happen, and I think I know how to fix this:  I'll put a version number in the data, and when I release version y of the app, I'll have to write code to migrate from version x state to version y state.  If I release version z of the app, I'll have to write code to migrate from version y to version z.  I'll probably call this logic after deserialization.

But that's not what this question is about (although if there's a flaw in my approach, I'd want to hear it).  What I want to know is: How do I automate something (possibly a test) that tells me when I need to write a migration script and when I need to change the data's version number?

I feel automation is the key here, because things will go very wrong if I make a mistake  and remembering to change a version number / write a migration script will be the last thing on my mind when I just finished that shiny new feature I want others to see.

An interesting (but perhaps irrelevant) realization: All these issues go away if I store the data on my server in a database with a schema.  That lets me confidently know that all the data is in the right state (if my schema is good).  The problem with persisting locally is I lose control of the data and when it gets migrated.

This question is similar but different to this one.  The difference is I'm concerned primarily with automation and s/he's not and we're using different languages (seeing how the accepted answer is a Java library, that makes it irrelevant to me).


问:
How to create Public API wrapper with different configuration parameters
I'm looking to see if there is a design pattern that can solve the following problem.  The example is fairly specific but the goal is a public + internal API.  I need specific information for my underlying library but I want to present the API generically.  If my question is vague or terrible I'll try and spruce it up with your comments.

As an example, let's say I am creating a public API and I want it to be agnostic to the implementation.  Continuing the example, I am creating a job handler API using the Quartz (can be any library) library in the current implementation.

I want people to be able to type:

```<code>Job job = jobManager.getJob("my.job.name");
String otherInformation = job.getOtherInformation();
job.setSchedule(new IntervalSchedule(repeatInterval, intervalUnit));
job.setSchedule(new CronSchedule(cronExpression));
</code>```

The Quartz API has builders for schedules (used in Trigger):

```<code>CronScheduleBuilder.cronSchedule(cronExpression);
CalendarIntervalBuilder.calendarIntervalSchedule()
                       .withInterval(repeatInterval,
                           DateBuilder.IntervalUnit.DAY);
</code>```

In my current example I would have a base interface or class Schedule.  With this structure how would it be possible to get the specific information I need for the schedule builders without revealing an implementation specific object in my interface while keeping it extensible.  My goal is to prevent implementation classes from leaking in to the public API.  If in the future Quartz falls out of favor, the public API doesn't need to change and deprecate the Quartz specific classes.  What design pattern or code reorganization am I missing?

答:
A good solution here would be the abstract factory pattern.  Essentially, there is an abstract base factory with a series of abstract methods for building certain abstract classes.  Then, you would provide a concrete subclass of this factory implementing the methods for a certain library.  Take this example:

```<code>public class ScheduleCreator {
    public abstract AbstractSchedule makeSchedule();
}
</code>```

Then you would have a specific implementation for every library you need:

```<code>public class QuartzScheduleCreator extends ScheduleCreator {
    @Override
    public AbstractSchedule makeSchedule() {
        return new QuartzSchedule(); // where QuartzSchedule extends AbstractSchedule
    }
}
</code>```

Then the client, using an abstract ScheduleCreator, wouldn't need to know the library supplying the implementation behind the scenes:

```<code>public void scheduleEvent(ScheduleCreator creator) {
    AbstractSchedule schedule = creator.makeSchedule();
    schedule.schedule(new Event());
}
</code>```

Later, if you decide to change your implementation from Quartz to a different library (let's call it Foo), you would simply create a new FooScheduleCreator that returns an instance of FooSchedule when call makeSchedule().  Then you could supply that ScheduleCreator to the method without the Client having to bother with what library is working under the hood:

```<code>scheduleEvent(new FooScheduleCreator()); // if you want the client to use Foo
scheduleEvent(new QuartzScheduleCreator()); // if you want the client to use Quartz
</code>```

Of course, each ScheduleCreator can have many more methods for whatever you need.

Body:
A good solution here would be the abstract factory pattern.  Essentially, there is an abstract base factory with a series of abstract methods for building certain abstract classes.  Then, you would provide a concrete subclass of this factory implementing the methods for a certain library.  Take this example:

public class ScheduleCreator {
    public abstract AbstractSchedule makeSchedule();
}

Then you would have a specific implementation for every library you need:

public class QuartzScheduleCreator extends ScheduleCreator {
    @Override
    public AbstractSchedule makeSchedule() {
        return new QuartzSchedule(); // where QuartzSchedule extends AbstractSchedule
    }
}

Then the client, using an abstract ScheduleCreator, wouldn't need to know the library supplying the implementation behind the scenes:

public void scheduleEvent(ScheduleCreator creator) {
    AbstractSchedule schedule = creator.makeSchedule();
    schedule.schedule(new Event());
}

Later, if you decide to change your implementation from Quartz to a different library (let's call it Foo), you would simply create a new FooScheduleCreator that returns an instance of FooSchedule when call makeSchedule().  Then you could supply that ScheduleCreator to the method without the Client having to bother with what library is working under the hood:

scheduleEvent(new FooScheduleCreator()); // if you want the client to use Foo
scheduleEvent(new QuartzScheduleCreator()); // if you want the client to use Quartz

Of course, each ScheduleCreator can have many more methods for whatever you need.


问:
Why use Android Fragments?
I have read the documentation and some other questions' threads about this topic and I don't really feel convinced; I don't see clearly the limits of use of this technique.

Fragments are now seen as a Best Practice; every Activity should be basically a support for one or more Fragments and not call a layout directly.

Fragments are created in order to:

allow the Activity to use many fragments, to change between them, to reuse these units... ==> the Fragment is totally dependent to the Context of an activity , so if I need something generic that I can reuse and handle in many Activities, I can create my own custom layouts or Views ... I will not care about this additional Complexity Developing Layer that fragments would add.

a better handling to different resolution ==> OK for tablets/phones in case of long process that we can show two (or more) fragments in the same Activity in Tablets, and one by one in phones. But why would I use fragments always ?

handling callbacks to navigate between Fragments (i.e: if the user is Logged-in I show a fragment else I show another fragment). ===> Just try to see how many bugs facebook SDK Log-in have because of this, to understand that it is really (?) ...

considering that an Android Application is based on Activities... Adding another life cycles in the Activity would be better to design an Application... I mean the modules, the scenarios, the data management and the connectivity would be better designed, in that way. ===> This is an answer of someone who's used to see the Android SDK and Android Framework with a Fragments vision. I don't think it's wrong, but I am not sure it will give good results... And it is really abstract...

====> Why would I complicate my life, coding more, in using them always? else, why is it a best practice if it's just a tool for some cases? what are these cases?

答:
Fragment is a modular section of an Activity that has it's own lifecycle, receives its own input events, which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities)

Apart from the obvious advantage of using fragments, UI optimization across different screens, it lets you manage activity's background processing without a visible user interface component.

Now...

====> Why would I complicate my life, coding more...??

Albeit recommended, you don't need to unless you plan to control the lifecycle of individual elements and/or reusing the stack-state or history of previous views.

Title: Why use Android Fragments?


问:
Are error variables an anti-pattern or good design?
In order to handle several possible errors that shouldn't halt execution, I have an error variable that clients can check and use to throw exceptions. Is this an Anti-Pattern? Is there a better way to handle this? For an example of this in action you can see PHP's mysqli API. Assume that visibility problems (accessors, public and private scope, is the variable in a class or global?) are handled correctly.

答:
There's definitely nothing wrong with not using exceptions when exceptions are not a good fit.

When the code execution should not be interrupted (e.g. acting on user input that may contain multiple errors, like a program to compile or a form to process), I find that collecting errors in error variables like has_errors and error_messages is indeed far more elegant design than throwing an exception at the first error.  It allows to find all errors in user input without forcing the user to resubmit unnecessarily.


问:
What are the limits of using OS X when it comes to compiling and running CLI-based tools and scripts that were written with Linux in mind?
I run little scientific scripts and C tools on OS X from time to time. For the C tools, I just download the source and compile using the provided Makefile. I usually don't have any problems when using the tools.

However, knowing that those tools were written on Linux most of the time, I wonder if the differences in architecture (Linux is System V based, OS X is BSD based) will present issues.

答:
Instead of compiling from scratch have you investigated Homebrew MacPorts and Fink.All of these port unix tools to OSX with the heavy lifting already done for you. they also provide porting guides to enable you to port your own applications.

Each of these systems has its own adherents but to be honest they are much of a muchness, each has strengths and weaknesses and none is perfect.

http://www.finkproject.org/index.php?phpLang=en

http://brew.sh

http://www.macports.org

There are other similar projects but I haven't tried those yet.
i am currently using Macports but all seem to work just fine.


问:
What do you use string reversal for?
In PHP it's strrev(), in Rails it's .reverse, but most languages don't have any string reverse function. Some have array reverse functions that can be used on characters. I was thinking this must be a major oversight but then it occurred to me, what would you actually use string reverse for???

The only time I can think I've seen it is in demos and lessons to turn "Hello World!" into "!dlroW olleH".

My question is; Is there a use for reversing a string or is it completely pointless?

.

Addendum

There have been way more answers that I had anticipated and not all of them were entirely academic. I would have put money that no one could come up with a legitimate example. I also didn't think I would learn anything new but Mark Canlas' regex suggestion is just brilliant and I look forward to the opportunity for it to prove itself. Thanks to all.

答:
```<code><span style="unicode-bidi: bidi-override; direction:rtl;">
    <?php echo strrev($emailaddress); ?>
</span>
</code>```

Not the best solution for obfuscating an email address, since when you add it to the clipboard it's still reversed.  And, if it became popular, it would soon be detected by email scraping bots.

Still, it's been suggested.

Title: What do you use string reversal for?

Body:
<span style="unicode-bidi: bidi-override; direction:rtl;">
    <?php echo strrev($emailaddress); ?>
</span>

Not the best solution for obfuscating an email address, since when you add it to the clipboard it's still reversed.  And, if it became popular, it would soon be detected by email scraping bots.

Still, it's been suggested.


答:
Most of the time you should be fairly safe.

OS-X is based on BSD which, like Linux, is a variant of Unix, albeit one of the more different versions.

It does however have very similar kernel and OS calls, and is considered to be Posix compliant, which is the main thing needed for cross platform operation.

The biggest issue your going to face when it comes to Apple's variation on things are

CPU & Processor architecture.

Additions made to the OS kernel but not released back into the wild.

Taking each of these in turn:

CPU & Processor architecture

All apple machines manufactured since 2007 have Intel based CPU's in them, however older apple machines used a variety of different CPU types ranging from the Motorola 68000 right through to the IBM PowerPC.

Some Linux projects do have in-line assembly language in them, especially things that are designed to interface to the kernel at a very low level.

On a modern day Apple with an Intel, this is not really too much of an issue, but if your trying to compile for something with a non Intel CPU in, your going to have problems.

Thankfully however, because of Linux's philosophy and open-source nature, this kind of practice is frowned upon, and very rarely seen in regular applications and tools.

Also, where an application is known to have platform specific parts in, there is often a ./configure script to run that 'configures' the sources for the platform being built on, or there is some way of specifying what the build target should be.

Additions made to the OS kernel but not released back into the wild

Apple are well known for putting thier own spin on things, and while I'm not an Apple developer (so I can't say for 100% what is and is not added), I do know a lot of other developers who are.

Going on the various comments and things I've been told by others, there are a number of OS facilities that are only available in Apples variation of the Linux base OS, and in some cases, developers are encouraged to use these in place of regular calls.

This really however, should only affect the porting of applications going the other way, in so much that, the target platform is tied to being apple and not easily portable to other variants.

Bringing in external apps should not be much of an issue as long as the application uses only standard posix based API calls, and does not try to do anything special or clever, or make any assumptions about the environment in which it is running.

The area where your likely to have the most trouble, is in the GUI space.  Beacuse the GUI is so closely tied to the windowing library, and the windowing library is where most of Apples 3rd party extensions lie, then IMHO if any type of application is going to present you with a whole heap of problems, it's going to be here.

Most of the generic Linux stuff is designed to run under either a Generic X server, or using a toolkit such as Gnome or Kde, both of which (Correct me if I'm wrong here) I'm let to believe are not available on OS-X.

Title: What are the limits of using OS X when it comes to compiling and running CLI-based tools and scripts that were written with Linux in mind?

Body:
I run little scientific scripts and C tools on OS X from time to time. For the C tools, I just download the source and compile using the provided Makefile. I usually don't have any problems when using the tools.

However, knowing that those tools were written on Linux most of the time, I wonder if the differences in architecture (Linux is System V based, OS X is BSD based) will present issues.


答:
There are sometimes minor annoyances in porting code from Linux to OS X. For example, until Lion, OS X didn't provide a 'getline()' function, so you were forced to provide your own. Then when Apple added it in Lion, you had to have conditional compilation to include the home grown getline() when building on Snow Leopard, and leave it out when building on newer versions of OS X. It isn't rocket science but it is surely annoying. Aside from nits like that, the UNIX API provided by OS X is pretty compatible with Linux.

The biggest headache now is that Apple has moved on to Clang for it's compilers. Most Linux projects are still built with GNU GCC and a lot of code that will compile with the GNU GCC compilers will not compile using the Clang compilers. For example the Boost libraries seem to get broken and then patched with each new version of Clang or Boost. You may have to install a copy of the GNU GCC compilers from MacPorts or Homebrew to get stuff to compile.


问:
Is it a good idea for JS objects to draw themselves when the page loads?
So normally I would only use JS to modify the dom after the user interacts with something or some event goes off. This seems right for some reason.

But I'm developing a widget based app where widgets need the capability to draw (print) themselves and it feels redundant to send the widget's html via the initial http request when I can just print them with the js method when the page loads.

Should I be trying to avoid printing html elements with JS on the page load as a rule or is it just an optimization thing?

答:
For those who are looking for the quick answer

Avoiding writing anything that modifies the JS DOM is always good practice, unless you have a good handle on exactly what is or is not going into the page, your likely going to run into a lot of trouble.

If you want the longer answer, keep reading

Unless your code and html is encapsulated in the new web component architecture, then when ever you call one of the various JS output methods, that's likely to modify anything the rest of the page flow may depend on, you're going to halt the DOM renderer and force it to wait while it checks everything.

Even if what you print out is not going to interfere with other elements in the page, the DOM renderer doesn't yet know this, (especially if it's still constructing things) and so will pause while it double checks what it does already know.

There are ways and means to mitigate this, for example you could output everything into a sandboxed I-Frame, then the only renderer that gets paused is the one in the I-Frame, or you can make sure that your script runs before anything else ever, produces its output, but keeps it hidden until the rest of the page is created.

Another reason that folks often overlook are things like Google advertising elements.

GAd's do some very, very funky stuff with the DOM, including busting themselves out of I-Frame containers and up the page tree to sit above other elements, so they can interact with them.

In a project I worked on previously, we where doing a LOT of work in this area, and the trouble GAd's caused us in scenarios like this was nothing short of maddening.  And it's not just GAd's there are other things too, widgets from other providers, map widgets, web components and various scripts that try to hook up to things in sneaky ways.

Unless you know every single line of code your including in your page (Including that in 3rd party scripts) I'd strongly advise against doing this.

If your target is modern HTML5 based browsers and you don't care much for the older ones, then you might want to consider using the newly emerging web-components standard.  It's designed exactly for this kind of scenario and is designed from the ground up to make sure you can wrap anything you need in your own little JS world and not harm anything running in the browser.  This new technology is what makes things like the new Video and Audio players available with their own controls and skinning capabilities.

If you use 'PolymerJS' or 'X-Tags' to support your efforts, these things will work across the board right now, and adapt to use native features as the browser manufacturers start to enable this in their browsers.

If you're using Polymer, then even though officially the Docs state IE 10 or higher, you can get support using it all the way back to IE8, Chrome 30 and I cant remember the exact version, but a few versions back on Fire fox too.

If you're not able to use the newer web-component architecture, or you have to support really old browsers, and need to write contents out, then the absolute safest way is to lock your script away inside an I-Frame and keep it as physically separate as you possibly can from the rest of the page DOM.


问:
Returning results of method on batch list?
The title is a bit vague so I'll try to elaborate.

I have a function

```<code>makeFoo(int bar) -> returns Foo or throws Exception.
</code>```

I also have a batch version of this

```<code>makeFoos(int[] bars) -> returns Foo[]
</code>```

which basically loops through bars and runs makeFoo() on them.

Issue is, if while running makeFoos(), makeFoo() throws an Exception, what do I do? I don't want to break out of makeFoos() because I want to continue processing the rest of the bars. But also, I want to retain the Exception that was thrown.

My initial solution is, instead of returning Foo[], I return Result<Foo>[]. Where Result is a wrapper class:

```<code>class Result<T>:
    T data;
    Exception e;
</code>```

Is there a better way that I can approach this?

Edit: Apologies if this is considered a duplicate post, but I posted a more general version of this question here: https://softwareengineering.stackexchange.com/questions/247149/result-object-vs-exceptions

答:
The simple apporach is to just fail when one of the bars fail.  But if you want to process the entire list of bars, then you will need a more complex object that contains arrays like:

SuccessfulFoos[]

FailedBars[]

FailedBars would be a composite object and would encapsulate the error information as well.  SuccessfulFoos would just be a Foo since no error occurred.


问:
Full signed part of two complement long
I am reverse engineering a data file (from a synthesizer).

It seems that e.g. -1 is written as FF FF FF FF, so in four bytes.
while +1 is written as 00 00 01 (--), so only three bytes.

Is something like this common? I only heard about either a 3 or 4 byte format, but not 3 OR 4 depending on the sign.

And is there some way to handle this in C#? BitConverter class is a bit too limited for this.

答:
I'm going to assume you already have a copy of the MIDI 1.0 Specification (latest version), and have digested it thoroughly.  (If you haven't, that's your first homework assignment.)

Manufacturers of MIDI synthesizers are usually good about publishing their dump file formats, to make it easier for third-party vendors to write programming utilities and librarians.  If the manufacturer of your synth is still in business, asking them POLITELY for a copy of their specification will almost certainly work quite well, and the resulting document will answer ALL of your questions.

Title: Full signed part of two complement long


答:
It depends.

Unless client-side performance is an observable concern, focus on maintainability.

That means you ideally want the translation from data to markup/DOM to be consolidated. You don't want two or three different objects, especially sitting in two or three different languages, that are each responsible for producing the same DOM structure.

If your client-side script provides progressive enhancement or needs to be crawl-able/scrape-able/Googleable, render HTML server-side. Write your server-side components in a highly modular fashion: Be able to request new markup for a single component quickly and easily. And depend as minimally as possible on direct client-side manipulation of the DOM.

Alternatively, if your app is "highly interactive" or dependent on client-side script, the server probably doesn't need to know anything about the final markup/DOM as it pertains to these interactive components. Send "bare" markup, XML, or JSON for your JavaScript library to consume and display.

Don't spend time optimizing for client-side rendering performance unless it's a known issue.

If you have doubts, and even if you don't, model your app after another successful app that's similar. Open your browser's network profiler and see what comes over the wire and when.

Personally, I've been tending towards client-side DOM construction and have found even the more ancient devices, running modern browsers, perform perfectly well using this strategy. The burden on keeping my client-side code and server-side code is greatly reduced.

Title: Is it a good idea for JS objects to draw themselves when the page loads?

Body:
So normally I would only use JS to modify the dom after the user interacts with something or some event goes off. This seems right for some reason.

But I'm developing a widget based app where widgets need the capability to draw (print) themselves and it feels redundant to send the widget's html via the initial http request when I can just print them with the js method when the page loads.

Should I be trying to avoid printing html elements with JS on the page load as a rule or is it just an optimization thing?


问:
Program Design clearness vs convenience
I've recently disputed with my colleague about the following situation:

I've developed a framework that processes the resources (in java, although its not really important). It goes (simplified, pseudo-code) like this:

```<code>class Algorithm {
    Processor processor = ...;
    execute() {
        forEach(Resource r : readResourceNamesFromFileSystem()) {
           DomainObject do = convertResourceToDomainObject(r);
           processor.process(do);
        }
    }

}

interface Processor {
     process(DomainObject do);
}
</code>```

Class Algorithm is an entry point to my framework. Resource is a representation of some content in the filesystem (it has methods for reading the data from file and the file name, which is important)

Class DomainObject (declaration is omitted) is a java representation of the content of the file depicted by Resource. DomainObject only has data and doesn't have a filename inside.

Class Processor represents the business logic layer, the DomainObject can be processed, stored in Database and so forth.

The content data is supplied by others, we just know that these files contain the data that can be converted into DomainObject(s) which is a real object we work with in the framework. We store one DomainObject in one file.

Now we argue about the file name. Colleague of mine wants the file name to be propagated into the Processor and potentially to all the layers because  its easy to print the logging message/throw an exception that contains a file name if something goes wrong during the processing, or maybe to write the message like "domain object stored in file (here__comes__filename) has been processed successfully".

I see the point of my colleague (convenience) but I'm sure it breaks the design and encapsulation because the processor module shouldn't really be aware of the "origin" of the DomainObject (today we store them in files one DomainObject per file, tomorrow we'll maybe use something else, something that doesn't necessarily has a filename).

I claim that we better catch the exception in the Algorithm.execute method and rethrow the exception with a filename/ log the filename. The log file will be less readable but the encapsulation won't be broken.

In my understanding its a design vs clearness. Could you please share your opinion, who is right, who is wrong? Should I sacrifice the design for the clearness of logs?

BTW I've promised my colleague to ask this question so we'll read the possible answers together :)

Thanks a lot in advance and have a nice day

答:
Catch the exception at the level where you do have the file name, incorporate the file name into the error message, and rethrow.

This is a classic example of why exceptions are designed the way they are; they propagate up the call stack to the next available catch clause, where new information can be added to them where it is available.  This avoids the need to pollute your classes by propagating logging information throughout your class hierarchy.

Java will even maintain the original stack trace.

The whole point of having things like stream objects is to abstract away details like file names.  A stream doesn't care where the data it is streaming comes from, and some data sources don't even have file names associated with them.

Title: Program Design clearness vs convenience


问:
Track performance numbers
I have a (large) software project in a git repository. There is a benchmark suite that spits out lots of numbers (time per benchmark, allocations done per benchmark) I’d like to track.

What is the best way to get a grip on intended and unintended performance changes in such a setup?

(Ideally, I think, there is a piece of free software that takes a git repository, a script to obtain the numbers, schedules jobs for new commit, also checks old commits when idle and presents a slick web interface with lots of graphs and analysis tools.)

答:
I have a limited amount of experience with Jenkins. One thing I really liked about it was the dashboard display that had been set up by my colleagues, using plugins for Jira, Subversion, and Clover (code coverage). Jenkins supports quite a number of plugins and you can develop them yourself.

I know that Hudson has a similar extensibility.

Title: Track performance numbers


问:
Is there any software development methodologies for small teams?
I'm working in a big software company and I'm developing a big enterprise-level web-solution with a team of about 25 people (2 architects, ~15 developers, 5 QA engineers, couple BAs, project manager). We are following agile methodology and scrum and it seems to be pretty convenient for such big team in circumstances of frequent requirement changes.

I also have one pet project - I have basic idea and I've started development. Currently I'm working alone, but I plan to propose to couple of my friends participate in my project.

Some time ago I've faced with a problem of proper task-tracking and formalizing requirements. My first thought was to use agile methodology as we used it with my team at work. While it is very convenient for my job, I have found it too much time-consuming for team with 1-3 people.

Is there any software development methodologies for really small teams? Or I should overcome myself and formalize all my thoughts into user stories and tasks and use iterations?

I don't want my project become just another folder on my disk, but I'm also don't want to waste time on unnecessary formalizations.

答:
In scrum you have periodic retrospectives where you adjust your process.  If your process doesn't evolve over time, or if it looks the same for every scrum team in a larger organization, you're not doing it right.

Likewise, with a small team, you should have periodic retrospectives and adjust your process as your needs change.  There's no need to nail everything down at the beginning.  Typically, the formality grows as the project grows.  You can still call it "agile" if you're focusing on quick adaptation to customer needs and other agile principles.  It won't and shouldn't look the same as a large multi-team project.

If you're asking more along the lines of tools and practices, my small projects start out with just a git repository.  Once I can't keep track of all the tasks/bugs/user stories in my head anymore, I create a TODO.txt in the repository.  As it grows, I add things like unit tests, documentation, packaging, etc.  At a certain point, I put it up on bitbucket.  Later on, I transfer my TODO.txt into bitbucket's simple issue tracker.  You could keep going up to CMM level 5 that would rival a DoD contractor's process.

In other words, you add formality as the benefits for doing so start to outweigh the costs.


问:
How can I perform a logical test to ensure that MY CUSTOM ERROR gets thrown instead of the NumberFormatException?
I am working on something that should be fairly simple. I have 95% of my program working, but one piece is still not fulfilling the requirement. (FYI, this is for a homework assignment, but I will prove that I have put good effort into it before coming here.)

The piece of the assignment:
* The ProductionWorker class should throw an exception named InvalidPayRate when it receives a negative number for the hourly pay rate or if the data entered is not numeric.

I have my InvalidPayRate logic for catching negative numbers, but I am not too sure how to ensure that the input is numeric. Here is the relevant code:

InvalidPayRate.java

```<code>public class InvalidPayRate extends Exception {
    public InvalidPayRate(){
        super("Error: Invalid Pay Rate.");
    }
}
</code>```

ProductionWorker.java

```<code>void setHourlyPayRate(double rate) throws InvalidPayRate
    {
        if (rate < 0.0){
            throw new InvalidPayRate();
        }

        this.hourlyPayRate = rate;
    }
</code>```

test.java (this is within a main function)

```<code>//Set Rate details
try{
    worker.setHourlyPayRate(-15.00);
    System.out.println(worker.getHourlyPayRate() + ": Valid HourlyRate");
} catch (InvalidPayRate e) {
    System.out.println(e.getMessage());
}

try{
    worker.setHourlyPayRate(20.00);
    System.out.println(worker.getHourlyPayRate() + ": Valid HourlyRate");
} catch (InvalidPayRate e) {
    System.out.println(e.getMessage());
}

String testRate = "1v2.65";
try{
    double rate = Double.parseDouble(testRate);
    worker.setHourlyPayRate(rate);
    System.out.println(worker.getHourlyPayRate() + ": Valid HourlyRate");
} catch (InvalidPayRate e) {
    System.out.println(e.getMessage());
}
</code>```

Right now, 2 of the 3 tests are working... the Valid entry, the negative number entry (returns my custom error) but my non-numeric entry is not working... it gives the standard NumberFormatException error.

How can I perform a logical test to ensure that MY CUSTOM ERROR gets thrown instead of the NumberFormatException?

答:
The error is thrown from Double.parseDouble, in other words outside of your code, by the time setHourlyPayRate gets called you know it's a valid double. The conversion from string to double is not your problem™.

If you really want to throw your custom exception then you need to wrap the conversion in a try catch and rethrow the custom exception:

```<code>String testRate = "1v2.65";
try{
    double rate;
    try{
        rate = Double.parseDouble(testRate);
    } catch (NumberFormatException e) {
        throw new InvalidPayRate();
    }
    worker.setHourlyPayRate(rate);
    System.out.println(worker.getHourlyPayRate() + ": Valid HourlyRate");
} catch (InvalidPayRate e) {
    System.out.println(e.getMessage());
}
</code>```

There is one input you don't guard against though and that is Double.NaN which you can test for with Double.isNan.

```<code>if (Double.isNaN(rate) || rate < 0.0){
    throw new InvalidPayRate();
}
</code>```

Body:
The error is thrown from Double.parseDouble, in other words outside of your code, by the time setHourlyPayRate gets called you know it's a valid double. The conversion from string to double is not your problem™.

If you really want to throw your custom exception then you need to wrap the conversion in a try catch and rethrow the custom exception:

String testRate = "1v2.65";
try{
    double rate;
    try{
        rate = Double.parseDouble(testRate);
    } catch (NumberFormatException e) {
        throw new InvalidPayRate();
    }
    worker.setHourlyPayRate(rate);
    System.out.println(worker.getHourlyPayRate() + ": Valid HourlyRate");
} catch (InvalidPayRate e) {
    System.out.println(e.getMessage());
}

There is one input you don't guard against though and that is Double.NaN which you can test for with Double.isNan.

if (Double.isNaN(rate) || rate < 0.0){
    throw new InvalidPayRate();
}


答:
I believe that the best approach for your case is using Jenkins with the Performance Plugin. It has nice graphs and can be used both with JMeter and SoapUI.

Also test performance is important. According to Martin Fowler it is better to run fast unit tests for every commit and slow integration and performance tests every few hours.

Title: Track performance numbers

Body:
I have a (large) software project in a git repository. There is a benchmark suite that spits out lots of numbers (time per benchmark, allocations done per benchmark) I’d like to track.

What is the best way to get a grip on intended and unintended performance changes in such a setup?

(Ideally, I think, there is a piece of free software that takes a git repository, a script to obtain the numbers, schedules jobs for new commit, also checks old commits when idle and presents a slick web interface with lots of graphs and analysis tools.)


答:
Return an array of Optional. That aside, you might want to consider better collections than arrays; they're quite cumbersome, especially since they don't implement Iterable or Collection.

EDIT: For catching the type of the error, your Result<T> is a good starting point, but I wouldn't expose both fields like that (I assume you only did that to get the idea accross.) Result, or as it's known in functional languages, Either, is only marginally different from Optional, so your final design should have roughly the same API. In particular, you definitely want to implement flatMap so you can easily chain computations on Results without having to do this:

```<code>Result<T1> result1 = foo();
if (result1.isValue()) {
    T1 value1 = result1.getValue();
    Result<T2> result2 = bar(value1);
    if (result2.isValue()) {
        T2 value2 = result2.getValue();
        Result<T3> result3 = baz(value2);
        if (result3.isValue()) {
            ...
        } else {
            result3.getError();
        }
    } else {
        result2.getError();
    }
} else {
    result1.getError();
}
</code>```

Normally I'd say you might want to parametrize the Result type over the type of error too, since you may not always want to return an exception, but with Java's practically non-existent type inference it'd just make the whole thing even more cumbersome.

You might want to look at this question for an alternative to implementing Result's API that doesn't involve calling getValue() if and only if isValue() returns true.

Title: Returning results of method on batch list?

Body:
The title is a bit vague so I'll try to elaborate.

I have a function

```<code>makeFoo(int bar) -> returns Foo or throws Exception.
</code>```

I also have a batch version of this

```<code>makeFoos(int[] bars) -> returns Foo[]
</code>```

which basically loops through bars and runs makeFoo() on them.

Issue is, if while running makeFoos(), makeFoo() throws an Exception, what do I do? I don't want to break out of makeFoos() because I want to continue processing the rest of the bars. But also, I want to retain the Exception that was thrown.

My initial solution is, instead of returning Foo[], I return Result<Foo>[]. Where Result is a wrapper class:

```<code>class Result<T>:
    T data;
    Exception e;
</code>```

Is there a better way that I can approach this?

Edit: Apologies if this is considered a duplicate post, but I posted a more general version of this question here: https://softwareengineering.stackexchange.com/questions/247149/result-object-vs-exceptions

Body:
Return an array of Optional. That aside, you might want to consider better collections than arrays; they're quite cumbersome, especially since they don't implement Iterable or Collection.

EDIT: For catching the type of the error, your Result<T> is a good starting point, but I wouldn't expose both fields like that (I assume you only did that to get the idea accross.) Result, or as it's known in functional languages, Either, is only marginally different from Optional, so your final design should have roughly the same API. In particular, you definitely want to implement flatMap so you can easily chain computations on Results without having to do this:

Result<T1> result1 = foo();
if (result1.isValue()) {
    T1 value1 = result1.getValue();
    Result<T2> result2 = bar(value1);
    if (result2.isValue()) {
        T2 value2 = result2.getValue();
        Result<T3> result3 = baz(value2);
        if (result3.isValue()) {
            ...
        } else {
            result3.getError();
        }
    } else {
        result2.getError();
    }
} else {
    result1.getError();
}

Normally I'd say you might want to parametrize the Result type over the type of error too, since you may not always want to return an exception, but with Java's practically non-existent type inference it'd just make the whole thing even more cumbersome.

You might want to look at this question for an alternative to implementing Result's API that doesn't involve calling getValue() if and only if isValue() returns true.


答:
What is the best way to get a grip on intended and unintended performance changes in such a setup?

I don't know anything about your benchmark suite, but as far as I understand the question, this can be implemented as an automatic test (I assume you have already a test suite with integration or acceptance tests in place). What you need is

a possibility to record the performance values in a machine readable form

a possibility to store the recorded values as reference values

a possibility to compare recorded values from "the latest run" with the reference values, and if those values differ "too much", you this up as a "failed test".

Maybe you have to implement these three things by using some scripts on your own, but when your test suite allows unattened execution, it should not be too hard.

So whenever your regular (integration) test suite is run (for example, as part of a "nightly build"), you run also the performance test suite, and will be informed about unwanted changes in the same manner as you will be informed about any other failed test.

Have in mind that you have to define what "too much" means. Have also in mind, that the outcome of the performance results can be extremely hardware depedent, so when you have to run the test suite on different machines, or if the build server is working on too many other things in parallel during the tests, expect the results to be different.

So before throwing some arbitrary tools at the data to produce some nicely coloured charts you have to check manually after each run, check if that is really appropriate for your case, and if a fully automatic without any graphics does not suite your needs better.

Of course, charts may be helpful for analysing the root cause whenever the performance drops, but just for detecting a deviation I would avoid anything which needs manual interception.

EDIT: Rereading your question again, I am wondering if you are using an automatic build server, or if you currently do all builds locally. If you have no build server, that may be indeed the first thing to start with (independent from your performance tests). Afterwards you can integrate some automatic tests on that platform, and afterwards the performance tests. If you don't want to setup such a system, the minimum thing you need is a single script which will check out the complete source code to a clean directory and compile everything in one step. Afterwards you can try to integrate the automatic run of the performance tests. But I guess a server system is more appropriate, because otherwise you are going to block your workstation for a certain amount of time with each test run.

Title: Track performance numbers