Rufus scheduler syntax error - ruby

Original code:
require 'oci8'
SCHEDULER.every '10s', :first_in => 0 do |job|
begin
conn = OCI8.new('apps','apps');
mylist = Hash.new
conn.exec("select full_name, count(*) from per_all_people_f
where rownum < 6 group by first_name") do |r|
mylist[r[0]] = { label: r[0], value: r[1].to_i.to_s }
end
send_event('emp-list', { items: mylist.values })
conn.logoff
rescue Exception => e
puts e.message
end
end
Running ruby oratest1.rb gives following errors:
oratest1.rb:11: syntax error
mylist[r[0]] = { label: r[0], value: r[1].to_i.to_s }
^
oratest1.rb:11: syntax error
mylist[r[0]] = { label: r[0], value: r[1].to_i.to_s }
^
oratest1.rb:11: syntax error
oratest1.rb:13: syntax error
send_event('emp-list', { items: mylist.values })
^
oratest1.rb:13: syntax error
send_event('emp-list', { items: mylist.values })
^
oratest1.rb:17: syntax error
rescue Exception => e
^
oratest1.rb:21: syntax error

You are probably using ruby 1.8. This hash syntax was included on 1.9 onwards.
To make sure, run ruby -v and check the output.

If you using ruby prior to 1.9, you must use the following syntax for hashes:
mylist[r[0]] = { :label => r[0], :value => r[1].to_i.to_s }
The syntax that you are using is valid in ruby 1.9 and onwards!

Related

How to delete a row from CSV in ruby with Table.delete_if()

I'm reading in a csv file
require 'csv'
recipients = CSV.read('recipients.csv', headers: true)
found = []
if User.find_by(email: recipients['email'])
found << recipients['email']
end
table = CSV.table('recipients.csv')
table.delete_if do |t|
found.each { |f| t['email'] == f['email']}
end
CSV.open('/tmp/users.csv', 'wb') do |w|
w << found.to_csv
end
The following line: found.each { |f| t['email'] == f['email']}
results in a
TypeError: no implicit conversion of String into Integer
from lib/scripts/foo.rb:13:in[]'`
It's obvious I don't grok how to use delete_if and how to resolve the type mismatch in this case.
So, help is very much appreciated.
in line number 13
found.each { |f| t['email'] == f['email']}
f is an instance of Array and your are trying to pass a String as an index, so this might have occurred.
Explanation
> a=[]
=> []
2.2.1 :015 > a['email']
TypeError: no implicit conversion of String into Integer
from (irb):15:in `[]'
> a=['email', 'ram']
=> ["email", "ram"]
2.2.1 :018 > a['email']
TypeError: no implicit conversion of String into Integer
from (irb):18:in `[]'

How to make pg gem query result symbolized?

In mysql2 gem, we can use this statement to make all query result symbolized
require 'mysql2'
Mysql2::Client.default_query_options.merge!(symbolize_keys: true)
DB = Mysql2::Client.new(host: "localhost", username: "benchmarkdbuser", password: 'benchmarkdbpass')
DB.select_db('hello_world')
res = DB.query "SELECT id, message FROM Fortune"
rows = res.map { |row| row }
# [{id: 1, message: 'bla'}] --> id and message are symbols, not strings
how to do this on pg gem?
require 'pg'
DB = PG::Connection.new('localhost',5432,nil,nil,'hello_world','benchmarkdbuser','benchmarkdbpass')
res = DB.query "SELECT id, message FROM Fortune"
rows = res.map { |row| row }
# [{"id" => 1, "message" => "bla"}] --> id and message are strings, not symbols
If there is no native way:
h_to_sym = ->(row){ row.keys.each_with_object({}) { |k, o|
o[k.to_sym] = row[k].is_a?(Hash) ? h_to_sym.(row[k]) : row[k] }
}
p res.map.with_object([]) { |row, h| h << h_to_sym.(row) }
This also supports joined models.

JumpStart Labs Event Manager: Syntax Error, unexpected ':'

I'm working on the JumpStart Labs Event Manager, specifically the time/day of the week targeting, and I'm running into trouble. When I run the following code through Terminal, it gives me the following error [EDIT]:
austin-winslows-macbook-4:event_manager HypnoBoy$ ruby event_manager.rb
event_manager.rb:8: odd number list for Hash
...vent_attendees.csv', {headers: true, header_converters: :sym...
^
event_manager.rb:8: syntax error, unexpected ':', expecting '}'
...vent_attendees.csv', {headers: true, header_converters: :sym...
^
event_manager.rb:8: Can't assign to true
...ttendees.csv', {headers: true, header_converters: :symbol})
^
event_manager.rb:8: syntax error, unexpected ':', expecting '='
...ders: true, header_converters: :symbol})
I've posted my code below, and am looking for suggestions! Something about the syntax is obviously off, but I've followed the steps to the letter thus far, and haven't had any problems, so I'm not sure where to look anymore. Any help would be a great help, thanks!
require 'csv'
require 'sunlight/congress'
require 'erb'
require 'date'
Sunglight::Congress.api_key = "e179a6973728c4dd3fb1204283aaccb5"
contents = CSV.open('event_attendees.csv', {headers: true, header_converters: :symbol})
def clean_zipcode(zipcode)
zipcode.to_s.rjust(5,"0")[0..4]
end
def clean_phone(number)
number.to_s.rjust(10,"0")[0..4]
end
def legislators_by_zipcode(zipcode)
Sunglight::Congress::Legislator.by_zipcode(zipcode)
end
def peak_days
time = row[:regdate]
day_array = []
time.each { |t|
array << Datetime.strptime(t, '%m/%d/%Y %H:%M').wday }
end
def peak_hours
time = row[:regdate]
hr_array = []
time.each { |t|
array << DateTime.strptime(t, '%m/%d/%Y %H:%M').hour }
array
end
def save_thanks_you_letters(id,form_letter)
Dir.mkdir("output") unless Dir.exists? "output"
filename = "output/thanks_#{id}.html"
File.open(filename, 'w') { |file|
file.puts form_letter}
end
puts "EventManager Initialized!"
template_letter = File.read "form_letter.erb"
erb_template = ERB.new template_letter
contents.each { |row|
id = row[0]
name = row[:first_name]
zipcode = clean_zipcode(row[:zipcode])
phone = clean_phone(row[:homephone])
legislators = legislators_by_zipcode(zipcode)
form_letter = erb_template.result(binding)
save_thank_you_letters(id,form_letter)
}
from the doc CSV::open you are using the construct :
open( filename, options = Hash.new )
So you line :
contents = CSV.open 'event_attendees.csv', headers: true, header_converters: :symbol is wrong,as from 2nd parameter onward it is expecting a Hash. Thus change it to:
contents = CSV.open('event_attendees.csv', {headers: true, header_converters: :symbol})
I completed this exercise today. I didn't have to change the contents = CSV.open line. What caused the error for me was that the date was not formatted in the Excel file. I formatted that date column to mm/dd/yyyy hh:mm in Excel. Also capitalization seemed to matter in the '%m/%d/%Y %H:%M' string -- I used lowercase 'y'.
This is what my first time exercise looks like:
# Iteration: Time Targeting
contents = CSV.open "event_attendees.csv", headers: true, header_converters: :symbol
regtimes = Array.new(25, 0)
contents.each do |row|
reghour = DateTime.strptime(row[:regdate],'%m/%d/%y %H:%M').hour
regtimes[reghour] += 1
end

