Decimal Save not Working in Rails 3.1 - ruby-on-rails-3

In my controller I am running the following code:
#place = Place.new :latitude => params[:lat].to_d, :longitude=>params[:lng].to_d
puts #place.latitude
puts #place.longitude
#place.save!
puts #place.latitude
puts #place.longitude
And the output in my server log is as follows:
37.865338226051534
-122.25851513692476
37.09024
-95.712891
I understand the fact that it is being rounded, as I used precision 15 scale 10 decimals. But why is it changing the number to a completely different value?!

Turns out the library I was using was limiting the size during a calculation.

Related

Reproducible screenshots with Selenium and Firefox

I use Selenium to automate some GUI tests using the firefox web driver.
It occurred to me that it would be also make sense to create screenshots during the run of the tests to use those in the manual.
The screens of my application are relatively static - no timestamps visible and so on. So my expectation would be, if I create a screenshot from lets say the start page, navigate later to the start page again, the screenshots should be identical. Also if I run the test twice, the screenshot of the start page should be identical between both runs.
I save the screenshots as PNG, I even process the screenshots (save without date) before saving them, so that the files should be really identical.
Nevertheless, if I compare the pictures with each other (e.g. subtract them from each other), there are minor differences between them (not visible to the naked eye), some faint lines at the border of tables, or around fonts.
My question:
1) Why are there differences at all?
2) What could be the easiest way to ensure that the screenshots are identical? (what kind of post processing could I do)
PS: I also tried to change the renderer from skia to windows to cairo, but although the differences are slightly different, it still doesn't solve the problem.
How do you save the images ?
In ruby I was using something like this ?
def take_screenshot(image_id)
scenario = Zpg::HooksHelper::FeatureHelper.scenario_name
Dir.mkdir('output', 0o777) unless File.directory?('output')
Dir.mkdir('output/screenshots', 0o777) unless File.directory?('output/screenshots')
screenshot = "./output/screenshots/#{image_id}#{scenario.tr(' ', '_').gsub(/[^0-9A-Za-z_]/, '')}.png"
if page.driver.browser.respond_to?(:save_screenshot)
page.driver.browser.save_screenshot(screenshot)
else
save_screenshot(screenshot)
end
FileUtils.chmod(0o777, screenshot)
end
And I was checking the image diff
# return[hash]
def image_diff(imageid_1 = nil, _imageid_2 = nil)
scenario = Zpg::HooksHelper::FeatureHelper.scenario_name
if imageid_1.class != Integer
image_1 = "./features/support/data/images/#{Zpg.brand}/#{imageid_1}.png"
image_2 = "./output/screenshots/#{_imageid_2}#{scenario.tr(' ', '_').gsub(/[^0-9A-Za-z_]/, '')}.png"
else
image_1 = "./output/screenshots/#{imageid_1}#{scenario.tr(' ', '_').gsub(/[^0-9A-Za-z_]/, '')}.png"
image_2 = "./output/screenshots/#{_imageid_2}#{scenario.tr(' ', '_').gsub(/[^0-9A-Za-z_]/, '')}.png"
end
images = [
ChunkyPNG::Image.from_file(image_1),
ChunkyPNG::Image.from_file(image_2)
]
diff = []
images.first.height.times do |y|
images.first.row(y).each_with_index do |pixel, x|
diff << [x, y] unless pixel == images.last[x, y]
end
end
puts "pixels (total): #{images.first.pixels.length}"
puts "pixels changed: #{diff.length}"
puts "pixels changed (%): #{(diff.length.to_f / images.first.pixels.length) * 100}%"
# init empty hash
diff_hash = {}
# return pixels changed number
diff_hash[:pixels_changed] = diff.length
# return pixels changed percentage
diff_hash[:pixels_changed_percentage] = (diff.length.to_f / images.first.pixels.length) * 100
# return diff hash
diff_hash
end
you can get different results if the browser DOM is not 100% loaded . I would try to have a threshold in which I would expect my image to be .
There is a very good project here in .Net https://www.codeproject.com/Articles/374386/Simple-image-comparison-in-NET which you can convert in any language you want.

Pentaho cuts double values from Table Input

I have a Problem that I could not fix up to now. When I do a "Select" at a Table-Input the double values are not returned completely and are always cut. Here are some examples:
15.0420 => 15 // 12.6000 => 12,6 // 4.1176 => 4,1 // 0.1123 => 0,1 // 0.0012 => 0
I seems like, that minimum two numbers are shown and max one number after the comma. However it is very important to get the right figures.
I use pentaho 6.1, and mariaDB 5.5.49.
Thanks for every help.
Best regards,
Dave
Finally I adjusted the configuration of the Default Number Format. Under "Edit->Edit the kettle.properties file", I set the "KETTLE_DEFAULT_NUMBER_FORMAT" with the format '#.####'. Now it is working!

Printing a pdf of more than 5000 pages takes longtime using Prawn pdf gem

