问:
What are the reasons to execute a WebService from SQL?
I was looking at some examples on how to call a Web Service from SQL Server.
And all of them show very unreadable code, that I imagine would be a nightmare to maintain.
So, the main question is why to choose that approach vs a standalone program that can do the same.

Just for example one of the how to call a web service from T-SQL:

```<code>CREATE PROCEDURE[dbo].[cm_genericHTTPRequest]
{
@URI varchar(2000) = '',
@methodName varchar(50) = '',
@requestBody varchar(max) = '',
@SoapAction varchar(255),
@UserName nvarchar(100), -- Domain\UserName or UserName
@Password nvarchar(100),
@responseText varchar(8000) output
)
as

begin
--print 'starting the generic call'
IF @methodName = ''
BEGIN
select FailPoint = 'Method Name must be set'
return
END
set @responseText = 'FAILED'

DECLARE @objectID int
DECLARE @hResult int
DECLARE @source varchar(255), @desc varchar(255)

--print 'Creating MSXML2.ServerXMLHTTP'

EXEC @hResult = sp_OACreate 'MSXML2.ServerXMLHTTP', @objectID OUT
IF @hResult <> 0
BEGIN
EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
SELECT hResult = convert(varbinary(4), @hResult),
source = @source,
description = @desc,
FailPoint = 'Create failed',
MedthodName = @methodName
goto destroy
return
END

--print 'open the destination URI with Specified method'
EXEC @hResult = sp_OAMethod @objectID, 'open', null, @methodName, @URI, 'false'--, @UserName, @Password
IF @hResult <> 0
BEGIN
--print 'error openiNg the destination URI with Specified method'
EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
SELECT hResult = convert(varbinary(4), @hResult),
source = @source,
description = @desc,
FailPoint = 'Open failed',
MedthodName = @methodName
goto destroy
return
END

--print 'set request headers'
EXEC @hResult = sp_OAMethod @objectID, 'setRequestHeader', null, 'Content-Type', 'application/soap+xml; charset=utf-8'
IF @hResult <> 0
BEGIN
-- print 'error setting request header'
EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
SELECT hResult = convert(varbinary(4), @hResult),
source = @source,
description = @desc,
FailPoint = 'SetRequestHeader failed',
MedthodName = @methodName
goto destroy
return
END

---- set soap action
--print 'set soap action '
--EXEC @hResult = sp_OAMethod @objectID, 'setRequestHeader', null, 'SOAPAction', @SoapAction
--IF @hResult <> 0
--BEGIN
-- print 'error setting soap action '
-- EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
-- SELECT hResult = convert(varbinary(4), @hResult),
-- source = @source,
-- description = @desc,
-- FailPoint = 'SetRequestHeader failed',
-- MedthodName = @methodName
-- goto destroy
-- return
--END

declare @len int
set @len = len(@requestBody)

--print 'send request body'
EXEC @hResult = sp_OAMethod @objectID, 'setRequestHeader', null, 'Content-Length', @len
IF @hResult <> 0
BEGIN
--print 'sending request body failed'
EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
SELECT hResult = convert(varbinary(4), @hResult),
source = @source,
description = @desc,
FailPoint = 'SetRequestHeader failed',
MedthodName = @methodName
goto destroy
return
END

--print 'send the request'
EXEC @hResult = sp_OAMethod @objectID, 'send', null, @requestBody
IF @hResult <> 0
BEGIN

EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
SELECT hResult = convert(varbinary(4), @hResult),
source = @source,
description = @desc,
FailPoint = 'Send failed',
MedthodName = @methodName
--print 'error sending the request '
goto destroy
return
END
declare @statusText varchar(1000), @status varchar(1000)

--print 'Get status text'
exec sp_OAGetProperty @objectID, 'StatusText', @statusText out
exec sp_OAGetProperty @objectID, 'Status', @status out

-- select @status, @statusText, @methodName

exec sp_OAGetProperty @objectID, 'responseText', @responseText out
--print convert(varchar(10),@hresult)

IF @hResult <> 0
BEGIN

EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
--print 'error getting response text'
SELECT hResult = convert(varbinary(4), @hResult),
source = @source,
description = @desc,
FailPoint = 'ResponseText failed',
MedthodName = @methodName
goto destroy
return
END

destroy:
exec sp_OADestroy @objectID
--print 'destroying'
</code>```

答:
You wouldn't want this. I can see a few reasons why this might be desirable, running a web query to fetch data in a trigger might be a nice idea, or returning data from a web service in response to a select call when reading data.

But these are all flawed, mainly because they all block the state of the DB whilst they are running - if inserting data fetched from a web query, until it returns your data is in an intermediate state. If reading data, it would block your query connection until it completed.

Both are bad. So put it where its supposed to be - the middle tier server and fetch data from both web service and DB and combine the data together afterwards, like how normal people do it :)


问:
How to deal with no code reviews in my new place when I come from that practice?
The team in my new company does not have a code review process.

I come from companies with code review as a must culture and thus I don't feel comfortable committing my code without having it reviewed by someone.

I'm a firm believer that code review is a way to improve quality and save time because it catches potential problems earlier (note I am not talking about pair programming though).

How can I show that code review is not a time waster but a time saver?

Can code review be skipped if you have unit tests?

答:
Disclaimer: This answer is my personal experience :)

I made very bad experiences with code reviews in code that we maintain. Because we usually have only one liners or so and there is not much to review.

But in actual projects I made good experiences, in my examination time my trainer reviewed my code regulary and it helped me a lot to find some mistakes I made very often, that I don't do anymore.

So I would say it highly depends on what are you doing, how many people you are etc.

Also the risk that your codereviews end in a war is not to underrate.

ContentLicense: CC BY-SA 3.0


问:
OOP: relying on protected properties in a class-subclass contract
I'm coding in Python, but the question seems independent of programming language.

I have a class that represents some system check:

```<code>class Check:
   @abstractmethod
   def run()
     """ You have to define your own run(). As a result, it must set self._ok. """
      ...

   @property
   def is_ok():
      return self._is_ok
</code>```

Then we have a set of checks by subclassing Check class, and they're used in the following way (simplified):

```<code>class Checker:
    checks = [check1, check2...]

    def __call__(self):
        for check in self.checks:
            if not check.is_ok:
                alarm()
</code>```

The question is: Is it fine to oblige subclass to set some protected object attributes?

答:
Why wouldn't it be okay to require subclasses to do work? The parent is abstract, after all.