When running Chef, RubyGems throws a System Stack Error

I'm running Ruby 1.9.3p392 and I've installed the latest chef gem (11.4.2). When I try to run any of the chef command line utilities, I get the following error:
bin/ruby_noexec_wrapper:14: stack level too deep (SystemStackError)
In fact, running the following also causes a similar error to be thrown:
require 'rubygems'
gem 'chef' # or gem 'chef', '11.4.2'
Digging a bit deeper, I see that the issue seems to originate from lib/ruby/site_ruby/1.9.1/rubygems/requirement.rb:
lib/ruby/site_ruby/1.9.1/rubygems/requirement.rb:24: stack level too deep (SystemStackError)
Which is odd, because that line is apart of a block that's defining a hash of lambdas that represent various requirement operations (ie; are versions =, is version1 >= version2, etc).
class Gem::Requirement
OPS = { #:nodoc:
"=" => lambda { |v, r| v == r },
"!=" => lambda { |v, r| v != r },
">" => lambda { |v, r| v > r },
"<" => lambda { |v, r| v < r },
">=" => lambda { |v, r| v >= r }, # <-- line 24
"<=" => lambda { |v, r| v <= r },
"~>" => lambda { |v, r| v >= r && v.release < r.bump }
}
#...
end
Scrolling down the file, I see that the only place OPS[">="] could be called is on line 198:
def satisfied_by? version
raise ArgumentError, "Need a Gem::Version: #{version.inspect}" unless
Gem::Version === version
# #28965: syck has a bug with unquoted '=' YAML.loading as YAML::DefaultKey
requirements.all? { |op, rv| (OPS[op] || OPS["="]).call version, rv } # <-- line 198
end
I've noticed that at the time of running requirements.all?, requirements is set to [[">=", #<Gem::Version "0">]]. It seems to be evaluating <Gem::Version "11.4.2"> >= <Gem::Version "0">.
I've been working on this all day and I have yet to get to the bottom of it. Could anybody help me understand why RubyGems is throwing this error?
Thanks.
edit: Chef seems to run fine on 1.8.7. Could it be an issue with 1.9.3?

