答:
I have had to deal with a similar situation, and this is how I solved it:

At the top of my file, I did not put the standard copyright notice, but rather a notice that the function contained held different copyrights.

Preceding each function implementation, I put a copyright notice pertaining to that function.

In my case, there were only a handful of functions in the file and two of them were copied from elsewhere.
If you have a different ratio between your own code and foreign code, you could also use this slightly different solution (which is possible because the license on the foreign code allows sub-licensing)

At the top of your file, augment the standard copyright notice to make it clear that some functions have additional copyrights.

Preceding the foreign function, place a copyright notice for that function containing the text from the LICENSE file that came with the original.
There is no need to include the LICENSE file itself in your distribution, as its contents are already reproduced at the relevant spot in the code.

Body:
How do I include the copyright/license for a library if I use on 1 function?

Say if I have a class that I have taking 1 function from another library:

```<code>class MyClass {
    ...
    public function someOtherLibrariesFunction() {}
}
</code>```

And the at the top of the file I took the function from it says:

```<code>/*
 * This file is part of the Other Library package.
 *
 * (c) James Smith <j.smith@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
</code>```

And the LICENSE file:

```<code>Copyright (c) 2004-2013 James Smith

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

...standard as is warranty...
</code>```

So my understanding is I would have to have a copy of the LICENSE file included with my code, and I would also somehow point out the exact function it it applies to?


问:
Write then optimise or write optimised
Do you write your code then optimise it? Or do you write an optimised code from the beginning.

I always believe in writing optimised since I really dont like to rewrite code, But please share your thoughts.

答: Write optimized when you know for sure that it will have an effect and is justified in the mean of code readability.

ContentLicense: CC BY-SA 3.0

Title: Write then optimise or write optimised


问:
Are UML class diagrams adequate to design JavaScript systems?
Given that UML is oriented towards a more classic approach to object orientation, is it still usable in a reliable way to design JavaScript systems?

One specific problem that I can see is that class diagrams are, in fact, a structural view of the system, and JavaScript is more behaviour driven, how can you deal with it?

Please keep in mind that I'm not talking about the real world domain here; it's a model for the solution that I'm trying to achieve.

答:
It seems that you can use UML for JavaScript, but it will depend on how you are going to approach your work.

Specifically JS/UML can automate UML documentation for JSDoc, Dojo, YUI.

I would guess that there's more out there but didn't run across anything else yet.


答:
The rule of thumb is this one (emphasis mine):

Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.

-- Donald E. Knuth, "Structured Programming with go to Statements"

Now, this doesn't mean you should write inefficient code. You should write efficient code if it doesn't take much more time than inefficient code. If you can do 1 SQL request instead of 100, please do so. If it doesn't take you much more time, that is.

This code might not be used very often, so it's actually not a bottleneck at all, even though it might seem inefficient. If writing it in an efficient way means spending too much time, there is no added-value to your business.

Then of course, if you have to optimize something because it's slow, never forget to profile first.

Some links that might interest you:

Is it always wrong to optimize before profiling?

Is micro-optimisation important when coding?

Title: Write then optimise or write optimised

Body:
Do you write your code then optimise it? Or do you write an optimised code from the beginning.

I always believe in writing optimised since I really dont like to rewrite code, But please share your thoughts.


答:
There's a simple order rule of three:

Get it right. Correctness is paramount, something that does the wrong thing fast or beautifully is useless.  This has to go deeper than "oh this seems to work okay" - it has to really work reliably for the entire domain of application that you are intending to use the code for.

Get it nice.  Elegance and simplicity of code is important.  The code you wrote under 1 is likely to have several prototype-like properties.  In this stage you may be able to reduce the amount of code from 1 drastically, make it a lot simpler, or both.  Having easy-to-understand, well-documented, elegant code makes it easier to move to the next step.  What often also happens here is that you may spot an algorithmic optimization to solve the same problem just as correctly.  These algorithmic optimizations are usually much cleaner, better and more effective than very low-level to-the-metal optimizations.

Get it fast.  Now that you know that it works, and how it works and it's well-documented, you have a look to see if you need to make it faster.  Usually you won't - see Florian's answer below.  Only if you absolutely do need to optimize (use a profiler!), you do that now.  You're starting from beautiful well-documented code.  You're likely to end up with much less beautiful arcane code if you're really optimizing hard - but that's okay, it's documented, and you have the beautiful version in your VCS history to refer back to as well.

Title: Write then optimise or write optimised


问:
Is it a good idea to format the code in eclipse using auto format
I use eclipse for coding, and the language which we use is Java.
Once it was suggested by someone that to properly format the code,
using the auto formatter(CTRL+SHIFT+F)
While this command does format the code, but sometimes I feel that overall
look becomes weird, and it is not actually very readable.

So is this a recommended thing to do?
If not what is the better of formatting our code in eclipse ?

答:
Whether or not it's recommended will depend on who you ask.

I can imagine that you would prefer to format code yourself, after all, you know what's best and easiest to read for yourself.
On the plus side, if you're a considerate person you can make it more readable for other human beings too.

Machines don't have that kind of foresight, and can (just like you said) make your code look like a bit of a mess, even if they format it by strict rules.

A good IDE or tool can often do a semi-decent job at formatting the code for you, but won't always make it as readable as you could.

So, my advice : don't use it unless you receive code from somebody else, and it's such a mess that you cannot read it otherwise.


问:
Best practice to sort then reverse, or write "backwards" comparator?
I wrote a comparator for a custom class of mine and when I ran my code I realised the output of my list of these objects was in the reverse order as to what I wanted. It was "ascending" as opposed to "descending". This was because I stuck to the spec of compare where a return value of less than 0 means the other object is less than this and so on.

To fix this I called the reverse method on my list, but I could've also changed the compare method so that it returns greater than 0 where the other object is less than this.

What is seen as the standard for this case and why?

答:
Comparer which makes it sorted in the right order is better. When you already use comparer (and you do in this case) it is better (faster/more by-the-book) to modify the comparer (or create another one).

Although, when sorting object which have "natural" comparison (for example: int) and "standard library" (for example: BCL for .NET) which can leverage this it might be faster to sort in natural order than reverse.