The more important question is: why is run() supposed to signal success via an out-of-bound mechanism (setting a global variable) rather than a return value? There are sometimes reasons for doing this (e.g. because it's an extremely entrenched convention, like errno in C), but usually it's a bad sign because of issues with concurrency, maintainability etc.


答:
To provide an alternative to letting the value be set by the subclass you can instead have them provide a doRun that returns true/false to signify success and the run assigns that result to self._ok, this also allows more checks like catching exceptions or ensuring it only runs once:

```<code>class Check:
   @abstractmethod
   def doRun()
     """ You have to define your own doRun(). As a result, it must return whether it was successful. """
      ...

   def run()
     if not is_ok """ runs once, remove if not needed """
         self._ok = doRun()

   @property
   def is_ok():
      return self._is_ok
</code>```

Title: OOP: relying on protected properties in a class-subclass contract

Body:
I'm coding in Python, but the question seems independent of programming language.

I have a class that represents some system check:

```<code>class Check:
   @abstractmethod
   def run()
     """ You have to define your own run(). As a result, it must set self._ok. """
      ...

   @property
   def is_ok():
      return self._is_ok
</code>```

Then we have a set of checks by subclassing Check class, and they're used in the following way (simplified):

```<code>class Checker:
    checks = [check1, check2...]

    def __call__(self):
        for check in self.checks:
            if not check.is_ok:
                alarm()
</code>```

The question is: Is it fine to oblige subclass to set some protected object attributes?

Body:
To provide an alternative to letting the value be set by the subclass you can instead have them provide a doRun that returns true/false to signify success and the run assigns that result to self._ok, this also allows more checks like catching exceptions or ensuring it only runs once:

class Check:
   @abstractmethod
   def doRun()
     """ You have to define your own doRun(). As a result, it must return whether it was successful. """
      ...

   def run()
     if not is_ok """ runs once, remove if not needed """
         self._ok = doRun()

   @property
   def is_ok():
      return self._is_ok


问:
GPL Copyright notice in fork of dual licenced software when copyright of original has been sold subsequently
Since 2009 we are developing a fork of a CMS that was started in 1999 as commercial project, but released 2009 additionally under GPL. The original programmer sold copyright, code, name and website in 2012 to a new owner (who is now using the name and website because they have a high google pagerank).

Should our copyright notice be:

@copyright 1999-2009 name of original programmer

@copyright 2009-2014 our names

or

@copyright 1999-2009 name of new copyright owner

@copyright 2009-2014 our names

答:
Assumed your current version is based on the newest 2014 version from the new owner (with some additional contributions from yourself), you should copy the original copyright notice from this version and add a notice that the additional contributions are yours.

For example: I guess in the original version of 2014 there is something like:

```<code>@copyright 1999-2012 name of original programmer
@copyright 2012-2014 name of new copyright owner
</code>```

then your new copyright notice should be something along the line of this:

```<code>This file is part of Fork XYZ
@copyright 2009 your name

This file incorporates work covered by the following copyright and permission notice:
@copyright 1999-2012 name of original programmer
@copyright 2012-2014 name of new copyright owner
</code>```

(this is no legal advice, and IANAL.) See this former SO post for a more contrived example.

Body:
Assumed your current version is based on the newest 2014 version from the new owner (with some additional contributions from yourself), you should copy the original copyright notice from this version and add a notice that the additional contributions are yours.

For example: I guess in the original version of 2014 there is something like:

@copyright 1999-2012 name of original programmer
@copyright 2012-2014 name of new copyright owner

then your new copyright notice should be something along the line of this:

This file is part of Fork XYZ
@copyright 2009 your name

This file incorporates work covered by the following copyright and permission notice:
@copyright 1999-2012 name of original programmer
@copyright 2012-2014 name of new copyright owner

(this is no legal advice, and IANAL.) See this former SO post for a more contrived example.


问:
Designing a system to archive databases with referential integrity
I have a very large Oracle database, with many many tables and millions of rows. I need to delete some of the rows end-to-end. By end-to-end, I mean, if I want to delete a row from a table then I must delete all the corresponding records in child tables first and ensure that deletion happens without any constraint violation errors while deleting the parent table entry.

As an example:

```<code>Table A defines dependency over Table B and Table C (means Table A has foreign key constraint on Table B and Table C).
Table B defines dependency over Table C and Table D.
</code>```

I want do delete rows in this specific order something like this:

Table A<=Table B<=Table C<=Table D

I have come up with two approaches:

Using a service API which takes parent table rowID and archives whole data in JSON format and keeps on deleting the entry using cascade option.

Other option is to use delete-with-cascade along with triggers to save the deleted values.

Once data is fetched, I want to better put it in similar archived tables Table_A_archived, Table_B_archived etc or If it could be fetched in file, that is fine too.

Any thoughts on initial approaches will be really valuable. If anyone has done this sort of thing before, it will be great to learn from their experience.

Just FYI, this is a live database and I can't do absurd things (I can obviously test it before pushing it to prod :)). Also, deletion/archival is not just on the basis of time.

Thanks in advance!

答:
Use archive tables, and use a trigger to archive the record into the archive table. These triggers can be generated programmatically from the table definition.

Then you can just delete the records with the cascade option, and know that the archive is being created automatically.


答:
This is venturing close to a request for legal advice, which we can't give. If you want to be really sure what is legally correct, consult a real lawyer.

The way that copyright statements are generally used is that the initial copyright statement indicates who owned the copyright at the time that a work was created, with a year of creation.

If the work is subsequently modified by the same copyright holder, then the list of years in the copyright statement can be extended to include the year of the modification.

If the work is modified by someone else (person, corporation, etc.) who can claim copyright on the modifications, then a new copyright line is added with the name of the copyright holder for the modifications and the year of change.

The basic principle is that you don't modify copyright statements, except to add additional years of modification to your copyright statement.

When forking a repository, you should leave the original copyrights intact and only add your copyright if and when you make changes to a file.

Thus, if you originally forked in 2010 and have not taken over new material from the original repository and only made a change in 2013, the copyright should look like:

```<code>@copyright 1999-2010 name of original programmer
@copyright 2013 your names
</code>```

In most copyright licenses it is not a strict requirement, but it is usually appreciated if you explicitly state which project you forked from and to change references to the project name to the name of your fork in files you changed to avoid confusion with the original if the file is seen in isolation.

Title: GPL Copyright notice in fork of dual licenced software when copyright of original has been sold subsequently

Body:
Since 2009 we are developing a fork of a CMS that was started in 1999 as commercial project, but released 2009 additionally under GPL. The original programmer sold copyright, code, name and website in 2012 to a new owner (who is now using the name and website because they have a high google pagerank).

Should our copyright notice be:

@copyright 1999-2009 name of original programmer

@copyright 2009-2014 our names

or

@copyright 1999-2009 name of new copyright owner

@copyright 2009-2014 our names

Body:
This is venturing close to a request for legal advice, which we can't give. If you want to be really sure what is legally correct, consult a real lawyer.

The way that copyright statements are generally used is that the initial copyright statement indicates who owned the copyright at the time that a work was created, with a year of creation.

If the work is subsequently modified by the same copyright holder, then the list of years in the copyright statement can be extended to include the year of the modification.

If the work is modified by someone else (person, corporation, etc.) who can claim copyright on the modifications, then a new copyright line is added with the name of the copyright holder for the modifications and the year of change.

The basic principle is that you don't modify copyright statements, except to add additional years of modification to your copyright statement.

When forking a repository, you should leave the original copyrights intact and only add your copyright if and when you make changes to a file.

Thus, if you originally forked in 2010 and have not taken over new material from the original repository and only made a change in 2013, the copyright should look like:

@copyright 1999-2010 name of original programmer
@copyright 2013 your names

In most copyright licenses it is not a strict requirement, but it is usually appreciated if you explicitly state which project you forked from and to change references to the project name to the name of your fork in files you changed to avoid confusion with the original if the file is seen in isolation.


问:
How do Event Bus and ReativeX interact with each other?
I wanted to look into communication/decoupling patterns and how to improve them.

My current approach is to have a centralized commander in the form of an Event Bus and make him be the one to respond to most external interactions, like UI or network. Whenever a new event pops up, the receiver callback sends a signal to the bus, which spreads it to the receivers. The message contains all the contextual elements needed to respond to that signal, making the receiver orchestrator only having to deal with processing and rendering those changes.

Example: my program is connected through a socket to a live stocks
  feed. Whenever a new stock arrives, it parses the payload into an
  object and signals the bus with it. My current window is subscribed for that
  event and whenever it gets signaled, it looks for the event payload in
  its internal list and applies any value changes on screen.

One shiny new technology that's getting attention lately is Reactive. If I understand it correctly, in this new paradigm every piece of information is considered a flow over time, in which we have an observable component that we subscribe to, and every time it gets signalled you can just process it. This observable piece of information can be referenced (injected?) in as many classes as wanted.

Are there any advantages from an architectural perspective from using ReactiveX having Buses?

答:
It's not really a question of one or the other. They can easily be combined.

The idea behind reactive streams (or whatever you may want to call them) is not exactly new in the functional world. The basic motivation behind it is to make composition easy. You can operate on streams the same as you would on values. So for example you could take the value of a text field and see that as a stream, then transform that stream by having each value be used as a search term over some search database, then transform that stream of search result lists to a stream of UI components and then just use that stream as the content of a window. So you have a lot of transformations from one data type to another, which can be written in complete isolation and then you wire that up. The contracts are pretty small. You can quite easily substitute the search term -> search result list transformation for another one, that uses a cache, or a different database or search strategy or what not.

The idea behind event buses is that events can travel pretty freely through your system and it makes it easy to plug behavior onto those events. Although that can just as easily become a big mess. In some sense you are just creating a loosely typed system here. You have no straight forward way of knowing whether events you subscribed for are ever fed onto the bus, or whether events that you trigger are ever consumed. Or whether a conflict
occurs and so on. So event buses have their strengths and weaknesses.

None the less, the two concepts are orthogonal. You can take a stream and feed it into an event bus, and you can take specific events from an event bus and produce a stream from them.

So you could say reactive streams are about how you transform data in events, and event buses are about how the events get from one subsystem to another.


问:
Scrum: Is it okay for the development manager to be the Product Owner
My company is going through an agile rollout and is currently considering options for what that means.

The ScrumMaster role is somewhat straightforward, but Product Owner has many candidates: Product Managers, UX, Software Analysts. The favored candidate for the moment is for each development manager to be the team Product Owner.

However, using development managers as product owners seems like it will discourage self-organization.  What's the "right" way to select product managers in an Agile way?

答:
As @Contrarian mentioned, the Product Owner needs to understand the requirements and is usually involved in a business perspective with clients or Product Managers who are influencing the overall product releases. Prioritization is a key feature here as well, so this person needs to be granted the power to decide on priority of what to do.

In most situations, a Business Analyst makes the jump to a Product Owner very easily. If you currently have somebody playing this role, they make a great PO.

In some organizations, however, the requirements are actually clarified to the team by an architect who has an overall vision of the product or of a particular module/component of the product. These individuals can act as the Product Owner and can help with prioritization, though they may not necessarily be involved in the business/client-facing side traditionally.

As for using a team's direct development manager, I would caution against this. It is one thing to have a colleague informing you of priorities and representing the client's needs, and quite another to have your boss doing it.

Imagine your colleague tells you: "Jay, the buttons here aren't going to work for the client. They don't match the branding guidelines." You can have a conversation about it, go back to your work, and ship out something new for a review.

Now put your boss in that place. Suddenly it's no longer about a conversation to get to the right deliverable and is now about performance. You will avoid showing things early on to get feedback because you might look bad to your boss. You will not necessarily be honest about what you are building or how much you have left. An agile team needs to be transparent to each other so that they can react and adjust.

That being said, we have put development managers in some of our teams, just not as the Product Owner. We will have them involved as a team member who happens to also be providing technical advice or support to the Product Owner and Scrum Master. This allows their knowledge and access to other levels of the organization to be a tool that the team can use, without them being able to have complete control over all aspects of the sprint.


答:
Stop worrying about it - your new employer just doesn't care about code reviews.  Learn to have some confidence in your own abilities without someone else telling you it's OK to check in the code you've written. You'll soon learn to live without the mind-numbingly tedious process that is reviewing other people's code.

Follow the style guidelines (or just the style) that everybody else uses.  Use your experience to decide what needs commenting, what naming conventions to use and so on.

Then test everything before you check it in.  The most important thing is that it works correctly.

Title: How to deal with no code reviews in my new place when I come from that practice?

Body:
The team in my new company does not have a code review process.

I come from companies with code review as a must culture and thus I don't feel comfortable committing my code without having it reviewed by someone.

I'm a firm believer that code review is a way to improve quality and save time because it catches potential problems earlier (note I am not talking about pair programming though).

How can I show that code review is not a time waster but a time saver?

Can code review be skipped if you have unit tests?


答: If your new employer doesn't like the idea of code reviews, it may be because they have a negative association with old-fashioned command and control type methodologies and they're aiming for a more modern, agile type set of practices. In this case, they may be more open to the idea of pair programing, which provides many of the same benefits, and is widely regarded as a more dynamic, modern practice.</p>


问:
Why do people disable JavaScript?
I asked a question yesterday Should I Bother to Develop For JavaScript Disabled?. I think the consencus is: Yes, I should develop for JavaScript Disabled. Now I just want to understand why users disable JS. It seems many developers (I guess people who answered the questions are developers) disable JS. Why is that. Why do users disable JS? For security? Speed? or what?</p>

答:
I disable JS for speed reasons. TechCrunch without JavaScript takes a few seconds to load with a primed cache. With JavaScript it takes almost 20 seconds, more if the cache isn't primed.

Lots of sites have become bloated with JavaScript, especially image galleries and commerce sites. Removing this gives you a better browsing experience in most cases.

ContentLicense: CC BY-SA 2.5

Title: Why do people disable JavaScript?


问:
Best practice for accessing data from an external legacy ERP system
I have an architectural problem, and would be glad to receive some consultancy :). The application I am developing (let's call it system A) is responsible for management of work groups, where these groups have a leader, a set of members, roles, categories etc.

The information about the people who will become the group members come from another application (system B), which is legacy, was developed by an external company, and will not be replaced any time soon. This system maintains records of every employee in my company (about 300,000+), and is one day per month very busy processing the payment bill of these employees. System A can obtain the employee information through SOAP Web Services developed by System B, but these web services are slow, and not very scalable.

The problem is, some operations in system A (like querying which employees do not belong to any group) do need to check every employee available in System B. Therefore, in order to avoid the performance bottlenecks related to directly obtaining these data from B's web services, I thought in the following solutions:

The slow operations would be performed in background by a parallel thread every two hours and the results would be cached. This reduces the number of times A would need to access B's web services, but every query performed on system A would be, in the worst case, two hours out of date.

One time per day, during the non-busy hours (i.e. midnight), a job would query system B for employee data and store on system A database. This would avoid querying B's web services every time the same info was needed, and since the number of employees from B didn't need to be updated quickly, a single day delay wouldn't be a problem. The issue in this case is duplication of data on two systems.

Giving direct access to B's database to system A. This would eliminate any delay related to remote communication, and opens the doors for many database optimizations. The problem of this solution is high coupling between two systems (not very SOA-like) and operations on system A would increase the performance burden on system B.

I would appreciate opinions about these three solutions, if anyone experienced the same problem, and would be all ears for a 4th solution.

答:
1 of course would most likely be the easiest option to implement.

2 is a reasonably common practice to help deal with slow or hard to deal with systems.  And your right it does duplicate the data, so you would need to have the policy that System B is the authority and A should be used as 'read only'.

I personally would go for option 3, with slight modifications.  I would replace the Web Service calls with an interface (dll) that goes directly to System B and have System A make calls to it. So still keeping the systems separate but giving you a better window into the system and more control.


问:
How to reuse common code between presenters
In my application there are 2 views both have 70% common fields like name, icon etc. One view is about list( contains 2-3 fields). On clicking the list  , the next view which is the details should be called.

Other functionality in both views is same. e.g while loading , presenter will be called to load data from the url. (The URL for both  views is different).
The common functionality includes
1. Load XML data from URL
2. Set the loading progress bar in activity
3. Removing the progress bar.
3. 50% methods for setting the activity views will be common.
4. Call the xml parser

The differences will be view specific:
1. The fields are only 50% common.
2. the action on button click

My doubt is shall I use 2 presenters or one presenter for both the views. Many methods are different , while many are same in the 2 presenters.

Which is the correct design strategy?:
1. Shall I use helper class
2. Shall both presenters have the same base class.
3. Shall i use the startegy pattern?
 What is the right way to do it in MVP? Or all are correct.

答: On Ruby I would either include a third class that shares the common code between both presenters or delegate, depending on how much shared code and what dependencies the presenters have. Probably by you description I would make the ListPresenter delegate to the DetailsPresenter whether methods they have in common.</p>


问:
Holding of files being edited in a text editor
I'm writing an implementation of Ex (hopefully Vi eventually) as a personal project. I need to somehow store an identifier for the file associated with each buffer. In terms of security/race conditions and performance (and convention, if there is one), should I store the name of the file as given by the user, the file descriptor as returned by open(), or the file pointer as returned by fopen()/fdopen()?

These are the methods I came up with, but I'm entirely open to any others.

答:
After further thought (and your comment), I realise there's a solid behavioural basis for choosing.

If I:

open an existing file in your editor

begin altering it

realise I want a backup and move (not copy) the original

save my modifications

should it alter the backup (the original inode with a new name)? Or write the altered file to the original name, leaving the backup alone?

I think the latter, which implies it shouldn't keep the original file open as it won't be able to use that file descriptor/FILE* safely anyway. You might decide you want different behaviour, though.

Well, what state do ex (or vi) need to track for each file?

Off the top of my head, vim needs:

file name

file descriptor or FILE*

could this be -1 or NULL if it isn't open? (are files in the buffer list held open even when not displayed? I don't know, but it might be reasonable to close files and preserve an entry for them)