How to use custom RR wildcard matcher?

I have created a wildcard matcher for RR that matches JSON strings by parsing them into hashes. This is because JSON (de)serialization doesn't preserve order; if we have:
{ 'foo': 42, 'bar': 123 }
... then after (de)serialization, we might find that our update method is called with:
{ 'bar': 123, 'foo': 42 }
The wildcard matcher looks like this:
class RR::WildcardMatchers::MatchesJsonString
attr_reader :expected_json_hash
def initialize(expected_json_string)
#expected_json_hash = JSON.parse(expected_json_string)
end
def ==(other)
other.respond_to?(:expected_json_hash) && other.expected_json_hash == self.expected_json_hash
end
def wildcard_matches?(actual_json_string)
actual_json_hash = JSON.parse(actual_json_string)
#expected_json_hash == actual_json_hash
end
end
module RR::Adapters::RRMethods
def matches_json(expected_json_string)
RR::WildcardMatchers::MatchesJsonString.new(expected_json_string)
end
end
... and we're using it like:
describe 'saving manifests' do
before do
#manifests = [
{ :sections => [], 'title' => 'manifest1' },
{ :sections => [], 'title' => 'manifest2' }
]
mock(manifest).create_or_update!(matches_json(#manifests[0].to_json)) { raise 'uh oh' }
mock(manifest).create_or_update!(matches_json(#manifests[1].to_json))
parser = ContentPack::ContentPackParser.new({
'manifests' => #manifests
})
#errors = parser.save
end
it 'updates manifests' do
manifest.should have_received.create_or_update!(anything).twice
end
end
This in accordance with the RR documentation. However, instead of mock() expecting an argument that matches JSON, it expects the argument to be a MatchesJsonString object:
1) ContentPack::ContentPackParser saving manifests updates manifests
Failure/Error: mock(Manifest).create_or_update!(matches_json(#manifests[0].to_json)) { raise 'uh oh' }
RR::Errors::TimesCalledError:
create_or_update!(#<RR::WildcardMatchers::MatchesJsonString:0x13540def0 #expected_json_hash={"title"=>"manifest1", "sections"=>[]}>)
Called 0 times.
Expected 1 times.
# ./spec/models/content_pack/content_pack_parser_spec.rb:196
The answer is that there's a typo in the documentation to which I linked. This (my emphasis):
#wildcard_matches?(other)
wildcard_matches? is the method that actually checks the argument against the expectation. It should return true if other is considered to match, false otherwise. In the case of DivisibleBy, wildcard_matches? reads:
... should actually read:
#wildcard_match?(other)
...
One of my colleagues suggested that we compare our code with one of the matchers defined in the rr gem, and then the difference stood out.

Resources