答:
At my current company we have a similar setup: public facing websites, a few API's for partners, and a whole bunch of background tasks and services. One thing I pushed for when I joined the team several years back was to log everything to one database table. Skeptical?

Yes, the DBA was too. I convinced him :)

Yes, we had to be careful of hampering the performance of our production DB with frequent (average ~4 per second) inserts of medium sized log records (average 100~2000 bytes each) -- we setup the table as leanly as possible and indexed it well to speed up queries.

Yes, we had to setup an archive/deletion job to clean up old records (just like a good sysadmin would do on a server.)

The advantages are huge:

The DB enforces a sequential ordering of log entries by a primary auto-increment integer key, so there is a canonical ordering to the list of log records, and of course a datetime field as well. (This addresses your specific question.)

We defined our own schema that categorized records by system component, subcomponent, and even method name (via reflection and stack tracing in our logging methods).

We can query the log according to specific patterns using SQL rather than grepping and concatenating a bunch of text files strewn about 10 different servers in 100 different folders.

Having worked with this logging setup for a few years, I would not willingly go back to logging to distributed text files, unless the system I was working on was very small.

Title: How do we sequence logs from different services in a system?

Body:
So, if I am designing a system as a set of different roles (client, app-server, backend services 1 to n). Each of these roles will have their own logging mechanism. I can aggregate all the logs at one location, but how can I sequence the logs from different sources, to show an interleaved log?

I can make my own strategy. Timestamps can help but will not be 100% accurate. What is normally done in the industry?


问:
Why is it (or was it) important to separate CSS from HTML?

Intro

I recently watched the slides from React: CSS in JS and I really like the idea of having CSS applied using JS (and with JSX, this would mean having all the HTML, JS and CSS in one file, which is just great for small, reusable components); however I'm worried about possible problems with semantic/performance/whatever, which lead me to...

The question

Why is it important to separate CSS from HTML?

Obvious reasons I can think of are avoiding duplication and keeping the HTML purely semantic while letting CSS handle the styling. I can do both in JS. Are there any other reasons I'm missing?

Edit: I missed a very important thing here - I'm designing architecture for a big web application, not some small blog thing. It will have its own build pipeline, with virtually any configuration possible.

Edit #2: I see a lot of arguments about separation of concerns, most of which are (in my understanding) based on assumption that it is more often to change just HTML or just CSS and once as opposed to editing HTML and CSS in parallel. While this might be the case for small websites, my commit history shows me the opposite - I usually edit both HTML and CSS together. So instead of separating all HTML from all CSS I would separate each component from each other.

I still don't see any serious drawback of doing this.

Caching? Each component file could be cached.

Semantics? I could still have semantic in HTML and styles in CSS, just in one file.

Re-use and maintainability? It will be even easier with separated components instead of a bunch of HTML and CSS files with unclear relationships.

MVC? I could have my mini MVC inside each component.

Edit #3: FYI all: @keithjgrant wrote a great folow-up article about this question: http://keithjgrant.com/posts/against-css-in-js.html

答:
1. Why was it important to separate CSS from HTML?

Originally, JavaScript was used for fancy (and extremely annoying) animations and websites were globally just a bunch of HTML and CSS. On server side, frameworks were not as numerous and powerful as now.

This meant that you had a choice:

Either you make proper separation between content (HTML) and style (CSS),

Or you mix both, either by putting CSS code within HTML files, or simply by using HTML analogs (
I'm red.
).

The first alternative gave you two important benefits:

No code duplication, which becomes valuable where you find yourself changing the color of a commonly used element from red to purple on every page of the website, making hundreds of changes in your code base instead of just one,

Reduced bandwidth usage (extremely important where most of your visitors have 56 Kbps internet connection), thanks to client cache,

Hypothetical ability to change style without touching the content: a point I'll discuss in part 3.

which also explains why so many personal websites were using
I'm red.
 style at their beginning, and when becoming larger and more popular, were forced to migrate to pure CSS.

2. Why is it important to separate CSS from HTML today?

Assume we are not under legal obligation to make our web app accessible (since accessibility would inevitably lead to no-JavaScript version), and that the app is already using JavaScript extensively for its core features.

At development level:

Separating content from style may still be useful for the same reason as above: code duplication. If two elements share the same style, you shouldn't be writing the style twice: you should define it once, and then reuse it. Writing it twice leads to maintenance problems which are too obvious to explain.

Note that it doesn't really matter how are you storing content and how are you storing styles. Content would in general be generated by the web app based on (1) data from the database and (2) business logic, while style would be defined in a static form, would it be a CSS file, XAML, or something completely different.

This leads to the second point: how this content and style is served.

At client level:

Serving content and style and applying style to content may take different forms: maybe an ordinary HTML/CSS, maybe some complex solution involving AJAX requests, DOM, etc. The previous bandwidth argument is irrelevant here: not only most users have 8 Mbps or faster connections, but AJAX requests can be cached as well.

Instead, the choice of the alternative would be rather based on the ease of use of a specific solution provided by a specific framework, and how comfortable the developer is delegating this task to the framework.

Here's a story.

Some version of ASP.NET MVC added a feature called bundles. Instead of serving CSS and JavaScript files yourself, you simply fed the framework with those files and the framework did all the job for you: it minified the files and sent them as a single file—one CSS file and one JavaScript file.

But as any magical tool, it had limitations. It worked well for small websites, and if one day, my grandma starts programming in C# and decides to make her personal website, I would be the first one to convince her that she should use bundles.

The story was different for more complex ones. What if I want to include LESS files? Well, there was¹ a possibility to do that, thanks to the excellent architecture of ASP.NET MVC, but this meant reading through dozens of pages of documentation and creating dozens of classes. I'm not sure why would I want to do that, when a bundle-lessn from scratch solution can be done in less than half an hour with fewer code to write.

Same thing for JavaScript. Can I ask ASP.NET MVC to use Google Closure Compiler to minify the files? Probably not easily, or at least not in the earlier versions of ASP.NET MVC.

Framework features are great and can simplify your life, but they can also be a limitation. Small, personal projects can benefit a lot from these. Large projects tend to rely more on custom-made solutions, which are easier and faster to develop than to extend the framework.

Imagine I have a great framework which does an excellent job of generating relevant styles for every page, managing cached styles, etc. This is great, because:

This can reduce even further the bandwidth: if I have 600 styles but only 30 are used on the home page, this means 570 styles less to send through the wire and to process by the client; chances are, my home page will appear a few seconds faster.

This can make my life and my code simpler, for example by removing the global state. For instance, if I know that a specific style should appear only on that page, I may let the framework figure out which selector should be used, without taking the risk of picking one which may be used on a different page.

Now, personally, I've never seen a framework which can do that, and the ones I've seen appear too limited while not making my life simpler.

Is writing plain CSS easier? I would say so. CSS has its weak points, but many of them are solved by preprocessors such as LESS and Sass. Being able to use features of LESS/Sass while letting the framework process the code into minified CSS is great. But I'm not sure today's tools are mature enough to move from this way of working to something more powerful and abstract.

3. Separation of concerns matters. Is it?

You were mentioning separation of concerns in your question, so I would like to highlight this particular aspect separately.

I see a lot of arguments about separation of concerns, most of which are (in my understanding) based on assumption that it is more often to change just HTML or just CSS and once as opposed to editing HTML and CSS in parallel. While this might be the case for small websites, my commit history shows me the opposite - I usually edit both HTML and CSS together. So instead of separating all HTML from all CSS I would separate each component from each other.

When you change HTML, you will necessarily change CSS in most cases. This is not like DAL/BL/PL, where you can, for example, swap database layer without affecting anything else. If you change content, presentation, often, will have to change.

For instance, you're adding a new button to an element. Not surprisingly, the element is now too small, so you need to adjust its width.

In theory, the inverse is not true: you're expected to be able to throw away all your CSS code, and do something completely different. Same content, different presentation.

When Microsoft released WPF (a technology which powers the interfaces of some Windows applications, making it easier than it was before to design interfaces and apply styles to them) and the underlying XAML (a language used to describe both the content of the interface—buttons, lists, combo boxes—and the style—rounded corners, fonts, transitions), one of the benefits which were highlighted all over the ads was the ability to style application independently of the content.

Microsoft even made a tool for that. It's called Microsoft Blend. The theoretical workflow of a team is the following:

Interaction designers make a wireframe of an application on a piece of paper.

Software developers pick this piece of paper and create, in Visual Studio (developer's tool number one in Microsoft's world), the different windows of the application, putting buttons, lists and combo boxes.

They then give the unfinished application to interaction and graphical designers who open the source code not in Visual Studio—they are designers, they don't use IDEs—but in Microsoft Blend, which shows them not the source code, but a pretty interface where they can visually change the visual aspects of the app: move controls, set color and font, add transitions and animations, etc. Meanwhile, developers finish to implement the features behind the buttons, lists and combo boxes.

We have here:

The same initial requirement: being able to change style independently of the content, with the ability to completely replace the current presentation with a different one.

The same constraint: if content changes, presentation will be affected in most cases and requires changes too.

While Microsoft did a great job with WPF and XAML, there is still a tiny problem: from time to time, when you need to change a style, you have to change the content as well, which means that the workflow of the team is rather:

Interaction designers make a wireframe of an application on a piece of paper.

Software developers pick this piece of paper and create, in Visual Studio, the different windows of the application, putting buttons, lists and combo boxes.

Interaction and graphical designers and software developers work side by side on the interface of the future application, ensuring constant communication, regular meetings, etc.