swapfile - should the fd above refer to this? do we need to track the swapfile name as well?

modification state

last read stat of the original file (so you can tell if it changed before overwriting)

or maybe just an "underlying file has changed" flag, if you want to use file change notifications

whether it's read-only or read-write (you could just try to write and get an error, but ... ick)

line-ending convention, encoding

Note that I can have multiple buffers looking at different positions in the same file, and possibly with different settings (syntax highlighting, line numbers etc.) so those can't be properties of the file itself.

Now, unless you can robustly infer all that from a single file descriptor, I think you need some struct storing all of that (and possibly more).


问:
Why does the US government disallow dynamic languages for secure projects?
I know some people that are currently working on a project for the US military (low security level, non-combat human resources type data).

An initial state of the project code was submitted to the military for review, and they ran the program through some sort of security analyzer tool. It returned a report of known security issues in the code and required changes that needed to be implemented before delivery of the final product.

One of the items that needed to be resolved was removal of part of the project that was written in Ruby as it is a dynamic language.

What is the background/reason for not allowing a dynamic language to be used in a secure setting? Is this the government being slow to adopt new technologies? Or do dynamic languages pose an additional security risk compared to static languages (ala C++ or Java)?

答:
I'd like to add to the existing answers by describing Drupal's SA-CORE-2014-005, which is a highly critical vulnerability which enables SQL injection and ultimately arbitrary code execution. It is caused by PHP's dynamic typing and lax runtime typing rules.

The entirety of the patch for this issue is:

```<code>-      foreach ($data as $i => $value) {
+      foreach (array_values($data) as $i => $value) {
</code>```

This code is part of an SQL abstraction layer designed to prevent SQL injection. It takes an SQL query with named parameters, and an associative array which provides a value for each named parameter. The value is allowed to be an array, for cases like WHERE x IN (val1, val2, val3), where all three values can be passed in as a single array value for a single named parameter.

The vulnerability occurs because the code assumes that $i in $i => $value must be an integer index of the value. It goes on and concatenates this "index" directly into the SQL query as part of a parameter name, because integers don't need any escaping, right?

Unfortunately for Drupal, PHP does not provide such a guarantee. It's possible to pass in another associative array, whose keys are strings, and this loop will happily concatenate the string key into the query, as-is (remember the code thinks it can only ever be an integer).

While there are ways to have a similar error in a statically typed language, they are unlikely. A good developer would consider what possible things $i could be before concatenating it into the query. With a statically typed language, it's very easy to enforce that $i must be an integer, and in security sensitive code like this, that would most certainly be done.

Furthermore, the code actually checks whether the value is an array before iterating over the items. And herein lies a second part of the fail that enables this vulnerability: both an associative array and a "normal" array return true for is_array. While it's also true that in C#, both dictionaries and arrays are IEnumerable, it is difficult to construct code which would conflate dictionary keys with array indices like this even intentionally, let alone accidentally.

Body:
I'd like to add to the existing answers by describing Drupal's SA-CORE-2014-005, which is a highly critical vulnerability which enables SQL injection and ultimately arbitrary code execution. It is caused by PHP's dynamic typing and lax runtime typing rules.

The entirety of the patch for this issue is:

-      foreach ($data as $i => $value) {
+      foreach (array_values($data) as $i => $value) {

This code is part of an SQL abstraction layer designed to prevent SQL injection. It takes an SQL query with named parameters, and an associative array which provides a value for each named parameter. The value is allowed to be an array, for cases like WHERE x IN (val1, val2, val3), where all three values can be passed in as a single array value for a single named parameter.

The vulnerability occurs because the code assumes that $i in $i => $value must be an integer index of the value. It goes on and concatenates this "index" directly into the SQL query as part of a parameter name, because integers don't need any escaping, right?

Unfortunately for Drupal, PHP does not provide such a guarantee. It's possible to pass in another associative array, whose keys are strings, and this loop will happily concatenate the string key into the query, as-is (remember the code thinks it can only ever be an integer).

While there are ways to have a similar error in a statically typed language, they are unlikely. A good developer would consider what possible things $i could be before concatenating it into the query. With a statically typed language, it's very easy to enforce that $i must be an integer, and in security sensitive code like this, that would most certainly be done.

Furthermore, the code actually checks whether the value is an array before iterating over the items. And herein lies a second part of the fail that enables this vulnerability: both an associative array and a "normal" array return true for is_array. While it's also true that in C#, both dictionaries and arrays are IEnumerable, it is difficult to construct code which would conflate dictionary keys with array indices like this even intentionally, let alone accidentally.


问:
What is meant by the term 'System requirement' and how does that relate to 'Functional requirement'?
What is the difference between a Functional Requirement and a System Requirement?

As I know, the term 'Functional requirement' refers to a requirement which describes a function that needs to be implemented to solve a problem.

But what is meant by the term 'System requirement' and how does that relate to 'Functional requirement'?

答:
In the context of requirements engineering, the concept of a "system requirement" is referring to a level of decomposition. In a sufficiently complex system, you could have any number of components (where a component could be hardware or software elements). Each component would have its own requirements, usually derived from the system requirements, that can be used to verify the behavior of the component in isolation prior to integration and verification and validation of the system as a whole throughout the integration process.

In the comments, Robert Harvey mentions another type of "system requirements": the required characteristics of the system that the software is being deployed on. These often include the hardware, operating system, and maybe even software dependencies. These would often be based on the technical system requirements that I mentioned above.

A functional requirement is a definition of a result of the system. The set of functional requirements on a system or component define what the system does. The opposite of a functional requirement is a non-functional requirement, which define attributes of a system, such as reliability, fault tolerance, documentation, security, testability, etc.

System requirements can be functional or non-functional, and define the behavior and attributes of a set of components.


问:
Cleanest choice for symmetric operations
I have a need to do some processing from a format A to a format B and from B to A. The job in one direction is very similar to its counterpart. Both formats are represented with an interface Msg.

In such a case, I can see four obvious solutions, which is the cleanest? I hope there are some concrete principles explaining one choice over the others and not just personal preferences

Here are the obvious choices

1) Different classes for each

```<code>public class TransformToA {
   public TransformToA() {
       ...
   }
   public Msg transform(Msg incoming) {
       ...
   }
}
public class TransformToB {
   public TransformToB() {
       ...
   }
   public Msg transform(Msg incoming) {
       ...
   }
}
</code>```

Note that in this option, I could extract some common logic into a third common class to avoid code duplication

2) A boolean field to define the direction

