I have a database table which stores the units name in full like liters, kilograms, milliliters, milligrams etc.. I need a library to recogonize these units and convert it to the unit I wish to. How do i do this ?
Code Logic:
I will read the unit "liters" from database and i wish to convert it to milli-liters so her the input is "20 liters" and output should be "20000 milli-liters"
I downloaded JScience library but i am not sure how to do this. please tel me how to use that or suggest any alternative. It would be better if you explain me with a code sample. Thanks!!
I'm inclined to say use Frink, but it does WAY more than you need here, although it does solve the problem
20 litres -> milliliters
//gives 20000
And it is just a cool little language. In java you'd have to run it like any other scripting library. The website has loads of info
I'm not aware that JScience provides a facility for parsing strings like "20 liters" (that spelling makes me cringe...), so you'll probably have to handle that yourself, by tokenizing the string into quantities and units.
Once you have that, you can use JScience to convert between units easily enough, although obviously converting from litres to milliltres is trivial. But in principle, it's something like:
Measure<Integer, Volume> input = Measure.valueOf(20, NonSI.LITRE);
Measure<Integer, Volume> output = input.to(SI.MILLI(NonSI.LITRE));
System.out.println(output);
Related
I'm new to learning Java and I'm bad at English but I try my best to write good, understandable source code.
I want to make variables to save the "number of cars" or "number of items". How do I abbreviate "number of ..." without using symbols like # that don't work in a source code?
Thanks
You have several choices to do that
numberOfItems (verbose, but clear in meaning)
numItems (it's ok)
itemCount (probably, the best — what I'd have used)
items (shortest, but can't know if it is an integer or a list of items)
I try my best to write good, understandable source code
Then my best advice would be not to abbreviate variable names.
Just go with numberOfCars.
Why?
I know you've probably seen a lot of programs where people use one-letter variables or stuff like numCars.
Abbreviating your variables make your code less clear for others (including you in 6 months).
We all have great text editors with auto-completion on variables, use that.
I am using freemarker and trying to display numbers in this format: $3,343,434.00 for example. This was easily taken care of by using ${total?string.currency} (assuming "total" is some number).
However, when I have negative numbers, it's showing them like this: ($343.34) instead of this: -$343.34. I need the negative sign instead of the parenthesis. Is there a way I could customize the formatting so it does everything that the string.currency did but replace the negative value behavior? I am relatively new to freemarker, so detailed responses are appreciated!
You can also try ?string(",##0.00"). However in this case you need to explicitly add $ and - sign would be after $ in case of negative numbers.
<#local total = 3343434/>
$ ${total?string(",##0.00")} //$ 3,343,434.00
<#local total = -3343434/>
$ ${total?string(",##0.00")} //$ -3,343,434.00
OR in case if you want what was expected you can replace the strings.
<#local total = -3343434/>
<#local total = "$ " + total?string(",##0.00")/>
${total?replace('$ -','- $')} //- $3,343,434.00
Update: Since FreeMarker 2.3.24 you can define named custom number formats, which can be an alias to a number format pattern (or even a formatter implemented in Java, but that level of flexibility isn't needed in this case). So add a custom number format called "money" as an alias to "¤,##0.00" to the FreeMarker configuration, and then you can write something like ${total?string.#money}. See: http://freemarker.org/docs/pgui_config_custom_formats.html
Currently FreeMarker just uses the formatting facility of the Java platform, so it's only as configurable as that (assuming you want to use ?string and ?string.somethingPredefiendHere). Which is not much... but, in general, the formatting categories provided by the Java platform is not fine-gradient enough anyway, I mean, you don't have application-domain categories like, price-of-product, a salary, a price on the stock, etc. (This demand is more frequent with non-currency numbers though.) So I think, generally, you want to make a formatter function, that you can use like ${salary(someNumber)}, ${price(someNumber)}, etc. Those functions can be implemented in a commonly #included/#imported template like a #function or in Java by using #assign salary = 'com.example.SalarayMethod'?new() in place of #function, where com.example.SalarayMethod is a TemplateMethodModelEx.
How about taking a mod of your number, convert it to the required string format and finally add a '-' prefix to the final string. You can retain the default format in just two steps.
Freemarker uses the currency formatting provided by the Java platform.
It requires a little tweaking of the DecimalFormat returned by NumberFormat.getCurrencyInstance() (which is what is called when you call .currency). You can see examples of it here.
However, that said it will likely be more effective for you to create a macro in freemarker to call which will handle your specific formatting.
Sorry for not having an example of what that macro would look like, but it's a good starter into macros in freemarker since you are just learning.
You might investigate if you can supply a custom format using the exposed configuration for number formats that will meet your needs.
If you want to maintain the default currency formatting (in case you need to use a locale other than '$'), you can just replace the parentheses like so:
${transaction.amount?string.currency?replace("(","-")?replace(")","")}
This will work without error regardless of if a number is negative or positive.
TIP: Make sure the number is actually a number with the ?number directive before converting to a currency format
I want to be able to parse expressions representing physical quantities like
g/l
m/s^2
m/s/kg
m/(s*kg)
kg*m*s
°F/(lb*s^2)
and so on. In the simplest way possible. Is it possible to do so using something like Pyparsing (if such a thing exists for Java), or should I use more complex tools like Java CUP?
EDIT: To answere MrD's question the goal is to make conversion between quantities, so for example convert g to kg (this one is simple...), or maybe °F/(kg*s^2) to K/(lb*h^2) supposing h is four hour and lb for pounds
This is harder than it looks. (I have done a fair amount of work here). The main problem is there is no standard (I have worked with NIST on units and although they have finally created a markup language few people use it). So it's really a form of natural language processing and has to deal with :
ambiguity (what does "M" mean - meters or mega)
inconsistent punctuation
abbreviations
symbols (e.g. "mu" for micro)
unclear semantics (e.g. is kg/m/s the same as kg/(m*s)?
If you are just creating a toy system then you should create a BNF for the system and make sure that all examples adhere to it. This will use common punctuation ("/", "", "(", ")", "^"). Character fields can be of variable length ("m", "kg", "lb"). Algebra on these strings ("kg" -> 1000"g" has problems as kg is a fundamental unit.
If you are doing it seriously then ANTLR (#Yaugen) is useful, but be aware that units in the wild will not follow a regular grammar due to the inconsistencies above.
If you are REALLY serious (i.e. prepared to put in a solid month), I'd be interested to know. :-)
My current approach (which is outside the scope of your question) is to collect a large number of examples from the literature automatically and create a number of heuristics.
Specifically I am converting a python script into a java helper method. Here is a snippet (slightly modified for simplicity).
# hash of values
vals = {}
vals['a'] = 'a'
vals['b'] = 'b'
vals['1'] = 1
output = sys.stdout
file = open(filename).read()
print >>output, file % vals,
So in the file there are %(a), %(b), %(1) etc that I want substituted with the hash keys. I perused the API but couldn't find anything. Did I miss it or does something like this not exist in the Java API?
You can't do this directly without some additional templating library. I recommend StringTemplate. Very lightweight, easy to use, and very optimized and robust.
I doubt you'll find a pure Java solution that'll do exactly what you want out of the box.
With this in mind, the best answer depends on the complexity and variety of Python formatting strings that appear in your file:
If they're simple and not varied, the easiest way might be to code something up yourself.
If the opposite is true, one way to get the result you want with little work is by embedding Jython into your Java program. This will enable you to use Python's string formatting operator (%) directly. What's more, you'll be able to give it a Java Map as if it were a Python dictionary (vals in your code).
I have some code which needs to do things based on a schedule: e.g. during business hours do X, after hours do Y. The schedule will be defined by our customer's so I need a notation which can be written by people and parsed by my program. I'm thinking of something like:
12/25:0730-1730 Do Y
[Mo-Fr]:0730-1730 Do X
[Mo-Tu]:1730-0730 Do Y
Fr:1730-Mo:0730 Do Y
There will definitely be weekly variation. Yearly variation (holidays) seems likely. I would like a notation that is efficient and flexible.
I also need java code which will parse the time ranges and tell me which range a given date time is in.
I've searched the web and found nothing. Closest is CRON notation, which is not quite what I need.
Any one know of an existing notation definition and implementation?
Thanks,
For Java Joda time (Scala wrapper scala-time) is a powerful library for time calculations. You could look at the google-rfc-2445 which does something like what you are asking for (?).
If you are looking for a Java scheduler http://www.quartz-scheduler.org/ is a good option.
I don't think you will find something out of the box. In such cases it's better to do the implementation by yourself and have a full control of the code. You can use antlr to create a parser.
Add a notion of priority to your syntax. Then it will be easier to schedule someting
01.01.2011-31.01.2011 prio 1 do-idle-stuff
[Mo-Fr] prio 2 do-work
[Sa-Su] prio 2 weekend
10.02.2011-17.02.2011 prio 3 go-on-holidays