This is exactly what happens with HTML and CSS. In theory, you shouldn't touch HTML when working on style. In practice, you're constantly adjusting the markup when working on CSS, because:

Either a specific style is impossible with the current markup,

Or doing it with the current markup would require too much CSS code or produce a very unclean, difficult to maintain code.

When you change HTML too often when you're working on CSS, this may be a sign that:

The HTML code was not well done in the first place.

The HTML code was made "without styling in mind". Experienced programmers who know well CSS will produce HTML code which will be easier to style. Programmers who master HTML but know nothing about CSS will write code which will require a huge amount of changes.

As an extreme example, CSS Zen Garden is an interesting study case of what can be done with pure CSS, based on an unchanged HTML code which was originally well done.

In practice, most websites and web applications are on the other side: every site I know which was "redesigned" visually was changed completely: different CSS, different HTML, different JavaScript, different code-behind.

¹ I believe LESS support is automatic in newer versions of ASP.NET MVC.

ContentLicense: CC BY-SA 3.0

Body:
1. Why was it important to separate CSS from HTML?

Originally, JavaScript was used for fancy (and extremely annoying) animations and websites were globally just a bunch of HTML and CSS. On server side, frameworks were not as numerous and powerful as now.

This meant that you had a choice:

Either you make proper separation between content (HTML) and style (CSS),