```<code>public class Transformer {
   private boolean toBFormat;
   public Transformer(boolean toBFormat) {
       ...
   }
   public Msg transform(Msg incoming) {
       if (toBFormat) {
          ...
       } else {
          //to A format
       }
   }
}
</code>```

3) a boolean flag on the method (this is probably the worst since the caller is forced to pass the flag every single time and makes a method behave in two different ways)

```<code>public class Transformer {
   public Transformer() {
       ...
   }
   public Msg transform(Msg incoming, boolean toBFormat) {
       if (toBFormat) {
          ...
       } else {
          //to A format
       }
   }
}
</code>```

4) Two different methods

```<code>public class Transformer {
   public Transformer() {
       ...
   }
   public Msg transformToA(Msg incoming) {
       ...
   }
   public Msg transformToB(Msg incoming) {
       ...
   }
}
</code>```

答:
You're describing a sort of copy constructor:  using one Msg instance to construct another.  I would implement it as such, finding another place to put common helper functionality.

```<code>public class A implements Msg {
  public A(Msg msg){...}
}

public class B implements Msg {
  public B(Msg msg){...}
}
</code>```

However, you've been vague about your reasons for doing the transformation, and I suspect there's another issue going on.  It feels like you might be trying to do too much in the A and B classes.  Perhaps you should split Msg into its own class that acts only as a model, then have A and B act more as a view, with only the functionality where it matters what format it's in.

For example, if Msg was a spreadsheet document, and A and B are Excel or OpenDocument formats, then you would want to do the vast majority of your work in your internal Msg format, and only create an A or B when you're reading or writing your document to disk.

Body:
You're describing a sort of copy constructor:  using one Msg instance to construct another.  I would implement it as such, finding another place to put common helper functionality.

public class A implements Msg {
  public A(Msg msg){...}
}

public class B implements Msg {
  public B(Msg msg){...}
}

However, you've been vague about your reasons for doing the transformation, and I suspect there's another issue going on.  It feels like you might be trying to do too much in the A and B classes.  Perhaps you should split Msg into its own class that acts only as a model, then have A and B act more as a view, with only the functionality where it matters what format it's in.

For example, if Msg was a spreadsheet document, and A and B are Excel or OpenDocument formats, then you would want to do the vast majority of your work in your internal Msg format, and only create an A or B when you're reading or writing your document to disk.


答:
One commonly (albeit not universally) accepted principle of object design is that an object should be immutable unless this makes the design substantially more complex. Immutable objects are easier to reason about, can be used in a multithreaded environment more easily and are generally less prone to bugs.

From the code you have shown us, there is no reason I can see why you need mutable objects, so I would use immutable ones.


问:
How to avoid spaghetti code when I have a lot of conditions?
I have the following problem:

An user can withdraw money from 2 payment systems (but the number of payment systems can change anytime in the future).

If user has a trusted account on either of these payment systems, money is transfered automatically

If user enters a new account then he needs to wait until the end of month to be able to transfer money to this account.

Suposse we have payment systems X and Y. There exist all the following information items:

We can do auto withdraw X (1 - Yes/0 - No)- column 1.

We can do auto withdraw Y (1 - Yes/0 - No) - column 2.

We have deficit of X (1 - Yes/0 - No) - column 3.

We have deficit of Y (1 - Yes/0 - No) - column 4.

User has trusted account of X (1 - Yes/0 - No) - column 5.

User has trusted account of Y (1 - Yes/0 - No) - column 6.

User can auto-withdraw X (1 - Yes/0 - No) - column 7.

User can auto-withdraw Y (1 - Yes/0 - No) - column 8.

User can withdraw X in end of month (1 - Yes/0 - No) - column 9.

User can withdraw Y in end of month (1 - Yes/0 - No) - column 10.

In table bellow I tried to show all use cases:

Column 1; Column 2; Column 3; Column 4; Column 5; Column 6; Column 7; Column 8; Column 9; Column 10

