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
2d0a3b85b53fe3369c701b48babfcb1f385d7796
Ruby
Hyftar/Yellow-Pages-Addresses-Scraper
/main.rb
UTF-8
1,765
2.875
3
[]
no_license
require 'http' require 'nokogiri' require 'parallel' require 'json' require 'byebug' def get_max_page(uri) content = HTTP.get(uri).to_s Nokogiri::HTML(content).css('.pageCount > span:nth-child(2)').text.to_i end PROVINCES = [ 'Manitoba+MB', 'Alberta+AB', 'Saskatchewan+SK', 'British+Columbia+BC', 'Ontario+ON' ] uris = Enumerator.new do |yielder| PROVINCES.each do |province| max_page = get_max_page("https://www.yellowpages.ca/search/si/1/pharmacy/#{province}") (1..max_page).each do |page| yielder << URI("https://www.yellowpages.ca/search/si/#{page}/pharmacy/#{province}") end max_page = get_max_page("https://www.yellowpages.ca/search/si/1/police/#{province}") (1..max_page).each do |page| yielder << URI("https://www.yellowpages.ca/search/si/#{page}/police/#{province}") end max_page = get_max_page("https://www.yellowpages.ca/search/si/1/tim+hortons/#{province}") (1..max_page).each do |page| yielder << URI("https://www.yellowpages.ca/search/si/#{page}/tim+hortons/#{province}") end end end results = Parallel.map(uris, progress: 'Crawling Yellow Pages', ) do |uri| content = HTTP.get(uri).to_s next if content.include?('We didn’t find any business listings matching') addresses = Nokogiri::HTML(content) .css('[itemprop="address"]') .map do |e| { StreetAddress: e.css('[itemprop="streetAddress"]').text, AddressRegion: e.css('[itemprop="addressRegion"]').text, AddressLocality: e.css('[itemprop="addressLocality"]').text, PostalCode: e.css('[itemprop="postalCode"]').text } end end File.open('bc+ab+sk+mb+on.json', 'a') do |io| io.puts({ results: results.flatten.compact }.to_json) end
true
aa5d1610512f9eb006391d80d61efa26048d7bd6
Ruby
ismith/elevator_alerts
/authy.rb
UTF-8
1,456
2.765625
3
[ "MIT" ]
permissive
require 'faraday' require 'json' class Authy START_ENDPOINT = "https://api.authy.com/protected/json/phones/verification/start".freeze VERIFY_ENDPOINT = "https://api.authy.com/protected/json/phones/verification/check".freeze def self.submit_number(number) # Running locally, we may not care about actually verifying return true unless ENV['AUTHY_API_KEY'] connection = Faraday.new(:url => START_ENDPOINT) raw_resp = connection.post do |req| req.headers['Content-Type'] = 'application/json' req.body = { :api_key => ENV['AUTHY_API_KEY'], :via => 'sms', :country_code => 1, :phone_number => number, :locale => 'en' }.to_json end resp = JSON.parse(raw_resp.body) unless resp['success'] puts "Authy submit error: #{resp}" end return resp['success'] end def self.verify_number(number, verification_code) # Running locally, we may not care about actually verifying return true unless ENV['AUTHY_API_KEY'] connection = Faraday.new(:url => VERIFY_ENDPOINT) raw_resp = connection.get do |req| req.body = { :api_key => ENV['AUTHY_API_KEY'], :phone_number => number, :country_code => 1, :verification_code => verification_code } end case raw_resp.status when 200 return true else puts "Authy verify error: #{raw_resp.body}" return false end end end
true
c907343f17aead8ba92963cf6bacef2fa24e9b7a
Ruby
mostafahussein/complaint-system
/lib/tasks/sample_data.rake
UTF-8
3,725
2.546875
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
namespace :db do desc 'Fill database with sample data' task populate: :environment do Faker::Config.locale = :en make_employees_and_students # make_employees_and_students_as_users # attended_subjects # assign_advisors_to_subjects # make_complaints end end def make_employees_and_students puts "Making Employees and Students" 120.times do full_name = Faker::Name.name gender = ["female" , "male"] Staff.create!([{full_name: full_name, gender: gender.sample, employee_department_id: 1, employee_position_id: 2}]) full_name = Faker::Name.name gender = ["female" , "male"] Advisor.create!([{full_name: full_name, gender: gender.sample, employee_department_id: 2, employee_position_id: 3}]) full_name = Faker::Name.name gender = ["female" , "male"] Student.create!([{full_name: full_name, gender: gender.sample, batch_id: 1, section_id: 1}]) full_name = Faker::Name.name gender = ["female" , "male"] Student.create!([{full_name: full_name, gender: gender.sample, batch_id: 1, section_id: 1}]) full_name = Faker::Name.name gender = ["female" , "male"] Student.create!([{full_name: full_name, gender: gender.sample, batch_id: 2, section_id: 1}]) full_name = Faker::Name.name gender = ["female" , "male"] Student.create!([{full_name: full_name, gender: gender.sample, batch_id: 2, section_id: 1}]) end end def make_employees_and_students_as_users puts "Making Employees and Students as Users" employees = Employee.all employees.each do |employee| User.create! do |user| user.email = "employee#{employee.id}@swe.com" user.password = '12345678' user.password_confirmation = '12345678' user.user_type = 'employee' if (employee.employee_department.department_name == "software engineering" && employee.employee_position.position_title == "head of department") user.role = 'head of department' elsif (employee.employee_department.department_name == "software engineering" && employee.employee_position.position_title == "staff") user.role = "staff" elsif (employee.employee_department.department_name == "student advisor" && employee.employee_position.position_title == "advisor") user.role = "advisor" end end user_id = User.last.id employee.update_attributes(user_id: user_id) end students = Student.all students.each do |student| User.create! do |user| user.email = "student#{student.id}@swe.com" user.password = '12345678' user.password_confirmation = '12345678' user.user_type = 'student' user.role = "student" end user_id = User.last.id student.update_attributes(user_id: user_id) end end def attended_subjects 5.times do students = Student.all(limit: 100, order: "RANDOM()") subjects = Subject.all students.each do |student| subjects.each do |subject| if Attend.where(student_id: student.id, subject_id: subject.id).exists? == false Attend.create!([{student_id: student.id, subject_id: subject.id}]) end end end end end def assign_advisors_to_subjects 5.times do advisor = Advisor.first(order: "RANDOM()") subjects = Subject.all(limit: 3, order: "RANDOM()") subjects.each do |subject| if subject.employee == nil subject.update_attributes!(employee_id: advisor.id) end end end end def make_complaints 50.times do studnets = Student.all(limit: 10, order: "RANDOM()") title = Faker::Lorem.sentence(1).chomp('.') description = Faker::Lorem.paragraphs(rand(2..8)).join('') studnets.each { |student| student.tickets.create!(title: title, description: description) } end end
true
817318f8cca5844b8d03a73591e45c6a3b4bf84e
Ruby
arunjax/vim_diff
/lib/vim_diff.rb
UTF-8
682
2.578125
3
[]
no_license
require 'installer.rb' module VimDiff class Generator attr_accessor :left_file_path attr_accessor :right_file_path attr_accessor :html_diff_path def initialize(left_file_path, right_file_path, html_diff_path) self.left_file_path = left_file_path self.right_file_path = right_file_path self.html_diff_path = html_diff_path end def generate command = ("nohup vimdiff #{self.left_file_path} #{self.right_file_path} -c TOhtml -c 'w! #{self.html_diff_path}' -c 'qa!'") say `#{command}` say "Generated file to #{self.html_diff_path}" end private def say(message) puts message end end end
true
618707e0e78d5f08715d794acef5b8cfe66d37a6
Ruby
marylenec/my-select-houston-web-071618
/lib/my_select.rb
UTF-8
370
3.59375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
nums = [1, 2, 3, 4, 5] empty_array = [] def my_select(collection) i = 0 new_collection = [] while i < collection.length # do something if yield(collection[i]) new_collection << collection[i] end # add to i each time through the loop i = i + 1 end # return new array new_collection end my_select(nums) do | num | num.even? end
true
17f553bc68fb3ee766972e684541733733b5d102
Ruby
owlworks/solvers_solver
/building.rb
UTF-8
995
2.734375
3
[]
no_license
require 'yaml' class BuildingManager attr_reader :list_buildings def initialize @list_buildings = YAML.load(File.open("./building_data.yml")) end def enumerate_available(company) list_available = [] company_outlay = company.outlay company_research = company.research @list_buildings.each do |building| next if building.research > company_research next if building.outlay + company_outlay > company.honor next if building.name == "barrack" list_available << building end (company.list_buildings || []).each do |owned| break if owned.nil? list_available.delete_if { |ava| ava.name == owned.name } end list_available end def search_by_name(name) result = nil @list_buildings.each do |building| result = building if building.name == name end result end end class Building attr_reader :name, :outlay, :antipathy, :limit, :research def enable_labo_to_build @research = 20 end end
true
392ba071b5d98dca5f8fdbb542c77dcc4002e59e
Ruby
trivedib/ruby-modular-mono
/engines/core-dal/app/api/core/dal/address_repo.rb
UTF-8
2,202
2.671875
3
[ "MIT" ]
permissive
# frozen_string_literal: true module Core module Dal # Repository object that provides CRUD and other DB operations on Address domain model. class AddressRepo class << self # method to create a new address instance into DB def create(entity) identity = Core::Dal::Address.create(entity.to_json) # puts "no of identities: #{Cim::Dal::Identity.count}" identity.id end # method to update an existing address instance from DB. def update(entity) return unless entity return unless entity.id address = Core::Dal::Address.find(entity.id) return unless address address.update(entity.to_json) address.save! entity.id end # method to fetch address instance from DB def get(id) return unless id address = Core::Dal::Address.find(id) address_dto = Amount::Types::AddressDto.new(address.uuid, address.address_1, address.address_2, address.city, address.state, address.zip) address_dto.id = id address_dto end # method to fetch address instance based on uuid def get_by_uuid(uuid) return unless uuid address = Core::Dal::Address.find_by(uuid: uuid) address_dto = Amount::Types::AddressDto.new(address.uuid, address.address_1, address.address_2, address.city, address.state, address.zip) address_dto.id = address.id address_dto end # method to get count def count Core::Dal::Address.count end end end end end
true
99296b9a13f3a8bdef45c2175e5b270d6af1b6b2
Ruby
GijuAmbrose/ruby-programs
/Threesum.rb
UTF-8
463
3.609375
4
[]
no_license
class Threesum def initialize (input,n) c = [] s = 2**n i = 0 arr = [] c = input.combination(3).to_a c.each do |ele| 3.times do |j| s += ele[i][j] puts s if s == 0 arr[i] = ele[i][j] end end end puts arr end end puts "Enter the limit:" n = gets.chomp.to_i input = [] puts "Enter the elements:" n.times do |i| input[i] = gets.chomp.to_i end Threesum.new(input,n)
true
4c99b773a4d34ca12f33f8e2a004a70b04470dab
Ruby
dalyc/smith2
/lib/smith/commands/smithctl/rm.rb
UTF-8
1,158
2.65625
3
[]
no_license
# -*- encoding: utf-8 -*- module Smith module Commands class Rm < Command def execute case target.size when 0 responder.value("No queue specified. Please specify a queue.") else target.each do |queue_name| Smith.channel.queue("smith.#{queue_name}", :passive => true) do |queue| queue_options = (options[:force]) ? {} : {:if_unused => true, :if_empty => true} queue.delete(queue_options) do |delete_ok| responder.value((options[:verbose]) ? delete_ok.message_count.to_s : nil) end end end end end def options_parser Trollop::Parser.new do banner Command.banner('remove-queue') opt :force, "force the removal even if there are messages on the queue", :short => :f opt :verbose, "print the number of messages deleted", :short => :v end end def format_output(message_count) if options[:verbose] responder.value("Queue deleted. #{message_count}s messages deleted.") end end end end end
true
11d7a2b6dea69dc3592c64828d0aa75d33e2d597
Ruby
ikwzm/rbvhdl
/lib/rbvhdl/ast/expression/shift_expression.rb
UTF-8
872
2.5625
3
[ "BSD-2-Clause" ]
permissive
module RbVHDL::Ast # # shift_expression : simple_expression # | simple_expression "sll" simple_expression # | simple_expression "srl" simple_expression # | simple_expression "sla" simple_expression # | simple_expression "sra" simple_expression # | simple_expression "rol" simple_expression # | simple_expression "ror" simple_expression # class Expression class ShiftExpression < Relation end end def self.shift_expression(expr) if expr.class < RbVHDL::Ast::Expression::ShiftExpression then return expr elsif expr.class < Numeric then return self.numeric_expression(expr) else raise ArgumentError, "#{self.inspect}.#{__method__}(#{expr.inspect}:#{expr.class})" end end end
true
7ee3777690e0a92b7e3f25c412dbfdb952b99003
Ruby
ewelinaszoda/ruby-enumerables-hash-practice-nyc-pigeon-organizer-lab-lon01-seng-ft-042020
/nyc_pigeon_organizer.rb
UTF-8
1,467
3.703125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def nyc_pigeon_organizer(data) pigeon_list = {} data.each do |key, values| values.each do |value, names_array| names_array.each do |name| pigeon_list[name] ||= {} pigeon_list[name][key] ||= [] pigeon_list[name][key] << value.to_s end end end pigeon_list end =begin Ruby's ||= (or equal) operator Ruby's ||= operator is a handy way to assign variables if they are not defined yet, but not change the variable if they are already defined. ... When a variable is already assigned to a value, the ||= operator will not reassign the value. =end #another solution =begin def nyc_pigeon_organizer(data) pigeon_list = {} data.each do |key, values| values.each do |value, names_array| names_array.each do |name| pigeon_list[name] = {:color => [], :gender => [], :lives => []} end end end data[:color].each do |value, names_array| names_array.each do |name| if data[:color][value].include?(name) pigeon_list[name][:color] << value.to_s end end end data[:gender].each do |value, names_array| names_array.each do |name| if data[:gender][value].include?(name) pigeon_list[name][:gender] << value.to_s end end end data[:lives].each do |value, names_array| names_array.each do |name| if data[:lives][value].include?(name) pigeon_list[name][:lives] << value end end end pigeon_list end =end
true
1a2a39d27d2558760caee8207dba41a9baf3e0a9
Ruby
resant18/AAClasswork
/W4D3/chess/pieces/king.rb
UTF-8
333
2.78125
3
[]
no_license
require_relative "module/stepable_module" require_relative "piece" class King < Piece include Stepable def symbol :K end def move_diffs [[1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1], [0, 1]] end end # board = Board.new # k = King.new(:W, board, [0, 3]) # p k.moves # p k.symbol # p k.move_dirs
true
1019cdebc2fd0a5182f442e35b85a58532e34ea2
Ruby
kurisu/abcrunch
/lib/abcrunch/tester.rb
UTF-8
2,191
2.546875
3
[ "MIT" ]
permissive
module AbCrunch module Tester def self.test(pages) results = [] pages.each do |page| passed, qps_result, errors = AbCrunch::PageTester.test(page) results << { :page => page, :passed => passed, :qps_result => qps_result, :errors => errors } end log_result_summary results passed = results.reduce(true) { |value, result| value && result[:passed] } if not passed errors = results.reduce('') do |value, result| page_set_errors = result[:errors].reduce('') do |val, error| "#{val}#{val.length > 0 ? "\n" : ''}#{error}" end "#{value}#{value.length > 0 ? "\n" : ''}#{page_set_errors}" end raise "Load tests FAILED\n#{errors}" end results end def self.log_result_summary(results) AbCrunch::Logger.log :summary_title, "Summary" AbCrunch::Logger.log :summary, "#{"Page".ljust(30, ' ')}#{"Response time".rjust(10, ' ')} #{"Concurrency".rjust(16, ' ')} #{"Queries/sec".rjust(12, ' ')}" results.each do |result| page_name = result[:page][:name].ljust(30, ' ') base_response_time = sprintf("%.2f", result[:qps_result].avg_response_time).rjust(10, ' ') max_concurrency = result[:qps_result].ab_options[:concurrency].to_s.rjust(16, ' ') queries_per_second = sprintf("%.2f", result[:qps_result].queries_per_second).rjust(12, ' ') if result[:passed] AbCrunch::Logger.log :summary_passed, "#{page_name}#{base_response_time} #{max_concurrency} #{queries_per_second}" else AbCrunch::Logger.log :summary_failed, "#{page_name}#{base_response_time} #{max_concurrency} #{queries_per_second}" end end AbCrunch::Logger.log :summary_title, "Legend" AbCrunch::Logger.log :summary, "Response Time = Best average response time (ms) at max concurrency" AbCrunch::Logger.log :summary, "Concurrency = Best concurrency where response time doesn't bust our performance threshold" AbCrunch::Logger.log :summary, "Queries/sec = Queries per second at best concurrency" results end end end
true
13fb81bba8b43a4ac806215d3753d25d1f2b6ca4
Ruby
xively/xively-rb
/lib/xively-rb/resource.rb
UTF-8
1,078
2.53125
3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
module Xively class Resource ALLOWED_KEYS = %w(feed_id datastream_id datastream_trigger_id) ALLOWED_KEYS.each { |key| attr_accessor(key.to_sym) } include Validations def valid? pass = true if feed_id.blank? && datastream_id.blank? && datastream_trigger_id.blank? errors[:feed_id] = "Must supply at least one of feed_id (optionally with a datastream_id) or datastream_trigger_id" pass = false end if feed_id.blank? && !datastream_id.blank? errors[:feed_id] = ["can't be blank if we have supplied a datastream_id"] pass = false end return pass end def initialize(input = {}) self.attributes = input end def attributes h = {} ALLOWED_KEYS.each do |key| value = self.send(key) h[key] = value unless value.nil? end return h end def attributes=(input) return if input.nil? input.deep_stringify_keys! ALLOWED_KEYS.each { |key| self.send("#{key}=", input[key]) } return attributes end end end
true
20866d8c652587ecbd36cb8ae9b7a6fcdabe2e59
Ruby
mmrobins/cookingcompendium
/test/unit/ingredient_test.rb
UTF-8
1,900
2.671875
3
[]
no_license
require 'test_helper' class IngredientTest < ActiveSupport::TestCase @@ingredient_default_values = { :recipe_id => 1, :food_id => 1, :quantity => 2.5, :units => "lbs", :percent_yield => 100, :prep_instructions => "chop finely", :position => "1" } def test_creating_ingredient_should_change_recipe_updated_at recipe = Recipe.find 1 original = recipe.updated_at ingredient = create after_create = recipe.reload.updated_at assert original < after_create end def test_update_ingredient_should_change_recipe_updated_at recipe = Recipe.find 1 original = recipe.updated_at ingredient = recipe.ingredients.first ingredient.save after_update = recipe.reload.updated_at assert original < after_update end def test_delete_ingredient_should_change_recipe_updated_at recipe = Recipe.find 1 original = recipe.updated_at ingredient = recipe.ingredients.first ingredient.destroy after_update = recipe.reload.updated_at assert original < after_update end def test_to_unit ingredient = create assert_equal ingredient.to_unit.units, ingredient.units end def test_quantity_to_food_purchase_units ingredient = create(:units => "g") assert_not_equal ingredient.units, ingredient.food.purchase_units assert_equal ingredient.quantity_to_food_purchase_units, (ingredient.to_unit >> ingredient.food.purchase_units).scalar end def test_cost ingredient = Ingredient.find(1) assert_equal ingredient.cost, ingredient.quantity_to_food_purchase_units * ingredient.food.cost_per_unit end def test_should_be_compitable_with_the_same_units_as_food ingredient = create assert_equal ingredient.compatible_units, ingredient.food.compatible_units end private def create(options = {}) Ingredient.create(@@ingredient_default_values.merge(options)) end end
true
667a6087aae832b9453d6379a80ee04777ce67fe
Ruby
jfinkhaeuser/unobtainium-cucumber
/features/step_definitions/action.rb
UTF-8
2,070
2.578125
3
[ "MITNFA" ]
permissive
# coding: utf-8 # # unobtainium-cucumber # https://github.com/jfinkhaeuser/unobtainium-cucumber # # Copyright (c) 2016-2017 Jens Finkhaeuser and other unobtainium-cucumber # contributors. All rights reserved. # require 'unobtainium-cucumber/action/screenshot' require 'unobtainium-cucumber/action/content' require_relative './mocks/scenario' Given(/^I take a screenshot$/) do ::Unobtainium::Cucumber::Action.store_screenshot( self, MockScenario.new('screenshots') ) end Then(/^I expect there to be a matching screenshot file$/) do # The expectation is that the file starts with an ISO8601 timestamp of today # and ends in 'screenshots.png'. The part we can't be certain about is the # exact time stamp, because seconds, minutes, etc. even years could have # rolled over between taking the screenshot and finding it. # So what we do instead is find files that match the end. If the start matches # the syntax of a timestamp string, we can convert it to a timestamp. Then we # can find out if between said timestamp and right now only a few seconds # elapsed. If we find one such file, the test succeeds. pattern = 'screenshots/*-screenshots.png' timeout_match_files(pattern) # *After* all checks, remove matching files. FileUtils.rm(Dir.glob(pattern)) end Given(/^I navigate to the best site in the world$/) do driver.navigate.to 'http://finkhaeuser.de' end When(/^I capture the page content$/) do # See the similar screnshot matching step for some details. ::Unobtainium::Cucumber::Action.store_content( self, MockScenario.new('contents') ) end Then(/^I expect there to be a matching content file$/) do # See the similar screnshot matching step for some details. pattern = 'content/*-contents.txt' match_file = timeout_match_files(pattern) # Check that some expected content exists. match = File.open(match_file).grep(/<html/) if match.empty? raise "File content of '#{match_file}' does not seem to be valid HTML!" end # *After* all checks, remove matching files. FileUtils.rm(Dir.glob(pattern)) end
true
e97038cdda551c1092ab8409662d42e87e6a3b7b
Ruby
Ami-tnk/rubybook
/chapter3/even_odd.rb
UTF-8
37
2.78125
3
[]
no_license
puts 2.even? puts 3.even? puts 3.odd?
true
c262b00c45c2ffc88aa347a1500054f1cb5d00fd
Ruby
dongho108/python-ruby
/Logical/1.rb
UTF-8
201
3.03125
3
[]
no_license
real_egoing = "egoing" real_k8805 = "k8805" puts("아이디를 입력해주세요") input = gets.chomp() if input == real_egoing or input == real_k8805 puts("Hello! ") else puts("who are you") end
true
65ef9f10b36cd6dbf0e857da6b518f5cc385903f
Ruby
Ksingh22/ruby_studio
/Game&Player/studio_game/lib/studio_game/player.rb
UTF-8
1,303
3.4375
3
[ "LicenseRef-scancode-other-permissive" ]
permissive
require_relative 'treasure_trove' require_relative 'playable' module StudioGame class Players include Playable attr_accessor :name, :health attr_reader :score def initialize(name, health = 80) @name = name.capitalize @health = health @found_treasure = Hash.new(0) end def to_s "I'm #{@name} with a health of #{@health} and score of #{score} (#{status})" end def self.from_csv(line) name, health = line.split(',') Players.new(name, Integer(health)) end def to_csv "#{@name}, #{@health}" end def points @found_treasure.values.reduce(0, :+) end def found_treasure(treasure) @found_treasure[treasure.name] += treasure.points puts "#{@name} found a #{treasure.name} worth #{treasure.points} points" puts "#{@name}'s treasures: #{@found_treasure}" end def each_found_treasure @found_treasure.each do |name,points| yield Treasures.new(name, points) end end def score @health + points end def <=>(other) other.score <=> score end def status # stronger? ? "Famous" : "Not Famous" if stronger? "Famous" else "Not Famous" end end end if __FILE__ == $0 player1 = StudioGame::Players.new ("kamal") puts player1 puts player1.blam puts player1 end end
true
5b553d740b4dce0a84a9004efb11b6539381cdb2
Ruby
dkindler/Project-Euler-Solutions
/048.rb
UTF-8
283
3.390625
3
[]
no_license
# https://projecteuler.net/problem=48 def raise(a, b, m) if b == 1 a elsif b.even? c = raise(a, b/2, m) c*c % m else c = raise(a, b/2, m) c*c*a % m end end sum = 0 1.upto(20000) do |n| sum = (sum + raise(n, n, 10000000000)) % 10000000000 end puts sum
true
f24469d4e97755e3ca8646497b994a6150199cc6
Ruby
b-enji-cmd/flash_cards
/lib/round.rb
UTF-8
2,141
3.875
4
[]
no_license
class Round attr_reader :deck , :turns , :number_correct def initialize(deck, turns = []) @deck = deck @turns = turns @number_correct = 0 end def first_card deck.cards[0] end def take_turn(guess) turn_test = Turn.new(guess, current_card) if turn_test.correct? @number_correct += 1 end @turns << turn_test turn_test end def current_card deck.cards[@turns.length] end def number_correct_by_category(category) @turns.find_all {|turn| turn.correct? && turn.card.category == category}.count end def percent_correct (@number_correct.to_f / @turns.count.to_f ) *100 end def percent_correct_by_category(category) (number_correct_by_category(category).to_f / @turns.find_all {|turn| turn.card.category == category}.count.to_f ) * 100 end def start puts "Welcome! You're playing with #{@deck.count} cards.\n --------------------------------------------------\n" until turns.count == @deck.count puts "This is card number #{turns.count+1} out of #{@deck.count}" puts "Question: #{current_card.question}" user_guess = gets.chomp turn = Turn.new(user_guess, @cards) user_guess == current_card.answer take_turn(user_guess) puts turns.last.feedback end puts "****** Game Over! ******" puts "You had #{number_correct} guesses out of #{@deck.count} for a total of #{percent_correct.round(0)}%" puts "Category Statistics:\n" # some loop iteration here #end category_stats = deck.cards.map do |card_category| card_category.category end.uniq category_stats.map do |category| puts "In category #{category} You had #{percent_correct_by_category(category).to_i}% correct" end end end
true
f56fc602c9544caa4afe85835ca21f9e86511fbf
Ruby
mmitchell/mmitchell.github.io
/code/merge_sort.rb
UTF-8
381
3.65625
4
[ "MIT" ]
permissive
def mergesort(arr) return arr if arr.length <= 1 mid = arr.length / 2 left = arr[0..mid-1] right = arr[mid..-1] merge(mergesort(left), mergesort(right)) end def merge(left, right) sorted = [] until left.empty? || right.empty? if left[0] <= right[0] sorted << left.shift else sorted << right.shift end end sorted + left + right end
true
69d5897f6c396cd79f09ad78d355fcd39bbeb014
Ruby
mamantoha/uz-api
/lib/uz/api.rb
UTF-8
1,406
2.609375
3
[ "MIT" ]
permissive
require 'json' require 'mechanize' require 'jjdecoder' require 'byebug' require 'uz/api/version' require 'uz/api/methods' module UZ class APIError < ArgumentError; end class TokenError < ArgumentError; end class API attr_reader :token JJ_ENCODE_PATTERN = /0\);}\);(.+)<\/script>/i TOKEN_PATTERN = /localStorage.setItem\(\"gv-token\", \"(\w+)\"\);/i # Create a new API object using the given parameters # def initialize @api_url = 'http://booking.uz.gov.ua' @agent = Mechanize.new get_token set_headers end # Shuts down this session by clearing browsing state and create # a new Mechanize instance with new token # def refresh_token @agent.shutdown @agent = Mechanize.new get_token set_headers end def inspect "#<#{self.class.name}:#{"0x00%x" % (object_id << 1)} @token=\"#{@token}\">" end private def get_token resp = @agent.get(@api_url) jj_code = JJ_ENCODE_PATTERN.match(resp.body)[1] jj_decoder = JJDecoder.new(jj_code) jj_decoded = jj_decoder.decode @token = TOKEN_PATTERN.match(jj_decoded)[1] end def set_headers headers = { 'GV-Ajax' => 1, 'GV-Referer' => @api_url, 'GV-Screen' => '1920x1080', 'GV-Token' => @token } @agent.request_headers = headers end end end
true
72a8e919dae46f3438c4062b0bbec1a9738c2bf5
Ruby
merrua/ruby
/ex5a.rb
UTF-8
506
4.09375
4
[]
no_license
even = 10 odd = 7 # %d Convert argument as a decimal number. # %u Identical to 'd' # %i same as d puts "Lets add a even number %d and an odd number %d." % [even, odd] # b Convert argument as a binary number. puts "Lets out the numbers in Binary" puts "A even number %b and an odd number %b." % [even, odd] inches = 45.45 pounds = 180.5 cm = inches * 2.54 # cm / inch kilos = pounds / 2.2 puts "%f inches is equal to %f cm." % [inches, cm] puts "%f pounds is equal to %f kilos." % [pounds, kilos]
true
0ce8e71448abe99d036d3d461959901cdb8cf49e
Ruby
sakikazu/relatives-sns
/app/models/ranking.rb
UTF-8
2,373
2.609375
3
[]
no_license
# == Schema Information # # Table name: rankings # # id :integer not null, primary key # classification :integer # content_type :string(255) # nice_count :integer # created_at :datetime not null # updated_at :datetime not null # content_id :integer # class Ranking < ApplicationRecord belongs_to :content, :polymorphic => true # [memo] ここで各コンテンツが「content」でincludeできるんだ!!すげー(polymorphic) default_scope {includes(:content => {:nices => {:user => :user_ext}}).order("nice_count DESC")} scope :total, lambda {where(classification: 1)} scope :month, lambda {where(classification: 2)} # 各コンテンツフィルタ scope :mutter, lambda {where(content_type: "Mutter")} scope :photo, lambda {where(content_type: "Photo")} scope :movie, lambda {where(content_type: "Movie")} scope :blog, lambda {where(content_type: "Blog")} # # 累計ランキング生成 # classification: 1 # def self.create_total contents = {} # 一つのコンテンツの評価人数を取得(type(Mutterなど)とIDでグループ化したときのそれぞれの個数) data = Nice.group(:asset_type, :asset_id).count data2 = data.map{|d| {:type => d[0][0], :id => d[0][1], :count => d[1]}} # ブロック中の正規表現のグループで分ける。「$1」はマッチ文字列を返すようにするため data3 = data2.group_by{|d| d[:type] =~ /(Mutter|Photo|Movie|Blog)/;$1} ["Mutter", "Photo", "Movie", "Blog"].each do |c| next if data3[c].blank? # 評価人数でソートして降順にする data4 = data3[c].sort_by{|d| d[:count]}.reverse # 上位200個のみ取得 contents[c] = data4.slice(0,200) end # todo トランザクションの使い方合ってるかな?あとdelete_allはトランザクション対応しているかとか ActiveRecord::Base.transaction do self.delete_all(classification: 1) contents.each do |content_data| content_data[1].each do |rank| self.create(classification: 1, content_type: rank[:type], content_id: rank[:id], nice_count: rank[:count]) end end end end # # 月間ランキング生成 # classification: 2 # def self.create_month p "まだ作ってません" end end
true
8bf4f70f02bbeef1e8d58ed5f3c08f94de2bfb6f
Ruby
hectorhuertas/turing_machine
/lib/printer.rb
UTF-8
1,905
3.59375
4
[]
no_license
module Printer def self.print_machine(tape, state, position) puts [ build_positioned_head(state,position), print_tape(tape) ] end def self.print_tape(tape) # => tape is an array of numbers ascii_tape=["","",""] tape.each do |number| ascii_tape = add_split(ascii_tape) ascii_tape = add_number(ascii_tape,number) end add_split(ascii_tape) end def self.add_number(ascii_tape,number) [ascii_tape[0] + "-",ascii_tape[1] + "#{number}", ascii_tape[2] + "-"] end def self.add_split(ascii_tape) split = ["-+-"," | ","-+-"] [ascii_tape[0]+ split[0],ascii_tape[1] + split[1], ascii_tape[2] + split[2]] end def self.join_ascii_outputs(array_of_inputs) if array_of_inputs.size == 3 line_1 = array_of_inputs.reduce("") do |result,input| result + input[0] end line_2 = array_of_inputs.reduce("") do |result,input| result + input[1] end line_3 = array_of_inputs.reduce("") do |result,input| result + input[2] end line_1 + "\n" + line_2 + "\n" + line_3 else line_1 = array_of_inputs.reduce("") do |result,input| result + input[0] end line_2 = array_of_inputs.reduce("") do |result,input| result + input[1] end line_3 = array_of_inputs.reduce("") do |result,input| result + input[2] end line_4 = array_of_inputs.reduce("") do |result,input| result + input[3] end line_1 + "\n" + line_2 + "\n" + line_3 + "\n" + line_4 end end def self.build_head(state) ["+---+", "| #{state} |", "+---+", " \\ /"] end def self.build_positioned_head(state,position) join_ascii_outputs([build_offset(position),build_head(state)]) # build_head(state) end def self.build_offset(position) offset = " " + " " * 4 * position [offset,offset,offset,offset] end end
true
786adac662c27102c1818e00fa34ffdbf194efb4
Ruby
citation-file-format/ruby-cff
/test/formatters/bibtex_test.rb
UTF-8
2,758
2.515625
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
# frozen_string_literal: true require_relative '../test_helper' require 'cff/formatters/bibtex' require 'cff/file' class CFFBibtexFormatterTest < Minitest::Test describe 'all bibtex fixtures' do Dir[::File.join(FORMATTER_DIR, '*.cff')].each do |input_file| define_method("test_converter_for_#{File.basename(input_file)}") do cff = ::CFF::File.read(input_file) output_file = ::File.join(FORMATTED_DIR, "#{File.basename(input_file, '.*')}.bibtex") if ::File.exist?(output_file) assert_equal File.read(output_file).strip, cff.to_bibtex else assert_nil cff.to_bibtex end end end end def test_formatter_label assert_equal('BibTeX', CFF::Formatters::BibTeX.label) end def test_can_tolerate_invalid_file cff = CFF::Index.new(nil) assert_nil cff.to_bibtex end def test_bibtex_type index = ::CFF::Index.new('Title') assert_equal('software', CFF::Formatters::BibTeX.bibtex_type(index)) index.type = 'software' assert_equal('software', CFF::Formatters::BibTeX.bibtex_type(index)) index.type = 'dataset' assert_equal('misc', CFF::Formatters::BibTeX.bibtex_type(index)) ref = ::CFF::Reference.new('Title') assert_equal('misc', CFF::Formatters::BibTeX.bibtex_type(ref)) ref.type = 'newspaper-article' assert_equal('article', CFF::Formatters::BibTeX.bibtex_type(ref)) ref.type = 'conference' assert_equal('proceedings', CFF::Formatters::BibTeX.bibtex_type(ref)) ref.type = 'conference-paper' assert_equal('inproceedings', CFF::Formatters::BibTeX.bibtex_type(ref)) ref.type = 'proceedings' assert_equal('proceedings', CFF::Formatters::BibTeX.bibtex_type(ref)) ref.type = 'pamphlet' assert_equal('booklet', CFF::Formatters::BibTeX.bibtex_type(ref)) ['article', 'book', 'manual', 'unpublished'].each do |type| ref.type = type assert_equal(type, CFF::Formatters::BibTeX.bibtex_type(ref)) end end def test_generate_citekey [ [ { 'author' => 'von Haines, Jr, Robert and Robert, Haines', 'title' => 'My Family and Other Animals', 'year' => '2021' }, 'von_Haines_My_Family_and_2021' ], [ { 'year' => nil, 'author' => '{An Organisation}', 'title' => "Really?! 'Everyone' Disagrees?" }, 'An_Organisation_Really_Everyone_Disagrees' ], [ { 'author' => 'Solskjær, Ole Gunnar', 'title' => 'My Straße', 'year' => '2021' }, 'Solskjaer_My_Strasse_2021' ] ].each do |fields, reference| assert_equal(reference, CFF::Formatters::BibTeX.generate_citekey(fields)) end end end
true
2bb2e287b3650d7b10da60cb91e08dfbd929c499
Ruby
hmesander/battleshift
/spec/services/values/space_spec.rb
UTF-8
748
2.890625
3
[]
no_license
require 'rails_helper' describe Space do context 'initialize' do it 'has valid attributes' do space = Space.new(['A1', 'A2']) expect(space.coordinates).to eq(['A1', 'A2']) expect(space.contents).to eq(nil) expect(space.status).to eq('Not Attacked') end end context 'instance methods' do let(:space) { Space.new(['A1', 'A2']) } it '.attack!' do space.attack! expect(space.status).to eq('Miss') end it '.occupy!' do ship = Ship.new(4) space.occupy!(ship) expect(space.contents).to eq(ship) end it '.occupied?' do expect(space.occupied?).to eq(false) end it '.not_attacked?' do expect(space.not_attacked?).to eq(true) end end end
true
bdae3949fc4e3bf5a70893987101181843b42177
Ruby
raquelnishimoto/ruby_intro
/facets_of_ruby/OrageTree.rb
UTF-8
1,221
4.0625
4
[]
no_license
class OrangeTree def initialize @birth = 2019 @age = Time.now.year - @birth end def a_one_year_passes @age += 1 if @age > 99 puts "Your tree died" end end def height # height in meters @height = @age * 0.5 until @age < 100 end def count_the_oranges if @age > 35 && @age < 50 puts "Your tree is #{@age} getting old, next year it might not bear as many fruits" @number_fruit = (@age * 2) - rand(10) elsif @age >= 50 puts "The tree is #{@age} not bearing more fruit :(" @number_fruit = 0 else @number_fruit = (@age * 3) end end def pick_oranges(number) if @number_fruit < number puts "Sorry, you don't have enough fruit!" else while number > 0 && @number_fruit > 0 @number_fruit -= 1 if @number_fruit == 0 puts "Delicious! This is the last one" break end puts "Delicious! Still #{@number_fruit} left" number -= 1 puts 'No more oranges, see you next year!' if @number_fruit == 0 end end end tree = OrangeTree.new tree.a_one_year_passes puts tree.height puts tree.count_the_oranges puts tree.pick_oranges(7) end
true
2534ade02259290ab441e948c394045e581198cf
Ruby
angstr0m/ADPraktikum
/lib/MergeSort.rb
UTF-8
2,239
3.3125
3
[]
no_license
require './AbstractSorter' #test class MergeSort < AbstractSorter def performSort() sortBetween(0,@data.size) end def sortBetween(index1, index2) @data = split(@data.slice(index1, index2)) end def split(datalist) if (datalist.size <= 1) return datalist end index_half = (datalist.size/2).floor - 1 # puts "Size: " + datalist.size.to_s # puts "Size/2: " + (datalist.size/2).floor.to_s # puts "HalberIndex " + index_half.to_s block1 = datalist.slice(0..index_half) #puts "Block1 " + block1.to_s block2 = datalist.slice((index_half + 1)..(datalist.size)) #puts "Block2 " + block2.to_s list1 = split(block1) list2 = split(block2) return merge(list1, list2) end def merge(list_left, list_right) resultList = [] while(list_left.size > 0 && list_right.size > 0) # falls (erstes Element der linkeListe <= erstes Element der rechteListe) if (compare(list_left[0], list_right[0]) < 1) # dann füge erstes Element linkeListe in die neueListe hinten ein und entferne es aus linkeListe resultList << list_left[0] list_left.delete_at(0) else # sonst füge erstes Element rechteListe in die neueListe hinten ein und entferne es aus rechteListe resultList << list_right[0] list_right.delete_at(0) end end # solange (linkeListe nicht leer) while (list_left.size > 0) # füge erstes Element linkeListe in die neueListe hinten ein und entferne es aus linkeListe resultList << list_left[0] list_left.delete_at(0) end # solange (rechteListe nicht leer) while (list_right.size > 0) # füge erstes Element rechteListe in die neueListe hinten ein und entferne es aus rechteListe resultList << list_right[0] list_right.delete_at(0) end return resultList end end #testMergeSort = MergeSort.new #testMergeSort.fillDescending(10) #testMergeSort.permuteRandom(50) #testMergeSort.fillWithText('./MobyDick.txt') #puts "SelectionSort" #puts "-------------" #puts "Unsorted Data" #puts testMergeSort.data #puts "-------------" #testMergeSort.sort() #puts testMergeSort.data
true
cd29d1fec32dda3824b6d1e7704291d72444878f
Ruby
Karanveer-singh671/mathGame
/main.rb
UTF-8
978
3.84375
4
[]
no_license
require './question' require './player' puts "player 1's name will be? " player1_name = gets.chomp puts "player 2's name will be?" player2_name = gets.chomp player1 = Player.new(player1_name) player2 = Player.new(player2_name) current_player = 0 while(player1.alive? && player2.alive?) do player = (current_player == 0) ? player1 : player2 question = Question.new() puts "#{player.name} Hi, #{question.display}" response = gets.chomp.to_i if(response == question.answer) puts "correct! P1 #{player1.lives}/3 vs P2: #{player2.lives}/3" else player.lives -= 1 puts "wrong, P1: #{player1.lives} lives left! vs P2: #{player2.lives} lives left!" end current_player = (current_player + 1) % 2 if (player1.lives == 0) puts "#{player2.name} wins this time" puts "GAME OVER" else if (player2.lives == 0) puts "#{player1.name} wins this time" puts "GAME OVER" end end end
true
cd611db909fc828086b54b6bf9bf40d14b31840f
Ruby
solmengs/seattle-web-102819
/11-retake-review/social_media.rb
UTF-8
208
2.765625
3
[]
no_license
class SocialMedia attr_reader :name, :website_url @@all = [] def initialize (name, website_url) @name = name @website_url = website_url @@all << self end def self.all @@all end end
true
676860262bf90eee2963aca13d4a98f303589b30
Ruby
spalak/tennis-kata
/test/models/tennis_game_test.rb
UTF-8
4,085
3.09375
3
[]
no_license
require 'test_helper' class TennisGameTest < ActiveSupport::TestCase # test "the truth" do # assert true # end test "score starts as love-love" do game = TennisGame.new("Mike", "Dave") assert_equal("love-love", game.score) end test "score goes to 15-love when a player scores" do game = TennisGame.new("Mike", "Dave") game.won_point("Mike") assert_equal("15-love", game.score) end test "score goes to 15-15 when second player scores" do game = TennisGame.new("Mike", "Dave") game.won_point("Mike") game.won_point("Dave") assert_equal("15-15", game.score) end test "score goes to 30-15 when first player scores agains" do game = TennisGame.new("Mike", "Dave") game.won_point("Mike") game.won_point("Dave") game.won_point("Mike") assert_equal("30-15", game.score) end test "score goes to 40-15 when first player scores again" do game = TennisGame.new("Mike", "Dave") game.won_point("Mike") game.won_point("Dave") game.won_point("Mike") game.won_point("Mike") assert_equal("40-15", game.score) end test "score goes to 40-30 when first player scores again" do game = TennisGame.new("Mike", "Dave") 3.times { game.won_point('Mike') } 2.times { game.won_point('Dave') } assert_equal("40-30", game.score) end test "first player wins game if he gets to 4 points and second player only has 2 or fewer" do game = TennisGame.new("Mike", "Dave") 4.times { game.won_point('Mike') } 2.times { game.won_point('Dave') } assert_equal("Mike defeats Dave", game.score) end test "second player wins game if he gets to 4 points and first player only has 2 or fewer" do game = TennisGame.new("Mike", "Dave") 2.times { game.won_point('Mike') } 4.times { game.won_point('Dave') } assert_equal("Dave defeats Mike", game.score) end test "both players have 3 points, score is deuce" do game = TennisGame.new("Mike", "Dave") 3.times { game.won_point('Mike') } 3.times { game.won_point('Dave') } assert_equal("Deuce", game.score) end test "first player gets to 3 points, second player to 3 points, then first player scores, score is 'Advantage In'" do game = TennisGame.new("Mike", "Dave") 3.times { game.won_point('Mike') } 3.times { game.won_point('Dave') } game.won_point('Mike') assert_equal('Advantage In', game.score) end test "first player gets to 3 points, second player to 3 points, then second player scores, score is 'Advantage Out'" do game = TennisGame.new("Mike", "Dave") 3.times { game.won_point('Mike') } 3.times { game.won_point('Dave') } game.won_point('Dave') assert_equal('Advantage Out', game.score) end test "first player gets 3 points, second player 2 points, then first player 2 points, first player wins" do game = TennisGame.new("Mike", "Dave") 3.times { game.won_point('Mike') } 3.times { game.won_point('Dave') } 2.times { game.won_point('Mike') } assert_equal('Mike defeats Dave', game.score) end test "first player gets 3 points, second player 5 points, second player wins" do game = TennisGame.new("Mike", "Dave") 3.times { game.won_point('Mike') } 5.times { game.won_point('Dave') } assert_equal('Dave defeats Mike', game.score) end # This last test is to double-check that as the score increase by 1 (like a real tennis match) the code doesn't break test "players alternate scores, up to 5 points, before player 1 breaks away and wins two straight points" do game = TennisGame.new("Mike", "Dave") 2.times { game.won_point('Mike') } 2.times { game.won_point('Dave') } assert_equal('30-30', game.score) game.won_point('Mike') assert_equal('40-30', game.score) game.won_point('Dave') assert_equal('Deuce', game.score) game.won_point('Mike') assert_equal('Advantage In', game.score) game.won_point('Dave') assert_equal('Deuce', game.score) 2.times { game.won_point('Mike') } assert_equal('Mike defeats Dave', game.score) end end
true
2ec0a7e4e153404fec2c101a474dcca70eaa843a
Ruby
MarciaOrr/firehose_image-blur
/temp/image.rb
UTF-8
939
3.46875
3
[]
no_license
class Image attr_accessor :image def initialize(image) @image = image @rows = @image.size @cols = @image.first.size end def blur @image_copy = Array.new(@rows) {Array.new(@cols)} @image.each_with_index do |row, row_index| row.each_with_index do |cell, col_index| @image_copy[row_index][col_index] = 0 end end @image.each_with_index do |row, row_index| row.each_with_index do |cell, col_index| if @image[row_index][col_index] == 1 blur_location(row_index,col_index) end end end @image = @image_copy return @image end def blur_location(row,col) @image_copy[row][col] = 1 @image_copy[row][col-1] = 1 unless col.zero? @image_copy[row][col+1] = 1 unless col == @cols-1 @image_copy[row-1][col] = 1 unless row.zero? @image_copy[row+1][col] = 1 unless row == @rows-1 end end
true
b84861d51ad81a3f36c79c7a119711d600c96d2b
Ruby
ndonnellan/finance
/lib/person.rb
UTF-8
1,161
3.375
3
[]
no_license
COLUMNS = 15 class Person attr_reader :accounts, :tax_account def initialize(name) @name = name end def print_tax_rate total_income = @taxable_income.reduce(:+) total_tax = @taxes_paid.reduce(:+) + @tax_account.balance printf "eff tax|%#{spacing-1}.1f%%\n", (total_tax / total_income * 100.0) end def max_account_name_length @accounts.collect {|a| a.name.length }.max end def spacing @spacing ||= [ max_account_name_length, COLUMNS].max end def print_account_names print " month |" @accounts.each {|a| printf "%#{spacing}s |", a.name } print "\n" end def print_account_balances printf "%6s |", $month+1 @accounts.each {|a| printf "%#{spacing}.0f |", a.balance } print "\n" end def print_account_changes print "change |" @accounts.each {|a| printf "%#{spacing-1}.1f%% |", a.year_change*100.0 } print "\n" end end class Array def element_wise_add(a2) self.zip(a2).map {|e| e.reduce(:+) } end def element_wise_sub(a2) self.zip(a2).map {|e| e.reduce(:-) } end alias_method :eadd, :element_wise_add alias_method :esub, :element_wise_sub end
true
c91086a5351a376bd9e22bf9a5667554be33f657
Ruby
Mardiniii/full-stack-bootcamp-ruby
/Ruby/OOP/oop.rb
UTF-8
711
3.46875
3
[]
no_license
class Transaction attr_accessor :user, :date, :concept, :amount end class Invoice < Transaction attr_accessor :number end class Income < Transaction end class Expense < Transaction end class Humano attr_accessor :name, :age, :genre def initialize(name, age, genre) @name = name @age = age @genre = genre end def greet "Hola, me llamo #{@name}" end end invoice = Invoice.new invoice.user = 'Juan Alberto' invoice.amount = 35_000 invoice.number = 1 puts invoice.user puts invoice.amount puts invoice.number juan = Humano.new("Juan Alberto", 25, "Masculino") # juan.name = "Juan Alberto" # juan.age = 25 # juan.genre = "Masculino" puts juan.name puts juan.age puts juan.genre puts juan.greet
true
743b66d46ae35214a5a6e8d5c77b0e367b4263fd
Ruby
tiyd-rails-2015-01/battleship
/battleship_test.rb
UTF-8
16,610
3.359375
3
[]
no_license
require 'minitest/autorun' require 'minitest/pride' require './battleship' $mock_inputs = [] def get_user_input $mock_inputs.shift end class BattleshipTest < Minitest::Test #This is not good practice, AND it forces you to do dumb things like test_00_ # in the code. However, it's easier to follow as you're learning if the # tests always run in the same order. def self.test_order :alpha end def test_00_ship_class_exists assert Ship end def test_01_ship_knows_its_length ship = Ship.new(4) assert_equal 4, ship.length end def test_02_ship_can_be_placed_across ship = Ship.new(4) assert ship.place(2, 1, true) refute ship.covers?(1, 1) assert ship.covers?(2, 1) assert ship.covers?(3, 1) assert ship.covers?(4, 1) assert ship.covers?(5, 1) refute ship.covers?(6, 1) refute ship.covers?(4, 2) end def test_03_ship_can_be_placed_down ship = Ship.new(4) assert ship.place(2, 2, false) refute ship.covers?(2, 1) assert ship.covers?(2, 2) assert ship.covers?(2, 3) assert ship.covers?(2, 4) assert ship.covers?(2, 5) refute ship.covers?(2, 6) refute ship.covers?(3, 2) end def test_04_ship_cant_be_placed_twice ship = Ship.new(4) assert ship.place(2, 1, true) refute ship.place(3, 2, false) end def test_05_ships_know_if_they_overlap ship1 = Ship.new(4) ship1.place(2, 1, true) ship2 = Ship.new(4) ship2.place(3, 1, true) ship3 = Ship.new(4) ship3.place(2, 1, false) assert ship1.overlaps_with?(ship2) assert ship1.overlaps_with?(ship3) refute ship2.overlaps_with?(ship3) end def test_06_ships_can_be_fired_at ship = Ship.new(4) ship.place(2, 1, true) assert ship.fire_at(2, 1) refute ship.fire_at(1, 1) end def test_07_ships_can_be_sunk ship = Ship.new(2) ship.place(2, 1, true) refute ship.sunk? ship.fire_at(2, 1) refute ship.sunk? ship.fire_at(3, 1) assert ship.sunk? end def test_08_board_class_exists assert Board end def test_09_empty_board board = Board.new refute board.has_ship_on?(1, 1) refute board.has_ship_on?(10, 7) end def test_10_place_ship board = Board.new assert board.place_ship(Ship.new(4), 3, 3, true) refute board.has_ship_on?(2, 3) assert board.has_ship_on?(3, 3) assert board.has_ship_on?(4, 3) assert board.has_ship_on?(6, 3) refute board.has_ship_on?(7, 3) refute board.has_ship_on?(5, 4) end def test_11_cant_place_overlapping_ships board = Board.new assert board.place_ship(Ship.new(4), 3, 3, true) refute board.place_ship(Ship.new(4), 1, 3, true) refute board.place_ship(Ship.new(4), 4, 3, true) refute board.place_ship(Ship.new(4), 4, 2, false) end def test_12_misses_on_empty_board board = Board.new refute board.fire_at(1, 1) refute board.fire_at(10, 7) end def test_13_hits_on_board board = Board.new board.place_ship(Ship.new(4), 3, 3, true) refute board.fire_at(1, 1) assert board.fire_at(3, 3) end def test_14_repeat_miss board = Board.new board.place_ship(Ship.new(4), 3, 3, true) refute board.fire_at(1, 1) refute board.fire_at(1, 1) end def test_15_repeat_hit board = Board.new board.place_ship(Ship.new(4), 3, 3, true) assert board.fire_at(3, 3) refute board.fire_at(3, 3) end def test_16_misses_outside_board board = Board.new refute board.fire_at(18, 1) refute board.fire_at(10, 26) end def test_17_empty_board_can_display_itself board = Board.new assert_output(empty_board) do board.display end end def empty_board %Q{ 1 2 3 4 5 6 7 8 9 10 ----------------------------------------- A | | | | | | | | | | | B | | | | | | | | | | | C | | | | | | | | | | | D | | | | | | | | | | | E | | | | | | | | | | | F | | | | | | | | | | | G | | | | | | | | | | | H | | | | | | | | | | | I | | | | | | | | | | | J | | | | | | | | | | | ----------------------------------------- } end def test_18_full_board_can_display_itself board = Board.new board.place_ship(Ship.new(2), 3, 6, true) board.place_ship(Ship.new(3), 7, 4, true) board.place_ship(Ship.new(3), 4, 8, true) board.place_ship(Ship.new(4), 1, 1, true) board.place_ship(Ship.new(5), 6, 2, false) assert_output(full_board) do board.display end end def full_board %Q{ 1 2 3 4 5 6 7 8 9 10 ----------------------------------------- A | O | O | O | O | | | | | | | B | | | | | | O | | | | | C | | | | | | O | | | | | D | | | | | | O | O | O | O | | E | | | | | | O | | | | | F | | | O | O | | O | | | | | G | | | | | | | | | | | H | | | | O | O | O | | | | | I | | | | | | | | | | | J | | | | | | | | | | | ----------------------------------------- } end def test_19_used_board_can_display_itself board = Board.new board.place_ship(Ship.new(4), 6, 4, true) board.fire_at(7, 4) board.fire_at(7, 5) assert_output(used_board) do board.display end end def used_board %Q{ 1 2 3 4 5 6 7 8 9 10 ----------------------------------------- A | | | | | | | | | | | B | | | | | | | | | | | C | | | | | | | | | | | D | | | | | | O | X | O | O | | E | | | | | | | | | | | F | | | | | | | | | | | G | | | | | | | | | | | H | | | | | | | | | | | I | | | | | | | | | | | J | | | | | | | | | | | ----------------------------------------- } end def test_20_entire_board_can_be_sunk board = Board.new refute board.sunk? board.place_ship(Ship.new(2), 6, 4, true) refute board.sunk? board.fire_at(6, 4) refute board.sunk? board.fire_at(7, 4) assert board.sunk? end def test_21_player_classes_exist assert Player assert HumanPlayer assert ComputerPlayer end def test_22_players_have_inheritance assert_equal Player, HumanPlayer.superclass assert_equal Player, ComputerPlayer.superclass end def test_23_humans_can_be_named assert_equal "Alice", HumanPlayer.new("Alice").name end def test_24_computers_cannot_be_named assert_raises(ArgumentError) do ComputerPlayer.new("The Red Queen") end end def test_25_players_have_default_names assert_equal "Dave", HumanPlayer.new.name assert_equal "HAL 9000", ComputerPlayer.new.name end def test_26_players_have_boards assert_equal Board, HumanPlayer.new.board.class assert_equal Board, ComputerPlayer.new.board.class end def test_27_computer_player_automatically_places_ships player = ComputerPlayer.new assert_output("HAL 9000 has placed his ships.\n") do assert player.place_ships([2, 3, 3, 4, 5]) end assert_equal 5, player.ships.length assert_equal 4, player.ships[3].length end def test_28_x_of board = Board.new assert_equal 1, board.x_of("A1") assert_equal 1, board.x_of("G1") assert_equal 6, board.x_of("D6") assert_equal 10, board.x_of("D10") end def test_29_y_of board = Board.new assert_equal 1, board.y_of("A1") assert_equal 7, board.y_of("G1") assert_equal 4, board.y_of("D6") assert_equal 4, board.y_of("D10") end def test_30_human_player_is_asked_to_place_ships player = HumanPlayer.new $mock_inputs.clear $mock_inputs << "A1" $mock_inputs << "Down" $mock_inputs << "A4" $mock_inputs << "Down" assert_output("Dave, where would you like to place a ship of length 2?\nAcross or Down?\n"+ "Dave, where would you like to place a ship of length 5?\nAcross or Down?\n") do assert player.place_ships([2, 5]) end assert_equal 2, player.ships.length assert_equal 5, player.ships[1].length assert player.board.has_ship_on?(1, 1) assert player.board.has_ship_on?(4, 1) assert player.board.has_ship_on?(1, 2) refute player.board.has_ship_on?(1, 3) end def test_31_game_class_exists assert Game end def test_32_games_require_players assert_raises(ArgumentError) do Game.new end human = HumanPlayer.new("Frank") computer = ComputerPlayer.new assert Game.new(human, computer) end def test_33_game_welcomes_player human = HumanPlayer.new("Frank") computer = ComputerPlayer.new game = Game.new(human, computer) assert_output("Welcome, Frank and HAL 9000!\nIt's time to play Battleship.\n") do game.welcome end end def test_34_game_can_ask_to_set_up_ships set_up_new_game assert_equal 5, @human.ships.length assert @human.board.has_ship_on?(1, 2) assert @human.board.has_ship_on?(3, 3) assert @human.board.has_ship_on?(9, 5) refute @human.board.has_ship_on?(7, 7) assert_equal 5, @computer.ships.length assert_equal 4, @computer.ships[3].length end def set_up_new_game @human = HumanPlayer.new("Frank") @computer = ComputerPlayer.new @game = Game.new(@human, @computer) $mock_inputs.clear $mock_inputs << "A1" $mock_inputs << "Down" $mock_inputs << "A3" $mock_inputs << "Down" $mock_inputs << "A5" $mock_inputs << "Down" $mock_inputs << "A7" $mock_inputs << "Down" $mock_inputs << "A9" $mock_inputs << "Down" assert_output("Frank, where would you like to place a ship of length 2?\nAcross or Down?\n"+ "Frank, where would you like to place a ship of length 3?\nAcross or Down?\n"+ "Frank, where would you like to place a ship of length 3?\nAcross or Down?\n"+ "Frank, where would you like to place a ship of length 4?\nAcross or Down?\n"+ "Frank, where would you like to place a ship of length 5?\nAcross or Down?\n"+ "HAL 9000 has placed his ships.\n") do @game.place_ships end end def test_35_game_can_have_nonstandard_set_of_ships human = HumanPlayer.new("Alice") computer = ComputerPlayer.new game = Game.new(human, computer, [2, 3]) $mock_inputs.clear $mock_inputs << "A1" $mock_inputs << "Down" $mock_inputs << "A3" $mock_inputs << "Down" assert_output("Alice, where would you like to place a ship of length 2?\nAcross or Down?\n"+ "Alice, where would you like to place a ship of length 3?\nAcross or Down?\n"+ "HAL 9000 has placed his ships.\n") do game.place_ships end end def test_36_game_tells_you_if_your_ships_overlap human = HumanPlayer.new("Alice") computer = ComputerPlayer.new game = Game.new(human, computer, [2, 3]) $mock_inputs.clear $mock_inputs << "A2" $mock_inputs << "Down" $mock_inputs << "A1" $mock_inputs << "Across" $mock_inputs << "F1" $mock_inputs << "Across" assert_output("Alice, where would you like to place a ship of length 2?\nAcross or Down?\n"+ "Alice, where would you like to place a ship of length 3?\nAcross or Down?\n"+ "Unfortunately, that ship overlaps with one of your other ships. Please try again.\n"+ "Alice, where would you like to place a ship of length 3?\nAcross or Down?\n"+ "HAL 9000 has placed his ships.\n") do game.place_ships end end def test_37_human_can_take_first_turn set_up_new_game $mock_inputs.clear $mock_inputs << "A1" # This /(Miss!|Hit!)/ thing just checks to see if Miss! or Hit! was included anywhere in the message. assert_output(/(Miss!|Hit!)/) do @game.take_turn end end def test_38_computer_can_take_second_turn set_up_new_game $mock_inputs.clear $mock_inputs << "A1" assert_output(/(Miss!|Hit!)/) do @game.take_turn end assert_output(/(Miss!|Hit!)/) do @game.take_turn end end def test_39_display_game_status set_up_new_game assert_output(starting_game_status) do @human.display_game_status end end def starting_game_status %Q{ 1 2 3 4 5 6 7 8 9 10 ----------------------------------------- A | | | | | | | | | | | B | | | | | | | | | | | C | | | | | | | | | | | D | | | | | | | | | | | E | | | | | | | | | | | F | | | | | | | | | | | G | | | | | | | | | | | H | | | | | | | | | | | I | | | | | | | | | | | J | | | | | | | | | | | ----------------------------------------- 1 2 3 4 5 6 7 8 9 10 ----------------------------------------- A | O | | O | | O | | O | | O | | B | O | | O | | O | | O | | O | | C | | | O | | O | | O | | O | | D | | | | | | | O | | O | | E | | | | | | | | | O | | F | | | | | | | | | | | G | | | | | | | | | | | H | | | | | | | | | | | I | | | | | | | | | | | J | | | | | | | | | | | ----------------------------------------- } end def test_40_game_status_shows_hits_and_misses human1 = HumanPlayer.new("Amy") human2 = HumanPlayer.new("Beth") game = Game.new(human1, human2, [2]) $mock_inputs.clear # It doesn't matter what messages come up during the turns assert_output(/./) do $mock_inputs << "A2" #Amy's ship's location $mock_inputs << "Down" #Amy's ship's direction $mock_inputs << "F3" #Beth's ship's location $mock_inputs << "Across" #Beth's ship's direction game.place_ships $mock_inputs << "F3" #Amy's hit game.take_turn $mock_inputs << "A2" #Beth's hit game.take_turn $mock_inputs << "H4" #Amy's miss game.take_turn $mock_inputs << "A2" #Beth's miss (she shot in the same spot as last time) game.take_turn end # Now the visuals matter. Should show Amy's shots up top and Amy's own ship below. assert_output(mid_game_status) do human1.display_game_status end end def mid_game_status %Q{ 1 2 3 4 5 6 7 8 9 10 ----------------------------------------- A | | | | | | | | | | | B | | | | | | | | | | | C | | | | | | | | | | | D | | | | | | | | | | | E | | | | | | | | | | | F | | | + | | | | | | | | G | | | | | | | | | | | H | | | | - | | | | | | | I | | | | | | | | | | | J | | | | | | | | | | | ----------------------------------------- 1 2 3 4 5 6 7 8 9 10 ----------------------------------------- A | | X | | | | | | | | | B | | O | | | | | | | | | C | | | | | | | | | | | D | | | | | | | | | | | E | | | | | | | | | | | F | | | | | | | | | | | G | | | | | | | | | | | H | | | | | | | | | | | I | | | | | | | | | | | J | | | | | | | | | | | ----------------------------------------- } end def test_41_game_can_be_won human1 = HumanPlayer.new("Amy") human2 = HumanPlayer.new("Beth") game = Game.new(human1, human2, [2]) $mock_inputs.clear $mock_inputs << "A2" #Amy's ship's location $mock_inputs << "Down" #Amy's ship's direction $mock_inputs << "F3" #Beth's ship's location $mock_inputs << "Across" #Beth's ship's direction $mock_inputs << "F3" #Amy's first shot $mock_inputs << "A1" #Beth's first shot $mock_inputs << "F4" #Amy's winning shot assert_output(/Congratulations, Amy!/) do game.play #When Amy wins, it has to say 'Congratulations, Amy' somewhere in the victory message. end end end
true
6f3f6476ced67364f300cd68e1ba481716e8651e
Ruby
prathamesh1993/intro-to-tdd-rspec-and-learn-bootcamp-prep-000
/current_age_for_birth_year.rb
UTF-8
59
2.640625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def current_age_for_birth_year(number) 2003 - number end
true
28bdc7a5678f37880a2410e3f7e61b07eabd8dbb
Ruby
oddruud/Ruby-Hive
/lib/hive/common/move/move_exception.rb
UTF-8
330
2.5625
3
[]
no_license
class Hive::MoveException < RuntimeError attr :ok_to_retry attr :code attr :message def initialize(code, message, ok_to_retry) @ok_to_retry = ok_to_retry @code = code @message= message end def to_string() return "Move Exception #{@code}: #{@message}, retry: #{@ok_to_retry}" end end
true
6968d328e5f1b945d9fe7aea69e404a2d312ea1c
Ruby
mayaugusto7/learn-ruby
/modulo20-classes-02/monkey_patching_part_03.rb
UTF-8
367
3.328125
3
[]
no_license
class Fixnum def seconds self end def minutes self * 60 end def hours self * 60 * 60 end def days self * 60 * 60 * 24 end def custom_times i = 0 while i < self yield(i + 1) i += 1 end end end 5.custom_times { |i| puts i} # puts Time.now + 45.minutes # puts Time.now + 4.hours # puts Time.now + 10.days
true
25bdc3741b10d1d1b8a1dc2013894c6a8b7070a9
Ruby
pecuerre/travel_demo
/lib/travel_demo/flight.rb
UTF-8
4,345
2.625
3
[]
no_license
module Sample class Flight @flight_ways=['One way flight', 'Two way flight'] @stops=['1 stop', '2 stops', '3 stops', 'multistops'] @flight_types=['Business', 'First Class', 'Economy', 'Premium Economy'] @inflight_features=['Available', 'Not Available'] @airlines=['Major Airline', 'United Airlines', 'Delta Airlines', 'Alitalia', 'US airways', 'Air France', 'Air tahiti nui', 'American Airlines', 'Copa Airlines'] ## to change the style of the icon add circle at the end. Example: soap-icon-entertainment circle @features={'WIFI' => 'soap-icon-wifi', 'entertainment' => 'soap-icon-entertainment', 'television' => 'soap-icon-entertainment', 'entertainment' => 'soap-icon-television', 'air conditioning' => 'soap-icon-aircon', 'drink' => 'soap-icon-juice', 'games' => 'soap-icon-joystick', 'coffee' => 'soap-icon-coffee', 'wines' => 'soap-icon-winebar', 'shopping' => 'soap-icon-shopping', 'food' => 'soap-icon-food', 'comfort' => 'soap-icon-comfort', 'magazines' => 'soap-icon-magazine' } class << self def generate_flight f = OpenStruct.new f.flight_way=@flight_ways.sample f.flight_type=@flight_types.sample f.name = Faker::Address.country + ' to '+ Faker::Address.country f.stops=@stops.sample takeoff=generate_date flight_duration=rand(3600...86400) landing=takeoff+flight_duration f.takeOff= takeoff.strftime('%d %b %Y,%I:%M %p') f.landing=landing.strftime('%d %b %Y,%I:%M %p') f.duration="#{(flight_duration/3600)} H #{(flight_duration%3600)/60} M" f.duration_long_style="#{(flight_duration/3600)} Hours #{(flight_duration%3600)/60} Minutes" f.airline= @airlines.sample f.cancellation="$ #{rand(40...200)} /person" f.flight_change="$ #{rand(40...200)} /person" f.seat_baggage="$ #{rand(40...200)} /person" keys = @features.keys.to_a set = Set.new 5.times { set << keys.sample } hash = @features.select { |key, _| set.include?(key) } f.inflight_features=@inflight_features.sample f.base_fare="$ #{rand(300...900)}" f.taxes_fees="$ #{rand(300...900)}" f.total_price="$ #{rand(300...900)}" f.long_description=Faker::Lorem.paragraph(5) f.lay_over="#{rand(1...4)} h #{rand(5...50)} m" f.short_description=Faker::Lorem.sentence f.airline_description=Faker::Lorem.paragraph(10) f.calendar_description=Faker::Lorem.paragraphs(1) f.identifier="#{f.airline[0]} #{f.airline[1]} - #{rand(100...999)} #{f.flight_type}" f.list_of_features_flight=hash f.features_description=Faker::Lorem.paragraphs(1) f.sets_selection_description=Faker::Lorem.paragraphs(1) f.number_of_available_seats=rand(1...10) seats=[] f.number_of_available_seats.times do seats<< generate_seat end f.seats=seats f.baggage_information=Faker::Lorem.paragraphs(4) f.fare_rules_description=Faker::Lorem.paragraphs(4) f.number_of_available_rules=rand(1...10) rules=[] f.number_of_available_rules.times do rules<< generate_rule end f.rules=rules f.countries=Faker::Address.country f end def generate_seat s= OpenStruct.new s.price='$'+rand(10...20).to_s s.description=Faker::Lorem.sentence s end def generate_rule r= OpenStruct.new r.title=Faker::Lorem.word r.description=Faker::Lorem.paragraphs(2) r end def sample @@_flights ||= begin flights= [] sample_size=10 sample_size.times do flights << generate_flight end flights end end def airlines @airlines end def stops @stops end def flight_types @flight_types end def features @features end def generate_date timeOff= Time.now+rand(0...864000) end end end end
true
1973f9efac5fa29c6ae2151c3645a68d44d4e041
Ruby
WGretz/rpg_dice
/lib/lib/dice.rb
UTF-8
1,596
3.28125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
class Dice attr_accessor :num_of_dice, :sides @@max_dice = nil @@max_sides = nil def initialize(num_of_dice,sides, options={}) options = filter_options(options) raise ArgumentError, "Your sides exceeds the maximum number of sides allowed" if @@max_sides && sides > @@max_sides raise ArgumentError, "Your dice exceeds the maximum dice allowed" if @@max_dice && num_of_dice > @@max_dice @num_of_dice = num_of_dice @sides = sides end def results return @results.inject {|sum,x| sum+=x} if @results @results = [] @num_of_dice.times do @results << rand(sides) + 1 end return @results.inject {|sum,x| sum+=x} end def reroll @results = nil return results end # Parses a dice string and returns a dice object # More documentation to come later def self.parse(string) dice_regex = /(?<num_of_dice>\d*)d(?<num_of_sides>\d+)/ dice = dice_regex.match(string) raise ArgumentError, "unable to parse dice string" if dice.nil? num_of_dice = dice[:num_of_dice].to_i num_of_dice = 1 if num_of_dice == 0 num_of_sides = dice[:num_of_sides].to_i dice = Dice.new(num_of_dice,num_of_sides) return dice end def self.max_dice=( value ) @@max_dice = value end def self.max_sides=( value ) @@max_sides = value end private def filter_options(options) defaults = {:highest=>nil} options.each do |key,vale| raise ArgumentError, "#{key} is not a valid option" unless defaults.has_key? key end return defaults.merge(options) end end
true
19e1d703417a53b919f771b6ed826a48dbb04112
Ruby
Smesworld/jungle_app
/spec/models/user_spec.rb
UTF-8
3,143
2.5625
3
[]
no_license
require 'rails_helper' RSpec.describe User, type: :model do describe 'Validations' do subject { described_class.new( first_name: "First", last_name: "Last", email: "email@test.com", password: "test", password_confirmation: "test" )} it "is valid with valid attributes" do subject.save expect(subject).to be_valid end it "is not valid without a first name" do subject.first_name = nil expect(subject).to_not be_valid expect(subject.errors.full_messages).to include("First name can't be blank") end it "is not valid without a last name" do subject.last_name = nil expect(subject).to_not be_valid expect(subject.errors.full_messages).to include("Last name can't be blank") end it "is not valid without a email" do subject.email = nil expect(subject).to_not be_valid expect(subject.errors.full_messages).to include("Email can't be blank") end it "is not valid without a password" do subject.password = nil expect(subject).to_not be_valid expect(subject.errors.full_messages).to include("Password can't be blank") end it "is not valid without matching password and password confirmation" do subject.password = "that" subject.password_confirmation = "test" expect(subject).to_not be_valid expect(subject.errors.full_messages).to include("Password confirmation doesn't match Password") end it "is not valid without a 4 character password" do subject.password = "the" subject.password_confirmation = "the" expect(subject).to_not be_valid expect(subject.errors.full_messages).to include("Password is too short (minimum is 4 characters)") end it "is not valid with a duplicate email" do user = User.new( first_name: "First", last_name: "Last", email: "Email@Test.com", password: "test", password_confirmation: "test" ) user.save expect(subject).to_not be_valid expect(subject.errors.full_messages).to include("Email has already been taken") end end describe '.authenticate_with_credentials' do subject { described_class.new( first_name: "First", last_name: "Last", email: "email@test.com", password: "test", password_confirmation: "test" )} it "is valid with existing email and matching password" do subject.save expect(User.authenticate_with_credentials("email@test.com", "test")).to be_valid end it "is not valide with incorrect password" do subject.save login = User.authenticate_with_credentials("email@test.com", "text") expect(login).to be_nil end it "is valid with an email with extra space" do subject.save expect(User.authenticate_with_credentials(" email@test.com ", "test")).to be_valid end it "is valid with an email not matching case" do subject.save expect(User.authenticate_with_credentials("eMaIl@tEst.cOm", "test")).to be_valid end end end
true
924fb940efdca5e5cb474268ee4c1b7ca02b8300
Ruby
ICRAR/TSN_alpha
/app/helpers/profiles_helper.rb
UTF-8
2,911
2.5625
3
[]
no_license
module ProfilesHelper def credit_location(profile) gsi = profile.general_stats_item bonuses = gsi.bonus_credits pogs = gsi.boinc_stats_item nereus =gsi.nereus_stats_item out = [] first = "&nbsp;&nbsp;&nbsp;" bonuses.each do |b| reason = "<abbr title=\"#{b.reason}\">Bonus Credit</abbr>" out << "<dt>#{reason}</dt> <dd>#{first}#{number_with_delimiter(b.amount)} cr</dd>" first = " + " end if !pogs.try(:credit).nil? && (pogs.credit > 0) out << "<dt>POGS</dt> <dd>#{first}#{number_with_delimiter(pogs.credit)} cr</dd>" first = " + " end if !nereus.try(:credit).nil? && (nereus.credit > 0) out << "<dt>SourceFinder</dt> <dd>#{first}#{number_with_delimiter(nereus.credit)} cr</dd>" first = " + " end out << "<dt>Total</dt> <dd> = #{number_with_delimiter(gsi.total_credit)} cr </dd>" out << "<p>(Please note that it may take a couple of hours for the total credit value to update)</p>" "<dl class=\"dl-horizontal\">#{out.join("\n")}</dl>".html_safe end def boinc_computers(boinc_hosts) out = [] out << "<ul>" boinc_hosts.each do |host| out << "<li>#{host.domain_name.to_s.encode("UTF-8")}</li>" end out << "</ul>" out.join("\n").html_safe end #sorts the trophies into rows and columns with the most important trophies centered def sort_trophies_by_priority(trophies) #number of trophies per row per_row_small = 16 per_row_medium = 4 per_row_large = 1 rows = [] per_row = per_row_small + per_row_medium + per_row_large num_rows = (trophies.size / per_row.to_f).ceil (1..num_rows).each {rows << {:far_left => [],:left => [],:center => [],:right => [],:far_right => []}} i = 0 trophies.each do |trophy| #fill center first if i < num_rows*per_row_large rows[i/per_row_large][:center] << trophy #fill left and right rows next elsif i < (num_rows*per_row_medium+num_rows*per_row_large) j = i - num_rows if j.even? rows[j/per_row_medium][:left] << trophy else rows[j/per_row_medium][:right] << trophy end #fill far left and far right rows next elsif i < (num_rows* per_row_small + num_rows*per_row_medium+num_rows) j = i - num_rows*per_row_medium - num_rows if j.even? rows[j/per_row_small][:far_left] << trophy else rows[j/per_row_small][:far_right] << trophy end end i = i + 1 end rows end def show_likes(model, display, model_name_method) out = '' out << "<h3>#{display}</h3> \n" out << "" m_array = [] objects = @profile.likeables_relation(model) objects.each do |object| m_array << link_to(object.send(model_name_method), object) end out << "<p>#{array_to_paragraph(m_array)}</p>" return out.html_safe end end
true
66faf6601955c19551d5d868dc9705d94ebd33a3
Ruby
yous/algospot
/problems/encrypt.rb
UTF-8
140
3.03125
3
[]
no_license
gets.to_i.times do chunks = ['', ''] gets.chop.each_char.with_index do |ch, idx| chunks[idx % 2] << ch end puts chunks.join end
true
28e36ff0ffbd0f17a9b0d6acfd377cda18307e1f
Ruby
MisterrW/codeclan-karaoke
/karaoke/specs/song_spec.rb
UTF-8
771
3.125
3
[]
no_license
require('minitest/autorun') require('minitest/rg') require_relative('../song.rb') class SongTest < MiniTest::Test def setup @song1 = Song.new({name: "Toxic", artist: "Britney Spears", lyrics: "...but you know that you're toxic", genre: "pop"}) @song2 = Song.new({name: "Marianne", artist: "Leonard Cohen", lyrics: "So long, Marianne...", genre: "folk"}) @song3 = Song.new({name: "Slave for You", artist: "Britney Spears", lyrics: "I'm a slave for you", genre: "pop"}) end def test_song_name assert_equal("Marianne", @song2.name) end def test_song_artist assert_equal("Britney Spears", @song3.artist) end def test_song_lyrics assert_equal("...but you know that you're toxic", @song1.lyrics) end def test_song_genre assert_equal("pop", @song1.genre) end end
true
0d78c7d2065a79341b197dbcb4a7bfc4d7383592
Ruby
Kira-kyuukyoku/OpenClassRooms
/mooc_start_ruby/bouclesIterator.rb
UTF-8
71
3.046875
3
[]
no_license
10.times do |i| puts "Hello #{i}" i.times do puts "World" end end
true
61d2aef12c4074008388117e9e2dd79409d516a5
Ruby
failure-driven/playing-with-tcr
/tcr-rspec-dojo/lib/tennis.rb
UTF-8
488
3.40625
3
[]
no_license
class Tennis SCORES = ["love", 15, 30] def initialize @points = { s: 0, r: 0 } end def score return "deuce" if deuce? score = @points.values.map { |point| SCORES[point] } score[1] = "all" if same_score? score.join(" ") end def point(*players) players.each do |player| @points[player] += 1 end end private def deuce? same_score? && @points.values.min >= 3 end def same_score? @points.values.uniq.length == 1 end end
true
8af29959858f97205c782bc85edb8e231b9bea4d
Ruby
s-espinosa/mastermind
/lib/play.rb
UTF-8
859
3.703125
4
[]
no_license
require_relative 'game' require_relative 'print_text' require_relative 'clean_text' module Play def self.start_game difficulty = ask_difficulty game = Game.new(difficulty) PrintText.short_instructions(difficulty) game.take_turn ask_play_again end def self.ask_difficulty puts "How difficult? (b)egginer, (i)ntermediate, (a)dvanced." difficulty = CleanText.getsmall if /[bia]/ =~ difficulty difficulty else ask_difficulty end end def self.ask_play_again puts "Would you like to play again? (y/n)" play_again = CleanText.getsmall check_play_again(play_again) end def self.check_play_again(play_again) if play_again == "y" start_game elsif play_again == "n" abort else puts "Sorry, that's not an option.\n\n" ask_play_again end end end
true
9f476d3ff2357a684e6c2faf74c7fac5cb28963b
Ruby
mikeboan/jumpstart-beginner-track
/problem_sets/problem_set_3_solution.rb
UTF-8
1,271
4.03125
4
[]
no_license
def third_greatest(array) array.sort[-3] end # ************************************ def count_vowels(string) count = 0 vowels = ["a", "e", "i", "o", "u"] string.chars.each do |character| if vowels.include?(character) count += 1 end end count end # ************************************ def convert_word(word) if word.length == 5 "#####" else word end end def redact_five_letter_words(string) words = string.split new_words = [] words.each do |word| new_words << convert_word(word) end new_words.join(" ") end # ************************************ def reverse(array) left_idx = 0 right_idx = array.length - 1 until left_idx >= right_idx array[left_idx], array[right_idx] = array[right_idx], array[left_idx] left_idx += 1 right_idx -= 1 end array end # ************************************ def rotate(array, shift) shift_count = 0 while shift_count < shift array.unshift(array.pop) shift_count += 1 end array end # ************************************ def all_uniqs(array1, array2) uniques = [] array1.each do |el| uniques << el unless array2.include?(el) end array2.each do |el| uniques << el unless array1.include?(el) end uniques end
true
e6be4fd2ad73b4732292fd0694c1f23c63e7b6fe
Ruby
kanwei/algorithms
/benchmarks/sorts.rb
UTF-8
918
2.734375
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
$: << File.join(File.expand_path(File.dirname(__FILE__)), '../lib') require 'algorithms' include Algorithms require 'rubygems' require 'rbench' RBench.run(5) do sorts = %w(ruby comb_sort heapsort insertion_sort shell_sort quicksort mergesort) sorts.each { |sort| self.send(:column, sort.intern) } n = 1000 proc = lambda { |scope, ary| scope.ruby { ary.dup.sort } scope.comb_sort { Sort.comb_sort(ary.dup) } scope.heapsort { Sort.heapsort(ary.dup) } scope.insertion_sort { Sort.insertion_sort(ary.dup) } scope.shell_sort { Sort.shell_sort(ary.dup) } scope.quicksort { Sort.quicksort(ary.dup) } scope.mergesort { Sort.mergesort(ary.dup) } } report "Already sorted" do sorted_array = Array.new(n) { rand(n) }.sort proc.call(self, sorted_array) end report "Random" do random_array = Array.new(n) { rand(n) } proc.call(self, random_array) end end
true
42c7a57a6fd0fe430b6d1ff2a74a090b67320297
Ruby
Eden-Eltume/101
/101_Exercises/Small_Problems2/Easy6/ex6.rb
UTF-8
215
3.796875
4
[]
no_license
def merge(arr1, arr2) new_arr = [] until arr1.empty? new_arr << arr1.pop end until arr2.empty? new_arr << arr2.pop end new_arr.sort.uniq! end p merge([1, 3, 5], [3, 6, 9]) == [1, 3, 5, 6, 9]
true
5bfb08ab842c527f9f8f47bfee0800fcb480d562
Ruby
dpolivaev/runner
/test/server/stream_writer_test.rb
UTF-8
958
2.546875
3
[ "BSD-2-Clause" ]
permissive
require_relative 'test_base' require_source 'stream_writer' class StreamWriterTest < TestBase def self.id58_prefix '55t' end # - - - - - - - - - - - - - - - - - test 'dF7', %w( write(s) is a no-op when s is empty ) do assert_equal '', write('') end # - - - - - - - - - - - - - - - - - test 'dF8', %w( write(s) logs s and a trailing newline when s does not end in a newline ) do assert_equal "hello\n", write('hello') end # - - - - - - - - - - - - - - - - - test 'dF9', %w( write(s) logs s as it is when s ends in a newline ) do assert_equal "world\n", write("world\n") end private def write(s) captured_stdout do writer = StreamWriter.new($stdout) writer.write(s) end end def captured_stdout begin old_stdout = $stdout $stdout = StringIO.new('', 'w') yield captured = $stdout.string ensure $stdout = old_stdout end captured end end
true
1500bbb797d2091b713084e496d7a54aa321dd14
Ruby
pliantmeerkat/Calculator
/lib/Calc.rb
UTF-8
660
3.671875
4
[]
no_license
# calculator class class Calc attr_reader :total attr_reader :operations def initialize @total = 0 @operations = [] # data struct for operations storage end def add(arr) @operations.push(arr.join(' + ')) @total = arr.inject(:+) end def subtract(arr) @operations.push(arr.join(' - ')) @total = arr.inject(:-) end def divide(arr) @operations.push(arr.join(' / ')) @total = arr.inject(:/) end def multiply(arr) @operations.push(arr.join(' * ')) @total = arr.inject(:*) end def print_total puts @total end def pretty_print "the total for #{operations.join} is #{total}" end end
true
9c1bc2ce275c64eacb072f7cf14276666824df2d
Ruby
michpara/file-io-and-serialization
/hangman.rb
UTF-8
5,422
3.546875
4
[]
no_license
require 'yaml' def word() flag = true while(flag) line = File.readlines('5desk.txt').sample if line.length >= 5 and line.length <= 12 flag = false break end end return line end def person() hangman = [""" ----- | | | | | | | | | -------- """, """ ----- | | | 0 | | | | | | -------- """, """ ----- | | | 0 | -+- | | | | | | -------- """, """ ----- | | | 0 | /-+- | | | | | -------- """, """ ----- | | | 0 | /-+-/ | | | | | -------- """, """ ----- | | | 0 | /-+-/ | | | | | | -------- """, """ ----- | | | 0 | /-+-/ | | | | | | | -------- """, """ ----- | | | 0 | /-+-/ | | | | | | | | -------- """, """ ----- | | | 0 | /-+-/ | | | | | | | | | -------- """, """ ----- | | | 0 | /-+-/ | | | | | | | | | | -------- """, """ ----- | | | 0 | /-+-/ | | | | | | | | | | | -------- """, ] return hangman end def ld(guesses, ind, word, already) puts "Would you like to reload your game? (yes/no): " ld = gets.chomp if ld.downcase == "yes" guesses = YAML.load(File.read("guesses.yml")) ind = YAML.load(File.read("ind.yml")) word = YAML.load(File.read("word.yml")) already = YAML.load(File.read("already.yml")) end return guesses, ind, word, already end def save(guesses, ind, word, already) puts "Would you like to save the game?: " save = gets.chomp if save.downcase == "yes" File.open("guesses.yml", "w") { |file| file.write(guesses.to_yaml)} File.open("ind.yml", "w") { |file| file.write(ind.to_yaml)} File.open("word.yml", "w") { |file| file.write(word.to_yaml)} File.open("already.yml", "w") { |file| file.write(already.to_yaml)} end end def guess_word(word) puts "What is your guess?: " guess = gets.chomp if(guess.downcase == word) #if the user guesses right puts "Congratulation! You guessed the right word! The word was " + word + "." else #if the user guesses wrong puts "Unfortunately, you guessed the wrong word. The word was " + word + "." end return false, false end def guess_letter(already, letters, guesses, ind) puts "Which letter would you like to guess?: " guess = gets.chomp if already.include? guess #if the user has already guessed this letter puts "You have already guessed this letter." ourinput = false game = true elsif !already.include? guess #if the user hasn't guessed this letter already << guess #add this letter to the list of guessed letters if letters.include? guess.downcase #if the letter is right indexes = [] (0..letters.length-1).each do |i| if letters[i] == guess.downcase indexes << i end end (0..indexes.length-1).each do |i| guesses[indexes[i]] = guess.downcase #add this letter to all of the indexes of guesses end if !guesses.difference(letters).any? #if the user guessed all the letters puts "Congratulation! You guessed the right word! The word was " + word + "." ourinput = false game = false #end the game else puts "Congratulations, you guessed a letter right!" ourinput = false game = true end else #if the user guesses a wrong letter puts "Unfortunately, you guessed wrong!" ind +=1 #ind increments by 1 ourinput = false game = true end end return already, guesses, ind, ourinput, game end def lose(ind, hangman) if ind > 9 #if the user uses up all their guesses puts hangman[10] #print the final hangman state puts "Unfortunately, you made too many wrong guesses. The word was " + word + "." return false, false end return false, true end game = true ind = 0 hangman = person() word = word() word = word.delete!("\n").downcase guesses = [] letters = word.chars #splits the random word into a list and assigns it to "letters" already = [] (0..letters.length-1).each do |i| guesses.append("_") end if (File.file?("guesses.yml") and File.file?("ind.yml") and File.file?("word.yml") and File.file?("already.yml")) guesses, ind, word, already = ld(guesses, ind, word, already) letters = word.chars end puts """Welcome to Hangman! A word will be chosen at random, and you must try to guess it by guessing one letter at a time. Everytime you guess a letter wrong, an extra body part will be added to the hangman. Once every body part appears on the hangman, you lose the game. At any point in the game you can choose to guess the entire word, but if you guess it wrong you will automatically lose.""" while game == true ourinput = true puts hangman[ind] #print the hangman at whichever state p guesses while ourinput == true save(guesses, ind, word, already) puts "Would you like to try guessing the entire word?: " yesno = gets.chomp if yesno.downcase == "yes" ourinput, game = guess_word(word) elsif yesno.downcase == "no" already, guesses, ind, ourinput, game = guess_letter(already, letters, guesses, ind) if(game == true) ourinput, game = lose(ind, hangman) end elsif yesno != "yes" or yesno != "no" and game == true #if the user doesn't enter yes or no puts "Please enter 'yes' or 'no'" end end end
true
a8582663e4a6e6acfc78877fe0419bdaeb59d3f8
Ruby
bingxie/code-questions
/lib/leetcode/189_rotate-array.rb
UTF-8
765
3.78125
4
[ "MIT" ]
permissive
# @param {Integer[]} nums # @param {Integer} k # @return {Void} Do not return anything, modify nums in-place instead. def rotate(nums, k) array = Array.new(nums.size) 0.upto(nums.size - 1) do |i| array[(i + k) % nums.length] = nums[i] end nums.each_index do |i| nums[i] = array[i] end end nums = [1,2,3,4,5,6,7] k = 3 rotate(nums, k) # @param {Integer[]} nums # @param {Integer} k # @return {Void} Do not return anything, modify nums in-place instead. def rotate2(nums, k) j = k % nums.size reverse(nums, 0, nums.size - 1) reverse(nums, 0, j - 1) reverse(nums, j, nums.length - 1) end def reverse(nums, left, right) while left < right nums[left], nums[right] = nums[right], nums[left] left += 1 right -= 1 end end
true
1f2b7aafa2ccb1effec0b40d817cac448e015155
Ruby
gavinlaking/vedeu
/test/lib/vedeu/cells/support/html_test.rb
UTF-8
2,753
2.65625
3
[ "MIT" ]
permissive
require 'test_helper' module Vedeu module Cells describe HTML do let(:described) { Vedeu::Cells::HTML } let(:instance) { described.new(cell, options) } let(:cell) { Vedeu::Cells::Char.new(colour: { background: background, foreground: foreground, }, value: _value) } let(:options) { { start_tag: start_tag, end_tag: end_tag, } } let(:start_tag) { '<td' } let(:end_tag) { '</td>' } let(:background) { '#220022' } let(:foreground) { '#0066ff' } let(:_value) { 'A' } describe '#initialize' do it { instance.must_be_instance_of(described) } it { instance.instance_variable_get('@cell').must_equal(cell) } it { instance.instance_variable_get('@options').must_equal(options) } end describe '#to_html' do subject { instance.to_html } it { subject.must_be_instance_of(String) } context 'with a custom :start_tag and :end_tag' do let(:start_tag) { '<div' } let(:end_tag) { '</div>' } let(:expected) { "<div style='background-color:#220022;color:#0066ff;'>A</div>" } it { subject.must_equal(expected) } end context 'with the default :start_tag and :end_tag' do let(:expected) { "<td style='background-color:#220022;color:#0066ff;'>A</td>" } it { subject.must_equal(expected) } end context 'when the cell has only a background colour' do let(:foreground) {} let(:expected) { "<td style='background-color:#220022;'>A</td>" } it { subject.must_equal(expected) } end context 'when the cell has only a foreground colour' do let(:background) {} let(:expected) { "<td style='color:#0066ff;'>A</td>" } it { subject.must_equal(expected) } end context 'when the cell has neither background or foreground colours' do let(:background) {} let(:foreground) {} let(:expected) { '<td>A</td>' } it { subject.must_equal(expected) } end context 'when the cell does not have a value or does not respond to ' \ ':as_html' do let(:_value) { '' } let(:expected) { "<td style='background-color:#220022;color:#0066ff;'>&nbsp;</td>" } it { subject.must_equal(expected) } end end end # HTML end # Cells end # Vedeu
true
03a2a31e39072054e2c03e966d6fb9a7f23f6c01
Ruby
reddavis/panda-mysql-and-activerecord
/lib/mysql_modules/mysql_user.rb
UTF-8
740
2.71875
3
[]
no_license
module MySqlUser module ClassMethods def authenticate(login, password) unless u = self.find_by_login(login) return nil else puts "#{u.crypted_password} | #{encrypt(password, u.salt)}" u && (u.crypted_password == encrypt(password, u.salt)) ? u : nil end end def encrypt(password, salt) Digest::SHA1.hexdigest("--#{salt}--#{password}--") end end module InstanceMethods def set_password(password) return if password.blank? puts '1' salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{self.key}--") puts '2' self.salt = salt puts '3' self.crypted_password = self.class.encrypt(password, salt) end end end
true
916f1fb0d78d693076bed45d6b1e3c04d3c682f3
Ruby
gregorymostizky/katas
/kata02/chop.rb
UTF-8
990
3.796875
4
[]
no_license
module Chop # iterative chop def chop_iterative(number, array) return -1 if array.empty? left = 0 right = array.size - 1 begin pointer = left + ((right-left) / 2) if array[pointer]==number return pointer elsif number > array[pointer] left = left == pointer ? left+1 : pointer else right = right == pointer ? right-1 : pointer end end while left<=right -1 #not found end # recursive chop def chop(number, array) return -1 if array.empty? return 0 if array.size == 1 && array[0] == number return -1 if array.size == 1 && array[0] != number middle = array.size / 2 if array[middle]==number return middle elsif number > array[middle] result = chop(number, array.slice(middle, array.size - middle)) return result < 0 ? -1 : middle+result else result = chop(number, array.slice(0, middle)) return result < 0 ? -1 : result end end end
true
f0bc3bec006741ad861f3fdef844af2a1de31c5d
Ruby
bcarrol2/oo-uber
/driver.rb
UTF-8
425
3.375
3
[]
no_license
class Driver attr_reader :name @@all = [] def initialize(name) @name = name @@all << self end def self.all @@all end #Gets all the rides associated with a driver def allrides Ride.all.select do |ride| ride.driver == self end end #Get all the passsengers associated with this driver def passengers self.allrides.map do |ride| ride.passenger.name end end end
true
4894455bb6d798b07681d49c2c4dd41ffb9959a2
Ruby
gypsydave5/boris-bikes
/lib/person.rb
UTF-8
547
2.9375
3
[]
no_license
class Person attr_reader :total_time_bike_hired def initialize(bike=nil) @bike = bike end def has_bike? not @bike.nil? end def has_accident! @bike.break! self end def rent_bike_from docking_station @bike = docking_station.release_bike @bike.set_time_bike_was_hired self end def return_bike_to docking_station set_total_time_bike_hired docking_station.dock_bike(@bike) @bike = nil self end def set_total_time_bike_hired @total_time_bike_hired = Time.now - @bike.time_bike_was_hired end end
true
4bcc7090d5fa4561e9c9ab9a66a8fe94e9cfa92c
Ruby
wildfauve/foucault_http
/lib/foucault_http/logger.rb
UTF-8
595
2.609375
3
[ "MIT" ]
permissive
module FoucaultHttp class Logger FILTERS = ["password"] def call(level, message) logger.send(level, filtered(message)) if ( logger && logger.respond_to?(level) ) end def configured_logger logger end private def logger @logger ||= configuration.config.logger end def filtered(msg) return unless msg.instance_of?(String) filters = FILTERS.map { |f| msg.downcase.include? f } if filters.any? "[FILTERED]" else msg end end def configuration Configuration end end end
true
961fcda95a368bd1727c075d37651e8e22145647
Ruby
kgilla/building-blocks
/lib/bubble_sort_by.rb
UTF-8
494
3.6875
4
[]
no_license
def bubble_sort_by (arr) unsorted = true while unsorted == true unsorted = false for a in 0...arr.length - 1 result = yield(arr[a], arr[a + 1]) if result > 0 arr[a], arr[a+1] = arr[a+1], arr[a] unsorted = true end end end print arr end # change the block params and the array! arr = ["hi", "hey", "hello"] bubble_sort_by(arr) do |first, second| (first.length - second.length) end
true
f1a24afa3a881ae641daabbfb7be41b8ba47baf6
Ruby
TheGrayWolf/Ruby_Exercises_and_Programs
/Operators.rb
UTF-8
449
4.125
4
[]
no_license
# == equal operator p 10 == 10; a = 10; b = 5; c = 10; p a == c; p a == b; p c == a; p 5 == 5.0; # != inequality operator p "hello" != "hello"; p "hello" != "Hello"; p "hello".downcase != "HeLlo".downcase p "123" != 123; # < and > do the same thing as in pute mathematics # <= less or equal ---> greater or equal to >= .... p 1 < 3; p 2 <= 2; p 12 <= 11; # aritmatic operators # + plus # - minus # / divided # * times # % modulo
true
7c5a20e8726fd3df4aadcfa04c5e57766108c369
Ruby
emre-basala/dxf-reader
/lib/dxf/dimension.rb
UTF-8
1,653
2.875
3
[]
no_license
module DXF class Dimension < Entity # 5 hanlde attr_reader :pairs attr_accessor :x1, :y1, :z1 attr_accessor :x2, :y2, :z2 attr_accessor :x3, :y3, :z3 attr_accessor :x4, :y4, :z4 attr_accessor :handle attr_accessor :layer_name attr_accessor :block_name attr_accessor :drawn_as_text attr_accessor :locally_referenced attr_accessor :style_name attr_accessor :rotation_angle def parse_pair(code, value) @pairs ||= {} case code when '10' then self.x1 = value.to_f when '20' then self.y1 = value.to_f when '30' then self.z1 = value.to_f when '11' then self.x2 = value.to_f when '21' then self.y2 = value.to_f when '31' then self.z2 = value.to_f when '13' then self.x3 = value.to_f when '23' then self.y3 = value.to_f when '33' then self.z3 = value.to_f when '14' then self.x4 = value.to_f when '24' then self.y4 = value.to_f when '34' then self.z4 = value.to_f when '5' then self.handle = value when '8' then self.layer_name = value when '2' then self.block_name = value when '1' then self.drawn_as_text = value.to_s == '<>' when '70' then self.locally_referenced = value.to_s == '32' when '3' then self.style_name = value when '50' then self.rotation_angle = value.to_f else @pairs[code] = value super # Handle common and unrecognized codes end end def debug # puts "keys: " + pairs.keys.join(",") end def initialize(*args) # puts "initialize #{self.class.to_s}" # puts args.to_s end end end
true
48f88829fc44703f51e0affdbe098171d92054fc
Ruby
emadb/kata_and_quiz
/tennis_game/lib/game.rb
UTF-8
614
3.4375
3
[]
no_license
class ZeroZero end class Game def initialize @players = [0,0] @score_map = { '1-0' => 'fifteen-love', '1-1' => 'fifteen-all', '2-3' => 'thirty-forty', '0-3' => 'love-forty', '3-3' => 'deuce', '4-3' => 'advantage player one', '4-5' => 'advantage player two', '4-0' => 'player one wins', '5-3' => 'player one wins', '6-8' => 'player two wins' } end def score_player_1(s) @players[0] = s end def score_player_2(s) @players[1] = s end def score key = "#{@players[0]}-#{@players[1]}" @score_map[key] end end
true
5a4f7ef5a926550f45dbf9065741a7ba84ce0e01
Ruby
cklim83/launch_school
/04_rb130_more_topics/03_exercises/04_medium_1/06_method_to_proc.rb
UTF-8
10,541
4.3125
4
[]
no_license
=begin Method to Proc In our Ruby course content on blocks, we learn about "symbol to proc" and how it works. To review briefly, consider this code: comparator = proc { |a, b| b <=> a } and the Array#sort method, which expects a block argument to express how the Array will be sorted. If we want to use comparator to sort the Array, we have a problem: it is a proc, not a block. The following code: array.sort(comparator) fails with an ArgumentError. To get around this, we can use the proc to block operator & to convert comparator to a block: array.sort(&comparator) This now works as expected, and we sort the Array in reverse order. When applied to an argument object for a method, a lone '&' causes ruby to try to convert that object to a block. If that object is a proc, the conversion happens automatically, just as shown above. If the object is not a proc, then & attempts to call the #to_proc method on the object first. Used with symbols, e.g., &:to_s, Ruby creates a proc that calls the #to_s method on a passed object, and then converts that proc to a block. This is the "symbol to proc" operation (though perhaps it should be called "symbol to block"). Note that &, when applied to an argument object is not the same as an & applied to a method parameter, as in this code: def foo(&block) block.call end While & applied to an argument object causes the object to be converted to a block, & applied to a method parameter causes the associated object to be converted to a proc. In essence, the two uses of & are opposites. Did you know that you can perform a similar trick with methods? You can apply the & operator to an object that contains a Method; in doing so, Ruby calls Method#to_proc. Using this information, together with the course page linked above, fill in the missing part of the following code so we can convert an array of integers to base 8 (octal numbers). Use the comments for help in determining where to make your modifications, and make sure to review the "Approach/Algorithm" section for this exercise; it should prove useful. def convert_to_base_8(n) n.method_name.method_name # replace these two method calls end # The correct type of argument must be used below base8_proc = method(argument).to_proc # We'll need a Proc object to make this code work. Replace `a_proc` # with the correct object [8, 10, 12, 14, 16, 33].map(&a_proc) The expected return value of map on this number array should be: [10, 12, 14, 16, 20, 41] You don't need a deep understanding of octal numbers -- base 8 -- for this problem. It's enough to know that octal numbers use the digits 0-7 only, much as decimal numbers use the digits 0-9. Thus, the octal number 10 is equivalent to the decimal number 8, octal 20 is the same as decimal 16, octal 100 is the same as decimal 64, and so on. No math is needed for this problem though; see the Approach/Algorithm section for some hints. Hint: To solve this problem you'll need to do a bit of research. Refer to this page on the Integer class instance method, to_s (https://ruby-doc.org/core-3.1.2/Integer.html). You will also have to use one method (https://ruby-doc.org/core-3.1.2/Object.html#method-i-method) from the Object class. NOTE: This exercise is tricky. If you can't finish it, feel free to follow along with the solution; it may be treated as a learning experience rather than something you should be able to figure out on your own. =end def convert_to_base_8(n) n.to_s(8).to_i end base8_proc = method(:convert_to_base_8) [8, 10, 12, 14, 16, 33].map(&base8_proc) # => [10, 12, 14, 16, 20, 41] =begin Solution def convert_to_base_8(n) n.to_s(8).to_i end base8_proc = method(:convert_to_base_8).to_proc [8, 10, 12, 14, 16, 33].map(&base8_proc) # => [10, 12, 14, 16, 20, 41] Discussion Let's start with our convert_to_base_8 method. Notice that this method takes a number-like argument, n. We also see that to_s(n) is using a number-like argument as well. This seems like a good place to start. We'll find that this form of to_s converts integers into the String representation of a base-n number. Right now, we use decimals (base 10), so to convert a number n to base 8, we call to_s(8) on it. If we take 8 as an example, then calling 8.to_s(8) returns "10". But, from the expected return value, we can see that we want an Integer, not a String. Therefore, we also need to call to_i on the return value of n.to_s(8). Next, let's handle the missing pieces of this line: base8_proc = method(argument).to_proc Based on the information from the "Approach/Algorithm" section, we know to research method from class Object. After looking at that documentation, we see that a symbol of an existing method may be passed into method method(sym). If we do that, the functionality of that method gets wrapped in a Method object, and we may now do work on that object. We want to convert our array of numbers to base 8, so it makes sense to make a method object out of the convert_to_base_8 method. This leaves us with: base8_proc = method(:convert_to_base_8).to_proc The final piece of this exercise asks us fill in this line. [8,10,12,14,16,33].map(&a_proc). We want access to the functionality of method convert_to_base_8, and we know that it has been converted to a Proc object, so that Proc is the natural choice. Remember that using just & (and not &:) lets us turn a Proc object to a block. A block that can now be used with map. There. All done. One last piece of information that may be good to mention is how a method looks when converted to a Proc. You can imagine the conversion to look like that: def convert_to_base_8(n) n.to_s(8).to_i end # -> Proc.new { |n| n.to_s(8).to_i } #when we use & to convert our Proc to a block, it expands out to... # -> [8, 10, 12, 14, 16, 33].map { |n| n.to_s(8).to_i } =end =begin CONCEPT (VERY IMPORTANT) - Ampersand & operator (https://ablogaboutcode.com/2012/01/04/the-ampersand-operator-in-ruby) - & can be prepended to the last parameter in a method definition. Used in this context, it symbolizes an explicit block parameter and the & will convert the given blockto a simple proc - &, can also be prepended to an argument in a method invocation. In this context, it will do one of the following: - If that argument is referencing a proc, & will convert it to a block - If the argument is not referencing a proc (e.g. it is a symbol or another object), & will first call #to_proc on that object to try to convert it into a proc before converting it to a block - Why the following doesn't work? def convert_to_base_8(n) n.to_s(8).to_i end [8, 10, 12, 14, 16, 33].map(&:convert_to_base_8) In Ruby 2.7 and earlier, the above returns ArgumentError (wrong number of arguments (given 0, expected 1)). - Just like [1, 2, 3].map(&:to_s) becomes [1, 2, 3].map { |n| n.to_s }, [8, 10, 12, 14, 16, 33].map(&:convert_to_base_8) is converted to [8, 10, 12, 14, 16, 33].map { |n| n.convert_to_base_8 }. Since convert_to_base_8 is expecting 1 argument but is not receiving 1, we get an argument error. A workaround this could be to conver the method to one not requiring an argument. Since n, the method call will take on the elements in the array, we can just use self in the method body and do without the argument. def convert_to_base_8 self.to_s(8).to_i end From Ruby 3.0 onwards, the above returns in `map': private method `convert_to_base_8' called for 8:Integer (NoMethodError) - It seems that from Ruby 3.0 onwards, all methods defined in main are default private methods in Object class Some background - the main object is a little strange. It behaves both like an instance of Object, 3.0.3 :001 > self => main 3.0.3 :002 > self.instance_of?(Object) => true 3.0.3 :003 > self.class => Object - but is also like the Object class itself. So if we define a method in the main scope, that method is available to instances of Object, and also to and classes that sub-class from Object (which is all custom classes). Since Ruby 3.0 onwards, these methods are private 3.0.3 :004 > def convert_to_base_8(n) 3.0.3 :005 > n.to_s(8).to_i 3.0.3 :006 > end => :convert_to_base_8 3.0.3 :007 > class MyClass; end => nil 3.0.3 :008 > my_obj = MyClass.new => #<MyClass:0x00007fa3a7121248> 3.0.3 :009 > my_obj.private_methods => [:timeout, :DelegateClass, :convert_to_base_8, ...] - Hence [8, 10, 12, 14, 16, 33].map(&:convert_to_base_8) becomes [8, 10, 12, 14, 16, 33].map { |n| n.convert_to_base_8 }, while complains we are trying to call a private method #convert_to_base_8 on an integer 8 (first element of array) - Integer and all custom class are subclasses of Object, hence they all inherit the private method #convert_to_base_8 - We suspect prior to Ruby 3.0, methods defined in main are public by default since it complain of ArgumentError rather than private method error when the same code is run in Ruby 2.7 - To solve this we could put public before convert_to_base_8 method definition public def convert_to_base_8(n) n.to_s(8).to_i end - Or we could define convert_to_base_8(n) as a public method of Integer class (not recommended since we will be altering Integer class) - Once we do that, we will get the ArgumentError seen in Ruby 2.7. - Object#method(:method_name) will wrap the method into a Method object. & will then automatically trigger Method#to_proc on the Method object (hence the extra to_proc call in base8_proc = method(:convert_to_base_8).to_proc is actually not required) and then convert that proc object into the following equivalent block [8, 10, 12, 14, 16, 33].map do |n| n.to_s(8).to_i end - Thus Object#method(sym) offers a workaround for methods with arguments to also use the symbol to block shortcut syntax. # No argument method Integer#to_s [10, 20, 30].map(&:to_s) # equivalent to [10, 20, 30].map { |n| n.to_s } => ['10', '20', '30'] # Two argument method def two_arg_method(a, b) a + b end my_method_obj = method(:two_arg_method) [1, 2, 3, 4].reduce(0, &my_method_obj) # equivalent to [1,2,3,4].reduce { |a, b| a + b } => 10 =end
true
164d3713643fea15d9e6c7c333915f5bada1b08e
Ruby
theodi/csv-profiler
/tests/tc_csvProfiler.rb
UTF-8
1,174
2.78125
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require 'test/unit' require 'csv_profiler' class TestCsvProfiler < Test::Unit::TestCase def setup @cp = CsvProfiler.new("tests/fixtures/ppms-november-with-columns-10000.csv") @profile = @cp.get_stats end def test_output_cleanup_cell dirty = '" foo bar "' clean = 'foo bar' assert_block('line not properly cleaned') { true if @cp.cleanup_cell(dirty) == clean } end def test_return_is_hash assert_instance_of( Hash, @profile ) end def test_return_hash_has_some_values assert_block("the returned hash has no values (zero length)") { true if @profile.length > 0 } end def test_return_hash_has_required_keys assert_block("the returned hash is missing some or all required keys") { @profile.has_key?("lines") && @profile.has_key?("minCols") && @profile.has_key?("maxCols") && @profile.has_key?("empties") } end def test_return_hash_key_are_strings assert(@profile.keys.all? { |key| key.is_a? String }, "not all hash keys are strings") end def test_return_hash_values_are_integers assert(@profile.values.all? { |value| value.is_a? Integer }, "not all hash values are integers") end end
true
dcc5b10d1ba56ba5e34a338cf1a631f358bd953f
Ruby
cairesr/hackerrank
/ruby/warmpup/diagonal_difference.rb
UTF-8
359
3.4375
3
[]
no_license
args = STDIN.read.split array_size = args[0].to_i array_values = args.slice(1, args.size) first_diagonal_sum = 0 second_diagonal_sum = 0 0..(array_size - 1) do |iterator| first_diagonal_sum += (array_size * iterator) + iterator second_diagonal_sum += (array_size * (iterator + 1)) - (iterator + 1) end puts (first_diagonal_sum - second_diagonal_sum).abs
true
bbe1e5fb475c1d697f07828cfa5150d10481619e
Ruby
loadcode229/top_breweries
/lib/scraper.rb
UTF-8
1,317
3.015625
3
[ "MIT" ]
permissive
class TopBreweries::Scraper def self.get_brewery_info html = Nokogiri::HTML(open("https://www.thrillist.com/drink/nation/the-best-craft-brewery-in-every-state-in-america/")) #opens url and reads all HTML states = html.css('h2').map(&:text) #variable states gets all 'h2' selectors in 'html' and gets all text within. parsed_page = html.css("h2+p") #parsed_page gets all within 'h2 and p' selectors #Zipper pattern is BAD however.. parsed_page.map.with_index do |brewery, i| #takes parsed_page & iterates through each element(brewery) within an index(i). b_links = brewery.css("a").attr("href").text b_name = brewery.css("a").first.text cityem = brewery.css("em:nth-child(3)").first description_unaltered = brewery.text.split('--')[0...-1].join("--") city = cityem ? cityem.text : find_city(description_unaltered) description = description_unaltered.split("\n").last {:state => states[i], :b_links => b_links, :b_name => b_name, :city => city, :description => description} end end def self.find_city(des) des.gsub(/([^\sA-Z])([A-Z])/, '\1'+"\n"+'\2').split("\n")[1] end end
true
b90bccac66675460a9e50981d427a1c064e784a8
Ruby
bonzouti/RUBY-MVC
/lib/view.rb
UTF-8
376
2.703125
3
[]
no_license
class View def initialize end def create_gossip params = {} puts "ton histoire marante" print ">" params[:content]= gets.chomp puts "c'est l'histoire de qui ?" print ">" params[:author]= gets.chomp return params end def index_gossips(gossips) gossips.each {|goss| puts "#{goss.author}: #{goss.content}"} end end
true
a8399e2f119bef2d56ff7e03680567892978ea20
Ruby
Solveug/Tutorial-Simdyanov
/chapter10/task3.rb
UTF-8
72
2.75
3
[]
no_license
surnames = %w[Иванов Петров Сидоров Алексеева Казанцев Антропов Анисимов Кузнецов Соловьев Кошкина] puts surnames.sort
true
a5c452a4fd9cc05b5e84b429f3b00b89536b958a
Ruby
AlisherZakir/cartoon-collections-london-web-051319
/cartoon_collections.rb
UTF-8
589
3.46875
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def roll_call_dwarves(dwarves)# code an argument here # Your code here dwarves.each_with_index {|dwarf, i| puts "#{i + 1}. #{dwarf}"} end def summon_captain_planet(array)# code an argument here # Your code here array.each do |x| x[0] = x[0].upcase x << "!" end end def long_planeteer_calls(calls)# code an argument here # Your code here calls.any? {|call| call.size > 4} end def find_the_cheese(food)# code an argument here # the array below is here to help cheese_types = ["cheddar", "gouda", "camembert"] food.find {|food| cheese_types.include?(food)} end
true
aa63071f333433e2222fe6eda4ea1b12991fabe4
Ruby
ciousiaocing/leetcode-ruby
/algorithms/maximum_subarray.rb
UTF-8
266
3.53125
4
[]
no_license
def max_sub_array(nums) sum, subsum = nums[0], nums[0] 1.upto(nums.size - 1) do |idx| subsum = 0 if subsum < 0 subsum += nums[idx] # 取最大值 sum = subsum if sum < subsum p sum end sum end p max_sub_array([-2,1,-3,4,-1,2,1,-5,4])
true
147e0f4f5398f64f31e8db6a8e9f005b06faf79c
Ruby
Codilot/blogger
/app/models/article.rb
UTF-8
777
2.59375
3
[]
no_license
class Article < ApplicationRecord has_many :comments, dependent: :destroy # ensures that all articles have a title of min 2, max 62 characters long validates :title, presence: true, length: { in: 2..70, message: "Title must have minimum 2, maximum 62 characters." } # ensures that all articles have a teaser of max 325 characters long validates :teaser, presence: true, length: { maximum: 325, message: "Teaser cannot have more than 325 characters." } def self.search(search_term) if Rails.env.production? Article.where("text ilike ?", "%#{search_term}%").order('id DESC') else Article.where("text LIKE ?", "%#{search_term}%").order('id DESC') end end end
true
62561528b2c7d9744d7ac6acf341ca3b912d7c6d
Ruby
richrace/Mars-Rover-First-Attempt
/spec/util_spec.rb
UTF-8
1,947
3.40625
3
[]
no_license
require './util' # Tests to ensure the common methods are correct describe Util do before(:all) do class TempObj include Util end end describe "#split_line" do it "should return array of 2 elements" do util = TempObj.new util.split_line("AB").length.should == 2 util.split_line("A B").length.should == 2 util.split_line("A B").length.should == 2 util.split_line(" A B ").length.should == 2 end it "should return array of 4" do util = TempObj.new util.split_line("MML").length.should == 3 util.split_line("0 4 N").length.should == 3 util.split_line("M R R ").length.should == 3 end end describe "#split_string" do it "should return an array of lines for instructions" do util = TempObj.new util.split_string("0 5\n0 0 N\nMLMMMRL").length.should == 3 util.split_string("0 2 E\nMLRLLM").length.should == 2 end end describe "#get_degree" do it "should get degree of 0 for North input (N)" do util = TempObj.new util.get_degree("N").should == 0 end it "should get degree of 90 for East input (E)" do util = TempObj.new util.get_degree("E").should == 90 end it "should get degree of 180 for South input (S)" do util = TempObj.new util.get_degree("S").should == 180 end it "should get degree of 270 for West input (W)" do util = TempObj.new util.get_degree("W").should == 270 end end describe "#get_direction" do it "should get direction of North (N) for input of 0" do util = TempObj.new util.get_direction(0).should == "N" end it "should get direction of East (E) for input of 90" do util = TempObj.new util.get_direction(90).should == "E" end it "should get direction of South (S) for input of 180" do util = TempObj.new util.get_direction(180).should == "S" end it "should get direction of West (W) for input of 270" do util = TempObj.new util.get_direction(270).should == "W" end end end
true
e068d9783e9e01f2be4c4952ac7e3349beb67fab
Ruby
NoDanCoder/holberton-system_engineering-devops
/0x06-regular_expressions/5-beginning_and_end.rb
UTF-8
187
2.984375
3
[]
no_license
#!/usr/bin/env ruby # The regular expression must be exactly matching a string that starts # with h ends with n and can have any single character in between puts ARGV[0].scan(/h.n/).join
true
7adc87c9d878593303f9a6e812970883a8e579c3
Ruby
snly2386/StyleMe
/spec/integration/gameplay_spec.rb
UTF-8
4,382
2.890625
3
[]
no_license
# require 'spec_helper' # describe 'Gameplay' do # let(:game) { RabbitDice.db.create_game :players => ['Alice', 'Bob', 'Carl'] } # def rig_dice(*dice_results) # RabbitDice::Roll.any_instance.stub(:roll_die).and_return(*dice_results) # end # def play_move(move) # result = RabbitDice::PlayMove.run(:game_id => game.id, :move => move) # result.game # end # def count_die_color(dice_cup, die_color) # dice_cup.instance_variable_get(:@dice).select {|color| color == die_color }.count # end # before do # game.turns.first.player = 'Alice' # end # xit "removes dice from the dice cup after multiple plays" do # # In order for the dice count to reduce by 3 every time, # # we need to ensure there are no paws (runners) # rig_dice('meat') # expect(game.dice_cup.dice_count).to eq 13 # game = play_move('roll_dice') # expect(game.dice_cup.dice_count).to eq 10 # game = play_move('roll_dice') # expect(game.dice_cup.dice_count).to eq 7 # end # xit "creates a roll with the correct dice" do # rig_dice('meat') # expect(game.dice_cup.dice_count).to eq 13 # game = play_move('roll_dice') # expect(game.dice_cup.dice_count).to eq 10 # roll = game.turns.last.rolls.last # expect(roll.results.first).to be_a RabbitDice::Die # expect(roll.results.map &:type).to eq ['meat', 'meat', 'meat'] # end # xit "calculates score" do # rig_dice('meat') # play_move('roll_dice') # game = play_move('roll_dice') # expect(game.score_for 'Alice').to eq(6) # expect(game.score_for 'Bob').to eq(0) # expect(game.score_for 'Carl').to eq(0) # end # describe 'Overblasting' do # before do # # First give them some points # rig_dice('meat') # game = play_move('roll_dice') # expect(game.score_for 'Alice').to eq(3) # # Now really give it to 'em! # rig_dice('blast') # game = play_move('roll_dice') # end # xit "does not score when the player rolls three blasts" do # expect(game.score_for 'Alice').to eq(0) # end # xit "creates the next player's turn when the current player rolls three blasts" do # expect(game.turns.count).to eq(2) # expect(game.turns.last.player).to eq 'Bob' # end # end # xit "ends the turn if the current player chooses to do so" do # # First give them some points # rig_dice('meat') # game = play_move('roll_dice') # expect(game.current_player).to eq 'Alice' # expect(game.score_for 'Alice').to eq(3) # # Now end the turn # game = play_move('stop') # expect(game.turns.count).to eq(2) # expect(game.current_player).to eq 'Bob' # # Double check score # expect(game.score_for 'Alice').to eq(3) # expect(game.turns.first.score).to eq(3) # end # xit "declares a winner once someone gets 13 meat" do # # To make things interesting, let's pass the turn to Carl # 2.times { play_move('stop') } # # Win that game # rig_dice('meat') # # 3meat x 4 = 12meat # 4.times { play_move('roll_dice') } # # 12 + 3 = 15 # game = play_move('roll_dice') # expect(game.winner).to eq 'Carl' # end # xit "ends the turn when there are no more dice left to draw" do # rig_dice('meat') # # 3meat x 4 = 12meat # 4.times { play_move('roll_dice') } # expect(game.current_player).to eq 'Alice' # expect(game.dice_cup.dice_count).to eq 1 # # Avoid three blasts to avoid (wrongly) ending the turn by death # # Wrongly because there should only be one die rolled # rig_dice('blast', 'blast', 'paws') # turn = game.turns.last # game = play_move('roll_dice') # expect(game.current_player).to eq 'Bob' # expect(game.dice_cup.dice_count).to eq 13 # end # xit "subtracts less dice from the cup when there are paws (runners)" do # rig_dice('paws') # game = play_move('roll_dice') # expect(game.dice_cup.dice_count).to eq 10 # game = play_move('roll_dice') # # Since all three dice were runners, we shouldn't need to draw more dice # expect(game.dice_cup.dice_count).to eq 10 # # Modify the last roll results to contain 2 paws instead of 3 # die = game.turns.last.rolls.last.results.last # die.type = 'meat' # game = play_move('roll_dice') # expect(game.dice_cup.dice_count).to eq 9 # end # end
true
7de2ca78911cf1e74db2997c5be8356cdabe6019
Ruby
stager94/poker-holdem
/spec/poker_spec.rb
UTF-8
1,194
2.65625
3
[]
no_license
require 'spec_helper' require './poker' describe Poker do before do @poker = Poker.new end it do expect(@poker.deck).to be_kind_of Deck expect(@poker.table).to be_kind_of Table expect(@poker.players.length).to eq 3 end context '#distribution_cards_to_players' do it do expect { @poker.send :distribution_cards_to_players }.to change { [@poker.players[0].cards.length, @poker.players[1].cards.length, @poker.players[2].cards.length] }.from([0,0,0]).to([2,2,2]) end end context '#distribution_cards_table_flop' do it do expect { @poker.send :distribution_cards_table_flop }.to change { @poker.table.cards.length }.from(0).to(3) end end context '#distribution_cards_table_turn' do before { @poker.send :distribution_cards_table_flop } it do expect { @poker.send :distribution_cards_table_turn }.to change { @poker.table.cards.length }.from(3).to(4) end end context '#distribution_cards_table_river' do before do @poker.send :distribution_cards_table_flop @poker.send :distribution_cards_table_turn end it do expect { @poker.send :distribution_cards_table_river }.to change { @poker.table.cards.length }.from(4).to(5) end end end
true
0e655123b40d7fd263d0fb75bc61f49a7b7057f6
Ruby
iref/housekeeper-archived
/test/circle_test.rb
UTF-8
6,223
2.515625
3
[ "MIT" ]
permissive
require "test_helper" describe Housekeeper::Circle do before do @circles = Housekeeper::mongo["circles"] @users = Housekeeper::mongo["users"] token = Housekeeper::GoogleToken.new "abcsd", "accessthis", 1234, Time.at(765432109) @userB = Housekeeper::User.new "octomama@github.com", token @userB.save end after do @circles.remove() @users.remove() end subject do token = Housekeeper::GoogleToken.new "abcsd", "accessthis", 1234, Time.at(765432109) user = Housekeeper::User.new "octo@github.com", token user.save item = Housekeeper::ShoppingItem.new "Octocat sticker", "12321asda", 2 list = Housekeeper::ShoppingList.new Time.new(2014, 2, 1), "GitHub Store", [item] circle = Housekeeper::Circle.new "Octocat Truthful", "The True Octocat lovers", user.id circle.shopping_lists = [list] circle end describe "save" do it "saves circle to database" do saved = subject.save circle = @circles.find({"_id" => BSON::ObjectId.from_string(saved.id)}).first saved.name.must_equal circle["name"] saved.description.must_equal circle["description"] saved.moderator.must_equal circle["moderator"] saved.shopping_lists.zip(circle["shopping_lists"]).each do |(actual, expected)| actual.date.gmtime.must_equal expected["date"] actual.shop.must_equal expected["shop"] actual.items.zip(expected["items"]).each do |(ai, ei)| ai.name.must_equal ei["name"] ai.requestor.must_equal ei["requestor"] ai.amount.must_equal ei["amount"] end end end it "saves circle without shopping lists" do subject.shopping_lists = nil saved = subject.save circle = @circles.find({"_id" => BSON::ObjectId.from_string(saved.id)}).first saved.name.must_equal circle["name"] saved.description.must_equal circle["description"] saved.moderator.must_equal circle["moderator"] circle["shopping_lists"].must_be_empty end it "sets circle id" do saved = subject.save saved.wont_be_nil saved.id end it "returns self" do saved = subject.save saved.must_be_same_as subject end end describe "update" do before do subject.save end it "updates circle in database" do subject.name = "Octocat" subject.description = "Shopping awesome octocat stuff" subject.update circle = @circles.find({"_id" => BSON::ObjectId.from_string(subject.id)}).first subject.name.must_equal circle["name"] subject.description.must_equal circle["description"] subject.moderator.must_equal circle["moderator"] end it "returns itself" do updated = subject.update updated.must_be_same_as subject end it "updates circle with members" do subject.members = [@userB] subject.update circle = @circles.find({"_id" => BSON::ObjectId.from_string(subject.id)}).first subject.name.must_equal circle["name"] subject.description.must_equal circle["description"] subject.moderator.must_equal circle["moderator"] subject.members[0].id.must_equal circle["members"][0] subject.members = [] previous_moderator = subject.moderator subject.update circleB = @circles.find({"_id" => BSON::ObjectId.from_string(subject.id)}).first previousModerator = subject.moderator subject.name.must_equal circleB["name"] subject.description.must_equal circleB["description"] subject.moderator.must_equal circleB["moderator"] subject.moderator.must_equal previous_moderator circleB["members"].must_be_empty end it "updates circle without shopping lists" do subject.shopping_lists = nil subject.update circle = @circles.find({"_id" => BSON::ObjectId.from_string(subject.id)}).first subject.name.must_equal circle["name"] subject.description.must_equal circle["description"] subject.moderator.must_equal circle["moderator"] circle["shopping_lists"].must_be_empty end end describe "find" do before do subject.save end it "returns existing circle with given id" do found = Housekeeper::Circle.find(subject.id) found.name.must_equal subject.name found.description.must_equal subject.description found.moderator.must_equal subject.moderator found.shopping_lists.zip(subject.shopping_lists).each do |(f, e)| f.date.gmtime.must_equal e.date.gmtime f.shop.must_equal e.shop f.items.zip(e.items).each do |(fi, ei)| fi.name.must_equal ei.name fi.amount.must_equal ei.amount fi.requestor.must_equal ei.requestor end end end it "should return existing circle even if it doesn't contains shopping lists" do subject.shopping_lists = nil subject.update found = Housekeeper::Circle.find(subject.id) found.name.must_equal subject.name found.description.must_equal subject.description found.moderator.must_equal subject.moderator found.shopping_lists.must_be_empty end it "returns nil if circle does not exist" do found = Housekeeper::Circle.find("507f1f77bcf86cd799439011") found.must_be_nil end end describe "remove" do before do subject.save end it "removes circle from collection" do Housekeeper::Circle.remove(subject.id) data = @circles.find({"_id" => subject.id}) data.has_next?.must_equal false end end describe "find_by_moderator" do before do subject.save end it "finds circles of given moderator" do actual = Housekeeper::Circle.find_by_moderator(subject.moderator) actual.size.must_equal 1 found = actual[0] found.id.must_equal subject.id found.name.must_equal subject.name found.description.must_equal subject.description found.moderator.must_equal subject.moderator end it "returns empty array for moderator that does not exist" do actual = Housekeeper::Circle.find_by_moderator("octo mama") actual.must_be_empty end end end
true
d78e75d47ec84f551b3127f6a3493e88cf75cefc
Ruby
davidmjiang/tag_crawler
/spec/web_scraper_spec.rb
UTF-8
1,511
2.75
3
[ "MIT" ]
permissive
require 'spec_helper' describe TagCrawler do let(:scraper){TagCrawler::WebScraper.new("test")} let(:html_doc){Nokogiri::HTML('<html><head><link rel="stylesheet" href="styles.css"/></head><body><a href="link">Link</a><a href="link2">Here\'s another link</a></body>')} let(:html_string){'<html><head><link rel="stylesheet" href="styles.css"/></head><body><a href="link">Link</a><a href="link2">Here\'s another link</a></body>'} describe '#get_links' do before do HTTParty.stub(:get).and_return(double("response", :body => html_string)) end it 'gets all the links on the page' do expect(scraper.get_links.length).to eq(2) end it "returns the href attribute for each link" do expect(scraper.get_links[0]).to eq("link") end end describe '#get_tags' do before do HTTParty.stub(:get).and_return(double("response", :body => html_string)) end it 'gets all tags' do expect(scraper.get_tags).to eq(["<html>", "<head>", "<link>", "</link>", "</head>", "<body>","<a>", "</a>", "<a>", "</a>", "</body>"]) end end describe '#get_sequences' do let(:html_string2){'<html><head><title>Title of Page</title</head><body><h1>Leadership</h1><p>CEO <span>John Boss</span></p><p>CTO Foo Bar</p></body>'} before do HTTParty.stub(:get).and_return(double("response", :body => html_string2)) end it 'should return a collection of sequences each at least two or more words and each word capitalized' do expect(scraper.get_sequences). to eq(["John Boss", "CTO Foo Bar"]) end end end
true
35c408ff4f70dc66e0dcc7839d5886404da0210a
Ruby
Touklakos/Hashi
/Sauvegarde/Grille.rb
UTF-8
3,705
3.515625
4
[]
no_license
require "matrix" # Cette classe represente une grille. class Grille #@longueur -> Sa longueur. #@largeur -> La largeur. #@table -> la matrice. #@sommets -> Sa liste de sommets. # Creer une grille. # === Parametre # * +longueur+ : Longueur de la grille (nombre de case). # * +largeur+ : Largeur de la grille (nombre de case). def self.creer(longueur, largeur) objet = new(longueur, largeur) objet.completerInitialize() return objet end # Privatise le new. private_class_method :new # Initialisation de la classe Grille. # === Parametre # * +longueur+ : Longueur de la grille (nombre de case). # * +largeur+ : Largeur de la grille (nombre de case). def initialize(longueur, largeur) @longueur = longueur @largeur = largeur @table = Matrix.build(@longueur, @largeur){|row, col| Case.new(row, col)} @sommets = Array.new() @aretes = Array.new() end # Accesseur get et set sur l'attribut table et sommets. attr_accessor :table, :sommets attr_reader :longueur, :largeur # Complete le initialize. def completerInitialize() for i in 0...@longueur do for j in 0...@largeur do @table[i, j].setGrille(self) end end end # Renvoie la case en x, y. # === Return # * +case+ : case La case correspondante. def getCase(x, y) return @table[x, y] end # Ajoute le sommet a la liste de sommet. def addSommet(sommet) @sommets.push(sommet) end # Ajoute l'arrete a la liste d'arete. def addArete(arete) @aretes.push(arete) end # Retire une arete de la liste de ses aretes. def retirerSommet(sommet) @sommets.delete(sommet) end # Retire une arete de la liste de ses aretes. def retirerArete(arete) @aretes.delete(arete) end #SUPPRIME TOUTES les aretes de la grille. def clearAretes() @listeArete.each{ |arete| arete.supprimer() } end # Renvoie le nombre de sommets dans la grille. # === Return # * +@sommets.count()+ : @sommets.count() Le nombre de sommets dans la grille. def nbSommets() return @sommets.count() end # Cette methode calcule si il y a un chemin hamiltonien dans la grille. # === Return # * +boolean+ : boolean Le resultat de l'evaluation. def testHamilton() marque = Hash.new(false) stack = Array.new() stack.push(@sommets.first) while !stack.empty? do temp = stack.shift temp.getVoisins().each do |v| if(marque[v] == false) then stack.push(v) end end marque[temp] = true end if(marque.count != self.nbSommets()) then return false else return true end end # Cette methode redefini to_s pour afficher une grille. def to_s() s = "" ajout = false 0.upto(@longueur - 1) do |i| 0.upto(@largeur - 1) do |j| @sommets.each do |x| if(x.position.x == i && x.position.y == j) s += x.valeur.to_s() ajout = true end end @aretes.each do |x| #p x.getListeCase() x.getListeCase().each do |y| if(y.x == i && y.y == j) s += "|" ajout = true end end end if(ajout == false) s += "X" end ajout = false end s += "\n" end return s + "\n" end # Affiche la grille. def afficher() 0.upto(@largeur + 1) do print("$") end print("\n$") @table.each{|c| if((c.y)+1 >= @largeur) c.afficher print("$\n$") else c.afficher end } 0.upto(@largeur - 1) do print("$") end puts("$") end end
true
aa7b999547403449313498aaaecc5d009bfd517c
Ruby
karanvalecha/twitter_clone
/test/models/user_test.rb
UTF-8
2,602
2.625
3
[]
no_license
require 'test_helper' class UserTest < ActiveSupport::TestCase def setup @user = User.new(name: "example", email: "example@example.com", password: "password", password_confirmation: "password" ) end test "Error for nil digest" do assert_not @user.authenticated?(:remember, '') end test "User must be valid" do assert @user.valid? end test "User name has to be present" do xxx = ["", " ", " "] xxx.each do |x| @user.name = x assert_not @user.valid? end end test "User email must be valid" do xxx = ["", " ", " "] xxx.each do |x| @user.email = x assert_not @user.valid? end end test "Name too long" do @user.name = "a"*51 assert_not @user.valid? end test "Email too long" do @user.email = "a"*244 + "@example.com" assert_not @user.valid? end test "email validation should accept valid addresses" do valid_addresses = %w[user@example.com USER@foo.COM A_US-ER@foo.bar.org first.last@foo.us alice+bob@baz.in] valid_addresses.each do |valid_address| @user.email = valid_address assert @user.valid?, "#{valid_address.inspect} should be valid" end end test "email validation should reject invalid addresses" do invalid_addresses = %w[user@example,com user_at_foo.org user.name@example. foo@bar_baz.com foo@bar+baz.com] invalid_addresses.each do |invalid_address| @user.email = invalid_address assert_not @user.valid?, "#{invalid_address.inspect} should be invalid" end end test "No duplicates allowed" do dup = @user.dup dup.email = @user.email.upcase @user.save assert_not dup.valid? end test "password cannot be blank" do @user.password = @user.password_confirmation = " "*6 assert_not @user.valid? end test "password minimum length" do @user.password = @user.password_confirmation = "a"*5 assert_not @user.valid? end test "Email Must be downcased before save!" do mix = "AbCjsndE@ExAmPle.CoM" @user.email = mix @user.save assert_equal mix.downcase, @user.reload.email end test "destroy microposts at user deletion" do @user.save @user.microposts.create!(content: "Lorem Ipsum") assert_difference 'Micropost.count', -1 do @user.destroy end end test "follow and unfollow" do karan = users(:karan) test = users(:test) assert_not karan.following?(test) karan.follow(test) assert karan.following?(test) assert test.followers.include?(karan) karan.unfollow(test) assert_not karan.following?(test) end end
true
8108c1947f6b13ccb09e88e762935144fca5bbfe
Ruby
kellypowers/ruby-objects-has-many-through-lab-onl01-seng-ft-012120
/lib/doctor.rb
UTF-8
561
3.21875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Doctor attr_accessor :name @@all = [] def initialize(name) @name = name @@all << self end def self.all @@all end def appointments Appointment.all.select{|i| i.doctor == self} end def new_appointment(patient, date) new_appointment = Appointment.new(date, patient, doctor=self) #puts " in Dr. class, date is #{date} patient is #{patient} doctor is #{doctor}" new_appointment end def patients appointments.map{|i| i.patient} end end
true
0cbe7e469ecc45ceb35c2f738a9b7fa9d0ececab
Ruby
bhuelbue/yamanalysis
/yam_thread_img.rb
UTF-8
9,777
2.6875
3
[]
no_license
require 'date' require 'optparse' require './yam_config.rb' require './lib/yam_database.rb' require './lib/yam_getUserPhoto.rb' def shortName(name) nname = name nname = nname[0, 8] if name.length > 8 nname = nname.gsub("-", '') return nname end def writeGraphvizLabelByName(f, name) gvlabel = "label=\"\", shape=\"box\", width=.5, height=.5, image=" users = Yuser.find :all, :select => "yamid, mugshot_url", :conditions => "name = '#{name}'", :limit => 1 users.each do |user| imgfile = "#{$YAM_IMG_PATH}/#{user.yamid}.jpg" getYamImage(user.yamid, imgfile, user.mugshot_url) unless File::exists?(imgfile) nname = shortName(name) nnode = " #{nname} [#{gvlabel}\"#{imgfile}\"];" f.write "#{nnode}\n" end end #------------------------------------------------------------------------------# # Yesterday's Thread Analysis # #------------------------------------------------------------------------------# date = DateTime.now - 1 dayfrom = date.strftime("%Y-%m-%d") date = date + 1 dayto = date.strftime("%Y-%m-%d") OPTIONS = { :dayfrom => dayfrom, :dayto => dayto } ARGV.options do |o| script_name = File.basename($0) o.banner = "Usage: #{script_name} [OPTIONS]" o.define_head "Create Yammer Thread Analysis" o.separator "[-ft] options yyyy-mm-dd" o.on("-f", "--from=yyyy-mm-dd", String, "Select the starting date") { |fromdate| OPTIONS[:dayfrom] = fromdate } o.on("-t", "--to=yyyy-mm-dd", String, "Select the end date") { |todate| OPTIONS[:dayto] = todate } o.on_tail("-h", "--help", "Show this help message.") { puts o; exit } o.separator "" o.parse! end dayfrom = OPTIONS[:dayfrom] dayto = OPTIONS[:dayto] puts "Between #{dayfrom} and #{dayto} ..." #------------------------------------------------------------------------------# # Connect to the database # #------------------------------------------------------------------------------# t0 = Time.new activerecord_connect #------------------------------------------------------------------------------# # Fetch all thread_id's within a time frame # #------------------------------------------------------------------------------# @cntthreads = Hash.new 0 @dailythreads = Ymessage.find :all, :select => "yamid, sender_id, thread_id", :conditions => "DATE(created_at) BETWEEN '#{dayfrom}' AND '#{dayto}'", :order => 'thread_id DESC' @dailythreads.each do |m| @cntthreads[m.thread_id] += 1 end puts "%d threads found between %s and %s" % [ @dailythreads.length, dayfrom, dayto ] #------------------------------------------------------------------------------# # Fetch all message_id's and sender_id's within each thread_id # #------------------------------------------------------------------------------# @usr2yamids = Hash.new @usr2sndids = Hash.new @dailythreads.each do |m| # Global Unique Message Id @dailymsgs = Ymessage.find :all, :select => "yamid, sender_id", :conditions => "thread_id = '#{m.thread_id}'" @dailymsgs.each do |m| usrs = Yuser.find :all, :select => "name", :conditions => "yamid = #{m.sender_id}" # Global Unique User Id ? usrs.each do |usr| @usr2yamids[m.yamid] = usr.name @usr2sndids[m.sender_id] = usr.name end end end puts "%d yamids (messages)" % @usr2yamids.length puts "%d senderids (people)" % @usr2sndids.length #------------------------------------------------------------------------------# # Generate edges # #------------------------------------------------------------------------------# @edges = Hash.new @toyam = Hash.new @cntthreads.keys.sort.reverse.each do |k| @threadmsgs = Ymessage.find :all, :conditions => "thread_id = '#{k}' AND DATE(created_at) <= '#{dayto}'", :order => 'created_at ASC' @threadmsgs.each do |t| unless @usr2yamids[t.replied_to_id].nil? # We have a conversation if @usr2sndids[t.sender_id].nil? # We have a missing sender_id in the User table puts t.inspect else edge_key = "#{@usr2sndids[t.sender_id]}-#{@usr2yamids[t.replied_to_id]}" unless @edges.has_key?(edge_key) @edges[edge_key] = "#{@usr2sndids[t.sender_id]} -> #{@usr2yamids[t.replied_to_id]}" puts "#{@edges[edge_key]};" if $YAM_VERBOSE end end else # Initial Message in Yammer if @usr2sndids[t.sender_id].nil? # We have a missing sender_id in the User table puts t.inspect else edge_key = "#{@usr2sndids[t.sender_id]}-yammer" unless @toyam.has_key?(edge_key) @toyam[edge_key] = "#{@usr2sndids[t.sender_id]} -> yammer" puts "#{@toyam[edge_key]};" if $YAM_VERBOSE end end end end end puts "%d initial posts" % @toyam.length puts "%d relations" % @edges.length #------------------------------------------------------------------------------# # Write the Graphviz .gv file # #------------------------------------------------------------------------------# gv_name = "#{$YAM_GRAPH_PATH}/thread_analysis_#{dayfrom}_#{dayto}.gv" gv_start = "digraph g {\n size=\"8,8\";\n ratio=\"fill\";\n rankdir=\"LR\";\n\n" gv_end = "\n}" fgv = File.open(gv_name, 'w') fgv.write gv_start @edges.keys.sort.each do |k| f = @edges[k].split("->") source_name = shortName(f[0].strip) target_name = shortName(f[1].strip) writeGraphvizLabelByName(fgv, f[0].strip) writeGraphvizLabelByName(fgv, f[1].strip) edge = " #{source_name} -> #{target_name}" fgv.write "#{edge};\n" end fgv.write gv_end fgv.close puts "GV File '#{gv_name}' created." #------------------------------------------------------------------------------# # Run all the Graphviz programs using the generated .gv file # #------------------------------------------------------------------------------# ["dot", "fdp", "sfdp", "twopi", "circo", "neato"].each do |grf| pngx = "_#{grf}.png" png_name = gv_name.gsub('.gv', pngx) cmdline = "#{grf} -Tpng -o #{png_name} #{gv_name}" system(cmdline) puts "PNG file is '#{png_name}'" end #------------------------------------------------------------------------------# # Write the Cytoscape .txt file # #------------------------------------------------------------------------------# cyto_name = "#{$YAM_GRAPH_PATH}/cyto_#{dayfrom}_#{dayto}.txt" fcyto = File.open(cyto_name, 'w') @toyam.keys.sort.each do |k| f = @toyam[k].split("->") source_name = shortName(f[0].strip) target_name = shortName(f[1].strip) edge = "#{source_name} #{target_name}" fcyto.write "#{edge}\n" end @edges.keys.sort.each do |k| f = @edges[k].split("->") source_name = shortName(f[0].strip) target_name = shortName(f[1].strip) edge = "#{source_name} #{target_name}" fcyto.write "#{edge}\n" end fcyto.close puts "Cytoscape File '#{cyto_name}' created." #------------------------------------------------------------------------------# # Write Gephi MySQL DDL for tables: nodes and edges # #------------------------------------------------------------------------------# gephi_sql = <<-EOT DROP TABLE IF EXISTS `nodes`; CREATE TABLE IF NOT EXISTS `nodes` ( `id` varchar(10) NOT NULL, `label` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; DROP TABLE IF EXISTS `edges`; CREATE TABLE IF NOT EXISTS `edges` ( `source` varchar(10) NOT NULL, `target` varchar(10) NOT NULL, `weight` double NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; EOT gephi_name = "#{$YAM_GRAPH_PATH}/gephi_#{dayfrom}_#{dayto}.sql" fgephi = File.open(gephi_name, 'w') fgephi.write gephi_sql gephi_nodes = Hash.new 0 @toyam.keys.sort.each do |k| f = @toyam[k].split("->") source_name = shortName(f[0].strip) target_name = shortName(f[1].strip) gephi_nodes[source_name] += 1 gephi_nodes[target_name] += 1 end @edges.keys.sort.each do |k| f = @edges[k].split("->") source_name = shortName(f[0].strip) target_name = shortName(f[1].strip) gephi_nodes[source_name] += 1 gephi_nodes[target_name] += 1 end insert_nodes = "INSERT INTO `nodes` (`id`, `label`) VALUES\n" fgephi.write insert_nodes node_names = Hash.new insert_data = '' nn = 0 gephi_nodes.each_key do |k| node_names[k] = "n%d" % nn insert_data += "('n%d', '#{k}'),\n" % nn nn += 1 end insert_data = insert_data.chomp insert_data = insert_data.chop + ";\n\n" fgephi.write insert_data insert_edges = "INSERT INTO `edges` (`source`, `target`, `weight`) VALUES\n" fgephi.write insert_edges insert_data = '' @toyam.keys.sort.each do |k| f = @toyam[k].split("->") source_name = shortName(f[0].strip) target_name = shortName(f[1].strip) insert_data += "('#{source_name}', '#{target_name}', 0.0),\n" end @edges.keys.sort.each do |k| f = @edges[k].split("->") source_name = shortName(f[0].strip) target_name = shortName(f[1].strip) insert_data += "('#{source_name}', '#{target_name}', 0.0),\n" end insert_data = insert_data.chomp insert_data = insert_data.chop + ";" fgephi.write insert_data fgephi.close puts "Gephi File '#{gephi_name}' created." #------------------------------------------------------------------------------# # Load Gephi tables into the MySQL db # #------------------------------------------------------------------------------# cmdline = "mysql yam_development < #{gephi_name} -u #{$YAM_DB_USR} -p#{$YAM_DB_PWD}" puts "mysql yam_development < #{gephi_name} running ..." system(cmdline) t1 = Time.new puts "Duration %.4f sec." % [t1 - t0]
true
6f823cb93427938c7c82ec1f0081f692aef278bd
Ruby
tltaylor22/tic_tac_toe
/random_ai.rb
UTF-8
422
3.203125
3
[]
no_license
class Random_AI attr_reader :marker # a reader attribute to read marker def initialize(marker) @marker = marker # the @ symbol is an instance variable that can be used anywhere within the instance of the class end def get_move(board) # passing the index of each element in the array and then selecting empty index positions board.each_index.select{ |empty| board[empty]==' '}.sample end end
true
4a94d2a335571a31f2b2611001fc7afa43e7c579
Ruby
zzeni/academy-app
/lib/error/not_eligible_for_course_error.rb
UTF-8
222
2.515625
3
[ "MIT" ]
permissive
require_relative './application_error.rb' module Error class NotEligibleForCourseError < ApplicationError def initialize(message = "The chosen course is too difficult for the student") super end end end
true
f6a3a315e5195584b9805ee695b10ac4ca8aa48d
Ruby
postmodern/deployml
/lib/deployml/remote_shell.rb
UTF-8
3,525
3.109375
3
[ "MIT" ]
permissive
require 'deployml/exceptions/invalid_config' require 'deployml/shell' require 'addressable/uri' module DeploYML # # Represents a shell running on a remote server. # class RemoteShell < Shell # The history of the Remote Shell attr_reader :history # # Initializes a remote shell session. # # @param [Addressable::URI, String] uri # The URI of the host to connect to. # # @param [Environment] environment # The environment the shell is connected to. # # @yield [session] # If a block is given, it will be passed the new remote shell session. # # @yieldparam [ShellSession] session # The remote shell session. # def initialize(uri,environment=nil,&block) @history = [] super(uri,environment,&block) replay if block end # # Enqueues a program to be ran in the session. # # @param [String] program # The name or path of the program to run. # # @param [Array<String>] arguments # Additional arguments for the program. # def run(program,*arguments) @history << [program, *arguments] end # # Adds a command to be executed. # # @param [String] command # The command string. # # @since 0.5.2 # def exec(command) @history << [command] end # # Enqueues an `echo` command to be ran in the session. # # @param [String] message # The message to echo. # def echo(message) run 'echo', message end # # Enqueues a directory change for the session. # # @param [String] path # The path of the new current working directory to use. # # @yield [] # If a block is given, then the directory will be changed back after # the block has returned. # def cd(path) @history << ['cd', path] if block_given? yield @history << ['cd', '-'] end end # # Joins the command history together with ` && `, to form a # single command. # # @return [String] # A single command string. # def join commands = [] @history.each do |command| program = command[0] arguments = command[1..-1].map { |word| shellescape(word.to_s) } commands << [program, *arguments].join(' ') end return commands.join(' && ') end # # Converts the URI to one compatible with SSH. # # @return [String] # The SSH compatible URI. # # @raise [InvalidConfig] # The URI of the shell does not have a host component. # def ssh_uri unless @uri.host raise(InvalidConfig,"URI does not have a host: #{@uri}",caller) end new_uri = @uri.host new_uri = "#{@uri.user}@#{new_uri}" if @uri.user return new_uri end # # Starts a SSH session with the destination server. # # @param [Array] arguments # Additional arguments to pass to SSH. # def ssh(*arguments) options = [] # Add the -p option if an alternate destination port is given if @uri.port options += ['-p', @uri.port.to_s] end # append the SSH URI options << ssh_uri # append the additional arguments arguments.each { |arg| options << arg.to_s } return system('ssh',*options) end # # Replays the command history on the remote server. # def replay ssh(self.join) unless @history.empty? end end end
true
f7e5ba79a1dbe49b470ba5ef54f16fc2173a3e7f
Ruby
readyready15728/advent-of-code-2020
/07a.rb
UTF-8
1,552
3.3125
3
[]
no_license
require 'set' bag_descriptions = [] File.readlines('07.txt').each do |line| bag_type = line.match('\A(.*?) bags')[1] contents = [] unless line.match('contain no other bags') line.scan(/(\d+) (.*?) bags?/).each do |count, color| contents.push [color, count] end end bag_descriptions.push({"bag_type" => bag_type, "contents" => contents.to_h}) end def scan_for_possible_containers(bag_descriptions, previous_possible_containers) new_containers = Set.new bag_descriptions.each do |bag_description| # Direct container of shiny gold bags if bag_description['contents'].include? 'shiny gold' # Don't need to check if already present because Set class is used new_containers.add bag_description['bag_type'] end # Indirect containers of shiny gold bags unless previous_possible_containers.intersection(Set.new bag_description['contents'].keys).empty? # Again, no need to check if already present new_containers.add bag_description['bag_type'] end end new_containers end previous_possible_containers = Set.new # Initial scan current_possible_containers = scan_for_possible_containers(bag_descriptions, previous_possible_containers) # Keep iterating until all possible choices are exhausted until previous_possible_containers == current_possible_containers previous_possible_containers = current_possible_containers current_possible_containers = scan_for_possible_containers(bag_descriptions, previous_possible_containers) end puts current_possible_containers.length
true
a6f485a794fd166f4f1b1e015d08a7e5a3ddb1e5
Ruby
shvets/misc-ruby
/check_gem_deps2.rb
UTF-8
447
2.609375
3
[]
no_license
require 'rubygems' require 'httparty' class RubyGemsApi include HTTParty base_uri 'rubygems.org' def self.info_for(gems) res = get('/api/v1/dependencies', :query => { :gems => gems }) Marshal.load(res) end def self.display_info_for(gems) info_for(gems).each do |info| puts "#{info[:name]} version #{info[:number]} dependencies: #{info[:dependencies].inspect}" end end end RubyGemsApi.display_info_for(ARGV[0])
true
cfa58550326353fcd65dbe5eae0c6c101930c92b
Ruby
svetlik/Core-Ruby-1
/week2/1-vectors/vector_solution_test.rb
UTF-8
1,807
3.140625
3
[ "MIT" ]
permissive
require 'minitest/autorun' require_relative 'vector_solution' class SolutionTest < Minitest::Test def test_length vector = Vector.new(3, 4, 5, 6) assert_equal 86**0.5, vector.length end def test_magnitude vector = Vector.new(3, 4, 5, 6) assert_equal 86**0.5, vector.magnitude end def test_normalize vector = Vector.new(3, 4, 5, 6) assert_equal [ Rational(3, 86**0.5), 2 * (Rational(2, 43)**0.5), Rational(5, 86**0.5), 3 * (Rational(2, 43)**0.5) ], vector.normalize end def test_equal vector = Vector.new(3, 4, 5, 6) another_vector = Vector.new(3, 4, 5, 6) unequal_vector = Vector.new(4, 5, 6, 7) assert_equal true, vector == another_vector assert_equal false, vector == unequal_vector end def test_add vector = Vector.new(3, 4, 5, 6) number = 5 another_vector = Vector.new(4, 5, 6, 7) assert_equal [8, 9, 10, 11], vector + number assert_equal [7, 9, 11, 13], vector + another_vector end def test_subtract vector = Vector.new(3, 4, 5, 6) number = 3 another_vector = Vector.new(4, 5, 6, 7) assert_equal [0, 1, 2, 3], vector - number assert_equal [-1, -1, -1, -1], vector - another_vector end def test_multiply vector = Vector.new(3, 4, 5, 6) number = 3 assert_equal [9, 12, 15, 18], vector * number end def test_divide vector = Vector.new(3, 4, 5, 6) number = 3 assert_equal [1, 4 / 3, 5 / 3, 2], vector / number end def test_to_s vector = Vector.new(3, 4, 5, 6, 7) string = "Vector ([3, 4, 5, 6, 7]) with object_id: #{vector.object_id}" assert_equal string, vector.to_s end def test_inspect vector = Vector.new(3, 4, 5, 6) assert_equal true, vector.inspect.include?(vector.object_id) end end
true
fcbaaf9f33601d4472f93a1487f48fd705dceb42
Ruby
Dorish/DataDriven
/Tools/IE/del_cache.rb
UTF-8
4,395
2.578125
3
[]
no_license
#!/bin/ruby # # # # # # set TEMPIF=%USERPROFILE%\Local Settings\Temporary Internet Files # %TEMPIF%\Content.IE5\Index.DAT #TODO This file needs to be cleaned up require 'Win32API' # # # HashMethods = a Hash that can be accessed with methods # e.g. h = MethodHash.new # h['street'] = 'Broadway' # h.street = 'Broadway' # puts h.street ===> Broadway require 'delegate' class MethodHash < SimpleDelegator def initialize h = {} super h end def method_missing(method_name, *args) name = method_name.to_s if name.ends_with?('=') self[ name.chop ] = args[0] else self[ name ] end end end class String def ends_with?(substr) len = substr.length self.reverse() [0 .. len-1].reverse == substr end def starts_with?(substr) len = substr.length self[0 .. len-1] == substr end alias start_with? starts_with? alias begin_with? starts_with? alias begins_with? starts_with? alias end_with? ends_with? # String each() operator reads line-by-line # These functions return characters def each_char self.each_byte{|x| yield x.chr } end def collect_char r = [] self.each_byte{|x| r << x.chr } r end end =begin // Windows System calls needed to clear cache. // BOOL DeleteUrlCacheEntry( LPCTSTR lpszUrlName ); HANDLE FindFirstUrlCacheEntry( LPCTSTR lpszUrlSearchPattern, LPINTERNET_CACHE_ENTRY_INFO lpFirstCacheEntryInfo, LPDWORD lpdwFirstCacheEntryInfoBufferSize ); BOOL FindNextUrlCacheEntry( HANDLE hEnumHandle, LPINTERNET_CACHE_ENTRY_INFO lpNextCacheEntryInfo, LPWORD lpdwNextCacheEntryInfoBufferSize ); BOOL FindCloseUrlCache( IN HANDLE hEnumHandle ); typedef struct _INTERNET_CACHE_ENTRY_INFO { DWORD dwStructSize; LPTSTR lpszSourceUrlName; LPTSTR lpszLocalFileName; DWORD CacheEntryType; DWORD dwUseCount; DWORD dwHitRate; DWORD dwSizeLow; DWORD dwSizeHigh; FILETIME LastModifiedTime; FILETIME ExpireTime; FILETIME LastAccessTime; FILETIME LastSyncTime; LPBYTE lpHeaderInfo; DWORD dwHeaderInfoSize; LPTSTR lpszFileExtension; union { DWORD dwReserved; DWORD dwExemptDelta; } } INTERNET_CACHE_ENTRY_INFO, *LPINTERNET_CACHE_ENTRY_INFO; =end def main w = get_api('wininet',FUNCS) i = 0 info,infosize = get_first_info(w) cache = w.FindFirstUrlCacheEntry.Call(nil,info,infosize) if cache != 0 begin len, source_file_ptr, local_file_ptr = info.unpack 'LLL' w.DeleteUrlCacheEntry.Call(source_file_ptr) i += 1 info,infosize = get_next_info( w, cache ) end while w.FindNextUrlCacheEntry.Call(cache, info, infosize) != 0 end w.FindCloseUrlCache.Call(cache) i end def get_first_info(api) sizenum = [0,0].pack('L*') buf = [1024,0].pack('L*').ljust(1024) r = api.FindFirstUrlCacheEntry.Call(nil,nil,sizenum) n = sizenum.unpack('L')[0] info = sizenum.ljust(n) [info,sizenum] end def get_next_info(api, handle) sizenum = [0,0].pack('L*') buf = [1024,0].pack('L*').ljust(1024) r = api.FindNextUrlCacheEntry.Call(handle,nil,sizenum) n = sizenum.unpack('L')[0] info = sizenum.ljust(n) [info,sizenum] end # # Win32 API used in this file is listed here. # Each system call can be instatiated like this # DeleteUrlCacheEntry = Win32API.new("wininet", "DeleteUrlCacheEntry", ['P'], 'V') # Instead, the functions are defined dynamically from this list: # FUNCS = { 'FindFirstUrlCacheEntry' => ['ppp','n'], 'FindNextUrlCacheEntry' => ['npp','n'], 'DeleteUrlCacheEntry' => ['n', 'n'], 'FindCloseUrlCache' => ['n', 'n'] } # # get_api returns a hash with Win32 API system calls # Usage: # api = get_api('Kernel32', {'GetLastError'=>['V', 'N'],...}) # def get_api(library, function_hash) f = MethodHash.new function_hash.each{|funcname,types| in_types = types[0].collect_char{|x| x} out_type = types[1] f[funcname] = Win32API.new(library, funcname, in_types, out_type) } f end def getLastError f = Win32API.new('Kernel32', 'GetLastError', ['V'], 'N') f.call end if __FILE__ == $0 n = main print "Deleted #{n} items\n" end
true
1d6383b8a1e6cb701506dd22a049eafe2b982a50
Ruby
Koyirox/s3_desafio_2arrays
/2.rb
UTF-8
1,114
3.796875
4
[]
no_license
a = [1,2,3,9,1,4,5,2,3,6,6] # Eliminar el último elemento puts 'arreglo original' p a a.delete_at(-1) puts 'elimina ultimo elemento del arreglo' p a #Eliminar el primer elemento. a.delete_at(0) puts 'elimina el primer elemento' p a #Eliminar el elemento que se encuentra en la posición media, si el arreglo tiene un número #par de elementos entonces remover el que se encuentre en la mitad izquierda. if (a.length).even? elimina=(a.length/2)/2 a.delete_at(elimina) puts 'elimina elemento que se encuentra en la posicion media, de la media en el lado izquierdo ' p a else elimina = a.length/2 a.delete_at(elimina) puts 'elimina elemento que se encuentra en la posicion media ' p a end #Borrar el último elemento mientras ese número sea distinto a 1. a.delete_at(-1) if a[-1] !=1 puts 'borra ultimo elemento siempre y cuando sea distinto de uno' p a #Utilizando un arreglo vacío auxiliar y operaciones de push and pop invertir el orden de los #elementos en un arreglo auxiliar=[] a.length.times do |i| aux = a.pop auxiliar.push(aux) end puts 'arreglo invertido ' p auxiliar
true
275a91d11efc73fb767530ead55dfe7b9d7540b7
Ruby
u2313nori/learning-Ruby
/Book01/Chapter02/2.8.3_ruby-sample.rb
UTF-8
234
2.625
3
[]
no_license
# encoding: utf-8 a = <<TEXT テストテストテストテストテスト テストテストテストテスト テストテストテスト テストテスト テスト TEXT puts a puts a.class def test a puts a end test "bbb"
true
a580bf987d8eb7f0d2b5ac349a2a1296569fcda9
Ruby
robbiejaeger/black_thursday
/lib/sales_analyst.rb
UTF-8
6,603
3.015625
3
[]
no_license
require 'time' require 'bigdecimal' require 'bigdecimal/util' class SalesAnalyst attr_reader :sales_engine def initialize(sales_engine) @se = sales_engine end def average_items_per_merchant (@se.items.all.count.to_f/@se.merchants.all.count.to_f).round(2) end def standard_deviation(set, avg) Math.sqrt(set.map do |set_item| (set_item - avg) ** 2 end.reduce(:+)/(set.count.to_f-1)).round(2) end def average_items_per_merchant_standard_deviation set = @se.merchants.all.map do |merchant| merchant.items.count end standard_deviation(set, average_items_per_merchant) end def merchants_with_high_item_count avg = average_items_per_merchant stdev = average_items_per_merchant_standard_deviation @se.merchants.all.find_all do |merchant| merchant.items.count > (avg + stdev) end end def average_item_price_for_merchant(merchant_id) merchant = @se.merchants.find_by_id(merchant_id) item_count = 0 (merchant.items.map do |item| item_count += 1 item.unit_price end.reduce(:+)/item_count).round(2) end def average_average_price_per_merchant (@se.merchants.all.map do |merchant| average_item_price_for_merchant(merchant.id) end.reduce(:+)/@se.merchants.all.count).round(2) end def golden_items stdev = item_price_standard_deviation avg = average_item_price @se.items.all.find_all {|item| item.unit_price > (avg + 2*stdev)} end def item_price_standard_deviation set = @se.items.all.map do |item| item.unit_price end standard_deviation(set, average_item_price) end def average_item_price @se.items.all.map do |item| item.unit_price end.reduce(:+)/@se.items.all.count end def average_invoices_per_merchant (@se.invoices.all.count.to_f / @se.merchants.all.count).round(2) end def average_invoices_per_merchant_standard_deviation set = @se.merchants.all.map do |merchant| merchant.invoices.count end standard_deviation(set, average_invoices_per_merchant) end def top_merchants_by_invoice_count avg = average_invoices_per_merchant std_dev = average_invoices_per_merchant_standard_deviation @se.merchants.all.find_all do |merchant| merchant.invoices.count > 2 * std_dev + avg end end def bottom_merchants_by_invoice_count avg = average_invoices_per_merchant std_dev = average_invoices_per_merchant_standard_deviation @se.merchants.all.find_all do |merchant| merchant.invoices.count < avg - 2 * std_dev end end def set_of_invoices_by_day set_of_invoices_by_day = Hash.new(0) @se.invoices.all.each do |invoice| set_of_invoices_by_day[invoice.created_at.strftime("%A")] += 1 end set_of_invoices_by_day end def avg_invoices_per_day set_of_invoices_by_day.values.reduce(:+)/7 end def standard_deviation_invoices_per_day set = set_of_invoices_by_day.values standard_deviation(set, avg_invoices_per_day) end def top_days_by_invoice_count std_dev = standard_deviation_invoices_per_day avg = avg_invoices_per_day set_of_invoices_by_day.select do |day, num| num > (std_dev + avg) end.map {|array| array[0] } end def total_invoices_shipped @se.invoices.all.count {|invoice| invoice.status == :shipped} end def total_invoices_pending @se.invoices.all.count {|invoice| invoice.status == :pending} end def total_invoices_returned @se.invoices.all.count {|invoice| invoice.status == :returned} end def invoice_status(status) total_invoices = @se.invoices.all.count if status == :pending (total_invoices_pending.to_f/total_invoices*100).round(2) elsif status == :shipped (total_invoices_shipped.to_f/total_invoices*100).round(2) elsif status == :returned (total_invoices_returned.to_f/total_invoices*100).round(2) end end def total_revenue_by_date(date) invoices = @se.invoices.all.find_all do |invoice| invoice.created_at.strftime("%Y-%m-%d") == date.strftime("%Y-%m-%d") end invoices.map do |invoice| invoice.total end.reduce(:+) end def top_revenue_earners(x = 20) all_merchants = @se.merchants.all merchant_invoices = all_merchants.map do |merchant| merchant.invoices end merchant_revenue = merchant_invoices.map do |invoices| invoices.map do |invoice| invoice.total end.reduce(:+) end merch_rev_in_order = all_merchants.zip(merchant_revenue).sort_by do |a| -a[1] end[0...x] merch_rev_in_order.map do |array| array[0] end end def merchants_ranked_by_revenue top_revenue_earners(@se.merchants.all.length) end def merchants_with_pending_invoices @se.invoices.all.find_all do |invoice| invoice.is_paid_in_full? == false end.map { |invoice| invoice.merchant }.uniq end def merchants_with_only_one_item @se.merchants.all.find_all { |merchant| merchant.items.count == 1 } end def merchants_with_only_one_item_registered_in_month(month) month_number = Date::MONTHNAMES.index(month.capitalize) merchants_with_only_one_item.find_all do |merchant| merchant.created_at.month == month_number end end def revenue_by_merchant(merchant_id) invoices = @se.merchants.find_all_invoices_by_merchant_id(merchant_id) invoices.map { |invoice| invoice.total }.reduce(:+) end def get_all_invoice_items_for_merchant(merchant_id) merchant = @se.merchants.find_by_id(merchant_id) invoices_paid = merchant.invoices.find_all do |invoice| invoice.is_paid_in_full? == true end invoices_paid.map do |invoice| @se.invoice_items.find_all_by_invoice_id(invoice.id) end.flatten end def most_sold_item_for_merchant(merchant_id) invoice_items = get_all_invoice_items_for_merchant(merchant_id) all_items = invoice_items.map do |invoice_item| [@se.items.find_by_id(invoice_item.item_id)]*invoice_item.quantity end.flatten all_items.group_by {|item| all_items.count(item)}.max[1].uniq end def best_item_for_merchant(merchant_id) invoice_items = get_all_invoice_items_for_merchant(merchant_id) grouped_invoice_items_times_quantity = invoice_items.map do |invoice_item| [invoice_item]*invoice_item.quantity end.flatten.group_by {|invoice_item| invoice_item.item_id} max_item_id = grouped_invoice_items_times_quantity.max_by do |k,v| v.map{|invoice_item| invoice_item.unit_price}.reduce(:+) end[0] @se.items.find_by_id(max_item_id) end end
true
2beefc3a57c8800f6cf2fc4d0be7c0a796862079
Ruby
mattkiernan/ruby
/leap.rb
UTF-8
259
3.484375
3
[]
no_license
puts 'provide a start year >>' start = gets.chomp puts 'provide an end year >>' finish = gets.chomp while start.to_i <= finish.to_i if start.to_f % 4 == 0 and (start.to_f % 100 != 0 or start.to_f % 400 != 0) puts start.to_i end start = start.to_i + 1 end
true
93b3750472554424642b9efe58b009c1c950ed3a
Ruby
violaleeblue/tealeaf-intro-to-programming-ruby
/methods.rb
UTF-8
603
4.5
4
[]
no_license
puts "exercise 1" def greet(name) puts "Hello " + name + "!" end puts greet('Mary') puts "exercise 2" puts "the integer 2" puts "nil" puts "Joe" puts "the string four" puts "nil" puts "exercise 3" def multiply(num1, num2) return num1 * num2 end puts "multiplying 4 times 5 is " + multiply(4,5).to_s puts "exercise 4" puts "it prints nothing, because the return occurs before the puts" puts "exercise 5" def scream(words) words = words + "!!!!" puts words end scream("woo") puts "it returns nil" puts "exercise 6" puts "two arguments were expected to the function, but only one was provided"
true
8a2de710aaafe73c13fd2d4ae12899e92840a5ac
Ruby
RaymondMcT/quandl_operation
/lib/quandl/operation/collapse.rb
UTF-8
8,583
2.75
3
[ "MIT" ]
permissive
# subclasses require 'quandl/operation/collapse/guess' # collapse module Quandl module Operation class Collapse class << self def perform(data, type) type = {:freq => type} if type.class != Hash assert_valid_arguments!(data, type) # nothing to do with an empty array return data unless data.compact.present? # source order order = Sort.order?(data) # operations expect data in ascending order data = Sort.asc(data) # collapse data = collapse(data, type[:freq], type[:algo]) # return to original order data = Sort.desc(data) if order == :desc # onwards data end def assert_valid_arguments!(data, type) raise ArgumentError, "data must be an Array. Received: #{data.class}" unless data.is_a?(Array) raise ArgumentError, "frequency must be one of #{valid_collapses}. Received: #{type[:freq]}" unless valid?(type[:freq]) raise ArgumentError, "algorithm must be one of #{valid_collapse_algos}. Received: #{type[:algo]}" unless type[:algo].nil? || valid_collapse_algo?(type[:algo]) end def valid_collapse?(type) valid?(type) end def valid?(type) valid_collapses.include?( type.try(:to_sym) ) end def valid_collapses [ :daily, :weekly, :monthly, :quarterly, :annual ] end def valid_collapse_algos [ :min, :max, :first, :last, :mid, :sum, :avg, :median ] end def valid_collapse_algo?(type) valid_collapse_algos.include?( type.try(:to_sym) ) end def collapse(data, frequency, algorithm) algorithm ||= :last return data unless valid_collapse?( frequency ) return data unless valid_collapse_algo?( algorithm ) # store the new collapsed data collapsed_data = {} data_in_range = {} case algorithm.to_sym when :min range = get_range( data[0][0], frequency ) data.each do |row| date, value = row[0], row[1..-1] range = get_range(date, frequency) unless inside_range?(date, range) collapsed_data[range] ||= value value.each_index do |a| collapsed_data[range][a] = value[a] if (collapsed_data[range][a].nil? && !value[a].nil?) || collapsed_data[range][a] > value[a] end end return(to_table(collapsed_data)) end when :max range = get_range( data[0][0], frequency ) data.each do |row| date, value = row[0], row[1..-1] range = get_range(date, frequency) unless inside_range?(date, range) collapsed_data[range] ||= value value.each_index do |a| collapsed_data[range][a] = value[a] if (collapsed_data[range][a].nil? && !value[a].nil?) || collapsed_data[range][a] < value[a] end end return(to_table(collapsed_data)) when :first range = get_range( data[-1][0], frequency ) Sort.desc(data).each do |row| # grab date and values date, value = row[0], row[1..-1] value = value.first if value.count == 1 # bump to the next range if it exceeds the current one range = get_range(date, frequency) unless inside_range?(date, range) # consider the value for the next range if inside_range?(date, range) && value.present? # merge this and previous row if nils are present value = merge_row_values( value, collapsed_data[range] ) unless collapsed_data[range].nil? # assign value collapsed_data[range] = value end end return(to_table(collapsed_data)) when :last range = find_end_of_range( data[0][0], frequency ) data.each do |row| # grab date and values date, value = row[0], row[1..-1] value = value.first if value.count == 1 # bump to the next range if it exceeds the current one range = find_end_of_range(date, frequency) unless inside_range?(date, range) # consider the value for the next range if inside_range?(date, range) && value.present? # merge this and previous row if nils are present value = merge_row_values( value, collapsed_data[range] ) unless collapsed_data[range].nil? # assign value collapsed_data[range] = value end end return(to_table(collapsed_data)) when :mid when :sum range = get_range( data[0][0], frequency ) data.each do |row| date, value = row[0], row[1..-1] range = get_range(date, frequency) unless inside_range?(date, range) data_in_range[range] ||= [] data_in_range[range] << value end data_in_range.each do |range, values| sum = Array.new(values.first.length, 0) values.each do |value| value.each_index do |index| sum[index] += value[index] unless value[index].nil? end end collapsed_data[range] = sum end return(to_table(collapsed_data)) when :avg range = get_range( data[0][0], frequency ) data.each do |row| date, value = row[0], row[1..-1] range = get_range(date, frequency) unless inside_range?(date, range) data_in_range[range] ||= [] data_in_range[range] << value end data_in_range.each do |range, values| avg = Array.new(values.first.length, 0) counter = Array.new(values.first.length, 0) values.each do |value| value.each_index do |index| avg[index] += value[index] unless value[index].nil? counter[index] += 1 unless value[index].nil? end end avg.each_index do |index| avg[index] = counter[index] == 0 ? nil : avg[index]/counter[index] end collapsed_data[range] = avg end return(to_table(collapsed_data)) when :median # data_in_range.each do |range, values| # avg = Array.new(values.first.length, 0) # counter = Array.new(values.first.length, 0) # values.each do |value| # value.each_index do |index| # avg[index] += value[index] unless value[index].nil? # counter[index] += 1 unless value[index].nil? # end # end # avg.each_index do |index| # avg[index] = counter[index] == 0 ? nil : avg[index]/counter[index] # end # collapsed_data[range] = avg # end # return(to_table(collapsed_data)) # iterate over the data end def to_table(data) data.collect do |date, values| date = date[1] if date.is_a?(Array) if values.is_a?(Array) values.unshift(date) else [date, values] end end end def merge_row_values(top_row, bottom_row) # merge previous values when nils are present if top_row.is_a?(Array) && top_row.include?(nil) # find nil indexes indexes = find_each_index(top_row, nil) # merge nils with previous values indexes.each{|index| top_row[index] = bottom_row[index] } end top_row end def collapses_greater_than(freq) return [] unless freq.respond_to?(:to_sym) index = valid_collapses.index(freq.to_sym) index.present? ? valid_collapses.slice( index + 1, valid_collapses.count ) : [] end def collapses_greater_than_or_equal_to(freq) return [] unless freq.respond_to?(:to_sym) valid_collapses.slice( valid_collapses.index(freq.to_sym), valid_collapses.count ) end def frequency?(data) Guess.frequency(data) end def inside_range?(date, range) if range.is_a?(Array) range[0] <= date && date <= range[1] else date <= range end end def get_range(date, frequency) [date.start_of_frequency(frequency), date.end_of_frequency(frequency)] end def find_end_of_range(date, frequency) date.end_of_frequency(frequency) end def find_start_of_range(date, frequency) date.start_of_frequency(frequency) end def find_each_index(array, find) found, index, q = -1, -1, [] while found found = array[index+1..-1].index(find) if found index = index + found + 1 q << index end end q end end end end end
true
e41c8d3106d75d097776d7b38e6bf0f8ac6630a2
Ruby
maciek-rr/misc
/reqlog.rb
UTF-8
1,331
2.671875
3
[]
no_license
require 'net/http' module ReqLog def self.hack_net_http_request!(opts={}) dest_dir = opts[:dest_dir] || "/tmp" klass = Net::HTTP unless klass.method_defined?(:request_without_logging) klass.send(:alias_method, :request_without_logging, :request) end klass.send(:define_method, :request) do |req, body=nil, &block| t = Time.now name_with_path = File.join(dest_dir, "log_request_#{[t.day,t.month,t.year].join("_")}_#{t.to_f}.txt") File.open(name_with_path, "w") do |f| f.puts("------>>>> Request >>") f.puts("Request start: #{t}") f.puts("#{req.method.upcase} #{@address}:#{@port}#{['/',req.path].uniq.join}") f.puts("Headers:") req.each_header { |k,v| f.puts(" #{k}: #{v}") } f.puts("\nBody: ", body ? body.force_encoding("UTF-8") : "(empty)") f.puts("<<<<<----- Response --") request_without_logging(req, body, &block).tap do |response| f.puts("Code: #{response.code}\nHeaders:") response.each_header { |k,v| f.puts(" #{k}: #{v}") } f.puts("\nBody:\n", response.body ? response.body.force_encoding("UTF-8") : "(empty)") f.puts("\n-------------\nTotal time: #{((Time.now.to_f - t.to_f) * 1000).round}ms") end end end end end ReqLog.hack_net_http_request!
true
970d8a1576158bf83b90739855c54a8a66f5b798
Ruby
StinaD/project_budget_tracker
/models/tag.rb
UTF-8
940
3.140625
3
[]
no_license
require( 'pry-byebug' ) require_relative('../db/sql_runner') class Tag attr_reader :id, :tag_name def initialize( options ) @id = options['id'].to_i if options['id'] @tag_name = options['tag_name'] end # class functions --------- def self.delete_all sql = "DELETE FROM tags;" SqlRunner.run( sql ) end def self.all sql = "SELECT * FROM tags ORDER BY tag_name ASC;" result = SqlRunner.run( sql ) return result.map { |tag| Tag.new(tag) } end def self.find(id) sql = "SELECT * FROM tags WHERE id = $1;" values = [id] result = SqlRunner.run( sql, values ) tag = Tag.new(result.first) return tag end # instance functions ------ def save() sql = "INSERT INTO tags ( tag_name ) VALUES ( $1 ) RETURNING *" values = [@tag_name] merchant = SqlRunner.run(sql, values) @id = merchant.first()['id'].to_i end end
true