Or you mix both, either by putting CSS code within HTML files, or simply by using HTML analogs (<div color="red">I'm red.</div>).

The first alternative gave you two important benefits:

No code duplication, which becomes valuable where you find yourself changing the color of a commonly used element from red to purple on every page of the website, making hundreds of changes in your code base instead of just one,

Reduced bandwidth usage (extremely important where most of your visitors have 56 Kbps internet connection), thanks to client cache,

Hypothetical ability to change style without touching the content: a point I'll discuss in part 3.

which also explains why so many personal websites were using <div color="red">I'm red.</div> style at their beginning, and when becoming larger and more popular, were forced to migrate to pure CSS.

2. Why is it important to separate CSS from HTML today?

Assume we are not under legal obligation to make our web app accessible (since accessibility would inevitably lead to no-JavaScript version), and that the app is already using JavaScript extensively for its core features.

At development level:

Separating content from style may still be useful for the same reason as above: code duplication. If two elements share the same style, you shouldn't be writing the style twice: you should define it once, and then reuse it. Writing it twice leads to maintenance problems which are too obvious to explain.

Note that it doesn't really matter how are you storing content and how are you storing styles. Content would in general be generated by the web app based on (1) data from the database and (2) business logic, while style would be defined in a static form, would it be a CSS file, XAML, or something completely different.

This leads to the second point: how this content and style is served.

At client level:

Serving content and style and applying style to content may take different forms: maybe an ordinary HTML/CSS, maybe some complex solution involving AJAX requests, DOM, etc. The previous bandwidth argument is irrelevant here: not only most users have 8 Mbps or faster connections, but AJAX requests can be cached as well.

Instead, the choice of the alternative would be rather based on the ease of use of a specific solution provided by a specific framework, and how comfortable the developer is delegating this task to the framework.

Here's a story.

Some version of ASP.NET MVC added a feature called bundles. Instead of serving CSS and JavaScript files yourself, you simply fed the framework with those files and the framework did all the job for you: it minified the files and sent them as a single file—one CSS file and one JavaScript file.

But as any magical tool, it had limitations. It worked well for small websites, and if one day, my grandma starts programming in C# and decides to make her personal website, I would be the first one to convince her that she should use bundles.

The story was different for more complex ones. What if I want to include LESS files? Well, there was¹ a possibility to do that, thanks to the excellent architecture of ASP.NET MVC, but this meant reading through dozens of pages of documentation and creating dozens of classes. I'm not sure why would I want to do that, when a bundle-lessn from scratch solution can be done in less than half an hour with fewer code to write.

Same thing for JavaScript. Can I ask ASP.NET MVC to use Google Closure Compiler to minify the files? Probably not easily, or at least not in the earlier versions of ASP.NET MVC.

Framework features are great and can simplify your life, but they can also be a limitation. Small, personal projects can benefit a lot from these. Large projects tend to rely more on custom-made solutions, which are easier and faster to develop than to extend the framework.

Imagine I have a great framework which does an excellent job of generating relevant styles for every page, managing cached styles, etc. This is great, because:

This can reduce even further the bandwidth: if I have 600 styles but only 30 are used on the home page, this means 570 styles less to send through the wire and to process by the client; chances are, my home page will appear a few seconds faster.

This can make my life and my code simpler, for example by removing the global state. For instance, if I know that a specific style should appear only on that page, I may let the framework figure out which selector should be used, without taking the risk of picking one which may be used on a different page.

Now, personally, I've never seen a framework which can do that, and the ones I've seen appear too limited while not making my life simpler.

Is writing plain CSS easier? I would say so. CSS has its weak points, but many of them are solved by preprocessors such as LESS and Sass. Being able to use features of LESS/Sass while letting the framework process the code into minified CSS is great. But I'm not sure today's tools are mature enough to move from this way of working to something more powerful and abstract.

3. Separation of concerns matters. Is it?

You were mentioning separation of concerns in your question, so I would like to highlight this particular aspect separately.

I see a lot of arguments about separation of concerns, most of which are (in my understanding) based on assumption that it is more often to change just HTML or just CSS and once as opposed to editing HTML and CSS in parallel. While this might be the case for small websites, my commit history shows me the opposite - I usually edit both HTML and CSS together. So instead of separating all HTML from all CSS I would separate each component from each other.

When you change HTML, you will necessarily change CSS in most cases. This is not like DAL/BL/PL, where you can, for example, swap database layer without affecting anything else. If you change content, presentation, often, will have to change.

For instance, you're adding a new button to an element. Not surprisingly, the element is now too small, so you need to adjust its width.

In theory, the inverse is not true: you're expected to be able to throw away all your CSS code, and do something completely different. Same content, different presentation.

When Microsoft released WPF (a technology which powers the interfaces of some Windows applications, making it easier than it was before to design interfaces and apply styles to them) and the underlying XAML (a language used to describe both the content of the interface—buttons, lists, combo boxes—and the style—rounded corners, fonts, transitions), one of the benefits which were highlighted all over the ads was the ability to style application independently of the content.

Microsoft even made a tool for that. It's called Microsoft Blend. The theoretical workflow of a team is the following:

Interaction designers make a wireframe of an application on a piece of paper.

Software developers pick this piece of paper and create, in Visual Studio (developer's tool number one in Microsoft's world), the different windows of the application, putting buttons, lists and combo boxes.

They then give the unfinished application to interaction and graphical designers who open the source code not in Visual Studio—they are designers, they don't use IDEs—but in Microsoft Blend, which shows them not the source code, but a pretty interface where they can visually change the visual aspects of the app: move controls, set color and font, add transitions and animations, etc. Meanwhile, developers finish to implement the features behind the buttons, lists and combo boxes.

We have here:

The same initial requirement: being able to change style independently of the content, with the ability to completely replace the current presentation with a different one.

The same constraint: if content changes, presentation will be affected in most cases and requires changes too.

While Microsoft did a great job with WPF and XAML, there is still a tiny problem: from time to time, when you need to change a style, you have to change the content as well, which means that the workflow of the team is rather:

Interaction designers make a wireframe of an application on a piece of paper.

Software developers pick this piece of paper and create, in Visual Studio, the different windows of the application, putting buttons, lists and combo boxes.

Interaction and graphical designers and software developers work side by side on the interface of the future application, ensuring constant communication, regular meetings, etc.

This is exactly what happens with HTML and CSS. In theory, you shouldn't touch HTML when working on style. In practice, you're constantly adjusting the markup when working on CSS, because:

Either a specific style is impossible with the current markup,

Or doing it with the current markup would require too much CSS code or produce a very unclean, difficult to maintain code.

When you change HTML too often when you're working on CSS, this may be a sign that:

The HTML code was not well done in the first place.

The HTML code was made "without styling in mind". Experienced programmers who know well CSS will produce HTML code which will be easier to style. Programmers who master HTML but know nothing about CSS will write code which will require a huge amount of changes.

As an extreme example, CSS Zen Garden is an interesting study case of what can be done with pure CSS, based on an unchanged HTML code which was originally well done.

In practice, most websites and web applications are on the other side: every site I know which was "redesigned" visually was changed completely: different CSS, different HTML, different JavaScript, different code-behind.

¹ I believe LESS support is automatic in newer versions of ASP.NET MVC.


问:
HTTP status code for mobile clients
There was a debate with one of the platform engineers (as a mobile dev), about the codes being returned.

The scenario is: when trying to create a resource the server is returning a 201 with the resource_id in the header. I would have expected a 201 response with a JSON body with the resource_id. In my opinion, this would be easier for the mobile clients to parse.

Am I wrong in thinking this way? Should I be really parsing headers?

答:
Looking at RFC2616, in the section about the 201 Created response code, we find:

The request has been fulfilled and resulted in a new resource being created. The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field.

So, putting that resource identifier in a Location header field is perfectly legitimate. But, reading further, we find:

The response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content-Type header field.

In other words, the server should provide the new resource location as part of the body of the response, formatted according to the requested content type.

Title: HTTP status code for mobile clients


问:
Sell dual licensed software with 3rd party contributions
I host a project on GitHub.

Right now it has a custom license (shareware) but I'm going to move to a dual license AGPLv3 + commercial license.

I would like to have some information about the commercial part of my software:

Lot of users send Pull Requests to my repository to implement new features or fix bugs. Right now I own the copyright and all the rights of these PR. But when I'll move to AGPLv3 or later everything will be under this License.

Does it mean that when I sell my software I will be able to sell with the commercial license only the parts written by me and I will not have rights for the parts written by users?

答:
So there's a gross misunderstanding of copyright and license behind your question, and it's getting in the way of what I think you're asking.

Copyright belongs to the person who creates or invents something.  It's their mark indicating that they created Foo.  Keep in mind that Copyright can be automatically assigned to employers during the course of employment.

A License is what a Copyright owner uses in order to allow someone else to legally use the creation they (the Copyright owner) made.  Grossly speaking, a licensee is someone who holds a license, and that license is nothing more than the terms and conditions the Copyright Owner specified in order to use the Copyright owner's creation.

So let's cut to the details of your question.

Lot of users send Pull Requests to my repository to implement new features or fix bugs. Right now I own the copyright and all the rights of these PR.

Unless you have signed, copyright assignment agreements in place, then you are mistaken.  Contributors who have suggested modifications to the codebase own their own modifications unless they have explicitly assigned that right to you as the project owner.  Maybe they have, maybe they haven't; you haven't provided enough information in your question to make it clear that they have assigned copyright.  Again, if you don't have signed contributor agreements from the various contributors, you do not own the copyright to their code.

... But when I'll move to AGPLv3 or later everything will be under this License.

This is true, but is completely unrelated to the ownership of copyright.

Does it mean that when I sell my software I will be able to sell with the commercial license only the parts written by me and I will not have rights for the parts written by users?

You're likely / potentially going to have issues.  I'm willing to venture that you do not have formal contributor agreements in place and therefore don't have ownership to the copyright of the external contributions to your project.  Without those agreements, your claim to the code becomes murky.

If you do have agreements in place, then things are fairly straightforward.  You own the copyright to the code and you can freely re-license as need be.

If you don't have agreements in place, then you're going to have to examine the shareware license you're using and how that affects re-licensing of the codebase.  Some licenses (BSD, MIT) are exceptionally permissive and the re-license is not really an issue.  Other licenses are more restrictive and you will not be able to relicense the contributed code because the existing shareware license doesn't support that.


答: For update, you shouldn't need to parse anything other than the Status Code. The updated content comes from the client so only the server needs to do the updating which after it finished it should just return 204 (No Content).

Title: HTTP status code for mobile clients

Body:
There was a debate with one of the platform engineers (as a mobile dev), about the codes being returned.

The scenario is: when trying to create a resource the server is returning a 201 with the resource_id in the header. I would have expected a 201 response with a JSON body with the resource_id. In my opinion, this would be easier for the mobile clients to parse.

Am I wrong in thinking this way? Should I be really parsing headers?


问:
Moving my ASP.NET MVC application to Amazon AWS
I built an ASP.NET MVC application, and now I want to move it to Amazon AWS from my development server. My question is: How does one migrate an ASP.NET application to Amazon AWS? Here is what I have researched/found so far:

Sessions don't work across instances, so I need to use DynamoDB or memcached to store state. I looked into various clients like Enyim as a possible solution to the session state problem using Amazon ElastiCloud.

Amazon has a web service for SMTP emails. So I will need to rework the code that sends SMTP emails to send through Amazon SES, and reroute incoming emails to a separate mail server by changing the DNS records.

There's an SDK for managing user identity (Amazon IAM). I will need to change the authentication code to use this web service.

Perhaps there are more points that I am unaware of. So, how does one migrate an MVC app to AWS?

答:
Firstly, the things you're currently investigating would largely be the same regardless of whether you're taking your site from one machine to several (in-site) servers, to Azure, to Rackspace, etc.

When it comes to session state, your production site is now likely to run across several instances so will need to persist session data at a shared store so that user sessions can be loaded regardless of which server endpoint they end up hitting.

Dynamo could well allow you to handle colossal scale, but is likely to be a relatively costly. Depending on your expected (and eventually, real) traffic workloads, you may well be able to get away with a cheaper form of storage such as AWS Elasticache (especially since user sessions can be transient).

Modifying your SMTP handlers should be pretty trivial.

IAM is more about controlling users' access to AWS services.

What you've described is wanting to manage your own user accounts storage & access (via ASP.NET Membership?) - for that, a persistent relational storage mechanism like Amazon RDS.

There are plenty of examples of others who've done most of this - just GoogleBing it.

Other things to consider:

I hope your site's doesn't require sticky sessions: this can make load-balancing a little tricky.

Have you tested your app running across a couple of local instances, fronted with a simple load-balancer/proxy? It's easier to debug these things locally vs. in the cloud.

You've not mentioned any form of back-end database ... I assume you've got your DB migration organized already?


问:
are multithreading, multiprocessing, multitasking implemented at instruction set or OS?
On a computer with a single cpu core,

must a multithreading program be implemented based on an OS? Can it be implemented in the instruction set and run without an OS?

Can multiple programs run in multitasking way without an OS?
Can multitasking between programs be implemented without an OS  (e.g. implemented only in the instruction set)?

On a computer with multiple cpus/cores,

must a multithreading program be implemented based on an OS? Can it be implemented in the instruction set and run with parallel threads without an OS?

Can multiple processes run in multiproccessing parallel way without an OS? Can this multiproccessing parallelism be implemented without an OS (e.g. but in the instruction set)?

The motivation of my questions is:

Are multithreading, multiprocessing,and multitasking, respectively, intrinsic to computer architecture or to operating system?
(note: an OS is implemented based and runs  on a computer architecture. Concepts intrinsic to a computer architecture can be independent of OS)

Some parallelisms such as pipeline, superscalar, and vector computing are intrinsic to computer architecture , and independent of OS. Are thread and process level parallelisms intrinsic to computer architecture, or to OS? Is multitasking ( as a kind of concurrent computing) intrinsic to computer architecture or OS?

Thanks.

答:
On a computer with a single cpu core, must a multithreading program be implemented based on an OS?

No. A program can implement its own threading and scheduler. At this point, however, the program is taking on the role of an operating system, in that in the absence of a proper operating system kernel, the program must implement all of the hardware communications code normally found in drivers.

Can it be implemented in the instruction set and run without an OS?

Yes and no. The instruction set of many modern CPUs includes the functionality required for hardware-level threads, and this functionality must be implemented in the form of a thread scheduler. That may indeed be part of the program, but again, in the absence of an operating system, the program must implement those features that communicate with hardware.

Can multiple programs run in multitasking way without an OS? Can multitasking between programs be implemented without an OS (e.g. implemented only in the instruction set)?

This suggests a confusion about the role of the operating system.

In order for distinct, disconnected, independent programs to execute in a multithreading environment, a process monitor is necessary to manage the scheduling, execution, and termination of these threads. At an extremely high level, the operating system kernel is, at its heart, a process monitor.

On a computer with multiple cpus/cores, must a multithreading program be implemented based on an OS? Can it be implemented in the instruction set and run with parallel threads without an OS?

There must be some piece of code that schedules code execution on multiple cores, as well as to manage the initialization of those cores. This is normally the role of the process monitor. A single, self-contained program could in principle implement these features, but, as above, it must take on all of the roles of the kernel in order to do so.

Can multiple processes run in multiproccessing parallel way without an OS? Can this multiproccessing parallelism be implemented without an OS (e.g. but in the instruction set)?

Again, this is the role of the program monitor. On typical modern general-purpose CPU architectures, such a monitor must exist in order for processes to be scheduled on cores other than the primary core. In principle, a CPU core could be designed to deal with these matters, and I believe some GPUs and certain other small cores (GreenArrays comes to mind) are in fact built this way, or, at the very least, rely on an ancillary general-purpose CPU to run the process monitor.

Are multithreading, multiprocessing,and multitasking, respectively, intrinsic to computer architecture or to operating system?

No.

Are thread and process level parallelisms intrinsic to computer architecture, or to OS? Is multitasking ( as a kind of concurrent computing) intrinsic to computer architecture or OS?

No, and no.

Again, I detect a misunderstanding of the role of operating systems.

There are aspects of parallelism that are implemented in either the computer hardware or the operating system, but they are intrinsic to neither. Historically, this was entirely the domain of the process monitor, especially in early time-sharing systems. That role was placed in the domain of the system libraries in cooperative multitasking systems, where some system calls temporarily hand over execution to the operating system to handle task scheduling, among other things. Modern multiprocessing operating systems are little more than process monitors that manage, among other tasks, processes dedicated to hardware management.


问:
Why do python generators and functions share the "def" keyword?
Consider the following:

```<code>def some_function():
    return 1

def some_generator():
    yield 1
</code>```

In the code above, some_function is a function, while some_generator is a generator. They look quite similar.

The problem that I have when reading code is that I need to scan through every line in a "function" looking for the yield keyword before I can determine whether it is actually a function or a generator!

It just seems to me that using a different keyword for generators would make more sense, e.g.:

```<code>gen some_generator():
    yield 1
</code>```

What are the merits of using the def keyword for both generators and functions? Why has a new keyword is not been introduced to separate functions and generators?

答:
Generators are functions that evaluate lazily. Given that they are the same thing at base, it makes sense that they would use the same keyword. One option might be to use a comment to identify which is which for a given instance:</p>

```<code>def some_function(): #This is a function.
    return 1

def some_generator(): #This is a generator.
    yield 1
</code>```

Body:
Generators are functions that evaluate lazily. Given that they are the same thing at base, it makes sense that they would use the same keyword. One option might be to use a comment to identify which is which for a given instance:

def some_function(): #This is a function.
    return 1

def some_generator(): #This is a generator.
    yield 1


答:
I would guess it is because it is more Pythonic but what do I know? ;)