```<code>1; 1; 0; 0; 1; 1; 1; 1; 0; 0

1; 1; 1; 0; 1; 1; 0; 1; 1; 0

1; 1; 0; 1; 1; 1; 1; 0; 0; 1

1; 1; 1; 0; 1; 0; 1; 0; 0; 1

1; 1; 0; 1; 0; 1; 0; 1; 1; 0

1; 1; 1; 1; 1; 1; 0; 0; 1; 1

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

Please advise how can I avoid a lot of ifs?

答:
As I don't see any language specified, use 'switch'.
-Or if using C, you can make a function that handles each account type, then make a list of function pointers.

```<code>typedef void (*Account)(uint32_t aParameter);
static const Account[] = { mondoBurger, goodBurger };
</code>```

-If using C++, JavaScript or any other OOP language, you could make an object that handles each account type.

The bottom line is: You can use modular code.
One "handler" (whether it be a function or an object) for an account.
One "handler" for each action type that can be made.

Thus you just install the handlers in a list and hands the list to the processing function.

Body:
As I don't see any language specified, use 'switch'.
-Or if using C, you can make a function that handles each account type, then make a list of function pointers.

typedef void (*Account)(uint32_t aParameter);
static const Account[] = { mondoBurger, goodBurger };

-If using C++, JavaScript or any other OOP language, you could make an object that handles each account type.

The bottom line is: You can use modular code.
One "handler" (whether it be a function or an object) for an account.
One "handler" for each action type that can be made.

Thus you just install the handlers in a list and hands the list to the processing function.


答:
One disables JavaScript in a browser environment because of the following considerations:

Speed & Bandwidth

Usability & Accessibility

Platform Support

Security

Speed & Bandwidth

A lot of applications use way too much JavaScript for their own good... Do you need parts of your interface to be refreshed by AJAX calls all the time? Maybe your interface feels great and fast when used with a broadband connection, but when you have to downgrade to slower connection speeds, a more streamlined interface is preferred. And switching off JavaScript is a good way of preventing dumb-struck web-apps of refreshing the world every 15 seconds or so for no good reason. (Ever looked at the amount of data Facebook sends through? It's scary. It's not only a JS-related issue though, but it's part of it).

We also tend to off-load more and more of the processing to the client, and if you use minimalistic (or just outdated) hardware, it's painfully slow.

Usability & Accessibility

Not all user interfaces should expressed in a dynamic fashion, and server-generated content
might be perfectly acceptable in many cases. Plus, some people simply don't want this type of interfaces. You cannot please everybody, but sometimes you have the chance to and the duty to satisfy all your users alike.

Finally, some users have disabilities, and thou shalt not ignore them, ever!!!

The worst-case scenarios here, in my opinion, are government websites that try to "modernize" their UIs to appear more friendly to the public, but end up leaving behind a big chunk of their intended audience. Similarly, it's a pity when a university student cannot access his course's content: because he/she is blind and his screen-reader doesn't support the site, or because the site is so heavy and requires ad-hoc modern plug-ins that he/she doesn't get to install on that refurbished laptop bought on e-bay 2 years ago, or again because he/she goes back home to another country for the spring break and the local bandwidth constraints cannot cope with the payload of the site.

Not everybody lives in a perfect world.

Platform Support

This point relates to the 2 previous ones and tends to be less relevant nowadays, as browsers embed JavaScript engines that are a level of magnitude more efficient than they used to be, and this keeps getting better.

However, there's no guarantee that all your users have the privilege of using modern browsers (either because of corporate constraints - which force us to support antediluvian browsers for no good reason, really - or other reasons which may or may not be valid). As mentioned by "Matthieu M." in the comments, you need to remember that a lot of people still use lower-quality hardware, and that not everybody uses the latest and coolest smartphone. As of today, there are still a significant portion of people using phones that have embedded browsers with limited support.

But, as I mentioned, things do get better in this area. But then you still need to remember the previous points about bandwidth limitations if you keep polling very regularly (or your users will enjoy a nice phone bill).

It's all very inter-related.

Security

While obviously you could think that nothing particularly dangerous can be done with JavaScript considering it runs in a browser environment, this is totally untrue.

You do realize that when you visit P.SE and SO you are automatically logged in if you were logged on any other network, right? There's some JS in there. That bit is still harmless though, but it uses some concepts that can be exploited by some malevolent sites. It is completely possible for a website to use JavaScript to gather information about some things you do (or did) during your browsing session (or the past ones if you don't clear your session data every time you exit your browser or run the now common incognito/private browsing modes extensively) and then just upload them to a server.

Recent vulnerabilities (working in major browsers at the time) included the ability to gather your saved input forms data (by trying out combinations for you on a malevolent page and recording the suggested texts for each possible starting letter combinations, possibly telling attackers who you are, where you work and live) or to extract your browsing history and habits (A very clever hack doing something as simple as injecting links into the page's DOM to match the color of the link and see if it's been visited. You just need to do this on a big enough table of known domain names. And your browser getting faster at processing JavaScript, this type of thing gets done quickly.)

Plus let's not forget that if your browser's security model is flawed, or the websites you visit don't protect themselves when enough against XSS attacks, then one might use JavaScript to simply tap into your open sessions on remote websites.

JavaScript is mostly harmless... if you use it for trusted websites. Gmail. Facebook (maybe... and not even...). Google Reader. StackExchange.

But yeah sure, JavaScript cannot be that bad, right? And there are scarier things to fear online anyway. Like thinking you're anonymous when you really aren't that much, as shown by the Panopticlick experiment of the EFF. Which is also partly done using JavaScript. You can even read their reasons to disable JavaScript to avoid browser fingerprinting.

All this being said, there might be perfectly good situations where you don't need to bother about supporting JavaScript. But if you offer a public-service website, do consider accepting both types of clients. Personally, I do think a lot of modern web-apps and websites would work just as well using the former server-generated content model with no JavaScript at all on the client side, and it would still be great and possibly a lot less consuming.

Your mileage may vary depending on your project.

Title: Why do people disable JavaScript?

Body: I asked a question yesterday Should I Bother to Develop For JavaScript Disabled?. I think the consencus is: Yes, I should develop for JavaScript Disabled. Now I just want to understand why users disable JS. It seems many developers (I guess people who answered the questions are developers) disable JS. Why is that. Why do users disable JS? For security? Speed? or what?</p>


问:
Managing multiple versions of the same Android Library Project
I have an Android Library Project which I intensively used in a few projects. I started a new project in which I am also using this library. I want to improve some things in library (method signatures\names, interfaces, etc.). But if I change method signatures\names, interfaces, I should update old projects that use this library. That could be hard work.

I want to make new version of my library which will be not compatible with previous versions.

Is this possible without creating new project?

IDE: Android Studio.

答:
You don't need create new project of course. Only Commit/Push project to Git.

Android Studio - GitHub Integration & Sharing Video
Watch on YouTube and create new branches for every version library You have.

It's very easy.

You can also create local subversion repository.

How To connect Android Studio to SVN & Subversion client for Windows


答:
Code reviews have advantages that don't come from the reviewing process itself: There is always a dilemma to get code that is of high quality, but created in a short time. Without code reviews, you're on your own, so you might sacrifice quality for doing the code in a short time. With code reviews, there is this reviewer who doesn't let you get away with low code quality - which is exactly what you want, being forced to spend the time to get quality code which is what you wanted in the first place, and which you know will end up saving time because every hour spent on writing better code is two hours saved on debugging (or more).

Without code reviews, you are on your own, so it's up to you to maintain high code quality. A simple solution is to review every change you make yourself and fix things that are not up to your quality standards.

This also avoids horrible situations where code reviews lead to clashes of egos - the situation where programmer A would use method X, while B would use method Y, so if A writes the code he uses method X, the reviewer B insists on method Y, so A rewrites the code using method Y, while if B had written the code and A reviewed it the exact opposite would have happened.


答:
You could ask your team leader and/or colleague to peer-review your code, even if code reviews aren't done normally, perhaps as part of your training.

Make sure that your code is well-written and tested before the review.

When I was a team leader I used to do code reviews myself of new employees, until (after a while) I would stop finding bugs or anything else to criticize in their code, and which point I would stop doing code reviews with them; that would happen when:

They learned the systems they interfacing with and didn't need my explanations of it

They learned to design and/or test their code until it was bug-free before I saw it

They learned enough about my coding style guidelines that I'd consider their code maintainable

Code reviews have several purposes:

Finding defects in the code

Knowledge transfer between team members

I think it's fine to do code reviews of new employees, even if the team chooses to skip code reviews among the experienced team members.


答:
How a bout a rules mechanism? Define a class(or a struct or whatever) that defines a rule:

```<code>class Rule {
    bool weCanDoAutoWithdrawX;
    bool weCanDoAutoWithdrawY;
    bool WeHaveDeficitOfX;
    bool WeHaveDeficitOfY;
    ...
}
</code>```

Now, create a list of Rules, and fill it with Rule objects that represent the rules you described in the question. When you want to check a transaction, go over that list and check if it matches the rule. If at least one rule does - approve the transaction.

If you are not familiar with OOP you can store the different sets of conditions as strings of concatenated 1s and 0s ("1100111100","1110110110", etc) stored in a string array. Then you can traverse that array. If at least one string matches the actual values - approve the transaction.

Title: How to avoid spaghetti code when I have a lot of conditions?

Body:
I have the following problem:

An user can withdraw money from 2 payment systems (but the number of payment systems can change anytime in the future).

If user has a trusted account on either of these payment systems, money is transfered automatically

If user enters a new account then he needs to wait until the end of month to be able to transfer money to this account.

Suposse we have payment systems X and Y. There exist all the following information items:

We can do auto withdraw X (1 - Yes/0 - No)- column 1.

We can do auto withdraw Y (1 - Yes/0 - No) - column 2.

We have deficit of X (1 - Yes/0 - No) - column 3.

We have deficit of Y (1 - Yes/0 - No) - column 4.

User has trusted account of X (1 - Yes/0 - No) - column 5.

User has trusted account of Y (1 - Yes/0 - No) - column 6.

User can auto-withdraw X (1 - Yes/0 - No) - column 7.

User can auto-withdraw Y (1 - Yes/0 - No) - column 8.

User can withdraw X in end of month (1 - Yes/0 - No) - column 9.

User can withdraw Y in end of month (1 - Yes/0 - No) - column 10.

In table bellow I tried to show all use cases:

Column 1; Column 2; Column 3; Column 4; Column 5; Column 6; Column 7; Column 8; Column 9; Column 10

```<code>1; 1; 0; 0; 1; 1; 1; 1; 0; 0

1; 1; 1; 0; 1; 1; 0; 1; 1; 0

1; 1; 0; 1; 1; 1; 1; 0; 0; 1

1; 1; 1; 0; 1; 0; 1; 0; 0; 1

1; 1; 0; 1; 0; 1; 0; 1; 1; 0

1; 1; 1; 1; 1; 1; 0; 0; 1; 1

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

Please advise how can I avoid a lot of ifs?

Body:
How a bout a rules mechanism? Define a class(or a struct or whatever) that defines a rule:

class Rule {
    bool weCanDoAutoWithdrawX;
    bool weCanDoAutoWithdrawY;
    bool WeHaveDeficitOfX;
    bool WeHaveDeficitOfY;
    ...
}

Now, create a list of Rules, and fill it with Rule objects that represent the rules you described in the question. When you want to check a transaction, go over that list and check if it matches the rule. If at least one rule does - approve the transaction.

If you are not familiar with OOP you can store the different sets of conditions as strings of concatenated 1s and 0s ("1100111100","1110110110", etc) stored in a string array. Then you can traverse that array. If at least one string matches the actual values - approve the transaction.


问:
Using public final rather than private getters
I see most immutable POJOs written like this:

```<code>public class MyObject {
    private final String foo;
    private final int bar;

    public MyObject(String foo, int bar) {
        this.foo = foo;
        this.bar = bar;
    }

    public String getFoo() {
        return foo;
    }

    public int getBar() {
        return bar;
    }
}
</code>```

Yet I tend to write them like this:

```<code>public class MyObject {
    public final String foo;
    public final int bar;

    public MyObject(String foo, int bar) {
        this.foo = foo;
        this.bar = bar;
    }
}
</code>```

Note the references are final, so the Object is still immutable.  It lets me write less code and allows shorter (by 5 chars: the get and ()) access.

The only disadvantage I can see is if you want to change the implementation of getFoo() down the road to do something crazy, you can't.  But realistically, this never happens because the Object is immutable; you can verify during instantiation, create immutable defensive copies during instantiation (see Guava's ImmutableList for example), and get the foo or bar objects ready for the get call.

Are there any disadvantages I'm missing?

EDIT

I suppose another disadvantage I'm missing is serialization libraries using reflection over methods starting with get or is, but that's a pretty terrible practice...

答:
Get rid of the getters/setters too, and you're fine!

This is a highly controversial topic amongst Java programmers.

Anyways, there's two situtation where i use public variables instead (!) of getters/setters:

public final To me this signals "I'm immutable" much better than just a getter. Most IDEs will indicate the final modifier with a 'F' during auto-completion. Unlike with getters/setters, where you have to search for the absence of a setXXX.

public non-final I love this for data classes. I just expose all the fields publicly. No getters, setters, constructors. No nothing. Less than a pojo. To me this immediately signals "look, i'm dumb. i hold data, that's all. it's YOUR job to put the right data inside of me". Gson/JAXB/etc. handle these classes just fine. They're a bliss to write. There's no doubt about their purpose or capabilities. And most importantly: You know there are no side effects when you change a variable. IMHO this results in very concise data models with few ambiguities, whereas getters and setters have this huge problem where sometimes magic happens inside of them.


问:
Publishing: Hows and Whos of Peer Reviews
So, I'm sitting here, chewing on a couple of novel data structures.  I'm thinking of coding them up, but I'ven't got any professional use for them at the moment.  Nonetheless, they solve interesting problems, and deserve reference implementations.  So, I'd like to publish them, ideally in a peer-reviewed journal, so there's at least an off-chance someone will run into them and get some use out of it.

