JFugue: Get notes of a specific scale - jfugue

What is the correct way to retrieve the notes that belong to a scale in JFugue, for example C maj?
I have seen there is this class org.jfugue.theory.Intervals but i don't understand what i should pass as constructor parameter

The following code snippet starts with a Major scale, gets the intervals from the scale (intervals being the steps between each of the notes in the scale), sets the root to C (so now you have a C Major), and get the notes that belong in C Major.
List<Note> notes = Scale.MAJOR.getIntervals().setRoot("C").getNotes();
As I type this, it feels like the 'getIntervals' call is not meaningful. When I wrote this all, I was trying to figure out if there is an actual distinction between intervals and a scale, aside from the fact that those two words aren't used exactly interchangeably. If you have feedback on this, please let me know!

Related

Order of evaluation in Manipulate

Assume I have a Manipulate with two dynamic variables and I want to put the corresponding controls in a Row for aesthetics reason. I can think of two ways to do it as follows:
Row[Control/#{{{a,a_in},a_min,a_max},{{b,b_in},b_min,b_bmax}}]
or
Row[{Control[{{a,a_in},a_min,a_max}],Control[{{b,b_in},b_min,b_bmax}]}]
The issue is that in the first case after the 1st run of the cell containing Manipulate with that line the variables a, b become having defined value (a_in and b_in) respectively and for further evaluation are not recognized as variables of Manipulate, while in the other case a and b remain undefined and serve correctly as dynamic variables.
I expect that the Map (/#) somehow changes the order of evaluation in the expression and that the variable "leaks" outside the Row, gets told by Manipulate to have a value and takes it on. While on the other hand the simple Control[] correctly encloses a control option and nothing "leaks". Yet I find this claim possibly false and unsatisfyingly vague (thus hard to generalize and understand Mathematica better, which I would like to).
Can someone explain why that happens or point me to some other insightful answer (I guess this is not the first time this issue came up, but I can't form a proper query to google for it.)?

Cross version line matching

I'm considering how to do automatic bug tracking and as part of that I'm wondering what is available to match source code line numbers (or more accurate numbers mapped from instruction pointers via something like addr2line) in one version of a program to the same line in another. (Assume everything is in some kind of source control and is available to my code)
The simplest approach would be to use a diff tool/lib on the files and do some math on the line number spans, however this has some limitations:
It doesn't handle cross file motion.
It might not play well with lines that get changed
It doesn't look at the information available in the intermediate versions.
It provides no way to manually patch up lines when the diff tool gets things wrong.
It's kinda clunky
Before I start diving into developing something better:
What already exists to do this?
What features do similar system have that I've not thought of?
Why do you need to do this? If you use decent source version control, you should have access to old versions of the code, you can simply provide a link to that so people can see the bug in its original place. In fact the main problem I see with this system is that the bug may have already been fixed, but your automatic line tracking code will point to a line and say there's a bug there. Seems this system would be a pain to build, and not provide a whole lot of help in practice.
My suggestion is: instead of trying to track line numbers, which as you observed can quickly get out of sync as software changes, you should decorate each assertion (or other line of interest) with a unique identifier.
Assuming you're using C, in the case of assertions, this could be as simple as changing something like assert(x == 42); to assert(("check_x", x == 42)); -- this is functionally identical, due to the semantics of the comma operator in C and the fact that a string literal will always evaluate to true.
Of course this means that you need to identify a priori those items that you wish to track. But given that there's no generally reliable way to match up source line numbers across versions (by which I mean that for any mechanism you could propose, I believe I could propose a situation in which that mechanism does the wrong thing) I would argue that this is the best you can do.
Another idea: If you're using C++, you can make use of RAII to track dynamic scopes very elegantly. Basically, you have a Track class whose constructor takes a string describing the scope and adds this to a global stack of currently active scopes. The Track destructor pops the top element off the stack. The final ingredient is a static function Track::getState(), which simply returns a list of all currently active scopes -- this can be called from an exception handler or other error-handling mechanism.

What the ugliest API for a relatively well known library that you have seen, and why and how could it be improved? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have been looking at the differences between Lucene 2.9 particular the redone tokenstream API and it just occurs to me its particularly ugly compared to the old just return a new or repopulate the given with values if your reusing said Token.
I have not done any profiling but it seems using a MAP to store attributes is not that efficient and it would be easier to just create a new value type holding values etc. The TokenStream and Attribute stuff looks like object pooling which is pretty much never necessary these days for simple value types like a Token of text.
creat()
When Ken Thompson and Dennis Ritchie received the 1983 Turing Award, after their respective acceptance speeches, someone in the audience asked Ken what he would do differently with Unix if he were to do it all over again. He said, "I'd spell 'creat' with an 'e'."
Livelink (OpenText) API
Everything comes back as some bizarre form of a jagged array
The documentation provides absolutely no examples
[your favorite search engine] typically returns no results for a given API method
The support forums feel near abandoned
The only reliable way of understanding the resultant data is to run the data in the Livelink debugger
And finally... the system costs tens (hundreds) of thousands of dollars
The wall next to my desk has an imprint of my head...
A very simple example of getting a value out of an API method:
var workflow = new LAPI_Workflow(CurrentSession);
// every Livelink method uses an out variable
LLValue outValue;
// every method returns an integer that says if the call was
// a success or not, where 0 = success and any other integer
// is a failure... oh yeah, there is no reference to what any
// of the failure values mean, you have to create your own
// error dictionary.
int result = workflow.ListWorkTasks(workId, subWorkId, taskId, outValue);
if (result = 0)
{
// and now let's traverse through at least 3 different arrays!
string taskName = outValue.toValue(0).toValue("TASKS").toValue(0).toString("TaskName");
}
Aaack!!! :D
I've never been a fan of the java.sql package...
You have to catch the checked exception for everything, and there's only one exception, so it doesn't really give any indication of what went wrong without examining the SQL code String.
Add to that the fact that you have to use java.sql.Date instead of java.util.Data, so you always have to specify the full package for one or the other. Not to mention the conversion that has to take place between the two.
And then there's the parameter index, which is 1-base-indexed instead of the rest of Java, which is 0-base-indexed.
All in all, a pretty annoying library. Thankfully, the Spring library does make it quite a bit easier to work with.
COM. Its biggest improvements ended up being .NET.
Certain java.io.File methods, critical to systems programming, return a boolean to indicate success or failure. If such a method (like, say, mkdir or delete) fails, you have no way at all to find out why.
This always leaves my jaw a-hangin' open.
Java's date/time API is pretty horrible to work with. java.util.Date has several constructors to create an instance for a specific date, but all of them are deprecated. java.util.GregorianCalendar should be used instead, but that has an extremely annoying way of setting fields (think calendar.setField(GregorianCalendar.MONTH, 7) instead of calendar.setMonth(7) which would be far better). The finishing touch is that most other classes and libraries still expect a Date instead of a Calendar, so you have to constantly convert back and forth.
Not not a winner, but deserves a honourably mention; Android. Uses the Java 5 programming language, but barely any of the Java 5 language features. Instead of enums you get integer constants with prefix or suffix.
It can not quite decide if it should be object oriented, or procedural. Showing dialogs being a prime example. Several callbacks with self defined integer ids to display call upon the dialog, that smells of an old C API. And then you get an inner builder class class with chained methods, that smells of over architectured OOP of the worst kind.
The MotionEvent class have X and Y coordinates as absolute and relative values from the same accessory method. But no way to check what kind of coordinates it currently holds.
Android sure is a mixed bag.
I'm going to turn this question on its head and name a beautiful API for a library whose standard API is mostly ugly: the Haskell bindings for OpenGL.
These are the reasons:
Instead of lumping everything into a small number of headers, the library is organized logically into discrete modules, whose contents parallel the structure of the OpenGL specification. This makes browsing the documentation a pleasant experience.
Pairs of "begin/end" functions are replaced by higher-order procedures. For example, instead of
pushMatrix();
doSomeStuff();
doSomeMoreStuff();
popMatrix();
you'd say
preservingMatrix $ do
doSomeStuff
doSomeMoreStuff
The syntax of the bindings enforces the conventions of the library, instead of making you do it by hand. This works for the drawing primitives of quads, triangles, lines, etc. as well. All of this is exception-safe, of course.
Getters and setters are replaced by idiomatic "StateVars", making reading and writing a more symmetric operation.
Multiple versions of functions replaced by polymorphism and extra datatypes. Instead of calling, say, glVertex2f with two float values, you call vertex with a value of type Vertex2 GLFloat.
References:
API Reference
The HaskellWiki page on OpenGL
Beautiful Code, Compelling Evidence (pdf)
Praise from Scott Dillard, quoted in Beautiful Code, Compelling Evidence
Direct3D!
No doubt the old pre-Direct3D 5 interface was pretty darn fugly:
// GL code
glBegin (GL_TRIANGLES);
glVertex (0,0,0);
glVertex (1,1,0);
glVertex (2,0,0);
glEnd ();
// D3D code, tonnes of crap removed
v = &buffer.vertexes[0];
v->x = 0; v->y = 0; v->z = 0;
v++;
v->x = 1; v->y = 1; v->z = 0;
v++;
v->x = 2; v->y = 0; v->z = 0;
c = &buffer.commands;
c->operation = DRAW_TRIANGLE;
c->vertexes[0] = 0;
c->vertexes[1] = 1;
c->vertexes[2] = 2;
IssueExecuteBuffer (buffer);
Its not too bad, nowadays - it only took Microsoft 10 versions to get it right...
I would say MFC, ATL and WTL. All 3 of these libraries use excessive hungarian notation, redefine data types for no apparent reason (CString redefined over and over) and are notoriously changed with each version of visual studio.
I like COM. It provides a component oriented architecture long before .NET was even developed. However, the expansion of COM into DCOM, its many wrappers like ATL and its general lack of comprehensive documentation make it the ugliest API i have to deal with at work.
Most certainly not the ugliest. There are probably so many, but Flex has a special place in hell. Specifically UIComponent which compared to the Sprite, feels like using a chainsaw to peel an apple. I believe Flex would have been much improved by using more lightweight objects and mixin-style features similar to how Dojo works on the Javascript side.
The ECMAScript/Actionscript Date class is all but backwards and useless. It's been a constant pain any time I've needed to do something more complex than add timestamps to logs. They need more parsing options (e.g., the ability to specify the input format), and better time management, like intelligent increments, convenience functions, etc...
C++ STL libraries (and templates in general), while obviously useful, have always felt plain ugly. No suggestions for improvements though. They work.
Oracle's ProC, ProAda, Pro*this-that-the-other things. They were a preprocessor front end for C, Ada, and Fortran, I think, maybe some others, that let you jam SQL into your source code.
They did also have a library which worked much better, and was much more flexible.
(That was more than 10 years ago, I have no idea what they do now, though I wouldn't be surprised if it was still the same, just so as not to break people's code.)
well, it was a well-known library about 20 years ago, but i think the original btrieve data engine has the worst api ever written. almost everything goes through a single call, with each of its many parameters containing a different value depending on which call you're really doing (one parameter was a flag telling the system if you wanted to open a file, close a file, search, insert, etc). i liked btrieve way back then, but i spent a long time making a good abstraction layer.
it could have been easily improved by not forcing everything into one call. not only was the one call hideous, but the programmer was responsible for allocating, passing in, and freeing the position block ... some memory used by btrieve to track the open file handle, position, etc. another improvement would be to allow ascii text to be used when defining the indexing. indices had to be specified by a convoluted binary representation.
best regards,
don
A lot of the CRT library functions are poorly or vaguely named possibly due to legacy coding restrictions back in the day and thus require frequent use of the F1 key for people to find the right function and supply the right arguments.
I've been using CRT functions for a while and I still find myself hitting F1 a fair amount.

Defining constants for 0 and 1

I was wondering whether others find it redundant to do something like this...
const double RESET_TIME = 0.0;
timeSinceWhatever = RESET_TIME;
rather than just doing
timeSinceWhatever = 0.0;
Do you find the first example to aid in readability? The argument comes down to using magic numbers, and while 0 and 1 are considered "exceptions" to the rule, I've always kind of thought that these exceptions only apply to initializing variables, or index accessing. When the number is meaningful, it should have a variable attached to its meaning.
I'm wondering whether this assumption is valid, or if it's just redundant to give 0 a named constant.
Well, in your particular example it doesn't make much sense to use a constant.
But, for example, if there was even a small chance that RESET_TIME will change in the future (and become, let's say, 1) then you should definitely use a constant.
You should also use a constant if your intent is not obvious from the number. But in your particular example I think that timeSinceWhatever = 0; is more clear than timeSinceWhatever = RESET_TIME.
Typically, one benefit of defining a constant rather than just using a literal is if the value ever needs to change in several places at once.
From your own example, what if REST_TIME needed to be -1.5 due to some obscure new business rule? You could change it one place, the definition of the constant, or you could change it everywhere you had last used 0.0 as a float literal.
In short, defining constants, in general, aids primarily in maintainability.
If you want to be more specific and letting others know why you're changing doing what you're doing you might want to instead create a function (if your language permits functions to float about) such as
timeSinceWhenever = ResetStopWatch();
or better yet when dealing with units either find a library which has built in function types or create your own. I wouldn't suggest creating your own with time as there are an abundant amount of such libraries. I've seen this before in code if it helps:
Temperature groundTemp = Temperature.AbsoluteZero();
which is a nice way of indicating what is going on.
I would define it only if there was ever a chance that RESET_TIME could be something different than 0.0, that way you can make one change and update all references. Otherwise 0.0 is the better choice to my eye just so you don't have to trace back and see what RESET_TIME was defined to.
Constants are preferable as it allows to use a value that can be then changed in successive versions of the code. It is not always possible to use constants, especially if you are programming in a OO language, and it is not possible to define a constant that doesn't contain a basic datatype. Generally, a programming language always has a way to define not modifiable objects / datatypes.
Well suppose that RESET_TIME is used often in your code and you want to change the value, it will be better to do it once and not in every statement.
better than a constant, make it a configuration variable, and set it to a default value. But yes, RESET_TIME is more readable, provided its used more than once otherwise just use a code comment.
That code is ok. const variable are unchangeable variables. so whenever you feel to reset something, you can always have your const to do that

Should a method parameter name specify its unit in its name?

Of the following two options for method parameter names that have a unit as well as a value, which do you prefer and why? (I've used Java syntax, but my question would apply to most languages.)
public void move(int length)
or
public void move(int lengthInMetres)
Option (1) would seem to be sufficient, but I find that when I'm coding/typing, my IDE can indicate to me I need a length value, but I typically have to break stride and look up the method's doco to determine the units, so that I pass in the correct value (and not kilometres instead of metres for example). This can be an annoying interruption to a thought process. Option (2) alleviates this problem, but can be verbose, particularly if your unit is metresPerSecondSquared or some such. Which do you think is the best?
I would recommend making your parameter (and method) names as clear as possible, even if they become wordy. You'll be glad when you look at or use the code in 6 months time, or when someone else has to look at your code.
If you think the names are becoming too long, consider rewording them. In your example you could use parameter name int Metres that would probably be clear enough. Consider changing the method name, eg public void moveMetres(int length).
In Visual Studio, the XML comments generated when you enter 3 comment symbols above a method definition will appear in Intellisense hints when you use the method in other locations. Other IDEs may have similar functionality.
Abbreviations should be used sparingly. If absolutely necessary only use commonly known and/or relevant industry-standard abbreviations and be consistent, ie use the same abbreviation everywhere.
Take a step back. Write the code then move on to something else. Come back the next day and check to see if the names are still clear.
Peer reviews can help too. Ask someone who knows the programming language (or just thinks logically), but not the specific functionality, if your naming scheme is clear enough or to help brainstorm alternatives. They might be the poor sap who has to maintain your code in the future!
I would prefer the second approach (i.e. lengthInMeters) as it describes the input needed for the method accurately. The fact that you find it confusing to figure out the units when you are just writing the code would imply it would be much more confusing when you (or some one) looks at the same piece of code later. As regard to issue of the variable name being longer you can find ways to abbreviate it (say "mtrsPerSecondSquared").
Also in defence second approach, the book Code Complete mentions a research that indicates, effort required to debug a program was minimized when variables had names averaged to 10 to 16 characters.

Resources