I don't really think that it matters all that much. It is easier to remember for me because no need to memorize them both.

EDIT: The PEP might say, you could investigate there.

Title: Why do python generators and functions share the "def" keyword?

Body:
Consider the following:

```<code>def some_function():
    return 1

def some_generator():
    yield 1
</code>```

In the code above, some_function is a function, while some_generator is a generator. They look quite similar.

The problem that I have when reading code is that I need to scan through every line in a "function" looking for the yield keyword before I can determine whether it is actually a function or a generator!

It just seems to me that using a different keyword for generators would make more sense, e.g.:

```<code>gen some_generator():
    yield 1
</code>```

What are the merits of using the def keyword for both generators and functions? Why has a new keyword is not been introduced to separate functions and generators?


问:
Can we assume that all users today have Internet access?
As the Internet is pretty much ubiquitous, can we as developers assume that all users have Internet access? Now I don't mean that the code is written in such a way that if there is no connection then the whole program crashes due to lack of error code. What I mean is, can programs today be developed under the assumption that its users will always have access to the Internet?

You may ask "What do we gain by assuming that?" The reason why I'm asking is because at uni we use quite a few programs which require Internet access due to the way it checks the licenses (it checks your IP address -- if it's not an address at campus, then you you're not allowed to use it). Note that the program itself should work fine without Internet access; it's just needed for license checking.

EDIT:
I'm talking about desktop applications here.

EDIT2:
From some of the answers I get a feeling of being accused of exploiting the users in unethical ways. I'm not endorsing what I've described in this question -- I'm just asking about it because the developers of some of the programs we use at uni have done this. Personally I think doing this is plain out stupid and wrong.

答: The answer is of course, it depends. If you are building software for a factory floor there is a good chance they wont have internet access. For consumer applications they most likely will.</p>

ContentLicense: CC BY-SA 2.5


答:
"What are the merits of using the def keyword for both generators and functions?"

