I'm studying TDD by Example and up so far I'm finding it a great book. But there's a point where he tells us to write:
// in class Money:
Expression plus(Money addend) {
return new Money(amount + addend.amount, currency);
}
Which won't build unless we declare:
class Money implements Expression {...
This doesn't really make sense to me. Author created Expression as an interface for Sum and Money has nothing in common with Sum. Later on he adds method reduce() in common to both classes, but reduce in Money merely returns this.
Making Money implement Expression is only the path of least effort for removing the error from the plus() method, but it fills the code with unnecessary information (it will have to implement reduce() because of this decision) and increases entropy.
I haven't given it much of a thought, but wouldn't it be cleaner to do something such as this?
class Money {
Money plus(Money addend) {
return new Money(amount + addend.amount, currency).reduce();
}
}
// edited this, it previously returned Expression
Edit:
In the following chapter, author implements a reduce() method in another class (named Bank), which converts Money in between currencies. I still find this to be a weird solution, Sum and Expression names imply we should have a conversion expression class for this task instead. What the author is likely intending to do is to use recursion to add money in different currencies. Either way, it seems to me that he did some far-ahead planning which seems incompatible with TDD as is presented in the book.
On planning ahead
TDD doesn't prohibit planning ahead. The process is about getting rapid feedback on your plans instead of wasting days (or weeks) creating elaborate plans, only to see them 'not survive contact with reality' (to paraphrase Helmuth von Moltke). It's okay to think ahead.
Still, Kent Beck reveals in chapter 17 that this isn't his first rodeo:
"I have programmed money in production at least three times that I can think of. I have used it as an example in print another half-dozen times. I have programmed it live on stage [...] another fifteen times. I coded another three or four times preparing for writing [...] Then, while I was writing this, I thought of using expression as a metaphor and the design went in a completely different direction than before."
So, if you think that he's cheating: yes, he is. He's open about it, though. I think that the motivation was to present a compelling example. He also writes that it was in part based on early reviews of the book.
On the API
That doesn't explain why the code looks like it does, but there's a reason for that. It's actually a nice API.
Why can't you write something like return new Expression(amount + addend.amount, currency).reduce()?
You can't because the reduce method isn't nullary. It takes arguments. You must supply both a bank (which holds the currency conversion rates) and a destination currency.
Keep in mind the problem being solved by the code. People get this wrong all the time, and I think that Kent Beck (inadvertently) fuelled the confusion by naming the example Money.
The problem isn't to model money, but to model investment portfolios in different currencies. If you have a portfolio of 25.000 USD and 10.000 CHF, reducing it to a single currency hides important details. With a portfolio in multiple currencies you diversify risk. Portfolio owners will want to see more than one view of their portfolios. Sometimes, they want to see the portfolio grouped by currency, and at other times they want to see 'the current total worth' of the portfolio presented in a single currency.
The API in the book enables both views.
The reason the underlying 'metaphor' is called an expression is that the API is just a specialised expression tree. It turns out fairly well, though, because it's lawful. Restricted to the sub-types presented in the book, it informally gives rise to a monoid.
I have a qualification test that I'd like to tune. If there are questions that are frequently missed, I will consider swapping them out or adding clarification.
The test is part of a Qualification Type. The worker is granted the test automatically after finishing with a score of the correct answers. My HITs require a minimum score on the qualification type to accept.
I don't see a view in the requester UI to see actual worker responses.
GetQualificationsForQualificationType only returns the status and value (score), though the documentation example response has answers. I've tried both java and WS calls. The sdk also has a getQualificationRequests() but it returns null for this qualification type. It returns an array of QualificationRequest. That class has getTest() and getAnswer() methods, but I don't see what it would return. It seems to me that qualification requests are only for those without tests, which are granted manually.
Anyone know a way to get the actuals? Thanks!
There's no way to to do this if you're using an AnswerKey. There are two general strategies to get around this:
Do not set the qualification to be autogranted (or use an Answer Key). Then you can use the GetQualificationRequests operation to see actual answers to individual questions. This may not work if you want to quickly qualify lots of workers, although you could write a script to poll for new requests and approve them based on the answers, while saving the qualification test answers locally. (They are no longer available from MTurk once the qualification has been granted.)
You can specify your qualification scores in such a way that each score uniquely identifies a pattern of answers. A simple way to do this is something like a three-question qualification test that scores each question separately by a factor of ten:
a. Q1: correct = 1, incorrect = 0
b. Q2: correct = 10, incorrect = 0
c. Q3: correct = 100, incorrect = 0
Then scores of 1, 10, or 100 indicate 1 correct answer. 11, 101, or 110 indicate two correct answers, and scores of 111 indicate three correct answers. You can use the In comparator for your QualificationRequirements to then require, for example, that a worker has a score that is "In" 11, 101, 110, or 111 if you want them to have 2 or more correct answers.
There are obviously other scoring patterns that would similarly produce uniquely identifiable patterns of scores.
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
I'm not a fan of complex passwords as I have a hard time remembering them. Because of that I like the message of this comic.
However typing the sentence "correct horse battery staple" into this calculator yields "12.41 trillion trillion trillion centuries" as opposed to the comic's "550 years".
How can they differ so much, which one is correct if any and how would I know?
How do I create a strong enough password without making it difficult to remember?
The reason for this difference is basically given on the linked side itself:
IMPORTANT!!! What this calculator is NOT . . .
It is NOT a “Password Strength Meter.”
Since it could be easily confused for one, it is very important for you to understand what it is, and what it isn't:
The #1 most commonly used password is “123456”, and the 4th most common is “Password.” So any password attacker and cracker would try those two passwords immediately. Yet the Search Space Calculator above shows the time to search for those two passwords online (assuming a very fast online rate of 1,000 guesses per second) as 18.52 minutes and 17.33 centuries respectively! If “123456” is the first password that's guessed, that wouldn't take 18.52 minutes. And no password cracker would wait 17.33 centuries before checking to see whether “Password” is the magic phrase.
The caclulator basically only considers brute force attempts, while an actual attack would probably be a dictionary arrack. Since most combinations of letters are not actual words a dictionary attack will try a lot less combinations, thous getting a result much faster
IMPORTANT!!! What this calculator is NOT . . .
It is NOT a “Password Strength Meter.”
The calculator assumes that cracker uses exhaustive search. xkcd assumes that cracker may know (or guess) your method of generating password and needs to check only the passwords which you can choose. xkcd method is far safer.
Not any strong password is 100% safe, few websites can really protect user's password. You'd better not to use only one password everywhere. What you do is to keep the straw on fire away from others.
What I do is:
a unforgettable password: A;
the website asking for a password, "www.example.com", as B;
get C = md5(A) + md5(B), and use the leading 8 characters of C as the password;
write a simple script for this, and of course, you may adjust the algorithm, and do keep the script on cloud.
the browser will save password for us, if it asks you for re-enter the password, you can get it back at once.
The operator '+' is not as strcat. It means:
I get the md5 in low letters, and saying that the '0' values 0, ..., 'a' values 10, ..., 'A' is 36, ..., and as so on.Then calculate the result at every character with their values, discarding the carry, and do "mod(62)".
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm trying to put together a simple RSS widget (for my wordpress blog) that will show a list of stocks, or markets, and their current prices.
I cant seem to find an API for this data anywhere - can anyone suggest such a thing (perhaps as an RSS feed?)
Yahoo have an (undocumented) Stock Quotes API as part of their Finance API
Basically, http://download.finance.yahoo.com/d/quotes.csv?s=GOOG&f=ll will return the price for GOOG stock in CVS format
The s parameter is the stock symbol. You can specify multiple by separating them with +
quotes.csv?s=GOOG+YHOO
The f parameter is the data format code, which I found documented from this Python script (which is also how I discovered the API..):
code description
l1 price
c1 change
v volume
a2 avg_daily_volume
x stock_exchange
j1 market_cap
b4 book_value
j4 ebitda
d dividend_per_share
y dividend_yield
e earnings_per_share
k 52_week_high
j 52_week_low
m3 50day_moving_avg
m4 200day_moving_avg
r price_earnings_ratio
r5 price_earnings_growth_ratio
p5 price_sales_ratio
p6 price_book_ratio
s7 short_ratio
They are all documented on this page
The data is returned as a comma separated file, which should be utterly trivial to parse in any language
You can also use Google's Finance API to get Stock Quotes in a slightly round-a-bout way
Basically you create a Google Spreadsheet, and use the GoogleFinance function:
=GoogleFinance("GOOG"; "price")
..then use the Spreadsheet API to access that value
I found this via ["Introducing the Google Finance API"](http://googlified.com/introducing-the-google-finance-api/
), and "How to get a real-time stock quote using Google API" describes this is more detail, including a simple bash shell-script to access the data (I think it could be simplified by making the spreadsheet publicly accessible)
There are already a few Wordpress plugins; among others:
http://wordpress.org/extend/plugins/stock-quote-sidebar/
http://andy.hillhome.org/blog/code/stockquotesidebar/
http://wordpress.org/extend/plugins/stocks-watchlist/
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 3 years ago.
Improve this question
I think most of us agree that it's a good idea to use a descriptive name for variables, object attributes, and database columns. If you want to store something's name, you may as well call the attribute Name so people know what to put in it.
Where the unit of measurement isn't immediately apparent, I think you should go a step further and include the unit of measurement in the name. Length_mm, for example, should help remind developers that they'd better convert the length to mm if the user just entered it in inches.
My database administrator, however, just told me that including units of measurement in database column names is “frowned upon”. I think that's just nuts, but perhaps there's some risk DBAs know about that I don't.
Throw me a line, here: should we embed units of measurement in our attribute names? Why? Why not?
If you have a consistent UOM for things, then your DBA's policy is OK.
For example, if timespans are ALWAYS in minutes, etc.
If the UOM could change, then you should store it in another column, alongside the qty.
That said, I tend to side with you on this. Clarity trumps most things, including this. I'd rather see DurationMinutes than Duration and have to guess what the UOM is.
Yes. You should.
The key, as #[Charles Bretana] pointed out, is legibility and that the other users of your table or developers following you know what you're using.
I would absolutely involve the units/measurement in a field name - in my business you can't guess what you'll find from the context or name: a field entitled MarketValue - is that in millions, thousands or units? US Dollars, Euros, pounds, $CURRENCY? Is that value a percentage, a ratio? Absolute or relative? Daily, monthly, calendar year, financial year? That timestamp, what time zone is it?
Your first, last and only task when providing data is to ensure that it isn't used incorrectly because the consumer wasn't able to find out enough about it. As developers, throwing "Metre", "USD", "GMT", "Percent" or whatever into a field name isn't the least bit smelly.
There are enormous smells that need resolving before the tiny whiff of field naming needs standardising.
This is why the Mars Climate Orbiter crashed into the surface at 350 meters/sec when it was planned to only handle 350 ft/sec (or something like that).
Although "Never say 'Never' or 'Always'" is, in general, a good rule of thumb, here I will bend my rule and say I think you should "always" make it clear what units a numeric value is in.
The convention of naming all my columns in the format:
{name}_in_{unit}
helped for one project, since I was using si units it actually ended up allowing me to be able to infer the column data type and generally simplify my writing style.
length_in_m
speed_in_ms-1
color_in_nm
there were a few exceptions that I handled either with at_time or number_of:
started_at_time
updated_at_time
number_of_rotations
I think this is a good idea anywhere since there is always room for ambiguity.
For example, the with high performance timer class we use, I keep having to check if the GetElapsed() method returns seconds or milliseconds or something else. If it were called GetElapsedMilliseconds() that would save the confusion.
The only downside being if you wanted to change your mind ... but in that case any clients would need to know about the change anyway.
F# has an interesting twist on this allowing measurement units to be specified in the type system. See this blog post, and another stackoverflow question discussing Are units of measurement unique to F#?
I've done a lot of database work, and I would not frown upon that at all, nor have I heard of frowning on it.
It's better than the extended properties, which is not apparent to the casual developer. It's better than in a separate document, because many developers won't read them, and certainly not in great detail. If the units are set, then having it in the name sounds like a good idea. If that changes, then when the unit field is added, change the name of the measurement field.
Where the unit of measurement isn't immediately apparent, I think you should go a step further and include the unit of measurement in the name. Length_mm, for example, should help remind developers that they'd better convert the length to mm if the user just entered it in inches.
You could go even a step further (in your code, not in the database) and have a Length type, which takes care of the measurement unit and of possible conversions. This is the approach of the "Quantity" pattern in Martin Fowler's "Analysis Patterns" book.
Do not put units of measurement (or column type) in your database column names.
Many Databases have the ability to document/comment columns in some way (in SQL Server it is sp_addextendedproperty), I would suggest that is a more appropriate place.
For Python datetimes, consider using objects from the datetime package. Doing so will capture the unit implicity to microsecond resolution. There is then no basis for including the unit in the variable name.
If you must use an int or float instead, it is strongly recommend to suffix the unit name abbreviation to the variable name. For example, instead of the variable name diff, use diff_secs for seconds, diff_ms for milliseconds, diff_µs for microseconds, or diff_ns for nanoseconds.
We don't put units of measurement in column names in our database. We do, however, have a data dictionary document where all of the columns and relationships are described.
The ideal approach is, if possible, to use a type that leaves no ambiguity as to the measurement. For example in .NET rather than saying int periodInSeconds you'd be much better off using TimeSpan period.
The F# language actually has units of measurement as part of the type system so you can declare types in units such as 10<m/s> and 5<s> and even perform calculations on them so something like 10<m/s> * 5<s> would result in 50<m>. See here for more info.
So I'd say if possible use a type that conveys your intention, but if that isn't possible then you should probably encode the measurement into the name. It's better and more obvious than a comment.
You definitely want units of measurement somewhere. I don't know if the column names are a good place or if the schema is better. Ask your database administrator
Where is the information about units of measure stored?
How can I get access to the units programmatically?
If the answers are "it isn't" or "you can't", complain bitterly---they have no right to deny you your naming convention. Otherwise, all may be happier if you work within the system.
P.S. I really like the support for units of measure that they've put into F#.
I have to say, I hate "descriptive" variable names becoming "incredibly verbose" variable names.
My preferred alternative is to use nothing but the unit-of-measure names in short functions. Eg.
function velocity(m, s) {
return m/s;
}
You don't need to say "length_m" because in this context, it's obvious that only lengths are measurable in metres.
Having said that. If I was writing a system where units of measure errors were really dangerous, I'd probably use the type system and define a Length class which always converted itself into a standard unit for any calculation. Maybe even different sub-classes for Feet, Metres etc.
NO, the name of the attribute is seperate from its unit of measurement.
If you call a variable length_mm then you are tied to mm.
what if you use a 32bit int to store length_mm, eventually the length in mm may get larger then 62,000, or whatever the limit is on 32bit ints. You cant switch over to m cause you tied you length variable to length_mm.
I think putting units in your identifiers is a huge design smell. It almost surely means that you chose the wrong language: if units are so important to the project, you'd better be using a language whose type system is capable of representing them.