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
0ae0b759ed22698f603dc62a1944edafe0bc5ffa
Ruby
Awilmerding1/prime-ruby-v-000
/prime.rb
UTF-8
364
3.40625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def prime?(integer) i = 3 array = (i..integer-1).to_a if integer == 1 return false elsif integer < 0 return false elsif integer == 2 || integer == 3 return true end while integer.even? == true return false end array.all? do |prime| if integer % prime > 0 true else false end end end
true
43cd4950e1af1348ab6dc109015fcbcdad4b88fa
Ruby
ECOtterstrom/IntroToProgRuby
/8_more_stuff/ex_84.rb
UTF-8
136
3.109375
3
[]
no_license
# 8_more_stuff exercise 4 def execute(&block) block.call end execute {puts "Hello from inside the execute method!"}
true
528624e8e62eb1eb48fbb30d46448a866d2b759d
Ruby
ted-scanlan/battle-challenge-new
/spec/player_spec.rb
UTF-8
888
3.296875
3
[]
no_license
require 'player.rb' describe Player do other_player = Player.new('other') it 'returns player name' do tester = Player.new('Ted') expect(tester.name).to eq 'Ted' end it 'returns player hit points' do tester = Player.new('Ted') expect(tester.hit_points).to eq 60 end describe "#attack" do it 'responds with one argument' do tester = Player.new('Ted') expect(tester).to respond_to(:attack).with(1).argument end it 'deducts hit points from oppoent player' do tester = Player.new('Ted') tester.attack(other_player) expect(other_player).to receive("deduct") other_player.deduct end end describe "#deduct" do it 'deducts hit points from player if attacked' do tester = Player.new('Ted') expect { tester.attack(other_player) }.to change{other_player.hit_points}.by(-10) end end end
true
53d363b0a2630dc7a67553941a7eb96a2a8172f4
Ruby
dinarka/ruby_lesson3
/quad_equation.rb
UTF-8
639
3.53125
4
[]
no_license
puts 'Введите коэффициент а:' coef_a = gets.chomp.to_f puts 'Введите коэффициент b:' coef_b = gets.chomp.to_f puts 'Введите коэффициент c:' coef_c = gets.chomp.to_f discr = coef_b ** 2 - (4 * coef_a * coef_c) if discr > 0 d_sqrt = Math.sqrt(discr) x1 = (-coef_b + d_sqrt) / 2 * coef_a x2 = (-coef_b - d_sqrt) / 2 * coef_a puts "Дискриминант: #{discr} \nx1: #{x1} \nx2: #{x2}" elsif discr == 0 x = -coef_b / 2 * coef_a puts "Дискриминант: #{discr} \nx: #{x}" elsif discr < 0 puts "Дискриминант: #{discr} \nКорней нет" end
true
68335d2c437383e960fa8b9618fb2f6dc7bf9dc2
Ruby
AdamPrusse/metaprogramming
/metaprogramming_example_2.rb
UTF-8
245
4
4
[]
no_license
class String def censor(bad_word) self.gsub! "#{bad_word}", "CENSORED" end def num_of_chars size end end # p "The bunny was in trouble with the king's bunny".censor("bunny") p "Paul is such a bunny bunny bunny bunny bunny".num_of_chars
true
1047f6faeac6aa545ea8243fcb9d73b6881931d5
Ruby
jasmarc/PageRank
/main.rb
UTF-8
2,451
3.25
3
[]
no_license
$LOAD_PATH.unshift File.dirname(__FILE__) + '/lib' require "rubygems" require "PageCollection" require "pp" require "PageRank" require "yaml" # This is the cache file. We don't want to spider if we don't # have to. It takes a long time. FILE = "collection.yaml" # Let's read that file from Dr. Ginsparg collection = PageCollection.new("test3.txt") if(!File.exist? FILE) # Are our results cached? collection.crawl # No. Let's crawl! collection.save(FILE) # Let's save it for next time else puts "Horray! I didn't have to crawl. Crawl results are cached in 'collection.yaml'" collection.load(FILE) end # Let's convert our data into a sparse matrix, e.g. something like this: # [[1, [3]], # [2, [2, 3]], # [3, [1, 3, 4]]] link_matrix = collection.pages.values.map do |page| [page.id, page.links.values.map {|link| link.id}] end # Now we convert to a dense matrix, filling in with alpha = 0.2 link_matrix = PageRank.sparse_to_dense(link_matrix, 0.2) # Now we compute PageRank page_ranks = PageRank.pagerank(link_matrix).to_a # Now let's weave the PageRank back into our main datastructure collection.pages.each_value do |page| page.rank = page_ranks[page.id - 1] end # Let's produce the "metadata" file and Short Index Record puts "Short Index Record:" File.open("metadata", "w") do |f| collection.pages.values.sort {|a,b| b.rank <=> a.rank }.each do |page| f.puts "[#{page.id}]\t[#{page.rank}]\t[#{page.anchors.to_a.join(', ')}]" puts "Title: [#{page.title}]\tAnchor: [#{page.anchors.to_a.join(', ')}]" end end # This is our query function that's going to get used below def query(collection, q) case q when String: collection.pages.values.find_all do |page| page.include? q end.sort { |a, b| b.rank <=> a.rank}.map do |page| "[#{page.title}]\n\t[#{page.url}]\n\t[#{page.snippet}]" end.join("\n") when Array: collection.pages.values.find_all do |page| page.includes_any? q end.sort { |a, b| b.rank <=> a.rank}.map do |page| "[#{page.title}]\n\t[#{page.url}]\n\t[#{page.snippet}]" end.join("\n") end end # This is our "Search Engine" # We handle user input here puts "Enter a query or type 'ZZZ' to end." ARGF.each do |line| words = line.split if(words.size == 1) exit if words[0] == "ZZZ" puts query(collection, words[0]) elsif(words.size > 1) puts query(collection, words) else puts "Enter a query or type 'ZZZ' to end." end end
true
bba4c47c7014c47b25fd938ab8c58db8b3a6a6d8
Ruby
chaochaocodes/ruby-oo-relationships-practice-blood-oath-exercise-seattle-web-120919
/app/models/cult.rb
UTF-8
1,256
3.5625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Cult attr_accessor :slogan, :follower, :location, :founding_year attr_reader :name @@all = [] # @@follower_list = [] def initialize(name, location, year, slogan) @name = name @location = location @founding_year = year @slogan = slogan @@all << self end # accepts and adds Follower instance to this cult's list of followers # access through BloodOath! def recruit_follower(follower) BloodOath.new(self, follower) end # returns an Integer that is the number of followers in this cult def cult_population BloodOath.all.find_all do |oath| oath.cult == self end.size end def self.all # returns an Array of all the cults @@all end # find a Cult instance by name def self.find_by_name(name) Cult.all.find {|cults| cults.name == name} end # returns an Array of cults that are in that location def self.find_by_location(location) Cult.all.find_all {|cults| cults.location == location} end # returns all of the cults founded in that year def self.find_by_founding_year(year) Cult.all.find_all {|cults| cults.founding_year == year} end end
true
6079f971f043f65305912a68bb8e81bb6966579a
Ruby
Etsap/my-advent
/adventofcode2016/problem06.rb
UTF-8
683
3.453125
3
[]
no_license
input = "" File.open("input06.txt", 'r') {|f| input = f.read} counter = [{}, {}, {}, {}, {}, {}, {}, {}] input.split(/\s+/).each do |line| (0..7).each do |i| counter[i].has_key?(line[i]) ? counter[i][line[i]] += 1 : counter[i][line[i]] = 1 end end result1 = result2 = "" (0..7).each do |i| character1 = character2 = nil counter[i].each_key do |key| character1 = key if !character1 || counter[i][key] > counter[i][character1] character2 = key if !character2 || counter[i][key] < counter[i][character2] end result1 += character1 result2 += character2 end puts "Part 1: #{result1}" puts "Part 2: #{result2}"
true
43e28996337e5bbbddb6336ac53f86a3327b9fec
Ruby
davidmunoz4185/udacitask
/todolist.rb
UTF-8
1,700
3.703125
4
[]
no_license
class TodoList # methods and stuff go here def initialize(list_title) @title = list_title @items = Array.new # Starts empty! No Items yet! end attr_accessor :title, :items def add_item(new_item, priority=0) item = Item.new(new_item,priority) @items.push(item) end def rename(list_title) @title = list_title end def delete_item(index) @items.delete_at(index) end def toggle_status(index) @items[index].toggle_status end def rename_item(index, description) @items[index].description = description end def completed? return @items.all? {|item| item.completion_status == true} end def print header = "#{@title} -- Completed: #{completed?}" puts "-" * header.length puts header puts "-" * header.length longest_word = @items.inject(0) do |previous_length, current_word| current_length = current_word.description.length current_length > previous_length ? current_length : previous_length end @items.each_index {|index| puts "#{index} - [#{items[index].priority}]#{@items[index].description}".ljust(longest_word + 10) + "Completed: #{@items[index].completion_status}" } end end class Item # Initialize item with a description and marked as # not complete def initialize(item_description, priority=0) @description = item_description @completion_status = false @priority = priority end # methods and stuff go here attr_accessor :description, :completion_status, :priority def toggle_status @completion_status = !@completion_status end def print puts "#{@description} Completed: #{@completion_status} Priority: #{@priority}" end end
true
1bbebd95f87a15ecfb4842d44bcae16eb095eb95
Ruby
fanjieqi/LeetCodeRuby
/901-1000/901. Online Stock Span.rb
UTF-8
494
3.421875
3
[ "MIT" ]
permissive
class StockSpanner def initialize() @array, @index, @k = [], [], 0 end =begin :type price: Integer :rtype: Integer =end def next(price) i = @array.bsearch_index { |ele| ele > price } || @array.size @array.insert(i, price) @index.insert(i, @k) @k += 1 maxi = @index[i+1..-1].max maxi.nil? ? @array.size : @k - maxi - 1 end end # Your StockSpanner object will be instantiated and called as such: # obj = StockSpanner.new() # param_1 = obj.next(price)
true
1d2a13c6907925768717eedca81b2e5c3eca4176
Ruby
emadb/playground
/hackerrank-meeting-point/app.rb
UTF-8
1,504
3.890625
4
[]
no_license
# https://www.hackerrank.com/challenges/meeting-point class Point < Struct.new(:x, :y, :distance); end class MeetingPoint def evaluate(map) first = map[0] index = 0 map.each do |p1| p1.distance = 0 map.each do |p2| p1.distance = p1.distance + get_distance(p1, p2) end end max = 999999 map.each do |p| if p.distance < max max = p.distance end end max.floor end def get_distance(p1, p2) dx2 = (p1.x - p2.x) * (p1.x - p2.x) dy2 = (p1.y - p2.y) * (p1.y - p2.y) Math.sqrt(dx2 + dy2) end end =begin class MeetingPoint def evaluate(map) x, y = 0, 0 count = 0.0 map.each do |p| count = count + 1 x = x + p.x y = y + p.y end puts "x: #{x} / #{count} = #{x/count} #{(x/count).round}" puts "y: #{y} / #{count} = #{y/count} #{(y/count).round}" x = (x/count).round y = (y/count).round d = 0 map.each do |p| dx2 = (x - p.x) * (x - p.x) dy2 = (y - p.y) * (y - p.y) puts "sqrt(#{dx2} + #{dy2}) = " + Math.sqrt(dx2 + dy2).to_s d = d + Math.sqrt(dx2 + dy2).floor end d end end =end =begin (0,1) 2-0 * 2-0 = 4 2-1 * 2-1 = 1 sqrt(5) = 2,23 2 (2,5) 2-2 * 2-2 = 0 2-5 * 2-5 = 9 sqrt(9) = 2 3 (3,1) 2-3 * 2-3 = 1 2-1 * 2-1 = 1 sqrt(2) = 1,4 1 (4,0) - (2,2) 2-4 * 2-4 = 4 2-0 * 2-0 = 4 sqrt(8) = 2,8 3 =end
true
03ec108cdfeb4bc5ac756bfaa2675d39944f5f9b
Ruby
amenning/RSpec_TutorialsPoint
/spec/comparison_matchers_spec.rb
UTF-8
408
2.703125
3
[]
no_license
describe "An example of the comparison Matchers" do it "should show how the comparison Matchers work" do a = 1 b = 2 c = 3 d = 'test string' # The following Expectations will all pass expect(b).to be > a expect(a).to be >= a expect(a).to be < b expect(b).to be <= b expect(c).to be_between(1,3).inclusive expect(b).to be_between(1,3).exclusive expect(d).to match /TEST/i end end
true
a371d7656f3f87a33af28e99ff5c47db83f86b72
Ruby
davekinkead/ristretto
/specs/ristretto_spec.rb
UTF-8
600
2.53125
3
[ "MIT" ]
permissive
require 'ristretto' require 'minitest/autorun' describe Ristretto do let(:parsed_markdown) { Ristretto.parse('specs/specification.md') } describe "#execute" do it "executes simple ruby code" do Ristretto.execute(parsed_markdown).must_equal 890 end it "parsed required ristretto files" end describe "#parse" do it "parses markdown according to the Ristretto specification" do parsed_markdown.must_equal "espresso = ('coffee' + 'water').bytes.reduce :+\nristretto = espresso - 'water'.bytes.reduce(:+)/2" end it "parses backticked codeblocks" end end
true
e4ea7bfcaaff8f237249237f2e1e92f40963d19e
Ruby
angusjfw/takeaway-challenge
/lib/takeaway.rb
UTF-8
990
3.578125
4
[]
no_license
require_relative 'menu' require_relative 'order' require_relative 'phone' class Takeaway ERROR = 'Cannot place order: ' TOTAL = 'total does not match pricing!' DISH = ' not available!' def initialize(menu=Menu.new, order_klass=Order, phone=Phone.new) @the_menu = menu @order_klass = order_klass @phone = phone end def menu puts the_menu.format the_menu.raw end def place_order(order, total) dishes = order_klass.new(order, total).as_hash fail(ERROR + unavailable(dishes) + DISH) unless have? dishes fail(ERROR + TOTAL) unless correct?(dishes, total) phone.complete_order end private attr_reader :the_menu, :order_klass, :phone def have? dishes (dishes.keys - the_menu.raw.keys).empty? end def unavailable dishes (dishes.keys - the_menu.raw.keys).first end def correct?(dishes, total) dishes.reduce(0) do |result, (dish, number)| result + (the_menu.raw[dish] * number) end == total end end
true
860d19faf198cb3e288ee68a79b7b3df1052615f
Ruby
vcavallo/flatiron-assignments
/oojukebox.rb
UTF-8
1,421
3.734375
4
[]
no_license
class Jukebox def initialize(songs) @songs = songs @command = "" end def play puts "make a selection (song name) or type 'list' again:" @choice = gets.chomp.downcase puts "--> Now Playing: #{@songs .select {|song| song.downcase.include?(@choice)}}" if @choice == "list" list end end def list puts "- - - - - - - - - - - -" puts @songs puts "- - - - - - - - - - - -" if @choice == "list" play end end def help puts "- - - - - - - - - - - -" puts "type:" puts "'list' - see a list of songs" puts "'play' - put a song on" puts "'exit' - exit the program" puts "'help' - see this menu again" puts "- - - - - - - - - - - -" end def do_command(cmd) case cmd when "list" list when "play" play when "help" help when "exit" puts "Goodbye!" else puts "I didn't understand that. Try again or type 'help'." end end def call cmd = @command while cmd!= "exit" puts "enter a command." puts "for a list of commands, type 'help'." puts "to get out of here, type 'exit'." cmd = gets.chomp.downcase do_command(cmd) end end end songs = [ "Melvins - Gluey Porch Treatments", "Charles Mingus - Goodbye, Porkpie Hat", "Slayer - Angel of Death", "Raffi - Baby Beluga" ] j = Jukebox.new(songs) j.call
true
842ed8afedda1470343f0fbcc8964a629216c433
Ruby
Chakaitos/algorithms-sort
/sort.rb
UTF-8
1,339
3.609375
4
[]
no_license
module Sort def self.selection_sort(array) arr = array.clone n = arr.size if arr.size <= 1 return arr end n.times do |index| min_index = index (index+1).upto(n-1) do |i| if arr[i] < arr[min_index] min_index = i end end arr[index], arr[min_index] = arr[min_index], arr[index] end return arr end # return the array if it's size 1 or less # sort the left half # sort the right half # merge the two halves and return def self.mergesort(array) return array if array.length <= 1 mid_point = array.size / 2 left = array[0...mid_point] right = array[mid_point...array.size] left = mergesort(left) right = mergesort(right) merge(left, right) end def self.merge (left, right) result = [] if left == [] return right elsif right == [] return left else while left.length > 0 || right.length > 0 if left.length > 0 && right.length > 0 if left[0] <= right[0] result.push(left.slice!(0)) else result.push(right.slice!(0)) end elsif left.length > 0 result.concat(left.slice!(0, left.length)) elsif right.length > 0 result.concat(right.slice!(0, right.length)) end end end result end end
true
0586df9be16f7b756abcd03d8a6915d4c1717b30
Ruby
colleeno/landlord
/db/seeds.rb
UTF-8
1,160
2.609375
3
[]
no_license
require 'active_record' require_relative 'connection' require_relative '../models/apartment' require_relative '../models/tenant' Apartment.destroy_all Tenant.destroy_all Apartment.create(address: '1401 S Street', monthly_rent: 4000, sqft: 1500, num_beds: 2, num_baths: 2) Apartment.create(address: '867 Main Street', monthly_rent: 1000, sqft: 500, num_beds: 1, num_baths: 1) Apartment.create(address: '42 Wallaby Way', monthly_rent: 1500, sqft: 950, num_beds: 2, num_baths: 1) Tenant.create(name: 'P Sherman', age: '30', gender: 'Male', apartment_id: 74) Tenant.create(name: 'Nemo', age: '10', gender: 'Male', apartment_id: 74) Tenant.create(name: 'John Smith', age: '42', gender: 'Male', apartment_id: 72) Tenant.create(name: 'Whitney Cargill', age: '32', gender: 'Female', apartment_id: 72) Tenant.create(name: 'Cindy Lou', age: '12', gender: 'Female', apartment_id: 73) Tenant.create(name: 'Brie Jones', age: '32', gender: 'Female', apartment_id: 73) Tenant.create(name: 'Mark Appleby', age: '35', gender: 'Male', apartment_id: 3) Tenant.create(name: 'James Johnson', age: '40', gender: 'Male', apartment_id: 1) Tenant.create(name: 'Wendy Bite', age: '80', gender: 'Female', apartment_id: 1)
true
045b931bb537c5da22a8f3364a170d52cd6159f3
Ruby
jbuelna/galleriamacondo
/app/models/location.rb
UTF-8
569
2.515625
3
[]
no_license
class Location < ActiveRecord::Base has_many :paintings validates_presence_of :name, :address_line_1, :city, :state, :zip, :lat, :lng before_validation_on_create :geocode_address before_validation_on_update :geocode_address def address "#{address_line_1} #{address_line_2}, #{city}, #{state}" end def geocode_address logger.debug("Test") geo = GeoKit::Geocoders::MultiGeocoder.geocode(address) errors.add(:address, "Could not geocode address") unless geo.success self.lat, self.lng = geo.lat, geo.lng if geo.success end end
true
ded964344b8be99945fc71f45e3cb40dbccb5b24
Ruby
FlipTech9/countdown-to-midnight-online-web-prework
/countdown.rb
UTF-8
454
3.875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
#write your code here def countdown (starting_number) phrase = "HAPPY NEW YEAR!" starting_number = 10 while starting_number !=0 puts "#{starting_number} SECOND(S)!" starting_number -=1 end phrase end def countdown_with_sleep(starting_number) phrase = "HAPPY NEW YEAR!" starting_number = 10 while starting_number !=0 puts "#{starting_number} SECOND(S)!" sleep(1) starting_number -=1 end phrase end
true
72e7028741f1bc8806544716e75e629ebf0584ca
Ruby
davet1985/social-challenges
/api/app/model/user.rb
UTF-8
5,733
2.703125
3
[]
no_license
require 'bcrypt' require 'net/smtp' require 'yaml' $db = SQLite3::Database.open './hashbang.db' class User /USERS =/ CONFIG = YAML.load_file("./config/config.yml") unless defined? CONFIG include BCrypt attr_reader :name attr_reader :id attr_reader :token def initialize(id, name, token) @id = id @name = name @token = token end def self.usernameDoesNotExist(username) row = $db.get_first_row("select * from users where username = ?", username) userDoesNotExists = false if row == nil userDoesNotExists = true end userDoesNotExists end def self.emailDoesNotExist(email) row = $db.get_first_row("select * from users where email = ?", email) emailDoesNotExists = false if row == nil emailDoesNotExists = true end emailDoesNotExists end def self.getEmailAddress(userId) $db.get_first_row("select email from users where id = ?", userId) end def self.save(username, password, email) insert = <<-SQL INSERT INTO users values (NULL, ?, ?, ?, "inactive", 0) SQL $db.execute(insert, username, Password.create(password),email) userId = $db.last_insert_row_id() token = createToken(userId) sendNewUserEmail(email, token) end def self.sendNewUserEmail(email, token) message = <<-MESSAGE_END From: Social Challanges <me@fromdomain.com> To: A Test User <#{email}> Subject: SMTP e-mail test Please use this token to login http://#{CONFIG['frontend_url']}/#!/user/#{token} MESSAGE_END Net::SMTP.start('localhost', 1025) do |smtp| smtp.send_message message, 'me@fromdomain.com', 'test@todomain.com' end end def self.sendForgotPassword(email) row = $db.get_first_row("select * from users where email = ? and status='active' and loginAttempts < 5", email) if row != nil token = createToken(row[0]) sendForgotPasswordEmail(email, token) end end def self.createToken(userId) token = SecureRandom.uuid insertToken = <<-SQL INSERT INTO user_token values (NULL, ?, datetime('now', '+30 minutes'), ?) SQL $db.execute(insertToken, userId, token) token end def self.sendForgotPasswordEmail(email, token) message = <<-MESSAGE_END From: Social Challanges <me@fromdomain.com> To: A Test User <#{email}> Subject: SMTP e-mail test Please use this token to change your password http://#{CONFIG['frontend_url']}/#!/forgot/#{token} MESSAGE_END Net::SMTP.start('localhost', 1025) do |smtp| smtp.send_message message, 'me@fromdomain.com', 'test@todomain.com' end end def self.getIdFromToken(token) tokenDetails = getActiveToken(token) id = -1 if tokenDetails != nil id = tokenDetails[1] end id end def self.activate(token) tokenDetails = getActiveToken(token) if tokenDetails != nil activateUserAccount(tokenDetails[1]) true else false end end def self.activateUserAccount(id) update = <<-SQL update users set status = "active" where id = ? SQL $db.execute(update, id) end def self.getActiveToken(token) $db.get_first_row("select * from user_token where token = ? and expires > datetime('now')", token) end def self.changePassword(userid, password) update = <<-SQL update users set password = ? where id = ? SQL $db.execute(update, Password.create(password), userid) end class << self include BCrypt def get(token) row = $db.get_first_row("select * from session where token = ? and expires > datetime('now')", token) if row != nil $db.execute( "update session set expires= datetime('now', '+30 minutes') where id = ?", row[0]) User.new(row[1], row[2], row[5]) end end def logout(token) delete = <<-SQL DELETE FROM session WHERE token = ? SQL $db.execute(delete, token) end def authenticate(u, p) row = $db.get_first_row("select * from users where username = ? and status='active' and loginAttempts < 5", u) if row != nil userId = row[0] currentPassword = row[2] matchingPass = false matchingPass = Password.new(currentPassword) == p if matchingPass == true token = SecureRandom.uuid insertSession(userId, u, token) resetLoginAttempts(userId) elsif row != nil increaseLoginAttempts(userId) end User.new(userId, u, token) if matchingPass end end def insertSession(id, username, token) insert = <<-SQL INSERT INTO session values (NULL, ? , ? , datetime('now', '+30 minutes'), ?) SQL $db.execute(insert, id, username, token) end def resetLoginAttempts(id) update = <<-SQL update users set loginAttempts = 0 where id = ? SQL $db.execute(update, id) end def increaseLoginAttempts(id) update = <<-SQL update users set loginAttempts = loginAttempts + 1 where id = ? SQL $db.execute(update, id) end end end
true
5d9ccaa9ab3eb347613c175e6ac29479a0a080f3
Ruby
maschwenk/ruby-sdk
/lib/paymentrails/Client.rb
UTF-8
2,560
2.65625
3
[ "MIT" ]
permissive
# require_relative 'Exceptions.rb' require 'digest' require 'net/http' require 'openssl' require 'uri' require 'json' module PaymentRails class Client def initialize(config) @config = config end def get(endPoint) send_request(endPoint, 'GET') end def post(endPoint, body) body = body.to_json send_request(endPoint, 'POST', body) end def delete(endPoint) send_request(endPoint, 'DELETE') end def patch(endPoint, body) body = body.to_json send_request(endPoint, 'PATCH', body) end private def send_request(endPoint, method, body = '') uri = URI.parse(@config.apiBase + endPoint) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = @config.useSsl? time = Time.now.to_i headers = {'X-PR-Timestamp': time.to_s, 'Authorization': generate_authorization(time, endPoint, method, body), 'Content-Type': 'application/json'} if method === "GET" request = Net::HTTP::Get.new(uri.request_uri, headers) elsif method === "POST" request = Net::HTTP::Post.new(uri.request_uri, headers) request.body = body elsif method === "PATCH" request = Net::HTTP::Patch.new(uri.request_uri, headers) request.body = body elsif method === "DELETE" request = Net::HTTP::Delete.new(uri.request_uri, headers) end response = http.request(request) if response.code != '200' && response.code != '204' throw_status_code_exception(response.message + ' ' + response.body , response.code) end response.body end private def generate_authorization(time, endPoint, method, body) message = [time.to_s, method, endPoint, body].join("\n") + "\n" signature = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), @config.privateKey, message) 'prsign ' + @config.publicKey + ':' + signature end private def throw_status_code_exception(message, code) case code when '400' raise MalformedException, message when '401' raise AuthenticationError, message when '403' raise AuthorizationErrormessage when '404' raise NotFoundError, message when '429' raise TooManyRequestsError message when '500' raise ServerError, message when '503' raise DownForMaintenanceError, message else raise UnexpectedError, message end end end end
true
9f1f3795c080378eda866bb3796df099f5aa968a
Ruby
Gabbendorf/Ruby-Tic-Tac-Toe
/spec/game_spec.rb
UTF-8
2,965
3.1875
3
[]
no_license
require 'spec_helper' require_relative '../lib/game' require_relative '../lib/ui' require_relative '../lib/grid' RSpec.describe Game do let(:grid) {Grid.new(3)} let(:output) {StringIO.new} let(:input) {StringIO.new("h\n4")} let(:ui) {Ui.new(input, output)} let(:game) {Game.new} let(:human_player) {HumanPlayer.new(ui)} let(:computer) {UnbeatableComputer.new(ui)} def players {:first_player => {:player => human_player, :mark => Marks::X}, :second_player => {:player => computer, :mark => Marks::O}} end it "returns players and their marks" do player_input_for_computer = "c" ui = Ui.new(StringIO.new(player_input_for_computer), output) game = Game.new players = game.players_and_marks(human_player, ui) human_player = players[:first_player][:player] first_player_mark = players[:first_player][:mark] second_player = players[:second_player][:player] second_player_mark = players[:second_player][:mark] expect(human_player).to be_kind_of(HumanPlayer) expect(first_player_mark).to eq("X") expect(second_player).to be_kind_of(UnbeatableComputer) expect(second_player_mark).to eq("O") end it "creates grid" do new_grid = game.create_grid(players) expect(new_grid).to have_attributes(:size => 3) end it "returns starter" do starter = game.starter(players) expect(starter).to be_kind_of(HumanPlayer) end it "switches player" do starter = game.starter(players) switched_player = game.switch_player(starter, players) current_player = game.switch_player(switched_player, players) expect(switched_player).to be_kind_of(UnbeatableComputer) expect(current_player).to be_kind_of(HumanPlayer) end it "gets move from current player and registers corresponding mark on grid" do players = game.players_and_marks(human_player, ui) current_player = game.starter(players) game.make_move(current_player, players, grid) grid_state = grid.cells expect(grid_state).to eq([nil, nil, nil, players[:first_player][:mark], nil, nil, nil, nil, nil]) end it "alternates player that starts game" do first_starter = players[:first_player][:player] next_starter = game.switch_player(first_starter, players) expect(next_starter).to be_kind_of(UnbeatableComputer) end it "takes move and calls method that prints message for move made announcement" do ui = double("ui") current_player = double("player") expect(current_player).to receive(:make_move).with("X", grid) {"3"} players = {:first_player => {:player => current_player, :mark => Marks::X}, :second_player => {:player => "computer", :mark => Marks::O}} game.make_move(current_player, players, grid) current_player = players[:first_player][:player] ui = Ui.new(input, output) game.announce_move_made(ui, current_player, players) expect(output.string).to include("Player X marked position 3.") end end
true
2a9fdc734ea21bd90edcd58405e5da808853e42d
Ruby
claudia-mccormack/contacts-app
/ruby_practice/oop8.rb
UTF-8
1,589
3.609375
4
[]
no_license
# Create Person class class Person def initialize(first_name, last_name, hair_color, hobbies) @first_name = first_name @last_name = last_name @hair_color = hair_color @hobbies = hobbies end def first_name return @first_name end def last_name return @last_name end def full_name return @full_name end def full_name @full_name = @first_name + " " + @last_name end def email @email = @first_name + @last_name + "@gmail.com" end def hair_color return @hair_color end def hobbies return @hobbies end def description return @description end def description @hobbies.each do |hobby| puts @first_name + " enjoys " + hobby + "." end end end contacts = [ Person.new("Bob", "Jones", "pink", ["basketball", "chess", "phone tag"]), Person.new("Molly", "Parker", "black", ["computer programming", "reading", "jogging"]), Person.new("Kelly", "Miller", "rainbow", ["cricket", "baking", "stamp collecting"]) ] # Create ContactList class class ContactList def initialize(title, contacts) @title = title @contacts = contacts end def title return @title end def contacts return @contacts end def contacts @contacts = contacts << person end def add_contact return @add_contact end def add_contact(person) @contacts << person end end person = Person.new("Sterling", "Archer", "black", ["scotch", "danger zone", "shouting"]) contact_list = ContactList.new("friends", contacts) puts contact_list.add_contact(person) p contact_list
true
6f94732c308581a5af68cba0d7e13a0493724cd5
Ruby
tnypxl/taza
/lib/taza/site.rb
UTF-8
4,673
2.984375
3
[ "MIT" ]
permissive
module Taza # An abstraction of a website, but more really a container for a sites pages. # # You can generate a site by performing the following command: # $ ./script/generate site google # # This will generate a site file for google, a flows folder, and a pages folder in lib # # Example: # # require 'taza' # # class Google < Taza::Site # # end class Site @@before_browser_closes = Proc.new {} @@donot_close_browser = false # Use this to do something with the browser before it closes, but note that it is a class method which # means that this will get called for any instance of a site. # # Here's an example of how you might use it to print the DOM output of a browser before it closes: # # Taza::Site.before_browser_closes do |browser| # puts browser.html # end def self.before_browser_closes(&block) @@before_browser_closes = block end def self.donot_close_browser @@donot_close_browser = true end attr_accessor :browser # A site can be called a few different ways # # The following example creates a new browser object and closes it: # Google.new do # google.search.set "taza" # google.submit.click # end # # This example will create a browser object but not close it: # Google.new.search.set "taza" # # Sites can take a couple of parameters in the constructor: # :browser => a browser object to act on instead of creating one automatically # :url => the url of where to start the site def initialize(params = {}, &block) @module_name = self.class.parent.to_s @class_name = self.class.to_s.split("::").last define_site_pages define_flows config = Settings.config(@class_name).merge(params) browser_name = config[:browser] || 'chrome' browser_driver = config[:driver] || 'watir' browser_params = config[browser_name] || {} @browser = Browser.create(browser_name, browser_driver, browser_params) goto(config[:url]) if config[:url] execute_block_and_close_browser(browser, &block) if block_given? end def execute_block_and_close_browser(browser) begin yield self rescue => site_block_exception ensure begin @@before_browser_closes.call(browser) rescue => before_browser_closes_block_exception "" # so basically rcov has a bug where it would insist this block is uncovered when empty end close_browser_and_raise_if site_block_exception || before_browser_closes_block_exception end end def close_browser_and_raise_if original_error # :nodoc: begin close unless @@donot_close_browser ensure raise original_error if original_error end end def goto(url) # :nodoc: @browser.goto url if @browser.is_a? Watir::Browser @browser.navigate.to url if @browser.is_a? Selenium::WebDriver::Driver # driver = browser.respond_to?(:driver) ? browser.driver : browser # driver.navigate.to url end def close # :nodoc: @browser.close if browser end def self.settings # :nodoc: Taza::Settings.site_file(self.name.to_s.split("::").last) end def define_site_pages # :nodoc: Dir.glob(pages_path) do |file| require file page_name = File.basename(file,'.rb') page_class = "#{@module_name}::#{page_name.camelize}" self.class.class_eval <<-EOS def #{page_name}(page_module = nil) page = '#{page_class}'.constantize.new(page_module) page.browser = @browser yield page if block_given? page end EOS end end def define_flows # :nodoc: Dir.glob(flows_path) do |file| require file end end # This is used to call a flow belonging to the site # # Example: # Google.new do |google| # google.flow(:perform_search, :query => "taza") # end # # Where the flow would be defined under lib/sites/google/flows/perform_search.rb and look like: # class PerformSearch < Taza::Flow # alias :google :site # # def run(params={}) # google.search.set params[:query] # google.submit.click # end # end def pages_path # :nodoc: File.join(path,'pages','**','*.rb') end def flows_path # :nodoc: File.join(path,'flows','**','*.rb') end def path # :nodoc: File.join(base_path,'lib','sites',@class_name.underscore) end def base_path # :nodoc: '.' end end end
true
f63f9324bc48e01805b4d11af2517cf596c0662b
Ruby
bugsnag/maze-runner
/lib/maze/client/bs_client_utils.rb
UTF-8
6,583
2.5625
3
[ "MIT" ]
permissive
# frozen_string_literal: true module Maze module Client # Utils supporting the BrowserStack device farm integration class BrowserStackClientUtils class << self # Uploads an app to BrowserStack for later consumption # @param username [String] the BrowserStack username # @param access_key [String] the BrowserStack access key # @param app_id_file [String] the file to write the uploaded app url to BrowserStack def upload_app(username, access_key, app, app_id_file=nil) if app.start_with? 'bs://' app_url = app $logger.info "Using pre-uploaded app from #{app}" else expanded_app = Maze::Helper.expand_path(app) uri = URI('https://api-cloud.browserstack.com/app-automate/upload') request = Net::HTTP::Post.new(uri) request.basic_auth(username, access_key) request.set_form({ 'file' => File.new(expanded_app, 'rb') }, 'multipart/form-data') upload_tries = 0 allowed_tries = 10 while upload_tries < allowed_tries begin $logger.info "Uploading app: #{expanded_app}" res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end body = res.body response = JSON.parse body if response.include?('error') $logger.error "Upload failed due to error: #{response['error']}" elsif !response.include?('app_url') $logger.error "Upload failed, response did not include an app_url: #{res}" else # Successful upload break end rescue Net::ReadTimeout $logger.error "Upload failed due to ReadTimeout" rescue JSON::ParserError $logger.error "Unexpected JSON response, received: #{body}" end upload_tries += 1 if upload_tries < allowed_tries $logger.info 'Retrying upload in 60s' Kernel::sleep 60 end end if response.nil? || response.include?('error') || !response.include?('app_url') raise "Failed to upload app after #{upload_tries} attempts" end app_url = response['app_url'] $logger.info "App uploaded to: #{app_url}" $logger.info 'You can use this url to avoid uploading the same app more than once.' end unless app_id_file.nil? $logger.info "Writing uploaded app url to #{app_id_file}" File.write(Maze::Helper.expand_path(app_id_file), app_url) end app_url end # Starts the BrowserStack local tunnel # @param bs_local [String] path to the BrowserStackLocal binary # @param local_id [String] unique key for the tunnel instance # @param access_key [String] BrowserStack access key def start_local_tunnel(bs_local, local_id, access_key) $logger.info 'Starting BrowserStack local tunnel' command = "#{bs_local} -d start --key #{access_key} --local-identifier #{local_id} " \ '--force-local --only-automate --force' # Extract the pid from the output so it gets killed at the end of the run output = Runner.run_command(command)[0][0] begin @pid = JSON.parse(output)['pid'] $logger.info "BrowserStackLocal daemon running under pid #{@pid}" rescue JSON::ParserError $logger.warn 'Unable to parse pid from output, BrowserStackLocal will be left to die its own death' end end # Stops the local tunnel def stop_local_tunnel if @pid $logger.info "Stopping BrowserStack local tunnel" Process.kill('TERM', @pid) @pid = nil end rescue Errno::ESRCH # ignored end # Gets the build/session info from BrowserStack # @param username [String] the BrowserStack username # @param access_key [String] the BrowserStack access key # @param build_name [String] the name of the BrowserStack build def build_info(username, access_key, build_name) # Get the ID of a build uri = URI("https://api.browserstack.com/app-automate/builds.json?name=#{build_name}") request = Net::HTTP::Get.new(uri) request.basic_auth(username, access_key) res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end build_info = JSON.parse(res.body) if !build_info.empty? build_id = build_info[0]['automation_build']['hashed_id'] # Get the build info uri = URI("https://api.browserstack.com/app-automate/builds/#{build_id}/sessions") request = Net::HTTP::Get.new(uri) request.basic_auth(username, access_key) res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end build_json = JSON.parse(res.body) else raise "No build found for given ID: #{build_name}" end build_json end # @param username [String] the BrowserStack username # @param access_key [String] the BrowserStack access key # @param name [String] name of the build the log is being downloaded from # @param log_url [String] url to the log # @param log_type [Symbol] The type of log we are downloading def download_log(username, access_key, name, log_url, log_type) begin path = File.join(Dir.pwd, 'maze_output', log_type.to_s) FileUtils.makedirs(path) uri = URI(log_url) request = Net::HTTP::Get.new(uri) request.basic_auth(username, access_key) res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end $logger.info "Saving #{log_type.to_s} log to #{path}/#{name}.log" File.open("#{path}/#{name}.log", 'w+') { |file| file.write(res.body) } rescue StandardError => e $logger.warn "Unable to save log from #{log_url}" $logger.warn e end end end end end end
true
6672134d2c81c1e51571dcd9223542aec6fe1cd2
Ruby
Epigene/nimbler-path
/lib/nimbler_path.rb
UTF-8
5,864
3.28125
3
[ "MIT" ]
permissive
require "nimbler_path/version" require 'ffi' module NimblerPath def self.test # binding.pry string = "yay!" puts string return string end def self.nim_binary_to_use @@nim_binary_to_use ||= case ruby_platfrom_string when %r'64.*linux'i "64-linux" when %r'darwin' "64-mac" else abort("Running on #{ruby_platfrom_string} for which there are no Nim functions included, sorry!") end end # # Spec to Pathname#chop_basename # # WARNING! Pathname#chop_basename in STDLIB doesn't handle blank strings correctly! # # This implementation correctly handles blank strings just as Pathname had intended # # to handle non-path strings. # Pathname#chop_basename(path) @ https://goo.gl/9Lk1N9 called 24456 times, 25% of execution time alone def self.chop_basename(path, _separator=nil) # The currently unused:_separator arg is usually a /\// regex on Unix systems matching the "/" string # NB, besides the obvious :path argument the method receives, Nim implementation must also be provided with the Pathname::SEPARATOR_PAT #=> /\// constant which indicates what path separator is in use on the system. # For version 0.9.0, no access to Pathname::SEPARATOR_PAT will be made, avoiding reducing regex to a string, and instead a hardcoded "/" will be passed. #binding.pry base = File.basename(path) # "/some/path/file.rb" -> "file.rb" # Pathname::SEPARATOR_PAT => /\// if base[%r'\A/?\z'o] nil else return path[0, path.to_s.rindex(base)], base end end # Pathname#absolute? @ https://goo.gl/5aXYxw called 4840 times. def self.absolute(path) # Arg must be a String instance !relative?(path) # while r = chop_basename(path) # path, = r # end # path == '' end def self.relative(path) # Arg must be a String instance # while r = chop_basename(path) # path, = r # end # path == '' path[0] != "/" end # Pathname#+ @ https://goo.gl/W7biJu called 4606 times. def self.p(path, other) # NB, Nim probably will have a problem with method named "+", use :plus_sign instead # :path arg must be a String instance Pathname.new(plus(path, other.to_s)) end # Pathname#plus @ https://goo.gl/eRxLYt called 4606 times. def self.plus(path1, path2) # This is the undocumented source, yuck # Both args are definitaly Strings prefix2 = path2 index_list2 = [] basename_list2 = [] # Progressively chops off the end of path2 arg # so if path2 was "/etc/passwd" after this loop we will have # index_list2 == [1, 5] # denoting that "/"" is 1 and "/etc/" is 5 # basename_list2 == ["etc", "passwd"] while r2 = chop_basename(prefix2) #=> prefix2, basename2 = r2 index_list2.unshift(prefix2.length) # adds the length(int) to the beginning of index array basename_list2.unshift(basename2) # adds the current last bit of path2 to the beginning of basename array end # returns the second argument given if turns out is absolute return path2 if prefix2 != '' prefix1 = path1 while true # gets rid of trailing dots from second arg in case of "./dir" while !basename_list2.empty? && basename_list2.first == '.' index_list2.shift basename_list2.shift end # break if first arg is root or empty break unless r1 = chop_basename(prefix1) prefix1, basename1 = r1 next if basename1 == '.' # throw away this cut if it's a "/." portion # recombine if ?? # So going in prefix1, basename1 = "/", "usr" # Going out they get recombined if ( basename1 == '..' || basename_list2.empty? || basename_list2.first != '..' ) prefix1 = prefix1 + basename1 break end index_list2.shift basename_list2.shift end # After this fancyness leading .. from second arg have cut the end of first arg r1 = chop_basename(prefix1) # if after cuts first arg is at root or blank AND clean 1st arg has separator pattern in last path element, wut? This never executes! if !r1 && /#{Pathname::SEPARATOR_PAT}/o =~ File.basename(prefix1) while !basename_list2.empty? && basename_list2.first == '..' index_list2.shift basename_list2.shift end end # final tweaks before return if !basename_list2.empty? # when there is something in clean 2nd arg suffix2 = path2[index_list2.first..-1] # determines the remaining portion of arg2 to append to remaining arg1 r1 ? File.join(prefix1, suffix2) : (prefix1 + suffix2) # here the diff is basically with arg1 trailing "/" handling else # when after cleans second arg is absent r1 ? prefix1 : File.dirname(prefix1) # File.dirname(prefix1) basically changes "" to "." as final fallback end end # Pathname#join @ https://goo.gl/9NzWRt called 4600 times. def self.join(path, args) # raise("oops") # NB, see how Nim can handle splat arguments. Maybe need to pass in an array # :path arg must be a Pathname instance return path if args.empty? result = args.pop result = Pathname.new(result) unless Pathname === result return result if result.absolute? args.reverse_each {|arg| arg = Pathname.new(arg) unless Pathname === arg result = arg + result return result if result.absolute? } path + result end private def ruby_platfrom_string RUBY_PLATFORM end module Nim # extend FFI::Library # # attach_function :rust_arch_bits, [], :int32 # attach_function :is_absolute, [ :string ], :bool # EXAMPLE # attach_function :one_and_two, [], FromRustArray.by_value end private_constant :Nim end
true
c67845e5d91b4998dfbcc4c2855815957d39b480
Ruby
dexterfitch/resume-helper
/spec/resume_helper_spec.rb
UTF-8
2,670
2.75
3
[ "MIT" ]
permissive
require('rspec') require('resume_helper') describe("Resume") do before() do Resume.clear() end describe("#employer") do it('reads out the name of the employer') do test_job = Resume.new("Pickleworld","Pickle Farmer","Farmed a lot of cukes","01/01/2001", "07-07-2007") expect(test_job.employer()).to(eq("Pickleworld")) end end describe("#title") do it('reads out the title of the job position') do test_job = Resume.new("Pickleworld","Pickle Farmer","Farmed a lot of cukes","01/01/2001", "07-07-2007") expect(test_job.title()).to(eq("Pickle Farmer")) end end describe("#description") do it('reads out the job description') do test_job = Resume.new("Pickleworld","Pickle Farmer","Farmed a lot of cukes","01/01/2001", "07-07-2007") expect(test_job.description()).to(eq("Farmed a lot of cukes")) end end describe("#start_date") do it('reads out the job start date') do test_job = Resume.new("Pickleworld","Pickle Farmer","Farmed a lot of cukes","01/01/2001", "07-07-2007") expect(test_job.start_date()).to(eq("01/01/2001")) end end describe("#end_date") do it('reads out the job end date') do test_job = Resume.new("Pickleworld","Pickle Farmer","Farmed a lot of cukes","01/01/2001", "07-07-2007") expect(test_job.end_date()).to(eq("07-07-2007")) end end describe("#save_data") do it('saves the job details to a list') do test_job = Resume.new("Pickleworld","Pickle Farmer","Farmed a lot of cukes","01/01/2001", "07-07-2007") expect(test_job.save_data()).to(eq([test_job])) end end describe(".all") do it("is empty when first initialized") do test_job = Resume.new("Pickleworld","Pickle Farmer","Farmed a lot of cukes","01/01/2001", "07-07-2007") expect(Resume.all()).to(eq([])) end it("returns data after data has been stored") do test_job = Resume.new("Pickleworld","Pickle Farmer","Farmed a lot of cukes","01/01/2001", "07-07-2007") test_job.save_data() test2_job = Resume.new("BurgerWorld", "Burger Flipper", "Flip a lot of patties", "08/08/1999", "08/09/1999") test2_job.save_data() expect(Resume.all()).to(eq([test_job, test2_job])) end end describe(".clear") do it("clears all job instances in the Resume class") do test_job = Resume.new("Pickleworld","Pickle Farmer","Farmed a lot of cukes","01/01/2001", "07-07-2007") test_job.save_data() test2_job = Resume.new("BurgerWorld", "Burger Flipper", "Flip a lot of patties", "08/08/1999", "08/09/1999") test2_job.save_data() Resume.clear() expect(Resume.all()).to(eq([])) end end end
true
58c873ffe674fe30861e5cd29c65a35d74263a24
Ruby
archiefielding/Battleships
/spec/board_spec.rb
UTF-8
588
2.71875
3
[]
no_license
require 'board' describe Board do it "can place a single cell ship" do ship = Ship.new expect(subject.place(ship, "A1")).to include(0) end it "can place a multi-cell ship" do ship = Ship_2.new(2) expect(subject.place(ship, 0)).to match_array(%w[0 0 A3 A4 A5 A6 A7 A8 A9 A10 B1 B2 B3 B4 B5 B6 B7 B8 B9 B10 C1 C2 C3 C4 C5 C6 C7 C8 C9 C10 D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 E1 E2 E3 E4 E5 E6 E7 E8 E9 E10 F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 G1 G2 G3 G4 G5 G6 G7 G8 G9 G10 H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 I1 I2 I3 I4 I5 I6 I7 I8 I9 I10 J1 J2 J3 J4 J5 J6 J7 J8 J9 J10]) end end
true
5176008c4937f934f674f04d4a060f21f812cef0
Ruby
m-negishi/ruby_training
/TeachYourselfRuby/section7/7.2.2.rb
UTF-8
701
3.71875
4
[]
no_license
# Dogクラス class Dog attr_reader :kind attr_writer :meal def initialize(k = 'Mongrel') @kind = k @meal = nil end # アクセスメソッドで代替 # def kind # @kind # end # def kind=(k) # @kind = k # end # アクセスメソッドで代替できる # def meal=(food) # puts 'エサを与える' # @meal = food # # end def feeling if @meal.nil? # puts 'Sad' return 'Sad' else @meal = nil return 'Good' end end end dog = Dog.new('Chihuahua') puts dog.kind # dog.kind = 'test' # エラー puts dog.feeling # Sad dog.meal = 'dogfood' # エサを与える puts dog.feeling # Good puts dog.feeling # Sad
true
2a5bb764ac2251904a1010d7a313773a715c7757
Ruby
thierrymoudiki/phase-0-tracks
/ruby/gps_2_2.rb
UTF-8
2,007
4.28125
4
[]
no_license
# Method to create a list # input: string of items separated by spaces (example: "carrots apples cereal pizza") # steps: def create_list_items(input_string) hsh = {} # create an array containing each item array_input = input_string.split(' ') # create a hash from the array (iterate), containing the information of key/value pairs array_input.each do |item| # set default quantity as value hsh[item] = 0 end # print the list to the console (we will use the last method) print_list(hsh) # output: hash data structure of key/value pairs return hsh end # Method to add an item to a list # input: list, item name, and optional quantity def add_item(input_hash, item, qty = 0) # steps: use input item as key and input quantity as value input_hash[item] = qty # output: hash data structure of key/value pairs return input_hash end # Method to remove an item from the list def remove_item(input_hash, item) # input: list, item name, and optional quantity # steps: use input item to delete key input_hash.delete(item) # output: hash data structure of key/value pairs return input_hash end # Method to update the quantity of an item # input:list, item name, and quantity def update_quantity(input_hash, item, qty) # steps: use input item as key and input quantity as value # output: hash input_hash[item] = qty return input_hash end # Method to print a list and make it look pretty # input: a hash containing the information def print_list(input_hash) # steps: iterate through the hash and print keys/values puts "Here are the items on your list" input_hash.each do |item, qty| p "For item #{item}, we have #{qty}" end # output: nil end hsh = create_list_items("carrots apples cereal pizza") hsh = add_item(hsh, "Lemonade", 2) hsh = add_item(hsh, "Tomatoes", 3) hsh = add_item(hsh, "Onions", 1) hsh = add_item(hsh, "Ice cream", 4) hsh = remove_item(hsh, "Lemonade") hsh = update_quantity(hsh, "Ice cream", 1) print_list(hsh)
true
fff2995bf15aa888159e78029802bb9925362f8d
Ruby
mamiyamahara/DWC-Task
/Ruby/第八章/for.rb
UTF-8
74
3.359375
3
[]
no_license
for i in 1..10 do # 1..10は、1~10までの範囲を表す puts i end
true
d56e72f75a795676813903a3e33f042f745baca7
Ruby
toksaitov/scenario
/lib/scenario/objects/pipe.rb
UTF-8
1,214
2.5625
3
[ "MIT" ]
permissive
# Scenario is a Ruby domain-specific language for graphics. # Copyright (C) 2010 Dmitrii Toksaitov # # This file is part of Scenario. # # Released under the MIT License. module Scenario class Pipe < Generic include Degradable meta_accessor :radius, :level, :update_call => true def initialize @radius = 0.5 @level = 0.3 @quality = 30 super end def update glNewList(list_id, GL_COMPILE) glPushMatrix() step = step(360.0) level = @level / 2.0 angle = 0.0 glBegin(GL_QUADS) 0.upto(@quality) do |i| x, y = Math.cos(angle.degrees), Math.sin(angle.degrees) define_vertex(x, y, level) define_vertex(x, y, -level) angle += step x, y = Math.cos(angle.degrees), Math.sin(angle.degrees) define_vertex(x, y, -level) define_vertex(x, y, level) end glEnd() glPopMatrix() glEndList() end private def define_vertex(x, y, z) glNormal(x, y, z) glVertex(x * @radius, y * @radius, z) end end end
true
e521d66c26b16178e7b70967e73d7f55537906eb
Ruby
cielavenir/procon
/atcoder/tyama_atcoderdwacon2018prelimsB.rb
UTF-8
81
2.796875
3
[ "0BSD" ]
permissive
#!/usr/bin/ruby s=gets.chomp;i=0;i+=1 while s.gsub!('25','');p s.empty? ? i : -1
true
aa01f5771de88c4acef2d4bee14fe3202f3b2e37
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/simple-linked-list/91ef897999984449a9a6084155000d1b.rb
UTF-8
1,068
3.359375
3
[]
no_license
class Element attr_reader :datum, :next def self.to_a(element) element.to_a end def self.from_a(source) source.to_a.reverse.reduce(nil) do |list, datum| self.new datum, list end end def initialize(datum, next_one) @datum = datum @next = next_one end def to_a map { |i| i } end def map(&block) return to_enum(__method__) unless block_given? array = [] each { |i| array << yield(i) } array end def each return to_enum unless block_given? e = self until e.nil? yield e.datum e = e.next end end def reverse self.class.from_a to_a.reverse end def reduce(initial, &block) return to_enum(__method__) unless block_given? acc = initial each { |e| acc = yield acc, e } acc end end class LinkedListTest < MiniTest::Unit::TestCase def test_reduce assert_equal 3, @two.reduce(0, &:+) end def test_map assert_equal [4, 2], @two.map { |i| i * 2 } end end
true
73ada39e49ea973ecde1b4cb6608a2aa56f88288
Ruby
hellosweta/poker_assessment
/lib/hand.rb
UTF-8
1,277
3.703125
4
[]
no_license
require_relative 'card' require_relative 'poker_hands' class Hand include PokerHands def initialize(cards) raise "must have five cards" if cards.length != 5 @cards = cards end attr_accessor :cards RANKS = [ :royal_flush, :straight_flush, :four_of_a_kind, :full_house, :flush, :straight, :three_of_a_kind, :two_pair, :one_pair, :high_card ] def trade_cards(take_cards, new_cards) raise "must have five cards" if take_cards.length != new_cards.length unless take_cards.all? { |card| @cards.include?(card) } raise "cannot discard unowned card" end @cards -= take_cards @cards += new_cards end # # def rank # RANKS.each do |rank| # return rank if self.send("#{rank}?") # end # end # # def <=>(other_hand) # if self == other_hand # 0 # elsif RANKS.index(self.rank) < RANKS.index(other_hand.rank) # return 1 # elsif RANKS.index(self.rank) > RANKS.index(other_hand.rank) # return -1 # else # tie_breaker(other_hand) # end # end def self.winner(hands) winning_hand = hands[0] hands.each do |hand| if (winning_hand <=> hand) == 1 winning_hand = hand end end winning_hand end end
true
fbd3917d3dbac5b99f352d2ff2e3c14dc689e84e
Ruby
jordanpoulton/ruby_kickstart
/session2/5-solved/2.rb
UTF-8
3,180
4.125
4
[ "MIT" ]
permissive
#paul fitz def hi_hi_goodbye # your code here puts "Enter a number" #ask user to input a number while answer = gets.chomp #while loop used to keep looping until the user inputs "bye" number = answer.to_i #can't use to_i on same line as gets number.times {|x| puts "hi"} #based on number the user inputs print "hi" this amount of times puts "enter a number" #ask the question again break if answer == "bye" #loop breaks if the answer is "bye" end puts "goodbye" end def prompt puts 'Enter a number or bye' end def hi_hi_goodbye prompt while (line = gets) && (line !~ /bye/) # first is an assignment statement that returns a line or nil, and is thus boolean line.to_i.times { print 'hi ' } puts prompt end puts "Goodbye!" end #solved by meads def hi_hi_goodbye #loop while getting user input while user_input = gets.chomp #why is this = and not ==? A good explanation is here http://www.evc-cit.info/cit020/beginning-programming/chp_04/file_while.html user_input.to_i.times {|n| print 'hi '}#convert input to an int and loop than number of times printing 'hi' puts "" break if user_input == "bye" #break to jump out of the loop. end puts "goodbye" end #=========================== #Sebastien def hi_hi_goodbye puts "Enter a number" while input = gets puts "hi " * input.to_i break if input == "bye" end puts "goodbye" end #kevin lanzon def hi_hi_goodbye puts "Please enter a number: " while num = gets.chomp # Can't add .to_i here as it affects the input "bye" num.to_i.times { |n| puts "hi " } # Input to integer puts " " break if num == "bye" end puts "goodbye" end #Jordan def hi_hi_goodbye puts "Enter a number: " while (input = gets.chomp) && (input !~ /bye/) input.to_i.times {|i| print "hi "} puts "Enter a number: " end puts "goodbye" end #Yannick def hi_hi_goodbye answer = "" while answer != "bye" puts "Enter a number" answer = gets.chomp puts "hi " * answer.to_i end puts "goodbye" end # Gabe def hi_hi_goodbye input = "not bye" while input != "bye" puts "Enter a number" input = gets.chomp if input == "bye" puts "goodbye" else integer = input.to_i puts "hi " * integer end end end #Costas def hi_hi_goodbye puts "Enter a number: " while (input = gets.chomp) && (input != "bye") puts "hi " * input.to_i puts "Enter a number: " end puts "goodbye" end hi_hi_goodbye if $0 == __FILE__ # a little magic so that you can run with "$ ruby 2_input_output_control.rb" but it will still work for our tests # Tom Coakes def hi_hi_goodbye while true puts "Enter a number " input = gets.chomp if input == "bye" print "goodbye" break else puts "hi " * input.to_i end end end #Chris Ward def hi_hi_goodbye input = '' while input != "bye" puts "Please enter a number" input = gets.chomp input.to_i.times {puts "hi"} end puts "goodbye" end #Phil def hi_hi_goodbye puts "Enter a number" input = gets.chomp while input != "bye" puts "hi " * input.to_i input = gets.chomp end puts "goodbye" end
true
c51291bb0181276a655716c580d215b3a4586718
Ruby
jahman07104/programming-univbasics-3-labs-with-tdd-online-web-prework
/calculator.rb
UTF-8
94
2.578125
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
dec calculator def first_number 6 second_number 4 puts first_number + second_number end
true
c14ffa63fc46e49ceb0473bfe2df8e0fb86950fc
Ruby
fadieh/BORIS_BIKES_ruby
/spec/bike_container_spec.rb
UTF-8
1,164
3.015625
3
[]
no_license
require 'bike_container' class BikeHolder; include BikeContainer; end describe BikeContainer do let(:bikeholder) { BikeHolder.new } let(:bike) { double :bike, :broken? => false } let(:broken_bike) { double :bike, :broken? => true } it "should have a default capacity" do holder = BikeHolder.new expect(bikeholder.capacity).to eq(20) end it "should have initially have no bikes" do expect(bikeholder.bike_count).to eq 0 bikeholder.dock(bike) expect(bikeholder.bike_count).to eq 1 end it "should know the total amount of bikes" do expect{bikeholder.dock(bike)}.to change{bikeholder.bike_count}.by 1 end it "should be able to dock a bike" do expect(bikeholder.dock(bike)).to include(bike) end it "should be able to release a bike" do bikeholder.dock(bike) bikeholder.release(bike) expect(bikeholder.bikes).to_not include(bike) end it "should know how many broken bikes there are" do bikeholder.dock(broken_bike) expect(bikeholder.broken_bikes).to include(broken_bike) end it "should know how many available bikes there are" do bikeholder.dock(bike) expect(bikeholder.available_bikes).to include(bike) end end
true
156dcfda4bc1ab753f9dbf202b83360a69b0e8d8
Ruby
jetsgit/set_game
/lib/constants.rb
UTF-8
471
2.515625
3
[ "MIT" ]
permissive
module SetGame ## # Constants used in the Set Game module Constants MASK = 7 BITS = 0 COLOR_MASK = BITS | MASK SHAPE_MASK = BITS | (MASK << 3) PATTERN_MASK = BITS | (MASK << 6) NUMBER_MASK = BITS | ( MASK << 9 ) COLOR = [ {red: 1}, {green: 2 }, {purple: 4}] SHAPE = [ {diamond: 8}, {squiggle: 16}, {oval: 32}] PATTERN = [{solid: 64}, {empty: 128}, {stripe: 256}] NUMBER = [{one: 512 }, {two: 1024}, {three: 2048}] end end
true
36e6949e9ce0d827033e23710ec9986e11622000
Ruby
ramprabhu-idexcel/bowling-club
/app/models/bowling.rb
UTF-8
4,160
3.046875
3
[ "MIT" ]
permissive
class Bowling include ActiveModel::Model attr_accessor :turns, :bonus, :total_frames_score, :game_bonus validate :cannot_be_greater_than_10 validate :validate_bonus # initialize with bowling attributes def initialize(turns) @total_frames_score = [] @turns = turns ## If the user enter 11 input then set bonus try/turn ## if turns.count == 11 actual_bonus = turns.last turns.pop calculate_bonus(turns.last, actual_bonus) end init_frames end # generate accessor for each frames def self.set_frames (1..10).each do |no| attr_accessor "frame#{no}" end end # calculate bonus def calculate_bonus(last_frame, actual_bonus) if last_frame[0] == 10 && last_frame[1] == 0 ## Strike @bonus = actual_bonus elsif (last_frame[0] + last_frame[1]) == 10 ## Spare @bonus = [actual_bonus[0], 0] else @bonus = [0,0] end end # input attributes def init_frames (0..9).each do |no| if @turns.present? instance_variable_set("@frame#{no+1}", @turns[no]) else instance_variable_set("@frame#{no+1}", [10,0]) # selected some default values end end set_game_bonus end # user game bonus def set_game_bonus if @turns.present? instance_variable_set("@game_bonus", @bonus) else instance_variable_set("@game_bonus", [10, 10]) end end # first turn def turn turns.first end # following turn def following_turn turns[1] end # second turn def second_turn turns[2] end # Score for one frame def sum turn[0] + turn[1] end # sum of following turn values def sum_following_turn following_turn[0] + following_turn[1] end # less than 10 pins def is_miss? sum < 10 && sum >= 0 end # Spare when the user scores 10 on two turns def is_spare? sum == 10 && turn[0] != 10 end # Strike when the user scores 10 on first turn def is_strike? turn[0] == 10 end # calculate ninth strike followed by strike def ninth_strike_followed_by_strike? following_turn[0] == 10 && second_turn == nil end # strike followed by two strike def strike_followed_by_two_strikes? following_turn[0] == 10 && second_turn[0] == 10 end # strike followed by strike def strike_followed_by_strike? following_turn[0] == 10 end # game turn score def turn_score if is_miss? frame_score = sum elsif is_spare? frame_score = 10 + following_turn[0] else is_strike? frame_score = strike_scorer end total_frames_score << frame_score frame_score end # total strike scorer def strike_scorer if ninth_strike_followed_by_strike? 20 + bonus[0] elsif strike_followed_by_two_strikes? 30 elsif strike_followed_by_strike? 20 + second_turn[0] else 10 + sum_following_turn end end # total scores def scorer score = 0 while turns.length > 1 score = score + turn_score turns.shift end if bonus last_frame = sum + bonus[0] + bonus[1] score = score + last_frame else last_frame = sum score = score + last_frame end total_frames_score << last_frame << score score end # sum of both tries cannot be more than 10 pins def cannot_be_greater_than_10 turns.each do |turn| if turn.sum > 10 || turn.sum < 0 errors.add(:base, 'sum of each frame values should be less than or equal to 10') end end end # validating bonus data def validate_bonus if !bonus.is_a?(Array) || bonus.detect{|b| !(0..10).include?(b)} errors.add(:bonus, :invalid) end end # displaying scores on UI def display_scores score_frames, total_values = {}, [] total_score = total_frames_score.last total_frames_score.pop total_frames_score.each_with_index do |value, index| score_frames["frame#{index+1}"] = value end score_frames["total_score"] = total_score score_frames["created_at"] = Time.now.strftime("%d-%m-%Y %I:%M%p") total_values << score_frames if score_frames.present? end set_frames end
true
1287e162e2e5dafff47286446014f3ce46109b5d
Ruby
antonror/riskmethods_test
/app/services/companies_list.rb
UTF-8
2,133
2.953125
3
[]
no_license
# frozen_string_literal: true class CompaniesList ValidationError = Class.new(StandardError) def initialize(params) @params = params @errors = [] @companies = nil @filters = {} end def call validate_params! extract_companies supply_data rescue ValidationError { errors: @errors } end def validate_params! extract_filter if !@params.empty? country_code = @filters[:country_code] with_employees = @filters[:with_employees] @errors << 'wrong_country_code' if country_code.try(:length).to_i > 2 @errors << 'wrong_employee_state' if with_employees == 'my-wrong-value' end raise ValidationError unless @errors.empty? end private def extract_companies @companies = Company.all end def extract_filter filters = @params[:filter] return if filters.blank? @filters[:country_code] = filters[:country_code] @filters[:with_employees] = filters[:with_employees] @filters[:number_of_employees_greater_than] = filters[:number_of_employees_greater_than] end def supply_data response = Hash.new.with_indifferent_access response["meta"] = {} response["data"] = [] country_code = @filters[:country_code] sanctioned = @filters[:with_employees] number_greater_than = @filters[:number_of_employees_greater_than] if country_code.present? companies = @companies.by_country_code(country_code) else companies = @companies end if sanctioned.eql?('sanctioned') companies = companies.with_sanctioned_employees elsif sanctioned.eql?('any') companies = companies.with_at_least_one_employee end if number_greater_than.present? companies = companies.with_employees_count(number_greater_than) end companies.each do |company| if sanctioned.eql?('sanctioned') employees_count = company.employees.sanctioned.count else employees_count = company.employees.count end response["data"] << { id: company.id, name: company.name, employees_count: employees_count } end response end end
true
6e0356ff3b001b101b398b1d478486924670f74d
Ruby
Dalf32/EconomicSim
/data/sim_data_builder.rb
UTF-8
3,545
3.015625
3
[]
no_license
# frozen_string_literal: true # sim_data_builder.rb # # Author:: Kyle Mullins require 'json' require_relative 'sim_data' require_relative 'commodity' require_relative 'agent_role_builder' # Builds the SimData class SimDataBuilder # Builds the SimData from a specification file (JSON) # # @param params_file [String] Path to the simulation data specification file # @return [SimData] Newly-constructed SimData def self.from_file(params_file) params_hash = SimDataBuilder.read_file(params_file) resource_hashes = params_hash['Resources'].map do |resource_file| SimDataBuilder.read_file(resource_file) end scripts = params_hash['Scripts'] SimDataBuilder.from_hash(params_hash, resource_hashes, scripts) end # Builds the SimData from specification hashes # # @param params_hash [Hash] Hash holding all of the basic simulation parameters # @param resource_hashes [Array<Hash>] List of Hashes specifying simulation # resources (Commodities, Agents, etc.) # @param scripts [Array<String>] List of script files to be loaded (Ruby) # @return [SimData] Newly-constructed SimData def self.from_hash(params_hash, resource_hashes, scripts) builder = SimDataBuilder.new.params(params_hash) scripts.each { |script_file| builder.script(script_file) } resource_hashes.each { |resource_hash| builder.resources(resource_hash) } builder.build end # Creates a new SimDataBuilder def initialize @sim_data = SimData.new end # Returns the constructed SimData # # @return [SimData] def build @sim_data end # Sets the basic parameters of the simulation # # @param params_hash [Hash] Specification of the basic simulation parameters # @return [SimDataBuilder] self def params(params_hash) return self if params_hash.nil? @sim_data.num_rounds = params_hash['NumRounds'] @sim_data.num_agents = params_hash['NumAgents'] @sim_data.starting_funds = params_hash['StartingFunds'] @sim_data.max_stock = params_hash['MaxStock'] self end # Builds and adds resources to the simulation # # @param resources_hash [Hash] Specification of Commodities and AgentRoles # @return [SimDataBuilder] self def resources(resources_hash) commodities(resources_hash['Commodities']) agents(resources_hash['Agents']) end # Loads Ruby script file containing Condition and/or ProductionRule methods # # @param script_file [String] Path to Ruby script file # @return [SimDataBuilder] self def script(script_file) load script_file self end # Builds and adds Commodities from the given hash to the simulation # # @param commodities_hash [Hash] Specification of Commodities # @return [SimDataBuilder] self def commodities(commodities_hash) return self if commodities_hash.nil? commodities_hash.each do |commodity_hash| @sim_data.add_commodity(Commodity.new(commodity_hash['Name'])) end self end # Builds and adds AgentRoles from the given hash to the simulation # # @param agents_hash [Hash] Specification of AgentRoles # @return [SimDataBuilder] self def agents(agents_hash) return self if agents_hash.nil? agents_hash.each do |agent_hash| @sim_data.add_agent_role(AgentRoleBuilder.from_hash(agent_hash, @sim_data)) end self end # Reads and parses a JSON file # # @param filename [String] Path to some JSON file # @return [Hash] Parsed JSON data def self.read_file(filename) JSON.parse(File.readlines(filename).join("\n")) end end
true
9a7613661d464c7f10fa158de6b9f060e4eac47a
Ruby
nyc-squirrels-2016/wanna_watch
/app/models/event.rb
UTF-8
1,010
2.53125
3
[]
no_license
class Event < ActiveRecord::Base belongs_to :host, class_name: :User has_many :requests, dependent: :destroy has_many :guests, through: :requests, dependent: :destroy validates :show, presence: true validates :time, presence: true validates :date, presence: true validates :host, presence: true validates :description, presence: true validates :max_occupancy, presence: true def attending_guests attending_guests = self.requests.where(active: 0).map do |request| request.guest end attending_guests end def filled? self.max_occupancy <= self.attending_guests.length end def self.search(location, show=nil) if show Event.all.select {|event| event.host.location == location && event.show.downcase.include?(show.downcase) && event.filled? == false} else Event.all.select {|event| event.host.location == location && event.filled? == false} end end def has_no_user_requests(user_id) self.guests.where(id: user_id).size < 1 end end
true
dcbb67904fc8c5d8cb520b5d46200e9d5dae4c9a
Ruby
recortable/Cuentas
/app/models/year.rb
UTF-8
1,859
2.625
3
[]
no_license
class Year < ActiveRecord::Base before_save :report! serialize :report belongs_to :account def balance after_ammount - before_ammount end def balance_before before_ammount end def balance_after after_ammount end def months Month.where(:year => self.number, :account_id => self.account_id) end def to_param "#{number}" end def r(key) report[key] if report end def report! 1.upto(12).each do |month_number| month = Month.where(:account_id => self.account_id, :year => self.number, :month => month_number).first Month.create(:account_id => self.account_id, :year => self.number, :month => month_number) unless month end report = {:count => 0, :ammount => 0, :positive => 0, :negative => 0, :before => 0, :after => 0, :tags => {}} months = self.months report[:before] = months.first.r :before report[:after]= months.last.r :after if report[:after] == 0 last = Movement.where(:account_id => self.account_id).order('date DESC').first report[:after] = last.balance end months.each do |month| if month.report.present? report[:positive] += month.r :positive report[:negative] += month.r :negative report[:count] += month.r :count if month.report[:tags] month.report[:tags].each do |key, value| tag_report = report[:tags][key] ||= {:count => 0, :ammount => 0, :positive => 0, :negative => 0} tag_report[:color] = value[:color] tag_report[:count] += value[:count] tag_report[:ammount] += value[:ammount] tag_report[:positive] += value[:positive] tag_report[:negative] += value[:negative] end end end end report[:ammount] = report[:after] - report[:before] self.report = report end end
true
7fab976948ac253edd8c4476475b98f3c3dc369f
Ruby
gitter-badger/heelbot
/lib/heel/bot_manager.rb
UTF-8
1,004
2.734375
3
[ "MIT" ]
permissive
module Heel class BotManager BOT_CONF_NAME = "heelspec/bots.yaml" @new_conf = false attr_reader :bot_list def initialize @bot_list ||= [] load_bots end def add_bot(bot_name) end def remove_bot(bot_name) end def run_bot(bot_name, bot_cmd) require_relative "../../heelspec/#{bot_name}" bot_class_name = bot_name_to_class_name(bot_name) bot_class = eval("Heelspec::#{bot_class_name}") bot = bot_class.new bot.run(bot_cmd) end private def load_bots if File.exists? BOT_CONF_NAME @new_conf = false; @bot_list = YAML.load_file BOT_CONF_NAME else @new_conf = true f = File.new(BOT_CONF_NAME, "w") f.close end end def bot_name_to_class_name(bot_name) ary_bot_name = bot_name.split "_" class_name = "" ary_bot_name.each do |name_part| class_name << name_part.capitalize end class_name end end end
true
37f772e207134eaf783cc3e41bcfff9d24493dbd
Ruby
justinsilvestre/recursion
/mergesort.rb
UTF-8
933
3.609375
4
[]
no_license
def merge_sort_rec(nums) num_chunks = nums.map { |n| [n] } merge_chunks(num_chunks) end def merge_chunks(all_chunks) return all_chunks[0] unless all_chunks.length > 1 sorted_chunks = [] all_chunks.each_slice(2) do |chunks| merged_chunks = merge_pair(chunks[0], chunks[1]) sorted_chunks << merged_chunks end merge_chunks(sorted_chunks) end def merge_pair(a, b) return a if b.nil? result = [] until a.empty? && b.empty? if a.empty? lower_first = b.shift elsif b.empty? lower_first = a.shift elsif a.first < b.first lower_first = a.shift else lower_first = b.shift end result << lower_first end result end roo = [8,6,4,7,2,3,9,1,4] p merge_sort_rec roo def ms(a) l = a.length if l < 2 a else m(ms(a[0...l/2]), ms(a[l/2..-1])) end end def m(a, b) return b if a.empty? return a if b.empty? a.first < b.first ? [a.first] + m(a[1..-1], b) : [b.first] + m(a, b[1..-1]) end p ms(roo)
true
ea0dbf7f651b5372fb8bc8577f2eb5d11f8ab043
Ruby
t1gerk1ngd0m/service-practice-app
/app/forms/transfer_money_form.rb
UTF-8
804
2.546875
3
[]
no_license
class TransferMoneyForm include Virtus.model include ActiveModel::Model attribute :transfer_amount, Integer attribute :from_user_id, Integer attribute :to_user_id, Integer attribute :currency, Integer validates_presence_of %i( transfer_amount from_user_id to_user_id ) def run from_bank_account = set_from_bank_account to_bank_account = set_to_bank_account @transfer_service = TransferService.new(from_bank_account, to_bank_account) transfered_money = Money.new(transfer_amount, currency) @transfer_service.transfer(transfered_money) end private def set_from_bank_account from_user = User.find(from_user_id) from_user.bank_account end def set_to_bank_account to_user = User.find(to_user_id) to_user.bank_account end end
true
37cc13ad2eba9942057b176a4412fbd85bf8474d
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/grains/0049c96c789f4f6c8dd25c23c417140c.rb
UTF-8
169
3.4375
3
[]
no_license
# 1, 2, 4, 8, 16, ... class Grains def square x (2 ** (x-1)) end def total sum = 0 for i in (1..64) sum += square(i) end sum end end
true
93d1f4a6c98784a8befd8286853f4a0c82e9aef1
Ruby
samlouiscohen/Genesis
/rtests/fail-expr2.god
UTF-8
164
2.8125
3
[]
no_license
void init(){} void update(int f){} int a; bool b; void foo(int c, bool d) { int d; bool e; b + a; /* Error: bool + int */ } int main() { return 0; }
true
ea9899430e8f938ec2c154fa1936004216b4d24f
Ruby
Nroulston/school-domain-onl01-seng-ft-052620
/lib/school.rb
UTF-8
525
3.53125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# code here! require "pry" class School def initialize(school) @school = school @roster = {} end def roster @roster end def add_student(name, grade) unless @roster.has_key?(grade) @roster[grade] = [] end @roster[grade] << name end def grade(number) @roster[number] end def sort @roster.keys.sort.map! do |i| @roster[i] = @roster[i].sort end @roster end end
true
385fa2404588d5e3737e5008d8aae321c71da489
Ruby
dominicsayers/json_validation
/lib/json_validation/validators/items.rb
UTF-8
1,397
2.609375
3
[ "MIT" ]
permissive
module JsonValidation module Validators class Items < Validator type :array def validate(value, value_path) case schema['items'] when Schema value.each_with_index.all? {|item, ix| inner_validator.validate(item, value_path + [ix.to_s])} when Array inner_validators.zip(value).all? {|validator, item| validator.validate(item) } else raise "Unexpected type for schema['items']" end end def validate_with_errors(value, value_path) case schema['items'] when Schema value.each_with_index.map {|item, ix| inner_validator.validate_with_errors(item, value_path + [ix.to_s])} when Array inner_validators.zip(value).each_with_index.map {|validator_and_item, ix| validator, item = validator_and_item validator.validate_with_errors(item, value_path + [ix.to_s]) } else raise "Unexpected type for schema['items']" end end def inner_validator raise unless schema["items"].is_a?(Schema) @inner_validator ||= SchemaValidator.new(schema["items"]) end def inner_validators raise unless schema["items"].is_a?(Array) @inner_validators ||= schema["items"].map {|subschema| SchemaValidator.new(subschema)} end end end end
true
70885c3da29ee4ce23ba3e0d2b97d07eced07391
Ruby
namespace-team/ruby-core-challenges
/square_each_digit/square_each_digit.rb
UTF-8
519
3.34375
3
[]
no_license
def square_each_digit num # Write your code here end describe "#square_each_digit" do context "it is a number" do it "returns square of each digit" do expect(square_each_digit(3211)).to eq(9411) expect(square_each_digit(654326)).to eq(3625169436) expect(square_each_digit(1111)).to eq(1111) end end context "it is not a number" do it "returns NaN" do expect(square_each_digit("hello")).to eq("NaN") expect(square_each_digit("12hello")).to eq("NaN") end end end
true
e3faa1718b0a6be1d22c428def754f9250b8f90a
Ruby
webclinic017/dxmodel
/app/models/stock.rb
UTF-8
779
2.5625
3
[]
no_license
class Stock < ActiveRecord::Base has_many :stock_dates, :dependent => :destroy has_many :trades, :dependent => :destroy belongs_to :industry validates :ticker, :presence => true, :uniqueness => {:scope => :country} validates :name, :presence => true validates :country, :presence => true validates :currency, :presence => true def price_on_date date stock_date = StockDate.where("stock_id = ? and date <= ?", id, date).order('date DESC').first stock_date.close end def unit currency + '&nbsp;'.html_safe end def ticker_country ticker + ' ' + country end def country_ticker country + ' ' + ticker end def trading_day? date StockDate.joins(:stock).where(stocks: {country: country}, date: date).count > 0 end end
true
6d8055fa2997eef0f055b079580eda0529f676ca
Ruby
savagesnake/flashcard
/controller.rb
UTF-8
1,231
2.953125
3
[]
no_license
require_relative "parser" class Controller attr_reader :view,:deck attr_accessor :score def initialize @view = View.new @deck = Deckmodel.new end def load_game commands = ARGV return view.choose_deck if commands.empty? return view.choose_deck if commands[0].downcase == "help" # this section will run an create teh deck and the cards # depending on the user selection deck_select = commands[0] deck_option = deck_options(deck_select) deck.create_cards(deck_option) system "cls" play_game(deck) view.game_over(deck.score,deck.cards) # binding.pry end def deck_options(deck_select) # binding.pry case deck_select.downcase when "nighthawk" "nighthawk_flashcard_data.txt" when "otter" "otter_flashcard_data.txt" when "raccoon" "raccoon_flashcard_data.txt" else view.display_error end end def play_game(deck) deck.cards.shuffle.each do |card| answer = view.dispay_question(card) if answer.downcase == card.answer.downcase deck.score_calculate view.correct else view.wrong(card.answer) end end end end
true
d410dd302e26cd8b6c4d8189ce38cf6d41554c29
Ruby
mtodd/flipper
/spec/flipper/adapter_spec.rb
UTF-8
12,094
2.515625
3
[ "MIT" ]
permissive
require 'helper' require 'flipper/adapter' require 'flipper/adapters/memory' require 'flipper/instrumenters/memory' describe Flipper::Adapter do let(:local_cache) { {} } let(:source) { {} } let(:adapter) { Flipper::Adapters::Memory.new(source) } let(:features_key) { described_class::FeaturesKey } subject { described_class.new(adapter, :local_cache => local_cache) } describe ".wrap" do context "with Flipper::Adapter instance" do before do @result = described_class.wrap(subject) end it "returns same Flipper::Adapter instance" do @result.should equal(subject) end it "wraps adapter that instance was wrapping" do @result.adapter.should be(subject.adapter) end end context "with adapter instance" do before do @result = described_class.wrap(adapter) end it "returns Flipper::Adapter instance" do @result.should be_instance_of(described_class) end it "wraps adapter" do @result.adapter.should be(adapter) end end context "with adapter instance and options" do let(:instrumenter) { double('Instrumentor') } before do @result = described_class.wrap(adapter, :instrumenter => instrumenter) end it "returns Flipper::Adapter instance" do @result.should be_instance_of(described_class) end it "wraps adapter" do @result.adapter.should be(adapter) end it "passes options to initialization" do @result.instrumenter.should be(instrumenter) end end end describe "#initialize" do it "sets adapter" do instance = described_class.new(adapter) instance.adapter.should be(adapter) end it "sets adapter name" do instance = described_class.new(adapter) instance.name.should be(:memory) end it "defaults instrumenter" do instance = described_class.new(adapter) instance.instrumenter.should be(Flipper::Instrumenters::Noop) end it "allows overriding instrumenter" do instrumenter = double('Instrumentor', :instrument => nil) instance = described_class.new(adapter, :instrumenter => instrumenter) instance.instrumenter.should be(instrumenter) end end describe "#use_local_cache=" do it "sets value" do subject.use_local_cache = true subject.using_local_cache?.should be_true subject.use_local_cache = false subject.using_local_cache?.should be_false end it "clears the local cache" do local_cache.should_receive(:clear) subject.use_local_cache = true end end describe "#using_local_cache?" do it "returns true if enabled" do subject.use_local_cache = true subject.using_local_cache?.should be_true end it "returns false if disabled" do subject.use_local_cache = false subject.using_local_cache?.should be_false end end context "with local cache enabled" do before do subject.use_local_cache = true end describe "#read" do before do adapter.write 'foo', 'bar' @result = subject.read('foo') end it "returns result of adapter read" do @result.should eq('bar') end it "memoizes adapter read value" do local_cache['foo'].should eq('bar') adapter.should_not_receive(:read) subject.read('foo').should eq('bar') end end describe "#set_members" do before do source['foo'] = Set['1', '2'] @result = subject.set_members('foo') end it "returns result of adapter set members" do @result.should eq(Set['1', '2']) end it "memoizes key" do local_cache['foo'].should eq(Set['1', '2']) adapter.should_not_receive(:set_members) subject.set_members('foo').should eq(Set['1', '2']) end end describe "#write" do before do subject.write 'foo', 'swanky' end it "performs adapter write" do adapter.read('foo').should eq('swanky') end it "unmemoizes key" do local_cache.key?('foo').should be_false end end describe "#delete" do before do adapter.write 'foo', 'bar' subject.delete 'foo' end it "performs adapter delete" do adapter.read('foo').should be_nil end it "unmemoizes key" do local_cache.key?('foo').should be_false end end describe "#set_add" do before do source['foo'] = Set['1'] local_cache['foo'] = Set['1'] subject.set_add 'foo', '2' end it "returns result of adapter set members" do adapter.set_members('foo').should eq(Set['1', '2']) end it "unmemoizes key" do local_cache.key?('foo').should be_false end end describe "#set_delete" do before do source['foo'] = Set['1', '2', '3'] local_cache['foo'] = Set['1', '2', '3'] subject.set_delete 'foo', '3' end it "returns result of adapter set members" do adapter.set_members('foo').should eq(Set['1', '2']) end it "unmemoizes key" do local_cache.key?('foo').should be_false end end end context "with local cache disabled" do before do subject.use_local_cache = false end describe "#read" do before do adapter.write 'foo', 'bar' @result = subject.read('foo') end it "returns result of adapter read" do @result.should eq('bar') end it "does not memoize adapter read value" do local_cache.key?('foo').should be_false end end describe "#set_members" do before do source['foo'] = Set['1', '2'] @result = subject.set_members('foo') end it "returns result of adapter set members" do @result.should eq(Set['1', '2']) end it "does not memoize the adapter set member result" do local_cache.key?('foo').should be_false end end describe "#write" do before do adapter.write 'foo', 'bar' local_cache['foo'] = 'bar' subject.write 'foo', 'swanky' end it "performs adapter write" do adapter.read('foo').should eq('swanky') end it "does not attempt to delete local cache key" do local_cache.key?('foo').should be_true end end describe "#delete" do before do adapter.write 'foo', 'bar' local_cache['foo'] = 'bar' subject.delete 'foo' end it "performs adapter delete" do adapter.read('foo').should be_nil end it "does not attempt to delete local cache key" do local_cache.key?('foo').should be_true end end describe "#set_add" do before do source['foo'] = Set['1'] local_cache['foo'] = Set['1'] subject.set_add 'foo', '2' end it "performs adapter set add" do adapter.set_members('foo').should eq(Set['1', '2']) end it "does not attempt to delete local cache key" do local_cache.key?('foo').should be_true end end describe "#set_delete" do before do source['foo'] = Set['1', '2', '3'] local_cache['foo'] = Set['1', '2', '3'] subject.set_delete 'foo', '3' end it "performs adapter set delete" do adapter.set_members('foo').should eq(Set['1', '2']) end it "does not attempt to delete local cache key" do local_cache.key?('foo').should be_true end end end describe "#eql?" do it "returns true for same class and adapter" do subject.eql?(described_class.new(adapter)).should be_true end it "returns false for different adapter" do instance = described_class.new(Flipper::Adapters::Memory.new) subject.eql?(instance).should be_false end it "returns false for different class" do subject.eql?(Object.new).should be_false end it "is aliased to ==" do (subject == described_class.new(adapter)).should be_true end end describe "#features" do context "with no features enabled/disabled" do it "defaults to empty set" do subject.features.should eq(Set.new) end end context "with features enabled and disabled" do before do subject.set_add(features_key, 'stats') subject.set_add(features_key, 'cache') subject.set_add(features_key, 'search') end it "returns set of feature names" do subject.features.should be_instance_of(Set) subject.features.sort.should eq(['cache', 'search', 'stats']) end end end describe "#feature_add" do context "with string name" do before do subject.feature_add('search') end it "adds string to set" do subject.set_members(features_key).should include('search') end end context "with symbol name" do before do subject.feature_add(:search) end it "adds string to set" do subject.set_members(features_key).should include('search') end end end describe "instrumentation" do let(:instrumenter) { Flipper::Instrumenters::Memory.new } subject { described_class.new(adapter, :instrumenter => instrumenter) } it "is recorded for read" do subject.read('foo') event = instrumenter.events.last event.should_not be_nil event.name.should eq('adapter_operation.flipper') event.payload[:key].should eq('foo') event.payload[:operation].should eq(:read) event.payload[:adapter_name].should eq(:memory) event.payload[:result].should be_nil end it "is recorded for write" do subject.write('foo', 'bar') event = instrumenter.events.last event.should_not be_nil event.name.should eq('adapter_operation.flipper') event.payload[:key].should eq('foo') event.payload[:value].should eq('bar') event.payload[:operation].should eq(:write) event.payload[:adapter_name].should eq(:memory) event.payload[:result].should eq('bar') end it "is recorded for delete" do subject.delete('foo') event = instrumenter.events.last event.should_not be_nil event.name.should eq('adapter_operation.flipper') event.payload[:key].should eq('foo') event.payload[:operation].should eq(:delete) event.payload[:adapter_name].should eq(:memory) event.payload[:result].should be_nil end it "is recorded for set_members" do subject.set_members('foo') event = instrumenter.events.last event.should_not be_nil event.name.should eq('adapter_operation.flipper') event.payload[:key].should eq('foo') event.payload[:operation].should eq(:set_members) event.payload[:adapter_name].should eq(:memory) event.payload[:result].should eq(Set.new) end it "is recorded for set_add" do subject.set_add('foo', 'bar') event = instrumenter.events.last event.should_not be_nil event.name.should eq('adapter_operation.flipper') event.payload[:key].should eq('foo') event.payload[:operation].should eq(:set_add) event.payload[:adapter_name].should eq(:memory) event.payload[:result].should eq(Set['bar']) end it "is recorded for set_delete" do subject.set_delete('foo', 'bar') event = instrumenter.events.last event.should_not be_nil event.name.should eq('adapter_operation.flipper') event.payload[:key].should eq('foo') event.payload[:operation].should eq(:set_delete) event.payload[:adapter_name].should eq(:memory) event.payload[:result].should eq(Set.new) end end describe "#inspect" do it "returns easy to read string representation" do subject.inspect.should eq("#<Flipper::Adapter:#{subject.object_id} name=:memory, use_local_cache=nil>") end end end
true
969181e4818d3a035ab6e0afe237819a52398b61
Ruby
sds/scss-lint
/lib/scss_lint/linter/property_spelling.rb
UTF-8
1,858
2.75
3
[ "MIT" ]
permissive
module SCSSLint # Checks for misspelled properties. class Linter::PropertySpelling < Linter include LinterRegistry KNOWN_PROPERTIES = File.open(File.join(SCSS_LINT_DATA, 'properties.txt')) .read .split .to_set def visit_root(_node) @extra_properties = Array(config['extra_properties']).to_set @disabled_properties = Array(config['disabled_properties']).to_set yield # Continue linting children end def visit_prop(node) # Ignore properties with interpolation return if node.name.count > 1 || !node.name.first.is_a?(String) nested_properties = node.children.select { |child| child.is_a?(Sass::Tree::PropNode) } if nested_properties.any? # Treat nested properties specially, as they are a concatenation of the # parent with child property nested_properties.each do |nested_prop| check_property(nested_prop, node.name.join) end else check_property(node) end end private def check_property(node, prefix = nil) # rubocop:disable CyclomaticComplexity return if contains_interpolation?(node) name = prefix ? "#{prefix}-" : '' name += node.name.join # Ignore vendor-prefixed properties return if name.start_with?('-') return if known_property?(name) && !@disabled_properties.include?(name) if @disabled_properties.include?(name) add_lint(node, "Property #{name} is prohibited") else add_lint(node, "Unknown property #{name}") end end def known_property?(name) KNOWN_PROPERTIES.include?(name) || @extra_properties.include?(name) end def contains_interpolation?(node) node.name.count > 1 || !node.name.first.is_a?(String) end end end
true
e66e1ac17cbf1f7be09cf8ef857cdbdc78750849
Ruby
vickyban/rubyBasic
/stdin.rb
UTF-8
406
4.21875
4
[]
no_license
# print "Please put your string here!" # # gets will prompt and ad new line to the input # user_input = gets.chomp # user_input.downcase! puts "Enter a number: " num1 = gets.chomp() # chomp remove the new line at the end of the input puts "Enter another number: " num2 = gets.chomp() puts (num1.to_i + num2.to_i ) # to_i convert to integer puts (num1.to_f + num2.to_f ) # to_f convert to float
true
a1d516ddf76a6b8b94d275fb6bdc9c0c7dc4fca9
Ruby
lee-angela/ThreadFeed
/test/models/shop_post_test.rb
UTF-8
1,012
2.59375
3
[]
no_license
require 'test_helper' class ShopPostTest < ActiveSupport::TestCase def setup @shop = shops(:madewell) # This code is not idiomatically correct. @shop_post = @shop.shop_posts.build(content: "Lorem ipsum") end test "should be valid" do assert @shop_post.valid? end test "user id should be present" do @shop_post.shop_id = nil assert_not @shop_post.valid? end test "content should be present" do @shop_post.content = " " assert_not @shop_post.valid? end test "content should be at most 140 characters" do @shop_post.content = "a" * 141 assert_not @shop_post.valid? end test "order should be most recent first" do assert_equal shop_posts(:most_recent), ShopPost.first end test "associated items should be destroyed" do @shop_post.save @shop_post.items.create!(name: "Item 1", price:"$58.00", main_img_url: "www.test.com/image.png") assert_difference 'Item.count', -1 do @shop_post.destroy end end end
true
e89144cbfb0695537e95bdaf6396c116b2573f1c
Ruby
lokibyte/myRubycode
/Ruby codes/Ruby Examples/sequel_examples/te.rb
UTF-8
174
2.765625
3
[]
no_license
a=[] name=nil while name !='q' do name=gets.chomp a.push(name) p a # break name =='loki' end # if name =='loki' then # until name =='loki' # a.pop() # p a # end # end
true
ea03d0e6c08ef3fead5eb2e4b2a4f3ad93601b8e
Ruby
mlh758/redis_stream_logger
/lib/redis_stream_logger/log_device.rb
UTF-8
4,143
2.765625
3
[ "MIT" ]
permissive
require 'logger' require "redis_stream_logger/config" module RedisStreamLogger class LogDevice attr_reader :config # # Creates a new LogDevice that can be used as a sink for Ruby Logger # # @param [Redis] conn connection to Redis # @param [String] stream name of key to write to # def initialize(conn = nil, stream: 'rails-log') @config = Config.new @closed = false # Just in case a whole new config is passed in like in the Railtie new_conf = yield @config if block_given? @config = new_conf if new_conf.is_a?(Config) @config.connection ||= conn @config.stream_name ||= stream raise ArgumentError, 'must provide connection' if @config.connection.nil? @q = Queue.new start end def write(msg) @q.push msg end def reopen(log = nil) close @config.connection._client.connect start end def close return if @closed @q.push :exit @ticker.exit @writer.join @config.connection.close @closed = true end private def start @closed = false @error_logger = ::Logger.new(STDERR) @ticker = Thread.new do ticker(@config.send_interval) end @writer = Thread.new do writer(@config.buffer_size, @config.send_interval) end at_exit { close } end def send_options return {} if @config.max_len.nil? { maxlen: @config.max_len, approximate: true } end # # Writes a batch of log lines to the Redis stream # # @param [Array<String>] messages to write to the stream # # def write_batch(messages) redis = @config.connection opt = send_options messages.each_slice(@config.batch_size) do attempt = 0 begin redis.pipelined do messages.each do |msg| redis.xadd(@config.stream_name, {m: msg}, **opt) end end rescue StandardError => exception attempt += 1 retry if attempt <= 3 @error_logger.warn "unable to write redis logs: #{exception}" messages.each { |m| @error_logger.info(m) } end end end # # Pushes a message into the queue at the given interval # to wake the writer thread up to ensure it sends partial # buffers if no new logs come in. # # @param [Integer] interval to wake the writer up on # def ticker(interval) loop do sleep(interval) @q.push(:nudge) end end def control_msg?(msg) msg == :nudge || msg == :exit end # # Stores the name of the logger in the configured set so other tools can # locate the list of available log streams # # def store_logger_name @config.connection.sadd(@config.log_set_key, @config.stream_name) rescue StandardError => exception @error_logger.warn "unable to store name of log: #{exception}" end # # Used in a thread to pull log messages from a queue and store them in batches into a redis # stream. # # @param [Integer] buffer_max maximum number of log entries to buffer before sending # @param [Integer] interval maximum amount of time to wait before sending a partial buffer # # def writer(buffer_max, interval) last_sent = Time.now buffered = [] store_logger_name loop do msg = @q.pop buffered.push(msg) unless control_msg?(msg) now = Time.new if buffered.count >= buffer_max || (now - last_sent) > interval || msg == :exit write_batch(buffered) return if msg == :exit last_sent = Time.now buffered = [] end end end end end
true
e6f65e4ca697c646dc94123b427bc883750be1d9
Ruby
mjwebdev/number_game
/app/controllers/numbers_controller.rb
UTF-8
543
2.65625
3
[]
no_license
class NumbersController < ApplicationController def index if !session[:random] session[:random] = rand(1..100) end end def random end def guess session[:guess] = params[:guess].to_i redirect_to "/result" end def result if session[:guess] > session[:random] flash[:high] = "You guessed too high, my friend." elsif session[:guess] < session[:random] flash[:low] = "You guessed too low, my friend." else flash[:right] = "You guessed correct. Great Job!!" end redirect_to "/" end end
true
cc86212bde59fb0ddce2dfbdda2815adf0a9eacd
Ruby
SnowD0g/adapter_pattern
/rectangle.rb
UTF-8
233
3.828125
4
[ "Apache-2.0" ]
permissive
require_relative 'shape' class Rectangle < Shape def initialize(x1, y1, x2, y2) @x1, @y1, @x2, @y2 = x1, y1, x2, y2 end def draw puts "#{super} primo punto (#{@x1}, #{@y1}) e secondo punto (#{@x2}, #{@y2})" end end
true
d68cce0bf4926ce055619de60e8d3179f990149f
Ruby
OliDM/order-of-the-pixel
/spec/heroes_spec.rb
UTF-8
1,961
2.59375
3
[]
no_license
ENV['RACK_ENV'] = 'test' gem "minitest" require 'rack/test' require 'minitest/autorun' require_relative '../app.rb' require_relative 'helpers.rb' # Custom methods to simulate Rspec’s “expect {}.to change {}.by(x)”. include Rack::Test::Methods def app Sinatra::Application end describe "See all heroes" do it "responds with OK to hero index call" do get "/api/heroes" last_response.status.must_equal 200 end end describe "See a hero" do before do data = {name: "Mindless Zombie", weapon_id: 1, job_id: 1, race_id: 1} post "/api/heroes", data end it "responds with OK to hero show call" do get "/api/heroes/2" last_response.status.must_equal 200 end end describe "Create a hero" do before do @data = { name: "Mindless Zombie", weapon_id: 1, job_id: 1, race_id: 1 } end it "must increase the hero count by one" do lambda { post "/api/heroes", @data }.must_change Hero.all, :count, +1 end it "check if the hero has been created accordingly" do post_data = post "/api/heroes", @data resp = JSON.parse(post_data.body) resp["name"].must_equal "Mindless Zombie" resp["weapon_id"].must_equal 1 resp["race_id"].must_equal 1 resp["job_id"].must_equal 1 end end describe "Edit a hero" do before do @data = {name: "Zeus"} end it "check if the hero has been updated accordingly" do put_data = put "/api/heroes/2", @data resp = JSON.parse(put_data.body) resp["name"].must_equal "Zeus" end end describe "Destroy a hero" do before do @data = { name: "Mindless Zombie", weapon_id: 1, job_id: 1, race_id: 1 } post "/api/heroes", @data end it "must decrease the hero count by one" do lambda { delete "/api/heroes/1" }.must_change Hero.all, :count, -1 last_response.status.must_equal 200 end end
true
a8208c2de16e2df77df4075439811bf013fbf120
Ruby
mattistrading/acts_as_gold
/test/acts_as_gold_test.rb
UTF-8
2,180
2.890625
3
[ "MIT" ]
permissive
require 'test/unit' require 'rubygems' gem 'activerecord', '>= 1.15.4.7794' require 'active_record' require "#{File.dirname(__FILE__)}/../init" ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :dbfile => ":memory:") def setup_db ActiveRecord::Schema.define(:version => 1) do create_table :players do |t| t.column :money, :integer end create_table :another_players do |t| t.column :pennies, :integer end end end def teardown_db ActiveRecord::Base.connection.tables.each do |table| ActiveRecord::Base.connection.drop_table(table) end end class Player < ActiveRecord::Base acts_as_gold # defaults to :column => :money end class AnotherPlayer < ActiveRecord::Base acts_as_gold :column => :pennies end class ActsAsGoldTest < Test::Unit::TestCase def setup # Creates a Player iwth 250G, 44S and 55C setup_db Player.create(:money => 2504455) @player = Player.find(:first) end def teardown teardown_db end def test_alternate_column_name AnotherPlayer.create(:pennies => 1005095) @alt_player = AnotherPlayer.find(:first) assert_equal 1005095, @alt_player.pennies assert_equal 100, @alt_player.gold assert_equal 50, @alt_player.silver assert_equal 95, @alt_player.copper end def test_money_retrieval assert_equal 2504455, @player.money assert_equal 250, @player.gold assert_equal 44, @player.silver assert_equal 55, @player.copper end def test_numeric_extensions assert_equal 2500000, 250.gold assert_equal 2500, 25.silver assert_equal 25, 25.copper end def test_money_earning assert_equal 2504455, @player.money assert @player.earn(3.gold + 22.silver + 33.copper) assert_equal 2536688, @player.money end def test_money_spending assert_equal 2504455, @player.money assert @player.spend(3.gold + 22.silver + 33.copper) assert_equal 2472222, @player.money end def test_too_much_money_spending assert_equal 2504455, @player.money assert_raise(ActsAsGold::NotEnoughMoneyError) { @player.spend(300.gold) } assert_equal 2504455, @player.money end end
true
31f247639463e2a072cd1ee3281d2479a023ce38
Ruby
Packmanager9/Soil-to-life
/soily.rb
UTF-8
11,507
3.015625
3
[]
no_license
require "TextGrapher" $xrange = 80 $yrange = 80 $steps = 2000 class Fighter attr_accessor :name, :status, :x, :y, :r, :g, :b, :all @@all = [] def initialize(name, x, y, status, r, g, b) @name = name @status = status @x = x.to_i @y = y.to_i @r = r @g = g @b = b @@all << self end def self.all @@all end end class Terrain < Fighter attr_accessor :type, :energy, :energy, :all @@all = [] def initialize(name, x, y, status, r, g, b, type, depth, energy) super(name, x, y, status, r, g, b) @type = type @energy = energy @depth = depth @@all << self end def self.all @@all end end class Plant < Fighter attr_accessor :type, :depth, :energy, :growthrate, :all @@all = [] def initialize(name, x, y, status, r, g, b, type, depth, energy, growthrate) super(name, x, y, status, r, g, b) @type = type @energy = energy @depth = depth @growthrate = growthrate @@all << self end def self.all @@all end def self.avg_energy x = 0 Plant.all.each do |plant| x += plant.energy end avg = (x.to_f/Plant.all.length) avg end end class Herbivore < Fighter attr_accessor :type, :depth, :energy, :growthrate, :all @@all = [] def initialize(name, x, y, status, r, g, b, type, depth, energy, growthrate) super(name, x, y, status, r, g, b) @type = type @energy = energy @depth = depth @growthrate = growthrate @@all << self end def self.all @@all end end #0 == dust #1 = active #0 = soil def belllcurve(y) x = 0 y.times do x += rand(0..1) end x end dustcolor = ChunkyPNG::Color.rgba(162, 116, 78, 255) dust = Terrain.new(0, 5, 5, 1, 162, 116, 78, "path", 0, 10) grass = Plant.new(0, 4, 4, 1, rand(50), (rand(122)+134), rand(50), "plant", 0, (belllcurve(100)+10), (belllcurve(5)+1)) puts dust puts grass def populate y = 0 x = 0 ($yrange+1).times do ($xrange+1).times do terr = provideterrain(0, 6, x, y) #pngx[x,y] = ChunkyPNG::Color.rgba(terr.r, terr.g, terr.b, 255) x+=1 end x = 0 y+=1 end y = 0 x = 0 ($yrange+1).times do ($xrange+1).times do if rand(20) == (x%20) terr = provideplants(0, 3, x, y) end #pngx[x,y] = ChunkyPNG::Color.rgba(terr.r, terr.g, terr.b, 255) x+=1 end x = 0 y+=1 end y = 0 x = 0 ($yrange+1).times do ($xrange+1).times do if rand(200) == (x%20) terr = provideanimals(0, 3, x, y) end #pngx[x,y] = ChunkyPNG::Color.rgba(terr.r, terr.g, terr.b, 255) x+=1 end x = 0 y+=1 end end def provideterrain(a, b, x, y) # dustcolor = ChunkyPNG::Color.rgba(rand(130..170), rand(80..130), rand(50..100), 255) dust = Terrain.new(-1, x, y, 1, rand(170..180), rand(110..120), 78, "path", 0, 1) clay = Terrain.new(-2, x, y, 1, rand(120..130), rand(80..90), 68, "path", 0, 10) dirt = Terrain.new(-3, x, y, 1, rand(110..120), rand(70..80), 58, "path", 0, 25) soil = Terrain.new(-4, x, y, 1, rand(100..110), rand(60..70), 48, "path", 0, 50) earth = Terrain.new(-5, x, y, 1, rand(90..110), rand(50..60), 38, "path", 0, 100) mud = Terrain.new(-6, x, y, 1, rand(80..100), rand(40..50), 28, "path", 0, 200) loam = Terrain.new(-7, x, y, 1, rand(70..90), rand(30..40), 18, "path", 0, 500) rock = Terrain.new(-8, x, y, 1, rand(150..170), rand(150..170), 160, "path", 0, 0) c = rand(a..b) case c when 7 d = rock when 0 d = dust when 1 d = clay when 2 d = dirt when 3 d = mud when 4 d = earth when 5 d = soil when 6 d = loam else d = mud end d end def provideterrainbasic(a, b, x, y) # dustcolor = ChunkyPNG::Color.rgba(rand(130..170), rand(80..130), rand(50..100), 255) dust = Terrain.new(0, x, y, 1, rand(170..180), rand(110..120), 78, "path", 0, 1) dirt = Terrain.new(1, x, y, 1, rand(120..130), rand(80..90), 68, "path", 0, 100) c = rand(a..b) case c when 0 d = dust when 1 d = dirt else d = dust end d end def fuzzer_x(num, range = $xrange, floor = 0) num += rand(-1..1) if num < 0 num = 0 end if num > range num = range end num end def interact(front, back) if front.name >= 0 && back.name >= 0 #&& front.name != back.name # puts "here" #puts front.name #puts back.name if front.name < 3 && back.name > 5 # puts "left" #puts front.status # puts front.status #puts back.energy back.energy += front.energy Plant.all.delete(front) front = nil # puts back.energy end if back.name < 3 && front.name > 5 # puts "right" front.energy += back.energy Plant.all.delete(back) back = nil end end GC.start(full_mark: true, immediate_sweep: true); end def fuzzer_y(num, range = $yrange, floor = 0) num += rand(-1..1) if num < 0 num = 0 end if num > range num = range end num end def provideplants(a, b, x, y) grass = Plant.new(0, x, y, 1, rand(50), (rand(122)+134), rand(50), "plant", 0, (belllcurve(100)+10), (belllcurve(10)+10)) shrub = Plant.new(1, x, y, 1, rand(20), (rand(100)+134), rand(20), "plant", 0, (belllcurve(200)+100), (belllcurve(7)+7)) tree = Plant.new(2, x, y, 1, rand(10), (rand(50)+134), rand(10), "plant", 0, (belllcurve(500)+200), (belllcurve(5)+3)) c = rand(a..b) case c when 0 d = grass when 1 d = shrub when 2 d = tree else d = grass end if (x % 20) == 0 d = tree end d end def provideanimals(a, b, x, y) rabbit = Herbivore.new(6, x, y, 1, 255, (rand(1)+134), rand(255), "herbi", 0, (belllcurve(200)+10), (belllcurve(1)+2)) deer = Herbivore.new(7, x, y, 1, rand(20), (rand(1)+134), 200, "herbi", 0, (belllcurve(400)+10), (belllcurve(2)+4)) elephant = Herbivore.new(8, x, y, 1, 150,150, 160, "herbi ", 0, (belllcurve(800)+10), (belllcurve(3)+6)) c = rand(a..b) case c when 0 d = rabbit when 1 d = deer when 2 d = elephant else d = rabbit end d end z = 0 $steps.times do pngx = ChunkyPNG::Image.new($xrange+1, $yrange+1, ChunkyPNG::Color::BLACK) if z == 0 ##start of the grid populate end paths = Terrain.all.select do |path| path.type = "path" end paths.each do |soil| if soil.status !=0 pngx[soil.x, soil.y] = ChunkyPNG::Color.rgba(soil.r, soil.g, soil.b, 255) if rand(7000000) < soil.energy provideplants(0, 2, soil.x, soil.y) end end end plants = Plant.all.select do |plant| plant.type == "plant" && plant.status != 0 end plants.each do |plant| if plant.status != 0 pngx[plant.x, plant.y] = ChunkyPNG::Color.rgba(plant.r, plant.g, plant.b, 255) plant.energy += plant.growthrate end end herbivores = Herbivore.all.select do |animal| animal.name > 5 end #if z == 5 # dogs.clear # end #herbivores.each do |animal| herbivores.each do |animal| pngx[animal.x, animal.y] = ChunkyPNG::Color.rgba(animal.r, animal.g, animal.b, 255) animal.x = fuzzer_x(animal.x) animal.y = fuzzer_y(animal.y) puts animal.energy animal.energy -= animal.growthrate puts animal.energy if (animal.energy > 1001 && animal.name == 8) || (animal.energy > 501 && animal.name == 7) || (animal.energy > 251 && animal.name == 6) if animal.name == 8 animal.energy -= 1000 Herbivore.new(animal.name, animal.x, animal.y, animal.status, [animal.r+rand(-10..10), 255].min, [animal.g+rand(-10..10), 150].min, [animal.b+rand(-10..10), 255].min, animal.type, animal.depth, 750, animal.growthrate) elsif animal.name ==7 animal.energy -= 500 Herbivore.new(animal.name, animal.x, animal.y, animal.status, [animal.r+rand(-10..10), 255].min, [animal.g+rand(-10..10), 150].min, [animal.b+rand(-10..10), 255].min, animal.type, animal.depth, 160, animal.growthrate) Herbivore.new(animal.name, animal.x, animal.y, animal.status, [animal.r+rand(-10..10), 255].min, [animal.g+rand(-10..10), 150].min, [animal.b+rand(-10..10), 255].min, animal.type, animal.depth, 160, animal.growthrate) elsif animal.name == 6 animal.energy -= 250 Herbivore.new(animal.name, animal.x, animal.y, animal.status, [animal.r+rand(-10..10), 255].min, [animal.g+rand(-10..10), 150].min, [animal.b+rand(-10..10), 255].min, animal.type, animal.depth, 50, animal.growthrate) Herbivore.new(animal.name, animal.x, animal.y, animal.status, [animal.r+rand(-10..10), 255].min, [animal.g+rand(-10..10), 150].min, [animal.b+rand(-10..10), 255].min, animal.type, animal.depth, 50, animal.growthrate) Herbivore.new(animal.name, animal.x, animal.y, animal.status, [animal.r+rand(-10..10), 255].min, [animal.g+rand(-10..10), 150].min, [animal.b+rand(-10..10), 255].min, animal.type, animal.depth, 50, animal.growthrate) end end if animal.energy <= 0 Herbivore.all.delete(animal) animal = nil GC.start(full_mark: true, immediate_sweep: true); end end z +=1 find = Plant.all.select do |plant| plant.name == 1 end plantoids = Plant.all.select do |plant| plant.name == 0 || plant.name == 1 || plant.name == 2 end trees = Plant.all.select do |plant| plant.name == 2 end animals = Herbivore.all.select do |animal| animal.name > 5 end # puts plantoids.length # puts find.length # puts grassfind.length # puts plantoids.length #puts Plant.avg_energy puts z matches = [] matches = animals + plantoids y = 0 x = 0 ($yrange).times do ($xrange).times do gather = matches.select do |part| part.x == x && part.y == y end ace = gather.find do |obj| obj.name > 5 end bace = gather.find do |obj| obj.name < 3 && obj.name >= 0 end if bace != nil && ace != nil # puts gather.length # puts bace.name # puts ace.name interact(bace, ace) end x+=1 end x = 0 y+=1 end dead = Plant.all.select do |every| every == nil end # puts dead.length Plant.all.delete_if do |obj| dead.include?(obj) end pngx.save("gifmake28/life/#{z}.png") end
true
ad2cc6ff69fd93845e0f2bb51aa1b4217a63e299
Ruby
auroralemieux/stacks-queues
/lib/Stack.rb
UTF-8
417
3.671875
4
[]
no_license
class Stack def initialize @store = Array.new end def push(element) @store << element end def pop raise ArgumentError.new "Can't pop from an empty stack!" if @store.empty? @store.pop end def top @store.last end def size @store.length end def empty? if @store.length == 0 true else false end end def to_s return @store.to_s end end
true
019da4b304f10bea1f9089bc86b1a16ff03cdc76
Ruby
scottwedge/coding-refresher
/src/practice/session-1/max_subarray_product.rb
UTF-8
670
3.640625
4
[ "MIT" ]
permissive
=begin Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. Example 1: Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6. Example 2: Input: [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray. =end # @param {Integer[]} nums # @return {Integer} def max_product(nums) min = max = 1 max_prod = nums.first nums.each do |n| # min so far could become when n is negative and the max could become min vice verca min, max = [n, min * n, max * n].minmax max_prod = [max_prod, max].max end return max_prod end
true
bb881da26539abbf97ed23ad5a369357e33af631
Ruby
wendy0402/jsm
/lib/jsm/callbacks/callback.rb
UTF-8
616
3.5
4
[ "MIT" ]
permissive
# the purpose of this class is to store the block that will be used as callback # e.g: # Jsm::Callbacks::Callback.new(:before) do # put 'me awesome' # end class Jsm::Callbacks::Callback FILTER_TYPES = [:before, :after] attr_reader :filter_type # the allowed filter_type: :before, :after def initialize(filter_type, &block) if FILTER_TYPES.include?(filter_type) @filter_type = filter_type else raise ArgumentError, "invalid type #{filter_type}, allowed: #{FILTER_TYPES.join(', ')}" end @block = block end # run callback def execute(*obj) @block.call(*obj) end end
true
6be783f2fbed821bb50be38f874e084984ad326c
Ruby
hivan/Ruby_Learn
/Programming/ex0016.rb
UTF-8
79
2.9375
3
[]
no_license
def say_goodnight(name) "Good night, #{name}" end puts say_goodnight("Ma")
true
f0093313f7d92afbe22df9f1bebf068d2f531332
Ruby
czycha/recluse
/lib/recluse/cli/roots.rb
UTF-8
1,716
2.59375
3
[ "MIT" ]
permissive
require 'thor' require 'user_config' module Recluse module CLI ## # Roots related commands. class Roots < Thor #:nodoc: all desc 'add profile pattern1 [pattern2] ...', 'add to roots' def add(name, *roots) uconf = UserConfig.new '.recluse' unless uconf.exist?("#{name}.yaml") puts "Profile #{name} doesn't exist" exit(-1) end profile = uconf["#{name}.yaml"] if profile.key?('roots') profile['roots'] += roots else profile['roots'] = roots end profile.save end desc 'remove profile pattern1 [pattern2] ...', 'remove from roots' def remove(name, *roots) uconf = UserConfig.new '.recluse' unless uconf.exist?("#{name}.yaml") puts "Profile #{name} doesn't exist" exit(-1) end profile = uconf["#{name}.yaml"] return unless profile.key?('roots') profile['roots'] -= roots profile.save end desc 'clear profile', 'remove all roots' def clear(name) uconf = UserConfig.new '.recluse' unless uconf.exist?("#{name}.yaml") puts "Profile #{name} doesn't exist" exit(-1) end profile = uconf["#{name}.yaml"] profile['roots'] = [] profile.save end desc 'list profile', 'list roots' def list(name) uconf = UserConfig.new '.recluse' unless uconf.exist?("#{name}.yaml") puts "Profile #{name} doesn't exist" exit(-1) end profile = uconf["#{name}.yaml"] profile['roots'].each { |root| puts root } if profile.key?('roots') end end end end
true
baa3df70a1f28012551c35e816696af6ee1b5a5a
Ruby
NoahZinter/black_thursday
/spec/invoice_item_spec.rb
UTF-8
4,246
2.578125
3
[]
no_license
require './lib/invoice_item' require 'bigdecimal' require 'time' describe InvoiceItem do describe '#initialize' do it 'exists' do ii_details = { id: 6, item_id: 7, invoice_id: 8, quantity: 1, unit_price: BigDecimal(10.99, 4), created_at: Time.now, updated_at: Time.now } invoice_item = InvoiceItem.new(ii_details) expect(invoice_item).is_a? InvoiceItem end it 'returns the integer id' do ii_details = { id: 6, item_id: 7, invoice_id: 8, quantity: 1, unit_price: BigDecimal(10.99, 4), created_at: Time.now, updated_at: Time.now } invoice_item = InvoiceItem.new(ii_details) expect(invoice_item.id).to eq 6 expect(invoice_item.id).is_a? Integer end it 'returns the item id' do ii_details = { id: 6, item_id: 7, invoice_id: 8, quantity: 1, unit_price: BigDecimal(10.99, 4), created_at: Time.now, updated_at: Time.now } invoice_item = InvoiceItem.new(ii_details) expect(invoice_item.item_id).to eq 7 expect(invoice_item.item_id).is_a? Integer end it 'returns the invoice id' do ii_details = { id: 6, item_id: 7, invoice_id: 8, quantity: 1, unit_price: BigDecimal(10.99, 4), created_at: Time.now, updated_at: Time.now } invoice_item = InvoiceItem.new(ii_details) expect(invoice_item.invoice_id).to eq 8 expect(invoice_item.invoice_id).is_a? Integer end it 'returns the quantity' do ii_details = { id: 6, item_id: 7, invoice_id: 8, quantity: 1, unit_price: BigDecimal(10.99, 4), created_at: Time.now, updated_at: Time.now } invoice_item = InvoiceItem.new(ii_details) expect(invoice_item.quantity).to eq 1 end it 'returns the unit price' do ii_details = { id: 6, item_id: 7, invoice_id: 8, quantity: 1, unit_price: '1099', created_at: Time.now, updated_at: Time.now } invoice_item = InvoiceItem.new(ii_details) expect(invoice_item.unit_price).to eq BigDecimal(10.99, 4) expect(invoice_item.unit_price).is_a? BigDecimal end it 'returns a Time instance for date invoice_item was created' do ii_details = { id: 6, item_id: 7, invoice_id: 8, quantity: 1, unit_price: '1099', created_at: Time.parse('2007-06-04 21:35:10 UTC'), updated_at: Time.now } invoice_item = InvoiceItem.new(ii_details) expect(invoice_item.created_at).to eq(Time.parse('2007-06-04 21:35:10 UTC')) expect(invoice_item.created_at).is_a? Time end it 'returns a Time instance for date invoice_item updated' do ii_details = { id: 6, item_id: 7, invoice_id: 8, quantity: 1, unit_price: BigDecimal(10.99, 4), created_at: Time.now, updated_at: Time.parse('2007-06-04 21:35:10 UTC') } invoice_item = InvoiceItem.new(ii_details) expect(invoice_item.updated_at).to eq(Time.parse('2007-06-04 21:35:10 UTC')) expect(invoice_item.updated_at).is_a? Time end end describe '#unit price to dollars' do it 'returns the price of the invoice_item in dollars as Float' do ii_details = { id: 6, item_id: 7, invoice_id: 8, quantity: 1, unit_price: '1099', created_at: Time.now, updated_at: Time.now } invoice_item = InvoiceItem.new(ii_details) expect(invoice_item.unit_price_to_dollars).is_a? Float expect(invoice_item.unit_price_to_dollars).to eq 10.99 end end describe '#total' do it 'returns the total price for the InvoiceItem' do ii_details = { id: 6, item_id: 7, invoice_id: 8, quantity: 1, unit_price: '1099', created_at: Time.now, updated_at: Time.now } invoice_item = InvoiceItem.new(ii_details) expect(invoice_item.total).to eq 10.99 end end end
true
e5b5bae74a98e5196e8fa4838cbb34fdeb6e90ef
Ruby
thoran/AsxhistoricaldataCom
/lib/Date/betweenQ.rb
UTF-8
323
3.34375
3
[]
no_license
# Date/betweenQ # Date#between? # 20120412 # 0.0.0 # Description: This determines whether a date is between two other dates inclusively, with no particular order to the to arguments. class Date def between?(date_1, date_2) (self <= date_1 && self >= date_2) || (self >= date_1 && self <= date_2) end end
true
8d2160d7472cd954bd742dc982cd6196cfbfe871
Ruby
daniel-certa-1228/Ruby-TDD-Demo
/magic_ball_test.rb
UTF-8
1,596
3.328125
3
[]
no_license
#Ruby Unit Testing require 'minitest/autorun' require_relative 'magic_ball.rb' #using a gem called minitest - rspec is also common class MagicballTest < MiniTest::Test def test_ask_returns_an_answer magicball = Magicball.new assert_includes Magicball::ANSWERS, magicball.ask("Test?") #the actual test 'assert' is part of minitest. The first part of the statement is the result your looking for, and the second part is what is being sent in to test the scenario end def test_predefined_answer_is_array assert_kind_of Array, Magicball::ANSWERS end def test_predefined_answers_is_not_empty refute_empty Magicball::ANSWERS #double colons allow access to class constant end def test_raises_error_when_question_is_number assert_raises "Question has invalid format" do magicball = Magicball.new magicball.ask(1) end end end # require "minitest/autorun" # require "minitest/spec" # require_relative "magic_ball.rb" # #behavior-driven testing - rspec will look like this # describe Magicball do # describe "#ask" do # it "returns an answer" do # magic_ball = Magicball.new # assert_includes Magicball::ANSWERS, magic_ball.ask("Test?") # end # it "predefined answers is array" do # assert_kind_of Array, Magicball::ANSWERS # end # it "predefined answers is not empty" do # refute_empty Magicball::ANSWERS # end # it "raises error when question is number" do # assert_raises "Question has invalid format." do # magic_ball = Magicball.new # magic_ball.ask(1) # end # end # end # end
true
d54336c38599b48a7584b86adcd3b678c53da850
Ruby
IanLawson8913/codewar_exercises
/playing_with_digits.rb
UTF-8
272
3.453125
3
[]
no_license
def dig_pow(n, p) digits = n.to_s.chars.map(&:to_i) powers = [] digits.length.times { |x| powers << (digits.shift**(x + p)) } sum = powers.reduce(:+) if (sum % n).zero? sum / n else -1 end end p dig_pow(89, 1) p dig_pow(92, 1) p dig_pow(46288, 3)
true
89556b4168981af844ecf5538e526baaf3c3d034
Ruby
emilianolowe/launch-school-exercises
/Ruby/easy/easy8/double_char2.rb
UTF-8
397
3.515625
4
[]
no_license
def double_consonants(string) result = [] string.chars.each do |elem| if elem.match?(/[b-df-hj-np-tv-z]/i) result << elem << elem else result << elem end end p result.join end p double_consonants('String') == "SSttrrinngg" p double_consonants("Hello-World!") == "HHellllo-WWorrlldd!" p double_consonants("July 4th") == "JJullyy 4tthh" p double_consonants('') == ""
true
ffe690daaa83d73c5d684de44956b8de7221a28a
Ruby
rodders110/week4-project
/seed.rb
UTF-8
1,273
2.6875
3
[]
no_license
require_relative('models/stock') require_relative('models/manufacturer') require_relative('models/inventory') require('pry') sweets = [{'name' => "Acid Drops"}, {'name' => 'Aniseed Balls'}, {'name' => 'American Hard Gums'}, {'name' => 'Apple Bon Bons'}, {'name' => 'Berwick Cockles'}, {'name' => 'Black Jacks'}, {'name' => 'Brown Mice'}, {'name' => 'White Mice'}] sweets.each {|sweet| Stock.new(sweet).save()} places = [{'name' => 'Aldomack Ltd', 'address' => 'Giffnock'}, {'name' => 'CandyCo of Troon', 'address' => 'Irvine'}, {'name' => 'Gordon & Durwood', 'address' => 'Creiff'}, {'name' => 'Drysdale & Gibb Ltd', 'address' => 'Greenock'}] places.each {|place| Manufacturer.new(place).save()} lists = [{'stock_id' => '1', 'manufacturers_id' => '1', 'volume' => '100'}, {'stock_id' => '3', 'manufacturers_id' => '1', 'volume' => '100'}, {'stock_id' => '2', 'manufacturers_id' => '2', 'volume' => '100'}, {'stock_id' => '4', 'manufacturers_id' => '2', 'volume' => '100'}, {'stock_id' => '5', 'manufacturers_id' => '3', 'volume' => '100'}, {'stock_id' => '7', 'manufacturers_id' => '3', 'volume' => '100'}, {'stock_id' => '6', 'manufacturers_id' => '4', 'volume' => '100'}, {'stock_id' => '8', 'manufacturers_id' => '4', 'volume' => '100'}] lists.each {|list| Inventory.new(list).save()}
true
217c608d0ea8cfa7d2298a6880d5fab29c65bf98
Ruby
maksar/shortener
/app/models/permalink_repo.rb
UTF-8
1,209
2.640625
3
[ "MIT" ]
permissive
class PermalinkRepo include Singleton def initialize uri = URI.parse ENV["REDIS_URL"] @redis = Redis.new host: uri.host, port: uri.port, password: uri.password end def recall short result = @redis.hgetall short return nil if result.empty? Permalink.new result.merge short: short end def register url, short = '' permalink = Permalink.new(url: url, short: short) return invalid_url(permalink) if url.empty? # Trying to register with custom short. if short.present? return hash_already_used(permalink) unless insert(short, url) else # Trying to insert until successful. until insert(short = generate_next_short, url) end end recall short end def count short, browser @redis.hincrby short, browser, 1 if recall short recall short end private def invalid_url permalink permalink.tap { |p| p.errors.add(:url, :blank) } end def hash_already_used permalink permalink.tap { |p| p.errors.add(:short, :used) } end def insert short, url @redis.hsetnx short, :url, url end def generate_next_short PermalinkCode.new(seed).generate end def seed @redis.incr :seed end end
true
f0a5d51a0b47aabccc048739fe1f59c4bc4ae33c
Ruby
sugi1119/wdi-5
/06-advanced/regexp/ex-2.rb
UTF-8
128
2.59375
3
[]
no_license
# Line reader program ARGF.each do |line| puts line if line =~ /fred/i # //i is a case "i"nsensitive regular expression. end
true
2ad2d3f849192cafcd8792ce97209b2faadbb536
Ruby
akjagadeesh/hw-ruby-intro
/lib/ruby_intro.rb
UTF-8
2,037
3.796875
4
[]
no_license
# When done, submit this entire file to the autograder. # Part 1 def sum arr # YOUR CODE HERE Integer zero = 0 if arr.length == 0 return zero else Integer r_sum = 0 for nums in arr r_sum = r_sum + nums end return r_sum end end def max_2_sum arr # YOUR CODE HERE if arr.length == 0 return 0 elsif arr.length == 1 return arr[0] else biggest= -1.0/0 biggest_2= -1.0/0 for nums in arr if(nums>biggest) biggest_2=biggest biggest = nums elsif (nums > biggest_2 ) biggest_2=nums end end return biggest+biggest_2 end end def sum_to_n? arr, n # YOUR CODE HERE if arr.length == 0 return false end combos = arr.combination(2).to_a for combo in combos sum = max_2_sum(combo) if sum == n return true end end return false end # Part 2 def hello(name) if name == nil return nil else return "Hello, " + name end end def starts_with_consonant? s if s.length == 0 return false elsif (/\W/.match(s[0])) return false elsif (/[AEIOUaeiou]/.match(s[0])) return false else return true end end def binary_multiple_of_4? s if not (/\A[+-]?\d+(\.\d+)?\z/.match(s)) return false end num=s.to_i puts num end_condition=1 last_digit = 0 dec_num = 0 base = 1 while(end_condition!=0) end_condition = num/10 last_digit = num % 10 num = end_condition dec_num = dec_num+(last_digit*base) base = base * 2 end if(dec_num % 4 == 0) return true else return false end end # Part 3 class BookInStock # YOUR CODE HERE attr_reader :isbn attr_writer :isbn attr_writer :price attr_reader :price def initialize(bisbn,bprice) raise ArgumentError if(bisbn.length == 0 || bprice <= 0) @isbn = bisbn @price = bprice end def price_as_string @price = '%.2f' % @price price_s = "$" + @price.to_s return price_s end end
true
7a7b494ac8d1785a319af47201088e01a42c6906
Ruby
SStrausman/codechallenge
/spec/models/assessment_spec.rb
UTF-8
1,602
2.671875
3
[]
no_license
require 'rails_helper' describe Assessment do it "is valid with a title." do assessment = Assessment.new(title: "Beer Assessment") expect(assessment).to be_valid end it "is invalid without a title" do assessment = Assessment.new(title: nil) assessment.valid? expect(assessment.errors[:title]).to include ("can't be blank") end it "returns a list of questions" do assessment = Assessment.new(title: "Wine Knowledge") assessment.save question_one = assessment.questions.new(prompt: "What is the best wine?", answer: "Pinot Grigio") question_one.save expect(assessment.questions.length).to eq(1) expect(assessment.questions.first).to eq(question_one) question_two = assessment.questions.new(prompt: "What is the worst wine?", answer: "reisling") question_two.save expect(assessment.questions.length).to eq(2) expect(assessment.questions.last).to eq(question_two) assessment.destroy question_one.destroy question_two.destroy end it "returns a list of tasters who have taken it" do assessment = Assessment.new(title: "Why do people drink 4loko?") assessment.save user = User.new(username: "shea", password: "password") user.save taster = Taster.new(user_id: user.id, real_name: "shea") taster.save user.update_attributes(usable: taster) taster_assessment = TasterAssessment.new(taster_id: taster.id, assessment_id: assessment.id) taster_assessment.save expect(assessment.tasters.first).to eq(taster) expect(assessment.tasters.length).to eq(1) taster.destroy user.destroy taster_assessment.destroy assessment.destroy end end
true
6d635f67b0205ae300e3172a66405f3a88f679b0
Ruby
timeout/cite_convert
/lib/cite_convert/article/expand.rb
UTF-8
971
3.046875
3
[]
no_license
module CiteConvert module Article class Expand def initialize(array) @array = array end attr_reader :array def blow_up while self.contains_range? index = self.range_symbol_index replace = expand_range(self.array.at(index - 1), self.array.at(index + 1)) self.array[index] = replace self.array.delete_at(index - 1) self.array.delete_at(index) self.array.flatten! end self.array.delete_if{ |entry| entry =~ /\A *, *\Z/ } self.array end def contains_range? self.array.include? '-' or self.array.include? '-' or self.array.include? '–' or self.array.include? '—' end def expand_range(start, finish) Array(start..finish) end def range_symbol_index self.array.each_with_index { |entry, index| return index if ['-','–','—', '-'].include? entry } end end end end
true
2d34512c3b6dee600da8cb2202337340671c0043
Ruby
ngenator/werewolf
/bin/script/full_game.rb
UTF-8
1,670
2.546875
3
[ "MIT" ]
permissive
#paste into 'bundle exec bin/console' session SlackRubyBot::Client.logger.level = Logger::INFO game = Werewolf::Game.instance slackbot = Werewolf::SlackBot.new(token: ENV['SLACK_API_TOKEN'], aliases: ['fangbot']) game.add_observer(slackbot) slackbot.start_async sleep 2 seer = Werewolf::Player.new(:name => 'bill', :bot => true) wolf = Werewolf::Player.new(:name => 'tom', :bot => true) beholder = Werewolf::Player.new(:name => 'seth', :bot => true) villager2 = Werewolf::Player.new(:name => 'john', :bot => true) villager3 = Werewolf::Player.new(:name => 'monty', :bot => true) game.join(seer) game.join(wolf) game.join(beholder) game.join(villager2) game.join(villager3) # start 5 player game game.start('seer') # reassign roles seer.role = 'seer' wolf.role = 'wolf' beholder.role = 'beholder' villager2.role = 'villager' villager3.role = 'cultist' # Night 0 seer.view(beholder) game.advance_time # Day 1 game.vote(voter_name: 'bill', candidate_name: 'john') game.vote(voter_name: 'tom', candidate_name: 'john') game.vote(voter_name: 'seth', candidate_name: 'bill') game.vote(voter_name: 'john', candidate_name: 'tom') #villager3 doesn't vote game.vote_tally game.status # Night 1 game.advance_time game.players['john'].dead? seer.view(wolf) game.nightkill(werewolf: 'tom', victim: 'monty') game.players['monty'].dead? game.status # Day 2 game.advance_time game.players['monty'].dead? game.vote(voter_name: 'bill', candidate_name: 'tom') game.vote(voter_name: 'tom', candidate_name: 'bill') game.vote(voter_name: 'seth', candidate_name: 'tom') game.vote_tally game.status # Game over game.advance_time game.status game.players['tom'].dead? game.winner
true
138abbe7a5bc479f670cd2ca18c080a21ce4a695
Ruby
hcmarchezi/ruby_bank_account_system
/bank_account_system/test/use_cases/current_balance_use_case_test.rb
UTF-8
888
2.5625
3
[]
no_license
require 'test_helper' class CurrentBalanceUseCaseTest < ActiveSupport::TestCase test "check current balance from a bank account" do account_id = FactoryGirl.create(:account, balance: 100, user: FactoryGirl.create(:user)).id current_balance_use_case = CurrentBalanceUseCase.new(account_id: account_id) assert current_balance_use_case.execute == 100 end test "check current balance from inexistent bank account raises an error" do current_balance_use_case = CurrentBalanceUseCase.new(account_id: 99999) assert_raises(InexistentAccountError) { current_balance_use_case.execute } end test "check current balance from nil bank account id raises an error" do current_balance_use_case = CurrentBalanceUseCase.new(account_id: nil) assert_raises(InexistentAccountError) { current_balance_use_case.execute } end end
true
d6a698db2f4d3375a5eb6e7c2b8170eb35b20391
Ruby
TGOlson/rpn
/spec/to_i_spec.rb
UTF-8
1,017
3.453125
3
[]
no_license
require_relative 'spec_helper' assert 'it can handle an empty string' do # nil converts to 0, same as Ruby #to_i method RPNCalculator.to_i('') == 0 end assert 'it can handle a number less than ten' do RPNCalculator.to_i('1') == 1 end assert 'it can handle a number less than 100' do RPNCalculator.to_i('67') == 67 end assert 'it can handle a large number' do RPNCalculator.to_i('6234037') == 6234037 end assert 'it can handle a single digit negative number' do RPNCalculator.to_i('-9') == -9 end assert 'it can handle a large negative number' do RPNCalculator.to_i('-1204916191') == -1204916191 end assert 'it returns the same integer if an integer is passed in' do RPNCalculator.to_i(135) == 135 end assert_thrown 'it returns an error for decimals' do RPNCalculator.to_i('12.0') end assert_thrown 'it returns an error for other illegal chars' do RPNCalculator.to_i('1345aba') end assert_thrown 'it should handle a nested negative sign with an error' do RPNCalculator.to_i('13-5') end
true
f279512f31cd2d174216c1ade749c1458ff2946d
Ruby
mozamimy/toolbox
/ruby/list_on_demand_ec2_instances/list.rb
UTF-8
1,485
2.65625
3
[ "CC0-1.0" ]
permissive
require 'aws-sdk-ec2' NORMALIZATION_FACTORS = { 'nano' => 0.25, 'micro' => 0.5, 'small' => 1.0, 'medium' => 2.0, 'large' => 4.0, 'xlarge' => 8.0, '2xlarge' => 16.0, '3xlarge' => 24.0, '4xlarge' => 32.0, '6xlarge' => 48.0, '8xlarge' => 64.0, '9xlarge' => 72.0, '10xlarge' => 80.0, '12xlarge' => 96.0, '16xlarge' => 128.0, '18xlarge' => 144.0, '24xlarge' => 192.0, '32xlarge' => 256.0, } instance_family = ARGV[0] # like m4, t3, etc ec2 = Aws::EC2::Client.new instances = ec2.describe_instances( filters: [ { name: 'instance-type', values: ["#{instance_family}.*"], }, { name: 'instance-state-name', values: ['running'], }, ], ).flat_map(&:reservations).flat_map(&:instances).select { |i| # XXX: Cannot filter by null value in DescribeInstances API i.instance_lifecycle.nil? } instances.each do |i| printf "%-30s | %-30s | %-10s\n", i.instance_id, i.tags.find { |t| t.key == 'Name' }&.value, i.instance_type end normalized_total_quantity = instances.reduce(0) do |acc, i| instance_size = i.instance_type.match(/^.+\.(.+)$/)[1] acc += NORMALIZATION_FACTORS[instance_size] end puts "\nTotal instance count: #{instances.count}" puts "Normalized total count: #{normalized_total_quantity}" puts " as #{instance_family}.small #{normalized_total_quantity / NORMALIZATION_FACTORS['small']}" puts " as #{instance_family}.large #{normalized_total_quantity / NORMALIZATION_FACTORS['large']}"
true
83194e72689ca16f0817d8ff50e278ccf0c7ad00
Ruby
xunma/livecodes-batch-666
/price-is-right/price.rb
UTF-8
1,018
4.75
5
[]
no_license
# Write a game where the player has to guess a random price between 1 and 100 chosen by the program. The program should keep asking until the player guesses the right price. When the guess is right, the program displays how many guesses it took the player to win. # pseudo-code # program picks a random number from 1 to 100 number = rand(1..100) user = nil counter = 0 # ask the user for another input until the guess is correct while user != number puts 'Choose a number between 1-100:' # ask the user for the user's guess # user will input their guess user = gets.chomp.to_i # compare the user's guess to the computer picked number # tell the user if this number is too big or too small if user == number puts ' you got it' elsif user > number puts 'too high' else puts 'too low' end counter += 1 end # when the guess is corrent, let the user know how many guesses they have taken, and what the right answer is puts "the answer is #{number} and it took you #{counter} tries."
true
274d9d13fb24f86e4c99695def0015600e4793ce
Ruby
igorsimdyanov/gb
/part1/lesson7/d.smolsky/6_2.rb
UTF-8
148
3.28125
3
[]
no_license
# frozen_string_literal: true print 'Input nuber:' input = gets if (input.to_f % 2).zero? puts 'Четное' else puts 'Нечетное' end
true
41e83a86ae362ad00292d47b109c20303228ea3d
Ruby
s-shimko/ruby_learn2
/lesson4/task4_5/check_variables.rb
UTF-8
171
2.640625
3
[]
no_license
require_relative 'be_class' a = 100 be = BeClass.new(10) puts "Переменная 'a': #{defined?(a)}" be.check_var puts "Переменная '@b': #{defined?(@b)}"
true
388cf903d1a821808cab2ef71c57e459958f5ddc
Ruby
cmaher92/launch_school
/coursework/rb120/lesson_4/hard_1/question1.rb
UTF-8
1,090
3.421875
3
[]
no_license
# Question 1 # Alyssa has been assigned a task of modifying a class that was initially created # to keep track of secret information. The new requirement calls for adding logging, # when clients of the class attempt to access the secret data. # Here is the class in its current form: class SecretFile def initialize(secret_data, logger) @data = secret_data @logger = logger end def data @security_logger.create_log_entry @data end end # She needs to modify it so that any access to data must result in a log entry being # generated. That is, any call to the class which will result in data being returned #must first call a logging class. #The logging class has been supplied to Alyssa and looks like the following: class SecurityLogger def create_log_entry # ... implementation omitted ... end end # Hint: Assume that you can modify the initialize method in SecretFile to # have an instance of SecurityLogger be passed in as an additional argument. # It may be helpful to review the lecture on collaborator objects for this # practice problem.
true
218c4f8b9c6944ecd4e4837a13f442e8fe68c549
Ruby
DMendez49/Lunch_Lady
/day2.rb
UTF-8
3,244
4.40625
4
[]
no_license
#we have access to pry commands # example require "pry" # @contacts = ["spancer", "Thomas"] #binding.pry used to check code #on were you think there is a problem #this is how to create a class class Person attr_accessor :name, :age #initialize method is being called first def initialize(name, age) #two instance variables inside method of class @name = name @age = age end #new method inside of the Person class def increase_age(number) #@age = @age + number // does the same as line 20 @age += number end end #calling a class / jack is the instance of the class jack = Person.new("jack", 27) jack.increase_age(5) # using the increased age varible to the instance variable # new instance David = Person.new("david", 24) # new instance Amber = Person.new("amber", 22) #new class class Dog attr_accessor :name, :breed def initialize(name, breed) @name = name @breed = breed end #instance method$$$$$$$$$$$$$$$$$$$$$$$ def info puts "#{@name} is of breed #{@breed}" end #Class Method$$$$$$$$$$$$$$$$$$$$$$$$$ def self.bark puts "WOOF!" end end walter_the_dog = Dog.new("Walter", "German sheperd") walter_the_dog.info Dog.bark class Parent def use_parent_method puts "this was called from the parent" end def overide puts "this was called from the parent" end def alterable puts "this was also called from the parent" end end #child is inhareting the use_parent method class Child < Parent def overide puts "theis was called from the child" end def alterable super()# calls the method of the opposite class puts "I am the child bitch" puts "here are some more details" end end p = Parent.new c = Child.new #plug in the methods p.alterable c.alterable #new example class Mammal attr_accessor :name, :age def initialize(name, age) @name = name @name = age end def breath puts "inhale and exhale" end def speak raise "You must ovverride this method in the sub class" end end class Cat < Mammal def initialize(name, age) super(name, age) @name = name @age = age end def speak puts "Meow" end end Fishy = Mammal.new("Fishy", 40) Gato = Cat.new("cat", 50) Fishy.breath Gato.speak #new Example class App def initialize # App starts here @person = init_person puts "welcome #{@person.name}" #Continue the app end #Private - cant call methods outside of the class private def init_person puts "Enter your name:" puts ">" name = gets.strip puts "what is your age?" puts ">" age = gets.to_i Person.new(name, age) end end class Person attr_accessor :name, :age def initialize(name, age) @name = name @age = age end end a = App.new # a.init_person #classes you can creat instences of the class and you cant with modules #Module # module Math # def add(num1, num2) # num1 + num2 # end # def subtract(num1, num2) # num1 - num2 # end # end # class MathAssignment # include Math # def first_solution # add(10,50) + subtract(3,10) # end # end # assignment = MathAssignment.new # puts assingment.first_solution
true
100381cd3c0653ef1268e02f37d78625003b9970
Ruby
urayoshie/array_practice
/array.rb
UTF-8
339
3.453125
3
[]
no_license
languages = ["Ruby", "PHP", "Java"] puts "様々な言語のHello World" puts "" languages.each do |language| case language when "Ruby" puts "#{language} :" + ' puts "Hello World!"' when "PHP" puts "#{language} :" + ' echo "Hello World!";' when "Java" puts "#{language} :" + ' System.out.println("Hello World!");' end end
true
3ec65b6ea8f157fd0e127b754a8650c424ba46b2
Ruby
souljuse/makersacademy-oop-workshop
/lib/student.rb
UTF-8
450
3.453125
3
[]
no_license
class Student attr_reader :first_name, :last_name, :date_of_birth, :height def initialize(data) #I espect a hash to be passed so data is the hash @first_name = data['first_name'] @last_name = data['last_name'] @date_of_birth = Date.parse(data['date_of_birth']) @height = data['height'] end def year_of_birth date_of_birth.year end def full_name(first_name, last_name) "#{first_name} #{last_name}" end end
true
e03d1352be17f3895f7cfdb558997fd8c8414c87
Ruby
Takashi-Na/ruby-drill
/drill-14.rb
UTF-8
189
3.375
3
[]
no_license
def police_trouble(a, b) if (a && b) || (!a && !b) puts "true" else puts "false" end end #容疑者a,bの証言の真偽を決める a = false b = false police_trouble(a, b)
true
23b03d3dffdcb5dabd6e242e5e0b8c62ae7825b7
Ruby
GBouffard/rps-first-attempt
/spec/player_spec.rb
UTF-8
401
3
3
[]
no_license
require 'player' describe Player do let(:player) { described_class.new('Guillaume') } it 'has a name' do expect(player.name).to eq 'Guillaume' end it 'can choose a hand' do expect(player.chose_hand('Rock')).to eq 'Rock' end it 'can only choose a hand that is Rock, Paper or Scissors' do expect { player.chose_hand('yo') } .to raise_error 'This is not a RPS hand!' end end
true
20d00c3d41ec5854117ad20175a4f74671b05bf5
Ruby
jlambert121/evenup-ct2ls
/files/ct2ls.rb
UTF-8
3,939
2.59375
3
[ "Apache-2.0" ]
permissive
#/usr/bin/env ruby require 'rubygems' require 'logger' require 'json' require 'aws-sdk' require 'zlib' require 'redis' require "daemons" require "yaml" class Cloudtrail2Logstash def initialize config # Set up logging @log = Logger.new("#{config[:logpath]}/ct2ls_log.json", 'weekly') @log.level = Logger.const_get config[:loglevel] @log.progname = 'cloudtrail2logstash' @log.formatter = proc do |serverity, time, progname, msg| message = { :serverity => serverity, :time => time, :progname => progname, :message => msg}.to_json "#{message}\n" end # Set up AWS AWS.config(:access_key_id => config[:access_key_id], :secret_access_key => config[:secret_access_key], :region => config[:region]) @queue = AWS::SQS.new.queues.named(config[:sqs_queue]) @s3 = AWS::S3.new # Set up redis @redis = Redis.new(:host => config[:redis_host], :port => config[:redis_port], :db => config[:redis_db]) # Local temp file @local_file = "#{config[:tmp_path]}/cloudtrail_tmp.gz" @remove_original = config[:remove_original] @redis_list = config[:redis_list] end def run # Constant SQS poll @log.info "Waiting for a message...\n" @queue.poll(:batch_size => 1, :wait_time_seconds => 20) do |orig_msg| @log.info "Message #{orig_msg.id} recieved" msg = JSON.parse(orig_msg.body) message = JSON.parse(msg['Message']) bucket = @s3.buckets[message['s3Bucket']] message['s3ObjectKey'].each do |key| @log.debug "fetching #{message['s3Bucket']}:#{key}" obj = bucket.objects[key] # Fetch the file from S3 begin File.open(@local_file, 'wb') do |file| obj.read do |chunk| file.write(chunk) end end rescue => e @log.error "There was an error fetching the file from S3" @log.error "#{e.message} #{e.class}" @log.error e.backtrace.join("\n") exit end # Read cloudtrail file file = File.open(@local_file, mode='r') file_stream = Zlib::GzipReader.new(file) file_stream.each_line do |line| begin records = JSON.parse(line) rescue => e @log.error "Line '#{line}' is not valid JSON" @log.error "#{e.message} #{e.class}" @log.error e.backtrace.join("\n") exit end records['Records'].each do |record| record['type'] = 'cloudtrail' record['@version'] = 1 record['@timestamp'] = record.delete('eventTime') begin @log.debug "pushing #{record.to_json} to redis" @redis.lpush(@redis_list, record.to_json) rescue => e @log.error "There was a problem pushing to redis" @log.error "#{e.message} #{e.class}" @log.error e.backtrace.join("\n") exit end end end file.close # Clean up local file @log.debug "Cleaning up #{@local_file}" File.delete(@local_file) # Remove original from S3 @log.debug "Cleaning up #{message['s3Bucket']}:#{key}" if @remove_original obj.delete if @remove_original end @log.info "Waiting for a message...\n" end end end # Read config cfg_file = '/etc/ct2ls.yaml' if File.exist?(cfg_file) begin config = YAML.load_file(cfg_file) rescue puts "#{cfg_file} is not valid YAML" exit else puts "Loading config from #{cfg_file}" end else puts "#{cfg_file} not found" exit end daemon_options = { :multiple => false, :dir_mode => :normal, :dir => '/var/run/ct2ls/', :backtrace => true } Daemons.run_proc("ct2ls", daemon_options) do if ARGV.include?("--") ARGV.slice! 0..ARGV.index("--") else ARGV.clear end Cloudtrail2Logstash.new(config).run end
true
db5b527ff76bf628dee2058eb0e6ea7e0203c960
Ruby
Gudarien/WIP-Gudarien
/loops1c.rb
UTF-8
64
3.125
3
[]
no_license
number = 7 10.times do puts number number = number + 1 end
true
e196d538950bd47221b6013f7a01aaabf64ac185
Ruby
ElyKar/Tools
/Ruby/basic/linked_deque.rb
UTF-8
2,896
4.4375
4
[ "MIT" ]
permissive
# LinkedDeque represents a dequeue using a doubly-linked list. # # It supports the add-first, add-last, remove-first, and remove-last operations. # # Iteration via each is done from first element to the last. # # Author:: Tristan Claverie # License:: MIT class LinkedDeque include Enumerable # Size of the deque attr_reader :size # Initialize an empty deque def initialize @size = 0 @head = nil @tail = nil end # Add an element at the head of the deque def add_first(elt) @head = Node.new(elt, @head, nil) if @size == 0 @tail = @head else @head.next.previous = @head end @size += 1 end # Add an element at the end of the deque def add_last(elt) @tail = Node.new(elt, nil, @tail) if @size == 0 @head = @tail else @tail.previous.next = @tail end @size += 1 end # Remove the node at the end of the list and returns its value def remove_last raise 'No such element' if @size == 0 elt = @tail.value if @size == 1 @head = nil @tail = nil else @tail = @tail.previous @tail.next.previous = nil @tail.next = nil end @size -= 1 return elt end # Remove the node at the head of the list and returns its value def remove_first raise 'No such element' if @size == 0 elt = @head.value if @size == 1 @head = nil @tail = nil else @head = @head.next @head.previous.next = nil @head.previous = nil end @size -= 1 return elt end # Return the first element without removing it def peek_first raise 'No such element' if @size == 0 @head.value end # Return the last element without removing it def peek_last raise 'No such element' if @size == 0 @tail.value end # Is the deque empty ? def empty? @size == 0 end # Iterate through the elements from first to last def each current = @head while current != nil yield current.value current = current.next end end private # The Node class represents a doubly linked node. # # It holds one link for the previous Node and one for the next. # # Author:: Tristan Claverie # License:: MIT class Node # Value contained in the node attr_accessor :value # Next node attr_accessor :next # Previous node attr_accessor :previous # Initialize a node with value v, previous p and next n def initialize(v, n, p) @value = v @next = n @previous = p end end end
true
ed92bafdbab4ad63a12871d5e85d71e43f4b8ef0
Ruby
ryancalhoun/just-keep-zipping
/spec/just_keep_zipping_spec.rb
UTF-8
2,966
2.71875
3
[ "MIT" ]
permissive
require 'rspec' require 'tempfile' require 'zip' require 'just-keep-zipping' describe JustKeepZipping do it 'adds a file as a string' do subject.add 'file', 'this is a string to be zipped' expect(subject.entries.size).to be == 1 expect(subject.entries.first.name).to be == 'file' expect(subject.current_size).to be > subject.entries.first.compressed_size end it 'adds a file as an IO' do subject.add 'file', StringIO.new('this is a string to be zipped') expect(subject.entries.size).to be == 1 expect(subject.entries.first.name).to be == 'file' expect(subject.current_size).to be > subject.entries.first.compressed_size end it 'can be marshalled' do subject.add 'file', 'this is a string to be zipped' new_instance = Marshal.load Marshal.dump subject expect(new_instance.entries.size).to be == 1 expect(new_instance.entries.first.name).to be == 'file' end it 'can be read' do subject.add 'file', 'this is a string to be zipped' data = subject.read expect(subject.entries.size).to be == 1 expect(subject.entries.first.name).to be == 'file' expect(subject.current_size).to be == 0 expect(data.encoding.name).to be == 'ASCII-8BIT' expect(data.size).to be > subject.entries.first.compressed_size end it 'can be added to' do subject.add 'file', 'this is a string to be zipped' data = subject.read subject.add 'file2', 'this is another string to be zipped' expect(subject.entries.size).to be == 2 expect(subject.entries.first.name).to be == 'file' expect(subject.entries.last.name).to be == 'file2' expect(subject.current_size).to be > subject.entries.last.compressed_size data2 = subject.read expect(data).to_not eq data2 end it 'can be closed and read' do subject.add 'file', 'this is a string to be zipped' data = subject.read subject.close zip_header = subject.read Tempfile.open('zip') do |f| f.write data f.write zip_header f.rewind Zip::InputStream.open(f.path) do |io| e = io.get_next_entry expect(e.name).to be == 'file' expect(io.read).to be == 'this is a string to be zipped' end end end it 'can be closed and read and assembled' do subject.add 'file', 'this is a string to be zipped' data1 = subject.read new_instance = Marshal.load Marshal.dump subject new_instance.add 'file2', 'this is another string to be zipped' new_instance.close data2 = new_instance.read Tempfile.open('zip') do |f| f.write data1 f.write data2 f.rewind Zip::InputStream.open(f.path) do |io| e = io.get_next_entry expect(e.name).to be == 'file' expect(io.read).to be == 'this is a string to be zipped' e = io.get_next_entry expect(e.name).to be == 'file2' expect(io.read).to be == 'this is another string to be zipped' end end end end
true
3d11111ff87dd5b891975e302ba208cdc2079f7b
Ruby
jgaskins/perpetuity-postgres
/spec/perpetuity/postgres/table_spec.rb
UTF-8
2,085
2.609375
3
[ "MIT" ]
permissive
require 'perpetuity/postgres/table' require 'perpetuity/postgres/table/attribute' module Perpetuity class Postgres describe Table do let(:title) { Table::Attribute.new('title', String, max_length: 40) } let(:body) { Table::Attribute.new('body', String) } let(:author) { Table::Attribute.new('author', Object) } let(:published_at) { Table::Attribute.new('published_at', Time) } let(:views) { Table::Attribute.new('views', Integer) } let(:attributes) { [title, body, author, published_at, views] } let(:table) { Table.new('Article', attributes) } it 'knows its name' do expect(table.name).to be == 'Article' end it 'knows its attributes' do expect(table.attributes).to be == attributes end it 'converts to a string for SQL' do expect(table.to_s).to be == '"Article"' end it 'generates proper SQL to create itself' do expect(table.create_table_sql).to be == 'CREATE TABLE IF NOT EXISTS "Article" (id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), title TEXT, body TEXT, author JSON, published_at TIMESTAMPTZ, views BIGINT)' end it 'sets the id as PRIMARY KEY even if specified in attributes' do attributes = self.attributes.dup attributes.unshift Table::Attribute.new(:id, String) table = Table.new('Article', attributes) expect(table.create_table_sql).to be == 'CREATE TABLE IF NOT EXISTS "Article" (id TEXT PRIMARY KEY, title TEXT, body TEXT, author JSON, published_at TIMESTAMPTZ, views BIGINT)' end describe 'id column' do context 'when there is an id attribute' do it 'uses the attribute type for the column type' do attributes = [Table::Attribute.new(:id, String, primary_key: true), Table::Attribute.new(:name, String)] table = Table.new('User', attributes) expect(table.create_table_sql).to be == 'CREATE TABLE IF NOT EXISTS "User" (id TEXT PRIMARY KEY, name TEXT)' end end end end end end
true
4cce93aae7bf1db842ab595416b39d28ae5fdfa5
Ruby
asheidan/Greed
/src/lib/rules/ones_and_fives_rule.rb
UTF-8
415
3.6875
4
[]
no_license
module Rules # Implements a rule which gives 100 points for each 1 and # 50 points for each 5. class OnesAndFivesRule def apply(dice) points = 0 rethrow = dice.select do |die| if die == 1 points += 100 false elsif die == 5 points += 50 false else true end end return points,rethrow end end end
true