While they are mechanically different, in practice when I use them they are often effectively the same to me conceptually (I don't think much of calling range() vs xrange()).

In terms of understanding what the function is all about quickly though, I agree something is lost with the use of def, but things should not be too obfuscated within the function to begin with.

Even an implicit return None can confuse the intended behavior of a function after a long bit of conditionals (as in, was a return None intended as a final behavior or an oversight in the logic). But those are just my believies about it.

I don't feel my argument is particularly convincing though so I will just defer to PEP 255:

Issue:  Introduce another new keyword (say, "gen" or "generator") in
     place of "def", or otherwise alter the syntax, to distinguish
     generator-functions from non-generator functions.

Con:  In practice (how you think about them), generators are
     functions, but with the twist that they're resumable.  The mechanics of
     how they're set up is a comparatively minor technical issue, and
     introducing a new keyword would unhelpfully overemphasize the
     mechanics of how generators get started (a vital but tiny part of a
     generator's life).

Pro:  In reality (how you think about them), generator-functions are
     actually factory functions that produce generator-iterators as if by
     magic.  In this respect they're radically different from non-generator
     functions, acting more like a constructor than a function, so reusing
     "def" is at best confusing.  A "yield" statement buried in the body is
     not enough warning that the semantics are so different.

BDFL:  "def" it stays.  No argument on either side is totally
     convincing, so I have consulted my language designer's intuition.  It
     tells me that the syntax proposed in the PEP is exactly right - not too
     hot, not too cold.  But, like the Oracle at Delphi in Greek mythology,
     it doesn't tell me why, so I don't have a rebuttal for the arguments
     against the PEP syntax.  The best I can come up with (apart from
     agreeing with the rebuttals ... already made) is "FUD".  If this had
     been part of the language from day one, I very much doubt it would have
     made Andrew Kuchling's "Python Warts" page.


问:
TLS alternatives that do not require a central authority?
I am creating a peer to peer program that runs on client computers connecting to other clients. I will be using Boost.Asio. The only options that I am aware of for securing these connections is using TLS, but it is not practical for every client to have their own certificate and self signed certificates are apparently insecure. What other cryptographic technologies are available that do not require registration with a central authority? Especially ones that would be easy to integrate with these technologies, i.e. there are programmatic implementations available.

Also, I was not sure whether to post this on here or on crypto.stackexchange.com, but crypto seemed more focused on implementing and designing cryptography than utilising it. If I have posted to the wrong one please tell me and I will happily move this question. Thanks.

答:
... TLS, but it is not practical for every client to have their own certificate and self signed certificates are apparently insecure.

Wrong.

Certificates are used within TLS to identify the peer. This identification is necessary to protect against man-in-the-middle attacks.

To make use of certificates for identification you have to be able to verify the certificate.

The only option to verify a self-signed certificate is to check it against the original certificate or its fingerprint, which thus needs to be propagated in a secure way to all client before the TLS connection can be established. This is possible but does not scale if you have lots of clients and servers.

If you instead use a central authority which issues and signs certificates scaling is much easier, because you only have to verify that the certificate belongs to the party (like checking if the hostname is contained in the certificate) and that is is signed by an authority you trust.

And to make it even easier browsers and OS ship with a predefined set of trusted authorities (the root-CA).

If you have only secure the connection over the clients (like with a mobile app) you can use a self-signed certificate and distribute it to the clients (outside the TLS connection). Thus there is no need to buy a certificate from somebody.

For more information, see the OWASP guide to certificate and public key pinning.

Apart from that, a good forum for asking these kind of questions is Information Security StackExchange.


问:
How specify acceptance criteria for randomness?
How would I express a Behavior Driven Development (BDD) acceptance criteria/story/scenario that indicates items should be random to some degree on a Home screen of an app like Instagram?

Here's what I've thought of so far:

Scenario: Random images appear in Home screen

Given 1000 images

  And each view of the Home screen shows 10 random images

  And the user has viewed the Home screen 99 times

  When the user views the Home screen for the 100th time

  Then no image should have appeared on the Home screen more than 25 times

From a user perspective, this seems like a good way to express the requirement.  However, if I run this test in a BDD framework as part of Continuous Integration (CI), then there is some chance it will not pass once in a while.

So, are there any better ways to specify an acceptance criteria for randomness that will only fail if there is a bug in the code and not due to the randomness itself?

答:
With randomized algorithms in a CI environment it is of utmost importance, that the result of the test is as non-random as possible. You must under any means find a way to ensure that a correct implementation will almost always result in a passed test. Otherwise, you or your co-workers will be forced to disable the test and plan to rewrite it. You cannot block the whole downstream due to a random test failing. It is also not acceptable having to rebuild "because sometimes it just doesn't work".

Therefore, you can and should not write any tests that involve an algorithm with a random result, but try to verify a concrete result. As Robert Harvey pointed out, the only meaningful way to deal with the quality of a random distribution is to analyze it in a mathematical/statistical way. How deep down you go into that rabbit hole though, is a matter of personal preference and the importance and required accuracy of the unit under test.

You could indeed try to measure values like standard deviations if your sample is large enough. You could also go for a more practical approach, like, ensuring that a certain number of different images is displayed within X views. For the latter though you still need to keep in mind that you must formulate a criterion, for which the likelihood that it is violated by a correct implementation due to a random variation is extremely small. Preferably, it should be smaller than the probability that your CI servers' hardware fails.

When writing the actual tests, there are generally two things to keep in mind with randomness:

Seed. As Robert Harvey already mentioned, you can make life easier on yourself when you know which seed caused the failure. Randomness is really hard to "reproduce" otherwise. I do not advise using a fixed seed though. You should take a fresh seed on each run, because you want your algorithm to be CI-tested on loads of different values over the time. But you should take care, that the test failure messages contain whichever seed was used.

Performance. If you are writing BDD tests for acceptance criteria it may not be much of a problem. If you include such tests within unit tests though, it will be significantly slower than other tests due to the required repeated runs. Some books claim that a unit test should be faster than 10ms. That's pretty much impossible if you try to run a randomized algorithm 1000 times. 10ms may sound extreme, but once you want to run hundreds of thousands of these tests it does sum up quickly - even more so when you need repeated runs.


问:
Implementing an interface already implemented by a parent class?
If a class extends a parent which defines an interface, should that class also explicitly implement the interface?

As an example, is it better to include or remove the portion in square brackets below:

```<code>interface IVerbable {}

abstract class BaseVerber implements IVerbable {}

class Verber extends BaseVerber [implements IVerbable] {}
</code>```

Functionally, there is no difference in forced implementation, since Verber "is-an" IVerbable by virtue of it's parentage, even if it doesn't explicitly implement the interface itself:

```<code>var_dump(new Verber() instanceof IVerbable); // bool(true)
</code>```

Non-functionally, there seem to be two benefits to implementing in both places:

A person reading the code immediately knows that it implements the interface, without having to view the parent's definition.

Second, PhpDocumentor doesn't follow the trail if the abstract class doesn't give a default implementation of the interface. The concrete implementation would not inherit the documentation unless either it explicitly implements the interface, or the abstract gives an implementation, even an empty one.

I suppose it might be bad practice to omit implemented methods from the abstract class though. It's probably better to at least show the empty signature, but then you're also just duplicating the empty signature in both the interface and the abstract class.

答:
I my opinion you shouldn't add the second implements IVerbable. Here is why:

It does not change the meaning of the code.

It is perfectly natural to navigate between classes when you try to understand someone else's code. You will have to do that anyway.

It is the feature of the base class that it implements the interface, what the derived class inherits like everithing else. I does not make sense to repeat, as it does not make sense to repeat any other feature from the base class.

I am not familiar with PhpDocumentor, but it does not seem like a good idea to change your code just so a tool can understand it better. (If a tool can't understand your code because you did not followed some generally accepted and advisable convention, that is a different case.)


问:
What to learn to become freelancer?
I have around 8 years experience in software development. I have worked on application development all these years using C++ /win32.

I few years from now I want to become a freelancer . I tried to look into some freelance sites and I am not able to find any projects on C++/win32. I feel C++/Win32 wont help me much and I need to learn new skills . But my job require me to still work on C++ , so I cann't learn any new skills. I can still learn some new skills but without good project , it won't make any sense.

I have shortlisted few skills

php

jquery

perl

python

android

I am still confused which one to start and how to get expertise in them.Any suggestions?

答: Becoming a freelancer != getting your projects from a freelancing site.</p>

Title: What to learn to become freelancer?


答:
The notion of whether or not software can do something without an OS is not really meaningful.

An OS is software, and really the only thing that distinguishes an OS from other software running on a computer is that (at least in most modern multitasking systems) the OS reserves certain kinds of operation to itself and prevents other software from performing them. Without an OS, there is nothing to stop any other software doing anything that an OS would usually do, including running using multiple threads and/or processors. This would typically involve interacting with the hardware at a level that would be prevented were an OS present, but without one such restrictions would not apply.

Now it is arguable that by implementing such features, your software (or at least some module of it) would itself become an OS, but that is an issue of semantics and not really productive.

Trying to get to a layer beneath your questions, I think what you're really trying to ask is something closer to "is it possible for a processor architecture to provide full multitasking capabilities at a level beneath the operating system". The answer to this is difficult: it would be possible for the processor to go further than current designs do in this direction, but in the end, operating system cooperation would be necessary because a new thread requires scheduling, and that is an OS responsibility.

Title: are multithreading, multiprocessing, multitasking implemented at instruction set or OS?

Body:
On a computer with a single cpu core,

must a multithreading program be implemented based on an OS? Can it be implemented in the instruction set and run without an OS?

Can multiple programs run in multitasking way without an OS?
Can multitasking between programs be implemented without an OS  (e.g. implemented only in the instruction set)?

On a computer with multiple cpus/cores,

must a multithreading program be implemented based on an OS? Can it be implemented in the instruction set and run with parallel threads without an OS?

Can multiple processes run in multiproccessing parallel way without an OS? Can this multiproccessing parallelism be implemented without an OS (e.g. but in the instruction set)?

The motivation of my questions is:

Are multithreading, multiprocessing,and multitasking, respectively, intrinsic to computer architecture or to operating system?
(note: an OS is implemented based and runs  on a computer architecture. Concepts intrinsic to a computer architecture can be independent of OS)

Some parallelisms such as pipeline, superscalar, and vector computing are intrinsic to computer architecture , and independent of OS. Are thread and process level parallelisms intrinsic to computer architecture, or to OS? Is multitasking ( as a kind of concurrent computing) intrinsic to computer architecture or OS?

Thanks.


问:
When is it not acceptable to model physical world objects with classes?

Does Object Oriented Programming Really Model The Real World? [closed]

also

"Firstly, A represents an object in the physical world, which is a strong argument for not splitting the class up." I was, unfortunately, told this when I started programming. It took me years to realize that it's a bunch of horse hockey. It's a terrible reason to group things. I can't articulate what are good reasons to group things (at least to my satisfaction), but that one is one you should discard right now. The end all, be all of "good code" is that it works right, is relatively easy to understand, and is relatively easy to change (i.e., changes don't have weird side effects). –  jpmc26 8 hours ago

"Firstly, A represents an object in the physical world, which is a strong argument for not splitting the class up."
  I disagree with this. For example, if I had a class that represents a car, I would definitely want to split it up, because I surely want a smaller class to represent the tires. -  jpmc26 11 hours ago

source

Until now, I considered the following a good design, because it emphasizes physical hierarchy among the objects. I would expect that to be easier to understand, than some abstractions e.g.class ViewManager, class WheelsFascade.

```<code>class Car
{
public:
    void start() {assert(!m_fuel_tank.empty()); m_engine.start();};
private:
    std::vector<Wheel> m_wheels;
    Engine m_engine;
    FuelTank m_fuel_tank;
}
</code>```

Am I understanding correctly the above criticism that this is not a good design? If so, what are the actual problems? If not, what is being criticized?

答:
To answer the question in the title, it is not acceptable to model real-world items with classes if those real-world items do not play a role in your problem domain.

To give an extreme example, it is not good to have a class House when you are modelling a railway network.

The criticism in the question you linked to was that the asker stated (paraphrased): "Car is a real-world object and therefore I shouldn't divide it further".

As you show in the question, real-world objects can be composed of other real-world objects, like a car has wheels, an engine and a fuel tank, and that composition can be reflected in the class design.


问:
Multiple classes with the same name, but different namespaces?
I've run into some code (C# if it matters) that has classes which have the same name, but differ in their namespaces. They all tend to represent the same logical thing, but often are different "views" of the same object. The different namespaces are at times part of the same solution, and even the same dll.

I have my thoughts, but couldn't find anything definitive about this practice to be considered a clever use of the tools available or a pattern to avoid.

This question on smurf naming touches on this, but from the other direction. Disambiguating the names would likely require an arbitrary and pervasive prefix, which that question wanted to eliminate.

What are the guidelines around this practice?

答:
This is a real interesting question where the two essentially opposing answers are both correct. Here's a real-world example of this discussion we're having on a project of mine.

I think there are two very salient considerations so far that would make you want to go in one direction or the other, drawing from the two answers from @Jorg and @Frank:

If you anticipate a situation where more than one of the same-named classes might need to be used within the same code context, this is a reason not to use the same name. That is, if you need to work with hr.Employee but at the same time need to look at permissions via security.Employee, it's going to get annoying real fast.

Conversely, if your classes with the same name all have the same or very similar APIs, then that's a good example of when you should use the same name with different namespaces. The Scala example is precisely this, where all the Map classes implement the same interface or are subclasses of each other. In this case the ambiguity or "confusion" can arguably be called a good thing, because the user rightly can treat all the implementations of the class or interface the same...which is the point of interfaces and subclasses.


答:
It is impossible to answer the question of whether the code you present is a good design without a good understanding of what and who the code is for. Why, exactly, do you have such a class in your application? What are its clients? Who specified the behaviours that are implemented by it? How likely are those specifications to change in future? Which aspects of the specification are likely to change together, and which are likely to change at different times?

Real software rarely does something identical to a real world object, so breaking it up along similar divisions is not necessarily the best approach. Even if what we are doing is simulating a real system, it may be best to either merge components that are conceptually distinct in the real world into a single abstraction (perhaps because we don't need to model the interactions between then, but only the end result of those interactions: your model has 4 separate wheel objects, but it may make more sense to consider two wheels and an axle as a single unit, for example) or split a single real component into multiple roles (because that component does multiple things and we need to model those in different ways: a car's wheels steer the car and impart forwards motion, which we may decide is easier to handle separately than together).

What we can say with certainty is that the dogma that modelling objects should be based strictly on the division of components in real world objects is clearly wrong.  We should split our code into objects for pragmatic reasons, rather than to conform to ideals that have no practical basis, which is what this suggestion appears to be.

Title: When is it not acceptable to model physical world objects with classes?

Body:
Does Object Oriented Programming Really Model The Real World? [closed]

also

"Firstly, A represents an object in the physical world, which is a strong argument for not splitting the class up." I was, unfortunately, told this when I started programming. It took me years to realize that it's a bunch of horse hockey. It's a terrible reason to group things. I can't articulate what are good reasons to group things (at least to my satisfaction), but that one is one you should discard right now. The end all, be all of "good code" is that it works right, is relatively easy to understand, and is relatively easy to change (i.e., changes don't have weird side effects). –  jpmc26 8 hours ago

"Firstly, A represents an object in the physical world, which is a strong argument for not splitting the class up."
  I disagree with this. For example, if I had a class that represents a car, I would definitely want to split it up, because I surely want a smaller class to represent the tires. -  jpmc26 11 hours ago

source

Until now, I considered the following a good design, because it emphasizes physical hierarchy among the objects. I would expect that to be easier to understand, than some abstractions e.g.class ViewManager, class WheelsFascade.

```<code>class Car
{
public:
    void start() {assert(!m_fuel_tank.empty()); m_engine.start();};
private:
    std::vector<Wheel> m_wheels;
    Engine m_engine;
    FuelTank m_fuel_tank;
}
</code>```

Am I understanding correctly the above criticism that this is not a good design? If so, what are the actual problems? If not, what is being criticized?


答:
Bad idea, for three reasons.  First off, even though everyone has Internet access these days, which is basically true, they don't always have it available at all times.  My primary machine is a laptop, and it's connected a lot of the time, but not when I'm on the bus, for example.

Second, and sort of related to the first, is your method of checking.  What if a student gets a legitimate copy of the program, puts it on his laptop computer, and then goes to study with a friend who lives off-campus?  You've just introduced a heck of a false-positive condition into your license checking.

Third, there's an ethical problem with the license checking in the first place.  If a person chooses to place a program on their computer, you have no right to cause their computer to treat it as invalid.  In any other context that's called hacking and it could land you in all sorts of hot water, and just because our copyright laws have been hijacked by copyright owners to make a special-case legal exemption for this scenario, that doesn't make it right.

Enforcing the law is the job of law enforcement, and private individuals are highly discouraged from taking law enforcement into their own hands (vigilantism) because they tend to do it all wrong.  (Just look at the Sony rootkit!)

Your best course of action would be to assume that the user has an Internet connection available for features that actually require it, but not require it for features that can get by without it, and certainly don't require it just to convince the program that it's not an illegitimate copy!

Title: Can we assume that all users today have Internet access?

Body:
As the Internet is pretty much ubiquitous, can we as developers assume that all users have Internet access? Now I don't mean that the code is written in such a way that if there is no connection then the whole program crashes due to lack of error code. What I mean is, can programs today be developed under the assumption that its users will always have access to the Internet?

You may ask "What do we gain by assuming that?" The reason why I'm asking is because at uni we use quite a few programs which require Internet access due to the way it checks the licenses (it checks your IP address -- if it's not an address at campus, then you you're not allowed to use it). Note that the program itself should work fine without Internet access; it's just needed for license checking.

EDIT:
I'm talking about desktop applications here.

EDIT2:
From some of the answers I get a feeling of being accused of exploiting the users in unethical ways. I'm not endorsing what I've described in this question -- I'm just asking about it because the developers of some of the programs we use at uni have done this. Personally I think doing this is plain out stupid and wrong.


问:
Application with really dynamic data structure
Well, I'm on the verge of this project that really puzzled me.
The situation is, in our office, we have a department that collect data about the corporate performance indicators from all across the departments and branches.

The method they used before is, they distribute a macro Excel file, which include some worksheets with certain tables to fill by all the departments and branches. Each worksheet was referenced to certain indicator value/score. When filled out, the indicator score will be automatically filled and evaluated. So they came across with many excel files to work with.

Now, we want to move that process into an application, which takes us to this problem. The indicators and the worksheet format itself was subject to change every year. So to incorporate this very dynamic structure, we design the db to store every rows, cells, and formulas, on the database, and come up with a very complex design.

Well my question is, did we do this OK and efficient? I mean is there any suggestions to this kind of problem? We are considering our option to use Google Docs API for the spreadsheet and extract the data from it too. What do you guys think?

答:
No not really.

The problem is that with every variation in the spreadsheet you end up with a different interpretation of the indicators.

So given the same set of inputs each sheet will come up with different recomendations.

Either determine what is the "correct" set of indicators and formulas to be used in the application.

or -

If you really want to leave well alone then excel has a perfectly good ODBC interface which would allow the application to read the original data. Alternatively the POI java library can read spreadsheet data directly. Trying to model the dynamism and general weirdness of a spreadsheet is just going to cause you problems.


问:
Creating variables in methods/functions
In how far do we create variables in our methods or functions?

Do we only create one when we're using the result of the variable more then one time like this?

```<code>function someFunction(SomeClass $someClass) {
    $thisVar = $someClass->thisVar();
    doSomethingElse($thisVar);
    echo $thisVar;
}
</code>```

Or just always create one no matter how many times we're using it (for better readability)?

Or just call the methods from the dependency directly like this?

```<code>function someFunction(SomeClass $someClass) {
    doSomethingElse($someClass->thisVar());
    echo $someClass->thisVar();
}
</code>```

答:
One reason for introducing a separate variable is to improve readability, assumed the real name of $someClass->thisVar() is not expressive enough. This can make sense even if the function is only called once:

```<code>function someFunction(SomeClass $someClass) {
    $explainingName = $someClass->thisVar();
    doSomethingElse($explainingName);
}
</code>```

Of course, if you think the function name is clear enough, this variant

```<code>function someFunction(SomeClass $someClass) {
    doSomethingElse($someClass->selfExplanatoryName());
}
</code>```

might be fine. But even in such a case, when both function names are very long,

```<code>function someFunction(SomeClass $someClass) {
    doSomethingElseWithAVeryLongFunctionName($someClass->selfExplanatoryButVeryLongName());
}
</code>```

might be considered to be less readable than

```<code>function someFunction(SomeClass $someClass) {
     $thisVar = $someClass->selfExplanatoryButVeryLongName();
     doSomethingElseWithAVeryLongFunctionName($thisVar);
}
</code>```

When you need to reuse the value at least twice like in your examples, a reason might be that $someClass->thisVar() must be called only once because of side effects, or it should be called only once because of a noteable performance impact.

A third reason might be to avoid code duplication. Think of this:

```<code>function someFunction(SomeClass $someClass) {
    doSomethingElse($someClass->thisVar($parameter1,$parameter2,$parameter3));
    echo $someClass->thisVar($parameter1,$parameter2,$parameter3);
}
</code>```

here $someClass->thisVar($parameter1,$parameter2,$parameter3) is repated twice, which violates the dry principle. Your second example is an edge case: it is also a violation of the DRY principle, but not a severe one, and to avoid it you have to introduce more code than it actually saves you. So it is a trade-off with no clear "best" solution.

Title: Creating variables in methods/functions

Body:
One reason for introducing a separate variable is to improve readability, assumed the real name of $someClass->thisVar() is not expressive enough. This can make sense even if the function is only called once:

function someFunction(SomeClass $someClass) {
    $explainingName = $someClass->thisVar();
    doSomethingElse($explainingName);
}

Of course, if you think the function name is clear enough, this variant

function someFunction(SomeClass $someClass) {
    doSomethingElse($someClass->selfExplanatoryName());
}

might be fine. But even in such a case, when both function names are very long,

function someFunction(SomeClass $someClass) {
    doSomethingElseWithAVeryLongFunctionName($someClass->selfExplanatoryButVeryLongName());
}

might be considered to be less readable than

function someFunction(SomeClass $someClass) {
     $thisVar = $someClass->selfExplanatoryButVeryLongName();
     doSomethingElseWithAVeryLongFunctionName($thisVar);
}

When you need to reuse the value at least twice like in your examples, a reason might be that $someClass->thisVar() must be called only once because of side effects, or it should be called only once because of a noteable performance impact.

A third reason might be to avoid code duplication. Think of this:

function someFunction(SomeClass $someClass) {
    doSomethingElse($someClass->thisVar($parameter1,$parameter2,$parameter3));
    echo $someClass->thisVar($parameter1,$parameter2,$parameter3);
}

here $someClass->thisVar($parameter1,$parameter2,$parameter3) is repated twice, which violates the dry principle. Your second example is an edge case: it is also a violation of the DRY principle, but not a severe one, and to avoid it you have to introduce more code than it actually saves you. So it is a trade-off with no clear "best" solution.


问:
In TDD, if I write a test case that passes without modifying production code, what does that mean?
These are Robert C. Martin's rules for TDD:

You are not allowed to write any production code unless it is to
make a failing unit test pass.

You are not allowed to write any more
of a unit test than is sufficient to fail; and compilation failures
are failures.

You are not allowed to write any more production code
than is sufficient to pass the one failing unit test.

When I write a test that seems worthwhile but passes without changing production code:

Does that mean I did something wrong?

Should I avoid writing such tests in the future if it can be helped?

Should I leave that test there or remove it?

Note:  I was trying to ask this question here: Can I start with a passing unit test?  But I wasn't able to articulate the question well enough until now.

答:
Actually the same issue came up on a dojo last night.

I did a quick research on it. This is what I came up with:

Basically it is not forbidden explicitly by the TDD rules. Maybe some additional tests are needed to prove that a function works correctly for a generalized input. In this case the TDD practice is left aside just for a little while. Note that leaving TDD practice shortly is not necessarily breaking TDD rules as long as there is no production code added in the meantime.

Additional tests may be written as long as they are not redundant. A good practice would be to do equivalence class partitioning testing. That means that the edge cases and at least one inner case for every equivalence class is tested.

One problem that could occur with this approach, though, is that if the tests pass from the beginning it cannot be assured that there are no false positives. Meaning that there could be tests that pass because the tests are not implemented correctly and not because the production code is working correctly. To prevent this the production code should be changed slightly to break the test. If this makes the test fail the test is most likely correctly implemented and the production code can be changed back to make the test pass again.

If you just want to practice strict TDD you might not write any additional tests that pass from the beginning. On the other hand in an enterprise development environment one actually should leave the TDD practice if additional tests seem usefull.


问:
efficient way to count number of swaps in insertion sort
I am browsing some online coding challenge online and got struck somewhere .
Objective of program is to find maximum number of swaps required in sorting an array via insertion sort in efficient time

the first approach that is brute force approach gives the O(n^2) complexity

The next i can think of is merge sort algorithm the code i use for that is

```<code>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int mergesort(int *,int);
int _mergesort(int *,int *,int,int);
int merge(int *,int *,int,int,int);

int mergesort(int arr[],int n)
{
    int temp[n];
    return _mergesort(arr,temp,0,n-1);
}

int _mergesort(int arr[],int temp[],int left,int right)
{
    int mid,count=0;
    if(right>left)
    {
      mid=(left+right)/2;
      count=_mergesort(arr,temp,left,mid);
      count+=_mergesort(arr,temp,mid+1,right);
      count+=merge(arr,temp,left,mid+1,right);
    }
    return count;
}

int merge(int arr[],int temp[],int left,int mid,int right)
{
  int i, j, k;
  int count = 0;
  i = left;
  j = mid;
  k = left;
  while ((i <= mid - 1) && (j <= right))
  {
    if (arr[i] <= arr[j])
    {
      temp[k++] = arr[i++];
    }
    else
    {
      temp[k++] = arr[j++];
      count = count + (mid - i);
    }
  }
  while (i <= mid - 1)
    temp[k++] = arr[i++];
  while (j <= right)
    temp[k++] = arr[j++];
  for (i=left; i <= right; i++)
    arr[i] = temp[i];

  return count;
}

int main()
{
    int n,tc,i;
    cin>>tc;
    while(tc)
    {
      cin>>n;
      int arr[n];
      for(i=0;i<n;i++)
          cin>>arr[i];
      cout<<mergesort(arr,n);
      tc--;
    }
    return 0;
}

The example test case is
Sample Input:
2
5
1 1 1 2 2
5
2 1 3 1 2

Sample Output:
0
4
</code>```

this gives me a complexity of nlogn
Initially the program reads number of test case that is 2 and followed by two test case

the algorithm works fine for small range of values but show time limit exceeded error in some test case .

What is the most efficient way of doing this i cant find out any suggestion or edits would be appreciated.

答:
You can make a order statistic tree from red black tree and not binary tree because that will fail in case of insertion of keys of sorted fashion.

Then you can implement Rank(T,x) to find the node x position in the current tree. This will be one indexed rank.

So no of elements greater than this will be N-Rank(T,x) where N is total no of nodes.
This is the no it has to shift right by.

so

```<code>swaps=0;
for all keys in array{
  insert in Order statistic Tree;
  g=current one based index-Rank(key);
  count+=g;
}
</code>```

count is your answer.

Body:
You can make a order statistic tree from red black tree and not binary tree because that will fail in case of insertion of keys of sorted fashion.

Then you can implement Rank(T,x) to find the node x position in the current tree. This will be one indexed rank.

So no of elements greater than this will be N-Rank(T,x) where N is total no of nodes.
This is the no it has to shift right by.

so

swaps=0;
for all keys in array{
  insert in Order statistic Tree;
  g=current one based index-Rank(key);
  count+=g;
}

count is your answer.


问:
How to politely decline a pull request?
There was a pull request made on one my repos adding explanations on the README file. Unfortunately, it's hardly understandable and I doubt will be helpful. What ways can I do to politely decline his/her pull request without discouraging future contributions?</p>

答: You can comment GitHub commits on a line basis. Just add comments explaining the concrete issues with the suggested changes and then you will see where it goes from there. Generally, not all contributors are worth keeping around. You really want those with whom you can establish a feedback loop in both directions.</p>

Title: How to politely decline a pull request?


答:
Yes in the sense that most people who work with computers can access an internet connection (so it's probably ok to distribute bug fixes through a package manager or FTP or similar).

No in the sense that most people don't necessarily have consistent, reliable, performant access to the internet all day (so assuming that each of your users can pull down 20mb/s consistently is probably a bad idea. People do also periodically use buses and airplanes where you're pretty much guaranteed a lack of connectivity).


问:
Should I keep email addresses as plaintext in database?
It's clear to everyone (I hope) that storing passwords without at least salting/hashing them is a terrible idea.

What about emails? Let's say you keep the subscription email address, if you encrypt it properly it may not be usable to send emails to the users. On the other hand, if you don't encrypt it and the database gets stolen, all your users risk a potential spam.

This question is not about law-specific issues (although they may be given, they remain country-dependent) or about encrypting the database itself.

答:
Storing a salted hash of the email addresses could be on option if you keep those records just for account confirmation / authentication.

In other cases, it seems to me that encrypting the emails would make the job of maintaining the database harder while gaining little in return.

Probably securing the access of the database itself is a better choice: usually there are a lot of other information in the database that you wouldn't like to be gathered.

A similar question on Stackoverflow: Is it worth encrypting email addresses in the database?


答:
I think that you already said it all.

The only thing I can think of is not to use a one way hash filter like SHA1 to store the email addresses. Use some (reversible) public key encryption in your application and be sure that your private key is nowhere near to the database, so that they can't be "stolen" together.

That way, you can still unencrypt the email addresses to send emails,

Title: Should I keep email addresses as plaintext in database?

Body:
It's clear to everyone (I hope) that storing passwords without at least salting/hashing them is a terrible idea.

What about emails? Let's say you keep the subscription email address, if you encrypt it properly it may not be usable to send emails to the users. On the other hand, if you don't encrypt it and the database gets stolen, all your users risk a potential spam.

This question is not about law-specific issues (although they may be given, they remain country-dependent) or about encrypting the database itself.


问:
Leaving intentional bugs in code for testers to find
We don't do this at our firm, but one of my friends says that his project manager asked every developer to add intentional bugs just before the product goes to QA. This is how it works:

Just before the product goes to QA, the development team adds some intentional bugs at random places in the code. They properly back up the original, working code to make sure that those bugs aren't shipped with the end product.

Testers are also informed about this. So they will test hard,
because they know there are bugs present and that not finding them might
be considered as a sign of incompetence.

If a bug (intentional or otherwise) has been found, they will be reported for the development team to fix. The development team then adds another intentional bug in a related section of the code just before the product goes to the second-level QA. The project manager says a tester should think like a developer and he/she should expect new bugs in sections where changes were made.

Well, this is how it goes. They say that this approach has following advantages.

Testers will be always on their toes and they will test like crazy.
That helps them to also find hidden (unintentional) bugs so developers
can fix them.

Testers feed on bugs. Not finding any bugs will affect their morale.
So giving them an easy one to find will help their morale.

If you ignore the scenario where one of these intentional bugs gets shipped with the final product, what are the other drawbacks we should consider before even thinking of adopting this approach?

Some clarifications:

They properly backup the original code in source control.

When a tester finds the intentional bug, the development team just ignores it. If tester finds out an unintentional (original) bug, the development team first checks whether it is caused by any of the intentional bugs. That is, the development team first tries to reproduce that on the original working code and tries to fix it if they can.

Just ignore the relationship issues between QA and development team. I specifically asked this question on Programmers, not on The Workplace. Consider that there is good rapport between QA and the development team, and they party together after working hours. The project manager is a nice, old gentleman who is always ready to support both teams (Godsend).

答:
This sounds absolutely ridiculous. It is expending a great deal of effort for very questionable benefit, and the practice seems based on some faulty premises:

That QA won't work hard unless they know they are being tested every day (which cannot be good for morale)

That there are not enough unintentionally introduced bugs in the software for QA to find

That QA's job is to find bugs - it isn't; it is to ensure the software is production quality

That this kind of battle of wits between development and QA is in some way healthy for the company - it isn't; all employees should be working together against the company's competitors instead of each other.

It's a terrible idea and the project manager in question is a jerk/idiot who understands nothing about people and motivation. And it's bad for business.

To expand on my description of "QA's job:" QA definitely should be finding bugs - both in the code and in their test suites - as an artifact of doing their jobs, but the role shouldn't be defined as "you have to find bugs." It should be "you have to keep the test suites up-to-date to account for new features and ensure all high coverage of testing. If this does not result in finding bugs, then the testing procedures are not sufficiently sophisticated for the product.

ContentLicense: CC BY-SA 4.0


答: I think it's reasonable to assume that all users will have internet access most of the time, or at least at install time. However, if I take my laptop with me on a plane, to a cabin in the woods, or on a boat out at sea, I would expect anything that doesn't obviously require internet access to work fine.


答:
Bad idea.

From the tester's point of view: "So they will test hard, because they know there are bugs present and not finding them might be considered as their incompetence." Basically the devs are booby-trapping the code. Few people like doing work which is ultimately pointless (because the bugs are known in advance) but which still affect how they are perceived. If there are tangible punishments for not finding the booby-traps, more so. And do you know testers thrive on finding bugs? That sounds like a toxic confrontational environment; a QA should be happy if the code they are examining is high quality. Although if they are paid by the bug... http://thedailywtf.com/articles/The-Defect-Black-Market

From the dev's point of view: the QAs are being incentivised to find the bugs you know are there. That may well increase the likelihood of real bugs going out of the door; the QAs are spending at least some of their time looking for the sort of bug that is easy to plant, not really subtle ones. Plus there is a small chance that a booby-trap may make it out of the door.

Title: Leaving intentional bugs in code for testers to find

Body:
We don't do this at our firm, but one of my friends says that his project manager asked every developer to add intentional bugs just before the product goes to QA. This is how it works:

Just before the product goes to QA, the development team adds some intentional bugs at random places in the code. They properly back up the original, working code to make sure that those bugs aren't shipped with the end product.

Testers are also informed about this. So they will test hard,
because they know there are bugs present and that not finding them might
be considered as a sign of incompetence.

If a bug (intentional or otherwise) has been found, they will be reported for the development team to fix. The development team then adds another intentional bug in a related section of the code just before the product goes to the second-level QA. The project manager says a tester should think like a developer and he/she should expect new bugs in sections where changes were made.

Well, this is how it goes. They say that this approach has following advantages.

Testers will be always on their toes and they will test like crazy.
That helps them to also find hidden (unintentional) bugs so developers
can fix them.

Testers feed on bugs. Not finding any bugs will affect their morale.
So giving them an easy one to find will help their morale.

If you ignore the scenario where one of these intentional bugs gets shipped with the final product, what are the other drawbacks we should consider before even thinking of adopting this approach?

Some clarifications:

They properly backup the original code in source control.

When a tester finds the intentional bug, the development team just ignores it. If tester finds out an unintentional (original) bug, the development team first checks whether it is caused by any of the intentional bugs. That is, the development team first tries to reproduce that on the original working code and tries to fix it if they can.

Just ignore the relationship issues between QA and development team. I specifically asked this question on Programmers, not on The Workplace. Consider that there is good rapport between QA and the development team, and they party together after working hours. The project manager is a nice, old gentleman who is always ready to support both teams (Godsend).


答:
Well, based on what I've learned:

It's not a school nor job interview;

The testers are not children;

It's not a game;

It wastes company's money.

The QA are not there only to find bugs but also to worry about how intuitive the system is, what is the learning curve for the user, usability, and accessibility in general. For example: "Is the system ugly?", "Is the user color blind and stuff is red and green?" They should complain too.

The minimal requirements for a system to pass QA is usually described in a user story for that particular feature or in how magical the PO wanted the system to be in his head.

tl;dr

It's not only bugs, testers should grow out of this narrow view.


问:
Algorithm for merging multiple rows of data
I need an algorithm to merge multiple rows for data, where one column is the index column and if one or more rows have the same index value merge the column values into a single row, and lastly sort the rows one the index column.

ASCII ART Example:

```<code>Starting point:

------------------------------------
| IndexCurve | Column A | Column B |
------------------------------------
| 1          | 1        |          |
------------------------------------
| 2          | 5        | 5        |
------------------------------------
| 1          |          | 1        |
------------------------------------
| 2          | 5        | 5        |
------------------------------------
| 3          | 1        |          |
------------------------------------

Outcome:

------------------------------------
| IndexCurve | Column A | Column B |
------------------------------------
| 1          | 1        | 1        |
------------------------------------
| 2          | 5        | 5        |
------------------------------------
| 3          | 1        |          |
------------------------------------
</code>```

As you can see the empty columns have been merged, duplicates have been discarded and rows have been sorted on the index column. (NOTE: The column values should not add to each other.)

I have been trying to come up with an efficient algorithm for this but so far I think I have failed as i think its pretty ineffective and also its not working correctly.

Here I have some code to show you what I currently have, the first code pieces are just POCO objects to give you an idea of what I'm working with, have also included equal methods for you to see how I compare objects.

```<code>public interface IWitsmlLogCurveInfo
{
    string Mnemonic { get; set; }
    bool IndexCurve { get; set; }
}

public class WitsmlLogCurveInfo
{
    string Mnemonic { get; set; }
    bool IndexCurve { get; set; }

    protected bool Equals(WitsmlLogCurveInfo other)
    {
        return string.Equals(Mnemonic, other.Mnemonic);
    }

    public override bool Equals(object obj)
    {
        if(ReferenceEquals(null, obj))
        {
            return false;
        }
        if(ReferenceEquals(this, obj))
        {
            return true;
        }
        if(obj.GetType() != this.GetType())
        {
            return false;
        }
        return Equals((WitsmlLogCurveInfo)obj);
    }

    public override int GetHashCode()
    {
        return (Mnemonic != null ? Mnemonic.GetHashCode() : 0);
    }
}

public interface IWitsmlLogDataColumn
{
    IWitsmlLogCurveInfo WitsmlLogCurveInfo { get; set; }
    string Value { get; set; }
}

public class WitsmlLogDataColumn : IWitsmlLogDataColumn
{
    public IWitsmlLogCurveInfo WitsmlLogCurveInfo { get; set; }
    public string Value { get; set; }

    protected bool Equals(WitsmlLogDataColumn other)
    {
        return string.Equals(Value, other.Value) && string.Equals(WitsmlLogCurveInfo, other.WitsmlLogCurveInfo);
    }

    public override bool Equals(object obj)
    {
        if(ReferenceEquals(null, obj))
        {
            return false;
        }
        if(ReferenceEquals(this, obj))
        {
            return true;
        }
        if(obj.GetType() != this.GetType())
        {
            return false;
        }
        return Equals((WitsmlLogDataColumn)obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            return ((Value != null ? Value.GetHashCode() : 0) * 397) ^ (WitsmlLogCurveInfo != null ? WitsmlLogCurveInfo.GetHashCode() : 0);
        }
    }
}

public interface IWitsmlLogDataRow
{
    IList<IWitsmlLogDataColumn> Columns { get; set; }
    IWitsmlLogDataColumn GetIndexColumn();
}

public class WitsmlLogDataRow : IWitsmlLogDataRow
{
    public IList<IWitsmlLogDataColumn> Columns { get; set; }

    public IWitsmlLogDataColumn GetIndexColumn()
    {
        return Columns.SingleOrDefault(x => x.WitsmlLogCurveInfo.IndexCurve);
    }

    protected bool Equals(WitsmlLogDataRow other)
    {
        return Columns.All(x => other.Columns.Contains(x));
    }

    public override bool Equals(object obj)
    {
        if(ReferenceEquals(null, obj))
        {
            return false;
        }
        if(ReferenceEquals(this, obj))
        {
            return true;
        }
        if(obj.GetType() != this.GetType())
        {
            return false;
        }
        return Equals((WitsmlLogDataRow)obj);
    }

    public override int GetHashCode()
    {
        return (Columns != null ? Columns.GetHashCode() : 0);
    }
}

public enum FrictionType
{
    Annulus,
    Sliding,
    Rotating
}

public interface IWitsmlLogFriction
{
    FrictionType Type { get; set; }
    IList<IWitsmlLogDataRow> Rows { get; set; }
}

public class WitsmlLogFriction : IWitsmlLogFriction
{
    public FrictionType Type { get; set; }
    public IList<IWitsmlLogDataRow> Rows { get; set; }

    public override string ToString()
    {
        return string.Format("FrictionType: {0}", Type);
    }

    protected bool Equals(WitsmlLogFriction other)
    {
        return Type == other.Type && Rows.All(x => other.Rows.Contains(x));
    }

    public override bool Equals(object obj)
    {
        if(ReferenceEquals(null, obj))
        {
            return false;
        }
        if(ReferenceEquals(this, obj))
        {
            return true;
        }
        if(obj.GetType() != this.GetType())
        {
            return false;
        }
        return Equals((WitsmlLogFriction)obj);
    }

    public override int GetHashCode()
    {
        unchecked
        {
            return ((int)Type * 397) ^ (Rows != null ? Rows.GetHashCode() : 0);
        }
    }
}
</code>```

Here is the Algorithm Function itself:

```<code>private IList<IWitsmlLogDataRow> CombineMultipleFrictionTypes(IList<WitsmlLogFriction> witsmlLogFrictions, WitsmlLogCurveInfo indexCurve)
{
    if(indexCurve == null)
    {
        throw new NoNullAllowedException("IndexCurve can not be null!");
    }
    if(witsmlLogFrictions.Count == 1)
    {
        return witsmlLogFrictions.First().Rows;
    }
    WitsmlLogFriction witsmlLogFrictionA = witsmlLogFrictions.FirstOrDefault();
    List<IWitsmlLogDataRow> rows = new List<IWitsmlLogDataRow>();
    if (witsmlLogFrictionA == null)
    {
        return rows;
    }
    foreach(WitsmlLogFriction witsmlLogFrictionB in witsmlLogFrictions.Where(witsmlLogFriction => witsmlLogFriction.Type != witsmlLogFrictionA.Type))
    {
        foreach (IWitsmlLogDataRow witsmlLogDataRowA in witsmlLogFrictionA.Rows)
        {
            // Get index curve for row A
            IWitsmlLogDataColumn indexCurveA = witsmlLogDataRowA.GetIndexColumn();
            if (indexCurveA == null) continue;

            IWitsmlLogDataRow tempWitsmlLogDataRowA = new WitsmlLogDataRow(witsmlLogDataRowA.Columns);
            foreach(IWitsmlLogDataRow witsmlLogDataRowB in witsmlLogFrictionB.Rows)
            {
                // Get index curve for row B
                IWitsmlLogDataColumn indexCurveB = witsmlLogDataRowB.GetIndexColumn();
                if (indexCurveB == null) continue;

                // Compare index curve values
                if(indexCurveA.Equals(indexCurveB))
                {
                    // Index curve values are identical, append columns from row B onto row A, except row B's index column
                    foreach(IWitsmlLogDataColumn column in witsmlLogDataRowB.Columns.Where(column => !column.WitsmlLogCurveInfo.Equals(indexCurve)))
                    {
                        tempWitsmlLogDataRowA.Columns.Add(column);
                    }
                }
                else
                {
                    rows.Add(witsmlLogDataRowB);
                }
            }
            // Add the new row
            rows.Add(tempWitsmlLogDataRowA);
        }
    }
    switch(indexCurve.IndexType)
    {
        case LogIndexType.datetime:
            return rows.OrderBy(x => Convert.ToDateTime(x.GetIndexColumn().Value)).ToList();
        default:
            throw new ArgumentOutOfRangeException("indexCurve", "IndexType: " + indexCurve.IndexType + " is not supported.");
    }
}
</code>```

The problem is I think its pretty ineffective, but it could also be the only way to do it, and it adds more data then it should. What would be a better and efficient way to solve this?

答:
Sort your table by index

trivially merge all data with the same index (as they'll all be together), when the index changes to the next value, write the row and repeat.

You may take a hit on sorting, but generally its a common operation with lots of good existing algorithms that can efficiently sort your dataset well. After that, manipulating your sorted dataset is easy.


问:
Bundling style and script files in asp MVC layout page
How to bundle style and script files using layout in asp MVC?

Here is an example.

Layout1 uses style and script file for header and footer functionality. Sections are declared.

View1 uses Layout1 . It also contains style and script files in order to make this view work. Layout sections are updated using @section Sectioname.

Is there a way to bundle all styles and script files at View1? Should I bundle only files needed for Layout1 and apply it in layout code and add View1 files in @section?

What is a good way to resolve this issue?

答: if the scripts and styles that used in view1, will not be used in another views, the best way is to bundle them only at view1, but if they are common scripts and styles that will be used in many views, bundle them at layout.</p>