But I can't for the life of me figure out how I'd even start to go about such a process, and none of my old professors seem to be in a position to help.  Can I get a primer on how to go about getting something published in a moderately reputable journal?

答:
In computer science, you generally don't immediately send something to a journal. Instead, you find a conference that is relevant to your problem, and send them a write-up of your findings (usually 2-3 pages, check the papers of the last year's conference for length and style of writing). Ideally, the conference papers are peer-reviewed, so that you get at least 1-2 useful comments on your work. Then you go to the conference, and present your work. This ensures that your ideas are being spread to the people who are most likely to be interested in your work, and who are experts enough that you get a lot more interesting/useful feedback.

Finally, if your ideas are well-received, and if you really want to have a publication in a journal, you can submit your longer and more detailed write-up there, but be patient. You will likely have to wait a while for referee comments, and then you might have to do some additional work - if the paper is not rejected, which means that you'll start over with another journal.


问:
Would it make sense to have a database table with only one record for tracking site summary stats?
I'm creating a web site that deals with monetary transactions. Users can deposit funds into a wallet and use them on the site. I'd like to keep track of some stats for the web site, like revenue and balance.

I already have a database table for tracking transactions, but I'd like to also store a summary of all transactions as mentioned above.

If I store these summary figures in my database, I think the table would always have only one row:

```<code>stats
    revenue
    balance
    depositCount
    ... (etc)

transactions  <-- already exists
    id
    transactionType
    userId (optional)
    amount
    balance
    createdAt
</code>```

答:
It seems to me that if you wanted to store that information in a table, you'd have to update that table ever time a transaction occurred. Or update at some regular interval.

If you used a view for that purpose, you could just query the view, and the view would do all the calculations for you.

Since it sounds like your system's volume is heavy enough to cripple an aggregation query even the best-indexed table (and I assume that you'd test this once or twice, just to see), having a table with the aggregate data might be better than constantly querying the source table. The problem that I see is if there are so many transactions in the system, doing a full aggregate every time there is a transaction is probably going to be a problem. So here's another idea I thought of: Have a table where you insert the aggregate data for a smaller time window. For example, every 5 minutes (or every hour, or every day) you run a job that aggregates all transaction data for the last 5 minutes. Then you have your total aggregate query run off of this table.  The downside to this approach is that you don't have real-time stats, you have stats up to the last aggregation.

```
window_aggregates
-----------------
  id
  start_time
  end_time
  revenue
  balance
  tansaction_count
  ...

total_stats_view
----------------
  select sum(revenue) as total_revenue, sum(balance) as total_balance, sum(transaction_count) as total_transaction_count
     from window_aggregates
     /*you could put a where clause here to specify values for start_time and end_time, if you want*/

```

Body:
It seems to me that if you wanted to store that information in a table, you'd have to update that table ever time a transaction occurred. Or update at some regular interval.

If you used a view for that purpose, you could just query the view, and the view would do all the calculations for you.

Since it sounds like your system's volume is heavy enough to cripple an aggregation query even the best-indexed table (and I assume that you'd test this once or twice, just to see), having a table with the aggregate data might be better than constantly querying the source table. The problem that I see is if there are so many transactions in the system, doing a full aggregate every time there is a transaction is probably going to be a problem. So here's another idea I thought of: Have a table where you insert the aggregate data for a smaller time window. For example, every 5 minutes (or every hour, or every day) you run a job that aggregates all transaction data for the last 5 minutes. Then you have your total aggregate query run off of this table.  The downside to this approach is that you don't have real-time stats, you have stats up to the last aggregation.

window_aggregates
-----------------
  id
  start_time
  end_time
  revenue
  balance
  tansaction_count
  ...

total_stats_view
----------------
  select sum(revenue) as total_revenue, sum(balance) as total_balance, sum(transaction_count) as total_transaction_count
     from window_aggregates
     /*you could put a where clause here to specify values for start_time and end_time, if you want*/


问:
How to deal with no code reviews in my new place when I come from that practice?
The team in my new company does not have a code review process.

I come from companies with code review as a must culture and thus I don't feel comfortable committing my code without having it reviewed by someone.

I'm a firm believer that code review is a way to improve quality and save time because it catches potential problems earlier (note I am not talking about pair programming though).

How can I show that code review is not a time waster but a time saver?

Can code review be skipped if you have unit tests?

答:
Taken from some random slides I found, but the hard data comes from Steve McConnell's Code Complete book:

Are Code Reviews Useful?

"I believe that peer code reviews are the single biggest thing you
can do to improve your code"

Jeff Atwood of Coding Horror at
http://www.codinghorror.com/blog/2006/01/code-reviews-just-do-it.html

"Individual inspections typically catch about 60 percent of defects,
which is higher than other techniques except prototyping and
high-volume beta testing."

Steve McConnell, Code Complete 2nd Edition, page 485

That 60% figure comes from the IEEE paper by Shull et al 2002 What We Have Learned About Fighting Defects which contains the section titled:

"Peer reviews catch 60% of the defects"


问:
More appropriate to validate a dependency filter parameter by mock+stub or by expression compile?
My lead is enforcing TDD on our project. He says he's following Uncle Bob (Robert Martin) and SOLID principles. One of the rules he's reinforcing is what I call "the single cog rule"--there should be no more than one cog in the implemented chain in your unit test.

We have a component that has a repository (IRepository) dependency. We've mocked the repository. The component that fetches from the repository passes a predicate to filter the list of items to be returned. My implementation had stub data get returned from a mock (Moq) repository and executed the predicate passed in from the component's invocation to filter the stub data, and the test validated that the filter accomplished an obvious filtering requirement by stubbing an implementation on the mock repository and invoking the mock repository's implementation. My lead clobbered this implementation and replaced it with an invocation of this:

```<code>    protected static Expression<Func<T, bool>> RepositoryFilterVerification<T>(T entity)
    {
        return It.Is<Expression<Func<T, bool>>>(y => y.Compile().Invoke(entity));
    }
</code>```

His concern is that by executing the expression by stubbing the mock and invoking the mock the test is doing too much.

I was wondering what others felt about this.

EDIT: I had previously stated that he brought in a hundreds-lines-long ExpressionVisitor utility that validated that the expression explicitly matched an  expression, but it turned out he wasn't using it for this.

答: As you now describe it, I agree with your lead.  What you need to test about your method is that it passes the correct predicate to the repository.  What the repository does with the predicate belongs in a test of the repository unit.</p>


问:
How to efficiently implement this background processing chain?
I am working on an audio software that uses The EchoNest web service to identify and retrieve metadata about audio songs and I would like to have some advice on implementing a background processing chain.