For example (C#), having:

```<code>int[] data = new int[1000000];
Random rand = new Random();
for (int i = data.Length - 1; i >= 0; i--) data[i] = rand.Next();
</code>```

sorting than reversing:

```<code>Array.Sort(data);
Array.Reverse(data);
</code>```

will be must faster than:

```<code>Array.Sort(data, (a, b) => b.CompareTo(a));
</code>```

It is not your case though, I just mentioned it for completeness.

Body:
Comparer which makes it sorted in the right order is better. When you already use comparer (and you do in this case) it is better (faster/more by-the-book) to modify the comparer (or create another one).

Although, when sorting object which have "natural" comparison (for example: int) and "standard library" (for example: BCL for .NET) which can leverage this it might be faster to sort in natural order than reverse.

For example (C#), having:

int[] data = new int[1000000];
Random rand = new Random();
for (int i = data.Length - 1; i >= 0; i--) data[i] = rand.Next();

sorting than reversing:

Array.Sort(data);
Array.Reverse(data);

will be must faster than:

Array.Sort(data, (a, b) => b.CompareTo(a));

It is not your case though, I just mentioned it for completeness.


答:
Start by ignoring any performance impact of reversing the list. Any sensible list-reversal will be linear in time, which means that for large lists, the sorting will dominate.

If there is a "natural" ordering of your elements (i.e. an ordering which is independent from your particular implementation), I would recommend sort + reverse. This will make the comparator easier to reuse, and it will be easier to understand the code which invokes the sort. Compare these two:

```<code>x = <array of integers>
x.sort(NaturalOrdering)
x.reverse
</code>```

and

```<code>x = <array of integers>
x.sort(MyOrdering) // what ordering is this?
</code>```

If there is no natural ordering (i.e. you are imposing an "artificial" ordering just to be able to sort elements), it probably makes more sense to have the comparator return the desired ordering directly.

If you are tempted to start optimizing at this point, please measure the code before and after you optimize. It is never obvious which implementation is the faster one.

Title: Best practice to sort then reverse, or write "backwards" comparator?

Body:
I wrote a comparator for a custom class of mine and when I ran my code I realised the output of my list of these objects was in the reverse order as to what I wanted. It was "ascending" as opposed to "descending". This was because I stuck to the spec of compare where a return value of less than 0 means the other object is less than this and so on.

To fix this I called the reverse method on my list, but I could've also changed the compare method so that it returns greater than 0 where the other object is less than this.

What is seen as the standard for this case and why?

Body:
Start by ignoring any performance impact of reversing the list. Any sensible list-reversal will be linear in time, which means that for large lists, the sorting will dominate.

If there is a "natural" ordering of your elements (i.e. an ordering which is independent from your particular implementation), I would recommend sort + reverse. This will make the comparator easier to reuse, and it will be easier to understand the code which invokes the sort. Compare these two:

x = <array of integers>
x.sort(NaturalOrdering)
x.reverse

and

x = <array of integers>
x.sort(MyOrdering) // what ordering is this?

If there is no natural ordering (i.e. you are imposing an "artificial" ordering just to be able to sort elements), it probably makes more sense to have the comparator return the desired ordering directly.

If you are tempted to start optimizing at this point, please measure the code before and after you optimize. It is never obvious which implementation is the faster one.


答:
Strict code formatting rules are useful when several developers work on the same code using a version control system. Merging can be a pain if different developers have different formatting rules as the same code would look different for the merging tool.

Eclipse (or any good IDE for that matter) has code formatting rules that can be customized in the preferences section (Java > Code Style > Formatter). Choose what you like best, but have also a look at the Java standard code conventions. Many open source projects also have their own code conventions that can be enforced with the Eclipse formatter.

In addition there are standard tools like CodeStyle, PMD and Findbugs that enforce additional rules and help avoid common (low-level) anti-patterns and mistakes.

Title: Is it a good idea to format the code in eclipse using auto format

Body:
I use eclipse for coding, and the language which we use is Java.
Once it was suggested by someone that to properly format the code,
using the auto formatter(CTRL+SHIFT+F)
While this command does format the code, but sometimes I feel that overall
look becomes weird, and it is not actually very readable.

So is this a recommended thing to do?
If not what is the better of formatting our code in eclipse ?


答: Your real problem is that you're using the wrong sorter.  Your comparator is correct, and (depending on the language) it may wind up being used for other cases where the comparison should not be reversed.  Instead of "fixing" (actually breaking) the comparator, you should find out how to get the sorter to sort in descending order.  Any decent sorting library will have that option.


答:
You should use it all the time to ensure that you use a consistent styling in all your source files. This will also save you a lot of time which you would usually spent trying to adjust the formatting manually.

The Java formatter in Eclipse does a pretty good job and is completely customizable. If you don’t agree with the default settings (which I can completely understand), then you should adjust the formatter to your own personal style preference or whatever is the standard you use. You can do that in the preferences under Java/Code Style/Formatter.

Formatters are even more useful when you are not working alone. It’s very likely that you and your team members will disagree on what you think is the perfect code style™. In that case you should agree to a common base and once and for all define formatter rules for this particular code styling. Then everybody can just hit the format-shortcut and everything fits the agreed styling. That way your personal preference (when writing) won’t get in the way. And note that the formatter styling can be stored in Eclipse’s project files, so different formatters for each project are possible too.


问:
What is tabular programming?
The Falcon programming language advertises itself as supporting tabular programming:

Falcon provides six integrated programming paradigms: procedural, object oriented, prototype oriented, functional, tabular and message oriented. And you don't have to master all of them; you just need to pick the ingredients you prefer, and let the code follow your inspiration.

The documentation expands a bit on how the language's flavour of tabular programming works, but it's focused on the language's own structures and syntax, and doesn't really explain the benefits of the paradigm (except of course those that are obvious from the simplistic examples).

I'm a bit confused on how the whole thing works internally, from what I understand Falcon's Table is a native structure that works more or less as a relational table and could be described (in OO vernacular) as a native Record Set with relational querying capabilities. A horrible description, I know (blame my OO roots and years of abusing tequila).

Could you help me get a better idea of what tabular programming is all about and how it works internally?

Clarification: I am not asking about Tabular Model Programming.

答:
Tabular programming is an alias of Table Oriented Programming paradigm (TOP). For TOP the key concept is a table as for Object Oriented Programming (OOP) the key concept is an object.

In general TOP language, tool, programming etc. deal with tables and focus on them. However a programmer can utilize certain paradigm even in languages that don't support nativly that paradigm. For instance languages that don't have keywords for defining classes and don't support syntax for operating on instances can be used to write object oriented code. For example in C language we can define a struct and put a reference to that struct into a function in order to simulate this pointer and method invocation. However OO code written in C++ or C# will be much more intuitive, compact, legible, flexible and less bug prone.

The Falcon is a language that support TOP nativly in terms that it contains built in programming structures to facilitate dealing with tables. Altough saying that Falcon constitutes TOP is like saying that C++ constitutes OOP. In fact, their are a tool, that facilitates or even enforces certain programming style.

I think, but maybe I'm wrong, that we should seek TOP ideas also in place that is created for operating especialy on tables. SQL Server and Analysis Services are an arena where tabular data focused operations are performed. In particular new Tabular Model Programming uses tables as key elements to deal with. I believe that there will be introduced more intuitive API support for tabular programming in the future. So I let myself to speak about TOP in context of Tabular Model Programming just as an another aspect of TOP beside Falcon.

Tabular Model Programming is used in Analysis Services which belongs to SQL Server Technologies so is closely associated with relational databases and business intelligence. Tabular mode is a new approach for creating a business intelligence semantic model as an alternative to multidimensional mode so it should be compared the latter. Each solution differs in how they are created, used, and deployed. Tabular mode is faster to design, test, and deploy. Is also familiar to audiences who work with relational databases, Excel, or Access. For more details and internals refer to Comparing Tabular and Multidimensional Solutions.

I think that the best way to understand what is a Tabular Model Programming is to use it in practice. Get through Tabular Modeling (Adventure Works Tutorial) and feel it.

Title: What is tabular programming?


答:
I've found the autoformatter very useful. Instead of constantly taking microdecisions on how the code should be formatted -- something which is error-prone and causes "cognitive friction" -- you can set up formatting rules and let Eclipse format the code for you (ideally automatically using "Save actions"). Of course, this requires that you have a code base with consistent formatting, or that you have the mandate to reformat the code according to the rules you setup.

Having "autoformat-on-save" enabled is a little like having incremental compilation, it allows your brain to stay focused on the code itself, instead of being concerned with trivial issues such as code formatting or syntax.

But yes, sometimes the autoformatter will mess up some nicely formatted table you have. In such cases I use "on/off tags". These are configured under the "on/off tags" tab in the code formatting profile. Using them, you can exclude regions in your code from being automatically formatted:

```<code>// @formatter:off

... my nicely formatted table here ...

// @formatter:on
</code>```

Body:
I've found the autoformatter very useful. Instead of constantly taking microdecisions on how the code should be formatted -- something which is error-prone and causes "cognitive friction" -- you can set up formatting rules and let Eclipse format the code for you (ideally automatically using "Save actions"). Of course, this requires that you have a code base with consistent formatting, or that you have the mandate to reformat the code according to the rules you setup.

Having "autoformat-on-save" enabled is a little like having incremental compilation, it allows your brain to stay focused on the code itself, instead of being concerned with trivial issues such as code formatting or syntax.

But yes, sometimes the autoformatter will mess up some nicely formatted table you have. In such cases I use "on/off tags". These are configured under the "on/off tags" tab in the code formatting profile. Using them, you can exclude regions in your code from being automatically formatted:

// @formatter:off

... my nicely formatted table here ...

// @formatter:on


问:
A weakness of the TDD method?
This is in summary the TDD method:

Write a test

check if thes test fails

write production code

run test

I think that TDD as presented  works only in ideal circumstances. I'll take a simple example:

Specification:
Write a program that calculates the square root of a number, the user must enter a number. If the number is negative, the program should display an error, and if the number is positive or zero the program should display the number whose square is the number entered, or for decimal number whose square is closest to the number entered.

Writing test

```<code>class SquareRootTest {

   private SquareRoot squareRoot;

   public void testNegativeNumber() {
      assertException(squareRoot.execute(-5);
   }

   public void testIntegerSquareRoot() {
      assertEqual(squareRoot.execute(9),3);
   }

   public void testDecimalSquareRoot() {
     assertEqual(squareRoot.execute(3),1.732);
   }
}
</code>```

run failed test

writing production code:

```<code>class SquareRoot {

 public double execute(Number number) {
     if(number < 0)
         throw exception;
     if(number < 1)
         return squareRootLessThanOne(number);
      else
         return squareRootGreaterThanOne(numner);
   }

//private methods....

}
</code>```

this is when writing production code, I find that I have to deal with the numbers lower than one differently from those numbers greater than 1. So I need to update my tests to reflect this.

Updating test

```<code>class SquareRootTest {

   public void testNegativeNumber() {
       assertException(squareRoot.execute(-5));
   }

   public void testIntegerSquareRoot() {
       assertEqual(squareRoot.execute(9),3);
   }

   public void testDecimalSquareRoot() {
      assertEqual(squareRoot.execute(3),1.732);
   }

   public void testNumberLowerThanOne() {
      assertEqual(squareRoot.execute(0.04),0.200);
   }
}
</code>```

If I had found a single algorithm to calculate the square root, I would not change my tests.

The TDD method focuses solely on tests from specifications, yet there are tests that are derived from the implementation, particularly all conditional instructions and all instructions controlled by loops should normally be tested. These tests case can not be detected at the time of specification.

My question: How does TDD will deal with this situation? or is effectivelly a weakness of the TDD?

答:
The TDD method focuses solely on tests from specifications

No. It doesn't. TDD encourages adding tests based on your implementation. At each stage of your implementation you are looking for a test that will fail. You add that test, and then make it pass.

So in your case, when you found that numbers less than one have to be deal with differently, you'd start by adding a test for those numbers which failed your implementation. Then you'd add the less than one version.

Title: A weakness of the TDD method?


问:
Best practice for creating a 'global' config class used by numerous components
I have a large project with a driver part and about 5 libraries doing various associated tasks.  Many of the libraries require access to 'global' configuration data which is read from a database at startup by the driver code.  By driver I just mean the part which contains the main function.

My idea on how to handle this was to create a config class with a static method to get the config items.  Is this the best approach?  How else could this be achieved?

eg:

```<code>class config {
 public:
   static get_item(key);

 private:
   static values;
};
</code>```

Is singleton design appropriate here?

答:
The non-singleton way is to create a regular configuration class with regular properties / members, instantiate that object with the correct settings from the database in the driver, and pass the instance to all of the libraries - probably through a std::shared_ptr.  This is a common design pattern called Dependency Injection.

That way you avoid all of the potential issues from the singleton design pattern and your code will be more testable as you can instantiate an instance of your configuration class any way you like, with any data, for testing.


答:
I think this is one of the times where a Singleton is actually the correct thing to do.

Regarding the interface of the class itself, you could either do get-by-key-name or have accessors for the individual config values. The latter scheme affords some convenience (IDE completion for one) and allows you to cast the config values to their correct datatypes before using them. It also introduces some separation between the users of the config class and its internal implemntation (the fact that all config values are stored as, say, strings, is an implementation detail the user of the class should not worry about).

Title: Best practice for creating a 'global' config class used by numerous components

Body:
I have a large project with a driver part and about 5 libraries doing various associated tasks.  Many of the libraries require access to 'global' configuration data which is read from a database at startup by the driver code.  By driver I just mean the part which contains the main function.

My idea on how to handle this was to create a config class with a static method to get the config items.  Is this the best approach?  How else could this be achieved?

eg:

```<code>class config {
 public:
   static get_item(key);

 private:
   static values;
};
</code>```

Is singleton design appropriate here?


问:
How to implement a Theme for View Controllers in an iOS app?
I have an application, where font size, font type, color, background color, image and a lot of things change based on theme.

I realised in the beginning itself that using enums to denote themes and then checking the theme everywhere was a horrible mistake.

So I have two approaches now and I am confused which one to go with.

Keep a Base View Controller for my app with default look and feel of the application and then create a subclass per theme.

Or

Create a Theme class which will provide theming information and then subclass it  per theme and set the theme Object on the view controller and query theme object before applying the theme.

Or

There could be another approach I haven't thought about :)

答:
You're right to want to change technique.  You can imagine all the work you'd have to do everytime you need to add a new theme.

Subclassing View/Controller

Some programmers may choose to subclass the base view controller in order to take into consideration multiple themes.  If the adaptations you have to apply between theme to theme is radically different, then this approach is fine.  However, most times themes share a lot of common features, and you may end up having to change very little between them.

Subclassing Theme

The second approach eliminates this problem by having a shared "theme" class which does a lot of the work common among themes.  It also keeps your view class single-purposed (and therefore easier to read) and doesn't have to worry about little nuances like theme changes.  Since this approach eliminates all the disadvantages of the 1st approach with no added disadvantages of its own (unless "excess classes" is something you consider a disadvantage), this approach is the best practice in general.

Do the best you can to use inversion-control principle and have your view/controller call the theme class in order to do theme-specific tasks like draw a control, passing all the necessary information about said control into the method.  In this way, your theme is stateless and you retain control in your controller without having to know how it works.  Plus, you can have a base theme behavior in your basic theme class so you even if you do not override method, you're sure to always see something, even if it may not be themed properly.

I hope that helps.


问:
Using sounds on distributable app - Copyright issue
I've created an app that has some sound file that I've downloaded from Macloops. The user can only listen these sound files (he can't create any new sound files using them) with the app. Now, I want to distribute the app over the internet and I'd like to know if I can do this legally. I've only found the following the Macloops' website about copyright :

Macloops membership disclaimer/terms & conditions.

By joining the Macloops website, you are accepting these Terms and Conditions.

You accept that Macloops.com is part of Siliconbeats.com and you grant us the right to send you occasional emails regarding our latest news and developments. Your email address will not be sold to any mailing list organizations and the content of our emails will be related to samples, loops and music making resources that we have to offer.

Whilst all reasonable efforts are made to ensure that all downloadable material is virus free, we strongly recommend the use of professional virus checking software. Playing sounds at excessive volumes can cause damage to hearing. Use common sense when playing sounds and ensure that volume levels are sensible.

Macloops cannot be held responsible for injury or damage caused from use of files and sounds. All members and nonmembers are totally responsible for ALL Internet access charges. No exceptions are made. The period of membership for all members is at the discretion of the site administrators. Macloops reserves the right to deactivate or remove your account at any time. Macloops cannot be held liable for any damage to hardware, software or equipment resulting from the use of any files or sounds obtained directly or indirectly from the Macloops website.

By joining the Macloops website, you are accepting to be bound by these Terms and Conditions.

There is nothing about using the sound files. So am I allowed to distribute my app?

答:
Right on their landing page:

All of the Apple loops that Macloops offers are free for you to
  download and use in your music. If you wish to use our apple loops in
  any type of professional or commercial capacity you must purchase
  those loops from the original sample source to be licensed. We provide
  links to the original source of all the loops available on Macloops.

So it looks like you would have to purchase a licence if you want to use them in a commercial product.


答:
It's on the very first page of the site. I've emphasized the relevant bits.

How can I use your free Apple Loops?

All of the Apple loops that Macloops offers are free for you to download and use in your music. If you wish to use our apple loops in any type of professional or commercial capacity you must purchase those loops from the original sample source to be licensed. We provide links to the original source of all the loops available on Macloops.

If you only want to use these loops for personal use which will never be used commercially then you do not need to purchase a license. if you have any doubts or questions regarding usage rights please contact us directly.

Title: Using sounds on distributable app - Copyright issue

Body:
I've created an app that has some sound file that I've downloaded from Macloops. The user can only listen these sound files (he can't create any new sound files using them) with the app. Now, I want to distribute the app over the internet and I'd like to know if I can do this legally. I've only found the following the Macloops' website about copyright :

Macloops membership disclaimer/terms & conditions.

By joining the Macloops website, you are accepting these Terms and Conditions.

You accept that Macloops.com is part of Siliconbeats.com and you grant us the right to send you occasional emails regarding our latest news and developments. Your email address will not be sold to any mailing list organizations and the content of our emails will be related to samples, loops and music making resources that we have to offer.

Whilst all reasonable efforts are made to ensure that all downloadable material is virus free, we strongly recommend the use of professional virus checking software. Playing sounds at excessive volumes can cause damage to hearing. Use common sense when playing sounds and ensure that volume levels are sensible.

Macloops cannot be held responsible for injury or damage caused from use of files and sounds. All members and nonmembers are totally responsible for ALL Internet access charges. No exceptions are made. The period of membership for all members is at the discretion of the site administrators. Macloops reserves the right to deactivate or remove your account at any time. Macloops cannot be held liable for any damage to hardware, software or equipment resulting from the use of any files or sounds obtained directly or indirectly from the Macloops website.

By joining the Macloops website, you are accepting to be bound by these Terms and Conditions.

There is nothing about using the sound files. So am I allowed to distribute my app?


问:
Why the ugly keywords in C11?
I am currently reading a draft of the C11 specification. The new introduced keywords: _Bool, _Alignof, _Atomic all feel like custom extensions, instead of standard reserved keywords like struct, union, int.

I realize that the standard basically consists of standardized extensions ... but still, this is awful! Maybe we will soon end up with __Long_Long_Reallylong_Integer_MSVC_2020_t creeping in the standard!

Is the backward compatibility of nonstandard code the only reason of the new style of the keywords?

答:
I imagine that backwards compatibility with perfectly standard code is a more important reason.

If you add a keyword that might have been used as a legitimate identifier in previous code, you create a ton of pain, of possible subtle errors, especially in C, a language with somehow complicated parsing rules.

If these identifiers were used as a public interface somewhere, you add pain to all users of such unfortunate libraries, who might not use C at all, but call the library from Ruby, or Python, etc.

That's why new keywords are bound to look less like nice words and more like bolt-on hacks that people have smaller chances of already using for another purpose.

Title: Why the ugly keywords in C11?


答:
Names beginning with an underscore and a capital letter (and anything with double underscore) were reserved for compiler/standard library implementation in previous standards.

From Reserved Identifiers of C89 and C99:

Also reserved for the implementor are all external identifiers
  beginning with an underscore, and all other identifiers beginning with
  an underscore followed by a capital letter or an underscore.

So in theory, those new keywords should not be in use in any code writen before and that leads to better backward compatibility than any simple name, which is likely the only reason.

Title: Why the ugly keywords in C11?

Body:
I am currently reading a draft of the C11 specification. The new introduced keywords: _Bool, _Alignof, _Atomic all feel like custom extensions, instead of standard reserved keywords like struct, union, int.

I realize that the standard basically consists of standardized extensions ... but still, this is awful! Maybe we will soon end up with __Long_Long_Reallylong_Integer_MSVC_2020_t creeping in the standard!

Is the backward compatibility of nonstandard code the only reason of the new style of the keywords?


问:
How to organize the quality testing of a large website?
I developed a pretty big website. I tested it myself to the best of my ability, but I cannot test all scenarios that my users may run in to.

I found a testing team in India, but they don't seem to have any systematic approach to testing website functionality. They test each individual page rather than the full process that user takes on website.

What processes or tools should I use to thoroughly test my website?

答:
While automated tests are good to find regressions our testers are very effective in finding new bugs because

there is a dedicated environment for the testers that is different from developer- and differerent from production-system.

there are written requirements the testestes can test against.

every feature is assigned to a productversionnumber

every deployment to the testers-system will increase the productversionnumber

the testers have excellent knowledge about the business, usecases and workflows.

According to the DISC assessment model
good testers should have a strong C-ompliance preference.


问:
What are the worst false economies in software development?
What are the worst false economies (that is ways of saving money that ultimately cost more than they save) prevalent in the software industry and how do you combat them?</p>

答:
Providing single-screen workstations because a second monitor is too expensive. Even if it only saves you an hour of work each year, an second screen is still a good investment. I know for sure that mine has saved me many, many hours of work.

A Multi-monitor setup can make almost any task more efficient, not only development tasks. Three monitors is even better than two, but the effect becomes less pronounced with every extra screen.

Multi-monitor setups:

decrease window switching overhead

allow you to keep an eye on stuff running in the background (mail, compilation, etc.).

give you a feeling of freedom. It's like being in an atrium vs. being in a broom closet.

etc...

ContentLicense: CC BY-SA 2.5


问:
balancing old cases with agile practices
My team is just getting started integrating agile practices (we've chosen kanban) into our dev, test and design teams, but we have a lot of bug cases and feature cases not written in user stories left over from the old system and we're trying to find a good way to take care of the bugs but still keep the devs that need to stay heads down focused. for now we have a newer dev assigned to bug fixes so the rest can work on new features but we are looking for the right way to structure the team. We have 7 devs, 2 testers and 2 designers.

Thanks in advance for the help :)

答:
Place the bug items on your Kanban board like everything else (in prioritized order of course) and then let the team decide who should implement the next item in the queue.

I believe the team knows best how to handle this, rather than having someone else distribute the items among specific team members. At least that will give them an opportunity to self-organize. This being agile and all.


答:
Finish the old bug cases and feature requests as usual and slowly begin to implement the kanban system as new bug cases and feature requests come in.

OR

Have some devs or other people in the office create user stories for the old bugs before progressing.

Title: balancing old cases with agile practices

Body:
My team is just getting started integrating agile practices (we've chosen kanban) into our dev, test and design teams, but we have a lot of bug cases and feature cases not written in user stories left over from the old system and we're trying to find a good way to take care of the bugs but still keep the devs that need to stay heads down focused. for now we have a newer dev assigned to bug fixes so the rest can work on new features but we are looking for the right way to structure the team. We have 7 devs, 2 testers and 2 designers.

Thanks in advance for the help :)


问:
CQRS with Repository pattern and Inversion of Control (with DI)
I assigned a POC project to someone where I asked to implement both Command Query Responsibility Segregation, Inversion of Control (with Dependency Injection) and Repository pattern.  “Someone” gave me a POC solution project but I am not sure whether this is the way it is done. I will brief here about the POC project

The project is a simple 3-tier application – the Presentation Layer (PL), the Business Logic Layer  (BLL) and the Data Access Layer (DAL); each tier being a separate project

The Presentation Layer is a Web Application, the BLL and DAL are class library projects

In the Business Layer, there are defined Repository Interfaces. The reference of BLL library is added to DAL project and inside the DAL project there are concrete classes that implement the Repository Interfaces. This is how Inversion of Control is applied

Since Command-Query-Responsibility-Segregation is done, the repository interfaces in the Business Layer only declare Add/Update and Delete methods. For read, there are “Read” interfaces directly in the DAL and in the DAL there are concrete classes that implement these interfaces.

The Presentation Layer contains reference to both the BLL library and the DAL library. Calls to Add/Update/Delete are routed through the BLL to the DAL while any read is done directly from the DAL. I believe this conforms to Command-Query-Responsibility-Segregation concept of bypassing the BLL for doing reads.

Here is an illustration of how this is all setup. There are three projects

NW.Web

NW.Business

NW.DataAccess

Below is a snapshot of code in the different layers.

-- NW.Web --

// A class in the Presentation Layer
public class CustomerPage
{

    // Business layer Interface from  NW.Business namespace
    private ICustomerBusiness ICustB;

    //DAL Read interface from NW.DataAccess.Read namepsace
    private ICustomerRead<Guid> ICustR;

    //Constructor for the Customer Page that uses Constructor Injection
  public CustomerPage(ICustomerBusiness ICustB, ICustomerRead<Guid> ICustR)
    {
        this.ICustB = ICustB;
        this.ICustR = ICustR;
    }
}
```

<p><strong>-- NW.Business --</strong></p>

<pre class="lang-cs prettyprint-override"><code>//Declaration of business interface in the Business Layer
interface ICustomerBusiness
{
    void Persist();
}

// A class in the Business Layer that implements the business interface
public class Customer: ICustomerBusiness
{
    //Repository interface object that will be injected by Constructor Injection.
    private ICustomerRepository ICustRep;

    public Customer(ICustomerRepository ICustRep)
    {
        this.ICustRep = ICustRep;
    }

    public void Persist()
    {

            ICustRep.AddOrUpdate();

    }
}

//Declaration of Repository interface in the Business Layer
public interface ICustomerRepository
{
    void AddOrUpdate();
    void Delete();
}
</code>```

-- NW.DataAccess--

public class CustomerRepository : ICustomerRepository
{

    public void AddOrUpdate()
    {
        //implementation of Add or Update
    }

    public void Delete()
    {
        //implementation of Delete
    }
}

//A Read interface in the Data Access Layer
interface ICustomerRead<T>
{
   // A read is returned as DTO since in Database this may map to more than 1 table
    CustomerDTO GetCustomerDetails(T id);
}

// An implementation of the Read Interface in the Data Access Layer
namespace NW.DataAccess.Read
{
    public class CustomerRead<T> : ICustomerRead<T>
    {

        public CustomerDTO GetCustomerDetails(T id)
        {
           //implementation here
        }
    }
}
```

My gut feeling is that there is something wrong here. It seems CQRS or at least the above implementation does not address some requirements

The Customer Business object (Customer class) may need to read from Database for its internal purpose (like initializing variables etc). With read directly defined in DAL layer, the only way to do this would be to reference the DAL dll in the BLL. But this would create circular reference and go against the IOC that is done

What happens when there is some common Read requirement across all business objects ?

答:
I think you need to create an interface in the BLL that holds your connection (datacontext, sqlConnection, or whatever).  That concrete class would then go into the DAL.  On initialization you would include the connection string.

When you do a data read function you would pass along the datacontext or whatever you used for the connection.  You could also send the connection along upon initialization.

Does that make sense?  You can look at the link below to get an idea on the data access interface.

http://vbsoftwaredeveloper.blogspot.com/2013/05/4-tier-ioc-application-converted-tier.html


问:
How do I split out a service layer
I currently have four projects in my website's solution:

Project.Data

This holds the EntityFramework DbContext object and also the Repositories that interact with it. It references Project.Models.

Project.Models

This holds the business objects and doesn't reference any other project

Project.Web

This holds all ViewModels, Views, Controllers and static website content. It references Project.Data (for the Repositories), Project.Models and Project.Service

And now I get to the problem project...

Project.Service

I want this to be the project that Project.Web uses to make its controllers thin, as I understand this is desirable.

Each of the classes in this project will probably have a repository injected into it so they can access any data they need to. One of their responsibilities will be to create a ViewModel for the controllers in Project.Web to use. This means that it will reference Project.Data for a reference to those repositories, Project.Models for the models and Project.Web for access to the ViewModels.

So just as I'm getting the feeling I'm doing something really wrong by all this, I go to add my last reference to Project.Web from Project.Service and it errors out telling me that I now have a circular dependency...

What exactly am I doing wrong here? Are there patterns I can use that will clean up some dependencies on other projects or am I trying to do something that isn't useful anyway?

答:
I think what you're trying to create is:

Data => Services => Controller | VM => View

But what you're setting up isn't lending itself to that.

As Jimmy Hoffa points out, you need to think of your end-points.  It's not clear to me exactly what roles you're intending with your existing project names.  So I'll provide my answer using slightly different descriptors.  Plug your projects in as appropriate.

Your Data Access Layer(DAL) is an endpoint, as is your Views.

Views will reference the Controller | ViewModel project.

Controller | VM project will reference your Model and / or Services project.  Which one(s) depends upon your terminology.

If you have a Model, it will reference your Services project.

Finally, the Services project will reference your DAL.

Title: How do I split out a service layer


问:
How do you name your private variables in C#?
What is the best practice, most commonly accepted naming conventions for private variables in C#?

private int myInteger;

private int MyInteger;

private int mMyInteger;

private int _myInteger;

private int _MyInteger;

Mysterious other option

Which do you use and why?  (My company is fairly new to C# and I would like to pick the most "industry accepted" method to try and get into our coding standard.)

答:
I use 4 (private int _myInteger;) because:

private int myInteger;

This is how I name my local variables.

private int MyInteger;

This is how I name constants.

private int mMyInteger;

This is not C# style.

private int _MyInteger;

This looks strange.


问:
What are the most popular IDEs per language?
This has nothing to do with having a favourite editor or anything like that. I was just wondering, per language, what are the most popular Integrated Development Environments? Maybe a top 2-3 if there is some contention. (Perceived popularity is enough)

Thus Far:

C# - Visual Studio, SharpDevelop

Java - Eclipse, NetBeans, IDEA

Objective-C - Xcode

Delphi - RAD Studio

Object Pascal - Delphi, Lazarus

C, C++ - Visual Studio, Vim

PL/SQL - RapidSQL, Oracle SQLDeveloper

PHP - Eclipse, NetBeans, Nusphere PHPed

Actionscript (AS2, AS3) - FlashDevelop

Flex - Flash Builder 4

Python - Eclipse, IDLE

Perl - Padre

Common Lisp - Lispworks, Emacs

Ruby - TextMate

Haskell - Vim

Fortran - Vim

Visual Basic - Visual Studio

答: If you're including Vim, then Notepad++. I use it for most languages, including Java (compiled with Ant) and smaller C++ projects (compiled with MinGW), and it seems to be pretty popular in general, especially for web development. It has more/better features than some of the more popular IDE's I've used, even. I do prefer using Visual Studio for C# and XCode for Objective-C, though.</p>


问:
Where should I parse data obtain with a DAO
I have a DAO that brings data from a web service, that data comes in a string, in the likes of:

```<code>*NAME|John Doe *DATEOFBIRTH|1978-23-01*ID|anID123 (...)
</code>```

I have a DTO that I wanna fill up with the parsed data (the DTO has fields in the like of name, birthdate, id...)

So, my question is, what is the best practice:

Parsing the string in the DAO to fill up the DTO

Passing the data string to the DTO and the DTO itself parse the string and fill itself up

Do the parsing in an utility class that would receive the string and return the fill up DTO

DAO: Data Access Object

DTO: Data Transfer Object

Note: I kept this language agnostic so it could be useful to anyone using object oriented languages, but, in my particular case, I'm using Java.

答:
The DTO should be responsible for filling up its own fields from the parsing result, because the fields are specific to the DTO.

The parsing itself can take place elsewhere, but Java has a Split() function, so your DTO already knows how to parse it.  So just hang a Parse(string) function onto your DTO.


答:
To re-frame your question,"What is the quality of my website?"

Testing is a simple means of measuring that quality. But, there are other means that can achieve some of those same results:
- paired programming
- code review
- test driven development
...

So, the next question in turn becomes "How do I measure quality?"

From that becomes what your traditional testers deliver, but really anyone could deliver:  business, developer, or tester.

So, what do you want to deliver that measures quality?
- defects
- coverage
- customer use cases

I would highly recommend a layered approach similar to what was mentioned in earlier posts:
-unit tests
-integration tests
-user acceptance tests

In regards to user acceptance tests I would highly recommend an Behavior Driven Development (BDD) approach or a test approach similar to Specification by Design.  A few example framworks around this are Cucumber or Robot Framework.

Title: How to organize the quality testing of a large website?

Body:
I developed a pretty big website. I tested it myself to the best of my ability, but I cannot test all scenarios that my users may run in to.

I found a testing team in India, but they don't seem to have any systematic approach to testing website functionality. They test each individual page rather than the full process that user takes on website.

What processes or tools should I use to thoroughly test my website?


答:
Typically an unmarshalling construct can be used.

The job of the unmarshaller would be simply to translate from the string to your domain specific DTO. Your DAO or DTO will not need to change if the transmission format changes. Additionally, the unmarshalling strategy can be mocked out for unit tests (and tested separately). Depending on your enterprise architecture pattern, you can invoke the unmarshaller anywhere (in the DAO, the DTO, using AOP, ...).

Many widely used software packages use the marshalling/unmarshalling concept including Spring, JAXB, and the AWS Java SDK. I suggest that you take a look at these libraries to get some ideas as to how you can implement and fit into your design (you may find a ready made solution that fits your needs).

Title: Where should I parse data obtain with a DAO

Body:
I have a DAO that brings data from a web service, that data comes in a string, in the likes of:

```<code>*NAME|John Doe *DATEOFBIRTH|1978-23-01*ID|anID123 (...)
</code>```

I have a DTO that I wanna fill up with the parsed data (the DTO has fields in the like of name, birthdate, id...)

So, my question is, what is the best practice:

Parsing the string in the DAO to fill up the DTO

Passing the data string to the DTO and the DTO itself parse the string and fill itself up

Do the parsing in an utility class that would receive the string and return the fill up DTO

DAO: Data Access Object

DTO: Data Transfer Object

Note: I kept this language agnostic so it could be useful to anyone using object oriented languages, but, in my particular case, I'm using Java.


问:
Web Application Licensing - Open Source vs Proprietary
I am developing a web application based on a proprietary (but free) JavaScript API. My company is considering releasing our application as "Open Source", but we are unsure of the different licensing options and how they will work considering we are using a third-party proprietary API.

Can anyone help me with the following questions?

If we cannot release the third-party API as open source, can we release the code that we have written as open source?

Are we, as the original developers, held to the same license that we release our code with? For instance, if we release our code under a "copy-left" license like GPL, would that restrict us from building on the original code base and releasing it in another product that is not open source?

What is the best resource for learning the difference among all the different license types? I looked at opensource.org, which listed all the licenses, but I have trouble understanding all the legalese of the licenses themselves.

答:
First of: I am not a lawyer, this is not legal advice, consult a real lawyer before proceeding.

That would depend on the license of the third-party code. Also, you will have to choose a license that allows linking to a proprietary libs. Consult the company from which you got the library - and a lawyer.

You can release your code under as many different licenses as you want, provided you own the copyright. Basically, your company can release the code it has written e.g. both licensed as GPL and using a proprietary license and charge for the proprietary license. However, if you accept contributions from the community without demanding copyright assignment, those contributions will have to be dealt with according to the license under which the contributor submitted them to you. Keeping this straight and legally above reproach entails a lot of bookkeeping. Consult a lawyer.

Opensource.org is a good starting point, then look at the webpages of the respective authors, they often provide a "plain english" explanation of the license. To get a definitive answer, consult a lawyer.


答:
One test at a time.  You say it should throw an exception if given a negative argument?

```<code>public double execute(Number number) {
    throw exception;
}
</code>```

Now it passes the first test.

You say it should return 3 if given 9?

```<code>public double execute(Number number) {
    if (number.equals(9))
        return 3;
    throw exception;
}
</code>```

Now it passes both tests.

But you know you're not done.  You know you've just been putting in dummy values, dummy logic.  You add tests to drive it to a correct solution, and you'll know when it's easier to put in the correct solution than to add yet another dummy branch.

I believe the problem you are having in understanding TDD is the thought that all tests are written up front.  They're not.  Write one, make it pass.  Write the next one, make it pass (without breaking the first one).  Refactor when green.  That is TDD, not translating a full spec into tests and then making them pass.

Title: A weakness of the TDD method?

Body:
This is in summary the TDD method:

Write a test

check if thes test fails

write production code

run test

I think that TDD as presented  works only in ideal circumstances. I'll take a simple example:

Specification:
Write a program that calculates the square root of a number, the user must enter a number. If the number is negative, the program should display an error, and if the number is positive or zero the program should display the number whose square is the number entered, or for decimal number whose square is closest to the number entered.

Writing test

```<code>class SquareRootTest {

   private SquareRoot squareRoot;

   public void testNegativeNumber() {
      assertException(squareRoot.execute(-5);
   }

   public void testIntegerSquareRoot() {
      assertEqual(squareRoot.execute(9),3);
   }

   public void testDecimalSquareRoot() {
     assertEqual(squareRoot.execute(3),1.732);
   }
}
</code>```

run failed test

writing production code:

```<code>class SquareRoot {

 public double execute(Number number) {
     if(number < 0)
         throw exception;
     if(number < 1)
         return squareRootLessThanOne(number);
      else
         return squareRootGreaterThanOne(numner);
   }

//private methods....

}
</code>```

this is when writing production code, I find that I have to deal with the numbers lower than one differently from those numbers greater than 1. So I need to update my tests to reflect this.

Updating test

```<code>class SquareRootTest {

   public void testNegativeNumber() {
       assertException(squareRoot.execute(-5));
   }

   public void testIntegerSquareRoot() {
       assertEqual(squareRoot.execute(9),3);
   }

   public void testDecimalSquareRoot() {
      assertEqual(squareRoot.execute(3),1.732);
   }

   public void testNumberLowerThanOne() {
      assertEqual(squareRoot.execute(0.04),0.200);
   }
}
</code>```

If I had found a single algorithm to calculate the square root, I would not change my tests.

The TDD method focuses solely on tests from specifications, yet there are tests that are derived from the implementation, particularly all conditional instructions and all instructions controlled by loops should normally be tested. These tests case can not be detected at the time of specification.

My question: How does TDD will deal with this situation? or is effectivelly a weakness of the TDD?

Body:
One test at a time.  You say it should throw an exception if given a negative argument?

public double execute(Number number) {
    throw exception;
}

Now it passes the first test.

You say it should return 3 if given 9?

public double execute(Number number) {
    if (number.equals(9))
        return 3;
    throw exception;
}

Now it passes both tests.

But you know you're not done.  You know you've just been putting in dummy values, dummy logic.  You add tests to drive it to a correct solution, and you'll know when it's easier to put in the correct solution than to add yet another dummy branch.

I believe the problem you are having in understanding TDD is the thought that all tests are written up front.  They're not.  Write one, make it pass.  Write the next one, make it pass (without breaking the first one).  Refactor when green.  That is TDD, not translating a full spec into tests and then making them pass.


问:
What does "downstream/upstream design" mean?
What does "downstream/upstream design" in software development mean?</p>

答:
Upstream = up the well (the origin of the software)
Downstream = downwards to the ocean (of use cases)

Open Source developers who are "downstream" build applications and tools on the finished products. Those who are upstream actually work on the products to be released.

If you develop software: you depend on the stability of the upstream development. And those who work on your software are downstream developers.

OwnerDisplayName: iSeiryu


问:
How to unit test method that returns a collection while avoiding logic in the test
I am test-driving a method that is to generate a collection of data objects. I want to verify that the properties of the objects are being set correctly. Some of the properties will be set to the same thing; others will be set to a value which is dependent on their position in the collection. The natural way to do this seems to be with a loop. However, Roy Osherove strongly recommends against using logic in unit tests (Art of Unit Testing, 178). He says:

A test that contains logic is usually testing more than one thing at a time, which isn't recommended, because the test is less readable and more fragile. But test logic also adds complexity that may contain a hidden bug.

Tests should, as a general rule, be a series of method calls with no control flows, not even try-catch, and with assert calls.

However, I can't see anything wrong with my design (how else do you generate a list of data objects, some of whose values are depended on where in the sequence they are?—can't exactly generate and test them separately). Is there something non-test-friendly with my design? Or am being too rigidly devoted to Osherove's teaching? Or is there some secret unit test magic I don't know about that circumvents this problem? (I'm writing in C#/VS2010/NUnit, but looking for language-agnostic answers if possible.)

答:
TL;DR:

Write the test

If the test does too much, the code may do too much too.

It may not be a unit test (but not a bad test).

The first thing for testing is about dogma being unhelpful.  I enjoy reading The Way of Testivus which points out some issues with dogma in a lighthearted way.

Write the test that needs to be written.

If the the test needs to be written some way, write it that way.  Attempting to force the test into some idealized test layout or not have it at all is not a good thing.  Having a test today that tests it is better than having a "perfect" test some later day.

I will also point to the bit on the ugly test:

When the code is ugly, the tests may be ugly.

You don’t like to write ugly tests, but ugly code needs testing the most.

Don’t let ugly code stop you from writing tests, but let ugly code stop you from writing more of it.

These can be considered truisms to those who have been following for a long time... and they just become ingrained in the way of thinking and writing tests.  For people that haven't been and are trying to get to that point, reminders can be helpful (I even find re-reading them helps me avoid getting locked into some dogma).

Do consider that when writing an ugly test, if the code it may be an indication that the code is trying to do too much too.  If the code that you are testing is too complex to be properly exercised by writing a simple test, you might want to consider breaking the code into smaller parts that can be tested with the simpler tests.  One should not write a unit test that does everything (it might not be a unit test then).  Just as 'god objects' are bad, 'god unit tests' are bad too and should be indications to go back and look at the code again.

You should be able to exercise all the code with reasonable coverage through such simple tests.  Tests that do more end to end testing that deal with larger questions ("I have this object, marshalled into xml, sent to the web service, through the rules, back out, and unmarshalled") is an excellent test - but it certainly isn't a unit test (and falls into the integration testing realm - even if it has mocked services that it calls and custom in memory databases to do the testing).  It may still use the XUnit framework for testing, but the testing framework doesn't make it a unit test.

ContentLicense: CC BY-SA 4.0


问:
Bayes filtering and data storage with expansive data sets
I am looking to write a Bayes filter that will act as an indicator of topic for a number of topics with a variable number of sources. Given a really big number of RSS feeds and here really big might only be a few hundred only few percent (let's say 2%) are interesting to a given group.

What I want to write (in PHP) is a filter I can train to say this is Topic X and this is not. Then I want selected users to be able to further train the filter. But I want to use only the base training for picking topics to mark as interesting for Topic X and then refine that collection based on the training the user has provided to give the most interesting results for that user by reassessing the probabilities including the user supplied training on the short list per user. Or maybe scoring the short list and picking the "best" items to show first.

So over time I am going to gain a fairly large collection of data (all of the headlines and blurbs from hundreds of feeds) and I am going to have flagged the feed items "yes" and "no" on an unspecified number of topics and have had users have likewise done so.

The headline and blurb will be stored for easy display later but I don't want to hold on to too many items that are "no" (up to 98% I imagine). Given I go with, say, this implementation from GitHub that I found earlier today https://github.com/benwaine/BayesPHP (or can be talked into rolling my own) what is the most efficient way to go about storing the data needed to carry out an assessment? Am I asking for trouble if simply try and store any news headlines etc flagged "yes" but store some sort of summary for the base "no" assessments and then just work it out on the fly each time storing the resultant "yes".

The server I have to work with is already doing a fair amount and is not going to spare me much horse power for this.

So balancing processing efficiency and storage needs what can you recommend?

答:
Bayes filters have to be taught. The activity of teaching the filter is a heavy operation, but it only needs to be performed once. After that, testing an article against a Bayes filter is very efficient. You only need to re-teach the filter if the population of accepting/rejected articles change enough to alter the filters outcome.

Teaching a filter that already works, by adding more keywords does little to improve the filter unless the new words introduced are significant in the population.

There is no need to store data for words with low thresholds (i.e. 0.00001%). Since they are most likely a single time occurrence of the word.

To store the filter in the database. I would convert the filter's statistical results to JSON and simply save it in a text field of the database. To test an article against the filter you would just load the data and serialize it back to a PHP array.

Once you have taught the Bayes filter with your sample articles. You can destroy those articles, but if you want to later re-teach you may need them again.

In time, you will have falsely rejected articles, and falsely accepted articles. You'll need to keep track of those, then re-categorize them and teach the Bayes filter again.

Bayes filters are only effective with articles that are significantly different from the rest of the population. Rather than categorize them as in or out of a category. You will have to weigh their membership to a category. An article may be 80% about gun control, 20% about gun registry and 45% about tax fraud. While this might seem like the article is mostly about gun control. It might really be about tax fraud simply because your filter wasn't taught enough about the subject.


问:
Decimal to 17-bit 2's Complement Signed Number
I am trying to convert decimals, (0.05, -0.28, 25.00, etc), to a 17-bit 2's complement Signed Number.  The parameter data I am sending is SysEX Midi Data (to some external Synthesizer).  The data parameters are composed of 3 bytes.

For example, the example given is as follows:

The parameter data to set the value to -0.02 is (07 7F 70) (Data2,Data1,Data0)

I was wondering if anyone could give me guidance for doing this in Java, here are the specifications I am going off of:

The parameter data is a 17-bit number 2’s complement signed number.

data2= Mix channel number and most significant bits (bits 14-16) of parameter’s data (with the format 0xxx xyyy, where xxxx is the mix channel
number (0-15) and yyy are the uppermost bits (bits 14-16) of the parameter data.)

data1= Bits 7-13 of parameter’s data

data0= Least significant bits (bits 0-6) of parameter’s data

So, here is what I am able to assume so far:

The 3 bytes is composed of 17 bits, + the 4 bits for sending #'s 0-15 (The Mix Channel)

The 17th bit is the signing bit?

The signing bit only needs to be set if It's a negative number, and in which that case needs to be formatted w/ 2's complement

The highest bit for each parameters data byte is set to 0

With all this in mind, can someone help me understand, post, or help me write a function to format this 17-bit number from a signed decimal value?  Binary Bit Adding / Subtracting In Java, Two's Complements, etc...It would be greatly appreciated it anyone has any example functions, or explanations!

Cheers

答:
Assuming that your parameter data are integers (like @Stargazer712 pointed out, 2s-complement) doesn't make any sense for non integer types) the following should do it:</p>

```<code>byte[] encode(int channel, int param) {
    byte[] data = new byte[3];
    // note that param is already 2's complement number, we only
    // need to split the bits apart (2x7 bits + 3 = 17)
    // 0x7f = 1111111 binary, so as to get 7 bits
    // 0x7  = 111 binary to get 3 bits
    data[2] = (byte) (param & 0x7f);         // lowest 7 bits
    data[1] = (byte) ((param >> 7) & 0x7f);  // next seven bits
    data[0] = (byte) ((param >> 14) & 0x7);  // 3 remaining bits
    // The channel must be placed 0xxxxyyy where xxxx are the 4 bit
    // channel number, and the yyy are the 3 upper bits of the param.
    // Hence, make sure we have only 4 bits shifted left by 3
    data[0] |= (byte) ((channel & 0xF) << 3);
    return data;
}
</code>```

Body:
Assuming that your parameter data are integers (like @Stargazer712 pointed out, 2s-complement) doesn't make any sense for non integer types) the following should do it:

byte[] encode(int channel, int param) {
    byte[] data = new byte[3];
    // note that param is already 2's complement number, we only
    // need to split the bits apart (2x7 bits + 3 = 17)
    // 0x7f = 1111111 binary, so as to get 7 bits
    // 0x7  = 111 binary to get 3 bits
    data[2] = (byte) (param & 0x7f);         // lowest 7 bits
    data[1] = (byte) ((param >> 7) & 0x7f);  // next seven bits
    data[0] = (byte) ((param >> 14) & 0x7);  // 3 remaining bits
    // The channel must be placed 0xxxxyyy where xxxx are the 4 bit
    // channel number, and the yyy are the 3 upper bits of the param.
    // Hence, make sure we have only 4 bits shifted left by 3
    data[0] |= (byte) ((channel & 0xF) << 3);
    return data;
}


问:
How to write readable Clojure Code?
I am new to Clojure. I can understand the code I write but it becomes too difficult to understand it later.It becomes difficult to match parentheses.

What are the generic conventions to follow regarding naming conventions andindentation in various situations?

For example I wrote a sample de-structuring example to understand but it looks completely unreadable the second time.

```<code>(defn f [{x :x y :y z :z [a b c] :coll}] (print x " " y  " " z " " a " " b " " c))
</code>```

In case of de-structuring,  is it better to do it directly at the parameter level or start a let form and then continue there?

答:
Naming conventions

stay lowercase for functions

use - for hyphenation (what would be underscore or camel case in other languages).

(defn add-one
   [i]
   (inc i))

Predicates (i.e. functions returning true or false) end with ?
 Examples: odd? even? nil? empty?

State changing procedures end in !. You remember set! right? or swap!

Choose short variable name lengths depending on their reach. That means if you have a really small auxiliary variable you can often just use a one-letter name. (map (fn [[k v]] (inc v)) {:test 4 :blub 5}) choose longer variable names as needed, especially if they are used for lots of code lines and you cannot immediately guess their purpose. (my opinion).

I feel that a lot of clojure programmers tend to rather use generic and short names. But this is of course not really an objective observation. The point is that a lot of clojure functions are actually quite generic.

Use meaningful names.Procedures are doing something, therefor you can best describe them by using verbs. Clojure built-in functions should put you on the right track: drop, take, assoc, etc. Then there is a nice article describing ways to choose a meaningful name: http://ecmendenhall.github.io/blog/blog/2013/09/02/clean-clojure-meaningful-names/

Lambda functions

You can actually name lambda functions. This is convenient for debugging and profiling (my experience here is with ClojureScript).

(fn square-em [[k v]] {k (* v v)})

Use inline lambda functions #() as convenient

Whitespace

There should not be parens-only lines. I.e. close the parentheses right away.  Remember parens are there for editor and compiler, indentation is for you.

Function parameter lists go on a new line

```
   (defn cons
     [a b]
     (list a b))
```

This makes sense if you think about the doc strings. They are between the function name and parameters. The following doc string is probably not the wisest ;)

```
   (defn cons
     "Pairing up things"
     [a b]
     (list a b))
```

Paired data can be separated by a new line as long as you retain the pairing

```
  (defn f
    [{x :x
      y :y
      z :z
      [a b c] :coll}]
    (print x " " y  " " z " " a " " b " " c))
```

(You can also enter , as you like but this feels unclojurish).

For indentation use a sufficiently good editor. Years ago this was emacs for lisp editing, vim is also great today. Typical clojure IDEs should also provide this functionality. Just do not use a random text editor.

In vim in command mode you can use the = command to properly indent.

If command get too long (nested, etc.) you can insert a newline after the first argument. Now the  following code is pretty senseless but it illustrates how you can group and indent expressions:

```
(+ (if-let [age (:personal-age coll)]
     (if (> age 18)
       age
       0))
   (count (range (- 3 b)
                 (reduce +
                         (range b 10)))))
```

Good indentation means that you do not have to count brackets. The brackets are for the computer (to interpret the source code and to indent it). Indentation is for your easy understanding.

Higher order functions vs. for and doseq forms

Coming from a Scheme background I was rather proud to have understood map and lambda functions, etc. So quite often, I would write something like this

(map (fn [[k x]] (+ x (k data))) {:a 10 :b 20 :c 30})

This is quite hard to read. The for form is way nicer:

```<code>(for [[k x] {:a 10 :b 20 :c30}]
  (+ x (k data)))
</code>```

`map has a lot of uses and is really nice if you are using named functions. I.e.

```<code>(map inc [12 30 10]

(map count [[10 20 23] [1 2 3 4 5] (range 5)])
</code>```

Use Threading macros

Use the threading macros -> and ->> as well as doto when applicable.

The point is that threading macros make the source code appear more linear than function composition. The following piece of code is pretty unreadable without the threading macro:

```<code>   (f (g (h 3) 10) [10 3 2 3])
</code>```

compare with

```<code>   (->
     (h 3)
     (g 10)
     (f [10 3 2 3]))
</code>```

By using the threading macro, one can typically avoid introducing temporary variables that are only used once.

Other Things

Use docstrings

keep functions short

read other clojure code

Title: How to write readable Clojure Code?

Body:
Naming conventions

stay lowercase for functions

use - for hyphenation (what would be underscore or camel case in other languages).

(defn add-one
   [i]
   (inc i))

Predicates (i.e. functions returning true or false) end with ?
 Examples: odd? even? nil? empty?

State changing procedures end in !. You remember set! right? or swap!

Choose short variable name lengths depending on their reach. That means if you have a really small auxiliary variable you can often just use a one-letter name. (map (fn [[k v]] (inc v)) {:test 4 :blub 5}) choose longer variable names as needed, especially if they are used for lots of code lines and you cannot immediately guess their purpose. (my opinion).

I feel that a lot of clojure programmers tend to rather use generic and short names. But this is of course not really an objective observation. The point is that a lot of clojure functions are actually quite generic.

Use meaningful names.Procedures are doing something, therefor you can best describe them by using verbs. Clojure built-in functions should put you on the right track: drop, take, assoc, etc. Then there is a nice article describing ways to choose a meaningful name: http://ecmendenhall.github.io/blog/blog/2013/09/02/clean-clojure-meaningful-names/

Lambda functions

You can actually name lambda functions. This is convenient for debugging and profiling (my experience here is with ClojureScript).

(fn square-em [[k v]] {k (* v v)})

Use inline lambda functions #() as convenient

Whitespace

There should not be parens-only lines. I.e. close the parentheses right away.  Remember parens are there for editor and compiler, indentation is for you.

Function parameter lists go on a new line

   (defn cons
     [a b]
     (list a b))

This makes sense if you think about the doc strings. They are between the function name and parameters. The following doc string is probably not the wisest ;)

   (defn cons
     "Pairing up things"
     [a b]
     (list a b))

Paired data can be separated by a new line as long as you retain the pairing

  (defn f
    [{x :x
      y :y
      z :z
      [a b c] :coll}]
    (print x " " y  " " z " " a " " b " " c))

(You can also enter , as you like but this feels unclojurish).

For indentation use a sufficiently good editor. Years ago this was emacs for lisp editing, vim is also great today. Typical clojure IDEs should also provide this functionality. Just do not use a random text editor.

In vim in command mode you can use the = command to properly indent.

If command get too long (nested, etc.) you can insert a newline after the first argument. Now the  following code is pretty senseless but it illustrates how you can group and indent expressions:

(+ (if-let [age (:personal-age coll)]
     (if (> age 18)
       age
       0))
   (count (range (- 3 b)
                 (reduce +
                         (range b 10)))))

Good indentation means that you do not have to count brackets. The brackets are for the computer (to interpret the source code and to indent it). Indentation is for your easy understanding.

Higher order functions vs. for and doseq forms

Coming from a Scheme background I was rather proud to have understood map and lambda functions, etc. So quite often, I would write something like this

(map (fn [[k x]] (+ x (k data))) {:a 10 :b 20 :c 30})

This is quite hard to read. The for form is way nicer:

(for [[k x] {:a 10 :b 20 :c30}]
  (+ x (k data)))

`map has a lot of uses and is really nice if you are using named functions. I.e.

(map inc [12 30 10]

(map count [[10 20 23] [1 2 3 4 5] (range 5)])

Use Threading macros

Use the threading macros -> and ->> as well as doto when applicable.

The point is that threading macros make the source code appear more linear than function composition. The following piece of code is pretty unreadable without the threading macro:

   (f (g (h 3) 10) [10 3 2 3])

compare with

   (->
     (h 3)
     (g 10)
     (f [10 3 2 3]))

By using the threading macro, one can typically avoid introducing temporary variables that are only used once.

Other Things

Use docstrings

keep functions short

read other clojure code


答:
Don't try to test too many things at once. Each of the properties of each data object in the collection is too much for one test. Instead, I recommend:

If the collection is fixed-length, write a unit test to validate length. If it is variable length, write several tests for lengths that will characterize its behavior (e.g. 0, 1, 3, 10). Either way, do not validate properties in these tests.

Write a unit test to validate each of the properties. If the collection is fixed-length and short, just assert against one property of each of the elements for each test. If it is fixed-length but long, choose a representative but small sample of the elements to assert against one property each. If it is variable-length, generate a relatively short but representative collection (i.e. maybe three elements) and assert against one property of each.

Doing it this way makes the tests small enough that leaving out loops doesn't seem painful. C#/Unit example, given method under test ICollection<Foo> generateFoos(uint numberOfFoos):

```<code>[Test]
void generate_zero_foos_returns_empty_list() { ... }
void generate_one_foo_returns_list_of_one_foo() { ... }
void generate_three_foos_returns_list_of_three_foos() { ... }
void generated_foos_have_sequential_ID()
{
    var foos = generateFoos(3).GetEnumerable();
    foos.MoveNext();
    Assert.AreEqual("ID1", foos.Current.id);
    foos.MoveNext();
    Assert.AreEqual("ID2", foos.Current.id);
    foos.MoveNext();
    Assert.AreEqual("ID3", foos.Current.id);
}
void generated_foos_have_bar()
{
    var foos = generateFoos(3).GetEnumerable();
    foos.MoveNext();
    Assert.AreEqual("baz", foos.Current.bar);
    foos.MoveNext();
    Assert.AreEqual("baz", foos.Current.bar);
    foos.MoveNext();
    Assert.AreEqual("baz", foos.Current.bar);
}
</code>```

If you are used to the "flat unit test" paradigm (no nested structures/logic), these tests seem pretty clean. Thus logic is avoided in the tests by identifying the original problem as trying to test too many properties at once, rather than lacking loops.

Title: How to unit test method that returns a collection while avoiding logic in the test

Body:
I am test-driving a method that is to generate a collection of data objects. I want to verify that the properties of the objects are being set correctly. Some of the properties will be set to the same thing; others will be set to a value which is dependent on their position in the collection. The natural way to do this seems to be with a loop. However, Roy Osherove strongly recommends against using logic in unit tests (Art of Unit Testing, 178). He says:

A test that contains logic is usually testing more than one thing at a time, which isn't recommended, because the test is less readable and more fragile. But test logic also adds complexity that may contain a hidden bug.

Tests should, as a general rule, be a series of method calls with no control flows, not even try-catch, and with assert calls.

However, I can't see anything wrong with my design (how else do you generate a list of data objects, some of whose values are depended on where in the sequence they are?—can't exactly generate and test them separately). Is there something non-test-friendly with my design? Or am being too rigidly devoted to Osherove's teaching? Or is there some secret unit test magic I don't know about that circumvents this problem? (I'm writing in C#/VS2010/NUnit, but looking for language-agnostic answers if possible.)

Body:
Don't try to test too many things at once. Each of the properties of each data object in the collection is too much for one test. Instead, I recommend:

If the collection is fixed-length, write a unit test to validate length. If it is variable length, write several tests for lengths that will characterize its behavior (e.g. 0, 1, 3, 10). Either way, do not validate properties in these tests.

Write a unit test to validate each of the properties. If the collection is fixed-length and short, just assert against one property of each of the elements for each test. If it is fixed-length but long, choose a representative but small sample of the elements to assert against one property each. If it is variable-length, generate a relatively short but representative collection (i.e. maybe three elements) and assert against one property of each.

Doing it this way makes the tests small enough that leaving out loops doesn't seem painful. C#/Unit example, given method under test ICollection<Foo> generateFoos(uint numberOfFoos):

[Test]
void generate_zero_foos_returns_empty_list() { ... }
void generate_one_foo_returns_list_of_one_foo() { ... }
void generate_three_foos_returns_list_of_three_foos() { ... }
void generated_foos_have_sequential_ID()
{
    var foos = generateFoos(3).GetEnumerable();
    foos.MoveNext();
    Assert.AreEqual("ID1", foos.Current.id);
    foos.MoveNext();
    Assert.AreEqual("ID2", foos.Current.id);
    foos.MoveNext();
    Assert.AreEqual("ID3", foos.Current.id);
}
void generated_foos_have_bar()
{
    var foos = generateFoos(3).GetEnumerable();
    foos.MoveNext();
    Assert.AreEqual("baz", foos.Current.bar);
    foos.MoveNext();
    Assert.AreEqual("baz", foos.Current.bar);
    foos.MoveNext();
    Assert.AreEqual("baz", foos.Current.bar);
}

If you are used to the "flat unit test" paradigm (no nested structures/logic), these tests seem pretty clean. Thus logic is avoided in the tests by identifying the original problem as trying to test too many properties at once, rather than lacking loops.


问:
What mindset should an ASP.NET developer have in terms of client-side vs server-side code?
I'm jumping back into ASP.NET development after spending the past 7 years playing manager, dba, and winforms developer.  I've dabbled with a few things web related, primarily maintenance of existing webforms apps, but I haven't done anything with newer technologies.  My, how things have changed!

After watching a lot of videos, reading a lot of articles, and messing around with some of the new tools, I think I must be looking at things the wrong way.  I tend to think in terms of writing web apps using C# and server-side processing rather than client-side processing.  I never used much JavaScript and depended on things like Infragistics NetAdvantage controls and their asynchronous refresh panel.

Is it reasonable to assume that "modern" web developers think in terms of JavaScript and client-side coding, only hitting the server via a service for data processing, retrieveal, and storage?

答:
As some of the commenters have mentioned, it really depends on what you're doing. Take validation--all validation that can be done on the client should be done there. It's more responsive and there's little hostility towards the developer (having a blank form returned with an error message mentioning required data was missing angered even the most docile users). Just because you have client-side validation doesn't mean the server can trust the input, though. Always remember that you don't control the client, no matter what you develop. Take special care with strings that are eventually destined for the database (you are using stored procedures/parameterized queries, right?).

As much power as there is in the client, there's a lot more in the server. Complex data processing belongs on the server. So do database queries, which get performance and security benefits from running behind the walled garden. When the client needs to interact with the server, think about AJAX and using light-weight responses (.ashx handlers rather than .aspx pages) to return just what's necessary.

Summing up the answer, a "modern" web developer knows the advantages of client-side and server-side programming and makes a decision balancing all of the concerns.

OwnerDisplayName: DarLom


答:
The value is scaled, so first you have to convert it into an integer.  A 17-bit two's complement number has a range from -2^16 to 2^16 - 1, or -65536 to 65535.  Therefore, for -0.02, you multiply it by 65536, which gives you -1310.  As Ingo pointed out, Java values are already in two's complement notation, so as long as you mask off the bits greater than bit 16, you are already good to go.

This assumes the display goes from -1.0 to 1.0.  If the maximum value on the display is different, you have to divide the -1310 by whatever the maximum value is.  100 gets pretty close to your example result, but it will differ for different parameters.

However, your three bytes are 7-bit bytes, but we just calculated it for 8-bit bytes, so you have to do some more screwy bit shifting to get it into the form it wants:

```<code>(0x1fae2 >> 14) & 0x7f = 0x07 # First byte
(0x1fae2 >> 7)  & 0x7f = 0x75 # Second byte
 0x1fae2        & 0x7f = 0x62 # Third byte
</code>```

I'll leave it as an exercise for the reader to implement the first part in Java.  If you pass in 0x1fae2 as param, Ingo's code works for the second part.

Title: Decimal to 17-bit 2's Complement Signed Number

Body:
I am trying to convert decimals, (0.05, -0.28, 25.00, etc), to a 17-bit 2's complement Signed Number.  The parameter data I am sending is SysEX Midi Data (to some external Synthesizer).  The data parameters are composed of 3 bytes.

For example, the example given is as follows:

The parameter data to set the value to -0.02 is (07 7F 70) (Data2,Data1,Data0)

I was wondering if anyone could give me guidance for doing this in Java, here are the specifications I am going off of:

The parameter data is a 17-bit number 2’s complement signed number.

data2= Mix channel number and most significant bits (bits 14-16) of parameter’s data (with the format 0xxx xyyy, where xxxx is the mix channel
number (0-15) and yyy are the uppermost bits (bits 14-16) of the parameter data.)

data1= Bits 7-13 of parameter’s data

data0= Least significant bits (bits 0-6) of parameter’s data

So, here is what I am able to assume so far:

The 3 bytes is composed of 17 bits, + the 4 bits for sending #'s 0-15 (The Mix Channel)

The 17th bit is the signing bit?

The signing bit only needs to be set if It's a negative number, and in which that case needs to be formatted w/ 2's complement

The highest bit for each parameters data byte is set to 0

With all this in mind, can someone help me understand, post, or help me write a function to format this 17-bit number from a signed decimal value?  Binary Bit Adding / Subtracting In Java, Two's Complements, etc...It would be greatly appreciated it anyone has any example functions, or explanations!

Cheers

Body:
The value is scaled, so first you have to convert it into an integer.  A 17-bit two's complement number has a range from -2^16 to 2^16 - 1, or -65536 to 65535.  Therefore, for -0.02, you multiply it by 65536, which gives you -1310.  As Ingo pointed out, Java values are already in two's complement notation, so as long as you mask off the bits greater than bit 16, you are already good to go.

This assumes the display goes from -1.0 to 1.0.  If the maximum value on the display is different, you have to divide the -1310 by whatever the maximum value is.  100 gets pretty close to your example result, but it will differ for different parameters.

However, your three bytes are 7-bit bytes, but we just calculated it for 8-bit bytes, so you have to do some more screwy bit shifting to get it into the form it wants:

(0x1fae2 >> 14) & 0x7f = 0x07 # First byte
(0x1fae2 >> 7)  & 0x7f = 0x75 # Second byte
 0x1fae2        & 0x7f = 0x62 # Third byte

I'll leave it as an exercise for the reader to implement the first part in Java.  If you pass in 0x1fae2 as param, Ingo's code works for the second part.


答: C++ - code::blocks</p>

Title: What are the most popular IDEs per language?

Body:
This has nothing to do with having a favourite editor or anything like that. I was just wondering, per language, what are the most popular Integrated Development Environments? Maybe a top 2-3 if there is some contention. (Perceived popularity is enough)

Thus Far:

C# - Visual Studio, SharpDevelop

Java - Eclipse, NetBeans, IDEA

Objective-C - Xcode

Delphi - RAD Studio

Object Pascal - Delphi, Lazarus

C, C++ - Visual Studio, Vim

PL/SQL - RapidSQL, Oracle SQLDeveloper

PHP - Eclipse, NetBeans, Nusphere PHPed

Actionscript (AS2, AS3) - FlashDevelop

Flex - Flash Builder 4

Python - Eclipse, IDLE

Perl - Padre

Common Lisp - Lispworks, Emacs

Ruby - TextMate

Haskell - Vim

Fortran - Vim

Visual Basic - Visual Studio

Body: C++ - code::blocks