blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
4
137
path
stringlengths
2
355
src_encoding
stringclasses
31 values
length_bytes
int64
11
3.9M
score
float64
2.52
5.47
int_score
int64
3
5
detected_licenses
listlengths
0
49
license_type
stringclasses
2 values
text
stringlengths
11
3.93M
download_success
bool
1 class
6e3fc2ea255f48950e0b6b05ceb8ddaf1301ad04
Ruby
ktaragorn/mobile_detect
/lib/mobile_detect/core.rb
UTF-8
4,898
2.953125
3
[ "MIT" ]
permissive
require 'json' class MobileDetect attr_reader :http_headers attr_writer :user_agent # Construct an instance of this class. # @param [hash] http_headers Specify the http headers of the request. # @param [string] user_agent Specify the User-Agent header. If null, will use HTTP_USER_AGENT # from the http_headers hash instead. def initialize(http_headers = {}, user_agent = nil) @@data ||= load_json_data self.http_headers = http_headers self.user_agent = user_agent end def data @@data end #UNIMPLEMENTED - incomplete data, property hash and utilities hash not provided # version , prepareVersionNo # mobileGrade # detection mode (deprecated in MobileDetect) #not including deprecated params #Check if the device is mobile. #Returns true if any type of mobile device detected, including special ones #@return bool def mobile? (check_http_headers_for_mobile or match_detection_rules_against_UA) end #set the hash of http headers, from env in rails or sinatra #used to get the UA and also to get some mobile headers def http_headers=(env) @http_headers = env.select {|header, value| header.to_s.start_with? "HTTP_"} end #To access the user agent, retrieved from http_headers if not explicitly set def user_agent @user_agent ||= parse_headers_for_user_agent raise "User agent needs to be set before this module can function" unless @user_agent @user_agent end #Check if the device is a tablet. #Return true if any type of tablet device is detected. #not including deprecated params #@return bool def tablet? match_detection_rules_against_UA tablets end # Checks if the device is conforming to the provided key # e.g detector.is?("ios") / detector.is?("androidos") / detector.is?("iphone") # @return bool def is?(key) # Make the keys lowercase so we can match: is?("Iphone"), is?("iPhone"), is?("iphone"), etc. key = key.downcase lc_rules = Hash[rules.map do |k, v| [k.downcase, v.downcase] end] unless lc_rules[key] raise NoMethodError, "Provided key, #{key}, is invalid" end match lc_rules[key] end # Checks if the device is conforming to the provided key # e.g detector.ios? / detector.androidos? / detector.iphone? # @return bool def method_missing(name, *args, &blk) unless(Array(args).empty?) puts "Args to #{name} method ignored" end unless(name[-1] == "?") super end is? name[0..-2] end protected def load_json_data File.open(File.expand_path("../../../data/Mobile_Detect.json", __FILE__), "r") do |file| JSON.load(file) end end def ua_http_headers data["uaHttpHeaders"] end # Parse the headers for the user agent - uses a list of possible keys as provided by upstream # @return (String) A concatenated list of possible user agents, should be just 1 def parse_headers_for_user_agent ua_http_headers.map{|header| http_headers[header]}.compact.join(" ").strip end ["phones", "tablets", "browsers", ["os", "operating_systems"]].each do |(key,func)| func ||=key define_method func do data["uaMatch"][key] end end def rules @rules ||= phones.merge(tablets.merge(browsers.merge(operating_systems))) end # Check the HTTP headers for signs of mobile. # This is the fastest mobile check possible; it's used # inside isMobile() method. # # @return bool def check_http_headers_for_mobile data["headerMatch"].each do |mobile_header, match_type| if(http_headers[mobile_header]) return false if match_type.nil? || !match_type["matches"].is_a?(Array) Array(match_type["matches"]).each do |match| return true if http_headers[mobile_header].include? match end return false end end false end # Some detection rules are relative (not standard), # because of the diversity of devices, vendors and # their conventions in representing the User-Agent or # the HTTP headers. # This method will be used to check custom regexes against # the User-Agent string. # @return bool def match key_regex, ua_string = user_agent # Escape the special character which is the delimiter. # _, regex = key_regex regex = Array(key_regex).last # accepts a plain regex or a pair of key,regex regex.gsub!("/", "\/") !! (ua_string =~ /#{regex}/iu) end #Find a detection rule that matches the current User-agent. #not including deprecated params #@return bool def match_detection_rules_against_UA rules = self.rules # not sure why the empty check is needed here.. not doing it rules.each do |regex| return true if match regex end false end end
true
a5cd271abb67639f7288c1cef97f0f9fba3c6f8e
Ruby
Liboul/martyr
/spec/helpers/intervals_spec.rb
UTF-8
25,580
2.75
3
[ "MIT" ]
permissive
require 'spec_helper' def define_date_functions [0, 1, 2, 5, 10, 15, 20, 25, 30, 40, 45, 50, 80, 90, 100, 101, 150, 200, 250, 300, 350, 400, 500, 600].each do |x| let("d#{x}") { x.days.from_now } end end describe Martyr::Interval do define_date_functions describe 'initialize' do it 'does not allow from bigger than to: integers' do expect { Martyr::Interval.new 5, 5 }.to raise_error(Martyr::Error) expect { Martyr::Interval.new 5, [5] }.to raise_error(Martyr::Error) expect { Martyr::Interval.new [5], 5 }.to raise_error(Martyr::Error) expect { Martyr::Interval.new [5], [5] }.not_to raise_error end it 'does not allow from bigger than to: dates' do expect { Martyr::Interval.new d5, d5 }.to raise_error(Martyr::Error) expect { Martyr::Interval.new d5, [d5] }.to raise_error(Martyr::Error) expect { Martyr::Interval.new [d5], d5 }.to raise_error(Martyr::Error) expect { Martyr::Interval.new [d5], [d5] }.not_to raise_error end end describe 'overlap?' do context 'integers' do it 'is false when not overlapping on open intervals' do interval1 = Martyr::Interval.new 1, 5 interval2 = Martyr::Interval.new 5, 10 expect(interval1.overlap?(interval2)).to eq(false) end it 'is false when not overlapping on open and closed interval' do interval1 = Martyr::Interval.new 1, 5 interval2 = Martyr::Interval.new [5], 10 expect(interval1.overlap?(interval2)).to eq(false) end it 'is false when not overlapping on open and closed interval' do interval1 = Martyr::Interval.new 1, [5] interval2 = Martyr::Interval.new 5, 10 expect(interval1.overlap?(interval2)).to eq(false) end it 'is true when overlapping on closed intervals' do interval1 = Martyr::Interval.new 1, [5] interval2 = Martyr::Interval.new [5], 10 expect(interval1.overlap?(interval2)).to eq(true) end end context 'dates' do it 'is false when not overlapping on open intervals' do interval1 = Martyr::Interval.new d1, d5 interval2 = Martyr::Interval.new d5, d10 expect(interval1.overlap?(interval2)).to eq(false) end it 'is false when not overlapping on open and closed interval' do interval1 = Martyr::Interval.new d1, d5 interval2 = Martyr::Interval.new [d5], d10 expect(interval1.overlap?(interval2)).to eq(false) end it 'is false when not overlapping on open and closed interval' do interval1 = Martyr::Interval.new d1, [d5] interval2 = Martyr::Interval.new d5, d10 expect(interval1.overlap?(interval2)).to eq(false) end it 'is true when overlapping on closed intervals' do interval1 = Martyr::Interval.new d1, [d5] interval2 = Martyr::Interval.new [d5], d10 expect(interval1.overlap?(interval2)).to eq(true) end end end describe 'touch?' do context 'integers' do it 'is false when not overlapping on open intervals' do interval1 = Martyr::Interval.new 1, 5 interval2 = Martyr::Interval.new 5, 10 expect(interval1.touch?(interval2)).to eq(false) end it 'is true when not overlapping on open and closed interval' do interval1 = Martyr::Interval.new 1, 5 interval2 = Martyr::Interval.new [5], 10 expect(interval1.touch?(interval2)).to eq(true) end it 'is true when not overlapping on open and closed interval' do interval1 = Martyr::Interval.new 1, [5] interval2 = Martyr::Interval.new 5, 10 expect(interval1.touch?(interval2)).to eq(true) end it 'is true when overlapping on closed intervals' do interval1 = Martyr::Interval.new 1, [5] interval2 = Martyr::Interval.new [5], 10 expect(interval1.touch?(interval2)).to eq(true) end end context 'dates' do it 'is false when not overlapping on open intervals' do interval1 = Martyr::Interval.new d1, d5 interval2 = Martyr::Interval.new d5, d10 expect(interval1.touch?(interval2)).to eq(false) end it 'is true when not overlapping on open and closed interval' do interval1 = Martyr::Interval.new d1, d5 interval2 = Martyr::Interval.new [d5], d10 expect(interval1.touch?(interval2)).to eq(true) end it 'is true when not overlapping on open and closed interval' do interval1 = Martyr::Interval.new d1, [d5] interval2 = Martyr::Interval.new d5, d10 expect(interval1.touch?(interval2)).to eq(true) end it 'is true when overlapping on closed intervals' do interval1 = Martyr::Interval.new d1, [d5] interval2 = Martyr::Interval.new [d5], d10 expect(interval1.touch?(interval2)).to eq(true) end end end describe 'intersect' do context 'integers' do it 'returns nil when not overlapping on open intervals' do interval1 = Martyr::Interval.new 1, 5 interval2 = Martyr::Interval.new 5, 10 expect(interval1.intersect(interval2)).to eq(nil) end it 'returns nil when not overlapping on open and closed interval' do interval1 = Martyr::Interval.new 1, 5 interval2 = Martyr::Interval.new [5], 10 expect(interval1.intersect(interval2)).to eq(nil) end it 'returns nil when not overlapping on open and closed interval' do interval1 = Martyr::Interval.new 1, [5] interval2 = Martyr::Interval.new 5, 10 expect(interval1.intersect(interval2)).to eq(nil) end it 'returns the intersect when overlapping on a point' do interval1 = Martyr::Interval.new 1, [5] interval2 = Martyr::Interval.new [5], 10 x = interval1.intersect(interval2) expect(x.from.to_param).to eq([5]) expect(x.to.to_param).to eq([5]) end it 'returns the intersect of fully contained' do interval1 = Martyr::Interval.new 1, 20 interval2 = Martyr::Interval.new 5, 10 x = interval1.intersect(interval2) expect(x.from.to_param).to eq(5) expect(x.to.to_param).to eq(10) end it 'returns the intersect of partially contained on the right' do interval1 = Martyr::Interval.new 10, 20 interval2 = Martyr::Interval.new 15, 25 x = interval1.intersect(interval2) expect(x.from.to_param).to eq(15) expect(x.to.to_param).to eq(20) end it 'returns the intersect of partially contained on the left' do interval1 = Martyr::Interval.new 10, 20 interval2 = Martyr::Interval.new 5, 15 x = interval1.intersect(interval2) expect(x.from.to_param).to eq(10) expect(x.to.to_param).to eq(15) end it 'returns the intersect of identical' do interval1 = Martyr::Interval.new 10, 20 interval2 = Martyr::Interval.new 10, 20 x = interval1.intersect(interval2) expect(x.from.to_param).to eq(10) expect(x.to.to_param).to eq(20) end it 'overrides closed with open' do interval1 = Martyr::Interval.new [10], [20] interval2 = Martyr::Interval.new 10, 20 x = interval1.intersect(interval2) expect(x.from.to_param).to eq(10) expect(x.to.to_param).to eq(20) end end context 'dates' do it 'returns nil when not overlapping on open intervals' do interval1 = Martyr::Interval.new d1, d5 interval2 = Martyr::Interval.new d5, d10 expect(interval1.intersect(interval2)).to eq(nil) end it 'returns nil when not overlapping on open and closed interval' do interval1 = Martyr::Interval.new d1, d5 interval2 = Martyr::Interval.new [d5], d10 expect(interval1.intersect(interval2)).to eq(nil) end it 'returns nil when not overlapping on open and closed interval' do interval1 = Martyr::Interval.new d1, [d5] interval2 = Martyr::Interval.new d5, d10 expect(interval1.intersect(interval2)).to eq(nil) end it 'returns the intersect when overlapping on a point' do interval1 = Martyr::Interval.new d1, [d5] interval2 = Martyr::Interval.new [d5], d10 x = interval1.intersect(interval2) expect(x.from.to_param).to eq([d5]) expect(x.to.to_param).to eq([d5]) end it 'returns the intersect of fully contained' do interval1 = Martyr::Interval.new d1, d20 interval2 = Martyr::Interval.new d5, d10 x = interval1.intersect(interval2) expect(x.from.to_param).to eq(d5) expect(x.to.to_param).to eq(d10) end it 'returns the intersect of partially contained on the right' do interval1 = Martyr::Interval.new d10, d20 interval2 = Martyr::Interval.new d15, d25 x = interval1.intersect(interval2) expect(x.from.to_param).to eq(d15) expect(x.to.to_param).to eq(d20) end it 'returns the intersect of partially contained on the left' do interval1 = Martyr::Interval.new d10, d20 interval2 = Martyr::Interval.new d5, d15 x = interval1.intersect(interval2) expect(x.from.to_param).to eq(d10) expect(x.to.to_param).to eq(d15) end it 'returns the intersect of identical' do interval1 = Martyr::Interval.new d10, d20 interval2 = Martyr::Interval.new d10, d20 x = interval1.intersect(interval2) expect(x.from.to_param).to eq(d10) expect(x.to.to_param).to eq(d20) end it 'overrides closed with open' do interval1 = Martyr::Interval.new [d10], [d20] interval2 = Martyr::Interval.new d10, d20 x = interval1.intersect(interval2) expect(x.from.to_param).to eq(d10) expect(x.to.to_param).to eq(d20) end end end describe 'union' do context 'integers' do it 'returns nil when not touching' do interval1 = Martyr::Interval.new 1, 5 interval2 = Martyr::Interval.new 5, 10 expect(interval1.union(interval2)).to eq(nil) end it 'returns the union when overlapping on a point' do interval1 = Martyr::Interval.new 1, [5] interval2 = Martyr::Interval.new 5, 10 x = interval1.union(interval2) expect(x.from.to_param).to eq(1) expect(x.to.to_param).to eq(10) end it 'returns the union of fully contained' do interval1 = Martyr::Interval.new 1, 20 interval2 = Martyr::Interval.new 5, 10 x = interval1.union(interval2) expect(x.from.to_param).to eq(1) expect(x.to.to_param).to eq(20) end it 'returns the union of partially contained on the right' do interval1 = Martyr::Interval.new 10, 20 interval2 = Martyr::Interval.new 15, 25 x = interval1.union(interval2) expect(x.from.to_param).to eq(10) expect(x.to.to_param).to eq(25) end it 'returns the union of partially contained on the left' do interval1 = Martyr::Interval.new 10, 20 interval2 = Martyr::Interval.new 5, 15 x = interval1.union(interval2) expect(x.from.to_param).to eq(5) expect(x.to.to_param).to eq(20) end it 'returns the union of identical' do interval1 = Martyr::Interval.new 10, 20 interval2 = Martyr::Interval.new 10, 20 x = interval1.union(interval2) expect(x.from.to_param).to eq(10) expect(x.to.to_param).to eq(20) end it 'overrides open with closed' do interval1 = Martyr::Interval.new [10], [20] interval2 = Martyr::Interval.new 10, 20 x = interval1.union(interval2) expect(x.from.to_param).to eq([10]) expect(x.to.to_param).to eq([20]) end end context 'dates' do it 'returns nil when not touching' do interval1 = Martyr::Interval.new d1, d5 interval2 = Martyr::Interval.new d5, d10 expect(interval1.union(interval2)).to eq(nil) end it 'returns the union when overlapping on a point' do interval1 = Martyr::Interval.new d1, [d5] interval2 = Martyr::Interval.new d5, d10 x = interval1.union(interval2) expect(x.from.to_param).to eq(d1) expect(x.to.to_param).to eq(d10) end it 'returns the union of fully contained' do interval1 = Martyr::Interval.new d1, d20 interval2 = Martyr::Interval.new d5, d10 x = interval1.union(interval2) expect(x.from.to_param).to eq(d1) expect(x.to.to_param).to eq(d20) end it 'returns the union of partially contained on the right' do interval1 = Martyr::Interval.new d10, d20 interval2 = Martyr::Interval.new d15, d25 x = interval1.union(interval2) expect(x.from.to_param).to eq(d10) expect(x.to.to_param).to eq(d25) end it 'returns the union of partially contained on the left' do interval1 = Martyr::Interval.new d10, d20 interval2 = Martyr::Interval.new d5, d15 x = interval1.union(interval2) expect(x.from.to_param).to eq(d5) expect(x.to.to_param).to eq(d20) end it 'returns the union of identical' do interval1 = Martyr::Interval.new d10, d20 interval2 = Martyr::Interval.new d10, d20 x = interval1.union(interval2) expect(x.from.to_param).to eq(d10) expect(x.to.to_param).to eq(d20) end it 'overrides open with closed' do interval1 = Martyr::Interval.new [d10], [d20] interval2 = Martyr::Interval.new d10, d20 x = interval1.union(interval2) expect(x.from.to_param).to eq([d10]) expect(x.to.to_param).to eq([d20]) end end end end describe Martyr::IntervalSet do define_date_functions context 'integers' do describe 'add' do it 'does not join when adding non touching intervals' do set = Martyr::IntervalSet.new set.add from: 5, to: 20 set.add from: 20, to: 30 expect(set.set.length).to eq(2) expect(set.set.first.from.to_param).to eq(5) expect(set.set.first.to.to_param).to eq(20) expect(set.set.second.from.to_param).to eq(20) expect(set.set.second.to.to_param).to eq(30) end it 'joins when adding non touching intervals' do set = Martyr::IntervalSet.new set.add from: 5, to: 20 set.add from: [20], to: 30 expect(set.set.length).to eq(1) expect(set.set.first.from.to_param).to eq(5) expect(set.set.first.to.to_param).to eq(30) end it 'handles correctly complex case' do set = Martyr::IntervalSet.new set.add from: 100, to: 200 set.add from: 300, to: 400 set.add from: 500, to: 600 set.add from: 150, to: 350 expect(set.set.length).to eq(2) expect(set.set.first.from.to_param).to eq(100) expect(set.set.first.to.to_param).to eq(400) expect(set.set.second.from.to_param).to eq(500) expect(set.set.second.to.to_param).to eq(600) end it 'handles correctly partial intervals' do set = Martyr::IntervalSet.new set.add to: 200 set.add from: 300 set.add from: [200], to: [300] expect(set.set.length).to eq(1) expect(set.set.first.from.to_param).to eq(-Float::INFINITY) expect(set.set.first.to.to_param).to eq(Float::INFINITY) end end describe 'intersect' do it 'handles correctly identical sets with one element' do set1 = Martyr::IntervalSet.new set2 = Martyr::IntervalSet.new set1.add from: 5, to: 20 set2.add from: 5, to: 20 set3 = set1.intersect(set2) expect(set3.set.length).to eq(1) expect(set3.set.first.from.to_param).to eq(5) expect(set3.set.first.to.to_param).to eq(20) end it 'handles correctly identical sets with two element' do set1 = Martyr::IntervalSet.new set2 = Martyr::IntervalSet.new set1.add from: 5, to: 20 set1.add from: 20, to: 30 set2.add from: 5, to: 20 set2.add from: 20, to: 30 set3 = set1.intersect(set2) expect(set3.set.length).to eq(2) expect(set3.set.first.from.to_param).to eq(5) expect(set3.set.first.to.to_param).to eq(20) expect(set3.set.second.from.to_param).to eq(20) expect(set3.set.second.to.to_param).to eq(30) end it 'handles correctly complex case' do set1 = Martyr::IntervalSet.new set2 = Martyr::IntervalSet.new set1.add from: 10, to: 20 set1.add from: 30, to: 40 set2.add from: 15, to: 25 set2.add from: 45, to: 50 set3 = set1.intersect(set2) expect(set3.set.length).to eq(1) expect(set3.set.first.from.to_param).to eq(15) expect(set3.set.first.to.to_param).to eq(20) end it 'handles correctly partial intervals' do set1 = Martyr::IntervalSet.new set2 = Martyr::IntervalSet.new set1.add to: 100 set1.add from: 200 set2.add from: 0, to: 80 set2.add from: 90 set3 = set1.intersect(set2) expect(set3.set.length).to eq(3) expect(set3.set.first.from.to_param).to eq(0) expect(set3.set.first.to.to_param).to eq(80) expect(set3.set.second.from.to_param).to eq(90) expect(set3.set.second.to.to_param).to eq(100) expect(set3.set.third.from.to_param).to eq(200) expect(set3.set.third.to.to_param).to eq(Float::INFINITY) end end describe 'extract_and_fill_holes' do it 'does nothing when there are no holes' do set = Martyr::IntervalSet.new set.add(to: 100).add(from: 101) expect(set.extract_and_fill_holes).to eq([]) expect(set.set.length).to eq(2) expect(set.set.first.from.to_param).to eq(-Float::INFINITY) expect(set.set.first.to.to_param).to eq(100) expect(set.set.second.from.to_param).to eq(101) expect(set.set.second.to.to_param).to eq(Float::INFINITY) end it 'fills holes when they exist' do set = Martyr::IntervalSet.new.add(from: 0, to: 100).add(from: 200, to: 300) hole1 = Martyr::IntervalSet.new.add(to: 50).add(from: 50) hole2 = Martyr::IntervalSet.new.add(to: 250).add(from: 250) set.intersect(hole1).intersect(hole2) expect(set.extract_and_fill_holes).to eq([50, 250]) expect(set.set.length).to eq(2) expect(set.set.first.from.to_param).to eq(0) expect(set.set.first.to.to_param).to eq(100) expect(set.set.second.from.to_param).to eq(200) expect(set.set.second.to.to_param).to eq(300) end end describe 'extract_and_remove_points' do it 'does nothing when there are no points' do set = Martyr::IntervalSet.new set.add(to: 100).add(from: 101) expect(set.extract_and_remove_points).to eq([]) expect(set.set.length).to eq(2) expect(set.set.first.from.to_param).to eq(-Float::INFINITY) expect(set.set.first.to.to_param).to eq(100) expect(set.set.second.from.to_param).to eq(101) expect(set.set.second.to.to_param).to eq(Float::INFINITY) end it 'extract points when they exist' do set = Martyr::IntervalSet.new.add(from: [50], to: [50]).add(from: [100], to: [100]) expect(set.extract_and_remove_points).to eq([50, 100]) expect(set.set.length).to eq(0) end end end context 'dates' do describe 'add' do it 'does not join when adding non touching intervals' do set = Martyr::IntervalSet.new set.add from: d5, to: d20 set.add from: d20, to: d30 expect(set.set.length).to eq(2) expect(set.set.first.from.to_param).to eq(d5) expect(set.set.first.to.to_param).to eq(d20) expect(set.set.second.from.to_param).to eq(d20) expect(set.set.second.to.to_param).to eq(d30) end it 'joins when adding non touching intervals' do set = Martyr::IntervalSet.new set.add from: d5, to: d20 set.add from: [d20], to: d30 expect(set.set.length).to eq(1) expect(set.set.first.from.to_param).to eq(d5) expect(set.set.first.to.to_param).to eq(d30) end it 'handles correctly complex case' do set = Martyr::IntervalSet.new set.add from: d100, to: d200 set.add from: d300, to: d400 set.add from: d500, to: d600 set.add from: d150, to: d350 expect(set.set.length).to eq(2) expect(set.set.first.from.to_param).to eq(d100) expect(set.set.first.to.to_param).to eq(d400) expect(set.set.second.from.to_param).to eq(d500) expect(set.set.second.to.to_param).to eq(d600) end it 'handles correctly partial intervals' do set = Martyr::IntervalSet.new set.add to: d200 set.add from: d300 set.add from: [d200], to: [d300] expect(set.set.length).to eq(1) expect(set.set.first.from.to_param).to eq(-Float::INFINITY) expect(set.set.first.to.to_param).to eq(Float::INFINITY) end end describe 'intersect' do it 'handles correctly identical sets with one element' do set1 = Martyr::IntervalSet.new set2 = Martyr::IntervalSet.new set1.add from: d5, to: d20 set2.add from: d5, to: d20 set3 = set1.intersect(set2) expect(set3.set.length).to eq(1) expect(set3.set.first.from.to_param).to eq(d5) expect(set3.set.first.to.to_param).to eq(d20) end it 'handles correctly identical sets with two element' do set1 = Martyr::IntervalSet.new set2 = Martyr::IntervalSet.new set1.add from: d5, to: d20 set1.add from: d20, to: d30 set2.add from: d5, to: d20 set2.add from: d20, to: d30 set3 = set1.intersect(set2) expect(set3.set.length).to eq(2) expect(set3.set.first.from.to_param).to eq(d5) expect(set3.set.first.to.to_param).to eq(d20) expect(set3.set.second.from.to_param).to eq(d20) expect(set3.set.second.to.to_param).to eq(d30) end it 'handles correctly complex case' do set1 = Martyr::IntervalSet.new set2 = Martyr::IntervalSet.new set1.add from: d10, to: d20 set1.add from: d30, to: d40 set2.add from: d15, to: d25 set2.add from: d45, to: d50 set3 = set1.intersect(set2) expect(set3.set.length).to eq(1) expect(set3.set.first.from.to_param).to eq(d15) expect(set3.set.first.to.to_param).to eq(d20) end it 'handles correctly partial intervals' do set1 = Martyr::IntervalSet.new set2 = Martyr::IntervalSet.new set1.add to: d100 set1.add from: d200 set2.add from: d0, to: d80 set2.add from: d90 set3 = set1.intersect(set2) expect(set3.set.length).to eq(3) expect(set3.set.first.from.to_param).to eq(d0) expect(set3.set.first.to.to_param).to eq(d80) expect(set3.set.second.from.to_param).to eq(d90) expect(set3.set.second.to.to_param).to eq(d100) expect(set3.set.third.from.to_param).to eq(d200) expect(set3.set.third.to.to_param).to eq(Float::INFINITY) end end describe 'extract_and_fill_holes' do it 'does nothing when there are no holes' do set = Martyr::IntervalSet.new set.add(to: d100).add(from: d101) expect(set.extract_and_fill_holes).to eq([]) expect(set.set.length).to eq(2) expect(set.set.first.from.to_param).to eq(-Float::INFINITY) expect(set.set.first.to.to_param).to eq(d100) expect(set.set.second.from.to_param).to eq(d101) expect(set.set.second.to.to_param).to eq(Float::INFINITY) end it 'fills holes when they exist' do set = Martyr::IntervalSet.new.add(from: d0, to: d100).add(from: d200, to: d300) hole1 = Martyr::IntervalSet.new.add(to: d50).add(from: d50) hole2 = Martyr::IntervalSet.new.add(to: d250).add(from: d250) set.intersect(hole1).intersect(hole2) expect(set.extract_and_fill_holes).to eq([d50, d250]) expect(set.set.length).to eq(2) expect(set.set.first.from.to_param).to eq(d0) expect(set.set.first.to.to_param).to eq(d100) expect(set.set.second.from.to_param).to eq(d200) expect(set.set.second.to.to_param).to eq(d300) end end describe 'extract_and_remove_points' do it 'does nothing when there are no points' do set = Martyr::IntervalSet.new set.add(to: d100).add(from: d101) expect(set.extract_and_remove_points).to eq([]) expect(set.set.length).to eq(2) expect(set.set.first.from.to_param).to eq(-Float::INFINITY) expect(set.set.first.to.to_param).to eq(d100) expect(set.set.second.from.to_param).to eq(d101) expect(set.set.second.to.to_param).to eq(Float::INFINITY) end it 'extract points when they exist' do set = Martyr::IntervalSet.new.add(from: [d50], to: [d50]).add(from: [d100], to: [d100]) expect(set.extract_and_remove_points).to eq([d50, d100]) expect(set.set.length).to eq(0) end end end end
true
3ea059534f4324894de5f975c7fa3473476603b1
Ruby
sergiovasquez122/Programming-Languages-Coursera-Solutions
/week8/introduction_to_ruby.rb
UTF-8
588
3.78125
4
[]
no_license
# Pure object-oriented: all values are objects # Class-based: Every object has a class that determines behavior # - Like Java, unlike Javascript # - Mixins # Dynamically typed # Convenient reflection: Run-time inspection of objects # Very dynamic: Can change class during execution # Blocks and libaries encourages lots of closure idioms # syntax, scoping rules, semantics of a "scripting langage" # - Variable "sprint to life" on use # - Very flexible arrays # Scripting language class Hello def my_first_method puts "Hello, world!" end end x = Hello.new x.my_first_method
true
360637bae4d556bcf1892011fc30f3c3c585b60d
Ruby
laneb/classical_crypto
/lib/classical_crypto/cyphers/playfair.rb
UTF-8
1,797
3.34375
3
[]
no_license
require_relative "../utils.rb" require_relative "./cypher.rb" module ClassicalCrypto::Cyphers class Playfair < Cypher #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #~~Class: Playfair # #~~Description: Playfair is a subclass of Cypher which encrypts alphanumeric text #~~according to the algorithm of the Playfair cypher: https://en.wikipedia.org/wiki/Playfair_cipher #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ require_relative "playfair/playfair_key.rb" @key_type = PlayfairKey @plaintext_alphabet = "abcdefghijklmnopqrstuvwxyz" @cyphertext_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" protected def _encrypt_(ptext) filledPtext = insert_filler(ptext) ctext = ClassicalCrypto::Utils::Text.substitute(filledPtext, 2) {|pair| key.table.sub_pair(pair)} ctext end def _decrypt_(ctext) ptext = ClassicalCrypto::Utils::Text.substitute(ctext, 2) {|pair| key.table.backsub_pair(pair)} ptext end private #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #~~Method: insert_filler(ptext) #=> String # #~~Description: insert_filler returns the contents of ptext with a garbage character #~~inserted to split up consecutive identical letters and such that the returned #~~String is of even length. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def insert_filler(ptext) idx = 0 newPtext = String.new ptext until idx >= newPtext.length do if newPtext[idx] == newPtext[idx+1] then newPtext.insert idx+1, ClassicalCrypto::Utils::GARBAGE_CH end idx += 2 end unless newPtext.length % 2 == 0 newPtext << ClassicalCrypto::Utils::GARBAGE_CH end newPtext end end end
true
9dd6f6e75bf4ffb62f6892fe50f3c3b3b33a9477
Ruby
htachib/clerk
/lib/google_sheets.rb
UTF-8
2,498
2.671875
3
[]
no_license
class GoogleSheets require 'google/apis/sheets_v4' require 'googleauth' require 'googleauth/stores/file_token_store' require 'fileutils' APPLICATION_NAME = 'Google Sheets API Ruby Quickstart'.freeze OOB_URI = 'https://f256f093.ngrok.io/oauth2callback' # The file token.yaml stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. TOKEN_PATH = 'config/initializers/drive_auth_token.yaml'.freeze SCOPES = [ 'https://www.googleapis.com/auth/drive', 'https://spreadsheets.google.com/feeds/', 'https://www.googleapis.com/auth/spreadsheets.readonly' ].freeze ## # Ensure valid credentials, either by restoring from the saved credentials # files or intitiating an OAuth2 authorization. If authorization is required, # the user's default browser will be launched to approve the request. # def self.authorize # client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH) client_id = Google::Auth::ClientId.new(ENV['GOOGLE_DRIVE_APP_CLIENT_ID'], ENV['GOOGLE_DRIVE_APP_CLIENT_SECRET']) token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH) authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPES, token_store) user_id = 'default' # credentials = authorizer.get_credentials(user_id) credentials = nil # force recreation if credentials.nil? url = authorizer.get_authorization_url(base_url: OOB_URI) puts 'Open the following URL in the browser and enter the ' \ "resulting code after authorization:\n" + url code = gets credentials = authorizer.get_and_store_credentials_from_code( user_id: user_id, code: code, base_url: OOB_URI ) end credentials end # Initialize the API def self.client service = Google::Apis::SheetsV4::SheetsService.new service.client_options.application_name = APPLICATION_NAME service.authorization = authorize service end # Prints the names and majors of students in a sample spreadsheet: # https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit # client = GoogleSheets.client # spreadsheet_id = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms' # range = 'Class Data!A2:E' # response = client.get_spreadsheet_values(spreadsheet_id, range) # puts 'No data found.' if response.values.empty? # response.values.each do |row| # # Print columns A and E, which correspond to indices 0 and 4. # puts "#{row[0]}, #{row[4]}" # end end
true
dacb5891fe6ec0c1d34da48cc65a7bf29f277e76
Ruby
bmoises/project-euler
/lib/fibonacci.rb
UTF-8
504
3.671875
4
[]
no_license
class Fibonacci attr_accessor :continue, :current, :n1, :n2 def initialize @continue = true @current, @n1, @n2 = 0, 0, 0 end def each while true break if !@continue if @current >= 2 @current = @n2 + n1 @n1 = @n2 @n2 = @current elsif @current == 0 @n1 = 1 @current = 1 elsif @current == 1 @n2 = 2 @current = 2 end yield @current end end def done @continue = false end end
true
e4af222975b9a06c3ff812602400c07632fb9165
Ruby
mstolbov/rocket_model
/lib/rocket_model/store/file.rb
UTF-8
1,479
2.71875
3
[ "MIT" ]
permissive
require "pstore" module RocketModel module Store class File < PStore def self.new(path:) super(path) end def initialize(path) super @table = {} fetch_all end def all(table:) @table[table] || [] end def create(data, table:) @table[table] ||= [] data["id"] = increment_sequence(table) @table[table] << data data end def read(data, table:) @table[table].select do |record| record.values_at(*data.keys) == data.values end end def update(id, data, table:) record = @table[table].select do |record| record["id"] == id end.first record.update data end def delete(id, table:) @table[table].delete_if do |record| record["id"] == id end end def persist table = @table #copy for available in transaction transaction do table.each do |root, value| self[root] = value end end end private def sequence(root) @table["#{root}_sequence"] ||= @table[root].count end def increment_sequence(root) @table["#{root}_sequence"] = sequence(root) + 1 end def fetch_all transaction(true) do roots.each do |root| @table[root] = fetch(root) end end end end end end
true
8a5a926e838cc18221ec912519a181eaa01939eb
Ruby
jfdimark/lesson02
/arrays.rb
UTF-8
517
4.5
4
[]
no_license
# 1. create an array with three different string values three_amigos = ["John", "Tom", "Bob"] # 2. add two new values to the Task #1 array in single expression puts three_amigos.unshift("Jason", "Jim") # 3. convert your name to an array, and display it, in a single expression puts ["Mark", "Walker"] # 4. remove and display the last value in the Task # 1 array, and discuss # with the instructor why both values added in Task # 2 may have been removed he_went = three_amigos.pop puts he_went
true
e87fea7eae732ac31b2bbce7487d894ca6f56a5f
Ruby
eatoncns/ttt_web
/lib/game_mode.rb
UTF-8
878
3.3125
3
[]
no_license
require 'ttt_core' require_relative 'web_player' class GameMode Computer = TttCore::Computer Human = WebPlayer attr_reader :player_one_type attr_reader :player_two_type attr_reader :board_dimension def initialize(params) board_dimension = params["board_dimension"].to_i @board_dimension = board_dimension >= 3 ? board_dimension : 3 mode = params["mode"] || "hvh" initialize_player_types(mode) end def initialize_player_types(mode) mode_first, mode_second = mode.split("v") @player_one_type = type_from_mode(mode_first) @player_two_type = type_from_mode(mode_second) end def type_from_mode(mode) if mode == "c" return Computer end Human end def computer_first? @player_one_type == Computer end def has_computer? @player_one_type == Computer || @player_two_type == Computer end end
true
36f676b1ef5f213271991c5065b6a8cde98df2dd
Ruby
hajoxx/simple-cdn-server
/lib/simple_cdn/server/ftp/driver.rb
UTF-8
1,866
2.84375
3
[ "MIT" ]
permissive
require 'fileutils' module SimpleCDN class Server::Ftp::Driver # Your driver's initialize method can be anything you need. Ftpd # does not create an instance of your driver. def initialize(base_dir) @base_dir = base_dir @access_dir = '/dev/null' end # Return true if the user should be allowed to log in. # @param user [String] # @param password [String] # @param account [String] # @return [Boolean] # # Depending upon the server's auth_level, some of these parameters # may be nil. A parameter with a nil value is not required for # authentication. Here are the parameters that are non-nil for # each auth_level: # * :user (user) # * :password (user, password) # * :account (user, password, account) def authenticate(user, password, account) @access = Access.find_by_identifier(user) if @access.password == password @access_dir = "#{@base_dir}/#{@access.identifier}/" return true end return false end # Return the file system to use for a user. # @param user [String] # @return A file system driver that quacks like {Ftpd::DiskFileSystem} def file_system(user) unless File.directory?(@access_dir) init_access end Ftpd::DiskFileSystem.new(@access_dir) end private def init_access FileUtils.mkdir_p(@access_dir) # create_files end # def create_file path, contents # full_path = File.expand_path(path, @access_dir) # FileUtils.mkdir_p File.dirname(full_path) # File.open(full_path, 'w') do |file| # file.write contents # end # end # # def create_files # create_file 'README', # "This file, and the directory it is in, will go away\n" # "When this example exits.\n" # end end end
true
58f7f51c3bc322d69ff52feef5c6be378b4183b6
Ruby
bryanduxbury/indicatinator
/crossover.rb
UTF-8
3,395
3.203125
3
[]
no_license
# scheme = [5, 4, 1, 0, 3, 2] require "rubygems" require "ruby-debug" schemes = [] def populate_schemes(alphabet, so_far, results, depth=0) if alphabet.empty? results << so_far return end for a in alphabet # this heuristic allows us to be sure we're never generating a pass-through # transposition instruction, since that would basically be the same as # ignoring that pin forever. next if a == depth populate_schemes(alphabet - [a], so_far.dup << a, results, depth+1) end end results = [] populate_schemes((0..9).to_a, [], schemes) puts "generated #{schemes.size} schemes" # # eliminate all shifted isotopes # for scheme in schemes # while scheme.first != 1 # scheme << scheme.shift # end # end # puts "eliminating rotated isotopes yields #{schemes.uniq.size} schemes" # exit # puts results.size # for i in 0..5 # for j in 0..5 # next if j == i # for k in 0..5 # next if [i, j].include?(k) # for l in 0..5 # next if [i, j, k].include?(l) # for m in 0..5 # next if [i, j, k, l].include?(m) # for n in 0..5 # next if [i, j, k, l, m].include?(n) # schemes << [i, j, k, l, m, n] # end # end # end # end # end # end # puts schemes.map{|x| x.inspect}.sort.join("\n") def strip_prime(s) s.gsub("'", "") end def terminating_condition(scheme, occ, nxt) if occ.include?(nxt) # puts "#{scheme}: after #{occ.size} steps, repeats on #{nxt}" return true end if occ.select{|x| (x[0] == nxt[0] && x[1] == nxt[1]) || (x[0] == nxt[1] && x[1] == nxt[0])}.size > 0 return true; end nxt_isotope = nxt.dup nxt_isotope[0], nxt_isotope[1], = nxt_isotope[1], nxt_isotope[0] if occ.include?(nxt_isotope) # puts "#{scheme}: after #{occ.size} steps, repeats on primary isotope of #{nxt}" return true end if strip_prime(nxt[0]) == strip_prime(nxt[1]) # puts "#{scheme}: after #{occ.size} steps, original and prime pin co-occur on #{nxt}" return true end if occ.size > 25 # puts "#{scheme}: after #{occ.size} steps, we've got no end in sight. cool??" return true end return false end def transform(v, scheme) vprime = [] for s in scheme vprime << v[s] end vprime end max_length_scheme = 0 best_schemes = [] for scheme in schemes occ = [["0", "1", "2", "3", "4", "0", "1", "2", "3", "4"]] while true cur = occ.last nxt = transform(cur, scheme) # puts "#{cur} => #{nxt}" if terminating_condition(scheme, occ, nxt) if occ.size > max_length_scheme best_schemes = [] max_length_scheme = occ.size end if occ.size == max_length_scheme best_schemes << scheme end break; end occ << nxt end end puts "found #{best_schemes.size} schemes with a max length of #{max_length_scheme}" schemes_with_inversions = [] min_inversions = 1000000 for scheme in best_schemes inversions = 0 scheme.each_with_index do |v, i| next if i == 0 if scheme[i] < scheme[i-1] inversions += 1 end end min_inversions = inversions if inversions < min_inversions # puts "#{scheme} features #{inversions} inversions" schemes_with_inversions << [scheme, inversions] end puts schemes_with_inversions.select{|x| x[1] == min_inversions}.map{|x| x[0]}.sort.map{|x| x.join("")}.join("\n")
true
eb973f50f48366ba9773e436d40bfd766b6e73a2
Ruby
WWCodeMID/ruby-taller
/metodos.rb
UTF-8
732
4.34375
4
[]
no_license
# Las funciones o métodos son bloques de código # Reutilizables. Pueden o no recibir parámetros. def hello print "Hello" end # Se pueden especificar parámetros opcionales. def hello_name(name = "You") print "Hello #{name}!" end # Los métodos tambien pueden procesar y # regresar valores o cadenas. def return_hello(name = "You") "Hello #{name}" end # Usando la sentencia RETURN se puede regresar # varios valores. def return_many_hellos sp = "Hola" en = "Hello" pr = "Olá" return sp, en, pr end # Se puede especificar que reciba muchos parámetros def multiple(*params) puts "Numero de parámetros recibidos: #{params.length}" params.each { |i| puts "Parametro: #{i}" } end multiple(1, 2, 3, "Hola")
true
810b9ff8ad71c23b1a51eb67663b52bc4b7cf46b
Ruby
Anna-Myzukina/Algorithms-Data-Structures
/Sets.rb
UTF-8
1,464
4.53125
5
[]
no_license
=begin Sets These are the important methods a Set supports: add(item) - Adds an item to the Set. delete(item) - Removes an item from the Set. include?(item) - Returns true if the item is in the Set, and false otherwise. Purpose of Sets The Set is useful when you want to check if items are in a collection but there's no specific order that you care about. For example, let's say you're given a raw list of numbers and need to find the numbers that appear more than once. What Algorithm could you use to find them? Solution Create a Set for holding the items. For each item, check if it's already in the Set. If it is, you've found a duplicate. Otherwise add the item to the Set. Standard Sets Ruby standard library has a class Set. Documentation: http://ruby-doc.org/stdlib/libdoc/set/rdoc/Set.html Challenge A duplicate is a number whose value appeared earlier in the list. Given a list of numbers, return an array with all the duplicates in the order that they appear. (Duplicates that appear multiple times should be printed multiple times). Use Ruby's Set class to solve the challenge. =end require 'set' def find_duplicates(array) # write your code here result = Set.new arr = [] array.each do |i| if result.include?(i) ? arr << i : result.add(i) end end arr end p find_duplicates([1, 2, 3, 1, 5, 6, 7, 8, 5, 2]) # => [1, 5, 2] p find_duplicates([3, 501, 17, 23, -43, 67, 5, 888, -402, 235, 77, 99, 311, 1, -43]) # => [-43]
true
9c682d82998e7d64ba26dfa24c726244218d1fb0
Ruby
maxmartinm/Max.Martin.maxmartinm
/d2/bouncer.rb
UTF-8
199
3.953125
4
[]
no_license
puts "Hello!" puts "What's your age?" age = gets.strip.to_i if age >= 50 puts "You're too old" elsif age >= 21 puts "You're old enough! Come on in!" else puts "Sorry. You're too young." end
true
a8d88e29fb5df4271f1d46e30bb2dfe9fada8343
Ruby
oleglr/forecast
/senti/topic3/news_bow3.rb
UTF-8
3,980
2.515625
3
[]
no_license
#!/bin/env ruby # coding:utf-8 require "natto" require "json" require "sqlite3" class MakeBOW def initialize @dr="../../../data/data/news" #@docs=Hash.new # key:doc, value:vector ,word count #@keys=Hash.new # key:word , value:docs vector index @natto = Natto::MeCab.new @files=[] @db=SQLite3::Database.new("../../../data/news_topic3.db") @db2=SQLite3::Database.new("../../../data/news_topic3.db") @db3=SQLite3::Database.new("../../../data/news_topic3.db") #@db.execute("delete from news_bow") @db.execute("delete from news_tf") @db.execute("delete from news_idf") @db.execute("delete from news_tfidf") end def exec # make_file("/201601*/*/*") # make_file("/201602*/*/*") # make_file("/201603*/*/*") # make_file("/201604*/*/*") # make_file("/201605*/*/*") #make_file("/201606*/*/*") #exec_all tfidf_all end def make_file(path) Dir.glob(@dr+path).each do |file| @files.push(file) end end def exec_all @files.each do |file| p file open(file) do |io| json=JSON.load(io) doc=json["href"] #http://headlines.yahoo.co.jp/hl?a=20160511-00050080-yom-peo doc.gsub!(/^.*\?a=/,"") #p doc lines=json["body"].split("。") lines.each do |line| @natto.parse(line) do |n| word=n.feature.split(',')[6] word=n.surface if word=="*" hinshi=n.feature.split(',')[0] bunrui=n.feature.split(',')[1] next if hinshi!="名詞" next if hinshi=="名詞" and (bunrui!="一般" and bunrui!="固有名詞") next if word.length<=1 next if word =~ /^[0-9a-zA-Z@_\-%=]+$/ analyze(word,doc) end end end end end def analyze(word,doc) cursor=@db.execute("select count from news_bow where doc=? and word=?",[doc,word]) cnt=0 cursor.each do |tuple| cnt=tuple[0] end p "insert into news_bow :doc="+doc+",word="+word+",cnt="+cnt.to_s @db.execute("delete from news_bow where doc=? and word=?",[doc,word]) @db.execute("insert into news_bow values(?,?,?)",[doc,word,cnt+1]) end def tfidf_all docs=Array.new cur=@db.execute("select distinct doc from news_bow") cur.each do |tuple| doc=tuple[0] cur2=@db2.execute("select sum(count) from news_bow where doc=?",[doc]) count_sum=0 cur2.each do |tuple2| count_sum=tuple2[0] end cur2=@db2.execute("select word,count from news_bow where doc=?",[doc]) cur2.each do |tuple2| word=tuple2[0] count=tuple2[1] tf=count.to_f/count_sum.to_f p "insert into news_tf :doc="+doc+",word="+word+",tf="+tf.to_s @db3.execute("insert into news_tf values(?,?,?)",[doc,word,tf]) end end doc_sum=0 cur=@db.execute("select count(distinct(doc)) from news_bow") cur.each do |tuple| doc_sum=tuple[0] end cur=@db.execute("select distinct word from news_bow") cur.each do |tuple| word=tuple[0] cur2=@db2.execute("select count(distinct(doc)) from news_bow where word=?",[word]) count=0 cur2.each do |tuple2| count=tuple2[0] end idf=Math.log(doc_sum.to_f/count.to_f) p "insert into news_idf :word="+word+",idf="+idf.to_s @db2.execute("insert into news_idf values (?,?)",[word,idf]) end cur=@db.execute("select doc,word,tf from news_tf") cur.each do |tuple| doc=tuple[0] word=tuple[1] tf=tuple[2] cur2=@db2.execute("select idf from news_idf where word=?",[word]) idf=0 cur2.each do |tuple| idf=tuple[0] end tfidf=tf*idf p "insert into news_tfidf :doc="+doc+",word="+word+",tfidf="+tfidf.to_s @db2.execute("insert into news_tfidf values (?,?,?)",[doc,word,tfidf]) end end end if __FILE__ == $0 then MakeBOW.new.exec #MakeBOW.new.analyze("キーワード","あたいです") end
true
82c1bc81783a7903da3b3b66356b350f237bd5d6
Ruby
todb-r7/junkdrawer
/wallet-info.rb
UTF-8
698
2.859375
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby # Just goofing around with simplistic data gathering given a BitCoin # wallet... module BitCoin class Wallet ADDRESS_REGEX = /\x04name\x22[13][A-Za-z0-9]{26,33}/ attr_reader :addresses def initialize(fname="./wallet.dat") @data = File.open(fname, "rb") {|f| f.read f.stat.size} extract_addresses return self end def to_s "#<#{self.class.to_s}:#{self.object_id}>" end def extract_addresses @addresses ||= @data.scan(ADDRESS_REGEX).map {|x| x[6,34]} end def blockchain_urls url_prefix = "https://www.biteasy.com/blockchain/addresses/" @addresses.map {|x| url_prefix + x} end end end
true
55a0851c58f5faff31edcad3b09a8b3278b92703
Ruby
uchennafokoye/ruby_algorithms
/lib/ruby_algorithms/graph_algorithms/dfs.rb
UTF-8
1,494
3.203125
3
[ "MIT" ]
permissive
module GraphAlgorithms class DFS def initialize graph, start validate_graph graph validate_vertex_exists graph, start dfs(graph, start) end def path_to v recursive_path_to v end private attr_reader :state, :discovered, :finished, :parent, :counter # Also repeated in bfs def recursive_path_to v, path=[] unless v.nil? parent = @parent[v] recursive_path_to parent, path unless parent.nil? path << v end end end def dfs (graph, start) vertices = graph.vertices @state = Hash.new @parent = Hash.new @discovered = Hash.new @finished = Hash.new @counter = 0 vertices.each do |vertex| state[vertex] = "undiscovered" parent[vertex] = nil end recursive_dfs graph, start end def recursive_dfs graph, u state[u] = "discovered" discovered[u] = counter @counter += 1 adj = graph.adj u adj.each do |v| if state[v] == "undiscovered" parent[v] = u recursive_dfs graph, v end end state[u] = "processed" finished[u] = counter @counter += 1 end def validate_graph g unless g.is_a? Graph raise "Please provide a Graph" end end def validate_vertex_exists graph, vertex unless graph.has_vertex? vertex raise "Provided vertex not in graph" end end end end
true
173aa849bb4c581a60264ab9346f8d3d0f115831
Ruby
breycarr/poker_scoring
/spec/card_spec.rb
UTF-8
415
2.71875
3
[]
no_license
require 'card' describe Card do let(:subject) { Card.new("2S") } it "has a suit" do expect(subject.suit).to eq("S") end it "has a rank" do expect(subject.rank).to eq("2") end it "can treat the rank as a value" do expect(subject.value).to eq(2) end it "can provide a face card with a value" do expect(Card.new("TS").value).to eq(10) end end
true
944eb07aba4c616e6feb834bb6a3bba54b4d44b7
Ruby
katebee/gems-and-snakes
/spec/fruit_machine_spec.rb
UTF-8
2,974
3.4375
3
[]
no_license
require_relative '../fruit-machine/fruit_machine' require 'rspec' describe Player do it 'should initialize' do player = Player.new(100) expect(player.wallet_fund).to eq 100 expect(player.play_credit).to eq 0 end end describe Machine do it 'should initialize' do machine = Machine.new(2222, 50) expect(machine.machine_bank).to eq 2222 expect(machine.play_cost).to eq 50 end it 'can run a game' do machine = Machine.new(2222, 50) expect { machine.run }.to output.to_stdout end it 'can roll four random slots' do machine = Machine.new(2222, 50) expect(machine.roll_slots.length).to eq(4) end it 'can check if all slots are unique' do machine = Machine.new(2222, 50) expect(machine.unique_set_win?(['black', 'white', 'green', 'yellow']) ).to be true expect(machine.unique_set_win?(['white', 'white', 'green', 'yellow']) ).to be false end context 'with a jackpot win condition' do it 'can calculate the jackpot when the bank is even' do machine = Machine.new(2222, 50) result = ['black', 'white', 'green', 'yellow'] expect(machine.unique_set_win?(result)).to be true expect(machine.determine_prize(result)).to eq 1111 expect(machine.machine_bank).to eq 1111 end it 'can calculate the jackpot when the bank is odd' do machine = Machine.new(1111, 50) result = ['black', 'white', 'green', 'yellow'] expect(machine.unique_set_win?(result)).to be true expect(machine.determine_prize(result)).to be 555 expect(machine.machine_bank).to eq 556 end end context 'with an adjacent win condition' do it 'can check if two adjacent slots match' do machine = Machine.new(2222, 50) expect(machine.adjacent_win?(['black', 'white', 'green', 'yellow']) ).to be false expect(machine.adjacent_win?(['yellow', 'white', 'green', 'white']) ).to be false expect(machine.adjacent_win?(['white', 'green', 'green', 'yellow']) ).to be true expect(machine.adjacent_win?(['green', 'yellow', 'white', 'white']) ).to be true end end context 'winning with a low machine bank' do it 'will credit free plays' do machine = Machine.new(110, 50) result = ['green', 'yellow', 'white', 'white'] expect(machine.adjacent_win?(result)).to be true expect(machine.determine_prize(result)).to eq 110 expect(machine.machine_bank).to eq 0 expect(machine.play_credit).to eq 2 end end context 'with a losing combination' do it 'will not fufill a win condition or give a prize' do machine = Machine.new(2222, 50) result = ['black', 'green', 'black', 'green'] expect(machine.unique_set_win?(result)).to be false expect(machine.adjacent_win?(result)).to be false expect(machine.determine_prize(result)).to eq 0 expect(machine.machine_bank).to eq 2222 end end end
true
0e574519444f36e6b36a2cfe80bd34d76bbda5e5
Ruby
thejapanexperience/code-wars-ruby
/7kyuBeginnerSeries#3SumOfNumbers.rb
UTF-8
199
3.4375
3
[]
no_license
def get_sum(_a, _b) return _a unless _a != _b ans = 0 if _a < _b (_a.._b).each { |num| ans += num } else (_b.._a).each { |num| ans += num } end puts ans ans end get_sum(5, -1)
true
524b470eabb8d8e221b730c996f2b1c193d73eee
Ruby
geelen/box
/app/definitions.rb
UTF-8
1,255
2.546875
3
[]
no_license
require "rubygems" require "term/ansicolor" include Term::ANSIColor $command_line_options = Hash[*ENV.keys.grep(/^with_(.+)/) { |param| [$1.to_sym,ENV[param]] }.flatten] $working_dir = $command_line_options[:dir] || Dir.pwd def run cmd, desc, *colours print bold, blue, "#{desc}:", reset, "\n" colours.each { |c| print c } IO.popen(cmd) { |f| f.each { |line| if block_given? yield line else puts " " + line end } } puts reset end def files Dir[File.join(content_dir, "**", "*.markdown")].delete_if { |f| f =~ /!intro.markdown$/ } end def filenames files.map { |f| File.basename(f, ".*") } end def html_files files.map { |f| File.join($working_dir, 'out', 'html', f.gsub(content_dir + '/','').gsub(/\//,'_').gsub(/\.markdown$/,'.html')) } end def content_dir File.join($working_dir, "content") end def intro_file File.join(content_dir, '!intro.markdown') end def header_file File.join(content_dir, '!header.html') end def footer_file File.join(content_dir, '!footer.html') end def out_html_dir File.join($working_dir, 'out', 'html') end def all_file File.join(out_html_dir, 'all.html') end #files.zip(html_files).each { |m,h| # file h => [m] do # pandoc(m,h) # end #}
true
eb627ebcad9cff8c152a15e5789298b19ad20f2b
Ruby
Julppu/ruby-tehtava17
/debugattava.rb
UTF-8
144
2.53125
3
[]
no_license
module Debugattava def tila self.instance_variables.each do |var| puts "#{var} #{self.instance_variable_get var}" end end end
true
48a12d328c5f4cb8117cf74c7c5ea4ce0b243f03
Ruby
bingo8670/ruby-programming-2.3
/9.3.point.rb
UTF-8
570
3.984375
4
[]
no_license
class Point attr_accessor :x, :y def initialize(x=0, y=0) @x, @y = x, y end def [](index) case index when 0 x when 1 y else raise ArgumentError, "out of range `#{index}`" end end def []=(index, val) case index when 0 self.x = val when 1 self.y = val else raise ArgumentError, "out of range `#{index}`" end end end point = Point.new(3, 6) p point[0] # => 3 p point[1] = 2 # => 2 p point[1] # => 2 p point[2] # => 错误(ArgumentError)
true
202035873b137b2cb5582e6f4ed8744384400a2a
Ruby
jd1386/importer
/pt/slice-meta.rb
UTF-8
4,217
3.34375
3
[]
no_license
require "csv" require "awesome_print" ### # # # ### def format_date(raw, month) year = raw.split(" ").last result = "01/#{month}/#{year}" return result end def format_pub_date(raw) if raw.include? "janeiro" month = "01" result = format_date(raw, month) elsif raw.include? "fevereiro" month = "02" result = format_date(raw, month) elsif raw.include? "março" # March month = "03" result = format_date(raw, month) elsif raw.include? "abril" # April month = "04" result = format_date(raw, month) elsif raw.include? "maio" # May month = "05" result = format_date(raw, month) elsif raw.include? "junho" # June month = "06" result = format_date(raw, month) elsif raw.include? "julho" # July month = "07" result = format_date(raw, month) elsif raw.include? "agosto" # August month = "08" result = format_date(raw, month) elsif raw.include? "setembro" # September month = "09" result = format_date(raw, month) elsif raw.include? "outubro" # October month = "10" result = format_date(raw, month) elsif raw.include? "novembro" # November month = "11" result = format_date(raw, month) elsif raw.include? "dezembro" # December month = "12" result = format_date(raw, month) else result = raw end return result end def reformat_pub_date(formatted_date) day = formatted_date.split("/")[0] month = formatted_date.split("/")[1] year = formatted_date.split("/")[2] return "#{year}-#{month}-#{day}" end # Read source file and clean up each line meta_all = [] File.readlines('/Users/jungdolee/projects/importer/data/to_hash_source.txt', encoding: 'UTF-8').each do |line| ## Pre-process new_line = line.gsub("Autor ", " || Author=> ") new_line = new_line.gsub("Ilustração ", " || Illustrator=> ") new_line = new_line.gsub("Tradução ", " || Translator=> ") new_line = new_line.gsub("Editor ", " || Publisher=> ") new_line = new_line.gsub("Data de lançamento ", " || Pub_date=> ") new_line = new_line.gsub("Nº Coleção ", " || Edition=> ") new_line = new_line.gsub("Coleção ", " || Collection=> ") new_line = new_line.gsub("ISBN ", " || ISBN=> ") new_line = new_line.gsub("EAN ", " || EAN=> ") new_line = new_line.gsub("Marca ", " || Brand=> ") new_line = new_line.gsub("Dimensões ", " || Dimension=> ") new_line = new_line.gsub("Nº Páginas ", " || Pages=> ") new_line = new_line.gsub("Encadernação ", " || Binding=> ") new_line = new_line.gsub("Peso ", " || Weight=> ") new_line = new_line.gsub("Idade Recomendada ", " || Age_group=> ") new_line = new_line.gsub("Conteúdo Inclui ", " || Including=> ") ## Process # Split each line with a delimiter and make it an array splitted_line = new_line.split(" || ") # Drop empty line to clean up. splitted_line.reject! { |i| i.empty? } book_array = [] hash = Hash.new # After splitted, make a hash with key-value pairs with corresponding values splitted_line.each do |e| key = e.split("=> ").first value = e.split("=> ").last.chomp('').rstrip hash[key] = value end # Try to convert/clean each value if needed. hash["Pub_date"] = format_pub_date(hash["Pub_date"]) unless hash["Pub_date"].nil? hash["Pub_date"] = reformat_pub_date(hash["Pub_date"]) unless hash["Pub_date"].nil? # Save the hash to a book_array book_array << hash ap hash meta_all << book_array end # Print the results puts "\nSuccess! Converted #{ meta_all.size } lines" ## Save meta_all to CSV file CSV.open("/Users/jungdolee/projects/importer/data/to_hash_results.csv", "w") do |csv| # Write header csv << [ "Author", "Illustrator", "Translator", "Publisher", "Pub_date", "Collection", "ISBN", "Edition", "Dimension", "Pages", "Binding", "Weight", "Age_group", "Including" ] # Write rows i = 0 (0...meta_all.length).each do csv << meta_all[i][0].values_at( "Author", "Illustrator", "Translator", "Publisher", "Pub_date", "Collection", "ISBN", "Edition", "Dimension", "Pages", "Binding", "Weight", "Age_group", "Including" ) i += 1 end end # Print the results puts "Success! Saved the results to data/to_hash_results.csv"
true
fb1b588a00daf92ea735126618f91af2d1fe9ee9
Ruby
Galaxylaughing/hotel
/lib/hotel.rb
UTF-8
4,397
2.90625
3
[]
no_license
module HotelBooking class AlreadyReservedError < StandardError; end class NonexistentIdError < StandardError; end class Hotel attr_reader :room_count, :price_per_night, :max_rooms_per_block, :blocks attr_accessor :block_factory, :daterange_factory, :reservation_total def initialize(room_count:, price_per_night:, max_rooms_per_block: nil) @room_count = room_count @price_per_night = price_per_night @max_rooms_per_block = max_rooms_per_block @daterange_factory = DateRangeFactory.new() @block_factory = BlockFactory.new() @reservation_total = 0 @blocks = [] @blocks << load_default_block(Array(1..room_count)) end def load_default_block(room_numbers) return block_factory.make_block(id: 0, room_numbers: room_numbers, price_per_night: price_per_night) end def find_block_by_id(block_id) blocks.each do |hotel_block| if hotel_block.id == block_id return hotel_block end end raise NonexistentIdError.new("No block found with the number #{block_id}") end def find_reservations_by_date(date) default_block = get_default_block() overlapping_reservations = default_block.find_reservations_by_date(date) return overlapping_reservations end def get_default_block() return blocks[0] end def create_block(room_numbers:, price_per_night:, start_date:, end_date:) if room_numbers.length > max_rooms_per_block raise ArgumentError.new("Expected a maximum of #{max_rooms_per_block} rooms, received #{room_numbers.length} rooms") end dates = daterange_factory.make_daterange(start_date: start_date, end_date: end_date) blocks.each do |hotel_block| next if (hotel_block.id == get_default_block().id) if hotel_block.dates.overlaps?(dates) room_list = hotel_block.list_rooms() room_numbers.each do |room_number| if room_list.include?(room_number) raise ArgumentError.new("Block #{hotel_block.id} already contains room #{room_number} during this time") end end end end block_id = blocks.length new_block = block_factory.make_block(id: block_id, room_numbers: room_numbers, start_date: start_date, end_date: end_date, price_per_night: price_per_night, room_source: get_default_block) blocks << new_block return new_block end def list_rooms() source = get_default_block() return source.list_rooms() end def reserve_room(block_id: nil, room_number: nil, start_date:, end_date:) if block_id.nil? block = get_default_block() else block = find_block_by_id(block_id) end self.reservation_total += 1 reservation_number = reservation_total dates = daterange_factory.make_daterange(start_date: start_date, end_date: end_date) blocks.each do |hotel_block| if (block_id.nil? || block_id != hotel_block.id) && (hotel_block.id != get_default_block().id) # does the block contain that room? # does the block exist over these dates? if hotel_block.find_room(room_number) && dates.overlaps?(hotel_block.dates) raise AlreadyReservedError.new("Room #{room_number} is in block #{hotel_block.id} during these dates") end end end block.reserve_room(reservation_id: reservation_number, room_number: room_number, start_date: start_date, end_date: end_date) return reservation_number end def find_available_rooms(block_id: nil, start_date: nil, end_date: nil) if block_id block = find_block_by_id(block_id) available_rooms = block.all_available_rooms() elsif start_date && end_date available_rooms = get_default_block().all_available_rooms(start_date: start_date, end_date: end_date) else raise ArgumentError.new("Either a block id or a date range must be provided") end return available_rooms end def find_price_of_reservation(reservation_id) default_block = get_default_block() return default_block.find_price_of_reservation(reservation_id) end end end
true
f9d96c8f0515e1bbe81c24acb3bce0b8748c98db
Ruby
jetrockets/activerecord-update_counters_with_values
/lib/active_record/update_counters_with_values/class_methods.rb
UTF-8
672
2.640625
3
[ "MIT" ]
permissive
require 'active_record/update_counters_with_values/query_builder' module ActiveRecord module UpdateCountersWithValues module ClassMethods def update_counters_and_return_values(id, counters) query = ActiveRecord::UpdateCountersWithValues::QueryBuilder.new(self).call(id, counters) connection.execute(query, "#{name.to_s} Update Counters: #{counters}").to_a end def increment_counter_and_return_value(id, counter) update_counters_and_return_values(id, counter => 1) end def decrement_counter_and_return_value(id, counter) update_counters_and_return_values(id, counter => -1) end end end end
true
270f4182f9f5d460c1a117ff19d3a66d04270b8d
Ruby
pmichaeljones/tealeaf-week1
/OrangeTree.rb
UTF-8
1,101
3.59375
4
[]
no_license
class OrangeTree attr_accessor :height, :age def initialize() @orange_count = 0 @height = 0 #these are inches @age = 0 end def count_the_orange end def pick_an_orange @oranges = @oranges -= 1 end def many_years_pass(years) years.times do one_year_passes end end def one_year_passes @oranges = 0 @age =+ @age + 1 unless @age > 10 @oranges = 0 else @oranges = @oranges + @age * (rand(4)+1) end growth = ((rand(3)+1) * rand(5)) @height = @height + growth #these are inches if @height >= 12 @height_feet = @height / 12 @height_inches = @height % 12 else @height_feet = 0 @height_inches = @height end puts "Our orange tree is now #{age} years old, has #{@oranges} oranges and #{@height_feet} feet and #{@height_inches} inches tall." if growth == 0 puts "No growth this year. Blame it on the drought." end end def tree_stats puts "The tree is currently #{height} inches tall, #{age} years old, and has #{count_the_orange} orange." end end
true
3906da55d30a502630bf6534fa46702b75eca54f
Ruby
lbirts/Coderbyte-Interview-Prep
/array_intersection.rb
UTF-8
186
2.96875
3
[]
no_license
def FindIntersection(strArr) res = (strArr[0].split(",").map(&:to_i) & strArr[1].split(",").map(&:to_i)).join(",").delete(" ") if res.empty? return false end return res end
true
3b67780cc01322ffc378204b6199600a906d0003
Ruby
mbarrerar/code
/app/services/space_service/ownership_checker.rb
UTF-8
244
2.515625
3
[]
no_license
module SpaceService module OwnershipChecker OwnershipError = Class.new(StandardError) def check_ownership! unless space.owner?(current_user) raise(OwnershipError, "User is not Space Owner") end end end end
true
dfbc9e30d473b8c08e9889d66de5e67176622a18
Ruby
peter-james-allen/bank-tech-test
/lib/transaction.rb
UTF-8
441
3.171875
3
[]
no_license
# frozen_string_literal: true # Transaction class - stores information about a transaction class Transaction attr_reader :date, :credit, :debit, :start_balance, :end_balance def initialize(amount, start_balance) @credit = nil @debit = nil amount.negative? ? @debit = -amount : @credit = amount @start_balance = start_balance @end_balance = start_balance + amount @date = Time.now.strftime('%d/%m/%Y') end end
true
0c1978e4c008a92b0602b9b2d535cb69befcba03
Ruby
verg/jet_fuel
/jet_fuel.rb
UTF-8
616
2.640625
3
[]
no_license
require 'sinatra' require './jet_fuel/persisted_uri' require './jet_fuel/uri_shortener' class JetFuel < Sinatra::Base get '/' do uris = PersistedURI.all erb :index , locals: { uris: uris } end post '/' do short_urn = URIShortener.new.shorten(params["uri_to_shorten"]) PersistedURI.new(short_urn: short_urn, long_uri: params["uri_to_shorten"]).save redirect '/' end # Shortened URNs begin with a digit, followed by random url safe chars get %r{/(\d+\w*)} do |short_urn| uri = PersistedURI.find_by_urn(short_urn) uri.increment_click_count redirect uri.long_uri end end
true
723ac1d821f5e0821bf1da3bd54cd87a140834c0
Ruby
bfl3tch/afternoon_zoo_2105
/lib/animal.rb
UTF-8
253
3.53125
4
[]
no_license
class Animal attr_reader :kind, :weight, :age, :age_in_days def initialize(kind, weight, age) @kind = kind @weight = weight @age = "#{age} weeks" @age_in_days = age * 7 end def feed!(amount) @weight += amount end end
true
5fc84577fac7f9397f3785fddb0ada0e449dbc0f
Ruby
jichen3000/colin-ruby
/metaprogramming_in_ruby/methods/roulette_method_missing.rb
UTF-8
532
3.390625
3
[]
no_license
class Roulette def method_missing(name, *args) person = name.to_s.capitalize number = 1 3.times do number = rand(10) + 1 puts "#{number}..." end "#{person} got a #{number}" end end if __FILE__ == $0 require 'minitest/autorun' require 'minitest/spec' require 'testhelper' describe "some" do it "function" do number_of = Roulette.new puts number_of.colin puts number_of.li end end end
true
024c8b627eac3d133d3d1d037a4648e9692bd9ee
Ruby
rubylogicgems/prawn-graph
/lib/prawn/graph/extension.rb
UTF-8
1,229
2.65625
3
[ "MIT" ]
permissive
module Prawn module Graph module Extension # Plots one or more Prawn::Graph::Series on a chart. Expects an array-like object of # Prawn::Graph::Series objects and some options for positioning the sizing the # rendered graph # # @param series [Array] of Prawn::Graph::Series objects # @param options [Hash] of options, which can be: # `:width` - The overall width of the graph to be drawn. `<Integer>` # `:height` - The overall height of the graph to be drawn. `<Integer>` # `:at` - The point from where the graph will be drawn. `[<Integer>x, <Integer>y]` # `:title` - The title for this chart. Must be a string. `<String>` # `:series_key` - Should we render the key to series in this chart? `<Boolean>` # `:theme ` - An instance of the theme to be used for styling this graph. `<Prawn::Graph::Theme>` # def graph(series, options = {}, &block) canvas = Prawn::Graph::ChartComponents::Canvas.new(series, self, options, &block) canvas.draw {warnings: [], width: self.bounds.width, height: self.bounds.height} end alias chart graph end end end
true
b351f6d06c8781057acc600ceff8daa09f77a458
Ruby
webgago/xml_schema_mapper
/lib/xml_schema_mapper/builder.rb
UTF-8
4,186
2.515625
3
[ "MIT" ]
permissive
class NoToXmlError < NoMethodError end module XmlSchemaMapper class Builder attr_reader :document, :parent, :namespace_resolver def initialize(source, parent, namespace_resolver) @parent = parent.is_a?(Nokogiri::XML::Document) ? parent.root : parent @document = parent.document @source = source @klass = source.class @namespace_resolver = namespace_resolver @schema = @klass._schema end def elements @klass.type.elements.values.map { |e| XmlSchemaMapper::Element.new e } end def build elements.each do |element| add_element_namespace_to_root!(element) node = create_node(element) parent << node if can_add?(element, node) if node.is_a?(Nokogiri::XML::NodeSet) node.each { |n| n.namespace = nil if element.namespace.nil? } else node.namespace = nil if element.namespace.nil? end end self end def can_add?(element, node) node.is_a?(Nokogiri::XML::NodeSet) || node.content.present? end private attr_reader :source, :schema def create_node(element) setup_namespace(element) do element.simple? ? simple_node(element) : complex_node(element) end end def setup_namespace(element) yield.tap do |node| case node when Nokogiri::XML::NodeSet node.each { |n| n.namespace = find_namespace_definition(element.namespace) } when NilClass else node.namespace = find_namespace_definition(element.namespace) end end end def simple_node(element) value = source.send(element.reader) if value.is_a? Array list = value.map do |i| document.create_element(element.name, i) end Nokogiri::XML::NodeSet.new(document, list) else document.create_element(element.name, element.content_from(source)) end end def complex_node(element) object = source.send(element.reader) complex_root_node = document.create_element(element.name) complex_children(complex_root_node, object) rescue NoToXmlError raise("object of #{source.class}##{element.reader} should respond to :to_xml") end def complex_children(complex_root_node, object) if object.is_a?(XmlSchemaMapper) complex_node_from_mapper(complex_root_node, object) else complex_node_from_xml(complex_root_node, object) end end def complex_node_from_xml(complex_root_node, object) return complex_root_node if object.nil? if object.is_a?(Array) list = object.map do |o| complex_node_item = complex_root_node.dup complex_children(complex_node_item, o) end Nokogiri::XML::NodeSet.new(complex_root_node.document, list) elsif object.respond_to?(:to_xml) complex_root_node << object.to_xml else raise NoToXmlError end end def complex_node_from_mapper(complex_root_node, object) XmlSchemaMapper::Builder.build(object, complex_root_node, namespace_resolver).parent end def add_element_namespace_to_root!(element) if element.namespace ns = find_namespace(element) raise "prefix for namespace #{element.namespace.inspect} not found. element: #{element.inspect}" unless ns document.root.add_namespace(ns.prefix, ns.href) end end def find_namespace(element) if namespace_resolver namespace_resolver.find_by_href(element.namespace) else schema.namespaces.find_by_href(element.namespace) end end def find_namespace_definition(href) document.root.namespace_definitions.find { |ns| ns.href == href } end # CLASS_METHODS def self.create_document(xtype) Nokogiri::XML::Document.new.tap do |doc| doc.root = doc.create_element(xtype.name.camelize(:lower)) end end def self.build(mapper, parent, namespace_resolver) XmlSchemaMapper::Builder.new(mapper, parent, namespace_resolver).build end end end
true
eeb5a9bbf60d0fb394fc31377d20ac28b3b9f215
Ruby
KatrinSi/100K
/Person.rb
UTF-8
1,950
3.859375
4
[]
no_license
load 'Car.rb' class Person attr_accessor "first_name", "last_name", "cars", "money", "shoes", "age", "country" def buy_car(any_car) if self.money >= any_car.price puts "Congratulations for buying #{any_car.name} #{any_car.model}!" self.money -= any_car.price puts "You have #{self.money} left" else puts "You don't have enough money." end end def donate (donation_money_integer) if self.money >= donation_money_integer puts "You donated successfully!" self.money = self.money - donation_money_integer else puts "You are a luser coz you don't have money at all." end end def beg () money = [1, 2, 5, 10, 20, 100] # rand function returns a random index for the array not number index = rand (money.length) # index = 2 puts "Somebody donated to you #{money [index]}" self.money = self.money + money [index] end end # car 1 car1 = Car.new car1.name = "Mercedes" car1.model = "GLE" car1.color = "black" car1.year = 2020 car1.maximum_speed = 200 car1.is_drivable = false car1.price = 150000 car1.VIN = "4Y1SL65848Z411439" # car 2 car2 = Car.new car2.name = "Ferrari" car2.model = "F50" car2.color = "red" car2.year = 2012 car2.maximum_speed = 300 car2.is_drivable = true car2.price = 30000000 car2.VIN = "4Y5SA57821Z411421" # person 1 person1 = Person.new person1.first_name = "Porosenok" person1.last_name = "Olaru" person1.cars = [] person1.money = 1000000 person1.shoes = "slippers" person1.age = 53 person1.country = "Azerbajan" person1.buy_car(car1) person1.buy_car(car2) person1.donate(100) person2 = Person.new person2.first_name = "Homeless" person2.money = 0 person2.beg() puts person2.money # if person has enough money # display "You donated successfully!" # substract donated money from wallet
true
17378f6ed36a2a1d486f9e3155b0f6dbd4a27353
Ruby
rsterenchak/bubble_sort
/bubble_sort.rb
UTF-8
754
4.1875
4
[]
no_license
# bubble_sort.rb unsorted_array = [4, 3, 78, 2, 0, 2] def bubble_sort(unsorted_array) sorted_array = [] index = 0 # START METHOD until unsorted_array == [] index = 0 while index < unsorted_array.length - 1 if unsorted_array[index] > unsorted_array[index + 1] temp = unsorted_array[index + 1] unsorted_array[index + 1] = unsorted_array[index] unsorted_array[index] = temp index += 1 else index += 1 end end sorted_array.push(unsorted_array[index]) unsorted_array.pop p unsorted_array p sorted_array end final_array = sorted_array.reverse puts "The following array is sorted #{final_array}" end # ENDS METHOD bubble_sort(unsorted_array)
true
cc3179353630a3f00ce665597bdec83c0d0eb490
Ruby
robertf0/100
/intro_programming_book/arrays/exercise7.rb
UTF-8
84
3.15625
3
[]
no_license
array_1 = [1, 2, 3, 4, 5] array_2 = array_1.map { |num| num + 2} p array_1 p array_2
true
f7beff81140bfae8ff7c6f5fe736cbe4c8c5f465
Ruby
AlexBrandt46/Ruby-Factorial-Finder
/factorial_finder.rb
UTF-8
250
3.6875
4
[]
no_license
puts "Give me the number you want to find the factorial of: " initialValue = gets.chomp.to_i i = initialValue finalValue = 1 while i >= 1 finalValue = finalValue * i i-- end puts "The result of the factorial is: #{finalValue}" response = gets.chomp
true
102d01c7c7f2e9001db7ed08df067f3651500155
Ruby
rickpeyton/project-euler-ruby
/problem_003.rb
UTF-8
303
3.890625
4
[]
no_license
# Largest prime factor # Problem 3 # The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143 ? require 'pry' prime_factors = [] number = 13195 i = 2 while i < (number / 2) prime_factors << i if number % i == 0 i += 1 end puts prime_factors
true
66c518c2e871553ee76a7a865c257424c94bd97e
Ruby
dougtebay/my-select-001-prework-web
/lib/my_select.rb
UTF-8
275
3.59375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def my_select(collection) if collection.length > 0 i = 0 new_collection = [] while i < collection.length new_collection << collection[i] if yield(collection[i]) i += 1 end new_collection else puts "This block should not run!" end end
true
3902164ced3e240e86d8b0df45d7bf345e317f4e
Ruby
dbetm/cp-history
/URI/Principiante/4_ProductoSimple.rb
UTF-8
138
3.09375
3
[]
no_license
# https://www.urionlinejudge.com.br/judge/es/problems/view/1004 a = gets.chomp.to_i b = gets.chomp.to_i res = a * b puts("PROD = #{res}")
true
8192319c78ce329b92ea61e4eb7144657d603d5b
Ruby
ZJUguquan/Leetcode
/Timus-acm/1222.rb
UTF-8
256
3.5625
4
[ "MIT" ]
permissive
# 1222 n = gets.chomp!.to_i if n ==1 res = 1 elsif n==2 res = 2 else if n % 3 == 0 res = 3**(n/3) elsif n % 3 == 2 c = (n-2) / 3 res = 3**(c)*2 else # n % 3 = 1 c = (n-4)/3 res = 3**(c) *4 end end puts res
true
ef6a188f05971414db4bb7485b74129f8fb36a79
Ruby
Zeynab-j/ruby-enumerables-cartoon-collections-lab-part-1-nyc04-seng-ft-053120
/cartoon_collections.rb
UTF-8
580
3.75
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def greet_characters(array) # Use `each` to enumerate over the provided array # # Print a custom greeting for each element characters_array = ["Dopey", "Grumpy", "Bashful"] characters_array.each do |characters_array| puts "Hello #{characters_array}!" end def list_dwarves(array) # Use `each_with_index` to enumerate over the provided array # # Print a numbered list of each element dwarves_array = ["Dopey", "Grumpy", "Bashful"] dwarves_array.each_with_index {|element, index| indexplusone = index + 1 puts " 1.#{indexplusone} #{element}" } end end
true
276344aa6b962818439d1144e04df2cd6c8818c8
Ruby
plasmatic1/Advent-of-Code-2019
/2019/d1t2.rb
UTF-8
222
3.453125
3
[]
no_license
require_relative '../funs.rb' require 'scanf' f = rin(2019, 1) def fuel x req = x.div(3) - 2 if req <= 0 return 0 end req + fuel(req) end ans = f.split("\n").map { |x| fuel x.to_i }.sum puts ans
true
289d06abae52dd5f4589e037164171593457a2c0
Ruby
JM3DWorks/Custodia
/test/models/entry_test.rb
UTF-8
2,017
2.53125
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'test_helper' class EntryTest < ActiveSupport::TestCase def setup @equipment = Equipment.new(name: 'Unit 59', description: 'Chevrolet Silverado 2008', serial: '1GCEK19098Z148759', purchase_date: '2012-10-25') @equipment.save @entry = @equipment.entries.build(date: '2013-03-30', content: 'Back shocks replaced, oil changed.', mileage: 197_000, employee: 'Thomas') end test 'should be valid' do assert @entry.valid? end test 'equipment id should be present' do @entry.equipment_id = nil assert_not @entry.valid? end test 'date should be present' do @entry.date = ' ' assert_not @entry.valid? end test 'date should be valid' do @entry.date = '2022-333-2' assert_not @entry.valid? end test 'content should be present' do @entry.content = ' ' assert_not @entry.valid? end test 'content should not be too long' do @entry.content = 'w' * 2001 assert_not @entry.valid? end test 'deprecated mileage should be valid if present' do @entry.mileage = -1 assert_not @entry.valid? @entry.mileage = 'a' assert_not @entry.valid? end test 'primary hours should be valid if present' do @entry.primary_hours = 100.0 assert @entry.valid? @entry.primary_hours = 'abc' assert_not @entry.valid? @entry.primary_hours = -1 assert_not @entry.valid? end test 'secondary hours should be valid if present' do @entry.primary_hours = 100.0 assert @entry.valid? @entry.primary_hours = 'abc' assert_not @entry.valid? @entry.primary_hours = -1 assert_not @entry.valid? end test 'employee should be present' do @entry.employee = ' ' assert_not @entry.valid? end test 'order should be newest first' do assert_equal entries(:red), Entry.first end test 'employee should exist' do # TODO: Test this once linked to employee database end end
true
46517fd0cd8df3ee52b4658d504ef48d0afeb937
Ruby
srycyk/templet
/lib/templet/renderers/erb.rb
UTF-8
1,891
2.671875
3
[ "MIT" ]
permissive
require 'erb' require 'ostruct' module Templet module Renderers # For rendering a supplied block within an ERb template class ERb attr_accessor :context, :proto_template # template_path can be a local ERb file, template string, or DATA append # # locals are local variables for the ERb template alone def initialize(proto_template=nil, **locals) self.proto_template = proto_template self.context = OpenStruct.new(**locals) end # The return value from the block in substituted in <%= yield %> def call(&block) context_binding = context.instance_eval { ::Kernel.binding } erb.result context_binding, &block end # Shortcut to instance method def self.call(template=nil, **locals, &block) new(template, **locals).(&block) end private def erb @erb ||= ERB.new get_template end def get_template if proto_template if proto_template =~ /(<%)|(\s\s)|(\n)/m proto_template else IO.read proto_template end else template or '' end end def template(read_from=false) if read_from call_stack = caller read_erb(call_stack) or read_end(call_stack) end end def read_erb(call_stack) path = erb_path(call_stack) IO.read(path) if File.file?(path) end def erb_path(call_stack) source_path(call_stack, 0).sub(/\.rb$/, '.erb') end def read_end(call_stack) if defined? DATA DATA.read else path = source_path(call_stack, 0) IO.read(path).split(/\s__END__\s/, 2)&.last end end def source_path(call_stack, index) call_stack[index].split(":").first end end end end
true
fccc3af0346b2751987722051fb37629f064f9bd
Ruby
bctechnologies/dare0a-ruby
/test/test.rb
UTF-8
400
2.71875
3
[]
no_license
require 'minitest/autorun' class AssignmentTest < Minitest::Test def test_greet require 'assignment' person = Person.new('Mary') greet = person.greet('John') assert_equal 'Hi John, my name is Mary', greet person = Person.new('Paul') greet = person.greet('Lisa') assert_equal 'Hi Lisa, my name is Paul', greet rescue flunk 'Assignment not fixed yet' end end
true
91937c34017c3bd0ccaf01ed4b03ebc46f57a126
Ruby
Johra444/tests-ruby
/lib/01_temperature.rb
UTF-8
201
3.6875
4
[]
no_license
def ftoc(fahrenheit_degrees) celsius = (fahrenheit_degrees.to_i - 32) * 5.0/ 9.0 celsius.round end def ctof(celsius_degrees) fahrenheit = (celsius_degrees.to_i * 9.0/ 5.0) + 32 end
true
17411457782939b2c6bd50207d14cee4d7d53787
Ruby
rda1902/ruby_forking_tutorial
/basic_fork.rb
UTF-8
139
2.75
3
[]
no_license
# basic_fork.rb # A fork inherits the terminal of its parent process fork do sleep 2 puts "Fork: finished" end puts "Main: finished"
true
3c817e796c115f8124769e12bf43e26d245faf8f
Ruby
ChristinaLeuci/Ruby
/ErbAndHaml.rb
UTF-8
5,357
3.71875
4
[]
no_license
The default templating language is Embedded Ruby(ERB) In ERB we have three main markup elements: HTML and text use no markers and appear plainly on the page <%= and %> wrap Ruby code whose return value will be output in place of the marker. <% and %> wrap Ruby code whose return value will NOT be output. <%- and %> wrap Ruby code whose return value will NOT be output and no blank lines will be generated. ERB works with any text format, it outputs javascript, html, etc. ERB doesn’t know anything about the surrounding text. It just injects printing or non-printing Ruby fragments into plaintext. Enter HAML It encourages stringent formatting of your view templates, lightens the content significantly, and draws clear lines between markup and code. a white-space templating engine In a typical template we’d have plain HTML like this: <h1>All Articles</h1> Using whitespace to reflect the nested structure, we could reformat it like this: <h1> All Articles </h1> And, if we assume that whitespace is significant, the close tag would become unnecessary here. The parser could know that the H1 ends when there’s an element at the same indentation level as the opening H1 tag. Cut the closing tag and we have: <h1> All Articles The H1 tag itself is heave with both open and close brackets. Leaving just <h1 as the HTML marker could have worked, but Hampton decided that HTML elements would be created with % like this: %h1 All Articles Lastly, when an HTML element just has one line of content, we will conventionally put it on a single line: %h1 All Articles The % followed by the tag name will output any HTML tag. The content of that tag can be on the same line or indented on the following lines. Note that content can’t both be inline with the tag and on the following lines. Outputting Ruby in HAML ERB method: <p class='flash'><%= flash[:notice] %></p> Given what you’ve seen from the H1, you would imagine the <p></p> becomes %p. But what about the Ruby injection? Ruby Injections HAML’s approach is to reduce <%= %> to just =. The HAML engine assumes that if the content starts with an =, that the entire rest of the line is Ruby. For example, the flash paragraph above would be rewritten like this: %p= flash[:notice] Note that the = must be flush against the %p tag. Adding a CSS Class But what about the class? There are two options. The verbose syntax uses a hash-like format: %p{class: 'flash'}= flash[:notice] But we can also use a CSS-like shorthand syntax: %p.flash= flash[:notice] The latter is easier and more commonly used. Mixing Plain Text and Ruby Consider a chunk of content that has both plain text and Ruby like this: <div id="sidebar"> Filter by Tag: <%= tag_links(Tag.all) %> </div> Given what we’ve seen so far, you might imagine it goes like this: %div#sidebar Filter by Tag: = tag_links(Tag.all) But HAML won’t recognize the Ruby code there. Since the element’s content starts with plain text, it will assume the whole line is plain text. Breaking Ruby and Text into Separate Lines One solution in HAML is to put the plain text and the Ruby on their own lines, each indented under the DIV: %div#sidebar Filter by Tag: = tag_links(Tag.all) Since version 3, HAML supports an interpolation syntax for mixing plain text and Ruby: %div#sidebar Filter by Tag: #{tag_links(Tag.all)} And it can be pushed back up to one line: %div#sidebar Filter by Tag: #{tag_links(Tag.all)} Implicit DIV Tags DIV is considered the "default" HTML tag. If you just use a CSS-style ID or Class with no explicit HTML element, HAML will assume a DIV: #sidebar Filter by Tag: #{tag_links(Tag.all)} Non-Printing Ruby We’ve seen plain text, HTML elements, and printing Ruby. Now let’s focus on non-printing Ruby. One of the most common uses of non-printing Ruby in a view template is iterating through a collection. In ERB we might have: <ul id='articles'> <% @articles.each do |article| %> <li><%= article.title %></li> <% end %> </ul> The second and fourth lines are non-printing because they omit the equals sign. HAML’s done away with the <%. So you might be tempted to write this: %ul#articles @articles.each do |article| %li= article.title Content with no marker is interpreted as plain text, so the @articles line will be output as plain text and the third line would cause a parse error. Marking Non-Printing Lines We need a new symbol to mark non-printing lines. In HAML these lines begin with a hyphen (-): %ul#articles - @articles.each do |article| %li= article.title The end Wait a minute, what about the end? HAML uses that significant whitespace to reduce the syntax of HTML and Ruby. The end for the do is not only unnecessary, it will raise an exception if you try to use it! Review The key ideas of HAML include: Whitespace is significant, indent using two spaces HTML elements are created with % and the tag name, ex: %p HTML elements can specify a CSS class (%p.my_class) or ID (%p#my_id) using a short-hand syntax Content starting with an = is interpreted as printing Ruby, ex: %p= article.title Content starting with a - is interpreted as non-printing Ruby, ex: - @articles.each do |article| Content can contain interpolation-style injections like %p Articles Available:#{@articles.count}
true
e8a26691752997499a98bff56238b147b3fbd004
Ruby
emiellohr/paynl-rb
/lib/paynl/transaction_status.rb
UTF-8
871
2.6875
3
[]
no_license
module Paynl class TransactionStatus CHARGEBACK = %w(-70 -71) PAID_CHECKAMOUNT = %w(-51) EXPIRED = %w(-80) REFUND_PENDING = %w(-72) REFUND = %w(-81) PARTIAL_REFUND = %w(-82) PENDING = %w(20 25 50 60 70 75 80 85 90) OPEN = %w(60) CONFIRMED = %w(75 76) PARTIAL_PAYMENT = %w(80) VERIFY = %w(85) PAID = %w(100) CANCEL = %w(-60 -63 -90) def initialize(status) @status = status.to_s end def success? PAID.include?(@status) end def cancelled? CANCEL.include?(@status) end def expired? EXPIRED.include?(@status) end def failure? CANCEL.include?(@status) end def pending? # added 80 & 85 to pending. PENDING.include?(@status) end end end
true
e2aabdddae3a03b65bddbf0e0c703c36dd681ef2
Ruby
kaledoux/ruby_small_problems
/Easy4/short_long_short.rb
UTF-8
1,834
4.84375
5
[]
no_license
# Write a method that takes two strings as arguments, # determines the longest of the two strings, and then returns the result of # concatenating the shorter string, the longer string, and the shorter string # once again. You may assume that the strings are of different lengths. # # Examples: # # short_long_short('abc', 'defgh') == "abcdefghabc" # short_long_short('abcde', 'fgh') == "fghabcdefgh" # short_long_short('', 'xyz') == "xyz" # # PEDAC: # Understand the Problem: # > Input: # - Two strings # > Output: # - One string, combination of two arguments # > Requirements: # - program needs to evaluate which input string is longer # - method needs to create a new string, short + long + short # > Rules: # - input strings will be uneven lengths # - case insensitive # - input strings will not contain spaces or symbols # # Examples: # short_long_short('abc', 'defgh') == "abcdefghabc" # short_long_short('abcde', 'fgh') == "fghabcdefgh" # short_long_short('', 'xyz') == "xyz" # # Data Structures: # The starting data structure will be the arguments in the form of strings. # The comparison of these strings' lengths can be determined without changing this # structure. The return string will also be in string form. # # Algorithm: # > Pseudo: # DEFINE method short_long_short with arguments ( string1, string2) # FIND the length of string1 # FIND the length of string2 # COMPARE lengths # IF string1.length > string2.length # RETURN string1 + string2 + string1 # ELSE # RETURN string2 + string1 + string2 # END # END method def # Code with Intent: def short_long_short(string1, string2) string1.length > string2.length ? (string2 + string1 + string2) : (string1 + string2 + string1) end p short_long_short('abc', 'defgh') p short_long_short('abcde', 'fgh') p short_long_short('', 'xyz')
true
fbae708fd007d37ce0c61a94875aa1dca5f17320
Ruby
michaeljevans/battleship
/test/cell_test.rb
UTF-8
1,598
3.140625
3
[]
no_license
require 'minitest/autorun' require 'minitest/pride' require './lib/ship' require './lib/cell' class Celltest < MiniTest::Test def test_it_exists cell = Cell.new("B4") assert_instance_of Cell, cell end def test_it_has_readable_attributes cell = Cell.new("B4") assert_equal "B4", cell.coordinate assert_nil cell.ship end def test_it_is_empty? cell = Cell.new("B4") assert_equal true, cell.empty? end def test_it_places_ship cruiser = Ship.new("Cruiser", 3) cell = Cell.new("B4") assert_equal true, cell.empty? cell.place_ship(cruiser) assert_equal false, cell.empty? end def test_it_is_fired_upon? cruiser = Ship.new("Cruiser", 3) cell = Cell.new("B4") cell.place_ship(cruiser) assert_equal false, cell.fired_upon? cell.fire_upon assert_equal true, cell.fired_upon? end def test_it_can_fire cruiser = Ship.new("Cruiser", 3) cell = Cell.new("B4") cell.place_ship(cruiser) assert_equal 2, cell.fire_upon assert_equal true, cell.fired_upon? end def test_it_renders_correctly cell1 = Cell.new("B4") assert_equal ".", cell1.render cell1.fire_upon assert_equal "M", cell1.render cell2 = Cell.new("C3") cruiser = Ship.new("Cruiser", 3) cell2.place_ship(cruiser) assert_equal ".", cell2.render assert_equal "S", cell2.render(true) cell2.fire_upon assert_equal "H", cell2.render assert_equal false, cruiser.sunk? cruiser.hit cruiser.hit assert_equal true, cruiser.sunk? assert_equal "X", cell2.render end end
true
e0d13804517ffaf2bc5739990408b68a6ba50791
Ruby
rameshsutaliya/RubyOnRails
/Source/Ch01/readingFromFile.rb
UTF-8
233
3.453125
3
[]
no_license
=begin Write a ruby program which reads the username from a text file and print the user name on the screen. =end def read_from_file username = File.read("username.txt") print "User name is :#{username}\n" end read_from_file()
true
f2c46e4faa45f75943af18886d307c3b404c8ddf
Ruby
abdelrauof97/breaking_news_cli_gem
/lib/data.rb
UTF-8
441
2.96875
3
[ "MIT" ]
permissive
require "colorize" class Data def self.get_data(url) Scraper.get_and_sort_data(url).reject{|x| x[:title] == ""} end def self.exposing_news(url) get_data(url).each.with_index(1) { |x,i| if i < 11 puts "" puts "#{i}. #{x[:title]}".colorize(:blue) puts "ptess the link to see the news: "+""+ x[:link].colorize(:red) puts "----------------".colorize(:light_blue) end } end end
true
ab9c2ea2a7b97b435d20767de8064babc4d2439e
Ruby
Narnach/fast_group_by
/spec/fast_group_by_spec.rb
UTF-8
314
2.609375
3
[ "MIT" ]
permissive
require File.join(File.dirname(__FILE__),%w[.. lib fast_group_by]) describe Array, '#fast_group_by' do it 'should return a Hash with key-Array pairs' do ary = (1..10).to_a groups = ary.fast_group_by {|e| e%2} groups.should == { 0 => [2, 4, 6, 8, 10], 1 => [1, 3, 5, 7, 9] } end end
true
0b3f042a398986c3e9797336f9db18116e7d66a9
Ruby
garciajordy/sales_tax_kata_advanced
/app/helpers/file_reader_helper.rb
UTF-8
573
2.71875
3
[]
no_license
module FileReaderHelper def file_reader(file) basket = current_user.baskets.create(name: file.original_filename.split('.').first) File.readlines(file).each do |line| line_item_constructor(line_constructor(line), basket.id) end basket end def line_constructor(line) { quantity: line[0].to_i, name: line.split(' at ')[0][2..], price: line.split(' at ')[1].to_f } end def line_item_constructor(hash, id) LineItem.create(quantity: hash[:quantity], name: hash[:name], price: hash[:price], basket_id: id) end end
true
111e07ec68cf6303dedd828d6bdf019bffebf269
Ruby
joan2kus/ChartDirector
/railsdemo/app/controllers/scatter_controller.rb
UTF-8
2,390
2.625
3
[ "IJG" ]
permissive
require("chartdirector") class ScatterController < ApplicationController def index() @title = "Scatter Chart" @ctrl_file = File.expand_path(__FILE__) @noOfCharts = 1 render :template => "templates/chartview" end # # Render and deliver the chart # def getchart() # The XY points for the scatter chart dataX0 = [10, 15, 6, 12, 14, 8, 13, 13, 16, 12, 10.5] dataY0 = [130, 150, 80, 110, 110, 105, 130, 115, 170, 125, 125] dataX1 = [6, 12, 4, 3.5, 7, 8, 9, 10, 12, 11, 8] dataY1 = [65, 80, 40, 45, 70, 80, 80, 90, 100, 105, 60] # Create a XYChart object of size 450 x 420 pixels c = ChartDirector::XYChart.new(450, 420) # Set the plotarea at (55, 65) and of size 350 x 300 pixels, with a light grey # border (0xc0c0c0). Turn on both horizontal and vertical grid lines with light # grey color (0xc0c0c0) c.setPlotArea(55, 65, 350, 300, -1, -1, 0xc0c0c0, 0xc0c0c0, -1) # Add a legend box at (50, 30) (top of the chart) with horizontal layout. Use 12 # pts Times Bold Italic font. Set the background and border color to Transparent. c.addLegend(50, 30, false, "timesbi.ttf", 12).setBackground( ChartDirector::Transparent) # Add a title to the chart using 18 pts Times Bold Itatic font. c.addTitle("Genetically Modified Predator", "timesbi.ttf", 18) # Add a title to the y axis using 12 pts Arial Bold Italic font c.yAxis().setTitle("Length (cm)", "arialbi.ttf", 12) # Add a title to the x axis using 12 pts Arial Bold Italic font c.xAxis().setTitle("Weight (kg)", "arialbi.ttf", 12) # Set the axes line width to 3 pixels c.xAxis().setWidth(3) c.yAxis().setWidth(3) # Add an orange (0xff9933) scatter chart layer, using 13 pixel diamonds as symbols c.addScatterLayer(dataX0, dataY0, "Genetically Engineered", ChartDirector::DiamondSymbol, 13, 0xff9933) # Add a green (0x33ff33) scatter chart layer, using 11 pixel triangles as symbols c.addScatterLayer(dataX1, dataY1, "Natural", ChartDirector::TriangleSymbol, 11, 0x33ff33) # Output the chart send_data(c.makeChart2(ChartDirector::PNG), :type => "image/png", :disposition => "inline") end end
true
6b19f2bb2511442c1b2c61c3afbafccaeb273b08
Ruby
TonyCWeng/Practice_Problems
/leetcode/ruby/add_two_numbers.rb
UTF-8
951
4.1875
4
[]
no_license
# leet code problem Add Two Numbers # You are given two non-empty linked lists representing two non-negative integers. # The digits are stored in reverse order and each of their nodes contain a single # digit. Add the two numbers and return it as a linked list. class ListNode attr_accessor :val, :next def initialize(val) @val = val @next = nil end end def add_two_numbers(l1, l2) sum1 = sum_link(l1) sum2 = sum_link(l2) total = sum1 + sum2 first_link = nil next_link = nil #convert the total to a string before adding its integers in reverse order total.to_s.chars.reverse.each do |el| if first_link.nil? first_link = ListNode.new(el.to_i) next_link = first_link else next_link.next = ListNode.new(el.to_i) next_link = next_link.next end end first_link end def sum_link(link) sum = "" while !link.nil? sum = link.val.to_s + sum link = link.next end sum.to_i end
true
07ce3cfa1f075c7ad6b5afee8bc919151fceb389
Ruby
danielpaul/ruby-tldr
/1. Variables.rb
UTF-8
293
3.84375
4
[]
no_license
puts 'Hello World!' greeting = 'Good morning!' puts greeting forecast = "sunny" # string temperature = 32 # number is_summer = true # boolean print "It's going to be #{forecast}, #{temperature} degrees outside today. " # output to the same line. print 'It\'s going to be a great day!'
true
dd348410551e44516adca5d28f84bcd5ab1c1e35
Ruby
fanjieqi/LeetCodeRuby
/701-800/707. Design Linked List.rb
UTF-8
1,730
4.125
4
[ "MIT" ]
permissive
class MyLinkedList =begin Initialize your data structure here. =end def initialize() @array = [] end =begin Get the value of the index-th node in the linked list. If the index is invalid, return -1. :type index: Integer :rtype: Integer =end def get(index) @array[index] || -1 end =begin Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. :type val: Integer :rtype: Void =end def add_at_head(val) @array.unshift(val) end =begin Append a node of value val to the last element of the linked list. :type val: Integer :rtype: Void =end def add_at_tail(val) @array << val end =begin Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. :type index: Integer :type val: Integer :rtype: Void =end def add_at_index(index, val) @array.insert(index, val) end =begin Delete the index-th node in the linked list, if the index is valid. :type index: Integer :rtype: Void =end def delete_at_index(index) @array.delete_at(index) end end # Your MyLinkedList object will be instantiated and called as such: # obj = MyLinkedList.new() # param_1 = obj.get(index) # obj.add_at_head(val) # obj.add_at_tail(val) # obj.add_at_index(index, val) # obj.delete_at_index(index)
true
e5887a0bbed33b228cf2e7ddf3df8610464989f1
Ruby
TheBitcoin/Prework
/Ruby Ironhack/data_types_in_ruby/data_types.rb
UTF-8
1,831
4.09375
4
[]
no_license
# #data_types # my_var = "This is a variable" # pelicula = "Torrente 3" # puts "My favourite movie is #{pelicula}" # name = "miGuel" # capitalized_name = name.capitalize # puts "hello #{capitalized_name}" # flavours = "chocolate, mint, strawberry, vanilla, caramel, chili" # flavours_array = flavours.split(",") # puts flavours_array # hola = "how many characters are in this string" # holacontado = hola.length # puts holacontado # puts 'how many characters are in this string'.length # puts 'awesome'.include? 'you' # puts 'awesome'.include? 'me' # phrase = 'Just kidding, you’re awesome too' # puts phrase.include? 'aw' # distancia_al_sol_en_km = 120_495_554_332_445_554 # puts "distancia en km del sol #{distancia_al_sol_en_km}" # age = 28 # puts "The age 28 is" # if age.odd? # puts " odd" # else # puts " even" # end # age = 344.779123 # puts age.round(-2) # puts age.round(4) # 10.times {puts "ola,"} # animals = [ "perro", "gato", "pato", "manso", "escorpión" ].sort # animals << "mariquita" # animals.push "conejo" # animals.delete_at 2 # puts animals # numbers = [1,4,2,5,6,10,9,3,11,12,15,16].join # puts numbers # numbers = [1,4,2,5,6,10,9,3,11,12,15,16].join(",") # puts numbers # numbers = [1,4,2,5,6,10,9,3,11,12,15,16] # puts numbers # my_hash = {} # my_hash["PUT"] = "Putuca" # my_hash['ZOR'] = "Zorrita" # puts my_hash["PUT"] # puts my_hash['ZOR'] # puts my_hash # puts "Siguiende ejercicio" my_hash = {} my_hash["AST"] = "Asturias" my_hash['GAL'] = "Galicia" puts my_hash.has_key?("AST") puts my_hash.has_key?("CAT") puts my_hash.has_value?("Galicia") puts "último ejercicio" puts my_hash.select { |key, value| key.include?("G") } # require 'pry' # total = 1+1 # binding.pry # puts "The result is #{total}" # "what is this?".class # 4.class # [1,2,3,4].class
true
04f8c3db895ee843874c9a0eb52295a54e9f2e01
Ruby
akchalasani1/myruby
/examples/ex21.rb
UTF-8
1,884
4.59375
5
[]
no_license
=begin Start from the inside and work out. Divide iq by 2. Multiply that by weight. Subtract that from height. Add that to age. In general, with nested parentheses, you always start from the innermost. The purpose of parentheses in this type of formula is to manage the order that the operations occur, Note: order of operations is PEMDAS (ex: please excuse my dear aunt sally) (standard order is multiplication and division,left to right, and then addition and subtraction, left to right). =end def add(a, b) puts "ADDING #{a} + #{b}" return a + b end def subtract( a, b) puts "SUBTRACTING #{a} - #{b}" return a - b end def multiply(a, b) puts "MULTIPLYING #{a} * #{b}" return a * b end def divide(a, b) puts "DIVIDING #{a} / #{b}" return a / b end puts "\nLet's do some math with just functions!" age = add(30, 5) height = subtract(78, 4) weight = multiply(90, 2) iq = divide(100, 2) puts "Age: #{age}, Height: #{height}, Weight: #{weight}, IQ: #{iq}" # A puzzle for the extra credit, type it in anyway puts "\nHere is the puzzle." # putting raw number's as per the study drill # what = 74 - 50 / 2 * 180 + 35 #what = (height - iq / 2 * weight + age) what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) puts "That becomes: #{what}. Can you do it by hand?" puts "\nmake your own assignment from the functions." # Finally, do the inverse. Write out a simple formula and use the functions in the same way to calculate it. test_this = add(2, 4) + subtract(200, 187) + multiply(height, weight) + divide(weight, age) # 6 + 13 + 13320 + 4 puts "looks like we get: #{test_this}" =begin puts "\nmodify the parts of the functions. Try to change it on purpose to make another value." age = add(38, 5) height = subtract(78, 4) weight = multiply(90, 2) iq = divide(180, 2) puts "Age: #{age}, Height: #{height}, Weight: #{weight}, IQ: #{iq}" =end
true
25c733311e925535926c5c0c73c519eb1d031bdb
Ruby
y-usuzumi/survive-the-course
/coursera/programming-languages/part-c/Week_1_Homework/hw6graphics.rb
UTF-8
2,189
3.359375
3
[ "BSD-3-Clause" ]
permissive
# University of Washington, Programming Languages, Homework 6, hw6graphics.rb # This file provides an interface to a wrapped Tk library. The auto-grader will # swap it out to use a different, non-Tk backend. require 'tk' class TetrisRoot def initialize @root = TkRoot.new('height' => 615, 'width' => 205, 'background' => 'lightblue') {title "Tetris"} end def bind(char, callback) @root.bind(char, callback) end # Necessary so we can unwrap before passing to Tk in some instances. # Student code MUST NOT CALL THIS. attr_reader :root end class TetrisTimer def initialize @timer = TkTimer.new end def stop @timer.stop end def start(delay, callback) @timer.start(delay, callback) end end class TetrisCanvas def initialize @canvas = TkCanvas.new('background' => 'grey') end def place(height, width, x, y) @canvas.place('height' => height, 'width' => width, 'x' => x, 'y' => y) end def unplace @canvas.unplace end def delete @canvas.delete end # Necessary so we can unwrap before passing to Tk in some instances. # Student code MUST NOT CALL THIS. attr_reader :canvas end class TetrisLabel def initialize(wrapped_root, &options) unwrapped_root = wrapped_root.root @label = TkLabel.new(unwrapped_root, &options) end def place(height, width, x, y) @label.place('height' => height, 'width' => width, 'x' => x, 'y' => y) end def text(str) @label.text(str) end end class TetrisButton def initialize(label, color) @button = TkButton.new do text label background color command (proc {yield}) end end def place(height, width, x, y) @button.place('height' => height, 'width' => width, 'x' => x, 'y' => y) end end class TetrisRect def initialize(wrapped_canvas, a, b, c, d, color) unwrapped_canvas = wrapped_canvas.canvas @rect = TkcRectangle.new(unwrapped_canvas, a, b, c, d, 'outline' => 'black', 'fill' => color) end def remove @rect.remove end def move(dx, dy) @rect.move(dx, dy) end end def mainLoop Tk.mainloop end def exitProgram Tk.exit end
true
003852429957e51daa6ff383fc0f97092e28d7b4
Ruby
robsdrops/Ship-ice-simulation
/Content/grid.rb
UTF-8
688
3.15625
3
[]
no_license
require_relative 'vector_and_point' class Grid attr_accessor :pointsArray, :horizontal_amount, :vertical_amount, :show, :size def initialize size @size = size @pointsArray = [] @show = false end def calculatePoints @pointsArray.clear if @pointsArray.any? x = 0 y = 0 @horizontal_amount = (800.0 / @size).ceil @vertical_amount = (600.0 / @size).ceil addAmountForOutWindowConnecting 1.upto horizontal_amount do |h| y = 0 1.upto vertical_amount do |v| point = Point.new(x, y) @pointsArray.push point y += @size end x += @size end end def addAmountForOutWindowConnecting @horizontal_amount += 1 @vertical_amount += 1 end end
true
0aedd6f79fd1ff45ad1e4ffbc0d6eb974e3cef32
Ruby
eva-barczykowska/Ruby
/Add_a_Key_Value_Pair_to_a_Hash.rb
UTF-8
255
3.734375
4
[]
no_license
p menu = {burger: 3.99, taco: 5.96, chips: 0.50} p menu[:sandwich] = 8.99 p menu menu[:taco] = 2.99 p menu[:taco] puts #another way - the STORE method #takes 2 arguments, key and value menu.store(:sushi, 7.99) p menu menu.store(:steak, 9.99) p menu
true
1caa0a10d45390174e9da2b9ad6518d07cb1ef60
Ruby
rioyi/the-well-rounded-rubyist
/chapter_2/ticket-information-request.rb
UTF-8
249
3.171875
3
[]
no_license
ticket = Object.new def ticket.venue "Town Hall" end def ticket.event "Author's reading" end print "Information desired: " request = gets.chomp if request == "venue" puts ticket.venue elsif request == "event" puts ticket.event end
true
92147699a0701f264bef2db01c2cc5788cd9e47c
Ruby
HurricaneJames/CWP
/app/models/game.rb
UTF-8
8,925
2.65625
3
[]
no_license
class Game < ActiveRecord::Base serialize :current_state, ApplicationHelper::JSONWithIndifferentAccess validate :current_state_must_include_board_and_pieces def board; current_state[:board]; end def board=(board); current_state[:board] = board; end def pieces; current_state[:pieces]; end def pieces=(pieces); current_state[:pieces] = pieces; end def current_state=(new_state); self[:current_state] = JSON.parse(new_state).with_indifferent_access; end def game_rules; @game_rules ||= GameRules.new; end def move(move_string) raise ArgumentError.new, "Move cannot be empty." if move_string.blank? return resolve_draw(move_string) if draw_syntax?(move_string) move_positions = move_string.present? ? move_string.split(':') : [] raise ArgumentError.new, "Did not describe move or used an invalid syntax." if move_positions.nil? || move_positions[0].blank? || move_positions[1].blank? from = [:x, :y].zip(move_positions[0].split(',').map {|i| i.to_i}).to_h to = [:x, :y].zip(move_positions[1].split(',').map {|i| i.to_i}).to_h dead_pieces = move_positions.fetch(2, nil) promotion = move_positions.fetch(3, nil) piece = piece_on_tile(from) # TODO - add test for this failing condition (causes a crash and it should not) return false if piece === :none promotion_rules = game_rules.promotions_for_move({ to: to, type: piece[:name] }) return false unless (promotion_rules.empty? || game_rules.can_promote?(piece, to, promotion)) return move_piece(from: from, to: to, with_dead_pieces: dead_pieces) && (promotion_rules.empty? || promote(piece, promotion)) end def move_piece(from:, to:, with_dead_pieces: nil) raise ArgumentError.new, "invlid move parameters" if (from.blank? || to.blank?) piece_id = id_piece_on_tile(from) return false unless is_legal?(piece_id: piece_id, to: to) dead_pieces = handle_collisions_of_attack(piece_id, to, with_dead_pieces) dead_piece_ids = dead_pieces.split(',') change_board_position(piece_id, from, to) unless dead_piece_ids.include?(piece_id) self.moves = moves.to_s + "#{from[:x]},#{from[:y]}:#{to[:x]},#{to[:y]}" + ":#{dead_pieces}" + win_lose_or_normal(dead_piece_ids, pieces[piece_id][:orientation]) + ';' return true end def promote(piece, new_type) unless pieces[piece[:id]][:state] == :dead pieces[piece[:id]][:name] = new_type.to_s self.moves = moves.to_s[0..-2] + ":#{new_type};" end return true end def move_requires_promotion?(from, to) piece = piece_on_tile(:from) return false if piece == :none promotion_rules = game_rules.promotions_for_move(self, { from: from, to: to, type: piece[:name] }) end def win_lose_or_normal(dead_piece_ids, attacking_piece_id) dead_kings = dead_piece_ids.select { |piece_id| pieces[piece_id][:name] == "king" } return "draw" if dead_kings.length > 1 dead_king = dead_kings.first return (pieces[dead_king][:orientation] == attacking_piece_id ? ":lost[#{attacking_piece_id}]" : ":won[#{attacking_piece_id}]") if dead_kings.length == 1 return '' end def change_board_position(piece_id=nil, from = nil, to) raise ArgumentError.new, "either piece_id or from must be valid" if (piece_id.blank? && from.blank?) raise ArgumentError.new, "must specify destination tile" if to.blank? from ||= get_tile_for_piece(piece_id) piece_id ||= id_piece_on_tile(from) from_id = tile_id_for(from[:x], from[:y]) to_id = tile_id_for(to[:x], to[:y]) board[to_id] = board.delete(from_id) pieces[piece_id][:state] = to_id end def handle_collisions_of_attack(piece_id, to, override_dead_pieces=nil) return override_dead_pieces unless override_dead_pieces.blank? dead_pieces = get_results_of_moving_piece(piece_id, to) collision_results = "" dead_pieces.each do |piece| kill_piece(piece[:id]) collision_results << piece[:id] + ',' end return collision_results[0...-1] end def kill_piece(piece_id) tile = get_tile_for_piece(piece_id) piece = remove_piece(x: tile[:x], y: tile[:y]) piece[:state] = :dead end # returns the set of pieces that lost (dead pieces) def get_results_of_moving_piece(piece_id, to) dead_pieces = [] rule = game_rules.legal_rule_for(game: self, move: "#{piece_id}:#{to[:x]},#{to[:y]}") collisions = rule.collisions(on: self, from: get_tile_for_piece(piece_id), to: to) collisions.each do |collision_at| if collision_at[:tile][:rule_properties][:rule].resolve_collision(collision_at) dead_pieces << piece_on_tile(collision_at[:tile]) else dead_pieces << pieces[piece_id] break end end return dead_pieces end def game_over? winner != 0 || moves.split(';').last == 'draw' end def winner match = moves.match(/.*:(won)\[(\d*)\];$/) || moves.match(/.*:(lost)\[(\d*)\];$/) return 0 if match.nil? return (match[1] == "won" ? 1 : -1) * match[2].to_i end def is_legal?(piece_id:, to:) !game_over? && !pending_draw_resolution? && can_move_piece_this_turn(piece_id) && game_rules.is_move_legal?(game: self, move: { id: piece_id, to: to }) end def can_move_piece_this_turn(piece_id) pieces[piece_id.to_s][:orientation] > 0 ? moves.split(';').length.even? : moves.split(';').length.odd? end def all_legal_moves_for_piece(id) return [] if game_over? || !can_move_piece_this_turn(id) game_rules.all_moves_for_piece(game: self, piece_id: id) end # position: { x: [x], y: [y] } def on_board?(position) position[:x] >= 0 && position[:x] <= 7 && position[:y] >= 0 && position[:y] <= 7 end # return the piece on the given tile # or :none, :off_board def piece_on_tile(tile) raise ArgumentError.new, "(#{tile}) is an invalid tile." if tile.blank? || tile[:x].nil? || tile[:y].nil? return :off_board unless on_board?(tile) piece_id = id_piece_on_tile(tile) pieces[piece_id].present? ? pieces[piece_id].merge({ id: piece_id }) : :none end def id_piece_on_tile(tile) tile_id = tile.is_a?(String) ? tile : tile_id_for(tile[:x], tile[:y]) return board[tile_id].to_s end def add_piece(name:, x:, y:, orientation: 1) new_id = pieces.length.to_s pieces[new_id] = { id: new_id, name: name, orientation: orientation, state: "#{x},#{y}" } board[tile_id_for(x, y)] = new_id end def remove_piece(x:, y:) piece_id = board.delete(tile_id_for(x, y)).to_s pieces[piece_id][:state] = '' return pieces[piece_id] end def add_rule(piece_type, rule); game_rules.add_rule(piece_type, rule); end def get_tile_for_piece(id) tile_string = tile_id_for_piece(id) return nil if tile_string.blank? tile = tile_string.split(',') return { x: tile[0].to_i, y: tile[1].to_i, orientation: pieces[id][:orientation] } end def pending_draw_resolution?; moves.split(';').last == "offer_draw"; end def mark(move); self.moves += "#{move};"; end private def draw_syntax?(string); ["offer_draw", "accept_draw", "reject_draw"].include?(string); end def resolve_draw(move) case move when 'offer_draw' return mark('draw') if should_grant_automatic_draw? return mark(move) unless pending_draw_resolution? when 'accept_draw' return mark("draw") if pending_draw_resolution? when 'reject_draw' return mark(move) if pending_draw_resolution? end return false end def should_grant_automatic_draw? move_set = moves.split(";").reject { |move| ["offer_draw", "reject_draw"].include? move } return false if move_set.length < 140 # 140/2 = 70 full moves (move_set.length-140..move_set.length-1).each do |i| return false unless move_set[i].split(':')[2].nil? end return true end def parse_move_string(move_string) move_array = move_string.split(':') { from: position_for(tile_id: move_array[0]), to: position_for(tile_id: move_array[1]) } end def tile_id_for(x, y); "#{x},#{y}"; end def position_for(tile_id:); [:x, :y].zip(tile_id.split(',').map { |o| o.to_i }).to_h; end # TODO - replace this with pieces[piece_id][:state] - because that is what state is supposed to represent def tile_id_for_piece(piece_id); board.detect { |tile, piece_id_on_tile| piece_id_on_tile == piece_id }.try(:first); end def current_state_must_include_board_and_pieces errors.add(:current_state, "must include the board") if board.nil? errors.add(:current_state, "must include pieces") if pieces.nil? end def translate_move(piece_id, to) # todo - add piece[:on_board] attribute to skip the check if this piece is currently dead/off-board piece_id = piece_id.to_s from = get_tile_for_piece(piece_id) { name: pieces[piece_id][:name], from: from, to: to } end end
true
f97d03cd9a91e5e31f187cbc170f79fdd92b47b2
Ruby
ml242/ruby-frequency-txt-url
/freq.rb
UTF-8
642
3.296875
3
[]
no_license
#open a url as if it's a standard file with a built in ruby library require 'open-uri' #This is Gutenberg's link to Hamlet link = 'http://www.gutenberg.org/cache/epub/2265/pg2265.txt' #read the link syntax file = File.read(open(link)) #create an array of the file with the words split on spaces words = file.to_s.split("\n").join('').split(' ') #create a new hash with the key set to key and the value set to 0 freq = Hash.new { |k,v| v = 0 } #increment a counter in the hash with the words +1 words.each { |word| freq[word] += 1 } #print out the results sorted in descending value for the "top ten" places p freq.sort_by { |k,v| -v }[0..9]
true
eb2e660114b5ca7b83426c687b162dcf9bd6424f
Ruby
kolyaventuri/module_3_diagnostic
/app/models/station.rb
UTF-8
837
2.921875
3
[]
no_license
class Station attr_reader :name, :address, :fuel_types, :distance, :access_times def initialize(opts) @name = opts[:name] @address = opts[:address] @fuel_types = opts[:fuel_types] @distance = opts[:distance] @access_times = opts[:access_times] @fuel_types.gsub!('ELEC', 'Electric') @fuel_types.gsub!('LGP', 'Propane') end def self.from_list(stations) stations.map do |station| new( name: station[:station_name], address: station[:street_address], fuel_types: station[:fuel_type_code], distance: station[:distance], access_times: station[:access_days_time] ) end end def self.get_nearest(params) response = NRELService::make_request('/alt-fuel-stations/v1/nearest.json', params) from_list(response[:fuel_stations]) end end
true
7acb6422cdae5fae5a8ec0fc8046de4dd08ae4b1
Ruby
multi-io/xml-mapping
/examples/xpath_usage.intin.rb
UTF-8
1,031
2.703125
3
[ "Apache-2.0" ]
permissive
#:invisible: $:.unshift "../lib" #<= #:visible: require 'xml/xxpath' d=REXML::Document.new <<EOS <foo> <bar> <baz key="work">Java</baz> <baz key="play">Ruby</baz> </bar> <bar> <baz key="ab">hello</baz> <baz key="play">scrabble</baz> <baz key="xy">goodbye</baz> </bar> <more> <baz key="play">poker</baz> </more> </foo> EOS ####read access path=XML::XXPath.new("/foo/bar[2]/baz") ## path.all(document) gives all elements matching path in document path.all(d)#<= ## loop over them path.each(d){|elt| puts elt.text}#<= ## the first of those path.first(d)#<= ## no match here (only three "baz" elements) path2=XML::XXPath.new("/foo/bar[2]/baz[4]") path2.all(d)#<= #:handle_exceptions: ## "first" raises XML::XXPathError in such cases... path2.first(d)#<= #:no_exceptions: ##...unless we allow nil returns path2.first(d,:allow_nil=>true)#<= ##attribute nodes can also be returned keysPath=XML::XXPath.new("/foo/*/*/@key") keysPath.all(d).map{|attr|attr.text}#<=
true
21240851d0292e2866a94688dc6d7b1b3207912b
Ruby
DouglasAllen/facebook_group_files
/misc/vsop87.rb
UTF-8
9,719
2.8125
3
[]
no_license
#!/usr/local/bin/ruby require 'date' require 'cgi' # doc class Clock attr_accessor :date, :year, :month, :time, :day, :hour, :min, :sec def initialize(date) @date = date.to_datetime.to_time.utc @time = @date date_parts(date) time_parts(date) end def time_in_day @hour.to_f / 24 + @min.to_f / 1140 + @sec.to_f / 86_400 end def time_in_hour @hour.to_f + @min.to_f / 60 + @sec.to_f / 3600 end def time_in_sec @hour * 3600 + @min * 60 + @sec end def date_parts(data) @year = data.year @month = data.month @day = data.day end def time_parts(data) @hour = data.hour @min = data.min @sec = data.sec end def the_variables(date) @date = date.to_datetime.to_time.utc @time = @date date_parts(date) time_parts(date) end =begin def jd if @month <= 2 y = (@year - 1).to_i m = (@month + 12).to_i else y = @year m = @month end julian_day = ( 365.25 * (y + 4716)).floor + (30.6001 * (m + 1)).floor + @day - 1524.5 if julian_day < 2_299_160.5 transition_offset = 0 else tmp = (@year / 100).floor transition_offset = 2 - tmp + (tmp / 4).floor end julian_day + transition_offset end =end end =begin # doc class SplitData def initialize(data) @data_array = [] @data = data end def split @data_array << @data[1..1].to_i # version @data_array << @data[2..2].to_i # body @data_array << @data[3..3].to_i # index @data_array << @data[4..4].to_i # alpha @data_array << @data[79..96].to_f # A @data_array << @data[97..110].to_f # B @data_array << @data[111..130].to_f # C @data_array end end # doc class VSOP87 def initialize(data_set, jd) @data_set = data_set @jd = jd end def load data_array = [] open(@data_set) do |file| while line = file.gets if line[1..1] != 'V' r = SplitData.new(line) data_array << r.split end end end data_array end def calc data_array = load t = ((@jd - 2_451_545.0) / 365_250).to_f v = [] data_array.each do |data| i = data[2] - 1 v[i] = 0 if v[i].nil? v[i] = v[i].to_f + ( t**data[3]) * data[4].to_f * Math.cos(data[5].to_f + data[6].to_f * t) end v end end # input = CGI.new data_set = input['f'] jd = input['d'] print "Content-type:text/plain\n\n" if data_set unless jd date = Time.now time = Clock.new(date) jd = time.jd end jd.to_f vsop = VSOP87.new(data_set, jd) puts "#{data_set} at JD#{jd}" v_array = vsop.calc i = 0 v_array.each do |v| puts "variable[#{i}] = #{v}" i += 1 end else f = open('vsop87.txt') description = f.read f.close print <<EOS ============ Planetary positions by VSOP87 theory ============ DESCRIPTION =========== Loading source files of VSOP87 and calculating positions of the planet at given julian day. USAGE ========= vsop87.rb?f=FILE_NAME(&d=JULIAN_DAY) if you omit param "d" you will get current position. REFERENCE ========= VI/81 Planetary Solutions VSOP87 (Bretagnon+, 1988) http://cdsarc.u-strasbg.fr/viz-bin/ftp-index?VI/81 Source Code ========= http://www.lizard-tail.com/isana/lab/astro_calc/vsop87/vsop87_rb.txt ### Here is the description of VSOP87 files. ### #{description} EOS end =end clock = Clock.new(DateTime.now.to_time.utc) puts clock.the_variables(clock.date) puts clock.date puts clock.date.year puts clock.date.month puts clock.date.day puts clock.date.to_datetime.jd puts clock.date.to_datetime.ajd.to_f puts clock.time puts clock.time.hour puts clock.time.min puts clock.time.sec =begin README.planetmath: Understanding Planetary Positions in KStars. copyright 2002 by Jason Harris and the KStars team. This document is licensed under the terms of the GNU Free Documentation License ------------------------------------------------------------------------------- 0. Introduction: Why are the calculations so complicated? We all learned in school that planets orbit the Sun on simple, beautiful elliptical orbits. It turns out this is only true to first order. It would be precisely true only if there was only one planet in the Solar System, and if both the Planet and the Sun were perfect point masses. In reality, each planet's orbit is constantly perturbed by the gravity of the other planets and moons. Since the distances to these other bodies change in a complex way, the orbital perturbations are also complex. In fact, any time you have more than two masses interacting through mutual gravitational attraction, it is *not possible* to find a general analytic solution to their orbital motion. The best you can do is come up with a numerical model that predicts the orbits pretty well, but imperfectly. 1. The Theory, Briefly We use the VSOP ("Variations Seculaires des Orbites Planetaires") theory of planet positions, as outlined in "Astronomical Algorithms", by Jean Meeus. The theory is essentially a Fourier-like expansion of the coordinates for a planet as a function of time. That is, for each planet, the Ecliptic Longitude, Ecliptic Latitude, and Distance can each be approximated as a sum: Long/Lat/Dist = s(0) + s(1)*T + s(2)*T^2 + s(3)*T^3 + s(4)*T^4 + s(5)*T^5 where T is the number of Julian Centuries since J2000. The s(N) parameters are each themselves a sum: s(N) = SUM_i[ A(N)_i * Cos( B(N)_i + C(N)_i*T ) ] Again, T is the Julian Centuries since J2000. The A(N)_i, B(N)_i and C(N)_i values are constants, and are unique for each planet. An s(N) sum can have hundreds of terms, but typically, higher N sums have fewer terms. The A/B/C values are stored for each planet in the files <planetname>.<L/B/R><N>.vsop. For example, the terms for the s(3) sum that describes the T^3 term for the Longitude of Mars are stored in "mars.L3.vsop". Pluto is a bit different. In this case, the positional sums describe the Cartesian X, Y, Z coordinates of Pluto (where the Sun is at X,Y,Z=0,0,0). The structure of the sums is a bit different as well. See KSPluto.cpp (or Astronomical Algorithms) for details. The Moon is also unique, but the general structure, where the coordinates are described by a sum of several sinusoidal series expansions, remains the same. 2. The Implementation. The KSplanet class contains a static OrbitDataManager member. The OrbitDataManager provides for loading and storing the A/B/C constants for each planet. In KstarsData::slotInitialize(), we simply call loadData() for each planet. KSPlanet::loadData() calls OrbitDataManager::loadData(QString n), where n is the name of the planet. The A/B/C constants are stored hierarchically: + The A,B,C values for a single term in an s(N) sum are stored in an OrbitData object. + The list of OrbitData objects that compose a single s(N) sum is stored in a QVector (recall, this can have up to hundreds of elements). + The six s(N) sums (s(0) through s(5)) are collected as an array of these QVectors ( typedef QVector<OrbitData> OBArray[6] ). + The OBArrays for the Longitude, Latitude, and Distance are collected in a class called OrbitDataColl. Thus, OrbitDataColl stores all the numbers needed to describe the position of any planet, given the Julian Day. + The OrbitDataColl objects for each planet are stored in a QDict object called OrbitDataManager. Since OrbitDataManager is static, each planet can access this single storage location for their positional information. (A QDict is basically a QArray indexed by a string instead of an integer. In this case, the OrbitDataColl elements are indexed by the name of the planets.) Tree view of this hierarchy: OrbitDataManager[QDict]: Stores 9 OrbitDataColl objects, one per planet. | +--OrbitDataColl: Contains all three OBArrays (for Longitude/Latitude/Distance) for a single planet. | +--OBArray[array of 6 QVectors]: the collection of s(N) sums for the Latitude, Longitude, or Distance. | +--QVector: Each s(N) sum is a QVector of OrbitData objects | +--OrbitData: a single triplet of the constants A/B/C for one term in an s(N) sum. To determine the instantaneous position of a planet, the planet calls its findPosition() function. This first calls calcEcliptic(double T), which does the calculation outlined above: it computes the s(N) sums to determine the Heliocentric Ecliptic Longitude, Ecliptic Latitude, and Distance to the planet. findPosition() then transforms from heliocentric to geocentric coordinates, using a KSPlanet object passed as an argument representing the Earth. Then the ecliptic coordinates are transformed to equatorial coordinates (RA,Dec). Finally, the coordinates are corrected for the effects of nutation, aberration, and figure-of-the-Earth. Figure-of-the-Earth just means correcting for the fact that the observer is not at the center of the Earth, rather they are on some point on the Earth's surface, some 6000 km from the center. This results in a small parallactic displacement of the planet's coordinates compared to its geocentric position. In most cases, the planets are far enough away that this correction is negligible; however, it is particularly important for the Moon, which is only 385 Mm (i.e., 385,000 km) away. =end =begin try: http://www.iausofa.org/2017_0420_C.html =end
true
7336c751f53436207ec75c1e00d539d9ff214b04
Ruby
jhallnation/ruby_test_pry
/string_reverser.rb
UTF-8
150
3.734375
4
[]
no_license
#reverse a string without using the .reverse method puts 'type in a ward' s = gets.chomp b = s.length - 1 while b >= 0 print s[b] b = b - 1 end
true
ac8de51c510a3a8965615cf33d7bf7ea9f382ec5
Ruby
GuilhermeMedeiross/Code-Wars
/1001 - Credit Card Mask.rb
UTF-8
263
3.03125
3
[]
no_license
def mineMaskify(cc) unmaks = cc.split(//).last(4).join mask = cc.gsub(unmaks, "").gsub(/\w/, "#") return mask + unmaks end def bestPraticeMaskify(cc) cc.gsub(/.(?=....)/, '#') end cc = gets.to_s puts mineMaskify(cc) puts bestPraticeMaskify(cc)
true
d8f4a4102b0c21056896a88b3dbc2e2dc9f7d7b9
Ruby
Rudis1261/ruby-the-hard-way
/Exercises/game/scenes/tavern.rb
UTF-8
1,204
3.15625
3
[]
no_license
class Tavern < Scene def enter message choices([ "(Old Lady) I need to track down my Husband in the city. It's been over a month without so much as a word.\n (Me) I should find out more...", "(Grimy welder to his friend) There's someone who found a vain of gold at the old mine, we should head out there and \"see\" what he has found. hahaha\n (Me) Yes maybe we \"I\" should...", "(Bartender) I really need to head out to the Ship Wreck this weekend. I heard there's some amazing loot there\n (Me) Why wait for the weekend, I can go there right now...", "(Hired gun to his friend) We could really use another hand on the ship, we need to set off in a day at most. Plenty looting and plundering to do...\n (Me) This sounds like something I can do with my hands tied behind my back", "(Me) I will just mind my own business, and keep sitting here" ]) action = Prompt.ask('Tavern').to_i if !(1..5).include?(action) return Prompt.invalid_option('tavern') end case action when 1 'city' when 2 'gold_mine' when 3 'ship_wreck' when 4 'pirate_ship' when 5 death end end end
true
5368ce0c8001f9984ba534d2e4600c9d6158ea8a
Ruby
al-nattahnam/ma-zmq
/lib/ma-zmq/proxy/balancer.rb
UTF-8
826
2.578125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module MaZMQ class Proxy class Balancer @@strategies = [ :round_robin, :connections, :load, # Cucub podria usar algo como 'less_jobs' :priority, :directed ] def initialize self.strategy = :round_robin # default strategy is round_robin @index = [] # @data = [] # connections, load end def strategy=(strategy) return false if not @@strategies.include? strategy @strategy = strategy end def add(index) @index << index end def remove(index) @index.delete(index) end def current @index[0] end def next case @strategy when :round_robin @index.push(@index.shift) end end end end end
true
551d46e2299fed9ef359391f41cd40bf9bec0714
Ruby
infinitom/object_oriented_programming
/mars_rover.rb
UTF-8
1,698
4.6875
5
[]
no_license
# # OOP Exercise - mars_rover.rb # A simple exercise to move an object on a grid using inputs such as # Command - L (spin robot 90 degrees counter clockwise) # Command - R (spin robot 90 degrees counter clockwise) # Command - M (move forward in spun direction by one point) # class Rover attr_accessor :x, :y, :direction def initialize(x,y,direction) @x = x @y = y @direction = direction end def read_instruction(instructions) rover=instructions.split(//) rover.each do |command| if command == "M" move else turn(command) end end end def move if @direction == "N" @y += 1 elsif @direction == "E" @x += 1 elsif @direction == "S" @y -= 1 elsif @direction == "W" @x -= 1 else puts "Direction unrecognized" end end def turn(face) if @direction == "N" if face == "L" @direction = "W" else @direction = "E" end elsif @direction == "E" if face == "L" @direction = "N" else @direction = "S" end elsif @direction == "S" if face == "L" @direction = "E" else @direction = "W" end elsif @direction == "W" if face == "L" @direction = "S" else @direction = "N" end end end def to_s "(#{@x}, #{@y}, \"#{@direction}\")" end end #Create Rovers rover1 = Rover.new(1, 2,"N") rover2 = Rover.new(3, 3,"E") # Take Rover's instructions puts "Welcome to mars" puts "Please specify Rover 1's moves" instructions = gets.chomp rover1.read_instruction(instructions) puts "Please specify Rover 2's moves" instructions = gets.chomp rover2.read_instruction(instructions) puts "Rover1's new position is now #{rover1}" puts "Rover2's new position is now #{rover2}"
true
9f8416dcd9f9cabd20aa0bd321f3c426c9ed77f0
Ruby
jtavarez14/cartoon-collections-onl01-seng-pt-032320
/cartoon_collections.rb
UTF-8
788
3.21875
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
dwarves = ["Doc", "Dopey", "Bashful", "Grumpy"] def roll_call_dwarves(dwarves) dwarves.each_with_index do |order_call, index| puts "#{index + 1}. #{order_call}" end end roll_call_dwarves(dwarves) planeteer_calls = ["earth", "wind", "fire", "water", "heart"] def summon_captain_planet(planeteer_calls) planeteer_calls.collect {|power| power.capitalize + "!"} end summon_captain_planet(planeteer_calls) short_words = ["puff", "goo", "two"] def long_planeteer_calls(short_words) short_words.any? do |word| word.size > 4 end end long_planeteer_calls(short_words) snacks = ["crackers", "gouda", "thyme"] def find_the_cheese(snacks) cheese_types = ["cheddar", "gouda", "camembert"] snacks.find do |cheese| cheese_types.include?(cheese) end end find_the_cheese(snacks)
true
f7762318cffcd71a88e1008ac1cb06040501ea18
Ruby
RudskikhIvan/dsl_parsers
/spec/field_methods_spec.rb
UTF-8
3,889
2.546875
3
[ "MIT" ]
permissive
require "spec_helper" class TestParser include DslParsers::BaseParser def self.default_finder :xpath end def self.available_finders [:xpath, :css, :regexp] end end describe 'has_one methods' do it 'build one level map' do test_class = Class.new(TestParser) do has_one :first_name, 'Users/User/@FirstName' has_one :last_name, :css => '#users .user #last_name' has_one :age, 'Users/User/Age', Integer has_one :birthday, :xpath => 'Users/User/Birthday', :type => Date end expect(test_class.map.size).to be 4 expect(test_class.map[:first_name]).to eq({ :path => 'Users/User/@FirstName', :finder_method => :xpath, :map => String }) expect(test_class.map[:last_name]).to eq({ :path => '#users .user #last_name', :finder_method => :css, :map => String }) expect(test_class.map[:age]).to eq({ :path => 'Users/User/Age', :finder_method => :xpath, :map => Integer }) expect(test_class.map[:birthday]).to eq({ :path => 'Users/User/Birthday', :finder_method => :xpath, :map => Date }) end it 'build some levels map' do test_class = Class.new(TestParser) do has_one :first_name, 'Parent/@FirstName' has_one :document, 'Parent/Document' do has_one :code, 'Code' has_one :number, 'Number' end has_many :children, 'Parent/Children' do has_one :document, 'Child/Document' do has_one :code, 'Code' has_one :number, 'Number' end has_one :first_name, 'Child/@FirstName' has_one :age, 'Child/@Age', type: Integer end end expect(test_class.map.size).to be 3 expect(test_class.map[:first_name]).to eq({ :path => 'Parent/@FirstName', :finder_method => :xpath, :map => String }) expect(test_class.map[:document]).to eq({ :path => 'Parent/Document', :finder_method => :xpath, :map => { :code => { :path => 'Code', :finder_method => :xpath, :map => String }, :number => { :path => 'Number', :finder_method => :xpath, :map => String } } }) expect(test_class.map[:children]).to eq({ :path => 'Parent/Children', :finder_method => :xpath, :many => true, :map => { :document => { :path => 'Child/Document', :finder_method => :xpath, :map => { :code => { :path => 'Code', :finder_method => :xpath, :map => String }, :number => { :path => 'Number', :finder_method => :xpath, :map => String } } }, :first_name => { :path => 'Child/@FirstName', :finder_method => :xpath, :map => String }, :age => { :path => 'Child/@Age', :finder_method => :xpath, :map => Integer } } }) end it 'build correct map where call has_many with type' do test_class = Class.new(TestParser) do has_many :fares, './/TotalFare/@Amount', Integer has_many :taxes, './/Taxes/@TotalAmount', Integer has_many :passengers, './/PassengerTypeQuantity/@Code' end expect(test_class.map).to eq({ :fares => { :path => './/TotalFare/@Amount', :finder_method => :xpath, :map => Integer, :many=>true }, :taxes => { :path => './/Taxes/@TotalAmount', :finder_method => :xpath, :map => Integer, :many=>true }, :passengers => { :path => './/PassengerTypeQuantity/@Code', :finder_method => :xpath, :map => String, :many=>true } }) end end
true
ccc7f09988b13a4a0f9eec7b1abd262a7175390c
Ruby
dylanham/reddit-pair-app
/spec/feature/posts_management_spec.rb
UTF-8
3,601
2.578125
3
[]
no_license
require 'rails_helper' feature 'User can do lots of stuff with posts' do scenario 'Only a logged in user can make a new post' do user = create_user login(user) expect(current_path).to eq root_path click_on "New Post" fill_in "Title", with: "My Favorite Post Ever" fill_in "Content", with: "I love this post alot" click_on "Create Post" expect(page).to have_content "My Favorite Post Ever" expect(page).to have_content "The Black Hole has recieved your post" end scenario 'A visitor should be redirected to sign in if trying to make a new post' do visit root_path click_on "New Post" expect(current_path).to eq sign_in_path expect(page).to have_content 'Please sign in first' end scenario 'Only a logged in user can comment on a post' do user = create_user login(user) post = create_post visit post_path(post) expect(page).to have_content post.title fill_in 'Content', with: 'This post was pretty cool' click_on 'Create Comment' expect(page).to have_content 'Comment added' expect(page).to have_content 'This post was pretty cool' end scenario 'A visitor is redirected to sign in if trying to comment on a post' do post = create_post visit post_path(post) fill_in "Content", with: "Can I save this comment?!" click_on "Create Comment" expect(current_path).to eq sign_in_path expect(page).to have_content "Please sign in first" end scenario 'An owner of a post can edit their post' do user = create_user post = create_post(user_id: user.id) login(user) visit post_path(post) expect(page).to have_content 'Edit' click_on 'Edit' expect(current_path).to eq edit_post_path(post) fill_in 'Title', with: 'HAHA I changed this Title' fill_in 'Content', with: 'Your comments make no sense now' click_on 'Update Post' expect(current_path).to eq post_path(post) expect(page).to have_content 'The Black Hole has accepted your changes' expect(page).to have_content 'HAHA I changed this Title' expect(page).to have_no_content 'Cool Post' end scenario 'A current user who is not the owner of a post is redirected to root' do user = create_user post = create_post login(user) visit post_path(post) click_on "Edit" expect(page).to have_content "Hey! You can't do that. Silly" expect(current_path).to eq root_path end scenario 'A visitor cannot edit a post and is redirected to root' do post = create_post visit post_path(post) click_on "Edit" expect(page).to have_content "Please sign in first" expect(current_path).to eq sign_in_path end scenario 'Only the owner of a post can delete that post' do user = create_user post = create_post(user_id: user.id) login(user) visit post_path(post) click_on "Delete Post" expect(current_path).to eq root_path expect(page).to have_content 'The Blackhole has swallowed your post!' expect(page).to have_no_content 'Cool Post' end scenario 'A current user who is not the owner of a post is redirected to root' do user = create_user post = create_post login(user) visit post_path(post) click_on "Delete Post" expect(page).to have_content "Hey! You can't do that. Silly" expect(current_path).to eq root_path end scenario 'A visitor cannot edit a post and is redirected to root' do post = create_post visit post_path(post) click_on "Delete" expect(page).to have_content "Please sign in first" expect(current_path).to eq sign_in_path end end
true
bc62e2c7e43425acaaa7bdeb2e61401d96eb51bc
Ruby
Viola100/codesensei_course
/homework_1/5.rb
UTF-8
150
2.890625
3
[]
no_license
puts "Podaj dystans w km" km = gets.to_f spalanie = km * 0.065 puts "Zużycie paliwa: #{spalanie}" koszt = spalanie * 4.30 puts "koszt: #{koszt} zł"
true
7b92aeff260e0a56dd2f4c5042866a1c0e7f807b
Ruby
pcruiksh/rmmts
/app/models/purchase.rb
UTF-8
1,006
2.765625
3
[]
no_license
class Purchase < ActiveRecord::Base belongs_to :mate has_many :payments, dependent: :destroy has_one :house, through: :mate mount_uploader :image, BillUploader def amount_paid paid = self.payments.sum(:amount) end def amount_owed owed = (self.amount_paid + self.amount_for_each) - self.amount end def amount_for_each each = ( self.amount / self.mate.house.mates.size ).round(2) end # def grouped_payments # grouped_payments = self.payments.group(:mate_id).sum(:amount) # end def payments_paid_by(housemate) housemate_payments = self.payments.where(mate_id: housemate.id) end def amount_paid_by(housemate) housemate_paid = self.payments_paid_by(housemate).sum(:amount) end def amount_owed_by(housemate) housemate_owes = self.amount_paid_by(housemate) - self.amount_for_each end def fully_paid? self.amount_paid >= self.amount end def paid_by?(housemate) self.amount_paid_by(housemate) >= self.amount_for_each end end
true
d11235188fd0fdb7e2c9149d313cfa34013d73a9
Ruby
martinliptak/codility
/S-MinAvgTwoSlice.rb
UTF-8
1,352
3.484375
3
[ "MIT" ]
permissive
# you can use puts for debugging purposes, e.g. # puts "this is a debug message" def solution(a) sums = prefix_sums(a) min = nil min_from = nil (0..a.count - 2).each { |i| (i + 1..[i + 4, a.count - 1].min).each { |j| avg = (sums[j + 1] - sums[i]).to_f / (j - i + 1) if min if avg < min min = avg min_from = i end else min = avg min_from = 0 end } } min_from end def prefix_sums(a) sums = [0] * (a.count + 1) 1.upto(a.count) { |i| sums[i] = sums[i - 1] + a[i - 1] } sums end require "minitest/autorun" require "byebug" require "timeout" class TestSolution < Minitest::Test def test_default input = [4, 2, 2, 5, 1, 5, 8] output = 1 assert_equal output, solution(input) end def test_simple_1 input = [4, 5, 2, 4, 1, 5, 8] output = 2 assert_equal output, solution(input) end def test_small input = [1, -1] output = 0 assert_equal output, solution(input) end def test_large input = [10_000] * 100_000 output = 0 Timeout::timeout(6) { assert_equal output, solution(input) } end end
true
091ab108ee03ccb53b3f4633145823ad90509121
Ruby
mynameisrufus/sorted
/lib/sorted/elasticsearch_query.rb
UTF-8
652
2.984375
3
[ "MIT" ]
permissive
require 'sorted/set' module Sorted ## # Parses an Elasticsearch type set of order # # Parsing: # # params = [{ 'email' => {'order' => 'desc'}}] # set = Sorted::ElasticsearchQuery.parse(params) # set.to_a #=> [['email', 'desc']] # # Encoding: # # Sorted::ParamsQuery.encode(set) #=> [{ 'email' => {'order' => 'desc'}}] # class ElasticsearchQuery def self.parse(raw) Set.new(raw.each_with_object([]) { |hash, a| a << [hash.first.first, hash.first.last['order']] }) end def self.encode(set) set.to_a.each_with_object([]) { |f, a| a << { f.first => { 'order' => f.last } } } end end end
true
8f40646d643ec1085ac8e950718c46a907e76392
Ruby
ParkMD7/reverse-each-word-nyc-web-080618
/reverse_each_word.rb
UTF-8
266
3.640625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
sentence1 = "Hello there, and how are you?" sentence2 = "Hi again, just making sure it's reversed!" def reverse_each_word(sentence) sentence = sentence.split sentence.collect do |word_reverse| word_reverse.reverse! end sentence.join(" ") end
true
d8a0c6eed6c09833332eb03eb9fe1d6903d89956
Ruby
fzhou7/ruby
/09_timer/timer.rb
UTF-8
226
3.109375
3
[]
no_license
class Timer attr_accessor :seconds def initialize() @seconds = 0 end def time_string "#{"%.2i" %(hour=seconds/3600)}:#{"%.2i" %(minute=(seconds-hour*3600)/60)}:#{"%.2i" %(seconds-hour*3600-minute*60)}" end end
true
14a2a197f0f3da0fb0310f657848701277206469
Ruby
PetePhx/ruby-tests
/exercises/easy_testing/04_empty_object_assertions.rb
UTF-8
978
2.984375
3
[]
no_license
=begin Empty Object Assertions Write a minitest assertion that will fail if the Array list is not empty. =end require 'minitest/autorun' require 'minitest/reporters' Minitest::Reporters.use! class EmptyTest < Minitest::Test def setup @arr1 = [] @arr2 = %w[I can haz test] end def test_empty assert_empty @arr1 assert_empty @arr2 end end # ===========================================================================| # F # # Failure: # EmptyTest#test_empty [/home/user/Launch/130_blocks_tests/exercises/easy_testing/04_empty_object_assertions.rb:21]: # Expected ["I", "can", "haz", "test"] to be empty. # # bin/rails test home/user/Launch/130_blocks_tests/exercises/easy_testing/04_empty_object_assertions.rb:19 # # # Finished in 0.03269s # 1 tests, 4 assertions, 1 failures, 0 errors, 0 skips # ]2;[Minitest results] 1 tests # # # Finished in 0.333627s, 2.9974 runs/s, 11.9894 assertions/s. # 1 runs, 4 assertions, 1 failures, 0 errors, 0 skips
true
a9f5a037874fbc3b875c958b03db98ecf015538d
Ruby
KaiserChan/ruby_fundamentals_1
/exercise4.1.rb
UTF-8
187
3.921875
4
[]
no_license
puts "Hey there, what is the number that you are thinking of now?" number = gets.chomp.to_i if number >= 100 puts "That's a big number!" else puts "Why? Dream a little bigger!" end
true
052a284dab5b84841dcbc8ef9cd0233e1c74397d
Ruby
BJSummerfield/Prework
/prework/Episode21/Exercise2.rb
UTF-8
64
3.078125
3
[]
no_license
number = -2 51.times do number = number + 2 puts number end
true
8ebf289a649ecbddb4cabb59bfa582066fcdba95
Ruby
dsaenztagarro/gundam
/lib/gundam/github/api/v3/connector.rb
UTF-8
5,088
2.546875
3
[]
no_license
# frozen_string_literal: true require 'octokit' require_relative 'mappers/combined_status_ref_mapper' require_relative 'mappers/commit_status_mapper' require_relative 'mappers/comment_mapper' require_relative 'mappers/issue_mapper' require_relative 'mappers/label_mapper' require_relative 'mappers/pull_request_mapper' require_relative 'mappers/remote_repository_mapper' require_relative 'mappers/team_mapper' require_relative 'mappers/team_member_mapper' module Gundam module Github module API module V3 # Rest API V3 Connector class Connector def initialize(client = Connector.new_client) @client = client end def org_teams(organization) response = @client.org_teams(organization) response.map { |resource| TeamMapper.load(resource) } end def team_members(team_id) response = @client.team_members(team_id) response.map { |resource| TeamMemberMapper.load(resource) } end def issue_comment(repo, number) response = @client.issue_comment(repo, number) CommentMapper.load(response) end # @param repo [String] # @param number [Fixnum] # @param comment [String] # @return [Gundam::Comment] def add_comment(repo, number, comment) response = @client.add_comment(repo, number, comment) CommentMapper.load(response) end # @param repo [String] A GitHub repository # @param number [Fixnum] Comment number # @param comment [String] Body of the comment which will replace the existing body # @return [Gundam::Comment] def update_comment(repo, number, comment) response = @client.update_comment(repo, number, comment) CommentMapper.load(response) end # @param repo [String] # @param [Gundam::Issue] # @return [Gundam::Issue] def create_issue(repo, issue) options = { assignee: issue.assignees.first, labels: issue.labels.map(&:name) } response = @client.create_issue(repo, issue.title, issue.body, options) IssueMapper.load(response) end # @param repo [String] # @param [Gundam::Issue] # @return [Gundam::Issue] def update_issue(repo, issue) options = { assignee: issue.assignees.first, body: issue.body, labels: issue.labels.map(&:name), title: issue.title } response = @client.update_issue(repo, issue.number, options) IssueMapper.load(response) rescue Octokit::UnprocessableEntity raise Gundam::UnprocessableEntity end # @param repo [String] # @param number [Fixnum] # @return [Array<Gundam::Comment>] def issue_comments(repo, number) list = @client.issue_comments(repo, number) list.map { |item| CommentMapper.load(item) } end # @param repo [String] # @return [Gundam::RemoteRepository] def repository(repo) response = @client.repository(repo) RemoteRepositoryMapper.load(response) rescue Octokit::Unauthorized raise Gundam::Error, 'Unauthorized access to Github REST API V3' end # @param repo [String] # @param [Gundam::PullRequest] # @return [Gundam::PullRequest] def update_pull_request(repo, pull) options = { title: pull.title, body: pull.body } response = @client.update_pull_request(repo, pull.number, options) PullRequestMapper.load(response) end # @param repo [String] # @param sha [String] # @return [CombinedStatusRef] def combined_status(repo, sha) response = @client.combined_status(repo, sha) CombinedStatusRefMapper.load(response) end # @param repo [String] A GitHub repository # @param base [String] The branch (or git ref) you want your changes pulled into # @param head [String] The branch (or git ref) where your changes are implemented # @param title [String] Title for the pull request # @param body [String] The body for the pull request # @return [Gundam::PullRequest] def create_pull_request(repo:, base:, head:, title:, body:) response = @client.create_pull_request(repo, base, head, title, body) PullRequestMapper.load(response) rescue Octokit::Error raise Gundam::CreatePullRequestError end def self.new_client Octokit::Client.new login: Gundam.github_access_token, password: 'x-oauth-basic' end end end end end end
true
9ceee1213ceb97328f7e738ef50a87dad7c5eee0
Ruby
Gia1987/Ruby-Bank-Tech-Test
/lib/printer.rb
UTF-8
249
3.171875
3
[]
no_license
class Printer def header "date || Credit || Debit || Balance\n" end def print_statement(history) string = '' history.reverse.map{ |row| string += " #{row[0]} || " + "#{row[1]} || " + "#{row[2]}\n" } header + string end end
true
98836efb8265b8d38a690daf5430bd6d43d4cf99
Ruby
arirusso/pulse-analysis
/lib/pulse-analysis/audio_data.rb
UTF-8
1,093
3.078125
3
[ "Apache-2.0" ]
permissive
module PulseAnalysis class AudioData extend Forwardable def_delegators :@data, :[], :count, :each, :length, :max, :min, :size # @param [PulseAnalysis::Sound] sound def initialize(sound) @sound = sound @data = @sound.data end # Prepare the audio data for analysis # @return [Boolean] def prepare convert_to_mono if convert_to_mono? normalize if normalize? true end private # Should the audio data be normalized? # @return [Boolean] def normalize? headroom = 1.0 - @data.max headroom > 0.0 end # Normalize the audio data # @return [Array<Float>] def normalize factor = 1.0 / @data.max @data.map! { |frame| frame * factor } end # Should the audio data be converted to a single channel? # @return [Boolean] def convert_to_mono? @sound.num_channels > 1 end # Logic for converting a stereo sound to mono # @return [Array<Float>] def convert_to_mono # Use left channel @data = @data.map(&:first) end end end
true
3efa945b2d8107742b76a7752614347a533ff841
Ruby
jasmine-carter/ruby-collaborating-objects-lab-online-web-sp-000
/lib/song.rb
UTF-8
676
3.375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class Song attr_accessor :name, :artist @@all = [] def initialize(name) @name = name save end def save @@all << self end def self.all @@all end def artist_name=(name) artist_name = Artist.find_or_create_by_name(name) @artist = artist_name #check to see if artist exists and and assign artist if exists #if doesn't exist, create artist instances end def self.new_by_filename(file_name) #binding.pry parsed_song_name = file_name.split(" - ")[1] parsed_artist_name = file_name.split(" - ")[0] song = Song.new(parsed_song_name) song.artist_name=(parsed_artist_name) song end end
true
134e6d4a32f676d48e2c7acd0689ff6aba141ea4
Ruby
PlaustralCL/mastermind
/test/clues_test.rb
UTF-8
1,974
2.65625
3
[]
no_license
# frozen_string_literal: true require "test_helper" require_relative "../lib/mastermind/clues" # Tests for class Clues class CluesTest < Minitest::Test def test_keys_returns_empty_when_no_matches code = 1233.digits.reverse guess = 5555.digits.reverse clue = MasterMind::Clues.new(guess: guess, code: code) assert_equal("", clue.keys) end def test_keys_returns_all_X_when_correct code = 1233.digits.reverse guess = 1233.digits.reverse clue = MasterMind::Clues.new(guess: guess, code: code) expect = "XXXX" assert_equal(expect, clue.keys) end def test_keys_returns_for_one_near_match code = 1233.digits.reverse guess = 5155.digits.reverse clue = MasterMind::Clues.new(guess: guess, code: code) expect = "O" assert_equal(expect, clue.keys) end def test_near_match__works_for_duplicate_digits_in_code code = 1133.digits.reverse guess = 5515.digits.reverse clue = MasterMind::Clues.new(guess: guess, code: code) expect = "O" assert_equal(expect, clue.keys) end def test_near_match_works_for_duplicate_digits_in_guess code = 1113.digits.reverse guess = 3332.digits.reverse clue = MasterMind::Clues.new(guess: guess, code: code) expect = "O" assert_equal(expect, clue.keys) end def test_exact_match_duplicates_in_code code = 1133.digits.reverse guess = 1155.digits.reverse clue = MasterMind::Clues.new(guess: guess, code: code) expect = "XX" assert_equal(expect, clue.keys) end def test_works_combo_matches code = 3123.digits.reverse guess = 2153.digits.reverse clue = MasterMind::Clues.new(guess: guess, code: code) expect = "OXX" assert_equal(expect, clue.keys) end def test_works_for_multiple_near_miss_of_same_value code = 4161.digits.reverse guess = 1313.digits.reverse clue = MasterMind::Clues.new(guess: guess, code: code) expect = "OO" assert_equal(expect, clue.keys) end end
true
99c1e6858dad4d366083e232fca0e4e844867fba
Ruby
joelhelbling/arche
/spec/lib/arche/function_spec.rb
UTF-8
1,009
2.984375
3
[ "MIT" ]
permissive
require 'arche/type' require 'arche/function' module Arche describe Function do it { should be_kind_of Arche::Type } it "has a Proc as its function" do subject.instance_eval("@function").should be_kind_of(Proc) end it "can be constructed with a Proc" do subject = Function.new { "fooBAR" } subject.instance_eval("@function.call").should == "fooBAR" end context "As an Arche::Type object" do it "has data members" do subject.foo = "FOO" subject[:foo].should == "FOO" end it "can be constructed with data members" do subject = Function.new({foo: "FOO"}) subject.foo.should == "FOO" end end context "As a data member of an Arche::Type object" do subject { Type.new({ foo: "bar" }) } it "has access to its parent's data via 'this'" do subject.uppifier = Function.new do this.foo.upcase end subject.uppifier!.should == "BAR" end end end end
true
80af3b8a7135fad57ffbca3954365b17e5229643
Ruby
gpepic/shoes_rb_sql
/lib/style.rb
UTF-8
520
3.09375
3
[]
no_license
class Style def initialize(name, id=nil) @name = name @id = id end def name @name end def id @id end def ==(another_style) self.name == another_style.name end def self.all results = DB.exec("SELECT * FROM style;") style = [] results.each do |result| name = result['name'] id = result['id'].to_i style << Style.new(name, id) end style end def save results = DB.exec("INSERT INTO style (name) VALUES ('#{@name}') RETURNING id;") @id = results.first['id'].to_i end end
true
350f4f045c15bb4fa40240858a60bd670452c69a
Ruby
Fred-209/RB100
/ruby_basics_exercises/loops/thats_odd.rb
UTF-8
253
4.28125
4
[]
no_license
# he code below shows an example of a for loop. Modify the code so that it only outputs i if i is # an odd number. for i in 1..100 puts i if i.odd? end # or using modulo to determine if a number is odd for i in 1..100 do puts i if i % 2 != 0 end
true
905608926e68cb3bdb6479ef5d6ca4bfd6500cd0
Ruby
holodigm/winnr
/lib/random_range.rb
UTF-8
256
3.234375
3
[]
no_license
def rand_int(from, to) rand_in_range(from, to).to_i end def rand_price(from, to) rand_in_range(from, to).round(2) end def rand_time(from, to) Time.at(rand_in_range(from.to_f, to.to_f)) end def rand_in_range(from, to) rand * (to - from) + from end
true
f9d3d63e77767d6796d5421929c369e91a387fb8
Ruby
nittan02/ruby
/file.rb
UTF-8
2,028
3.75
4
[]
no_license
#! /usr/bin/ruby -Ks puts "------------------------------------------------------" begin # File.openはファイルをオープンし、Fileオブジェクトを返す # 第一引数: ファイルパス # 第二引数: ファイルモード(デフォルト "r") # 第三引数: ファイルを生成する場合のパーミッション # 失敗した場合にErrno::EXXX例外が発生 # # File.openにブロックを渡すと、 # ブロックを閉じた時点でファイルを自動クローズする。 File.open('./inputFile.txt', 'r') do |file| # IO#each_lineは1行ずつ文字列として読み込み、 # ブロックを実行する。 # 第一引数:行の区切り文字 # 第二引数:最大の読み込みバイト数 # 読み込み用にオープンされていない場合にIOError file.each_line {|line| puts line } end # 例外処理 rescue SystemCallError => e puts %Q(class=[#{e.class}] message=[#{e.message}]) rescue IOError => e puts %Q(class=[#{e.class}] message=[#{e.message}]) end puts "------------------------------------------------------" # IO.foreachを使う場合。IO.foreachはオープンしたファイルの # 各行を引数としてブロックを実行する。 # ファイルモードは'r'? # 第一引数:ファイルパス # 第二引数:行の区切り文字 # オープンに失敗した場合はErrono::EXXX例外が発生 begin File.foreach('./inputFile.txt') do |line| puts line end # 例外処理 rescue SystemCallError => e puts %Q(class=[#{e.class}] message=[#{e.message}]) end puts "-----------------------------------------------" # 他にもファイルの全ラインを先に読んだり、一文字ずつ読んだりできる。 # 下記は一度に読む例。区切り文字を与えて配列で取り出すこともできる。 begin s = File.read("./inputFile.txt") puts s rescue SystemCallError => e puts %Q(class=[#{e.class}] message=[#{e.message}]) end
true