(to get the full picture, I'll show you what I did already)

I've implemented the following chain that is mandatory before querying the service about a song's details:

Not much to say except that before being able to query song data, we need its fingerprint and a song ID returned by the Identify sub-process. Of all these steps, they all happen locally but the last one (Identify).

Now about the part of the system I'm seeking for advices:

Above are the different types of queries that can be requested for a song, they are not inter-dependent as we already have the only thing needed, the song ID (diagram 1). Note that I've only put a few but there are nearly 30 of them (see here).

Requirements/architecture:

user can drop files at any time, they are queued for identification

queries can run in parallel with step 1 and optionally concurrently

Ideally, the system should be:

easily extensible when for instance, I implement a new type of query.

easy to use, I just enqueue a query to the chain and wait for a response

Environment:

I am using C# with Dataflow (Task Parallel Library), currently I've had some good success implementing diagram 1 using this approach.

My question:

Is there a particular/well-known pattern to tackle this problem ?

答:
Use a finite state machine for the "chain," where each step in the chain is a sub-state. For example, the states may be:

Start

Initial processing

Adding to collection

Fingerprinting

Querying

Ready

Finite state machines are good for coordinating asynchronous operations. I would also add tracing or logging to indicate when a state transition occurs.


问:
Order by different Enum property each row
So I have a list of DefaultSearchModal items that have an enum called TypeSearch in every list item. I would like to order the list to have a different enum property each row.

So if you have an unordered list by this:

1,1,2,2,3,3,4,4,5,5,5,5,5,5

I would like to order it to:

1,2,3,4,5,1,2,3,4,5,5,5,5,5

What would be a good algorithm to sort it like this?

```<code>    public class DefaultSearchModel
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Url { get; set; }
    public TypeSearch TypeSearch { get; set; }
}

public enum TypeSearch
        {
           News = 0,
           Blog = 1,
           Photo = 3,
           Page = 4
        }
</code>```

答:
Personally I would just put it in a loop Here's psudo code for it.</p>

```<code>while mainList has items
{
  find first 0 item.
  add to queue,
  remove from mailList

  find first 1 item
  add to queue,
  remove from mailList

  find first 3 item.
  add to queue,
  remove from mailList

  find first 4 item.
  add to queue,
  remove from mailList
}

return queue
</code>```

Body:
Personally I would just put it in a loop Here's psudo code for it.

while mainList has items
{
  find first 0 item.
  add to queue,
  remove from mailList

  find first 1 item
  add to queue,
  remove from mailList

  find first 3 item.
  add to queue,
  remove from mailList

  find first 4 item.
  add to queue,
  remove from mailList
}

return queue


答:
As far as I can tell, official Department of Defense policy does not generally forbid dynamic languages.

Standards for software developed or procured by the DoD are promulgated by
the Defense Information Systems Agency (DISA). Their Application Security - Application Security & Development Security Technical Implementation Guide (STIG) does not prohibit any particular language. It doesn't mention Ruby, but it mentions Perl and Python which are similarly dynamic. It mentions them in the context of various topics (following established Coding Standards, avoiding Command Injection Vulnerabilities, etc).

Probably what you are seeing is an overly-strict scanning tool (there are several different ones mentioned in the STIG, each may have its own interpretation of the rules) and/or overly-strict interpretation of its output.

Title: Why does the US government disallow dynamic languages for secure projects?

Body:
I know some people that are currently working on a project for the US military (low security level, non-combat human resources type data).

An initial state of the project code was submitted to the military for review, and they ran the program through some sort of security analyzer tool. It returned a report of known security issues in the code and required changes that needed to be implemented before delivery of the final product.

One of the items that needed to be resolved was removal of part of the project that was written in Ruby as it is a dynamic language.

What is the background/reason for not allowing a dynamic language to be used in a secure setting? Is this the government being slow to adopt new technologies? Or do dynamic languages pose an additional security risk compared to static languages (ala C++ or Java)?


答:
The end result thanks to bowlturner:</p>

```<code>  private IEnumerable<DefaultSearchModel> Sort(IList<DefaultSearchModel> items)
    {
        var returnList = new Collection<DefaultSearchModel>();

        while (items.Any())
        {
            foreach (var type in Enum.GetValues(typeof (TypeSearch)))
            {
                if (items.Any(x => x.TypeSearch == (TypeSearch) type))
                {
                    var item = items.FirstOrDefault(x => x.TypeSearch == (TypeSearch) type);
                    returnList.Add(item);
                    items.Remove(item);
                }
            }
        }

        return returnList;
    }
</code>```

Title: Order by different Enum property each row

Body:
So I have a list of DefaultSearchModal items that have an enum called TypeSearch in every list item. I would like to order the list to have a different enum property each row.

So if you have an unordered list by this:

1,1,2,2,3,3,4,4,5,5,5,5,5,5

I would like to order it to:

1,2,3,4,5,1,2,3,4,5,5,5,5,5

What would be a good algorithm to sort it like this?

```<code>    public class DefaultSearchModel
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Url { get; set; }
    public TypeSearch TypeSearch { get; set; }
}

public enum TypeSearch
        {
           News = 0,
           Blog = 1,
           Photo = 3,
           Page = 4
        }
</code>```

Body:
The end result thanks to bowlturner:

  private IEnumerable<DefaultSearchModel> Sort(IList<DefaultSearchModel> items)
    {
        var returnList = new Collection<DefaultSearchModel>();

        while (items.Any())
        {
            foreach (var type in Enum.GetValues(typeof (TypeSearch)))
            {
                if (items.Any(x => x.TypeSearch == (TypeSearch) type))
                {
                    var item = items.FirstOrDefault(x => x.TypeSearch == (TypeSearch) type);
                    returnList.Add(item);
                    items.Remove(item);
                }
            }
        }

        return returnList;
    }


答:
My FP-flavored solution:

```<code>IEnumerable<DefaultSearchModel> DoMagic(IEnumerable<DefaultSearchModel> models)
{
    var groups = models.GroupBy(model => model.TypeSearch);
    var solution = Enumerable
        .Range(0, groups.Max(grp => grp.Count()))
        .SelectMany(i => groups
            .Where(grp => grp.Count() > i)
            .Select(grp => grp.ElementAt(i))
            .OrderBy(model => model.TypeSearch));
    return solution;
}
</code>```

Probably not most efficient either (since I pointed out that @Jamie's solution isn't, I can't be a hypocrite), but it is not my point right now. I just wanted to show how terse and non-imperative LINQ can be.

Note that we are not repeatedly looking for TypeSearch values that aren't on the list at all, or whose count is beyond a specific treshold.

Body:
My FP-flavored solution:

IEnumerable<DefaultSearchModel> DoMagic(IEnumerable<DefaultSearchModel> models)
{
    var groups = models.GroupBy(model => model.TypeSearch);
    var solution = Enumerable
        .Range(0, groups.Max(grp => grp.Count()))
        .SelectMany(i => groups
            .Where(grp => grp.Count() > i)
            .Select(grp => grp.ElementAt(i))
            .OrderBy(model => model.TypeSearch));
    return solution;
}

Probably not most efficient either (since I pointed out that @Jamie's solution isn't, I can't be a hypocrite), but it is not my point right now. I just wanted to show how terse and non-imperative LINQ can be.

Note that we are not repeatedly looking for TypeSearch values that aren't on the list at all, or whose count is beyond a specific treshold.


问:
What is a good design pattern for multi-mode software?
I will explain my question by way of example, but I'd love a general solution.

I am writing a JavaScript application that needs to function differently depending on its run-time context. To handle this, I have have done the following. (1) At the beginning of the program, I set two context variables—let's say is_foo and is_bar, which can't both be true. Then (2) throughout the code, I check these variables whenever I need to account for the context:

```<code>if (is_foo) {
    app.do_something(is_foo_config);
} else if (is_bar) {
    app.do_something(is_bar_config);
}
</code>```

Are there any good design patterns or best practices for designing a program that has a "mode" with related configurations?

答:
Generally, instead of setting a flag, you want to use polymorphism to choose between different implementations.  In other words, instead of checking is_foo all over the place, do it once at the start, like:

if (is_foo) {
  app = new FooApp();
} else {
  app = new BarApp();
}
```

<p>Alternately, if only the config is different, do something like this at the start:</p>

<pre class="lang-js prettyprint-override"><code>if (is_foo) {
  config = is_foo_config;
} else {
  config = is_bar_config;
}
</code>```

This lets you later just do:

app.do_something(config);
```

Basically, by doing the if statement once, you minimize the possibility of accidentally forgetting to do it at some later point, and usually also eliminates a lot of repetition.

Body:
Generally, instead of setting a flag, you want to use polymorphism to choose between different implementations.  In other words, instead of checking is_foo all over the place, do it once at the start, like:

if (is_foo) {
  app = new FooApp();
} else {
  app = new BarApp();
}

Alternately, if only the config is different, do something like this at the start:

if (is_foo) {
  config = is_foo_config;
} else {
  config = is_bar_config;
}

This lets you later just do:

app.do_something(config);

Basically, by doing the if statement once, you minimize the possibility of accidentally forgetting to do it at some later point, and usually also eliminates a lot of repetition.


问:
Does laziness yield more race conditions?
I recently ran into a race condition while accessing a configuration setting.  After examining what I could of the code, I came to the conclusion that the Configuration class' laziness1 was the source of the race condition.  Pondering that lead me to me wonder if laziness naturally yields a greater chance of race conditions?

Here's how I came to the initial finding:

The Configuration class is implemented as a static class, which means:

The program cannot specify exactly when the class is loaded. However, it is guaranteed to be loaded and to have its fields initialized and its static constructor called before the class is referenced for the first time in your program.

Which, if I read it correctly, is a long way of saying that the class is lazily loaded.  I did not find anything referencing ordering of events when using additional resources.  i.e. It didn't say when the configuration file (app.config) would be read.

And while the class itself states the following for thread safety, it's not clear when it actually reads the configuration file.

Any public static members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

The bit about Any instance members are not guaranteed to be thread safe is particularly confusing since a static class cannot be instantiated.

What I believe occurred is that my program wrote to a section of the Configuration which was subsequently over-written as the static instance completed it's initialization and reading from the configuration file.

All of that led me to believe that the lazy loading of the static class with its indeterminate reading of the configuration file created the race condition I smacked into.

Which leads me to my broader question of: does laziness within an application naturally yield a greater chance of race conditions?

1 The particular class in question is System.Configuration.Configuration from the .NET framework which is defined as public static class ConfigurationManager.

For the gory details, this is the abstract version of the code:

```<code>//This first line probably isn't required, but I inherited the code and didn't test removing it.
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings[DBName].ConnectionString = passedParam;
config.Save();
...
ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings[DBName];
</code>```

The answers from here hint at my question, but don't directly address my concern with race conditions.  And this one is somewhat related but more focused on IoC.

答:
Your first link does address the issue - it's laziness combined with side effects that is problematic, because the order of side effects matters.

For pure computations, the main thing that changes is space/time usage and whether the computation produces a result or not. More specifically, lazy evaluation won't evaluate expressions that aren't used, so the time usage can be lower, but the space usage is very hard to reason about.

For pure computations that don't complete successfully, both evaluation strategies can give different results. For example, since lazy evaluation doesn't evaluate expressions that aren't used, if an unused expression would've resulted in an exception or an infinite loop, the computation will still terminate.

If the computation is both pure and total (always terminates successfully) both evaluation strategies give the same results (though space/time usage may still be different).

In short, while laziness may require you to think differently to figure out the execution order, it won't result in race conditions unless it's combined with side effects.


问:
How to compute data for charting?
I'm building a charting component that displays data directly from the raw data records. It should be able to filter data (subset) and then perform some rudimentry maths on the data (sum, avg, etc). It will finally display the data in a month-wise manner with a scrollbar to navigate through months.

I'm currently building this for an offline desktop application scenario, but ideas involving database engines are also appreciated since I could use an offline RDBMS such as SQLite to achieve the same.

An example data set is as follows, and the typical size is 10K to 1M records.

```<code> Cust   Category        Date         Price
{John   Hair products   25-June-2010  25.2}
{Tina   Food products   26-May-2012   635.5}
{Bob,   Food products   4-Apr-2012    35.3}
{Stacy  Hair products   12-Dec-2010   525.2}
(etc)
</code>```

Assuming a simple business chart displaying "month-wise total sales of hair products", what are good patterns for computing this data such that it can be displayed in a visual chart?

Some possibilities:

Supposing the chart component is displaying only 2012 data, first filter data within the year 2012. Then search for matching records for each month, summing up the total price, to arrive at the month-wise total sales.

Pre-separate all data records based on the year, so when we are displaying 2012 data, calculation only needs to be done on data for 2012.

Pre-compute all data for all months of all years, the entire data set, possibly displaying a "loading bar" while doing this. Then, when we need to display a certain year's data, everything is ready for display.

What are you thoughts on this? And what are the usual strategies/algorithms for displaying simple business charts and computing data for charting?

答:
Your data size is low, thats why I doesn't make sense to think about the possibilities (1-3). I suggest following pipeline:

parse your data from binary

put the data in a SQL database

do some clever SQL selects, aggregations, computing or ...

visualize the results as an report

Its more important to use test driven development (TDD) instead of select the right software architecture. If you use TDD, its easy to change the If you run in problems because of runtime or memory, ask again.

Title: How to compute data for charting?


问:
How should I design an application using Ember.js to suit a given scenario?
I am going to develop an application in ember.js which is kind of a small CRM through which customer representatives can answer to queries of customers.

The layout is pretty simple, I have a 3 column layout.
First column respresent all the queries by customers.
Second column represents the detail of query and section which offers an editor to write and send response to the query
Thrid column consists all templates which customer rep. can use to answer routine questions.

I have prior experience of backbone.js and javascript, but I am still facing difficulty in thinking, in terms of ember.js. In the backbone I would have develop a route which will load the main view with sub views of three column and then there sub views. As ember.js is quite different from backbone, my head is not becoming clear to plan the application.

According to my assumption I would use three models (i.e queries, responses and templates) for a single route, but I am not sure how to do it since emberjs only allows one model to attach with route. Secondly I need a view in response section which can manipulate the queries markup too.

How do you propose to plan this application and think in terms of emberjs?

答:
According to my assumption I would use three models (i.e queries,
  responses and templates) for a single route, but I am not sure how to
  do it since emberjs only allows one model to attach with route.

Ember doesn't actually put this restriction. You can create an RSVP.hash of all the models that you want. Something like:

```<code>QueryRoute = Ember.Route.extend({
  model: function(){
      return Ember.RSVP.hash({
          queries: this.store.find('query'),
          details: this.store.find('detail'),
          templates: this.store.find('template'),
          response: this.store.createRecord('response')
       });
  }
})
</code>```

--

As to your question*:

You can create your routes so that there's an index route (which lists all the queries) and there's a query route, which lists the details of a single query, the response, and response templates.

So, your router might look like this:

```<code>App.Router.map(function() {
  this.resource("queries", function(){
    this.route("query", { path: "/query/:id" })
  });
});
</code>```

Your queries route might look something like this:

```<code>QueriesRoute = Ember.Route.extend({
  model: function(){
      return this.store.find('query'); # this will find all queries
  }
});
</code>```

On your queries template, you can show the list of queries and an outlet so that we can render the query when a user clicks on it.

```<code>{{#each query in queries}}
    {{#link-to "query" query}}
        {{query.name}}
        {{query.description}}
    {{/link-to}}
{{#each}}

{{ outlet }}
</code>```

Once the user clicks on the query, they will be transitioned to the "query" route. Let's create that route now.

```<code>QueryRoute = Ember.Route.extend({
  model: function(params){
      return Ember.RSVP.hash({
          query: this.store.find('query', params.id),
          details: this.store.find('detail', { query: params.id }),
          templates: this.store.find('template'),
          response: this.store.createRecord('response')
       });
  }
});
</code>```

We're:

a) finding the query for that query ID

b) finding the details for that query ID

c) finding all the templates

d) creating a new response record

On the query template, you can do something like:

```<code><div class="query-details">
  <h3>{{query.title}}</h3>
  <small>{{query.description}}</small>

  <p>{{query.details}}</p> # you can loop too if it's an array
</div>

<div class="query-response">
  {{textarea value=response.body}}
  <button {{ action "sendResponse" }}>Send Response</button>
</div>

<div class="templates">
  {{#each template in templates}}
    <h3>{{template.title}}</h3>
    <p>{{template.body}}</p>
    <button {{ action "selectTemplate" template }}>Select Template</button>
  {{/each}}
</div>
</code>```

Here, you're:

a) rendering the query's title and description as well as its details

b) rendering a response form that has a text area and submit button that has an action of "sendResponse", i.e. when you click, it will look up the action "sendResponse" on its controller and the router and keep bubbling up until it finds the action or gets to the applicationRoute at which stage it'll throw an error.

c) rendering the templates and a button to select any template. Notice the action "selectTemplate" that also passes along the "template" parameter.

So... what now? We need to handle these actions and do the right thing. We can do that in two places: the QueryController or the QueryRoute. I'll create a QueryController.

--

There are three types of controllers: Object, Array, and, well, the default controller. An object controller represents a single model and an array controller represents a collection.

In our case, since a query is a single object, we'll use an ObjectController.

So:

```<code>QueryController = Ember.ObjectController.extend({
  actions: {

    sendResponse: function(){
      var response = this.get('response');
      var success  = function(){
        console.log("Successfully posted response!");
      };
      var failure = function(err){
        console.log("Something went wrong:", err);
      };
      response.save().then(success, failure);
    },

    selectTemplate: function(template){
      var response = this.get('response');
      response.get('body').set(template.get('body'));
    }

  }
})
</code>```

There are two actions:

a) sendResponse: takes the response[**] and sends a POST request to your server. Then it executes the success/failure functions when the save() promise resolves.

b) selectTemplate: this just takes the template as parameter and sets the response's body to what the template's body is. Of course, if you have multiple properties, you can set all of them.

--

That should put you on the right path. Ember is actually quite easy once you get a hang of the basic conventions it expects you to follow; you may be surprised just how productive you can be with it. :)

--

[*] I'm assuming that you're using Ember Data; if you aren't, I can modify my answer to use normal ajax queries

[**] There's a little bit to explain there: the response object that you created on the route has properties (body, for example) that will automatically change when the user inputs something into the textarea. Thus, when you call save(), it will do the right thing: serialize the model and POST it to your server.

Body:
According to my assumption I would use three models (i.e queries,
  responses and templates) for a single route, but I am not sure how to
  do it since emberjs only allows one model to attach with route.

Ember doesn't actually put this restriction. You can create an RSVP.hash of all the models that you want. Something like:

QueryRoute = Ember.Route.extend({
  model: function(){
      return Ember.RSVP.hash({
          queries: this.store.find('query'),
          details: this.store.find('detail'),
          templates: this.store.find('template'),
          response: this.store.createRecord('response')
       });
  }
})

--

As to your question*:

You can create your routes so that there's an index route (which lists all the queries) and there's a query route, which lists the details of a single query, the response, and response templates.

So, your router might look like this:

App.Router.map(function() {
  this.resource("queries", function(){
    this.route("query", { path: "/query/:id" })
  });
});

Your queries route might look something like this:

QueriesRoute = Ember.Route.extend({
  model: function(){
      return this.store.find('query'); # this will find all queries
  }
});

On your queries template, you can show the list of queries and an outlet so that we can render the query when a user clicks on it.

{{#each query in queries}}
    {{#link-to "query" query}}
        {{query.name}}
        {{query.description}}
    {{/link-to}}
{{#each}}

{{ outlet }}

Once the user clicks on the query, they will be transitioned to the "query" route. Let's create that route now.

QueryRoute = Ember.Route.extend({
  model: function(params){
      return Ember.RSVP.hash({
          query: this.store.find('query', params.id),
          details: this.store.find('detail', { query: params.id }),
          templates: this.store.find('template'),
          response: this.store.createRecord('response')
       });
  }
});

We're:

a) finding the query for that query ID

b) finding the details for that query ID

c) finding all the templates

d) creating a new response record

On the query template, you can do something like:

<div class="query-details">
  <h3>{{query.title}}</h3>
  <small>{{query.description}}</small>

  <p>{{query.details}}</p> # you can loop too if it's an array
</div>

<div class="query-response">
  {{textarea value=response.body}}
  <button {{ action "sendResponse" }}>Send Response</button>
</div>

<div class="templates">
  {{#each template in templates}}
    <h3>{{template.title}}</h3>
    <p>{{template.body}}</p>
    <button {{ action "selectTemplate" template }}>Select Template</button>
  {{/each}}
</div>

Here, you're:

a) rendering the query's title and description as well as its details

b) rendering a response form that has a text area and submit button that has an action of "sendResponse", i.e. when you click, it will look up the action "sendResponse" on its controller and the router and keep bubbling up until it finds the action or gets to the applicationRoute at which stage it'll throw an error.

c) rendering the templates and a button to select any template. Notice the action "selectTemplate" that also passes along the "template" parameter.

So... what now? We need to handle these actions and do the right thing. We can do that in two places: the QueryController or the QueryRoute. I'll create a QueryController.

--

There are three types of controllers: Object, Array, and, well, the default controller. An object controller represents a single model and an array controller represents a collection.

In our case, since a query is a single object, we'll use an ObjectController.

So:

QueryController = Ember.ObjectController.extend({
  actions: {

    sendResponse: function(){
      var response = this.get('response');
      var success  = function(){
        console.log("Successfully posted response!");
      };
      var failure = function(err){
        console.log("Something went wrong:", err);
      };
      response.save().then(success, failure);
    },

    selectTemplate: function(template){
      var response = this.get('response');
      response.get('body').set(template.get('body'));
    }

  }
})

There are two actions:

a) sendResponse: takes the response[**] and sends a POST request to your server. Then it executes the success/failure functions when the save() promise resolves.

b) selectTemplate: this just takes the template as parameter and sets the response's body to what the template's body is. Of course, if you have multiple properties, you can set all of them.

--

That should put you on the right path. Ember is actually quite easy once you get a hang of the basic conventions it expects you to follow; you may be surprised just how productive you can be with it. :)

--

[*] I'm assuming that you're using Ember Data; if you aren't, I can modify my answer to use normal ajax queries

[**] There's a little bit to explain there: the response object that you created on the route has properties (body, for example) that will automatically change when the user inputs something into the textarea. Thus, when you call save(), it will do the right thing: serialize the model and POST it to your server.