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
edcbd300e203ff8284518db9a2f6574ef16c5f59
Ruby
arbovm/scratchweb
/spec/lib/scratchweb/http/header_spec.rb
UTF-8
3,553
2.59375
3
[]
no_license
require File.dirname(__FILE__) + '/../../../../lib/scratchweb' describe Scratchweb::Http::Header do POST_HEADER = <<EOH POST /uploads HTTP/1.1 User-Agent: curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8l zlib/1.2.3 Host: localhost:8081 Accept: */* Content-Length: 3273 Expect: 100-continue Content-Type: multipart/form-data; boundary=----------------------------ac7579a3cd1d EOH GET_HEADER = <<EOH GET /uploads/123/progress HTTP/1.1 Host: 0.0.0.0:8081 User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; en-us) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4 Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 Accept-Language: en-us Accept-Encoding: gzip, deflate Connection: keep-alive EOH DELETE_HEADER = <<EOH DELETE / HTTP/1.1 User-Agent: curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8l zlib/1.2.3 Host: 0.0.0.0:8081 Accept: */* EOH describe "when processing POST header with path /uploads" do before(:each) do @handler = Scratchweb::Http::Header.new :header_string => POST_HEADER end it "should parse content length" do @handler.content_length.should eql(3273) end it "should know its method" do @handler.method.should be(:post) @handler.method?(:post).should be_true @handler.method?(:get ).should be_false end it "should know its path" do @handler.path.should be_eql("/uploads") end it "should call block if method and path matches" do @handler.call_if_action_matches(:post, "/uploads"){true}.should be_true @handler.call_if_action_matches(:post, "/"){true}.should be_false @handler.call_if_action_matches(:get, "/uploads"){true}.should be_false @handler.call_if_action_matches(:post, "/xxxxxxx"){true}.should be_false end it "should yield path parameters to block if method and path matches" do @handler.call_if_action_matches(:post, "/:path"){|path| path.should eql("uploads")} @handler.call_if_action_matches(:get, "/:path"){true}.should be_false @handler.call_if_action_matches(:post, "/uploads/:path"){true}.should be_false end it "should extract path parameters" do @handler.extract_path_params("/:path").should be_eql(["uploads"]) end it "should extract the multipart boundary" do @handler.multipart_boundary.should be_eql('----------------------------ac7579a3cd1d') end end describe "when processing GET header with path /uploads/123/progress" do before(:each) do @handler = Scratchweb::Http::Header.new :header_string => GET_HEADER end it "content length should be zero for GET header without content-length" do @handler.content_length.should eql(0) end it "should know its method" do @handler.method.should be(:get) @handler.method?(:get ).should be_true @handler.method?(:post).should be_false end it "should know its path" do @handler.path.should be_eql("/uploads/123/progress") end it "should extract path params" do @handler.extract_path_params("/uploads/:id/progress").should be_eql(["123"]) end end describe "when processing DELETE header" do before(:each) do @handler = Scratchweb::Http::Header.new :header_string => DELETE_HEADER end it "should know its method" do @handler.method.should be(:delete) end end end
true
7bb2dfac94d9c4a12c9c6c9894eb4c0b28996179
Ruby
TheBoyMoe/Book-Repo
/Effective-Testing-with-RSpec3/basics/chap2/spec/coffee_spec.rb
UTF-8
3,572
3.03125
3
[]
no_license
require_relative '../spec_helper' require 'coffee' =begin NOTE: 1. use the 'coderay' gem to add syntax highlighting to the cli (in bundler projects add coderay to your gem, otherwise install it using 'gem install coderay') 2. to identify slow running tests use the --profile option, e.g. $ rspec spec/test_spec.rb --profile 3. you can run tests by directory - all files/test executed you can run tests by file - all tests in the file run you can run tests by line number you can run tests by name using the -e option with a search term, e.g. $ rspec spec -e milk #=> run all examples in the spec folder which include the term 'milk' #=> Rspec searches the full description, 'A cup of coffee with milk' #=> searches are case sensitive 4. you can run only failures with the '--only-failures' option, e.g. $ rspec --only-failures #=> run the rspec normally the first time(with out the option) to find and record all the failures #=> on subsequent runs add the option so as to exclude all passing and skipped tests #=> 'pending' tests are still executed - marked as failed #=> you need to define a path where Rspec can save the resulting data: Configure the spec_helper file RSpec.configure do |config| config.example_status_persistence_file_path = ​'path/to/file.txt'​ end 5. you can execute the next failure only with the '--next-failure' option $ rspec spec/ --next-failure #=> run rspec normally first time, add the option to subsequent runs #=> stops execution at the first failure similar to the '--fail-fast' option which stops at the first failure - does not require spec_helper configuration 6. you can focus on an example or a group by adding 'f' to the beginning of the method name, e.g 'it', 'context', 'describe' becomes 'fit', 'fcontext' and 'fdescribe', run rspec(no options required) only that example/group are executed You need to configure the spec_helper file RSpec.configure ​do​ |config| config.filter_run_when_matching(​focus: ​​true​)​ end 7. empty examples: - just the 'it' statement - displayed in yellow with an astrix - marked as pending 8. pending examples: - use the 'pending' keyword, with an explanation(optional) - rspec treats them as failing tests - use for tests expected to fail - displayed in red as failed - lines appearing afterwards are not run 9. skipped examples: - to skip 'it', 'describe' or 'context' - use the 'skip' keyword (with an optional explanation), or add 'x' in front of the method, e.g. - 'xit', 'xcontext' , 'xcontext' - the example/group is skipped with the description & explanation displayed in yellow 10. to see the full back trace, add the '--backtrace' or '-b' option =end RSpec.describe 'A cup of coffee' do let(:coffee){Coffee.new} it "costs $1.00" do expect(coffee.price).to eq(1.0) end context 'with milk' do before{coffee.add :milk} it "costs $1.25" do # pending 'Not yet implemented' # skip 'Not yet implemented' expect(coffee.price).to eq(1.25) end it "is light in color" do # pending 'Color not yet implemented' # skip 'Not yet implemented' expect(coffee.color).to eq(:light) end it "is cooler than 200 degrees Farenheit" do pending "Temperature no yet implemented" # skip 'Not yet implemented' # expect(coffee.temperature)<.to be < 200.0 end end end
true
66f628dffa84608890d84d7e2e33b2311f474a8d
Ruby
BaptisteBecmeur/fullstack-challenges
/02-OOP/05-Food-Delivery-Day-One/01-Food-Delivery/app/repositories/customers_repository.rb
UTF-8
1,269
3.21875
3
[]
no_license
require 'csv' require_relative '../models/customer' class CustomersRepository attr_reader :customers def initialize(csv_path) @customers = [] @csv_path = csv_path # load_csv if File.exist?(csv_path) @next_id = @customers.empty? ? 1 : (@customers.map {|c| c.id }.max.to_i + 1) # si le tableau de customers est vide alors id = 1 sinon max + 1 end def add_customer(customer) customer.id = @next_id @next_id += 1 @customers << customer save_to_csv end # ##################### def find(id) @customers.find do |customer| customer.id == customer_id_to_find end end # ##################### private def save_to_csv CSV.open(@csv_path, 'w') do |csv| csv << ["id", "name", "address"] @customers.each do |customer| csv << [customer.id, customer.name, customer.address] end end end def load_csv return unless File.exist?(@csv_path) CSV.foreach(@csv_path, headers: :first_row, header_converters: :symbol) do |row| # le header sera une preière rangée, le header convertit en symbole attributes = { id: row[:id].to_i, name: row[:name], customer: row[:customer_id] } @customers << Customer.new(attributes) end end end
true
dc9adbd791850e9bd0d7132ab8adfa924b48a17f
Ruby
Hawleywoo/programming-univbasics-4-square-array-den01-seng-ft-051120
/lib/square_array.rb
UTF-8
272
3.546875
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def square_array(array) # your code here #new_array = array.collect{|i| i**2} #puts new_array count= 0 new_array = [] while count < array.length do new_array.push(array[count]**2) count += 1 end new_array end #array =[4,8,12] #square_array(array)
true
47eec247057ca0478496c6e717f4cab9f9a1aa33
Ruby
threepistons/advent-of-code
/2019/05/lib/05.rb
UTF-8
4,209
3.796875
4
[]
no_license
require 'expect' class Intcode attr_reader :result attr_accessor :input attr_reader :output def initialize @result = '' @input = 0 @output = 'cat' thearray = [] end # this didn't work for reasons I have yet to work out def calculate(program) operator = '' a = 0 b = 0 thearray = program.split(",").map { |s| s.to_i } thearray.each_with_index do | val, key | case key.divmod(4)[1] when 0 case val when 1 operator = 'add' when 2 operator = 'multiply' when 99 break else @result = "program input invalid" break end when 1 a = thearray.at(val) puts "A is #{a}" when 2 b = thearray.at(val) #puts "B is #{b}" else case operator when 'add' thearray[val] = a + b else thearray[val] = a * b end end end @result = thearray.join(",") end # this did work def loopcalculate(program) thearray = program.split(",").map { |s| s.to_i } self.reusedbit(thearray) @result = thearray.join(",") # puts @result end def reusedbit(thearray) i = 0 lim = thearray.length while i < lim puts 'current instruction', thearray[i] digits = thearray[i].digits # remember, 12345 becomes [5,4,3,2,1] puts 'The digits array', digits puts 'number of members', digits.length if digits.length > 1 digits[1] = 10 * digits[1] + digits[0] digits.delete_at(0) end # digits should now be an array like [1] or [3,1,0,1] or [99,1], with digits[0] being the opcode and only mandatory element. de = digits[0] puts 'opcode', de # puts '---', digits # everything seems ok to here. if digits.length > 3 # then there must be a mode 1 instruction in digits[3] a = i+3 puts 'mode immediate for third parameter', a else a = thearray[i+3] puts 'mode positional for third parameter', a end if digits.length > 2 && digits[2] == 1 b = i+2 puts 'mode immediate for second parameter', b else b = thearray[i+2] puts 'mode positional for second parameter', b end if digits.length > 1 && digits[1] == 1 c = i+1 puts 'mode immediate for first parameter', c else c = thearray[i+1] puts 'mode positional for first parameter', c end case de when 1 thearray[a] = thearray.at(c) + thearray.at(b) i+=4 when 2 thearray[a] = thearray.at(c) * thearray.at(b) i+=4 when 3 thearray[c] = @input if lim < c lim = c end i+=2 when 4 @output = thearray.at(c).to_s i+=2 when 5 if thearray[c] != 0 i = thearray.at(b) else i+=3 end when 6 if thearray[c] == 0 i = thearray.at(b) else i+=3 end when 7 if thearray.at(c) < thearray.at(b) thearray[a] = 1 else thearray[a] = 0 end i+=4 when 8 if thearray.at(c) == thearray.at(b) thearray[a] = 1 else thearray[a] = 0 end i+=4 when 99 break default puts "improperly-formed Intcode program" break end end end def bruteforce(program) noun = 0 until noun == 100 verb = 0 until verb == 100 thearray = program.split(",").map { |s| s.to_i } # for each iteration, we reset to "program" thearray[1] = noun thearray[2] = verb self.reusedbit(thearray) if thearray[0] == 19690720 then answer = verb + 100 * noun puts "Answer is #{answer}" end verb+=1 end noun+=1 end end end computer = Intcode.new IO.foreach('input.txt') do |line| computer.input = 5 computer.loopcalculate(line) if computer.result != '0' puts 'ERROR:', computer.result end # computer.bruteforce(line) puts 'output is', computer.output end
true
9989115221506a28bcc8670d9468018642168d57
Ruby
sogapalag/contest
/atcoder/abc117/c.rb
UTF-8
183
2.90625
3
[]
no_license
n,m=gets.split.map &:to_i x=gets.split.map &:to_i x.sort! a=[] for i in 0 .. m - 2 a << x[i + 1] - x[i] end a.sort! ans = 0 for i in 0 ... [0, m - n].max ans += a[i] end puts ans
true
5c03b49434b56305404241986d00dc5d422d3cd8
Ruby
BlookHo/api_sinatra_pg
/models/company.rb
UTF-8
2,216
2.5625
3
[]
no_license
class Company < Sequel::Model one_to_many :jobs plugin :validation_helpers def validate super errors.add(:name, "can't be empty") if name.empty? validates_presence [:name, :location] validates_unique [:name] end def to_api # Not for array!! { id: id.to_s, name: name, location: location, } end # def company_to_api # Not for array!! # { # id: id.to_s, # name: name, # location: location, # } # end # dataset_module do # Model scope's OR self. def self.by_name(name) res = [] res = where(name: /#{name}/i) if name puts "In by_name dataset mod: res = #{res.inspect}" res.empty? ? [] : res end # end dataset_module do # Model scope's OR self. def by_location(location) puts 'In by_location dataset mod' where(location: /#{location}/i) if location end end def self.company_jobs(name) company = Company.by_name(name)#[:id] puts "company = #{company.inspect}" if company # puts "company = #{company.columns.inspect}" unless company.to_a == [] # company = [:id, :name, :location, :created_at, :upated_at] # puts "company = #{company.map(:id).inspect}" # company# = [2] puts "company.count = #{company.count}" unless company.nil? company_id = company.map(:id)[0] unless company == [] || company == nil puts "company_id = #{company_id.inspect}" # company_id # company_id_select_map = company.select_map(:id) unless company.to_a == [] # puts "company_id_select_map = #{company_id_select_map.inspect}" # company_id = company.select(:id).naked.all.inspect # "[{:id=>2}]" # company_id.nil? ? [].to_json : company_id.to_json # puts "company_id = #{company_id.to_json}" company_jobs = Job.company_jobs(company_id) unless company_id.nil? puts "company_jobs = #{company_jobs.count}" unless company_jobs.nil? puts "company_jobs = #{company_jobs.inspect}" company_jobs.nil? ? [].to_json : collection_to_api(company_jobs) end def call_one_method(model_name, method, params) if params model_name.send(method, params) else puts "Enter Name!" [].to_json end end end
true
e969757e9bae7f6683304125e5e026cc0fa94198
Ruby
leopoldkwok/borisbikes
/spec/garage_spec.rb
UTF-8
522
2.890625
3
[]
no_license
require 'garage' describe Garage do let(:broken_bikes) { [broken_bike = Bike.new.break!] } let(:garage) { Garage.new(:capacity => 123, :bikes => broken_bikes)} it "should allow setting default capacity on initialising" do expect(garage.capacity).to eq(123) end it "should fix broken bikes" do garage.fix_all_broken_bikes! expect(garage.broken_bikes).to eq [] end # add some broken bikes in the garage # call a method to fix all broken bikes # all bikes should be fixed in the end end
true
49eb7a7244cfee043f811151b9dbe5d7de283fe8
Ruby
MikeConner/Kula
/lib/burn_link_destination.rb
UTF-8
1,210
2.578125
3
[]
no_license
require 'pg' class BurnLinkDestination # connect_url should look like; # mysql://user:pass@localhost/dbname def initialize(connect_url) @conn = PG.connect(connect_url) #TODO - Insert Cause Statement @conn.prepare('insert_pg_stmt', 'INSERT INTO replicated_burn_links( burn_link_id, burn_balance_transaction_id, earn_balance_transaction_id, type, cut_payee_id, amount, cut_percent, cut_amount, matched, updated) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10);') #INSERT INTO replicated_causes(cause_id, org_name) VALUES ($1, $2) end def write(row) time = Time.now @conn.exec_prepared('insert_pg_stmt', [ row[:burn_link_id], row[:burn_balance_transaction_id], row[:earn_balance_transaction_id], row[:type], row[:cut_payee_id], row[:amount], row[:cut_percent], row[:cut_amount], row[:matched], row[:updated] ] ) #, time rescue PG::Error => ex puts "ERROR for burn link updated at: #{row[:updated]}" puts ex.message # Maybe, write to db table or file end def close @conn.close @conn = nil end end
true
511923c6893f614581fd785a167bf5457bb9f8fe
Ruby
Sindhuraghavan/Ruby
/fifth.rb
UTF-8
435
3.640625
4
[]
no_license
class Operation def add(value1,value2) if (value1 =~ /[0-9]/ and value2 =~ /[0-9]/) sum= value1.to_f + value2.to_f print sum elsif value1 =~ /[a-zA-Z]/ and value2=~ /[a-zA-Z]/ print value1.concat(value2) else puts "no idea" end end end puts "Enter the value1" value1 = gets.chomp puts "Enter the value 2" value2 = gets.chomp obj=Operation.new() obj.add(value1,value2)
true
18b4317e5b0a16e3dc1cf9836d1526aea38cc159
Ruby
heroku/heroku-kafka-demo-ruby
/app.rb
UTF-8
4,008
2.609375
3
[ "ISC" ]
permissive
# frozen_string_literal: true require 'kafka' require 'sinatra' require 'json' require 'active_support/notifications' require 'tempfile' KAFKA_TOPIC = ENV.fetch('KAFKA_TOPIC', 'messages') GROUP_ID = ENV.fetch('KAFKA_CONSUMER_GROUP', 'heroku-kafka-demo') def with_prefix(name) "#{ENV['KAFKA_PREFIX']}#{name}" end def initialize_kafka tmp_ca_file = Tempfile.new('ca_certs') tmp_ca_file.write(ENV.fetch('KAFKA_TRUSTED_CERT')) tmp_ca_file.close # This demo app connects to kafka on multiple threads. # Right now ruby-kafka isn't thread safe, so we establish a new client # for the consumer and a different one for the consumer. producer_kafka = Kafka.new( seed_brokers: ENV.fetch('KAFKA_URL'), ssl_ca_cert_file_path: tmp_ca_file.path, ssl_client_cert: ENV.fetch('KAFKA_CLIENT_CERT'), ssl_client_cert_key: ENV.fetch('KAFKA_CLIENT_CERT_KEY'), ssl_verify_hostname: false, ) $producer = producer_kafka.async_producer(delivery_interval: 1) consumer_kafka = Kafka.new( seed_brokers: ENV.fetch('KAFKA_URL'), ssl_ca_cert_file_path: tmp_ca_file.path, ssl_client_cert: ENV.fetch('KAFKA_CLIENT_CERT'), ssl_client_cert_key: ENV.fetch('KAFKA_CLIENT_CERT_KEY'), ssl_verify_hostname: false, ) # Connect a consumer. Consumers in Kafka have a "group" id, which # denotes how consumers balance work. Each group coordinates # which partitions to process between its nodes. # For the demo app, there's only one group, but a production app # could use separate groups for e.g. processing events and archiving # raw events to S3 for longer term storage $consumer = consumer_kafka.consumer(group_id: with_prefix(GROUP_ID)) $recent_messages = [] start_consumer start_metrics at_exit do $producer.shutdown tmp_ca_file.unlink end end get '/' do erb :index end # This endpoint accesses in memory state gathered # by the consumer, which holds the last 10 messages received get '/messages' do content_type :json $recent_messages.map do |message, metadata| { offset: message.offset, partition: message.partition, message: message.value, topic: message.topic, metadata: metadata } end.to_json end # A sample producer endpoint. # It receives messages as http bodies on /messages, # and posts them directly to a Kafka topic. post '/messages' do if request.body.size.positive? request.body.rewind message = request.body.read $producer.produce(message, topic: with_prefix(KAFKA_TOPIC)) "received_message: #{message}" else status 400 body 'message was empty' end end # The consumer subscribes to the topic, and keeps the last 10 messages # received in memory, so the webapp can send them back over the api. # # Consumer group management in Kafka means that this app won't work correctly # if you run more than one dyno - Kafka will balance out the consumed partition # between processes, and the web API will return reads from arbitrary workers, # which will be incorrect. def start_consumer Thread.new do $consumer.subscribe(with_prefix(KAFKA_TOPIC)) begin $consumer.each_message do |message| $recent_messages << [message, {received_at: Time.now.iso8601}] $recent_messages.shift if $recent_messages.length > 10 puts "consumer received message! local message count: #{$recent_messages.size} offset=#{message.offset}" end rescue Exception => e puts 'CONSUMER ERROR' puts "#{e}\n#{e.backtrace.join("\n")}" exit(1) end end end # ruby-kafka exposes metrics over ActiveSupport::Notifications. # This demo app just logs them, but you could send them to librato or # another metrics service for graphing. def start_metrics Thread.new do ActiveSupport::Notifications.subscribe(/.*\.kafka$/) do |*args| event = ActiveSupport::Notifications::Event.new(*args) formatted = event.payload.map { |k, v| "#{k}=#{v}" }.join(' ') puts "at=#{event.name} #{formatted}" end end end
true
263ea33bb0765aef23a0e360114015ebcc2b55db
Ruby
JustynaStebel/ParkYourCar
/test/models/address_test.rb
UTF-8
719
2.59375
3
[]
no_license
require 'test_helper' class AddressTest < ActiveSupport::TestCase def setup @address = addresses(:krakow) end test "is invalid without city" do @address.city = nil assert @address.invalid? assert @address.errors.has_key?(:city) end test "is invalid without street" do @address.street = nil assert @address.invalid? assert @address.errors.has_key?(:street) end test "is invalid without zip_code" do @address.zip_code = nil assert @address.invalid? assert @address.errors.has_key?(:zip_code) end test "is invalid without proper zip_code format" do @address.zip_code = "1a34h6" assert @address.invalid? @address.errors[:zip_code] end end
true
0f8a18599412acf0e7bb0dfee8ca0b9ad77d9d21
Ruby
stupendousC/hotel
/lib/hotelFrontDesk.rb
UTF-8
19,317
3.015625
3
[]
no_license
require_relative 'lib_requirements.rb' require_relative 'room' require_relative 'reservation' require_relative 'block' require_relative 'dateRange' require_relative 'csvRecord' def reset_avail_id(array_of_objs:, class_name:) max = array_of_objs.max_by do |obj| obj.id end class_name.set_available_id(max.id) end class HotelFrontDesk include Helpers attr_reader :all_rooms, :all_reservations, :all_blocks, :num_rooms_in_hotel def initialize (num_rooms_in_hotel: 20, all_rooms: [], all_reservations: [], all_blocks: [], use_csv: false) if use_csv # Loading data from CSV & initiating objs using that @all_rooms = Room.load_all(full_path: ALL_ROOMS_CSV) @all_reservations = Reservation.load_all(full_path: ALL_RESERVATIONS_CSV) @all_blocks = Block.load_all(full_path: ALL_BLOCKS_CSV) # B/c CSV can't store objects, will need to reconnect obj attribs for all Room/Reservation/Block instances finish_setup_all_blocks finish_setup_all_reservations finish_setup_all_rooms # B/c CSV may come with assigned reservations & blocks, will need to make sure the id generator is updated to avoid overlap reset_avail_id(array_of_objs: @all_reservations, class_name: Reservation) reset_avail_id(array_of_objs: @all_blocks, class_name: Block) else # Making all new objects @all_rooms = all_rooms @all_reservations = all_reservations @all_blocks = all_blocks # set up Room instances @num_rooms_in_hotel = num_rooms_in_hotel @num_rooms_in_hotel.times do |i| room = Room.new(id: (i+1)) @all_rooms << room end end end def write_csv(all_rooms_target:, all_blocks_target:, all_reservations_target:) # RESERVATIONS CSV.open(all_reservations_target, "w") do |file| file << ["id", "room_id", "cost", "customer", "start_date", "end_date", "new_nightly_rate", "block_id"] all_reservations.each do |res| puts "SAVING #{res}..." file << [res.id, res.room_id, res.cost, res.customer, res.start_date, res.end_date, res.new_nightly_rate, res.block_id] end end # BLOCKS CSV.open(all_blocks_target, "w") do |file| file << ["id", "start_date", "end_date", "new_nightly_rate", "occupied_room_ids", "unoccupied_room_ids", "all_reservations_ids"] all_blocks.each do |block| puts "SAVING #{block}..." file << [block.id, block.date_range.start_date, block.date_range.end_date, block.new_nightly_rate, block.occupied_room_ids, block.unoccupied_room_ids, block.all_reservations_ids] end end # ROOMS CSV.open(all_rooms_target, "w") do |file| file << ["id", "nightly_rate", "occupied_nights_strs", "all_reservations_ids", "all_blocks_ids"] all_rooms.each do |room| puts "SAVING #{room}..." occupied_nights_strs = "" room.occupied_nights.each do |date_obj| occupied_nights_strs << date_obj.to_s occupied_nights_strs << " " end file << [room.id, room.nightly_rate, occupied_nights_strs, room.all_reservations_ids, room.all_blocks_ids] end end end def list_all_rooms list = "LIST OF ALL ROOMS:\n" @all_rooms.each { |room| list << " ROOM ##{room.id}\n" } return list end def find_avail_room(date_range) # returns 1 Room object that is unoccupied on date_range, or nil if no rooms if date_range.class != DateRange raise ArgumentError, "You must pass in a DateRange object" end return @all_rooms.find { |room| room.check_avail?(date_range)} end def find_all_avail_rooms(date_range) # returns all Room objects that are unoccupied on date_range, or nil if no rooms if date_range.class != DateRange raise ArgumentError, "You must pass in a DateRange object" end return @all_rooms.find_all { |room| room.check_avail?(date_range)} end def make_reservation(date_range:, customer:, new_nightly_rate: nil) # currently does not allow u to choose specific room. FUture improvement! if date_range.class != DateRange raise ArgumentError, "Requires a DateRange object" elsif !non_blank_string? customer raise ArgumentError, "Customer must have a name string!" elsif new_nightly_rate if !(non_zero_dollar_float? new_nightly_rate) raise ArgumentError, "New_nightly_rate must be a non-zero dollar float" end # I chose to allow new_nightly_rate to be higher number than standard rate end # go thru @all_rooms, result is either a room or nil room = find_avail_room(date_range) if !room raise ArgumentError, "No rooms at this inn" # I'd prefer to return nil but the rubric calls for raising errors end # By now, all args have passed validation tests reservation = Reservation.new(room_id: room.id, room: room, date_range: date_range, customer: customer, new_nightly_rate: new_nightly_rate) # update Room w/ make_unavail, add to Room.reservations room.make_unavail(date_range) room.all_reservations << reservation room.all_reservations_ids << reservation.id # update @all_reservations @all_reservations << reservation return reservation end def get_cost(reservation_id) if reservation_id.class == Integer reservation = @all_reservations.find { |res| res.id == reservation_id } else raise ArgumentError, "Reservation id needs to be an Integer" end if reservation == nil raise ArgumentError, "No reservations with id##{reservation_id} exists" end return reservation.cost end def list_reservations(date) if date.class != Date raise ArgumentError, "You must pass in a Date object" end # go thru @all_reservations results = @all_reservations.find_all { |reservation| reservation.date_range.date_in_range? (date) } if results == [] string = "\nNO RESERVATIONS FOR DATE #{date}" else string = "\nLISTING RESERVATIONS FOR DATE #{date}..." results.each { |reservation| string << "\n #{reservation}" } end return string end def list_available_rooms(date_range) # arg validation done in find_all_avail_rooms results = find_all_avail_rooms(date_range) if results == [] string = "\nNO ROOMS AVAILABLE FOR #{date_range.start_date} TO #{date_range.end_date}" else string = "\nLISTING AVAILABLE ROOMS FOR #{date_range.start_date} TO #{date_range.end_date}..." results.each { |room| string << "\n #{room}"} end return string end def get_room_from_id(id_int) if id_int.class != Integer raise ArgumentError, "Room id# should be an integer..." end room = @all_rooms.find { |room| room.id == id_int } if room return room else raise ArgumentError, "Room ##{id_int} does not exist" end end def get_rooms_from_ids (room_ids) # given room_ids in an array, return an array of Room instances if (room_ids.class != Array) || (room_ids.length == 0) raise ArgumentError, "Expecting argument of room_ids in an Array" # room_id.class == Integer will be checked in get_room_from_id later elsif num_rooms_in_hotel && (room_ids.length > num_rooms_in_hotel) raise ArgumentError, "You're asking for more rooms than in existence at this here hotel" elsif room_ids.uniq.length != room_ids.length raise ArgumentError, "Some of your args are duplicates, fix it plz" end rooms = room_ids.map { |id| get_room_from_id(id) } return rooms end def get_block_from_id(id_int) if id_int.class != Integer raise ArgumentError, "Block id# should be an integer..." end block = @all_blocks.find { |block| block.id == id_int } if block return block else raise ArgumentError, "Block ##{id_int} does not exist" end end def get_blocks_from_ids(block_ids) # given block_ids in an array, return an array of Block instances if (block_ids.class != Array) || (block_ids.length == 0) raise ArgumentError, "Expecting argument of block_ids in an Array" elsif block_ids.uniq.length != block_ids.length raise ArgumentError, "Some of your args are duplicates, fix it plz" end blocks = block_ids.map { |block_id| get_block_from_id(block_id) } return blocks end def get_reservation_from_id(id_int) if id_int.class != Integer raise ArgumentError, "Reservation id# should be an integer..." end res = @all_reservations.find { |res| res.id == id_int } if res return res else raise ArgumentError, "Reservation ##{id_int} does not exist" end end def get_reservations_from_ids(res_ids) # given res_ids in an array, return an array of Reservation instances if (res_ids.class != Array) || (res_ids.length == 0) raise ArgumentError, "Expecting argument of res_ids in an Array" elsif res_ids.uniq.length != res_ids.length raise ArgumentError, "Some of your args are duplicates, fix it plz" end reservations = res_ids.map { |res_id| get_reservation_from_id(res_id) } return reservations end def make_block(date_range:, room_ids:, new_nightly_rate:) # Validate date_range if date_range.class != DateRange raise ArgumentError, "Must pass in a DateRange object" else @date_range = date_range end # Validate room_ids[] if (room_ids.class != Array) || (room_ids.length == 0) raise ArgumentError, "Expecting argument of room_ids in an Array" elsif room_ids.length == 1 raise ArgumentError, "You can't make a block with just 1 room" elsif room_ids.length > MAX_BLOCK_SIZE raise ArgumentError, "Max block size allowed is #{MAX_BLOCK_SIZE}" else @room_ids = room_ids # continue validating as we check rooms' availability later end # Validate new_nightly_rate if !non_zero_dollar_float?(new_nightly_rate) raise ArgumentError, "We need a non-zero dollar Float for new_nightly_rate" elsif new_nightly_rate >= STANDARD_RATE puts "Shouldn't the new_nightly_rate be a discount? compared to standard rate of #{STANDARD_RATE}?" # I decided not to raise error because CLI might take in a standard_rate from user end # Checking rooms' actual availability rooms_ready_for_block = [] rooms = get_rooms_from_ids(room_ids) rooms.each do |room| room.occupied_nights.each do |occupied_night| if date_range.date_in_range?(occupied_night) unless occupied_night == date_range.end_date # Not a real clash b/c one has checkin vs the other has checkout raise ArgumentError, "Can't block Room ##{room.id} b/c it's occupied on #{occupied_night}" end end end # room is available for block's date range rooms_ready_for_block << room end # Make block & update @all_blocks block = Block.new(date_range: date_range, new_nightly_rate: new_nightly_rate, room_ids: room_ids, rooms: rooms_ready_for_block) @all_blocks << block # Update Room objects's occupied_nights so no one else can take it rooms_ready_for_block.each do |room| room.make_unavail(date_range) room.add_block_ids(block) end return block end def make_reservation_from_block(room_id:, block_id:, customer:) if !non_zero_integer? room_id raise ArgumentError, "We need a non-zero Integer for the room_id" elsif !non_zero_integer? block_id raise ArgumentError, "We need a non-zero Integer for the block_id" elsif !non_blank_string? customer raise ArgumentError, "Customer must have a name string!" end # Does this block have this room available? room_id = room_id.to_i block_id = block_id.to_i block = get_block_from_id(block_id) if block.unoccupied_room_ids.include? room_id # no need to update Room obj's occupied_nights, they're already marked when Block was created # Make Reservation object, then update attribs for Block obj, Room obj, and Hotel obj room = get_room_from_id(room_id) new_res = Reservation.new(room_id: room_id, room:room, date_range:block.date_range, customer: customer, new_nightly_rate: block.new_nightly_rate, block: block, block_id: block.id) block.occupied_rooms << room block.occupied_room_ids << room_id block.unoccupied_room_ids.delete(room_id) block.unoccupied_rooms.delete(room) room.all_reservations << new_res room.all_reservations_ids << new_res.id @all_reservations << new_res block.all_reservations << new_res block.all_reservations_ids << new_res.id elsif block.occupied_room_ids.include? room_id raise ArgumentError, "Room ##{room_id} is already taken. Try these other rooms: #{block.unoccupied_room_ids}" else raise ArgumentError, "Room ##{room_id} is not in a Block, plz use regular .make_reservation()" end return new_res end def list_available_rooms_from_block(block_id) block = get_block_from_id(block_id) if block.unoccupied_room_ids != [] string = "\nLISTING AVAILABLE ROOMS FOR BLOCK #{block_id}..." block.unoccupied_room_ids.each { |room_id| string << "\n Room ##{room_id}"} else string = "\nNO ROOMS AVAILABLE FOR BLOCK #{block_id}" end return string end def change_room_rate(room_id:, new_nightly_rate:) room_obj = get_room_from_id(room_id) if non_zero_dollar_float? new_nightly_rate room_obj.change_rate(new_nightly_rate: new_nightly_rate) # need to update whichever reservations that are affected by this new rate update_costs(room_id: room_id, new_room_rate: new_nightly_rate) else raise ArgumentError, "new_nightly_rate must be a non-zero integer" end end def update_costs(room_id:, new_room_rate:) # recalculate costs for all existing reservations, unless lower block rate is in effect affected_reservations = @all_reservations.find_all { |res| res.room_id == room_id } affected_reservations.each { |res| # I didn't want to do a long (a && b) || (c && d), I'd rather have it easy to read if res.new_nightly_rate && (res.new_nightly_rate > new_room_rate) # compare new rate to existing discounted rate change_cost = true elsif (res.new_nightly_rate == nil) && (STANDARD_RATE > new_room_rate) # compare new rate to default standard rate change_cost = true end if change_cost res.new_nightly_rate = new_room_rate res.calc_cost end } end ### EVERYTHING BELOW THIS LINE IS FOR CSV or COMMAND-LINE INTERFACE IN MAIN.RB ### ### NO VALIDATION OR UNIT TESTS WRITTEN due to time ### def finish_setup_all_reservations # For Reservation objs in @all_reservations, will need to add their own @block and @room @all_reservations.each do |res_obj| res_obj.room = get_room_from_id(res_obj.room_id) if res_obj.block_id res_obj.block = get_block_from_id(res_obj.block_id) end end end def finish_setup_all_blocks # For Block objs in @all_blocks, will need to add their own @occupied_rooms, @unoccupied_rooms, and @all_reservations @all_blocks.each do |block_obj| if block_obj.occupied_room_ids != [] block_obj.occupied_rooms = get_rooms_from_ids(block_obj.occupied_room_ids) end if block_obj.unoccupied_room_ids != [] block_obj.unoccupied_rooms = get_rooms_from_ids(block_obj.unoccupied_room_ids) end if block_obj.all_reservations_ids != [] block_obj.all_reservations = get_reservations_from_ids(block_obj.all_reservations_ids) end end end def finish_setup_all_rooms # For Room objs in @all_rooms, will need to add their own @all_reservations and @all_blocks @all_rooms.each do |room_obj| if room_obj.all_reservations_ids != [] room_obj.all_reservations = get_reservations_from_ids(room_obj.all_reservations_ids) end if room_obj.all_blocks_ids != [] room_obj.all_blocks = get_blocks_from_ids(room_obj.all_blocks_ids) end end end def hash_of_all_methods return { A: "List all rooms", B: "List available rooms", C: "Make reservation", D: "List reservations", E: "Get cost", F: "Make block", G: "Make reservation from block", H: "List available rooms from block", I: "Change room rate", Q: "Quit" } end def show_menu puts "\n############################" puts "MAIN MENU:" hash_of_all_methods.each do |key, value| puts " #{key}: #{value}" end puts "############################\n" end def prompt_for_input(statement: "PLEASE MAKE A SELECTION") puts statement print ">>> " choice = gets.chomp return choice.upcase end def prompt_for_date date = prompt_for_input(statement: "Please provide the date, as YYYY-MM-DD") return Date.parse(date) end def prompt_for_date_range start_date = prompt_for_input(statement: "Please provide the start date, as YYYY-MM-DD") end_date = prompt_for_input(statement: "Please provide the end date, as YYYY-MM-DD") start_date = Date.parse(start_date) end_date = Date.parse(end_date) date_range = DateRange.new(start_date_obj: start_date, end_date_obj: end_date) return date_range end def prompt_for_new_nightly_rate new_nightly_rate = prompt_for_input(statement: "Is there a new nightly rate? Else press enter") if new_nightly_rate == "" return STANDARD_RATE else float_or_nil = checkCurrency(new_nightly_rate) if float_or_nil return float_or_nil else raise ArgumentError, "Not a valid dollar float? Investigate!" end end end def prompt_for_id(statement: "What's the id? ") input = prompt_for_input(statement: statement) if input.to_i != input.to_f raise ArgumentError, "Invalid, must be an Integer" elsif non_zero_integer? input.to_i return input.to_i else raise ArgumentError, "Invalid input, that's not even a number" end end def prompt_for_room_id(statement: "What is the room id?") return prompt_for_id(statement: statement) end def prompt_for_block_id(statement: "What is the block id?") return prompt_for_id(statement: statement) end def prompt_for_reservation_id(statement: "What is the reservation id?") return prompt_for_id(statement: statement) end def prompt_for_array_of_ids(max_allowed: MAX_BLOCK_SIZE) results = [] statement = "Please enter the id number, or Q to quit" elements = 0 until elements >= 5 id = prompt_for_input(statement: statement) if id.to_i != id.to_f puts "Nope! Invalid entry!" return results elsif non_zero_integer? id.to_i results << id.to_i elsif ["Q", "q"].include? id return results end elements += 1 end return results end end
true
3b750997f74c3dca43a50e211b37163f9a16850d
Ruby
bitliner/constituent-parser
/lib/opener/constituent_parser/cli.rb
UTF-8
1,998
2.8125
3
[ "Apache-2.0" ]
permissive
module Opener class ConstituentParser ## # CLI wrapper around {Opener::ConstituentParser} using OptionParser. # # @!attribute [r] options # @return [Hash] # @!attribute [r] option_parser # @return [OptionParser] # class CLI attr_reader :options, :option_parser ## # @param [Hash] options # def initialize(options = {}) @options = DEFAULT_OPTIONS.merge(options) @option_parser = OptionParser.new do |opts| opts.program_name = 'constituent-parser' opts.summary_indent = ' ' opts.on('-h', '--help', 'Shows this help message') do show_help end opts.on('-v', '--version', 'Shows the current version') do show_version end opts.on( '-l', '--language [VALUE]', 'Uses this specific language' ) do |value| @options[:language] = value end opts.separator <<-EOF Examples: cat input_file.kaf | #{opts.program_name} cat input_file.kaf | #{opts.program_name} -l nl EOF end end ## # @param [String] input # def run(input) option_parser.parse!(options[:args]) runner = ConstituentParser.new(options) stdout, stderr, process = runner.run(input) if process if process.success? puts stdout STDERR.puts(stderr) unless stderr.empty? else abort stderr end else puts stdout end end private ## # Shows the help message and exits the program. # def show_help abort option_parser.to_s end ## # Shows the version and exits the program. # def show_version abort "#{option_parser.program_name} v#{VERSION} on #{RUBY_DESCRIPTION}" end end # CLI end # ConstituentParser end # Opener
true
ad64d6af9d7c73d028069e3f8f7c563536df7f38
Ruby
abigezunt/ga-rspec-quiz
/spec/credit-card_spec.rb
UTF-8
1,550
3
3
[]
no_license
require 'spec_helper' require_relative '../lib/credit-card' describe CreditCard do subject {CreditCard.new(5290_1196_4306_7693, '1113', 623, "Matt Clement", 78782)} it "should be valid" do subject.valid?.should be true end end describe "Invalid Credit Card" do let(:wrong_number_card) {CreditCard.new(543_2874_5678_087, '1213', 623, "Matt Clement", 02143)} it "should return an error when the card number has not sixteen digits" do wrong_number_card.valid?.should eq "Error: card number is not 16 digits long." end end describe "Expired Credit Card" do let(:expired_card) {CreditCard.new(4716_5316_2702_8476, '0608', 623, "Matt Clement", 02143)} it "should return an error when the card has expired" do expired_card.valid?.should eq "Error: card is expired." end end describe "Nameless Credit Card" do let(:nameless_card) {CreditCard.new(4716_5316_2702_8476, '1113', 623, 02143, 78726)} it "should return an error when no name is passed in" do nameless_card.valid?.should eq "Error: not a valid name." end end describe "Bad Zip Code" do let(:zipless_card) {CreditCard.new(4716_5316_2702_8476, '1113', 623, "Amal Hussein", 7876)} it "should return an error when an invalid zip code is passed in" do zipless_card.valid?.should eq "Error: zip code invalid." end end describe "invalid card number" do let(:invalid_card) {CreditCard.new(1234_5678_9012_3456, '1014', 623, "Matt Clement", 92143)} it "should check the card number against an algorithm for validity" do invalid_card.valid?.should eq "Error: invalid card number." end end
true
7d8eda431ab7bfadd983dafb7099bf018fadb464
Ruby
FHappy/Project-Euler-Exercises
/problem4.rb
UTF-8
1,012
4.125
4
[]
no_license
# # PROMPT # A palindromic number reads the same both ways. The largest palindrome made # from the product of two 2-digit numbers is 9009 = 91 × 99. # # Find the largest palindrome made from the product of two 3-digit numbers. # SOLUTION require 'pry' # find all palindromes in range of 3 digit products palindromes = [] (100001..998001).each do |num| str = num.to_s if str == str.reverse palindromes.push(num) end end # work backwards and find if any have a 3 digit factor (also working backwords) def find_largest_palindrome(pals) answer = 0 pals.reverse_each do |palin| # loop backwards over all three digit integers (100..999).reverse_each do |three_dig| factor = palin / three_dig # determine if current palindrome has a three digit factor and corresponding # factor pair is also three digits if palin % three_dig == 0 && factor.to_s.length == 3 answer = palin return answer end end end end find_largest_palindrome(palindromes)
true
de32197c2a13ea4416bd898ef98b45d56f0e031a
Ruby
AlexUkPC/The-Well-Grounded-Rubyist
/Chapter11/11.2.2_Simple_matching_with_literal_regular_expressions.rb
UTF-8
326
3
3
[]
no_license
p /abc/.match?("The alphabet starts with abc.") p "The alphabet starts with abc.".match?(/abc/) puts "Match!" if /abc/ =~ "The alphabet starts with abc." puts "Match!" if "The alphabet starts with abc." =~ /abc/ p /abc/.match("The alphabet starts with abc.") p /abc/.match("def") p "The alphabet starts with abc." =~ /abc/
true
5090400c274ea66f2a0ce0441191abe1a3fd67f2
Ruby
szich/simplesite
/script/import.rb
UTF-8
2,709
2.578125
3
[]
no_license
# To use this script # 1) Place this file in the RAILS_ROOT/script directory. # 2) Place the epcp_database.csv file in the same directory. # 3) Open the terminal in the script directory (if you haven't already) # 4) Run it using: ./runner -e production 'load "./import.rb"' require 'rubygems' require 'faster_csv' require 'digest/sha1' # mock for testing # class User # attr_accessor :is_donor, :is_business, :login, :password, :business_name, :notes, :contact_person, :address, :city, :state, :zip, :phone_primary, :fax_primary, :relationship_to_school, :website, :contact_person, :contact_person_title, :email_primary, :fax # def User.transaction() yield end # def save() true end # end unknown_disciplne = Discipline.find_by_name('Unknown') def make_login(strings) new_login = [] strings.each do |s| next unless s; new_login << s.gsub('.', '').gsub(' ', '') end new_login.join('.').downcase end def make_password(length=7, key="abcedfghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ123456789") pass = "*" * length srand = Time.now.to_i length.times {|i| pass[i] = key[rand(key.length)]} return pass end # Main entry point User.transaction do count = 1 FasterCSV.foreach('epcp_database.csv', {:headers => true, :header_converters => :symbol } ) do |row| count = count + 1 user = User.new user.first_name = row[:firstname] user.last_name = row[:lastname] user.job_title = row[:jobtitle] user.business_name = row[:company] user.business_address = row[:address1].to_s user.business_address2 = row[:address2].to_s user.business_city = row[:city] user.business_state = row[:state] user.business_zip = row[:zip] user.phone = row[:phone] user.business_fax = row[:fax] user.email = row[:email] user.member_since = row[:membershipyear] user.login = make_login([user.first_name, user.last_name]) # user.first_name.downcase + '.' + user.last_name.downcase user.password = make_password user.password_confirmation = user.password d = Discipline.find_by_name(row[:category]) user.discipline = d ? d : unknown_disciplne user.is_active = 1 user.can_manage_content = 0 user.can_manage_users = 0 user.show_personal_info = 0 if user.save puts "#{count},#{user.id},#{user.first_name},#{user.last_name},#{user.email},#{user.login},#{user.password}" else raise(ScriptError, "Could not save '#{user.first_name} #{user.last_name}' row #{count}, errors #{user.errors.each do |err| puts err end} rolling back ENTIRE import.") end end end # transaction # raw csv col names: #LastName,FirstName,Category,JobTitle,Company,Address1,Address2,City,State,ZIP,Phone,Fax,EMail,OSB,WSB,CFP,MembershipYear
true
6fbfdb7cc3806fae566b6622a75c68d5e056b75c
Ruby
afeiship/ruby-programing-book-notes
/docs/2018-08/2018-08-05/001-area_volume.rb
UTF-8
280
2.765625
3
[]
no_license
# = begin # 这里可以写一大断注释 # = end x = 10 y = 20 z = 30 area = (x*y + y*z + z*x) * 2 volumn = x * y * z print "表面积=", area, "\n"; print "体积=", volumn, "\n"; # cd /Users/feizheng/github/ruby-programing-book-notes/docs/2018-08 # ruby area_volume.rb
true
b2c7031c0b45d5a48b67f355893d8289a45a5173
Ruby
doshea/SenaTest
/db/seeds.rb
UTF-8
7,520
2.515625
3
[]
no_license
require 'httparty' require 'json' reset_containers = false reset_politicians = false seed_start_time = Time.now puts "\nBEGINNING SEED" puts "-------------" User.delete_all if reset_politicians Politician.delete_all else puts 'Politicians not deleted to save time.' end if reset_containers State.destroy_all Chamber.destroy_all Party.destroy_all end puts "\nOld records deleted." #Seed two admin users and two test users puts "\nSeeding Users..." User.create(email: '[email protected]', username: 'doshea', password: 'qwerty', password_confirmation: 'qwerty', is_admin: true) User.create(email: '[email protected]', username: 'jgonchar', password: 'qwerty', password_confirmation: 'qwerty', is_admin: true) User.create(email: '[email protected]', username: 'test', password: 'qwerty', password_confirmation: 'qwerty', is_admin: false) User.create(email: '[email protected]', username: 'test2', password: 'qwerty', password_confirmation: 'qwerty', is_admin: false) puts "Users seeded." if reset_containers #Seed all 50 states puts "\nSeeding States..." State.create(abbreviation: "AR",name: "Arkansas") State.create(abbreviation: "DE",name: "Delaware") State.create(abbreviation: "FL",name: "Florida") State.create(abbreviation: "GA",name: "Georgia") State.create(abbreviation: "KS",name: "Kansas") State.create(abbreviation: "LA",name: "Louisiana") State.create(abbreviation: "MD",name: "Maryland") State.create(abbreviation: "MO",name: "Missouri") State.create(abbreviation: "MS",name: "Mississippi") State.create(abbreviation: "NC",name: "North Carolina") State.create(abbreviation: "OK",name: "Oklahoma") State.create(abbreviation: "SC",name: "South Carolina") State.create(abbreviation: "TN",name: "Tennessee") State.create(abbreviation: "TX",name: "Texas") State.create(abbreviation: "WV",name: "West Virginia") State.create(abbreviation: "AL",name: "Alabama") State.create(abbreviation: "CT",name: "Connecticut") State.create(abbreviation: "IA",name: "Iowa") State.create(abbreviation: "IL",name: "Illinois") State.create(abbreviation: "IN",name: "Indiana") State.create(abbreviation: "ME",name: "Maine") State.create(abbreviation: "MI",name: "Michigan") State.create(abbreviation: "MN",name: "Minnesota") State.create(abbreviation: "NE",name: "Nebraska") State.create(abbreviation: "NH",name: "New Hampshire") State.create(abbreviation: "NJ",name: "New Jersey") State.create(abbreviation: "NY",name: "New York") State.create(abbreviation: "OH",name: "Ohio") State.create(abbreviation: "RI",name: "Rhode Island") State.create(abbreviation: "VT",name: "Vermont") State.create(abbreviation: "WI",name: "Wisconsin") State.create(abbreviation: "CA",name: "California") State.create(abbreviation: "CO",name: "Colorado") State.create(abbreviation: "NM",name: "New Mexico") State.create(abbreviation: "NV",name: "Nevada") State.create(abbreviation: "UT",name: "Utah") State.create(abbreviation: "AZ",name: "Arizona") State.create(abbreviation: "ID",name: "Idaho") State.create(abbreviation: "MT",name: "Montana") State.create(abbreviation: "ND",name: "North Dakota") State.create(abbreviation: "OR",name: "Oregon") State.create(abbreviation: "SD",name: "South Dakota") State.create(abbreviation: "WA",name: "Washington") State.create(abbreviation: "WY",name: "Wyoming") State.create(abbreviation: "HI",name: "Hawaii") State.create(abbreviation: "AK",name: "Alaska") State.create(abbreviation: "KY",name: "Kentucky") State.create(abbreviation: "MA",name: "Massachusetts") State.create(abbreviation: "PA",name: "Pennsylvania") State.create(abbreviation: "VA",name: "Virginia") puts "Voting States seeded." #Seed Washington DC and the other 5 nonvoting states State.create(abbreviation: "DC",name: "Washington, D.C.", nonvoting: true) State.create(abbreviation: "MP",name: "Northern Mariana Islands", nonvoting: true) State.create(abbreviation: "PR",name: "Puerto Rico", nonvoting: true) State.create(abbreviation: "AS",name: "American Samoa", nonvoting: true) State.create(abbreviation: "VI",name: "US Virgin Islands", nonvoting: true) State.create(abbreviation: "GU",name: "Guam", nonvoting: true) puts "Non-voting States seeded." #Seed the two main political parties and Independent puts "\nSeeding Parties..." Party.create(name: 'Democratic Party', adjective: 'Democratic', member_noun: 'Democrat') Party.create(name: 'Republican Party', adjective: 'Republican', member_noun: 'Republican') Party.create(name: 'Independent', adjective: 'Independent', member_noun: 'Independent') puts "Parties seeded." #Seed the two chambers of Congress puts "\nSeeding Chambers(House and Senate)..." Chamber.create(name: 'Senate', short_name: 'senate', male_title: 'senator', female_title: 'senator', neuter_title: 'senator') Chamber.create(name: 'House of Representatives', short_name: 'house', male_title: 'congressman', female_title: 'congresswoman', neuter_title: 'congressperson') puts "Chambers seeded." end #Seed the members of both houses of Congress Chamber.all.each do |chamber| settings = { chamber: chamber.short_name, apikey: ENV['SUNLIGHT_KEY'], per_page: 50, page: 0 } puts "\nSeeding #{chamber.neuter_title}s..." counter = 1 total_results = nil while total_results.nil? || (counter <= total_results) page_start = settings[:per_page] * (settings[:page]-1) page_end = settings[:per_page] * settings[:page] if counter > page_end settings[:page] += 1 page_start = settings[:per_page] * (settings[:page]-1) page_end = settings[:per_page] * settings[:page] url = "http://congress.api.sunlightfoundation.com/legislators?chamber=#{settings[:chamber]}&apikey=#{settings[:apikey]}&per_page=#{settings[:per_page]}&page=#{settings[:page]}" data = HTTParty.get(url) total_results ||= data['count'] results = data['results'] end p_h = results[counter-page_start-1] if reset_politicians || Politician.find_by_govtrack_id(p_h['govtrack_id']).nil? state = State.find_by_abbreviation(p_h['state']) if state.present? politician = Politician.create( first_name: p_h['first_name'], last_name: p_h['last_name'], middle_name: p_h['middle_name'], nickname: p_h['nickname'], gender: p_h['gender'], in_office: p_h['in_office'], senate_class: p_h['senate_class'], birthday: p_h['birthday'], govtrack_id: p_h['govtrack_id'], seniority: p_h['state_rank'] == 'senior' if p_h['state_rank'].present?, name_suffix: p_h['name_suffix'] ) State.find_by_abbreviation(p_h['state']).politicians << politician Party.find_by_party_initial(p_h['party']).politicians << politician chamber.politicians << politician end end counter += 1 end puts "#{chamber.neuter_title.capitalize}s seeded." end #Add images to each rep from Govtrack new_counter = 1 needs_image = reset_politicians ? Politician.all : Politician.where('image = ?', nil) needs_image.each do |p| # if new_counter < 20 puts "\nAdding image to #{new_counter.ordinalize} politician" puts "#{p.first_name} #{p.last_name}" p.get_govtrack_image! new_counter += 1 # end end puts "\n-------------" puts "SEED COMPLETE" puts "\nSeeding took ~ #{distance_of_time_in_words_to_now(seed_start_time, true)}" #this line required an import of the DateHelper in the Rakefile
true
39f0d77f011bee6e6534c62792661ff77f9a5483
Ruby
Dariusz-Choinski/tdd-backbone-demo
/lib/modules/router/routes.rb
UTF-8
560
2.890625
3
[ "MIT" ]
permissive
require_relative '../../../config/routes.map' require_relative 'route' class Routes include RoutesMap attr_accessor :routes def initialize @routes = [] build_map_convertion_methods convert_maps_to_route_objects end private def convert_maps_to_route_objects map end Methods = %w( get post put delete).freeze def build_map_convertion_methods Methods.each do |method| define_singleton_method(method) do |map| @routes << Route.new(method.upcase, map.keys.first, map.values.first) end end end end
true
a4b40e7efdd5c26cf94a70a61e97fe5f0b660fee
Ruby
grubern/rtesseract
/lib/processors/mini_magick.rb
UTF-8
873
2.59375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# encoding: UTF-8 # Add to rtesseract a image manipulation with MiniMagick module RTesseract::Processor::MiniMagickProcessor def self.setup require 'mini_magick' end def self.a_name?(name) %w(mini_magick MiniMagickProcessor).include?(name.to_s) end def self.image_to_tif(source, _points = {}) tmp_file = Tempfile.new(['', '.tif']) cat = source.is_a?(Pathname) ? read_with_processor(source.to_s) : source cat.format('tif') do |c| c.compress 'None' c.alpha 'off' end cat.crop("#{_points[:w]}x#{_points[:h]}+#{_points[:x]}+#{_points[:y]}") if _points.is_a?(Hash) && _points.values.compact != [] cat.alpha 'off' cat.write tmp_file.path.to_s tmp_file end def self.read_with_processor(path) MiniMagick::Image.open(path.to_s) end def self.image?(object) object.class == MiniMagick::Image end end
true
7bce2a6cc57d8b63d6a8235d475f30f1d80f4959
Ruby
RolandStuder/odin_project_solutions
/oop/tic-tac-toe/lib/ai_player.rb
UTF-8
2,222
3.28125
3
[]
no_license
require 'pry' class AIPlayer < Player def initialize(name, strategy = nil) super @moves = [] @winning_sequences = [] @strategy = strategy end def prompt_for_action(moves) @moves = moves # return random_available_move if @moves.length == 0 case @strategy when :both avoid_loosing || winning_strategy || random_available_move when :recommendation recommendation || random_available_move else random_available_move end end def recommendation recommendations = @winning_sequences.reduce(Hash.new(0)) do |rec, seq| if next_move_available?(seq) && winning_for_me?(seq) && (@moves - seq).empty? rec[seq[@moves.length]] += 1 elsif next_move_available?(seq) && winning_for_oppenent?(seq) && (@moves - seq).empty? rec[seq[@moves.length]] -= 2 end rec end unless recommendations.empty? return recommendations.max_by{|k,v| v}[0][0] else return nil end end def winning_strategy my_winning_sequences = @winning_sequences.select do |seq| (@moves - seq).empty? && next_move_available?(seq) && winning_for_me?(seq) end my_winning_sequences.empty? ? nil : my_winning_sequences.sample[@moves.length][0] end def wins(moves) super @winning_sequences << moves end def loses(moves) super @winning_sequences << moves end def avoid_loosing my_losing_sequences = @winning_sequences.select do |seq| (@moves - seq).empty? && next_move_available?(seq) && winning_for_oppenent?(seq) end my_losing_moves = my_losing_sequences.map { |seq| seq[@moves.length][0] } good_moves = available_moves - my_losing_moves good_moves.empty? ? nil : good_moves.sample end def next_move_available?(seq) if seq.length <= @moves.length return false else return [email protected]?(seq[@moves.length]) end end def winning_for_me?(seq) seq.last[1] == @tile end def winning_for_oppenent?(seq) seq.last[1] != @tile end def available_moves occupied = @moves.map { |move| move[0]} (1..9).to_a - occupied end def random_available_move available_moves.sample end end
true
b484b4fbf721e764670c3aba0ca6b3bbfb61d831
Ruby
raravena80/zulia
/pangram/pangram.rb
UTF-8
583
3.875
4
[ "Apache-2.0", "MIT" ]
permissive
#!/usr/bin/env ruby # This solution is using ascii codes in decimal # pangram = "The quick brown fox jumps over the lazy dog" pangram.tr!(' ,!@#$%', '').downcase! pangramArray = pangram.split("") letters = [] pangramArray.each do |c| if (c.ord >= 97 || c.ord <= 122) letters.push(c.ord) end end # sort and get all uniques letters.uniq!.sort! l = letters.length - 1 ispangram = true # Calculate if numbers are consecutive # If they are not then it's not a pangram for i in 0..(l - 1) if letters[i] + 1 != letters[i + 1] ispangram = false end end puts ispangram
true
fc70109681f1d3d6120e721e27a8aa47b6d47a5b
Ruby
tsonntag/interfaces
/lib/interfaces/zip_filter.rb
UTF-8
566
2.515625
3
[ "MIT" ]
permissive
require 'zip' module Interfaces class ZipFilter < Filter attribute :zip_filename validates_presence_of :zip_filename def do_filter_files pathes dir = File.dirname pathes.first target_path = File.join dir, zip_filename Zip::ZipOutputStream.open(target_path) do |zos| pathes.each do |path| zos.put_next_entry File.basename(path) zos.write IO.read(path) end end logger.info{"#{self}: zipped #{Utils.basenames(pathes).join(',')} => #{zip_filename}"} [target_path] end end end
true
18ca004d7f7ab4c36da52013fa68872145a39008
Ruby
LE-HU/odin_project_le-hu
/archive/tictactoe_eh.rb
UTF-8
806
3.875
4
[]
no_license
class TicTacToe def initialize(board) @board = board end def play n = 0 while n < 4 # 4 moves for now n += 1 def display_board(board) puts " #{board[0]} | #{board[1]} | #{board[2]} " puts separator = "-----------------" puts " #{board[3]} | #{board[4]} | #{board[5]} " puts separator puts " #{board[6]} | #{board[7]} | #{board[8]} " end end end end class Board attr_accessor :play_area def initialize() @play_area = [1, 2, 3, 4, 5, 6, 7, 8, 9] end def make_move(player, spot) end end player1 = "X" player2 = "O" ######################################## x = Board.new x.play_area[0] = player1 x.play_area[4] = player2 puts "" print x.play_area puts "" puts "" x.display_board puts ""
true
c700ec229fac71324bb1607dd1eeac3901c20e7d
Ruby
jstirk/pennytel
/lib/pennytel/default.rb
UTF-8
17,007
2.765625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'xsd/qname' # {http://pennytel.com}PennyTelAccount # balance - SOAP::SOAPFloat # blocked - SOAP::SOAPBoolean # currency - SOAP::SOAPString # lastUsageDate - SOAP::SOAPDateTime # others - SOAP::SOAPString # zeroBalanceDate - SOAP::SOAPDateTime class PennyTelAccount attr_accessor :balance attr_accessor :blocked attr_accessor :currency attr_accessor :lastUsageDate attr_accessor :others attr_accessor :zeroBalanceDate def initialize(balance = nil, blocked = nil, currency = nil, lastUsageDate = nil, others = nil, zeroBalanceDate = nil) @balance = balance @blocked = blocked @currency = currency @lastUsageDate = lastUsageDate @others = others @zeroBalanceDate = zeroBalanceDate end end # {http://pennytel.com}PennyTelContact # displayName - SOAP::SOAPString # emailAddress - SOAP::SOAPString # faxNumber - SOAP::SOAPString # firstName - SOAP::SOAPString # group - SOAP::SOAPString # homeAddress - SOAP::SOAPString # homeCity - SOAP::SOAPString # homeCountry - SOAP::SOAPString # homeNumber - SOAP::SOAPString # homeState - SOAP::SOAPString # lastName - SOAP::SOAPString # mobileNumber - SOAP::SOAPString # officeAddress - SOAP::SOAPString # officeCity - SOAP::SOAPString # officeCountry - SOAP::SOAPString # officeNumber - SOAP::SOAPString # officeState - SOAP::SOAPString # others - SOAP::SOAPString # pennyTelNumber - SOAP::SOAPString # webSite - SOAP::SOAPString class PennyTelContact attr_accessor :displayName attr_accessor :emailAddress attr_accessor :faxNumber attr_accessor :firstName attr_accessor :group attr_accessor :homeAddress attr_accessor :homeCity attr_accessor :homeCountry attr_accessor :homeNumber attr_accessor :homeState attr_accessor :lastName attr_accessor :mobileNumber attr_accessor :officeAddress attr_accessor :officeCity attr_accessor :officeCountry attr_accessor :officeNumber attr_accessor :officeState attr_accessor :others attr_accessor :pennyTelNumber attr_accessor :webSite def initialize(displayName = nil, emailAddress = nil, faxNumber = nil, firstName = nil, group = nil, homeAddress = nil, homeCity = nil, homeCountry = nil, homeNumber = nil, homeState = nil, lastName = nil, mobileNumber = nil, officeAddress = nil, officeCity = nil, officeCountry = nil, officeNumber = nil, officeState = nil, others = nil, pennyTelNumber = nil, webSite = nil) @displayName = displayName @emailAddress = emailAddress @faxNumber = faxNumber @firstName = firstName @group = group @homeAddress = homeAddress @homeCity = homeCity @homeCountry = homeCountry @homeNumber = homeNumber @homeState = homeState @lastName = lastName @mobileNumber = mobileNumber @officeAddress = officeAddress @officeCity = officeCity @officeCountry = officeCountry @officeNumber = officeNumber @officeState = officeState @others = others @pennyTelNumber = pennyTelNumber @webSite = webSite end end # {http://pennytel.com}getSmartDialSettings # id - SOAP::SOAPString # password - SOAP::SOAPString # options - SOAP::SOAPString class GetSmartDialSettings attr_accessor :id attr_accessor :password attr_accessor :options def initialize(id = nil, password = nil, options = []) @id = id @password = password @options = options end end # {http://pennytel.com}getSmartDialSettingsResponse class GetSmartDialSettingsResponse < ::Array end # {http://pennytel.com}getAccount # id - SOAP::SOAPString # password - SOAP::SOAPString class GetAccount attr_accessor :id attr_accessor :password def initialize(id = nil, password = nil) @id = id @password = password end end # {http://pennytel.com}getAccountResponse # getAccountReturn - PennyTelAccount class GetAccountResponse attr_accessor :getAccountReturn def initialize(getAccountReturn = nil) @getAccountReturn = getAccountReturn end end # {http://pennytel.com}addSmartDialForward # id - SOAP::SOAPString # password - SOAP::SOAPString # access - SOAP::SOAPString # numbers - SOAP::SOAPString class AddSmartDialForward attr_accessor :id attr_accessor :password attr_accessor :access attr_accessor :numbers def initialize(id = nil, password = nil, access = [], numbers = []) @id = id @password = password @access = access @numbers = numbers end end # {http://pennytel.com}addSmartDialForwardResponse class AddSmartDialForwardResponse def initialize end end # {http://pennytel.com}getSmartDialForward # id - SOAP::SOAPString # password - SOAP::SOAPString class GetSmartDialForward attr_accessor :id attr_accessor :password def initialize(id = nil, password = nil) @id = id @password = password end end # {http://pennytel.com}getSmartDialForwardResponse class GetSmartDialForwardResponse < ::Array end # {http://pennytel.com}removeSmartDialForward # id - SOAP::SOAPString # password - SOAP::SOAPString # access - SOAP::SOAPString class RemoveSmartDialForward attr_accessor :id attr_accessor :password attr_accessor :access def initialize(id = nil, password = nil, access = []) @id = id @password = password @access = access end end # {http://pennytel.com}removeSmartDialForwardResponse class RemoveSmartDialForwardResponse def initialize end end # {http://pennytel.com}setSmartDialCustomCLI # id - SOAP::SOAPString # password - SOAP::SOAPString # customcli - SOAP::SOAPString class SetSmartDialCustomCLI attr_accessor :id attr_accessor :password attr_accessor :customcli def initialize(id = nil, password = nil, customcli = nil) @id = id @password = password @customcli = customcli end end # {http://pennytel.com}setSmartDialCustomCLIResponse class SetSmartDialCustomCLIResponse def initialize end end # {http://pennytel.com}addAllowQuickDial # id - SOAP::SOAPString # password - SOAP::SOAPString # numbers - SOAP::SOAPString class AddAllowQuickDial attr_accessor :id attr_accessor :password attr_accessor :numbers def initialize(id = nil, password = nil, numbers = []) @id = id @password = password @numbers = numbers end end # {http://pennytel.com}addAllowQuickDialResponse class AddAllowQuickDialResponse def initialize end end # {http://pennytel.com}removeAllowQuickDial # id - SOAP::SOAPString # password - SOAP::SOAPString # numbers - SOAP::SOAPString class RemoveAllowQuickDial attr_accessor :id attr_accessor :password attr_accessor :numbers def initialize(id = nil, password = nil, numbers = []) @id = id @password = password @numbers = numbers end end # {http://pennytel.com}removeAllowQuickDialResponse class RemoveAllowQuickDialResponse def initialize end end # {http://pennytel.com}getAllowQuickDial # id - SOAP::SOAPString # password - SOAP::SOAPString class GetAllowQuickDial attr_accessor :id attr_accessor :password def initialize(id = nil, password = nil) @id = id @password = password end end # {http://pennytel.com}getAllowQuickDialResponse class GetAllowQuickDialResponse < ::Array end # {http://pennytel.com}getVerifiedCreditCard # id - SOAP::SOAPString # password - SOAP::SOAPString class GetVerifiedCreditCard attr_accessor :id attr_accessor :password def initialize(id = nil, password = nil) @id = id @password = password end end # {http://pennytel.com}getVerifiedCreditCardResponse # getVerifiedCreditCardReturn - SOAP::SOAPString class GetVerifiedCreditCardResponse attr_accessor :getVerifiedCreditCardReturn def initialize(getVerifiedCreditCardReturn = nil) @getVerifiedCreditCardReturn = getVerifiedCreditCardReturn end end # {http://pennytel.com}setProfile # id - SOAP::SOAPString # password - SOAP::SOAPString # contact - PennyTelContact class SetProfile attr_accessor :id attr_accessor :password attr_accessor :contact def initialize(id = nil, password = nil, contact = nil) @id = id @password = password @contact = contact end end # {http://pennytel.com}setProfileResponse class SetProfileResponse def initialize end end # {http://pennytel.com}insertOrUpdateAddressBookEntries # id - SOAP::SOAPString # password - SOAP::SOAPString # contacts - PennyTelContact class InsertOrUpdateAddressBookEntries attr_accessor :id attr_accessor :password attr_accessor :contacts def initialize(id = nil, password = nil, contacts = []) @id = id @password = password @contacts = contacts end end # {http://pennytel.com}insertOrUpdateAddressBookEntriesResponse class InsertOrUpdateAddressBookEntriesResponse def initialize end end # {http://pennytel.com}removeAddressBookEntryByDisplayNames # id - SOAP::SOAPString # password - SOAP::SOAPString # displayNames - SOAP::SOAPString class RemoveAddressBookEntryByDisplayNames attr_accessor :id attr_accessor :password attr_accessor :displayNames def initialize(id = nil, password = nil, displayNames = []) @id = id @password = password @displayNames = displayNames end end # {http://pennytel.com}removeAddressBookEntryByDisplayNamesResponse class RemoveAddressBookEntryByDisplayNamesResponse def initialize end end # {http://pennytel.com}removeAddressBookEntry # id - SOAP::SOAPString # password - SOAP::SOAPString # criteria - SOAP::SOAPString class RemoveAddressBookEntry attr_accessor :id attr_accessor :password attr_accessor :criteria def initialize(id = nil, password = nil, criteria = nil) @id = id @password = password @criteria = criteria end end # {http://pennytel.com}removeAddressBookEntryResponse class RemoveAddressBookEntryResponse def initialize end end # {http://pennytel.com}getAddressBookEntries # id - SOAP::SOAPString # password - SOAP::SOAPString # criteria - SOAP::SOAPString class GetAddressBookEntries attr_accessor :id attr_accessor :password attr_accessor :criteria def initialize(id = nil, password = nil, criteria = nil) @id = id @password = password @criteria = criteria end end # {http://pennytel.com}getAddressBookEntriesResponse class GetAddressBookEntriesResponse < ::Array end # {http://pennytel.com}sendSMS # id - SOAP::SOAPString # password - SOAP::SOAPString # type - SOAP::SOAPInt # to - SOAP::SOAPString # message - SOAP::SOAPString # date - SOAP::SOAPDateTime class SendSMS attr_accessor :id attr_accessor :password attr_accessor :type attr_accessor :to attr_accessor :message attr_accessor :date def initialize(id = nil, password = nil, type = nil, to = nil, message = nil, date = nil) @id = id @password = password @type = type @to = to @message = message @date = date end end # {http://pennytel.com}sendSMSResponse class SendSMSResponse def initialize end end # {http://pennytel.com}triggerCallback # id - SOAP::SOAPString # password - SOAP::SOAPString # leg1 - SOAP::SOAPString # leg2 - SOAP::SOAPString # date - SOAP::SOAPDateTime class TriggerCallback attr_accessor :id attr_accessor :password attr_accessor :leg1 attr_accessor :leg2 attr_accessor :date def initialize(id = nil, password = nil, leg1 = nil, leg2 = nil, date = nil) @id = id @password = password @leg1 = leg1 @leg2 = leg2 @date = date end end # {http://pennytel.com}triggerCallbackResponse class TriggerCallbackResponse def initialize end end # {http://pennytel.com}makePayment # id - SOAP::SOAPString # password - SOAP::SOAPString # amount - SOAP::SOAPFloat class MakePayment attr_accessor :id attr_accessor :password attr_accessor :amount def initialize(id = nil, password = nil, amount = nil) @id = id @password = password @amount = amount end end # {http://pennytel.com}makePaymentResponse # makePaymentReturn - SOAP::SOAPString class MakePaymentResponse attr_accessor :makePaymentReturn def initialize(makePaymentReturn = nil) @makePaymentReturn = makePaymentReturn end end # {http://pennytel.com}verifyUsingWirecard # id - SOAP::SOAPString # password - SOAP::SOAPString # cardName - SOAP::SOAPString # creditCardNumber - SOAP::SOAPString # expmonth - SOAP::SOAPString # expyear - SOAP::SOAPString # csc - SOAP::SOAPString # currency - SOAP::SOAPString class VerifyUsingWirecard attr_accessor :id attr_accessor :password attr_accessor :cardName attr_accessor :creditCardNumber attr_accessor :expmonth attr_accessor :expyear attr_accessor :csc attr_accessor :currency def initialize(id = nil, password = nil, cardName = nil, creditCardNumber = nil, expmonth = nil, expyear = nil, csc = nil, currency = nil) @id = id @password = password @cardName = cardName @creditCardNumber = creditCardNumber @expmonth = expmonth @expyear = expyear @csc = csc @currency = currency end end # {http://pennytel.com}verifyUsingWirecardResponse # verifyUsingWirecardReturn - SOAP::SOAPString class VerifyUsingWirecardResponse attr_accessor :verifyUsingWirecardReturn def initialize(verifyUsingWirecardReturn = nil) @verifyUsingWirecardReturn = verifyUsingWirecardReturn end end # {http://pennytel.com}insertOrUpdateWallet # id - SOAP::SOAPString # password - SOAP::SOAPString # cardName - SOAP::SOAPString # creditCardNumber - SOAP::SOAPString # exp - SOAP::SOAPString class InsertOrUpdateWallet attr_accessor :id attr_accessor :password attr_accessor :cardName attr_accessor :creditCardNumber attr_accessor :exp def initialize(id = nil, password = nil, cardName = nil, creditCardNumber = nil, exp = nil) @id = id @password = password @cardName = cardName @creditCardNumber = creditCardNumber @exp = exp end end # {http://pennytel.com}insertOrUpdateWalletResponse # insertOrUpdateWalletReturn - SOAP::SOAPString class InsertOrUpdateWalletResponse attr_accessor :insertOrUpdateWalletReturn def initialize(insertOrUpdateWalletReturn = nil) @insertOrUpdateWalletReturn = insertOrUpdateWalletReturn end end # {http://pennytel.com}multipleSignup # email - SOAP::SOAPString # password - SOAP::SOAPString # location - SOAP::SOAPString # numberOfAccounts - SOAP::SOAPInt class MultipleSignup attr_accessor :email attr_accessor :password attr_accessor :location attr_accessor :numberOfAccounts def initialize(email = nil, password = nil, location = nil, numberOfAccounts = nil) @email = email @password = password @location = location @numberOfAccounts = numberOfAccounts end end # {http://pennytel.com}multipleSignupResponse class MultipleSignupResponse < ::Array end # {http://pennytel.com}signup # email - SOAP::SOAPString # password - SOAP::SOAPString # location - SOAP::SOAPString class Signup attr_accessor :email attr_accessor :password attr_accessor :location def initialize(email = nil, password = nil, location = nil) @email = email @password = password @location = location end end # {http://pennytel.com}signupResponse # signupReturn - SOAP::SOAPString class SignupResponse attr_accessor :signupReturn def initialize(signupReturn = nil) @signupReturn = signupReturn end end # {http://pennytel.com}replace # regexPlan - SOAP::SOAPString # number - SOAP::SOAPString class Replace attr_accessor :regexPlan attr_accessor :number def initialize(regexPlan = nil, number = nil) @regexPlan = regexPlan @number = number end end # {http://pennytel.com}replaceResponse # replaceReturn - SOAP::SOAPString class ReplaceResponse attr_accessor :replaceReturn def initialize(replaceReturn = nil) @replaceReturn = replaceReturn end end # {http://pennytel.com}verify # id - SOAP::SOAPString # password - SOAP::SOAPString # amount - SOAP::SOAPFloat class Verify attr_accessor :id attr_accessor :password attr_accessor :amount def initialize(id = nil, password = nil, amount = nil) @id = id @password = password @amount = amount end end # {http://pennytel.com}verifyResponse # verifyReturn - SOAP::SOAPString class VerifyResponse attr_accessor :verifyReturn def initialize(verifyReturn = nil) @verifyReturn = verifyReturn end end # {http://pennytel.com}getProfile # id - SOAP::SOAPString # password - SOAP::SOAPString class GetProfile attr_accessor :id attr_accessor :password def initialize(id = nil, password = nil) @id = id @password = password end end # {http://pennytel.com}getProfileResponse # getProfileReturn - PennyTelContact class GetProfileResponse attr_accessor :getProfileReturn def initialize(getProfileReturn = nil) @getProfileReturn = getProfileReturn end end # {http://pennytel.com}getVersion class GetVersion def initialize end end # {http://pennytel.com}getVersionResponse # getVersionReturn - SOAP::SOAPString class GetVersionResponse attr_accessor :getVersionReturn def initialize(getVersionReturn = nil) @getVersionReturn = getVersionReturn end end
true
d55871a88e0c9237c38422f265ff4b5d8601aec1
Ruby
conradszklarz/object_oriented_ruby
/runner_code.rb
UTF-8
699
3.125
3
[]
no_license
store_item_1 =StoreFront::StoreItem.new( color: "blue", price: 5.50, fruit: "blueberries" ) store_item_2 =StoreFront::StoreItem.new( color: "red", price: 3.00, fruit: "strawberries" ) store_item_3 =StoreFront::StoreItem.new( color: "green", price: 2.45, fruit: "pears" ) store_item_1.print_info store_item_2.print_info store_item_3.print_info
true
fdb283be46fafb6d6846108786097e6d9639518e
Ruby
Carrison57/ruby_functions
/multiplication/multiply.rb
UTF-8
116
3.109375
3
[]
no_license
def my_multiply(first_num, second_num, third_num) num = first_num * (second_num * third_num) end puts num
true
12ed50bfc6b0d55053e9471987da268f36d44ff2
Ruby
greggroth/knapsack
/test_examples/fast/spec_test.rb
UTF-8
304
2.84375
3
[ "MIT" ]
permissive
require 'test_helper' class FakeCalculator def add(x, y) x + y end def mal(x, y) x * y end end describe FakeCalculator do before do @calc = FakeCalculator.new end it '#add' do @calc.add(2, 3).must_equal 5 end it '#mal' do @calc.mal(2, 3).must_equal 6 end end
true
920804522c977ab5fde17ef142f3f7b13ea305f5
Ruby
VincentLloyd/the_final_cafe
/menu.rb
UTF-8
1,473
2.859375
3
[]
no_license
module FinalCafe class MenuItem attr_accessor :name, :price def initialize(name, price) @name = name @price = price end end class Menu FOOD_ENTREE = [ MenuItem.new('Oysters', 13), MenuItem.new('Parma', 15), MenuItem.new('Eggplant Casserole', 15), MenuItem.new('Chips', 7), MenuItem.new('Beer', 7), MenuItem.new('Soft drink', 3.50) ] FOOD_MAIN = [ MenuItem.new('Steak', 20), MenuItem.new('Parma', 15), MenuItem.new('Eggplant Casserole', 15), MenuItem.new('Chips', 7), MenuItem.new('Beer', 7), MenuItem.new('Soft drink', 3.50) ] FOOD_DESERT = [ MenuItem.new('Ice Cream', 7), MenuItem.new('Pavlova', 8), MenuItem.new('Sticky Date Pudding', 8), MenuItem.new('Cheescake', 7), MenuItem.new('Cheese platter', 13), MenuItem.new('Soft drink', 3.50) ] DRINKS = [ MenuItem.new('Ice Cream', 7), MenuItem.new('Pavlova', 8), MenuItem.new('Sticky Date Pudding', 8), MenuItem.new('Cheescake', 7), MenuItem.new('Cheese platter', 13), MenuItem.new('Soft drink', 3.50) ] def initialize @entree = build_menu(FOOD_ENTREE) @main = build_menu(FOOD_MAIN) @dessert = build_menu(FOOD_DESSERT) @drinks = build_menu(DRINKS) end def build_menu(items) item_array = [] items.each { |menu_item| item_array << menu_item } end end end
true
7c701772a4083deb848466f6a13c3664055e5766
Ruby
meitel/Pre-course-
/LeapYears.rb
UTF-8
371
3.90625
4
[]
no_license
puts 'What is the start year?' startyear = gets.chomp.to_i puts 'And what is the end year?' endyear = gets.chomp.to_i puts 'Below are the following leap years in between ' + startyear.to_s + ' and ' + endyear.to_s + ':' while (startyear <= endyear) if ((startyear % 4 == 0 and startyear % 100 !=0) or startyear % 400 == 0) puts startyear.to_s end startyear += 1 end
true
6c35dec37c4b32a3abc24117856756a77bfe859b
Ruby
kbarley/toc-vis
/2-extract-isbn.rb
UTF-8
478
2.9375
3
[]
no_license
require 'json' json_files = Dir["*.json"] - Dir["extract-*.json"] files = json_files.map{|file| JSON.parse(File.open(file).read)}.flatten # Basic url: http://search.barnesandnoble.com/title/author/e/isbn # But title and author can be omitted and url still works isbns = files.map do |file| file["books"].map do |book| book["url"].match("/e/(.*?)/")[1] end end.flatten.uniq.sort File.open("isbns.txt", "w+") do |file| isbns.each{|isbn| file.write isbn + "\n"} end
true
cda46892a46faf8e628ef43957397d54e5577f81
Ruby
compilerla/simmons
/data_processors/mergeall.rb
UTF-8
12,732
2.703125
3
[]
no_license
require 'csv' require 'rest-client' require 'merc_convert' require 'geocoder' require 'securerandom' require '../property_deduper.rb' Geocoder.configure( :lookup => :google, :use_https => true, :api_key => 'AIzaSyDzL_IIGdqVTs0_E6Oln6uYoJMXEffHfyk', :region => 'us' ) class Housekeeping def self.clean_apn(apn) if apn.nil? '' elsif apn.include?('#') '' elsif apn.length == 1 '' elsif apn =~ /^.{4}-.{3}-.{3}$/ [apn.gsub(/^(.{4})-(.{3})-(.{3})$/, '\1\2\3')] elsif apn =~ /^.{7}\*{3}$/ '' elsif apn.include?(';') apn.split(';').map(&:strip) elsif apn.include?(',') apn.split(',').map do |no_commas_apn| clean_apn(no_commas_apn) end else apn end end end class Deduper def self.dedup_all in_csv = CSV.open("../data/master_with_dups.csv", { headers: true }) out_csv = CSV.open("../data/master_without_dups.csv", "wb") out_csv << ['APN', 'Address given', 'Address from apn', 'Times encountered', 'Lists', 'Shape', 'Latlng from address given'] deduper = PropertyDeduper.new in_csv.each do |row| list = row['File name'] apn = row['APN given'] address_from_apn = row['Address from APN'] address_given = row['Address given'] shape = row['Shape coords from APN'] latlng = row['Latlng from address given'] deduper.add(apn, address_from_apn, address_given, list, shape, latlng) end deduper.each_property do |property| out_csv << [property[:apn], property[:address_given], property[:address_from_apn], property[:times_encountered], property[:source_lists].join(', '), property[:shape_from_apn], property[:latlng_from_address]] end puts "Finished! #{deduper.dups} duplicates." in_csv.close out_csv.close end end class Merger def self.merge_file(file_name, apn_col, address_col, new_file = false) open_mode = new_file ? 'wb' : 'ab' in_csv = CSV.open("../data/raw/#{file_name}", { headers: true }) out_csv = CSV.open("../data/master_with_dups.csv", open_mode) if new_file out_csv << headers end in_csv.each do |row| cleaned_rows = generate_cleaned_rows(row, file_name, apn_col, address_col) cleaned_rows.each do |cleaned_row| out_csv << cleaned_row end end in_csv.close out_csv.close end def self.update_headers in_csv = CSV.open("../data/master_with_dups.csv", { headers: true }) out_csv = CSV.open("../data/master_with_dups_updated_headers.csv", "wb") out_csv << headers in_csv.each do |row| headers.each do |header| if !row[header] row[header] = '' end end out_csv << row end in_csv.close out_csv.close end def self.headers ['File name', 'APN given', 'Address given', 'Address from APN', 'Shape coords from APN', 'Latlng from address given', 'Latlng from city API', 'Assessed value', 'council district', 'Property Type', 'Region/Cluster', 'Tax Rate Area', 'Recording Date', 'Land', 'Improvements', 'Property Boundary Description', 'Building Square Footage', 'Year Built/Effective Year Built', 'Units'] end def self.patch_missing_geos in_csv = CSV.open("../data/master_with_dups.csv", { headers: true }) out_csv = CSV.open("../data/master_with_dups_patched.csv", "wb") processed = 0 skipped = 0 out_csv << headers in_csv.each do |row| processed += 1 if (row['APN given'].nil? || row['APN given'] == '') && (!row['Address given'].nil? && row['Address given'] != '') puts "#{processed}: Geocoding #{row['Address given']}..." row['Latlng from address given'] = latlng_for_address(row['Address given']) puts "Done: #{row['Latlng from address given']}" else skipped += 1 puts "APN present or no address, skipping... (#{skipped})" end out_csv << row end in_csv.close out_csv.close end def self.patch_missing_shapes in_csv = CSV.open("../data/master_with_dups.csv", { headers: true }) out_csv = CSV.open("../data/master_with_dups_patched.csv", "wb") out_csv << headers in_csv.each do |row| if row['Shape coords from APN'].nil? || row['Shape coords from APN'] == '' && (!row['APN given'].nil? && row['APN given'] != '') puts "Querying #{row['APN given']}..." row['Shape coords from APN'] = shape_from_apn(row['APN given'].strip) puts "Done: #{row['Shape coords from APN']}" else puts "Skipping..." end out_csv << row end in_csv.close out_csv.close end def self.generate_cleaned_rows(row, file_name, apn_col, address_col) apn_raw = apn_col.nil? ? '' : row[apn_col] apns_cleaned = Housekeeping.clean_apn(apn_raw) address = address_col.nil? ? '' : build_column_value(row, address_col) apns_cleaned = [apns_cleaned] if !apns_cleaned.kind_of?(Array) apns_cleaned.map do |clean_apn| [file_name, clean_apn, address, self.address_from_apn(clean_apn), self.shape_from_apn(clean_apn), self.latlng_for_address(address), nil, nil, row['Council District'], nil, nil, nil, nil, nil, nil, nil, nil, nil, nil] end end def self.latlng_for_address(address) return nil unless address && address.length > 0 puts "Geocoding #{address}" geo_response = Geocoder.search(address).first if geo_response.nil? log_error("Couldn't geocode address: #{address}") return end geo_response.coordinates end def self.log_error(error) # TODO end def self.address_from_apn(apn) return '' unless apn && apn.length > 0 address_from_apn = '' puts "Checking address for apn: #{apn}" begin request = RestClient.get("http://maps.assessor.lacounty.gov/Geocortex/Essentials/REST/sites/PAIS/SQLAINSearch?f=json&AIN=#{apn}&dojo.preventCache=1449797179914") details = JSON.parse(request)['results']['ParcelDetails'] address_from_apn = '' if details['Address1'].length > 0 && details['Address2'].length > 0 address_from_apn = "#{details['Address1']}, #{details['Address2']}" end rescue puts "API error" end puts "Response: #{address_from_apn}" address_from_apn end def self.shape_from_apn(apn) return '' unless apn && apn.length > 0 shape_from_apn = nil puts "Checking shape for apn: #{apn}" begin puts "Trying city" url = "http://maps.lacity.org/lahub/rest/services/Landbase_Information/MapServer/5/query?where=BPP%3D%27#{apn}%27&text=&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=*&returnGeometry=true&returnTrueCurves=false&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&returnDistinctValues=false&resultOffset=&resultRecordCount=&f=json" request = RestClient.get(url) parsed = JSON.parse(request) if parsed['features'].any? p "Found city shape" shape_from_apn = parsed['features'].first['geometry']['rings'] else puts "City failed. Using county." url = "http://assessor.gis.lacounty.gov/assessor/rest/services/PAIS/pais_parcels/MapServer/0/query?f=json&where=AIN%20%3D%20%27#{apn}%27&returnGeometry=true&spatialRel=esriSpatialRelIntersects&outFields=AIN&outSR=102100" request = RestClient.get(url) parsed = JSON.parse(request) shape_from_apn = parsed['features'].first['geometry']['rings'] end puts "Response: #{shape_from_apn}" shape_from_apn rescue log_error("Couldn't get shape for APN: #{apn}") puts "Failed to fetch shape" nil end end def self.build_column_value(input_row, keys) return '' if keys.nil? || keys == '' return input_row[keys] unless keys.kind_of?(Array) keys.map do |key| input_row[key] end.join(' ') end end class Geobuilder def self.build in_csv = CSV.open("../data/master_with_dups.csv", { headers: true }) features = [] in_csv.each do |row| feature = build_feature_from_row(row) features << feature if feature end in_csv.close feature_collection = { "type": "FeatureCollection", "features": features } File.open('../data/geo.geojson', 'w') { |file| file.write(feature_collection.to_json) } end def self.build_feature_from_row(row) if !row['Shape coords from APN'].nil? && row['Shape coords from APN'] != '' return { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": JSON.parse(row['Shape coords from APN']).map{ |polygon| polygon.map{ |coords| MercConvert.inverse(coords[0], coords[1]) } } }, "properties": { "title": row['File name'], "APN": row['APN given'] }, "id": row['APN given'] } elsif !row['Latlng from address given'].nil? && row['Latlng from address given'] != '' return { "type": "Feature", "geometry": { "type": "Point", "coordinates": JSON.parse(row['Latlng from address given']).reverse }, "properties": { "title": row['File name'], "address": row['Address given'] }, "id": SecureRandom.uuid } end end end # Merger.merge_file("2015 Registered Foreclosed Properties.csv", 'APN', 'Property Address', true) # Merger.merge_file("Assumed outside LA City Limits.csv", 'AIN', 'PropertyLocation') # Merger.merge_file("Brownfields Program - Sanitation Department.csv", 'APN', 'Address') # Merger.merge_file("Building Book - GSD - 4468 FY 2014_by_building_book_number.csv", 'APN', ['Street #', 'Street Dir', 'Street Name', 'Street Type', 'Community', 'Zip Code']) # Merger.merge_file("Building Book - GSD - 4468 FY 2014_listed_by_address.csv", 'APN', ['Street #', 'Street Dir', 'Street Name', 'Street Type', 'Community', 'Zip Code']) # Merger.merge_file("City Owned Within CDs.csv", 'AIN', nil) # Merger.merge_file("CRA Option Properties .csv", nil, 'Address') # Merger.merge_file("CRA Property List Oct 2012.csv", 'Parcel Number', 'Address') # Merger.merge_file("Decommissioned Fire Stations.csv", 'APN', nil) # Merger.merge_file("GSD Facilities For Filming.csv", nil, 'Address') # Merger.merge_file("Insured Buildings & Uninsured Buildings -CAO - 359.csv", nil, ['Address','City', 'State', 'Zip']) # Merger.merge_file("Leased properties to NPOs - GSD - 110 - FY 2014.csv", nil, 'Address') # Manually cleaned # Merger.merge_file("Master Property List (Simple) 03-7-2013- Update (1) (2) manual cleaned.csv", 'APN', ['Address', 'City']) # Merger.merge_file("MICLA Commercial Paper Note Program.csv", nil, 'ADDRESS') # Merger.merge_file("Neighborhood Land Trust Empty Lots .csv", 'AIN', nil) # Merger.merge_file("Own a Piece of LA - OPLA (3).csv", 'APN', 'ADDRESS') # Merger.merge_file("Parking Lots & Structures - LADOT.csv", nil, ['Address', 'Zip Code']) # Merger.merge_file("Projected Surplus Properties Sales FY15-16 (Per GSD).csv", 'APN', ['PROPERTY ADDRESS', 'ZIP']) # Merger.merge_file("Properties in BIDS - Compiled.csv", 'APN', 'Site Addr') # Merger.merge_file("Properties Recommended for Disposition byb HCIDLA.csv", nil, ['City', 'Zip Code']) # # # This file was manually cleaned! # Merger.merge_file("Recreation and Parks - Provided by Department manual cleaned.csv", 'APN', ['Address', 'City']) # Merger.merge_file("Reported Nuisance Properties FYs 14-16__14-15_sheet.csv", nil, ['Street #', 'Street Name', 'City & ZIP']) # Merger.merge_file("Reported Nuisance Properties FYs 14-16__15-16_sheet.csv", nil, ['Street #', 'Street Name', 'City & ZIP']) # Merger.merge_file("Residential Leases - GSD - 11 total - FY 2013.csv", nil, ['ADDRESS', 'ADDRESS_2']) # Merger.merge_file("undeclared surplus property by id.csv", 'APN', 'ADDRESS') # Merger.merge_file("Department of Building & Safety Vacant Buildings.csv", nil, ['Address', 'City']) # Merger.merge_file("HCIDLA Owned Properties for Filming.csv", 'APN', ['Property Address', 'City', 'Zip Code']) # Merger.update_headers Geobuilder.build # Deduper.dedup_all # out_csv = CSV.open("../data/master_with_dups_patched.csv", "wb") # out_csv << Merger.headers # wrong = [] # CSV.open "../data/master_with_dups.csv", { headers: true } do |in_csv| # in_csv.each do |row| # if row['Shape coords from APN'].nil? || row['Shape coords from APN'] == '' # row['Shape coords from APN'] = Merger.shape_from_apn(row['APN given']) # end # out_csv << row # end # end # out_csv.close
true
c41188c90877b78866ef98f5462d681e3df7b71f
Ruby
maloneyl/WDI_LDN_3_Work_Clone
/maloneyl/w2d5/homework/movies_app/main.rb
UTF-8
2,239
2.75
3
[]
no_license
require "sinatra" require "sinatra/contrib/all" require "sinatra/reloader" require "pg" require "pry" require_relative "./model/movie.rb" require_relative "./model/actor.rb" also_reload "./model/movie.rb" also_reload "./model/actor.rb" before do @db = PG.connect(dbname: "movies", host: "localhost") @movie = Movie.new(@db) @actor = Actor.new(@db) end after do @db.close end get "/" do @movies = @movie.all @actors = @actor.all erb :index end post "/search" do @movies = @movie.search(params[:query]) @actors = @actor.search(params[:query]) erb :index end get "/movies/:movie_id" do @actors = @movie.actor(params[:movie_id]) # this must come first; otherwise it's undefined method for the resulting hash. not 100% getting it... @movie = @movie.find(params[:movie_id]) erb :show_movie end get "/actors/:actor_id" do @movies = @actor.movie(params[:actor_id]) @actor = @actor.find(params[:actor_id]) erb :show_actor end get "/new/movie" do @actors = @actor.all @actors_in_db = @actor.all @movie = {} erb :new_movie end post "/new/movie" do new_created_id = @movie.create(params) redirect "/movies/#{new_created_id}" end get "/new/actor" do @actor = {} erb :new_actor end post "/new/actor" do new_created_id = @actor.create(params) # params is that hash that Sinatra gives you! redirect "/actors/#{new_created_id}" end get "/movies/:movie_id/update" do @actors = @movie.actor(params[:movie_id]) @actors_in_db = @actor.all @movie = @movie.find(params[:movie_id]) erb :new_movie end post "/movies/:movie_id/update" do @movie.update(params) # no need to assign it to @movie here because we don't need the value aftter redirect "/movies/#{params[:movie_id]}" end get "/actors/:actor_id/update" do @movies = @movie.all @actor = @actor.find(params[:actor_id]) erb :new_actor end post "/actors/:actor_id/update" do @actor.update(params) # no need to assign it to @movie here because we don't need the value aftter redirect "/actors/#{params[:actor_id]}" end post "/movies/:movie_id/delete" do @movie.delete(params[:movie_id]) redirect "/" end post "/actors/:actor_id/delete" do @actor.delete(params[:actor_id]) redirect "/" end
true
7edf83240be4cbb446894ba49d526de0a504199e
Ruby
dnuffer/dpcode
/print_table/ruby/start.rb
UTF-8
621
2.875
3
[]
no_license
if __FILE__ == $1 exit 1 unless system "rspec #{__FILE__}" end require 'rspec' describe "print_table" do it "formats a table with a single element" do print_table([["x"]]).should == "x\n" end it "formats a table with a single element in two rows" do print_table([["1"], ["2"]]).should == "1\n2\n" end it "formats a table with a two elements in two rows" do print_table([["12", "34"], ["5", "6"]]).should == "1234\n5 6 \n" end it "formats a complex table" do print_table([["12", "34", "X"], ["5", "678", "Y"], ["901", "2", "ZA"]]).should == "12 34 X \n5 678Y \n9012 ZA\n" end end
true
de0928c56c40c8f134d423b613fee8e4ad331e7f
Ruby
mathycoder/ruby-music-library-cli-online-web-sp-000
/lib/artist.rb
UTF-8
844
3.171875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' require_relative '../lib/concerns/findable' class Artist extend Concerns::Findable attr_accessor :name, :songs @@all = [] def self.all @@all end def initialize(name) @name = name @songs = [] end def self.destroy_all @@all.clear end def save @@all << self end def self.create(name) new_artist = Artist.new(name) new_artist.save new_artist end def add_song(song) if song.artist.nil? song.artist = self @songs << song end end def genres artists_songs = Song.all.select do |song| song.artist == self end genre_array = [] artists_songs.each do |song| if !(genre_array.include?(song.genre)) genre_array << song.genre end end genre_array end end
true
7ad032568b0a9ce4999aaa9e9de7673753345adc
Ruby
chadellison/lib
/the_cracker.rb
UTF-8
2,075
3.46875
3
[]
no_license
require_relative 'wheel' class TheCracker attr_reader :encrypted_message, :the_wheel, :crack_rotator, :cracked_message, :crack_indices, :key_location, :end_of_message def initialize @encrypted_message = encrypted_message @the_wheel = Wheel.new @crack_rotator = [] @crack_indices = [] @cracked_message = cracked_message @key_location = key_location @end_of_message = [1, 1, 34, 25, 35, 1, 1] end def crack(encrypted_message, date = 2) @encrypted_message = encrypted_message.chars @key_location = encrypted_message.length 7.times { @crack_rotator << @encrypted_message.pop } @crack_rotator.reverse! @crack_rotator.map! { |char| the_wheel.wheel.reverse.index(char) } compute_rotator find_rotator_position print_cracked_message end def compute_rotator difference = [] difference = @crack_rotator.zip(end_of_message).map do |combined| combined.reduce do |rot, end_rot| if rot - end_rot < 0 difference << rot - end_rot + 39 else difference << rot - end_rot end @crack_rotator = difference end end end def find_rotator_position if key_location % 4 == 0 @crack_rotator = @crack_rotator[-4..-1] elsif key_location % 4 == 1 @crack_rotator = @crack_rotator[-5..-2] elsif key_location % 4 == 2 @crack_rotator = @crack_rotator[-6..-3] else @crack_rotator = @crack_rotator[-7..-4] end end def print_cracked_message while encrypted_message.first != nil @crack_rotator.map do |key| @crack_indices << (key + the_wheel.wheel.index(encrypted_message.shift)) break if encrypted_message.length == 0 end end crack = @crack_indices.map do |index| the_wheel.wheel[index % 39] end @cracked_message = crack.join + '..end..' end end if __FILE__ == $0 a = TheCracker.new puts a.encrypted_message puts a.crack("e32k7qr i7o77p3wp3off6v27qv1 99373wwq33x8t428n") puts a.crack_indices puts a.cracked_message puts a.crack_rotator end
true
0ab17b61f06ffc7dba1581d6ab472c5abacc1203
Ruby
flazzarotto/ruby_morpion-game
/app.rb
UTF-8
825
2.984375
3
[]
no_license
require 'bundler' Bundler.require $:.unshift File.expand_path("./../lib", __FILE__) require 'app/board' require 'app/boardcase' require 'app/game' require 'app/player' require 'views/show' class Application def perform # TO DO : méthode qui initialise le jeu puis contient des boucles while pour faire tourner le jeu tant que la partie n'est pas terminée. # puts "--------------------------------------------------" puts "| Bienvenue sur 'ILS SONT SUR MES POILS' ! |" puts "| Un jeu du morpion pas piqué des hannetons ! |" puts "--------------------------------------------------" puts "Quel est le nom de ton personnage ?" print ">" player = gets.chomp player1 = HumanPlayer.new(player) puts player1.accueil binding.pry end end Application.new.perform
true
b7848a87bf1ab23d35a3cd4d779f722df2ec9538
Ruby
LasVegasRubyGroup/presentations
/2012-03-21 Ruby's Enumerable module - David Grayson/test2.rb
UTF-8
1,121
4.03125
4
[]
no_license
# BASIC USE enum = "a".."f" p enum.to_a # => ["a", "b", "c", "d", "e", "f"] p enum.entries # => ["a", "b", "c", "d", "e", "f"] p enum.count # => 6 p enum.count("b") # => 1 p enum.count { |s| s <= "c" } # => 3 # ITERATION WITH ENUMERATOR enumerable = 1 ..3 enumerator = enumerable.to_enum p enumerator.next # => 1 p enumerator.next # => 2 p enumerator.next # => 3 p enumerator.next # => StopIteration exception # ITERATION enum = 1..6 enum.each { |x| :stuff } enum.each_entry { |x| :stuff } # yields 1, 2, 3, 4, 5, 6 enum.each_cons(2) { |x, next_x| :stuff } # yields [1,2], [2,3], [3,4] :stuff enum.each_slice(3) { |x0, x1, x2| :stuff } # yields [1,2,3], [4,5,6] enum.each_with_index { |x, index| :stuff } # yields [1, 0], [2, 1], [3, 2] :stuff enum.reverse_each { |x| :stuff } # yields 6, 5, 4, 3, 2, 1 players = ["alan", "brian", "caterina", "david", "errol", "fay"] players.cycle { |player| :stuff } # Equivalent to: while true players.each do |player| :stuff end end # Can also specify number of cycles: players.cycle(3) { |player| :stuff }
true
d54dc821f7649b9a5a924b2a3176d8694697783e
Ruby
shiiotaka/pro_ruby
/test/rgh_test.rb
UTF-8
736
2.78125
3
[]
no_license
require 'minitest/autorun' require '../lib/rgb' class RghTest < Minitest::Test def test_to_hex assert_equal '#000000', to_hex(0, 0, 0) assert_equal '#ffffff', to_hex(255, 255, 255) assert_equal '#043c78', to_hex(4, 60, 120) end def test_to_ints assert_equal [0, 0, 0], to_ints('#000000') assert_equal [255, 255, 255], to_ints('#ffffff') assert_equal [4, 60, 120], to_ints('#043c78') end end File.open("./sample.txt", "w") do |file| file.puts("1行目のテキストです") file.puts("2行目のテキストです") file.puts("3行目のテキストです") file.puts("3行目のテキストです") file.puts("3行目のテキストです") file.puts("3行目のテキストです") end
true
a84333e9cd492d0b55dc3c8586f0e5152803d0e1
Ruby
jon-dominguez94/alpha-course
/jon_dominguez_tictactoe/lib/board.rb
UTF-8
1,732
3.75
4
[]
no_license
require 'byebug' class Board attr_accessor :grid def initialize(*args) if args.empty? @grid = Array.new(3){Array.new(3)} else @grid = args[0] end end def [](pos) row, col = pos @grid[row][col] end def []=(pos, mark) row, col = pos @grid[row][col] = mark end def place_mark(pos, mark) if empty?(pos) self[pos] = mark return true else puts "Position already taken! Try again!" return false end end def empty?(pos) self[pos] == nil end def winner @grid.each do |row| return row[0] if (row.none? {|el| el == nil}) && row.uniq.length == 1 end diag = [] @grid.each_index {|i| diag << self[[i,i]]} return diag[0] if (diag.none? {|el| el == nil}) && diag.uniq.length == 1 diag = [] @grid.each_index do |i| j = (@grid.length - 1) - i diag << self[[i,j]] end return diag[0] if (diag.none? {|el| el == nil}) && diag.uniq.length == 1 @grid.each_index do |j| col = [] @grid.each_index {|i| col << self[[i,j]]} return col[0] if (col.none? {|el| el == nil}) && col.uniq.length == 1 end nil end def over? if winner return true else return false if @grid.any? do |row| row.any? {|el| el == nil} end true end end def display underline = "-"*(@grid.length*3 + @grid.length - 1) @grid.each_with_index do |row,i| row_string = "" row.each do |el| if el row_string += " #{el} |" else row_string += " |" end end puts row_string[0...-1] unless i == @grid.length - 1 puts underline end end end end
true
570b2e588b1b7d919180e28c167867c3ab14342b
Ruby
rkettering/exercises
/reverse_array.rb
UTF-8
415
4.15625
4
[]
no_license
#!/usr/bin/ruby # Write a function which reverses the contents of an array in place. $numbers=[] for num in 1..23 $numbers.push num end def flip_array(array) for iter in 0..((array.length-1)/2) flip = array[array.length-1-iter] array[array.length-1-iter] = array[iter] array[iter] = flip end end flip_array($numbers) print "$numbers= [" $numbers.each { |i| print i, ", "} print "] \n"
true
24d6652dd6882ec82012f07eecc53253bb1b6734
Ruby
TSSaint/ruby-misc
/ruby_array_manipulations.rb
UTF-8
1,999
4.40625
4
[]
no_license
# pracs with new array manipulations # << adds elements into the end of an array. evaluates to array # array.push adds elements to the end. " " # array.pop removes last element of the array. evals to the removed only # array.unshift adds element to front. evaluates to array # array.shift removes first element. evaluates to the removed only arr = ["vanessa", "candace", "camille", "lubini"] arr << "lubona" # puts arr arr.push "lubiola" # puts arr # puts arr.pop # puts arr.unshift("newguy") arr.shift # puts arr # array/string.index(ele) - evals to the index where it's found # array/string.include?(ele) - evaluates to boolean IF ele is found # works for both arrays and strings arr = ["SF", "NY", "LA"] # puts arr.index("LA") # index 2 # puts arr.index("PA") # nothing, empty space # puts arr.include?("LA") # true # puts arr.include?("PA") # false str = "hiya" # puts str.index("iya") # 1; index 1 # puts str.index("ols") # nothing; empty space # array/string.reverse, evals to new reverse version of array or string # array/string.reverse!, reverses an array/string in place # lots of methods that CHANGE the actual resulting/existing data commonly uses exclamation points arr = [1, 2, 3, 4, 5] arr.reverse # print arr.reverse # --> [5, 4, 3, 2, 1] # print arr.reverse! # --> [5, 4, 3, 2, 1] # print arr # [5, 4, 3, 2, 1] # palindrome time def is_palindrome(word) return word == word.reverse end puts is_palindrome("madam") # array/string slicing # array[startIdx..endIdx] - grabs elements from startIdx to endIdx (inclusive) # array[startIdx...endIdx] - grabs elements from startIdx to endIdx (excludes element at endIdx) # arr = ["a", "b", "c", "d", "e"] # print arr[1...5] # b,c,d,e # string.split evaluates to an array # array.join evaluates to strings str = "follow the yellow brick road" # print str.split("y") quote = "follow the yellow brick road" def func(str) str.split(" ") end print func(quote) # ["follow", "the", "yellow", "brick", "road"]
true
025bca0397a41761abed1f6025eb03906b13fa2e
Ruby
yukihirop/fcoin_ruby_client
/lib/fcoin/authorization.rb
UTF-8
2,446
2.734375
3
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
require 'openssl' require 'base64' require 'active_support' require 'active_support/core_ext' module Fcoin class Authorization # @param http_method [String] # @param path [String] # @param payload [Hash] # @param endpoint [String] # @api_key [String] # @secret_key [String] def initialize(http_method:, path:, payload:, endpoint:, api_key:, secret_key:) self.http_method = http_method self.path = path self.payload = payload self.endpoint = endpoint self.api_key = api_key self.secret_key = secret_key end # Header required for authentication # # @see https://developer.fcoin.com/zh.html#32c808cbe5 def original_headers { 'FC-ACCESS-KEY' => api_key, 'FC-ACCESS-SIGNATURE' => encoded_signature, 'FC-ACCESS-TIMESTAMP' => timestamp } end private attr_accessor :http_method, :path, :payload, :endpoint, :api_key, :secret_key def encoded_signature base64_signature = Base64.strict_encode64(signature) Base64.strict_encode64(OpenSSL::HMAC.digest('sha1', secret_key.to_s, base64_signature)) end # @example HTTP_METHOD + HTTP_REQUEST_URI + TIMESTAMP + POST_BODY # POSThttps://api.fcoin.com/v2/orders1523069544359amount=100.0&price=100.0&side=buy&symbol=btcusdt&type=limit # # @see https://developer.fcoin.com/zh.html#api def signature if http_method == :get && query_string.present? http_method.upcase.to_s + full_url.to_s + '?' +query_string.to_s + timestamp.to_s else http_method.upcase.to_s + full_url.to_s + timestamp.to_s + payload_string.to_s end end def full_url endpoint.to_s + path.to_s end # digits number: 13 # # @note When accessing the API with the UNIX EPOCH timestamp, the time difference between the server and the server must be less than 30 seconds. # # @example # 1531632081423 # # # @see https://developer.fcoin.com/zh.html#api def timestamp # digits number: 13 # e.x.) 1531632081423 @timestamp ||= Time.now.strftime('%s%L').to_i.to_s end # sort by alphabet ASC # # @see https://developer.fcoin.com/jp.html?javascript# def query_string query_string = Hash[ payload.sort ].to_query query_string.blank? ? '' : query_string end alias :payload_string :query_string end end
true
02f6444b8f38c16d001ee821dd82e6057a0d3874
Ruby
reruns/archive
/poker-master/array_lib.rb
UTF-8
1,724
3.75
4
[]
no_license
class Array def my_uniq elements = [] self.each do |el| elements << el unless elements.include?(el) end elements end def two_sum container = [] self.each_with_index do |value, index| (index + 1).upto(self.size - 1) do |index2| container << [index, index2] if value + self[index2] == 0 end end container end def my_transpose return self unless self.all? {|row| self.size == row.size} new_array = Array.new(self.size) {Array.new(self.size)} self.each_index do |i| self[i].each_index do |j| new_array[i][j] = self[j][i] end end new_array end end class TowersOfHanoi def initialize(size) @rods = [(size.downto(1).to_a)] << [] << [] end attr_accessor :rods def move(start, finish) return if @rods[start].empty? if @rods[finish][-1].nil? || @rods[start][-1] < @rods[finish][-1] @rods[finish] << @rods[start].pop end end def won? if @rods[0].empty? && @rods[1].empty? && @rods[2] == @rods[2][0].downto(1).to_a true else false end end def play until won? puts "Please enter a move" input = get_input move(input[0],input[1]) end puts "You won!" end def get_input input = gets.chomp input.split(',').map(&:to_i) end end def stock_picker(arr) smallest = nil smallest_day = 0 max_diff = 0 buy_day, sell_day = 0,0 arr.each_with_index do |value,day| if smallest.nil? or value < smallest smallest = value smallest_day = day elsif value - smallest > max_diff max_diff = value - smallest buy_day = smallest_day sell_day = day end end [buy_day, sell_day] end
true
cc73f1d78b53149e417766b07d37d2556edbd7f7
Ruby
grossjo/tododoo
/bin/todo
UTF-8
1,926
2.890625
3
[]
no_license
#!/usr/bin/env ruby require 'httparty' require 'json' require 'pp' URL_ROOT = "http://localhost:3000" # List Todos result = HTTParty.get('http://localhost:3000/todos') puts result.code puts result.body pp JSON.parse(result.body) # Create body = { todo: { title: "New Todo 1" } } result = HTTParty.post('http://localhost:3000/todos', body: body) puts result.code puts result.body pp JSON.parse(result.body) # Update body = { todo: { title: "Redo Todo 1" } } id = 3 result = HTTParty.put("http://localhost:3000/todos/#{3}", body: body) puts result.code puts result.body pp JSON.parse(result.body) # Destroy id = 3 result = HTTParty.delete("http://localhost:3000/todos/#{3}", body: body) puts result.code puts result.body pp JSON.parse(result.body) # List items todo_id = 2 result = HTTParty.get("http://localhost:3000/todos/#{todo_id}/items") puts result.code puts result.body pp JSON.parse(result.body) # Create body = { item: { subject: "New item 1", contents: "Reallyimportant", status: 'open' } } result = HTTParty.post("http://localhost:3000/todos/#{todo_id}/items", body: body) puts result.code puts result.body pp JSON.parse(result.body) # Update body = { item: { status: "closed" } } id = 3 result = HTTParty.put("http://localhost:3000/todos/#{todo_id}/items/#{id}", body: body) puts result.code puts result.body pp JSON.parse(result.body) # Destroy id = 3 result = HTTParty.delete("http://localhost:3000/todos/#{todo_id}/items/#{id}") puts result.code puts result.body pp JSON.parse(result.body) puts "Item list: il todo_id" puts "Item create: ic" #subject contents todo_id puts "Item update: iu id" #status puts "Item delete: id id" command = gets.chomp case command when 'tl' result = HttpParty.get("#{URL_ROOT}/todos") if result.code == 200 puts result.body.to_json else puts "Error #{" end
true
23bfdc79abc3ab538a27dd26e0a25e2ae1d0d05f
Ruby
tomhowarth76/pig_latin_kata
/exercise_5.rb
UTF-8
1,761
4.15625
4
[]
no_license
# Develop your work so far to handle sentences # e.g. "The quick fox jumped over the lazy dog" -> # "Ethay ickquay oxfay umpedjay overway ethay azylay ogday" def pig_latin(word) if word[0..0] =~ /[A-Z]/ iscap = true else iscap = false end if word.slice(0) == "a" || word.slice(0) == "e" || word.slice(0) == "i" || word.slice(0) == "o" || word.slice(0) == "u" word += "way" elsif word.slice(0..1) == "qu" word = word.slice(2..word.length) + word.slice(0..1) + "ay" elsif word.slice(1) == "a" || word.slice(1) == "e" || word.slice(1) == "i" || word.slice(1) == "o" || word.slice(1) == "u" word = word.slice(1..word.length) + word.slice(0) + "ay" elsif word.slice(2) == "a" || word.slice(2) == "e" || word.slice(2) == "i" || word.slice(2) == "o" || word.slice(2) == "u" word = word.slice(2..word.length) + word.slice(0..1) + "ay" else word.slice(3) == "a" || word.slice(3) == "e" || word.slice(3) == "i" || word.slice(3) == "o" || word.slice(3) == "u" word = word.slice(3..word.length) + word.slice(0..2) + "ay" end if iscap == true return word.capitalize else return word end end # puts pig_latin("quick") # def pig_latin_sentence(sentence) new_array = [] sentence_array = sentence.split (/ /) sentence_array.each { |arg| new_array << pig_latin(arg) } return new_array.join(" ") end puts pig_latin_sentence("The quick brown fox jumpoed over the lazy dog") ## Tests: require_relative './helpers/assert_equal' assert_equal( pig_latin_sentence('The quick fox jumped over the lazy dog'), 'Ethay ickquay oxfay umpedjay overway ethay azylay ogday' )
true
96227f443a8efb32e5c68ab27c89e38eab1a6a7f
Ruby
ynportfolios/vending-machine-2
/vending_machine.rb
UTF-8
4,161
3.546875
4
[]
no_license
require './beverage' require './line' class VendingMachine # ステップ0 お金の投入と払い戻しの例コード # ステップ1 扱えないお金の例コード # 10円玉、50円玉、100円玉、500円玉、1000円札を1つずつ投入できる。 MONEY = [10, 50, 100, 500, 1000].freeze # (自動販売機に投入された金額をインスタンス変数の @slot_money に代入する) def initialize # 最初の自動販売機に入っている売上金額は0円 @earn_money = 0 # 最初の自動販売機に入っている投入金額は0円 @slot_money = 0 # 飲料を格納する配列 @stock = Stock.new end # 現在の売上金額を取得できる。 def current_earn_money # 自動販売機に入っている売上を表示する @earn_money end # 投入金額の総計を取得できる。 def current_slot_money # 自動販売機に入っているお金を表示する @slot_money end # 10円玉、50円玉、100円玉、500円玉、1000円札を1つずつ投入できる。 # 投入は複数回できる。 def slot_money puts '金額を入力してください(|10|50|100|500|1000|のみ使用できます)' money = gets.to_i # 想定外のもの(1円玉や5円玉。千円札以外のお札、そもそもお金じゃないもの(数字以外のもの)など) # が投入された場合は、投入金額に加算せず、それをそのまま釣り銭としてユーザに出力する。 return false unless MONEY.include?(money) # 自動販売機にお金を入れる @slot_money += money end # 払い戻し操作を行うと、投入金額の総計を釣り銭として出力する。 # 払い戻し操作では現在の投入金額からジュース購入金額を引いた釣り銭を出力する。 def return_money # 返すお金の金額を表示する puts @slot_money # 自動販売機に入っているお金を0円に戻す @slot_money = 0 end # 格納されているジュースの情報(値段と名前と在庫)を取得できる。 def beverages_infomation puts 'ID|商品名|価格|在庫数' @beverages.map(&:display_line_information) end # 投入金額、在庫の点で、コーラが購入できるかどうかを取得できる。 # ジュース値段以上の投入金額が投入されている条件下で購入操作を行うと、ジュースの在庫を減らし、売り上げ金額を増やす。 # 投入金額が足りない場合もしくは在庫がない場合、購入操作を行っても何もしない。 # 投入金額、在庫の点で購入可能なドリンクのリストを取得できる。 # ジュース値段以上の投入金額が投入されている条件下で購入操作を行うと、釣り銭(投入金額とジュース値段の差分)を出力する。 def buy_beverage display_bevarages puts 'IDを入力してください' line_id = gets.to_i # return false unless beverage_ids.include?(beverage_id) if @stock.buy(line_id) line = @stock.get_line(line_id) @earn_money += line.price @slot_money -= line.price puts @slot_money else puts '購入できませんでした' end # @beverages[beverage_id].decrease_count end def display_bevarages puts 'ID|商品名|価格|購入可否' @beverages.each do |line| print "#{line.id}|#{line.beverage.name}|#{line.beverage.price}" if (line.beverage.price <= @slot_money) && line.count.positive? # beverage_ids << line.id puts '|購入できます' else puts '|購入できません' end end end # ジュースを3種類管理できるようにする。 def slot_beverage puts '商品名を入力してください' name = gets.chomp puts '価格を入力してください' price = gets.to_i puts '個数を入力してください' count = gets.to_i beverage = Beverage.new(name, price) @stock.add_line(beverage, count) end end
true
2cf0a899101b7a3cb4a5c57f1c98c558ac051be9
Ruby
snusnu/substation
/lib/substation/dispatcher.rb
UTF-8
2,526
2.625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# encoding: utf-8 module Substation # Encapsulates all registered actions and their observers # # The only protocol actions must support is +#call(request)+. # Actions are intended to be classes that handle one specific # application use case. class Dispatcher include Concord.new(:actions, :env) include Adamantium::Flat GUARD = DSL::Guard.new(EMPTY_ARRAY) # Return a new registry instance suitable for {Dispatcher} # # @return [DSL::Registry] # # @api private def self.new_registry DSL::Registry.new(GUARD) end # Invoke the action identified by +name+ # # @example # # module App # class Environment # def initialize(storage, logger) # @storage, @logger = storage, logger # end # end # # class SomeUseCase # def self.call(request) # data = perform_work # request.success(data) # end # end # end # # storage = SomeStorageAbstraction.new # env = App::Environment.new(storage, Logger.new($stdout)) # config = { :some_use_case => { :action => App::SomeUseCase } } # dispatcher = Substation::Dispatcher.coerce(config, env) # # response = dispatcher.call(:some_use_case, :some_input) # response.success? # => true # # @param [Symbol] name # a registered action name # # @param [Object] input # the input model instance to pass to the action # # @return [Response] # the response returned when calling the action # # @raise [UnknownActionError] # if no action is registered for +name+ # # @api public def call(name, input) fetch(name).call(Request.new(name, env, input)) end # Test wether a chain with the given +name+ is registered # # @param [Symbol] name # the name of the chain to test for # # @return [Boolean] # # @api private def include?(name) actions.include?(name) end private # The action registered with +name+ # # @param [Symbol] name # a name for which an action is registered # # @return [#call] # the callable registered for +name+ # # @raise [UnknownActionError] # if no action is registered with +name+ # # @api private def fetch(name) actions.fetch(name) { raise(UnknownActionError.new(name)) } end end # class Dispatcher end # module Substation
true
7c5f448921e0ac09254699f09e305059af05bbcf
Ruby
ruby-amqp/amq-client
/spec/unit/client/settings_spec.rb
UTF-8
3,735
2.578125
3
[ "MIT" ]
permissive
# encoding: utf-8 require "spec_helper" require "amq/client/settings" describe AMQ::Client::Settings do describe ".default" do it "should provide some default values" do AMQ::Client::Settings.default.should_not be_nil AMQ::Client::Settings.default[:host].should_not be_nil end end describe ".configure(&block)" do it "should merge custom settings with default settings" do settings = AMQ::Client::Settings.configure(:host => "tagadab") settings[:host].should eql("tagadab") end it "should merge custom settings from AMQP URL with default settings" do settings = AMQ::Client::Settings.configure("amqp://tagadab") settings[:host].should eql("tagadab") end end describe ".parse_amqp_url(connection_string)" do context "when schema is not one of [amqp, amqps]" do it "raises ArgumentError" do expect { described_class.parse_amqp_url("http://dev.rabbitmq.com") }.to raise_error(ArgumentError, /amqp or amqps schema/) end end it "handles amqp:// URIs w/o path part" do val = described_class.parse_amqp_url("amqp://dev.rabbitmq.com") val[:vhost].should be_nil # in this case, default / will be used val[:host].should == "dev.rabbitmq.com" val[:port].should == 5672 val[:scheme].should == "amqp" val[:ssl].should be_false end it "handles amqps:// URIs w/o path part" do val = described_class.parse_amqp_url("amqps://dev.rabbitmq.com") val[:vhost].should be_nil val[:host].should == "dev.rabbitmq.com" val[:port].should == 5671 val[:scheme].should == "amqps" val[:ssl].should be_true end context "when URI ends in a slash" do it "parses vhost as an empty string" do val = described_class.parse_amqp_url("amqp://dev.rabbitmq.com/") val[:host].should == "dev.rabbitmq.com" val[:port].should == 5672 val[:scheme].should == "amqp" val[:ssl].should be_false val[:vhost].should == "" end end context "when URI ends in /%2Fvault" do it "parses vhost as /vault" do val = described_class.parse_amqp_url("amqp://dev.rabbitmq.com/%2Fvault") val[:host].should == "dev.rabbitmq.com" val[:port].should == 5672 val[:scheme].should == "amqp" val[:ssl].should be_false val[:vhost].should == "/vault" end end context "when URI is amqp://dev.rabbitmq.com/a.path.without.slashes" do it "parses vhost as a.path.without.slashes" do val = described_class.parse_amqp_url("amqp://dev.rabbitmq.com/a.path.without.slashes") val[:host].should == "dev.rabbitmq.com" val[:port].should == 5672 val[:scheme].should == "amqp" val[:ssl].should be_false val[:vhost].should == "a.path.without.slashes" end end context "when URI is amqp://dev.rabbitmq.com/a/path/with/slashes" do it "raises an ArgumentError" do lambda { described_class.parse_amqp_url("amqp://dev.rabbitmq.com/a/path/with/slashes") }.should raise_error(ArgumentError) end end context "when URI has username:password, for instance, amqp://hedgehog:[email protected]" do it "parses them out" do val = described_class.parse_amqp_url("amqp://hedgehog:[email protected]") val[:host].should == "hub.megacorp.internal" val[:port].should == 5672 val[:scheme].should == "amqp" val[:ssl].should be_false val[:user].should == "hedgehog" val[:pass].should == "t0ps3kr3t" val[:vhost].should be_nil # in this case, default / will be used end end end end
true
27a1e6620c7918404dcf3343c196840cef2c1dec
Ruby
gomeswes/Coursera_Ruby
/course_1/module_2/playground_methods.rb
UTF-8
451
3.875
4
[]
no_license
def can_divide_by?(number) return false if number.zero? true end puts "can divide by 3? #{can_divide_by? 3}" puts "can divide by 0? #{can_divide_by?(0)}" def factorial(number = 7) number == 0 ? 1 : number * factorial(number - 1) end puts "Factorial of 3: #{factorial(3)}" puts "Default Factorial: #{factorial}" #Splat def mySplat(a, *b, c) puts b.size end # *b receives an undefined number of parameters. mySplat("a", 1,2,3,3.4,-5, "c", "d")
true
7c891dd98e1b0dd207cc6b6bb3b9f7f994dd508c
Ruby
erixhartman/ruby_fundamentals2
/exercise5.rb
UTF-8
193
3.796875
4
[]
no_license
def faren(num) return (num - 32) * (5.0/9) end puts "WHAT IS THE TEMPERATURE!?!?! (F)" temp = gets.chomp.to_i puts "According to the rest of the world" puts "The temperature is #{faren(temp)}"
true
cadfec0777ddd106a08954160ba46f2b6bf22c13
Ruby
weelliam/mpm-magic
/lib/misc/log.rb
UTF-8
699
2.71875
3
[]
no_license
class Log attr_accessor :world, :description, :card, :target, :action, :time def initialize(world:nil, description: "", card: nil, target: nil , action: nil) @world = world @description = description @time = DateTime.now @card = card @action = action @target = target end def js_id "#{object_id}" end def to_json { js_id: object_id, time: @time.strftime('%Q'), card: @card.nil? ? nil : @card.js_id , card_name: @card.nil? ? nil : @card.name , action: @action.nil? ? nil : @action.to_s, target: @target.nil? ? nil : @target.js_id, target_name: @target.nil? ? nil : @target.name , }.to_json end end
true
de3c7eb4a5eff2ebe7dd19d8a7014716fa28a160
Ruby
rom5566/Wii.rb
/archive.rb
UTF-8
7,858
2.921875
3
[]
no_license
#!/usr/bin/env ruby # Wii.rb -- A Wii toolkit written in Ruby # # Author:: Alex Marshall "trap15" (mailto:[email protected]) # Copyright:: Copyright (C) 2010 HACKERCHANNEL # License:: New BSD License # The header for a U8 archive. class U8Header attr_accessor :tag, :rootnode_off, :header_sz, :data_off, :pad def initialize() @tag = "" @rootnode_off = 0 @header_sz = 0 @data_off = 0 @pad = "\0" * 16 end def pack() return [ @tag, @rootnode_off, @header_sz, @data_off, @pad ].pack("a4NNNa16") end def unpack(data) array = data.unpack("a4NNNa16") @tag = array[0] @rootnode_off = array[1] @header_sz = array[2] @data_off = array[3] @pad = array[4] end def length() return 32 end end # A U8 archive node. class U8Node TYPE_FILE = 0x0000 TYPE_FOLDER = 0x0100 attr_accessor :type, :name_off, :data_off, :size def initialize() @type = 0 @name_off = 0 @data_off = 0 @size = 0 end def pack() return [ @type, @name_off, @data_off, @size ].pack("nnNN") end def unpack(data) array = data.unpack("nnNN") @type = array[0] @name_off = array[1] @data_off = array[2] @size = array[3] end def length() return 12 end end # This class wraps the U8 format. class U8Archive < WiiArchive # A hash indexed by filename, that contains file data. attr_accessor :files # A hash indexed by filename, that contains file sizes. attr_accessor :filesizes def initialize() @filearray = [] @files = {} @filesizes = {} end # Loads internal structures with the data from a pre-existing U8 file. def load(data) header = U8Header.new() header.unpack(data[0,0 + header.length()]) offset = header.rootnode_off rootnode = U8Node.new() rootnode.unpack(data[offset,offset + rootnode.length()]) offset += rootnode.length() nodes = [] for i in (0...rootnode.size - 1) node = U8Node.new() node.unpack(data[offset,offset + node.length()]) offset += node.length() nodes.push(node) end strings = data[offset,offset + header.data_off - header.length() - (rootnode.length() * rootnode.size)] offset += strings.length() recursion = [rootnode.size] recursiondir = ["."] counter = 0 for node in nodes counter += 1 name = (strings[node.name_off,strings.length()].split(/\x00/))[0] if node.type == U8Node::TYPE_FOLDER recursion.push(node.size) recursiondir.push(name.clone) @files[recursiondir.join('/')] = nil @filesizes[recursiondir.join('/')] = 0 @filearray.push(recursiondir.join('/')) @filearray.push(nil) # No data for directories @filearray.push(0) # No size for directories if $DEBUG puts "Dir: " + name end elsif node.type == U8Node::TYPE_FILE offset = node.data_off @files[recursiondir.join('/') + '/' + name.clone] = data[offset..offset + node.size] @filesizes[recursiondir.join('/') + '/' + name.clone] = node.size @filearray.push(recursiondir.join('/') + '/' + name.clone) @filearray.push(data[offset..offset + node.size]) @filearray.push(node.size) if $DEBUG puts "File: " + name end else raise TypeError, name + " U8 node type is not file nor folder. Is " + node.type.to_s() end if $DEBUG puts "Data Offset: " + node.data_off.to_s puts "Size: " + node.size.to_s puts "Name Offset: " + node.name_off.to_s end sz = recursion.last while sz == counter + 1 if $DEBUG puts "Popped directory " + recursiondir.last end recursion.pop() recursiondir.pop() sz = recursion.last end if $DEBUG puts "" end end end # Dumps out the internal structure into regular files on the host. # Exposed as +dumpDir+. def _dumpDir(dirname) files = @filearray.clone while true file = files.shift break if !file data = files.shift size = files.shift if $DEBUG == true puts file end if data == nil # Folder if $DEBUG == true puts "Folder" end if not File.directory?(file) Dir.mkdir(file) end else if $DEBUG == true puts "File" end outf = File.new(file, "w+") outf.write(data[0,size]) outf.close end end end # Loads regular files from a directory on the host into the internal # structure. Exposed as +loadDir+. def _loadDir(dirname) dirs = File.join("**", "*") dirlist = Dir.glob(dirs) while true dir = dirlist.shift break if !dir if $DEBUG puts dir end @filearray.push(dir) if File.directory?(dir) if $DEBUG puts " Dir" end @files[dir] = nil @filesizes[dir] = 0 @filearray.push(nil) @filearray.push(0) else if $DEBUG puts " File" end @files[dir] = readFile(dir) @filesizes[dir] = File.size(dir) @filearray.push(readFile(dir)) @filearray.push(File.size(dir)) end end end # Adds +filename+ to the internal structure, naming it +target+. def addFile(filename, target) @files[target] = readFile(filename) @filesizes[target] = File.size(filename) @filearray.push(target) @filearray.push(readFile(filename)) @filearray.push(File.size(filename)) end # Creates a directory named +target+ in the internal structure. def addDirectory(target) @files[target] = nil @filesizes[target] = 0 @filearray.push(target) @filearray.push(nil) @filearray.push(0) end # Deletes an entry from the internal structure. def delEntry(target) ctr = 0 @files.delete(target) @filesizes.delete(target) @filearray.each {|f| if ctr % 3 == 0 if f == target @filearray.delete_at(ctr) @filearray.delete_at(ctr) @filearray.delete_at(ctr) ctr -= 1 end end ctr += 1 } end # Dumps out the internal structure into a U8 archive. def dump() head = U8Header.new() rootnode = U8Node.new() head.tag = "U\xAA8-" head.rootnode_off = 0x20 rootnode.type = U8Node::TYPE_FOLDER nodes = [] strings = "\x00" filedata = "" files = @filearray.clone files2 = @filearray.clone while true file = files.shift break if !file data = files.shift size = files.shift if $DEBUG puts file end node = U8Node.new() recurse = file.count "/" if file.rindex("/") == nil name = file.clone else name = file[file.rindex("/") + 1..-1] end node.name_off = strings.length() if $DEBUG puts name end strings += name + "\x00" if data == nil # Directory if $DEBUG puts "Directory" end node.type = U8Node::TYPE_FOLDER node.data_off = recurse node.size = nodes.length() + 2 if $DEBUG puts " Position: " + node.size.to_s end files3 = files2.clone while true file2 = files3.shift break if !file2 if $DEBUG puts " " + file2 end files3.shift files3.shift if file2[0..file.length()] == (file + "/") if $DEBUG puts " YES" end node.size += 1 end end if $DEBUG puts " Size: " + node.size.to_s end else # File if $DEBUG puts "File" end node.type = U8Node::TYPE_FILE node.data_off = filedata.length() # 32 bytes seems to work best for "fuzzyness". ??? node.size = size filedata += data + ("\x00" * pad_length(node.size, 32)) if $DEBUG puts " Size: " + node.size.to_s end end if $DEBUG puts "" end nodes.push(node) end head.header_sz = ((nodes.length() + 1) * rootnode.length()) + strings.length() head.data_off = align(head.header_sz + head.rootnode_off, 64) rootnode.size = nodes.length() + 1 for i in (0...nodes.length()) if nodes[i].type == U8Node::TYPE_FILE nodes[i].data_off += head.data_off end end dat = "" dat += head.pack() dat += rootnode.pack() nodes.map {|node| dat += node.pack() } dat += strings dat += "\x00" * (head.data_off - head.rootnode_off - head.header_sz) dat += filedata return dat end end
true
a66e5f1e1facad73538c4d7f4009506694d852ae
Ruby
f1nesse13/aA_chess_game
/board.rb
UTF-8
2,440
3.578125
4
[]
no_license
require_relative 'pieces' require_relative 'display' class Board attr_accessor :rows def initialize(fill_board = true) @sentinel = NullPiece.instance create_grid(fill_board) end def [](pos) pos.each { |num| num.to_i } a, b = pos @rows[a][b] end def []=(pos, value) a, b = pos @rows[a][b] = value end def move_piece(turn_color, start_pos, end_pos) piece = self[start_pos] if piece.color != turn_color raise "Cannot move an opponents piece!" elsif !piece.moves.include?(end_pos) raise "You cannot move like that" elsif !piece.valid_moves.include?(end_pos) raise "You can't move into check" end move_piece!(start_pos, end_pos) end def move_piece!(start_pos, end_pos) piece = self[start_pos] raise "You cannot move like that" unless piece.moves.include?(end_pos) self[start_pos] = @sentinel self[end_pos] = piece piece.pos = end_pos end def valid_pos?(pos) pos.all? { |coord| coord.between?(0, 7) } end def add_piece(piece, pos) raise 'position not empty' unless empty?(pos) self[pos] = piece end def checkmate?(color) return false unless in_check?(color) pieces.select { |p| p.color == color }.all? do |piece| piece.valid_moves.empty? end end def in_check?(color) king_pos = find_king(color).pos pieces.any? do |p| p.color != color && p.moves.include?(king_pos) end end def dup new_board = Board.new(false) pieces.each do |piece| piece.class.new(piece.color, new_board, piece.pos) end new_board end def empty?(pos) self[pos].empty? end def pieces @rows.flatten.reject(&:empty?) end private attr_reader :sentinel def find_king(color) king_pos = pieces.find { |p| p.color == color && p.is_a?(King) } king_pos end def fill_back_row(color) back_row = [Rook, Knight, Bishop, Queen, King, Bishop, Knight, Rook] i = color == :white ? 7 : 0 back_row.each_with_index do |piece_type, x| piece_type.new(color, self, [i, x]) end end def fill_pawn_row(color) i = color == :white ? 6 : 1 8.times { |x| Pawn.new(color, self, [i, x]) } end def create_grid(fill_board) @rows = Array.new(8) { Array.new(8, @sentinel) } return unless fill_board %i(white black).each do |color| fill_back_row(color) fill_pawn_row(color) end end end
true
fba0d50cbc5635e4b7a739ee2c8395fc8240203f
Ruby
JoshCheek/PresentationFiles
/UnderstandAllTheThings/presentation/01-ruby-feedback/03-rake--trace/Rakefile
UTF-8
68
2.859375
3
[ "MIT" ]
permissive
def add_two(n) puts n + 2 end task :default do add_two '2' end
true
766c129041c87915dc751f1d64322e3246cf2900
Ruby
pindell-matt/maze_maker
/test/maze_test.rb
UTF-8
1,836
3.3125
3
[]
no_license
require 'minitest/autorun' require_relative '../lib/maze' require 'pp' class MazeTest < Minitest::Test attr_reader :maze, :grid def setup @def_size = 5 @maze = Maze.new(@def_size) @grid = @maze.generate_grid(@def_size) end def test_maze_has_fixed_size desired_size = 10 maze = Maze.new(desired_size) assert_equal desired_size, maze.size end def test_maze_can_generate_a_grid_of_nested_arrays grid = @maze.generate_grid(8) assert_equal 8, grid.length assert_equal 8, grid[0].length end def test_maze_can_generate_a_grid_of_nested_arrays_with_desired_type desired_size = @def_size grid = @maze.generate_grid(desired_size, 0) assert_equal desired_size, grid.length assert_equal desired_size, grid[0].length assert_equal 0, grid[0][0] assert_equal 0, grid[desired_size - 1][desired_size - 1] end def test_cells_can_be_valid first_cell = @maze.cell_valid?(0, 0) last_cell = @maze.cell_valid?(@maze.size - 1, @maze.size - 1) assert first_cell assert last_cell end def test_can_generate_movements_from_a_given_cell all_movements = [[0, 1], [1, 0], [0, -1], [-1, 0]] movements = @maze.generate_movements(0, 0) assert_equal all_movements.sort, movements.sort end def test_can_generate_the_maze maze = Maze.new(@def_size) visited_positions = maze.visited refute visited_positions[0][0] refute visited_positions[@def_size - 1][@def_size - 1] maze.generate_maze(0, 0) assert visited_positions[0][0] assert visited_positions[@def_size - 1][@def_size - 1] end def test_can_print_to_console out, err = capture_io do @maze.print_to_console end first_line = out.split("\n")[1] assert_equal "Generated Maze size: #{@def_size} x #{@def_size}", first_line end end
true
5b8dc1ab36294b4211b2ff547a3624084f11cf0e
Ruby
thebravoman/software_engineering_2013
/class10_homework/Teodor_Draganov.rb
UTF-8
912
2.75
3
[]
no_license
require 'rexml/document' def line(svg,x1,x2,y1,y2,red=0,green=0,blue=0) line=svg.add_element "line" line.attributes["x1"]=x1 line.attributes["x2"]=x2 line.attributes["y1"]=y1 line.attributes["y2"]=y2 line.attributes["stroke"]="rgb(#{red},#{green},#{blue})" line.attributes["stroke-width"]="2" end doc=REXML::Document.new svg=doc.add_element "svg" svg.attributes["version"]="1.1" svg.attributes["xmlns"]="http://www.w3.org/2000/svg" line(svg,0,1200,350,350) line(svg,600,600,0,700) argument=ARGV[1] i=0 while argument!=nil y1=150 x2=-150 x1=(-ARGV[i+1].to_i+y1)/ARGV[i].to_i y2=(ARGV[i].to_i*x2)+ARGV[i+1].to_i line(svg,x1+600,x2+600,350-y1,350-y2,red=rand(255),green=rand(255),blue=rand(255)) i+=2 argument=ARGV[i+1] end File.open("Teodor_Draganov.svg","w") do |svg| svg.write(doc.to_s) end
true
27165e32f650f2ff74257eb50b6d070bd82fe77a
Ruby
stijlist/jarvis
/spec/calendar_spec.rb
UTF-8
4,339
2.609375
3
[]
no_license
require 'vcr' require_relative '../spec/vcr_helper.rb' require_relative '../lib/calendar.rb' describe Calendar do it 'lists events' do VCR.use_cassette('google-calendar-event-listing') do c = Calendar.new expect(c.events.count).to be > 1 end end it 'adds events' do VCR.use_cassette('adds-events') do c = Calendar.new request_sdate = DateTime.new(2014,8,9,10,35).new_offset("-04:00") request_edate = DateTime.new(2014,8,9,11,35).new_offset("-04:00") room = "Babbage" desc = "algebraic data types party!" res = c.add(request_sdate, request_edate, room, desc) expect(res['status']).to eq('confirmed') expect(res['summary']).to eq(desc) expect(res['location']).to eq(room) end end # event_start ------------------ event_end # req_start ------------------ req_end it 'indicates not bookable if time/room-combo is booked' do VCR.use_cassette('not-bookable-1') do c = Calendar.new request_sdate = DateTime.new(2014,8,9,10,35).new_offset("-04:00") request_edate = DateTime.new(2014,8,9,11,35).new_offset("-04:00") bookable = c.bookable_for?(request_sdate, request_edate, "Babbage") expect(bookable).to eq(false) end end # event_start ------------------ event_end # req_start ------------------ req_end it 'indicates not bookable in 1-sided overlapping case' do VCR.use_cassette('not-bookable-2') do c = Calendar.new request_sdate2 = DateTime.new(2014,8,9,10,20).new_offset("-04:00") request_edate2 = DateTime.new(2014,8,9,11,00).new_offset("-04:00") bookable = c.bookable_for?(request_sdate2, request_edate2, "Babbage") expect(bookable).to eq(false) end end # event_start ------------------ event_end # req_start ------------------ req_end it 'indicates not bookable in 1-sided overlapping case 2' do VCR.use_cassette('not-bookable-3') do c = Calendar.new request_sdate2 = DateTime.new(2014,8,9,10,50).new_offset("-04:00") request_edate2 = DateTime.new(2014,8,9,11,50).new_offset("-04:00") bookable = c.bookable_for?(request_sdate2, request_edate2, "Babbage") expect(bookable).to eq(false) end end # event_start ------------------ event_end # req_start ------------------------------------------------------ req_end it 'indicates not bookable in totally overlapping case' do VCR.use_cassette('not-bookable-4') do c = Calendar.new request_sdate2 = DateTime.new(2014,8,9,10,20).new_offset("-04:00") request_edate2 = DateTime.new(2014,8,9,11,50).new_offset("-04:00") bookable = c.bookable_for?(request_sdate2, request_edate2, "Babbage") expect(bookable).to eq(false) end end # event_start ------------------------------------------------------ event_end # req_start ------------------ req_end it 'indicates not bookable in totally overlapping case 2' do VCR.use_cassette('not-bookable-5') do c = Calendar.new request_sdate2 = DateTime.new(2014,8,9,10,50).new_offset("-04:00") request_edate2 = DateTime.new(2014,8,9,11,00).new_offset("-04:00") bookable = c.bookable_for?(request_sdate2, request_edate2, "Babbage") expect(bookable).to eq(false) end end it 'indicates bookable if room is free, even if time is booked' do VCR.use_cassette('bookable-1') do c = Calendar.new request_sdate = DateTime.new(2014,8,9,10,35).new_offset("-04:00") request_edate = DateTime.new(2014,8,9,11,35).new_offset("-04:00") bookable = c.bookable_for?(request_sdate, request_edate, "Lovelace") expect(bookable).to eq(true) end end it 'indicates bookable if time/room-combo is free' do VCR.use_cassette('bookable-2') do c = Calendar.new diff_start = DateTime.new(1900,8,9,10,35).new_offset("-04:00") diff_end = DateTime.new(1900,8,9,11,35).new_offset("-04:00") bookable = c.bookable_for?(diff_start, diff_end, "Lovelace") expect(bookable).to eq(true) end end end
true
c3629e2e1faa22f893f47372f243b170ee2f96e8
Ruby
techbelly/roguecommuter
/site/db.rb
UTF-8
989
2.578125
3
[]
no_license
require 'datamapper' require 'json' require 'v8' class Runtime def log(message) puts "#{message}" end end class Personality include DataMapper::Resource property :id, Serial property :name, String property :bluetooth_id, String, :length=> 0..40 property :code, Text property :state, String, :default => "ACTIVE" property :environment, Text def self.active Personality.all(:state => "ACTIVE") end def self.dispatch(event) active.each do |a| puts "RUNNING #{a}" Personality.transaction do a.run(event) end end end def run(event) begin ctx = V8::Context.new type,time,args = *event ctx['ego'] = {:name=>self.name,:state=>self.state } ctx['lib'] = Runtime.new ctx['env'] = JSON.parse(self.environment) ctx['event'] = {:type=>type,:time=>time,:args=>args} ctx.eval(self.code) environment = ctx['env'].to_json save() rescue Exception => e puts e end end end
true
20ff943a5fcb37ddc08d3b244b65b47dec2a922d
Ruby
sealink/ruby_core_extensions
/lib/ruby_core_extensions/class.rb
UTF-8
74
2.53125
3
[ "MIT" ]
permissive
class Class def downcase_symbol self.to_s.downcase.to_sym end end
true
90d465064167f32f5ec4969f1e28f3d3eb9d443e
Ruby
vickyGao/unity-learning
/ruby/spine/supernova/service.rb
UTF-8
3,480
2.609375
3
[]
no_license
require 'singleton' require 'securerandom' module SuperNova class Service include Singleton @@services = Array.new attr :sleeptime, true attr :restarts attr :name def self.[] (key) @@services.detect { |service| service.name == key } end def self.each @@services.each { |service| yield service } end def initialize @queue = Queue.new @name = @title = self.class.to_s.sub(/^SuperNova::/, '').sub(/::Service$/, '') @sleeptime = 3 @messagelimit = 5 @ready = false @handlers = Hash.new @loaded = false @restarts = 0 @threads = ThreadGroup.new @@services << self end def booted?() @booted end def boot return if booted? begin logInfo {"BootStrap"} start_time = Time.now bootstrap elapsed = Time.now - start_time if elapsed > 10 logWarning {"BootStrap took #{elapsed} seconds"} else logNotice {"BootStrap complete"} end rescue Exception => exception die('bootstrap', exception) end @booted = true end def bootstrap() end def ready? @ready end def alive? @thread.nil? ? false : @thread.alive? end def warn(phase, exception) svc_name = (@thread.nil? ? 'UNKNOWN' : (@thread['name'] || 'UNKNOWN')) logError {"===================================================="} logError(svc_name) {"Service died: phase [#{phase}], with exception #{exception}"} exception.backtrace.each { |line| logError {" => #{line}"} } logError {"===================================================="} end def die(phase, exception) warn(phase, exception) Kernel.exit end def start @thread = Thread.new do Thread.current['name'] = @title Thread.current['service'] = self boot unless booted? begin logDebug { "Starting" } @ready = true run rescue Exception => exception @restarts += 1 sleep 5 logInfo { "Restart (#{@restarts} times)" } retry end end sleep(1) until ready? unless ready? logInfo { "Ready" } end def run logInfo {"TODO: run method"} # while true # svc_name = Thread.current['name'] # end end def shutdown logNotice {"Shutdown service"} end def stop shutdown @threads.list.each { |thread| logNotice {"Stop: #{thread['name']} helper"} thread.exit } if @thread svc_name = @thread['name'] || 'UNKNOWN' @thread.exit @thread.join @thread = nil end logNotice {"Stop: shutdown"} end end end $service = SuperNova::Service
true
ae52c13ad8ba621047f07a3b00ef4245592187eb
Ruby
brastoner/now_serving
/test/line_man_test.rb
UTF-8
1,703
2.734375
3
[]
no_license
require 'rubygems' require 'test/unit' require 'sequel' require '../lib/line_man_base' require '../lib/line_man_queue' require '../lib/line_man_queue_element' require '../lib/line_man_repository' class LineManTest < Test::Unit::TestCase def setup end def teardown end def test_create_queue repo = get_repo q = repo.create_queue('blue', 'me') assert_equal('blue', q.id) assert_equal('me', q.owner) assert_equal(-1, q.curr_pos) assert_equal([], q.elements) end def test_create_next_element repo = get_repo q = repo.create_queue('blue', 'me') e = q.create_next_queue_element('you') assert_not_nil(e.id) assert_equal('blue', e.queue_id) assert_equal('you', e.owner) assert_equal(0, e.pos) assert_nil(e.used_ts) end def test_queue_advance repo = get_repo q = repo.create_queue('blue', 'me') e = q.create_next_queue_element('you') e2 = q.advance assert_equal(e, e2) assert_equal(0, q.curr_pos) # Test that can't advance past the length of the q e3 = q.advance assert_nil(e3) end def test_use_element repo = get_repo q = repo.create_queue('blue', 'me') q.create_next_queue_element('you') q.create_next_queue_element('you') q.advance q.advance q.use_element(1) q2 = repo.get_queue('blue') assert_nil(q2.elements[0].used_ts) assert_not_nil(q2.elements[1].used_ts) end def get_repo db = create_db LineManRepository.new(db) end def create_db db = Sequel.connect('jdbc:sqlite::memory:') db.run("CREATE TABLE queue(id TEXT PRIMARY KEY, curr_pos INTEGER, owner TEXT)") db.run("CREATE TABLE queue_element(id TEXT, queue_id TEXT, pos INTEGER, owner TEXT, used_ts INTEGER)") db end end
true
dc5776fe6cc560531186711540c231235eb2ce81
Ruby
akshatj/launchschool-ruby-intro
/exercises/3.rb
UTF-8
53
3.265625
3
[]
no_license
odds = (1..10).select { |i| i % 2 != 0 } puts odds
true
b558141b5c70b76dee8f9c63e87dd673a20cc0d7
Ruby
morenoh149/TheAlgorithmDesignManual
/dynamicProgramming/min_coin_sum.rb
UTF-8
571
3.53125
4
[]
no_license
# Given a list of N coins, their values (V1, V2, ... , VN), and the total sum S # Find the minimum number of coins the sum of which is S (we can use as many # coins of one type as we want), or report that it's not possible to select # coins in such a way that they sum up to S. def min_coin_sum(coins, sum) memo = Array.new(999999999999, sum+1) memo[0] = 0 for i in 1..sum for coin in coins if coin <= i and (memo[i-coin]+1 < memo[i]) memo[i] = memo[i-coins[j]] + 1 end end end puts memo[sum] end min_coin_sum([1,3,5],gets.to_i)
true
4f08033d24b485187e7336320dada13177796bed
Ruby
wisq/autocrew
/lib/autocrew/solver/range_error_function.rb
UTF-8
2,799
2.96875
3
[]
no_license
require 'autocrew/solver/error_function_base' require 'autocrew/vector' require 'autocrew/coord' module Autocrew::Solver class RangeErrorFunction < ErrorFunctionBase include Autocrew def arity return 5 end def evaluate(pos_x, pos_y, nvel_x, nvel_y, speed) super(Coord.new(pos_x, pos_y), Vector.new(nvel_x, nvel_y) * speed) end def evaluate_gradient(pos_x, pos_y, nvel_x, nvel_y, speed) unit_start = Coord.new(pos_x, pos_y) time_offset = @unit.origin_time normal_velocity = Vector.new(nvel_x, nvel_y) velocity = normal_velocity * speed x_deriv = y_deriv = vx_deriv = vy_deriv = speed_deriv = 0.0 @unit.observations.each_with_index do |observation, index| time = (observation.game_time - time_offset).hours_f time_velocity = velocity * time unit_point = unit_start + time_velocity observer_point = observation.observer.location(observation.game_time) bearing_vector = observation.bearing_vector obs_vector = unit_point - observer_point #puts #puts "#{index} gradient:" #puts " time = #{time.inspect}" #puts " velocity = #{velocity.inspect}" #puts " unit_point = #{unit_point.inspect}" #puts " observer_point = #{observer_point.inspect}" #puts " bearing_vector = #{bearing_vector.inspect}" #puts " obs_vector = #{obs_vector.inspect}" if bearing_vector.dot_product(obs_vector) >= 0 # if the target position is on the correct side of the observer... # then the error is the signed distance to the bearing line, which equals the dot product of the cross vector (which is # already normalized) and the observation vector error = bearing_vector.cross_vector.dot_product(obs_vector) #puts " same side, error = #{error.inspect}" x_deriv += bearing_vector.y * error y_deriv -= bearing_vector.x * error vx_deriv += bearing_vector.y*speed*time * error vy_deriv -= bearing_vector.x*speed*time * error speed_deriv += (bearing_vector.y*normal_velocity.x*time - bearing_vector.x*normal_velocity.y*time) * error; else # otherwise, the target position is on the wrong side of the observer... #puts " opposite side" x_deriv += obs_vector.x y_deriv += obs_vector.y vx_deriv += speed * time * obs_vector.x vy_deriv += speed * time * obs_vector.y speed_deriv += normal_velocity.x*time*obs_vector.x + normal_velocity.y*time*obs_vector.y end end return [ 2*x_deriv, 2*y_deriv, 2*vx_deriv, 2*vy_deriv, 2*speed_deriv ] end end end
true
913ad11e2525529e98fb939fde6884c58eb9413a
Ruby
hortencia718/ruby-oo-inheritance-defining-inheritance-nyc04-seng-ft-071220
/lib/car.rb
UTF-8
231
3.015625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require_relative "./vehicle.rb" class Car < Vehicle def go "VRRROOOOOOOOOOOOOOOOOOOOOOOM!!!!!" end end # We use the < to inherit the Car class from Vehicle. Notice that there are no methods defined in the Car class.
true
7fd392413a0ad5c08f3078e17185e7cf7a173907
Ruby
yohei-koba-tokyo/playground
/exist123.rb
UTF-8
197
3.375
3
[]
no_license
def array123(nums) nums.include?(1) && nums.include?(2) && nums.include?(3) ? (puts "True") : (puts "False") end array123([1, 1, 2, 3, 1]) array123([1, 1, 2, 4, 1]) array123([1, 1, 2, 1, 2, 3])
true
0383850f414d988ad1acf7578d0c5337f1c0019b
Ruby
with-a-k/enigma
/test/decryptor_test.rb
UTF-8
1,502
2.75
3
[]
no_license
require 'minitest' require 'minitest/autorun' require './lib/decryptor' class DecryptorTest < Minitest::Test def test_decryptors_exist_and_take_three_arguments assert Decryptor.new("sample text.", 25326, "140415") end def test_decryptors_make_their_own_key testdecryptor = Decryptor.new("sample text.", 25326, "140415") assert testdecryptor.key.is_a?(Key) end def test_decryptors_make_their_own_rotator testdecryptor = Decryptor.new("sample text.", 25326, "140415") assert testdecryptor.rotator.is_a?(Rotator) end def test_decryptors_store_their_text testdecryptor = Decryptor.new("gqhh,u5l5ao3", 25326, "140415") assert_equal "gqhh,u5l5ao3", testdecryptor.text end def test_decryptors_encrypt testdecryptor = Decryptor.new("gqhh,u5l5ao3", 25326, "140415") assert_equal "sample text.", testdecryptor.decrypt end def test_decryptors_encrypt_other_things testdecryptor = Decryptor.new("dumkcuid9scc5yo", 25326, "140415") assert_equal "persoenlichkeit", testdecryptor.decrypt end def test_very_long_key testdecryptor = Decryptor.new(", 9j emzw0k660eq6k2bqbas0j2143fqqdgjc7517dkj07jqq36 .i22a7k5q455,b9jada5x22pxi7q6j2n7ecythcj, 9jzh5zw0 u63dqqii6t6j060 m4b2u6jgjwh9m522n7kfpthqj7823x5gx47751ef", 56685, "150415") assert_equal "the round sun menu 2 light plane no weapons here abyss quest battle unite, descent bookmark the grand finale squadron fall into dream, boundary of recollection", testdecryptor.decrypt end end
true
53d3d2665467333c0e625a667d6e24d3568653ca
Ruby
iLtc/launch-school
/101/lesson2/calculator.rb
UTF-8
1,325
4.5
4
[]
no_license
def prompt(message) puts "=> #{message}" end def valid_number?(num) num.to_i != 0 end prompt("Welcome to Calculator! What's your name?") name = nil loop do name = gets.chomp if name.empty? prompt("Make sure to use a valid name.") else break end end prompt("Hi #{name}!") loop do # main loop num1 = num2 = nil loop do prompt("What's the first number?") num1 = gets.chomp if valid_number?(num1) break else prompt("That doesn't look like a valid number!") end end loop do prompt("What's the second number?") num2 = gets.chomp if valid_number?(num2) break else prompt("That doesn't look like a valid number!") end end prompt("What operation would you like to perform? 1) add 2) subtract 3) multiply 4) divide") operator = gets.chomp.to_i result = case operator when 1 num1.to_i + num2.to_i when 2 num1.to_i - num2.to_i when 3 num1.to_i * num2.to_i else # num2 = 0? num1.to_f / num2.to_f end prompt("The result is #{result}") prompt("Do you want to perform another calculation? (y/N)") answer = gets.chomp break unless answer.downcase.start_with?('y') end prompt("Good bye!")
true
cd120a732a05c5a7c8603f96595164ee81f60290
Ruby
jfo/hello
/jeff.rb
UTF-8
2,233
3.078125
3
[]
no_license
class Human attr_reader :corporeal_being, :consciousness def initialize @corporeal_being = true @consciousness = true end #TODO: figure out universal truths, meaning of life, etc... (why is there no Stack Overflow thread on that?) end class Jeff < Human attr_reader :s, :l, :edumactions, :jorbs, :contacts, :beard def initialize super @a = age_right_now @s = 'm' @l = 'Brooklyn, NY' @beard = false @edumaction = { :undergrad => 'BA Music and English, UNC Chapel Hill 2005', :grad => 'MM Jazz Guitar Performance, NYU 2011'} @jorbs = { 2005 => 'Scuba Diver', 2006 => 'ESL Teacher in Japan (like JET, but not)', 2008 => 'Various horrible NY temp stuff', 2009 => 'Adjunct Faculty of Music, NYU', 2011 => ['Musician', 'Owner and Teacher at Guitar from the Ground Up', 'Freelance Photographer']} @contacts = { :email => '[email protected]', :phone => '336-693-5342', :twitter => '@jeffowler', :github => 'http://www.github.com/urthbound', :flickr => 'http://www.flickr.com/photos/monkeywithamirror'} end def hello if RbConfig::CONFIG['host_os'].scan(/darwin|mac os/) system('say hello to you too!') else puts 'Hello!' end end def show_picture print File.open('picture.txt', 'rb').read end def shave @beard = false puts 'Ok, I shaved!' end def dont_shave_for_a_while @beard = true puts "I'm going for that Jeff Bridges / Scandinavian fisherman look" end def a @a = age_right_now end private def age_right_now birthday = Time.new('1983','02','15','16','32') seconds_alive = (Time.now - birthday).to_i minutes_alive = seconds_alive / 60 hours_alive = minutes_alive / 60 days_alive = (hours_alive / 24) years_alive = days_alive / 365 "#{years_alive} years, #{(days_alive % 365) - leaps} days, #{hours_alive % 24} hours, #{minutes_alive % 60} minutes, and #{seconds_alive % 60} seconds." end def leaps leaps = 0 (1983..Time.now.year).each do |year| leaps += 1 if year % 4 == 0 end leaps end end
true
a9ff270f9ab2edea24a4b618eb001ac31b140102
Ruby
thiensau/N2M_Openshift_Hosting
/db/seeds.rb
UTF-8
2,862
2.6875
3
[]
no_license
Product.delete_all Product.create!(title: 'Perfect Shape Bra', description: %{<p> The everyday go-to bra you love pairs push-up padding and the coverage you want with soft, sleek cups and a smoothing U-shaped back.<br> Lift & Lining: Extreme lift, Full coverage underwire cups.<br> Straps & Hooks: Fully adjustable straps can convert to crossback and snap into place for a secure hold, Back closure.<br> Details & Fabric: Crisscross straps between cups, U-shaped ballet back prevents band from riding up and offers more coverage </p>}, image_url: 'ruby/Perfect_Shape_Bra.jpg', price: 36.00) # . . . Product.create!(title: 'Add 2 Cups Push-Up Bra', description: %{<p> The ultimate lift-loving push-up is better than ever with even softer padding for the most cleavage and fullness.<br> Lift & Lining: Maximum lift (adds 2 cups sizes), Underwire cups<br> Straps & Hooks: Fully adjustable straps, Back closure, Double row of hook and eye closures, Can be worn classic or crossback<br> Details & Fabric: U-shaped ballet back for an ultra-comfy fit, Imported nylon/spandex. Racer-back: polyester/spandex. </p>}, image_url: 'ruby/Add_2_Cups_Push_Up_Bra.jpg', price: 49.95) # . . . Product.create!(title: 'Unlined Demi Bra', description: %{<p> A naturally sexy, unlined demi and soft cups make this low-cut bra your everyday go-to. Designed to disappear under everything.<br> Lift & Lining: Unlined, Underwire cups.<br> Straps & Hooks: Fully adjustable straps can convert to crossback and snap into place for a secure hold, Back closure.<br> Details & Fabric: U-shaped ballet back prevents band from riding up and offers more coverage, VS logo at center front </p>}, image_url: 'ruby/Unlined_Demi_Bra.jpg', price: 41.50) # . . . Product.create!(title: 'Shimmer Bralette', description: %{<p> Beautiful floral embroidery shines across this sheer shape, adorned with feminine ruffles and a delicate necklace.<br> Lift & Lining: Unlined triangle cups, Wireless cups.<br> Straps & Hooks: Adjustable straps, Back hook closure<br> Details & Fabric: Allover shimmery, floral embroidery, Ruffle trim under cups, Imported nylon/polyester<br> </p>}, image_url: 'ruby/Shimmer_Bralette.jpg', price: 44.05) # . . . Product.create!(title: 'Cups Push-Up Bra', description: %{<p> The push-up that gives you a little extra lift for serious cleavage, with Memory Fit padding that memorizes your curves, a concealed.<br> Lift & Lining: Adds 1 1/2 cups for extreme lift, Foam-encased underwire cups for comfort<br> Straps & Hooks: Back closure, Double row of hook and eye closures<br> Details & Fabric: Shine finish with matte trim at the top of the cups,VS logo charm between the cups<br> </p>}, image_url: 'ruby/Cups_Push_Up_Bra.jpg', price: 50.99)
true
6f5ac7e5042556c626b3128bdd5f3c8c22b59834
Ruby
cananth/rails-app
/RailsApp/ruby_programs/text_dollar.rb
UTF-8
2,150
3.484375
3
[]
no_license
class TextDollar def initialize hash @hash = hash end def text_dollar file_name begin File.open(file_name, "r").each do | value | integer_array = value.split(" ") integer_array = integer_array[0].split(" ") integer_array.each do | integer_array | result_value = get_hash (integer_array) puts result_value if result_value.class != Hash end end rescue Exception => e puts e.message end end def get_hash integer_array if integer_array.length == 0 return "there is no input process" else if integer_array.length == 1 print @hash[integer_array[0].to_i] << "Dollars" elsif integer_array.length == 2 if integer_array[1].to_i != 0 print (@hash[integer_array[0].to_i * 10].to_s + @hash[integer_array[1].to_i].to_s) << "Dollars" else print (@hash[integer_array[0].to_i * 10].to_s) << "Dollars" end elsif integer_array.length == 3 print @hash[integer_array[0].to_i].to_s + @hash[100] + @hash[integer_array[1].to_i * 10].to_s + @hash[integer_array[2].to_i].to_s << "Dollers" elsif integer_array.length == 4 print @hash[integer_array[0].to_i].to_s + @hash[1000] + @hash[integer_array[1].to_i].to_s+ @hash[100] + @hash[integer_array[2].to_i * 10 ].to_s + @hash[integer_array[3].to_i].to_s << "Dollers" elsif integer_array.length == 5 print (@hash[integer_array[0].to_i * 10 ].to_s + @hash[integer_array[1].to_i].to_s) + @hash[1000] + @hash[integer_array[2].to_i].to_s + @hash[100] + @hash[integer_array[3].to_i * 10 ] + @hash[integer_array[4].to_i] + "Dollers" else puts " the number is too large" end end end end file = ARGV[0] hash = {0=>"zero",1=>"one",2=>"two",3=>"three",4=>"four",5=>"five",6=>"six",7=>"seven",8=>"eight",9=>"nine",10=>"ten", 11=>"eleven",12=>"twelve",13=>"thirteen",14=>"forteen",15=>"fifteen",16=>"sixteen",17=>"seventeen",18=>"eighteen",19=>"ninteen", 20=>"twenty",30=>"thirty",40=>"forty",50=>"fifty",60=>"sixty",70=>"seventy",80=>"eighty",90=>"ninty",100=>"hundred",1000=>"thousand" ,1000000000=>"onemillion"} text_dollar = TextDollar.new hash text_dollar.text_dollar file
true
d610d39abbfd0a4db097973c59569d6163db9d3f
Ruby
bdewey/git-stack
/features/support/town_helpers.rb
UTF-8
1,406
2.546875
3
[ "MIT" ]
permissive
# frozen_string_literal: true def add_perennial_branch branch old_value = perennial_branch_configuration new_value = [old_value, branch].reject(&:blank?).join(' ') set_configuration 'perennial-branch-names', new_value end def delete_main_branch_configuration run 'git config --unset git-town.main-branch-name' end def delete_perennial_branches_configuration run 'git config --unset git-town.perennial-branch-names' end def get_configuration configuration output_of "git config --get git-town.#{configuration} || true" end def get_global_configuration configuration output_of "git config --global --get git-town.#{configuration} || true" end def git_town_configuration # OR'ed with true so that this doesn't exit with an error if config doesn't exist array_output_of 'git config --get-regex git-town || true' end def main_branch_configuration get_configuration 'main-branch-name' end def non_feature_branch_configuration get_configuration 'non-feature-branch-names' end def perennial_branch_configuration get_configuration 'perennial-branch-names' end def pull_branch_strategy_configuration get_configuration 'pull-branch-strategy' end def set_configuration configuration, value run "git config git-town.#{configuration} '#{value}'" end def set_global_configuration configuration, value run "git config --global git-town.#{configuration} '#{value}'" end
true
e962f6fdeb5c680df2e276b0322e1610ffb1f725
Ruby
MikeSilvis/shindig
/app/lib/refresh_google_token.rb
UTF-8
803
2.609375
3
[]
no_license
class RefreshGoogleToken attr_accessor :client, :google_account def initialize(google_account) @google_account = google_account end def get_new_token refresh_token = google_account.refresh_token.gsub("/", "%2F") resp = client.post do |req| req.url "/o/oauth2/token" req.body = "client_secret=#{GOOGLE_SECRET}&grant_type=refresh_token&refresh_token=#{refresh_token}&client_id=#{GOOGLE_KEY}" end JSON.parse(resp.body) end def save_token google_account.token = get_new_token["access_token"] google_account.save end def client Faraday.new(:url => "https://accounts.google.com") do |faraday| faraday.request :url_encoded faraday.response :logger faraday.adapter Faraday.default_adapter end end end
true
4e8d5934ea25aa9b70a7ca3983ad5a8210373624
Ruby
nakulsapkal/two_player_math_game
/questions.rb
UTF-8
221
3.421875
3
[]
no_license
class Questions attr_accessor :question, :answer def initialize() @number_1=rand(1..20) @number_2=rand(1..20) @answer= @number_1 + @number_2 @question="What does #{@number_1} plus #{@number_2} equals?" end end
true
dc5cbbc7a042aee8af1f9cb15b02933e71b1adf6
Ruby
alexxck/RoR-Ruby-Basics
/1 Lesson/48.rb
UTF-8
204
2.6875
3
[]
no_license
#Дан целочисленный массив и интервал a..b. Найти максимальный из элементов в этом интервале. m=[1,2,3,45,4,6] a=3 b=5 p m[a..b].max
true
da306a1a9af5dc3810fe8ca4bc2c5269a2f4b06c
Ruby
jimanx2/translatable_model
/lib/translatable_model.rb
UTF-8
1,769
2.625
3
[ "MIT" ]
permissive
require "translatable_model/version" require "translatable_model/railtie" if defined?(Rails) module TranslatableModel class ActiveRecord::Base class << self def translatable(column, option = {}) # check if coloumn exists raise "Column #{column} does not exist in Model #{self.name}" unless self.column_names.include? column.to_s define_method column do MyModel.new(column, self) end end end end class MyModel < String attr_accessor :attributes attr_accessor :parent attr_accessor :column def method_missing(method_sym, *args, &block) locale = method_sym.to_s.gsub('=', '') if I18n.config.available_locales_set.include? locale define_attribute(locale) send(method_sym, args, block) else super(method_sym, args, block) end end def initialize(column, parent) @parent = parent @column = column while (@attributes = is_json?(parent[column]))==false do parent.send(:"#{column}=", {I18n.default_locale => parent[column]}.to_json) parent.save end super(@attributes[I18n.locale.to_s] || "Undefined translation for #{I18n.locale.to_s}") @attributes.each_key do |locale| define_attribute locale end end def is_json?(json) begin return JSON.parse(json) rescue Exception => e return false end end def define_attribute(locale) define_singleton_method locale do @attributes[locale] end define_singleton_method "#{locale}=" do |newval| @attributes[locale] = newval @parent.send("#{@column}=", @attributes.to_json) end end end end
true
cfde32255fec331e6fda7ce6abfd645a21e7a209
Ruby
masterkain/concurrent-ruby
/tasks/stresstest/support/stressor.rb
UTF-8
2,012
3.21875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require_relative 'word_sec' module Stressor FILE_PATH = File.dirname(__FILE__) TEST_FILES = { test_data_a: { file: 'TestdataA.txt', total: 13, highest_count: 4 }, test_data_b: { file: 'TestdataB.txt', total: 80, highest_count: 10 }, test_data_c: { file: 'TestdataC.txt', total: 180, highest_count: 17 }, the_art_of_war: { file: 'the_art_of_war.txt', total: 2653, highest_count: 294 }, the_republic: { file: 'the_republic.txt', total: 11497, highest_count: 1217 }, war_and_peace: { file: 'war_and_peace.txt', total: 20532, highest_count: 2302 } } Tally = Class.new do attr_reader :good, :bad, :ugly, :total def initialize @good, @bad, @ugly, @total = 0, 0, 0, 0 @mutex = Mutex.new end def add(result) @mutex.synchronize do case result when :good @good += 1 when :bad @bad += 1 when :ugly @ugly += 1 end @total += 1 end end def <<(result) self.add(result) return self end end def random_dataset d100 = rand(100) + 1 if d100 < 28 return :test_data_a elsif d100 < 56 return :test_data_b elsif d100 < 84 return :test_data_c elsif d100 < 94 return :the_art_of_war elsif d100 < 100 return :the_republic else return :war_and_peace end end module_function :random_dataset def test(dataset) dataset = TEST_FILES[dataset] infile = File.open(File.join(FILE_PATH, dataset[:file])) words, total_word_count = WordSec.make_word_list(infile) infile.close tally = WordSec.tally_from_words_array(words, true) if tally[:total] == dataset[:total] && tally[:highest_count] == dataset[:highest_count] return :good else return :bad end rescue => ex return :ugly end module_function :test end
true
19dd92c6a2ee5945191b573a034358102272ab85
Ruby
appirio-tech/cs-api
/app/models/salesforce.rb
UTF-8
5,409
2.640625
3
[]
no_license
require 'uri' class Salesforce include HTTParty format :json headers 'Content-Type' => 'application/json' def self.esc(str) URI.escape(str) end def self.set_header_token(access_token) headers 'Authorization' => "OAuth #{access_token}" end def self.access_token(type=:public) client = Restforce.new :username => ENV['SFDC_PUBLIC_USERNAME'], :password => ENV['SFDC_PUBLIC_PASSWORD'], :client_id => ENV['DATABASEDOTCOM_CLIENT_ID'], :client_secret => ENV['DATABASEDOTCOM_CLIENT_SECRET'], :host => ENV['DATABASEDOTCOM_HOST'] client.authenticate!.access_token end # # Returns a restforce client from an access_token # * *Args* : # - access_token -> the oauth token to use # * *Returns* : # - Restforce client # * *Raises* : # - ++ -> # def self.restforce_client(access_token) Restforce.new :oauth_token => access_token, :instance_url => ENV['SFDC_INSTANCE_URL'] end # # Makes generic 'get' to CloudSpokes Apex REST services # * *Args* : # - url_string -> the string to be appended to teh end of the url # * *Returns* : # - a results object # * *Raises* : # - ++ -> # def self.get_apex_rest(url_string, version='v.9') Forcifier::JsonMassager.deforce_json(get(ENV['SFDC_APEXREST_ROOT_URL']+"/#{version}#{url_string}")) end # # Makes generic 'post' to CloudSpokes Apex REST services # * *Args* : # - url_string -> the string to be appended to teh end of the url # * *Returns* : # - a results object # * *Raises* : # - ++ -> # def self.post_apex_rest(url_string, options) Forcifier::JsonMassager.deforce_json(post(ENV['SFDC_APEXREST_URL']+"#{url_string}", options)) end # # Makes generic 'put' to CloudSpokes Apex REST services # * *Args* : # - url_string -> the string to be appended to teh end of the url # * *Returns* : # - a results object # * *Raises* : # - ++ -> # def self.put_apex_rest(url_string, params={}) Forcifier::JsonMassager.deforce_json(put(ENV['SFDC_APEXREST_URL']+"#{url_string}?#{params.to_param}")) end # # Makes generic 'get' to CloudSpokes Apex REST services # and returns success # * *Args* : # - url_string -> the string to be appended to teh end of the url # * *Returns* : # - true/false # * *Raises* : # - ++ -> # def self.get_apex_rest_return_boolean(url_string) success = false success = true if get(ENV['SFDC_APEXREST_URL'] + "#{url_string}")['Success'].eql?('true') success end # # Performs a soql query against salesforce # * *Args* : # - access_token -> the oauth token to use # - soql -> the soql query # * *Returns* : # - a results object # * *Raises* : # - ++ -> # def self.query_salesforce(access_token, soql) Forcifier::JsonMassager.deforce_json(restforce_client(access_token).query(soql)) rescue Exception => e puts "[FATAL][Salesforce] Query exception: #{soql} -- #{e.message}" nil end # # Creates a new record in salesforce # * *Args* : # - access_token -> the oauth token to use # - params -> the hash of values for the new record # * *Returns* : # - new record id # * *Raises* : # - ++ -> # def self.create_in_salesforce(access_token, sobject, params) {:success => true, :message => restforce_client(access_token).create!(sobject, params)} rescue Exception => e puts "[FATAL][Salesforce] Create exception: #{e.message}" {:success => false, :message => e.message} end # # Updates a new record in salesforce # * *Args* : # - access_token -> the oauth token to use # - params -> the hash of values for the new record # * *Returns* : # - new record id # * *Raises* : # - ++ -> # def self.update_in_salesforce(access_token, sobject, params) {:success => restforce_client(access_token).update!(sobject, params), :message => ''} rescue Exception => e puts "[FATAL][Salesforce] Update exception: #{e.message}" {:success => false, :message => e.message} end # # Makes generic destroy to delete a records in salesforce # * *Args* : # - sobject -> the sObject to create # - id -> the id of the record to delete # * *Returns* : # - a hash containing the following keys: success, message # * *Raises* : # - ++ -> # def self.destroy_in_salesforce(access_token, sobject, id) restforce_client(access_token).destroy!(sobject, id) {:success => true, :message => 'Record successfully deleted.'} rescue Exception => e puts "[FATAL][Salesforce] Destroy exception for Id #{id}: #{e.message}" {:success => false, :message => e.message} end # # Makes generic destroy to delete a records in salesforce # * *Args* : # - sobject -> the sObject to create # - id -> the id of the record to delete # * *Returns* : # - a hash containing the following keys: success, message # * *Raises* : # - ++ -> # def self.picklist_values(access_token, sobject, field) restforce_client(access_token).picklist_values(sobject, field) rescue Exception => e puts "[FATAL][Salesforce] Exception getting picklist values: #{e.message}" {:success => false, :message => e.message} end end
true
6065d97ad36a61742452274fb28e132d6a351969
Ruby
tstaros23/seattle_grace_2105
/lib/doctor.rb
UTF-8
204
2.765625
3
[]
no_license
class Doctor attr_reader :name, :specialty, :salary def initialize(doctor_info) @name = doctor_info[:name] @speciality = doctor_info[:specialty] @salary = doctor_info[:salary] end end
true
9bc4f19c5470aa09b535eb36c3fe30dbeb7587ae
Ruby
bah87/app-academy-daily-projects
/W1D4/minesweeper/board.rb
UTF-8
514
3.109375
3
[]
no_license
class Board attr_reader :grid def initalize (grid = Array.new(9){Array.new(9)}) @grid = grid end def self.populate(num_tiles) tiles = [] grid = Array.new(num_tiles**0.5){Array.new(num_tiles**0.5)} grid.each_with_index do |row, i| row.each_with_index do |val, j| pos = [i, j] bomb = rand(1..10) == 1 tiles << Tile.new(pos, bomb) end end self.new(tiles) end def neighbors(tile) end def neighbor_bomb_count end end
true
13bafeea9d1d2cef7d7a5026e5ec214a20683341
Ruby
mjaric/r-calc
/spec/spec_helper.rb
UTF-8
1,043
3.015625
3
[ "MIT" ]
permissive
require 'r_calc' #require 'supermodel' #require 'minitest/spec' #require 'minitest/autorun' module RCalcHelpers class Calculator < RCalc::FormulaProcessor # Let's just add all of the usual operators include ::RCalc::ParentheticalGrouping # () include ::RCalc::AssignmentOperator # = include ::RCalc::LastResultOperator # $ include ::RCalc::ArithmeticOperators # +-*/%^ include ::RCalc::BooleanOperators # true false and or eq ne gt lt ge le not include ::RCalc::FunctionOperators # sum(), max(), min() # example of adding custom operators def AddOperators_custom calc = self # Now let's show how you can use a function to access a constant, like PI @operators << ::RCalc::BinaryOperator.new("[", 3) {|x, y| x.value + y.value} @operators << ::RCalc::UnaryOperator.new("]", 4) { |x| x.value } end end def calculator values = Hash.new calc = Calculator.new do |key, val| values[key] = val if val values[key] end [calc, values] end end
true
9abfc8aab49935440026d1e15defe6d212dba38e
Ruby
yuzixun/algorithm_exercise
/main/20170327-122.rb
UTF-8
641
4.09375
4
[]
no_license
# Say you have an array for which the ith element is the price of a given stock on day i. # Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). # Subscribe to see which companies asked this question. # @param {Integer[]} prices # @return {Integer} def max_profit(prices) sum = 0 prices.size.times do |index| sum += [prices.fetch(index+1, 0) - prices[index], 0].max end sum end puts max_profit([1])
true
5f7409b3c40cc50b1f21c42e2cc3d3ac59bf708a
Ruby
prakash-dubey/Training
/Ruby/mixin.rb
UTF-8
237
3.046875
3
[]
no_license
module A def a1 puts "in a1" end def a2 puts "in a2" end end module B def b1 puts "in b1" end def b2 puts "in b2" end end class Sample include A exclude A end Sample.a1 a = Sample.new a.a1
true
b9c9bb30df20ce526ed28e2a999eaf8f17ec5fe1
Ruby
Michael-S-cott/SerialMatrix
/Playback.rb
UTF-8
438
2.671875
3
[]
no_license
# Welcome to Sonic Pi v3.1 ary = [61, 72, 83] i = 0 j = 0 data = Array.new voice = Array.new linea = '' use_synth :tri File.open('/Users/michaelscott/desktop/SerialMatrix/SonicPiInput.txt','r') do |f1| while linea = f1.gets while i <linea.length-1 data = linea[i]+linea[i+1] voice = voice.push(data) play voice[j].to_i print("hi") sleep 1 j +=1 i +=3 end i = 0 end end
true
993ccb5c92dcb2fb01ebb2414c0ea4c039f12db6
Ruby
eakmotion/RubyPracticeProblems
/password_generator.rb
UTF-8
663
3.375
3
[]
no_license
# You need to write a password generator that meets the following criteria: # 6 - 20 characters long # contains at least one lowercase letter # contains at least one uppercase letter # contains at least one number # contains only alphanumeric characters (no special characters) # Return the random password as a string. require 'spec_helper' ALPHA_NUM = [*('a'..'z'), *('A'..'Z'), *('0'..'9')] def password_gen Array.new(20) { ALPHA_NUM.sample }.take(rand(6..20)).join end def test_pwd(pwd) (/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^\W_]{6,20}$/=~pwd) != nil end describe 'password_gen' do it "Example cases" do expect(test_pwd(password_gen())) end end
true
418d49ef1775b118bc1dfca381ba361f158d69f4
Ruby
ln1draw/selfsite
/my_app.rb
UTF-8
1,164
2.765625
3
[]
no_license
require 'sinatra' require 'yaml' class MyApp < Sinatra::Base before do @posts = Dir.glob("views/posts/*.erb").map {|path| path.split("/").last.gsub(".erb", "") } @sorted_posts = meta_data.sort_by {|post, data_hash| data_hash["date"]}.reverse end get '/' do erb :index end get '/about' do erb :about end get'/blog/:post_name' do #since @posts now exists, I can call it other places (because line 14 created an array of post names) html = erb("/posts/#{params[:post_name]}".to_sym, layout: false) html = html.split("\n\n", 2).last erb html end def meta_data if @meta_data @meta_data else @meta_data = {} @posts.each do |post| html = erb("/posts/#{post}".to_sym, layout: false) puts html.inspect meta = YAML.load(html.split("\n\n", 2).first) @meta_data[post] = meta end @meta_data end end get '/byfirst' do @recent = false erb :adablog end get '/ada-blog' do @recent = false erb :adablog end get '/bylast' do @recent = true erb :adablog end get '/dealwithit' do erb :dealwithit end end
true
77d209a5feaa1255d149bd83a7a9bc082604470e
Ruby
SteRobWms/oo-my-pets-houston-web-012720
/lib/owner.rb
UTF-8
1,372
3.4375
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'pry' require_relative 'cat.rb' require_relative 'dog.rb' class Owner @@all = [] attr_reader :name, :species def initialize(name) @name = name @species = "human" @@all << self end def say_species "I am a #{@species}." end def self.all @@all end def self.count @@all.count end def self.reset_all @@all.clear end def cats Cat.all.select do |i| i.owner == self end end def dogs Dog.all.select do |i| i.owner == self end end def buy_cat(name) Cat.new(name,self) # # binding.pry # cat = find_cat(name) # cat.owner = self # p Owner.all[0]. # # cats.push(cat) # p cats # p self.find_cat(name) end def buy_dog(name) Dog.new(name,self) end def walk_dogs dogs.each{|d| d.mood = "happy"} end def feed_cats cats.each{|c| c.mood = "happy"} end def sell_pets cats.each{|c| c.mood = "nervous"} dogs.each{|c| c.mood = "nervous"} cats.each{|c| c.owner = nil} dogs.each{|c| c.owner = nil} end def list_pets "I have #{dogs.count} dog(s), and #{cats.count} cat(s)." end def find_cat(name) Cat.all.find{|i| i.name == name} end def find_dog(name) Dog.all.find{|i| i.name == name} end end # anam = Owner.new("Anam") # caleb = Owner.new("Caleb") # raul = Owner.new("Raul") # binding.pry 0
true
56147b96e9c9b0e42535ab5fb5c8c7982b2705c9
Ruby
synion/Codeval
/new_exerise/file_open.rb
UTF-8
375
3.28125
3
[]
no_license
filename = " " in_file = nil print "Enter the filename" filename = gets.chomp! if File.exists?(filename) && File.readable?(filename) in_file = File.open(filename, "r") in_file.each do |line| puts line end in_file.close puts "finish" elsif !File.exists?(filename) puts "File not exstist" elsif !File.readable?(filename) puts "Can't read" end
true
c8ecc07155dc5c7e892f53e8399c16319e236f2d
Ruby
thoughtbot/kumade
/lib/kumade/rake_task_runner.rb
UTF-8
578
2.53125
3
[ "MIT" ]
permissive
module Kumade class RakeTaskRunner def initialize(task_name) @task_name = task_name end def invoke return unless task_defined? Kumade.configuration.outputter.success("Running rake task: #{@task_name}") Rake::Task[@task_name].invoke if task_should_be_run? end private def task_defined? load_rakefile Rake::Task.task_defined?(@task_name) end def task_should_be_run? !Kumade.configuration.pretending? end def load_rakefile load("Rakefile") if File.exist?("Rakefile") end end end
true
162662d28d6aa6ffa41268109515c2ba2c57c650
Ruby
RIVASW/tennis
/spec/sets/initial_spec.rb
UTF-8
3,370
2.875
3
[]
no_license
# frozen_string_literal: true require 'sets/initial' RSpec.describe Sets::Initial do subject do described_class.new( player1_games: player1_games, player2_games: player2_games, player1_name: player1_name, player2_name: player2_name, score_counter: score_counter, ) end let(:score_counter) do Scores::Initial.new( player1_points: player1_points, player2_points: player2_points, player1_name: player1_name, player2_name: player2_name, ) end let(:player1_games) { 0 } let(:player2_games) { 0 } let(:player1_points) { 0 } let(:player2_points) { 0 } let(:player1_name) { 'Player 1' } let(:player2_name) { 'Player 2' } context 'when games are 0 - 0' do context 'when points are 0 - 0' do it 'returns games 0 - 0 if no scores added to players' do expect(subject.score).to eq('0 - 0') end it 'returns points 15 - 0 score and initial set class' do new_set = subject.add_point_player1 expect(new_set.score).to eq('0 - 0, 15 - 0') expect(new_set).to be_an_instance_of(described_class) end end context 'when points are 15 - 30' do let(:player1_points) { 2 } let(:player2_points) { 3 } it 'returns deuce and initial set class' do new_set = subject.add_point_player1 expect(new_set.score).to eq('0 - 0, Deuce') expect(new_set).to be_an_instance_of(described_class) end it 'returns games 0 - 1 and initial set class' do new_set = subject.add_point_player2 expect(new_set.score).to eq('0 - 1') expect(new_set).to be_an_instance_of(described_class) end end end context 'when games are 5 - 6' do let(:player1_games) { 5 } let(:player2_games) { 6 } context 'when points are 30 - 0' do let(:player1_points) { 3 } let(:player2_points) { 0 } it 'returns games 6 - 6, initial set class and tie score class' do new_set = subject.add_point_player1 expect(new_set.score).to eq('6 - 6') expect(new_set).to be_an_instance_of(described_class) expect(new_set.__send__(:score_counter)).to be_an_instance_of(Scores::Tie) end end end context 'when games are 6 - 6' do let(:player1_games) { 6 } let(:player2_games) { 6 } let(:score_counter) do Scores::Initial.new( player1_points: player1_points, player2_points: player2_points, player1_name: player1_name, player2_name: player2_name, ) end context 'when points are 5 - 6' do let(:player1_points) { 5 } let(:player2_points) { 6 } it 'returns games 6 - 7 and victory set class' do new_set = subject.add_point_player2 expect(new_set.score).to eq('6 - 7, Player 2 has won!') expect(new_set).to be_an_instance_of(Sets::Victory) end end end context 'when games are 6 - 5' do let(:player1_games) { 6 } let(:player2_games) { 5 } context 'when points are 5 - 6' do let(:player1_points) { 3 } let(:player2_points) { 2 } it 'returns games 7 - 5 and victory set class' do new_set = subject.add_point_player1 expect(new_set.score).to eq('7 - 5, Player 1 has won!') expect(new_set).to be_an_instance_of(Sets::Victory) end end end end
true
551dc309186b05e2202a0132014542b252a591be
Ruby
santiagosan93/like_tutorial
/db/seeds.rb
UTF-8
1,018
2.59375
3
[]
no_license
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) if Rails.env.development? require 'faker' puts "Deleting all places" Place.delete_all puts "Finished" puts "deleting all users" User.delete_all puts "Finished" puts "Creating Santi" User.create(email: "[email protected]", password: "santiago") puts "Finished" puts "Creating 10 random users" 10.times do User.create(email: Faker::Internet.email, password: "testing") end puts "Finished" puts "Creating 10 random places" 10.times do Place.create(address: Faker::Address.city, user: User.all.sample) end puts "Finished" puts "Congrats, you now have #{User.count} users and #{Place.count} places" end
true
03de7c0ad140a45b041f1045f69ed0bfcc7dc59c
Ruby
g5search/yield_star_client
/spec/yield_star_client/models/rent_summary_spec.rb
UTF-8
2,055
2.734375
3
[ "MIT" ]
permissive
require "spec_helper" module YieldStarClient describe RentSummary do context "attributes" do subject { described_class } it { is_expected.to have_attribute(:effective_date, Date) } it { is_expected.to have_attribute(:external_property_id, String) } it { is_expected.to have_attribute(:floor_plan_name, String) } it { is_expected.to have_attribute(:unit_type, String) } it { is_expected.to have_attribute(:bedrooms, Float) } it { is_expected.to have_attribute(:bathrooms, Float) } it { is_expected.to have_attribute(:avg_square_feet, Integer) } it { is_expected.to have_attribute(:min_market_rent, Integer) } it { is_expected.to have_attribute(:max_market_rent, Integer) } it { is_expected.to have_attribute(:concession_type, String) } it { is_expected.to have_attribute(:min_concession, Integer) } it { is_expected.to have_attribute(:max_concession, Integer) } it { is_expected.to have_attribute(:min_final_rent, Integer) } it { is_expected.to have_attribute(:max_final_rent, Integer) } it { is_expected.to have_attribute(:floor_plan_description, String) } end describe ".new_from" do it "maps attributes correctly" do args = { bed_rooms: 2.5, bath_rooms: 1, avg_sq_ft: 50 } rs = RentSummary.new_from(args) expect(rs.bedrooms).to eq 2.5 expect(rs.bathrooms).to eq 1 expect(rs.avg_square_feet).to eq 50 end end describe "#bedrooms_override_from_unit_type and #bathrooms_override_from_unit_type" do context "unit_type is composed of two dimensions separated by an 'x' character" do let(:unit_type) { "3.5x2" } let(:rent_summary) { RentSummary.new(unit_type: unit_type) } it "return dimensions extracted from the unit_type" do expect(rent_summary.bedrooms_override_from_unit_type).to eq 3.5 expect(rent_summary.bathrooms_override_from_unit_type).to eq 2 end end end end end
true
3291ad3560febf3a6edfcf48b15dc41bbc6c655d
Ruby
Carolsien/MetodyObliczeniowe
/lib/hermitcore.rb
UTF-8
3,772
3.328125
3
[]
no_license
class Hermit @n # Liczba podprzedzialow @a # Poczatek przedzialu @b # Koniec przedzialu @x # Punkty wezlowe siatki @y # Wartosci f(x) @z # Wartosci f'(x) @t # Generowana lista dwukrotnych x @f0 # Generowana lista wartosci @f # Wynikowa lista metody @debug = false # Flaga wyswietlania danych kontrolnych def initialize(a, b, n, y, z) @a = a.to_f @b = b.to_f @n = n.to_f @y = y @z = z @x = [] # Obliczenie kroku h h = (b.to_f - a.to_f) / n.to_f # Wypelnienie danych x tx = a for i in Range.new(0, n) @x.push(tx) tx = tx + h end end def compute() x = @x y = @y z = @z # Tworzymy tablice t poprzez wstawienie x podwojnie t = [] for i in x t.push(i.to_f) t.push(i.to_f) end @t = t # Tworzymy pierwszy wiersz z wielomianami stopnia pierwszego poprzez wpisanie wartosci funkcji i pochodnej dla kazdego punktu f0 = [] for i in Range.new(0, t.count-1) f0.push(y[i].to_f) f0.push(z[i].to_f) end @f0 = f0 # Inicjujemy tabele z wynikami tn = (@n - 1) * 2 tab = Array.new(tn + 1, Array.new(tn + 1)) wynik = [] # Wstawiamy pierwszy wiersz do macierzy for i in Range.new(0, tn) k = f0[i].to_f tab[0][i] = k wynik.push(k) if i == 0 if k < 0 print " #{k} |" if @debug == true else print " #{k} |" if @debug == true end end # Obliczamy macierz za pomoca metody g = 0 for i in Range.new(1, tn) g = g + 1 for j in Range.new(0, tn-g) # Sprawdzamy czy dzielenie przez 0 d = t[j+g]-t[j] if (d == 0) k = z[t[j]].to_f tab[i][j] = k wynik.push(k) if j == 0 print " #{k} |" if @debug == true else k = ((tab[i-1][j+1] - tab[i-1][j]) / d).to_f puts "#{i} #{j}" if @debug == true tab[i][j] = k wynik.push(k) if j == 0 if k < 0 print " #{k} |" if @debug == true else print " #{k} |" if @debug == true end end end puts if @debug == true end #Zapisujemy wyniki @f = wynik # Wydruk kontrolny obliczonych danych print "pierwsza kolumna: #{wynik}" if @debug == true puts if @debug == true print "perwszy wiersz: #{f0}" if @debug == true end def newton(n, k, setT) # Generowanie podzbiorow k elementowych z pierwszych n elementow zbioru setT setT.take(n).combination(k).to_a end # Funkcja generujaca liste wspolczynnikow dla kolejnych poteg x (x^0, x^1, x^2 ...) w celu wydruku def getW() t = @t f = @f n = @n wynik = Array.new(n) for i in Range.new(0, n-1) if i > 0 print " + " if @debug == true end print "x^#{i}(" if @debug == true wynik[i] = 0 for j in Range.new(i, n-1) x = newton(j, j-i, t) if x.count > 0 for a in x tmp = f[j] if j != i if (((j-i) % 2) == 0) tmp = f[j] print " + " if @debug == true else tmp = -tmp print " - " if @debug == true end end print "f[#{j}]" if @debug == true for b in a print "*" if @debug == true print b if @debug == true tmp *= b end wynik[i] += tmp end end end print ")" if @debug == true end return wynik end # Wydrukowanie na ekran wielomianu przy pomocy listy wspolczynnikow dla kolejnych poteg x (x^0, x^1, x^2 ...) def printW(w) puts "\n" if @debug == true puts "\n" if @debug == true n = w.count for i in Range.new(0, n-1) print "+" if i > 0 && w[i] > 0 && w[i-1] != 0 print "#{w[i]}*" unless w[i] == 0 || w[i] == 1 || w[i] == -1 print "-" if w[i] == -1 print "x^#{i}" unless w[i] == 0 end end # Gettery def a() @a end def b() @b end def n() @n end def x() @x end def y() @y end def z() @z end def t() @t end def f() @f end end
true
c045b1c999c408b2037b704790584e72975e3d16
Ruby
agiratech-keerthana/ruby_sample
/arms_st.rb
UTF-8
98
2.953125
3
[]
no_license
a=123 len = a.to_s.length c = 0 puts len a.to_s.each_char{|b| c = c + b.to_i**len} puts c
true
41d6c33e7938ace9b54743d0e996aea1be6c1f94
Ruby
scottiler/rubybabble
/tile_group.rb
UTF-8
355
3.421875
3
[]
no_license
class TileGroup attr_accessor :tiles def initialize() @tiles = [] end def append(tile) @tiles << tile end def remove(tile) @tiles.delete_at(@tiles.index(tile)) end def hand hand = "" @tiles.each {|tile| hand += tile.to_s} return hand end def is_empty return @tiles.empty? end end
true
0e7985655bcd1b855cf72a7a028a7faf04865911
Ruby
SiCuellar/Code_Wars
/Ruby/Isograms/algo.rb
UTF-8
331
3.265625
3
[]
no_license
require 'pry' class Algo def is_isogram(word) if word.downcase.chars.uniq!.nil? == true true else false end end end # def is_isogram(string) # string.downcase.chars.uniq == string.downcase.chars # end # def is_isogram(string) # letters = string.downcase.chars # letters == letters.uniq # end
true
9f1fe0ec8f39fcf33bbeab56513a7ec2cb19cc3f
Ruby
cored/codingkatas
/ruby/find_sum/find_sum_spec.rb
UTF-8
781
3.3125
3
[]
no_license
require 'minitest/autorun' module FindSum extend self def call(array) array.each.with_index.inject(0) do |sum, (inner_array, idx)| sum += inner_array[idx % array.size] end end end describe FindSum do it 'returns the diagonal sum for a two dimensional array of lenght 4' do example_array = [[1,0,0,0], [0,1,0,0], [0,0,1,0], [0,0,0,1]] FindSum.(example_array).must_equal 4 end it 'returns the diagonal sum for a two dimensional array of lenght 5' do example_array = [[1,0,0,0,0], [0,1,0,0,0], [0,0,1,0,0], [0,0,0,1,0], [0,0,0,0,1] ] FindSum.(example_array).must_equal 5 end end
true