I am using prawn pdf gem to print pdf.
I am formatting the data in to tables and then printing it to the pdf. I have around 5000 pages (about 50000 entries) to print and it takes forever. For small number of pages its quick ... Is there any way I can improve the speed of printing.
Also, printing without the data in table format was quick. please help me out with this.
code for this :
format.pdf {
pdf = Prawn::Document.new(:margin => [20,20,20,20])
pdf.font "Helvetica"
pdf.font_size 12
#test_points_all = Hash.new
dataset_id = Dataset.where(collection_success: true).order('created_at DESC').first
if(inode.leaf?)
meta=MetricInstance.where(dataset_id: dataset_id, file_or_folder_id: inode.id).includes(:test_points,:file_or_folder,:dataset).first
#test_points_all[inode.name] = meta.test_points
else
nodes2 = []
nodes2 = inode.leaves
if(!nodes2.nil?)
nodes2.each do |node|
meta=MetricInstance.where(dataset_id: dataset_id, file_or_folder_id: node.id).includes(:test_points,:file_or_folder,:dataset).first
#test_pointa = meta.test_points
if(!#test_pointa.nil?)
#test_points_all[node.name] = #test_pointa
end
end
end
end
#test_points_all.each do |key, points|
table_data = [["<b> #{key} </b>", "<b>433<b>","xyz","xyzs"]]
points.each do |test|
td=TestDescription.find(:first, :conditions=>["test_point_id=?", test.id])
if (!td.nil?)
table_data << ["#{test.name}","#{td.header_info}","#{td.comment_info}","#{td.line_number}"]
end
pdf.move_down(5)
pdf.table(table_data, :width => 500, :cell_style => { :inline_format => true ,:border_width => 0}, :row_colors => ["FFFFFF", "DDDDDD"])
pdf.text ""
pdf.stroke do
pdf.horizontal_line(0, 570)
end
pdf.move_down(5)
end
end
pdf.number_pages("<page> of <total>", {
:start_count_at => 1,
:page_filter => lambda{ |pg| pg > 0 },
:at => [pdf.bounds.right - 50, 0],
:align => :right,
:size => 9
})
pdf.render_file File.join(Rails.root, "app/reports", "x.pdf")
filename = File.join(Rails.root, "app/reports", "x.pdf")
send_file filename, :filename => "x.pdf", :type => "application/pdf",:disposition => "inline"
end
The first of those two lines is pointless, take it out!
nodes2 = []
nodes2 = inode.leaves
Based on your information, i understand that the following query to the database seems to be performed around 50000 times ... Depending on the volume and content of your table, it might be very reasonable to perform one single query (fetching the whole table) at the start of your whole script, and to keep this data in memory to perform any following operations on it in pure Ruby, without talking to the database. Then again, if the table you are working with is insanely huge, it might also totally clog up your memory and be not a good idea at all. It really depends ... so figure it out!
TestDescription.find(:first, :conditions=>["test_point_id=?", test.id])
Also, if, as you say, printing without tables was very quick, you might be able to achieve a major speedup by reimplementing that minor part of table functionality you are actually using yourself, with only low level functions from prawn. Why? Prawn's table function is surely made to fulfill as many usecases as possible, and therefore includes a lot of overhead (at least form the perspective of someone who needs only barebones functionality - For everyone else this "overhead" is gold!). And therefore you can just implement that little part of tables you need yourself, and that might just give you a major performance boost. Give it a shot!
If you're using a recent version of ActiveRecord, I'd suggest using pluck in your inner loop. Instead of this:
td=TestDescription.find(:first, :conditions=>["test_point_id=?", test.id])
if (!td.nil?)
table_data << ["#{test.name}","#{td.header_info}","#{td.comment_info}","#{td.line_number}"]
end
Try this instead:
td = TestDescription.where(test_point_id: test.id)
.pluck(:name, :header_info, :comment_info, :line_number).first
table_data << td unless td.blank?
Instead of instantiating an ActiveRecord object for each TestDescription, you'll just get back an array of field values that you should be able to append directly to table_data, which is really all you need here. This means less memory usage, and less time spent in GC.
It might also be worth trying to use pluck to retrieve all the entries at once, in which case you'd have an array of arrays to loop over. This would take more memory than fetching one at a time, but a lot less than an array of AR objects, and you'd save doing separate db queries.

Round to sensible location in rails

I'd like to round my floats to get rid of all trailing zeros after the decimal place in rails, inside a model method.
So, 30.0 becomes 30 but 10.5 stays 10.5.
I know about number_with_precision and it works if I do
include ActionView::Helpers::NumberHelper
in my model. Is this poor design? Is there a better alternative that doesn't involve moving the rounding into a helper?
This is the source code of the number_with_precision method.
# File actionpack/lib/action_view/helpers/number_helper.rb, line 199
def number_with_delimiter(number, options = {})
options.symbolize_keys!
begin
Float(number)
rescue ArgumentError, TypeError
if options[:raise]
raise InvalidNumberError, number
else
return number
end
end
defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
options = options.reverse_merge(defaults)
parts = number.to_s.to_str.split('.')
parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{options[:delimiter]}")
parts.join(options[:separator]).html_safe
end
Nothing prevents you to clone this method into your model. You might want to remove the unnecessary parts.

Rails number_to_currency precision doesn't work - is it a bug?

I'm trying to use number_to_currency to get two digits after the decimal dot in Rails 3, but I can get only one. My DB field is defined like this:
t.decimal "amount", :precision => 5, :scale => 2
In my template I have:
#{number_to_currency(#purch.amount)}
And yet as the result I get: PLN 34,7
In the DB I can clearly see: 34.70
I would like to see my second zero - is it a feature or am I missing something?
Thanks!
The answer is to check the following setting in one's locale configuration file:
currency:
format:
strip_insignificant_zeros: false
Since you seem to be using a custom locale, try forcing the behavior you want by explicitly setting the options of number_to_currency:
number_to_currency(#purch.amount, :precision => 2)
You can also set these options in the locale file for your language. Take a look at http://guides.rubyonrails.org/i18n.html