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
57749122f7a002854848d2ec87468f81430d3c23
Ruby
teresa-m-knowles/backend_prework
/day_7/fizzbuzz.rb
UTF-8
605
4.59375
5
[]
no_license
puts "This program prints numbers in any range. For any number that is a multiple of 3, it prints 'Frizz'. For any number that is a multiple of 5, it prints 'Buzz'. For any number that is a multiple of both 3 and 5, it prints 'FizzBuzz'. For all other numbers, it prints the number " puts "If we start at 0, what's the highest number you would like to print towards?" x = gets.chomp.to_i y = x+1 y.times do |i| if i==0 print "" elsif i % 3 == 0 print "Fizz, " elsif i % 5 == 0 print "Buzz, " elsif i % 3 == 0 && i % 5==0 print "FizzBuzz, " else print "#{i}, " end end
true
0800856ab207faefea98eb28763dd184e04ca135
Ruby
spurton/dm-more
/dm-types/spec/unit/epoch_time_spec.rb
UTF-8
1,516
2.515625
3
[ "MIT" ]
permissive
require 'pathname' require Pathname(__FILE__).dirname.parent.expand_path + 'spec_helper' describe DataMapper::Types::EpochTime do describe ".dump" do describe "when given Time instance" do before :all do @input = Time.now end it "returns timestamp" do DataMapper::Types::EpochTime.dump(@input, :property).should == @input.to_i end end describe "when given DateTime instance" do before :all do @input = DateTime.now end it "returns timestamp" do DataMapper::Types::EpochTime.dump(@input, :property).should == Time.parse(@input.to_s).to_i end end describe "when given an integer" do before :all do @input = Time.now.to_i end it "returns value as is" do DataMapper::Types::EpochTime.dump(@input, :property).should == @input end end describe "when given nil" do before :all do @input = nil end it "returns value as is" do DataMapper::Types::EpochTime.dump(@input, :property).should == @input end end end describe ".load" do describe "when value is nil" do it "returns nil" do DataMapper::Types::EpochTime.load(nil, :property).should == nil end end describe "when value is an integer" do it "returns time object from timestamp" do t = Time.now.to_i DataMapper::Types::EpochTime.load(Time.now.to_i, :property).should == Time.at(t) end end end end
true
15328faebd57753f06c15da95a58dcdc1ad58567
Ruby
malfix/kata-findLongestSequence
/exercise.rb
UTF-8
392
3.171875
3
[]
no_license
class Exercise def find(*list) prev_element, longest_sequence, current_sequence = list[0], 0, 0 list.sort().each do |current_element| current_sequence = (prev_element == current_element - 1) ? current_sequence + 1 : 1 prev_element = current_element longest_sequence = current_sequence if current_sequence > longest_sequence end longest_sequence end end
true
d33c98536f6c72c006e094a1c2775df31376186b
Ruby
gameda/prfOperativos
/Memoria.rb
UTF-8
1,235
3.0625
3
[]
no_license
require './Marco' class Memoria def initialize(cantBytes, tamPagina) @cantBytes = Integer(cantBytes) @tamPagina = Integer(tamPagina) if @cantBytes <= 0 @cantBytes = 1 end if @tamPagina <= 0 @tamPagina = 1 end @cantMarcos = @cantBytes/@tamPagina if @cantMarcos <= 0 @cantMarcos = 1 end @arrMarcos = Array.new(@cantMarcos) @cantMarcos.times do |i| marcoTemp = Marco.new(-1, -1, -1) @arrMarcos[i] = marcoTemp end @dispMarcos = @arrMarcos.size @ocupMarcos = 0 end #Metodos get def cantBytes @cantBytes end def tamPagina @tamPagina end def cantMarcos @cantMarcos end def arrMarcos @arrMarcos end def dispMarcos @dispMarcos end def ocupMarcos @ocupMarcos end def indiceMarcoViejo timestampTemp = @arrMarcos[0].timestampCarga i=0 iMayor=0 @arrMarcos.size.times do timestampMarcoActual = @arrMarcos[i].timestampCarga if timestampMarcoActual < timestampTemp && @arrMarcos[i].idProceso != -1 iMayor = i timestampTemp = @arrMarcos[i].timestampCarga end i = i+1 end return iMayor end #Metodos set def dispMarcos=(dispMarcos) @dispMarcos = dispMarcos end def ocupMarcos=(ocupMarcos) @ocupMarcos = ocupMarcos end end
true
2b6bac3e343275e3e6fe54ceadcc8c5f174db59a
Ruby
cindyn11/ruby_challenges
/hello.rb
UTF-8
194
3.671875
4
[]
no_license
puts "Hello, Ruby World!!" if 2 + 2 == 4 puts "All is right with the world!" elsif 2 + 2 == 5 puts "2 + 2 is more than the sum of its parts" else puts "All is NOT right with the world!" end
true
05c4260dbd7f5d5e0bd2f5997c739ca74279bf86
Ruby
MarcinBalejko/Ruby
/tablecontents.rb
UTF-8
392
3.34375
3
[]
no_license
toc = ['Table of Contents', 'Chapter 1: Getting Started', 'page 1','Chapter 2: Numbers','page 9', 'Chapter 3: Letters','page 13'] page_width = 60 puts (toc[0].center(page_width)) puts '' puts (toc[1].ljust(page_width/2) + toc[2].rjust(page_width/2)) puts (toc[3].ljust(page_width/2) + toc[4].rjust(page_width/2)) puts (toc[5].ljust(page_width/2) + toc[6].rjust(page_width/2)) gets
true
64256c76bd9cae1324b574f7a4c586d506d69f9e
Ruby
mpalmer/puppet-module-dnsquery
/lib/puppet/parser/functions/dns_a.rb
UTF-8
582
2.546875
3
[ "MIT" ]
permissive
require 'resolv' module Puppet::Parser::Functions newfunction(:dns_a, :type => :rvalue, :doc => <<-EOS Retrieves DNS A records and returns it as an array. Each record in the array will be an IPv4 address. EOS ) do |arguments| res = Resolv::DNS.new arguments.flatten.map do |name| unless name.is_a? String raise Puppet::ParseError, "dns_a: Only accepts strings (you gave me #{name.inspect})" end res.getresources(name, Resolv::DNS::Resource::IN::A).sort_by { |r| r.address.to_s }.map do |r| r.address.to_s end end.flatten end end
true
d4a27766b440662c97e4659148519f9c842d627b
Ruby
Kyero/vignette
/lib/vignette.rb
UTF-8
3,145
2.515625
3
[ "MIT" ]
permissive
require "active_support/core_ext/module/attribute_accessors" require "action_controller" require "vignette/version" require "vignette/object_extensions" require "vignette/filter" module Vignette module Errors class VignetteStandardError < StandardError; end class ConfigError < VignetteStandardError; end class TemplateRequiresNameError < VignetteStandardError; end end # Module Attributes, please set via `init()` mattr_accessor :logging mattr_accessor :store mattr_accessor :force_choice_param # Initialization Code # Defaults Vignette.store = :session Vignette.logging = false Vignette.force_choice_param = nil # We're going to include ArrayExtensions ActionController::Base.send(:include, ObjectExtensions::ActionControllerExtensions) Array.send(:include, ObjectExtensions::ArrayExtensions) # Member Functions # Set any initializers def self.init(opts={}) opts.each do |k,v| Vignette.send("#{k}=", v) end end # Sets the current repo to be used to get and store tests for this thread def self.set_repo(repo, force_choice=nil) Thread.current[:vignette_repo] = repo Thread.current[:vignette_force_choice] = force_choice end # Clears the current repo on this thread def self.clear_repo set_repo(nil, nil) end # Performs block with repo set to `repo` for this thread # Force choice will be automatically selected if given def self.with_repo(repo, force_choice=nil) begin Vignette.set_repo(repo, force_choice) yield ensure Vignette.clear_repo end end # Is Vignette active for this thread (i.e. do we have a repo?) def self.active? !Thread.current[:vignette_repo].nil? end # Get the repo for this thread def self.repo raise Errors::ConfigError.new("Repo not active, please call Vignette.set_repo before using Vignette (or use around_filter in Rails)") if !active? Thread.current[:vignette_repo] end # Get the force_choice for this thread def self.force_choice raise Errors::ConfigError.new("Repo not active, please call Vignette.set_repo before using Vignette (or use around_filter in Rails)") if !active? Thread.current[:vignette_force_choice] end # From the repo (default whatever is set for the thread), grab Vignettes' repo and unpack def self.vig(repo=nil) repo ||= Vignette.repo # allow using existing repo && repo[:v].present? ? JSON(repo[:v]) : {} end # For this repo, store an update Vig def self.set_vig(vig) repo[:v] = vig.to_json end # Pull all the tests for this current repo def self.tests(vig=nil) vig ||= Vignette.vig name_values = vig.values.map { |v| [ v['n'], [ v['t'], v['v'] ] ] }.group_by { |el| el[0] } arr = name_values.map { |k,v| [ k.to_s.to_sym, v.sort { |a,b| b[1][0] <=> a[1][0] }.first[1][1] ] } Hash[arr] end private def self.strip_path(filename) if defined?(Rails) && Rails && Rails.respond_to?(:root) filename.gsub(Regexp.new("#{Rails.root}[/]?"), '') else filename.split('/')[-1] end end def self.rand(length) Kernel.rand(length) end end
true
188486dc64b793baae33643da949dbe0e24121f7
Ruby
Bumsuk/MyRubyBase
/08-013-instance_variable.rb
UTF-8
478
3.328125
3
[]
no_license
class Duration def initialize(since, till) @since = since @until = till end attr_accessor :since, :until # 属性へのgetterとsetterを定義する end class Duration # 例7-6の定義を再オープン def print_since; p @since end end duration1 = Duration.new(Time.now-7, Time.now) duration2 = Duration.new(Time.now+7, Time.now+14) duration1.print_since #=> Fri Feb 01 18:57:30 +0900 2008 duration2.print_since #=> Fri Feb 01 18:57:43 +0900 2008
true
d58596c0fbb598075af46d1040b901933ed9448f
Ruby
polfliet/demo-deployer
/src/common/logger/logger_factory.rb
UTF-8
909
2.859375
3
[ "Apache-2.0" ]
permissive
require './src/common/logger/info_logger' require './src/common/logger/debug_logger' require './src/common/logger/error_logger' module Common module Logger class LoggerFactory def self.set_logging_level(logging_level = "error") @logging_level = logging_level @logger = nil end def self.get_logging_level() return @logging_level end def self.set_execution_type(execution_type) @execution_type = execution_type end def self.get_logger() return @logger ||= self.create_logger_type() end private def self.create_logger_type() case @logging_level when 'debug' return Common::Logger::DebugLogger.new() when 'error' return Common::Logger::ErrorLogger.new() else return Common::Logger::InfoLogger.new() end end end end end
true
07a5781bceec84ddb1cb2a983738c559d5797412
Ruby
harakonan/misc-codes
/Ruby/Exploring_Everyday_Things/Chap4/Restroom_test.rb
UTF-8
1,191
2.953125
3
[]
no_license
Dir.chdir("./Exploring_Everyday_Things/Chap4") require './Restroom_class' DURATION = 60*9 frequency = 3 use_duration = 1 population_size = 10 facilities_per_restroom = 3 restroom = Restroom.new p restroom restroom.facilities.each do |facility| print(facility, " o=", facility.occupier, " d=", facility.duration, "\n") end p restroom.queue population_size.times {Person.population << Person.new(frequency, use_duration)} p Person.population p Person.population.size (restroom.facilities.size + 1).times do restroom.enter(Person.population[0]) restroom.facilities.each do |facility| print(facility, " o=", facility.occupier, " d=", facility.duration, "\n") end p Person.population p Person.population.size end p restroom.queue 2.times do restroom.tick restroom.facilities.each do |facility| print(facility, " o=", facility.occupier, " d=", facility.duration, "\n") end end p Person.population p Person.population.size restroom.enter restroom.queue.shift restroom.facilities.each do |facility| print(facility, " o=", facility.occupier, " d=", facility.duration, "\n") end p restroom.queue p Person.population.size
true
8d92149ff95efdc8988d2bedbff17da5984e5833
Ruby
diogolsq/SpaceCobra
/lib/food.rb
UTF-8
390
3
3
[]
no_license
class Food attr_accessor :x, :y def initialize(tile, width, height) @x = 15 @y = 15 @tile = tile @width = width @height = height end def update end def draw Gosu.draw_rect(@x * @tile, @y * @tile, @tile - 1, @tile - 1, Gosu::Color::RED) end def respawn @x = (rand * @tile).floor @y = (rand * @tile).floor end end
true
98576584ff3946368661e636bf35b7011cd14269
Ruby
charleshenriponiard/01-Food-Delivery
/router.rb
UTF-8
791
3.078125
3
[]
no_license
# TODO: implement the router of your app. require 'pry-byebug' class Router def initialize(meals_controller, sessions_controller, orders_controller) @meals_controller = meals_controller @sessions_controller = sessions_controller @orders_constroller = orders_controller end def run puts " > connection" @sessions_controller.sign_in loop do print_action action = gets.chomp.to_i dispatch(action) end end private def print_action puts "__"*20 puts "> what do you want to do ? " puts "1 - List" puts "2 - Add" puts "3 - Exit" puts "__"*20 end def dispatch(action) case action when 1 then @meals_controller.list when 2 then @meals_controller.add when 3 then exit end end end
true
d88ca869182c916505bffafb5878671ddec7ef47
Ruby
rymo4/gunslinger
/genetic_optimization.rb
UTF-8
2,933
3.40625
3
[]
no_license
require 'rubygems' require 'java' include_class 'gunslinger.sim.Gunslinger' class Chromosome attr_accessor :genes MUTATION_P = 0.8 def initialize genes, features, eval_f, res, step_sizes @features = features @eval_f = eval_f @genes = genes @res = res @fitness = nil @genes = genes @step_sizes = step_sizes end def clone_with_genes genes Chromosome.new(genes, @features, @eval_f, @res, @step_sizes) end # { name: "..." min: 0 max: 3} def self.random features, eval_f, res genes = [] step_sizes = [] features.each do |f| step_size = (f[:max] - f[:min]).to_f / res step_sizes << step_size genes << f[:min] + ((rand * res).to_i * step_size) end Chromosome.new(genes, features, eval_f, res, step_sizes) end def self.mate dad, mom split_point = rand(dad.genes.size - 2) + 1 son_genes = dad.genes.clone daughter_genes = mom.genes.clone son_genes[0..split_point], daughter_genes[0..split_point] = mom.genes[0..split_point], dad.genes[0..split_point] return dad.clone_with_genes(son_genes), mom.clone_with_genes(daughter_genes) end def fitness @fitness ||= @eval_f.call(@genes) end def mutate! @genes.each_with_index do |g, i| if rand < MUTATION_P if rand < 0.5 @genes[i] = g + @step_sizes[i] else @genes[i] = g - @step_sizes[i] end if @genes[i] < @features[i][:min] @genes[i] = @features[i][:min] elsif @genes[i] > @features[i][:max] @genes[i] = @features[i][:max] end end end end end POPULATION_SIZE = 12 RESOLUTION = 5 NUM_ITERATIONS = 6 NUM_ELITES = 6 features = [ {name: "friend", min: -10, max: 0}, {name: "shot", min: -1, max: 10}, {name: "foe", min: -1, max: 10}, {name: "friends_foe", min: -1, max: 10}, {name: "enemy", min: 0, max: 10}, {name: "none", min: -10, max: 0}, {name: "retaliation", min: 6, max: 10} ] eval_f = lambda { |gene_values| Gunslinger.avgScoreWithCoeffs(gene_values.to_java :float) } # Make base population pop = [] POPULATION_SIZE.times do |n| pop << Chromosome.random(features, eval_f, RESOLUTION) end NUM_ITERATIONS.times do |n| puts "Iteration #{n+1}/#{NUM_ITERATIONS}" # compute across many threads and cache result #pop.threach(4) { |p| p.fitness } pop.sort! { |a,b| -a.fitness <=> -b.fitness } # print top three solutions puts pop.map(&:genes).inspect puts pop.map(&:fitness).inspect # Take NUM_ELITES best from pop pop_1 = pop[0..NUM_ELITES-1] pop_2 = [] num_crossovers = (POPULATION_SIZE - NUM_ELITES) / 2 num_crossovers.times do dad = pop.sample mom = pop.sample son, daughter = Chromosome.mate dad, mom pop_2 << son pop_2 << daughter end num_crossovers.times do # mutate a random sample in children pop_2[(rand * pop_2.size).to_i].mutate! end pop = pop_1 + pop_2 end
true
bf895191e1da6103ce905b911d05139deebc0082
Ruby
Chikey1/website
/code/qa_selenium_css.rb
UTF-8
12,739
2.671875
3
[]
no_license
require 'selenium-webdriver' require 'nokogiri' require 'pry' $username = 'sara.qi' $password = 'Welcome1234' class TelevoxQA attr_accessor :driver_old, :driver_new, :old_domain, :new_domain def initialize(old_domain, new_domain) self.driver_old = Selenium::WebDriver.for :chrome self.driver_new = Selenium::WebDriver.for :chrome self.old_domain = old_domain self.new_domain = new_domain end def test File.open("Desktop/css_results.txt", "w") do |file| file.puts "*************************************************" file.puts "CURRENTLY TESTING:" file.puts "old site: #{old_domain}" file.puts "new site: #{new_domain}" file.puts "*************************************************" end relatives = get_relatives relatives.map do |path| next if path.end_with?("main") or path.end_with?("home") old_url = old_url_for(path) new_url = new_url_for(path) driver_old.navigate.to(old_url) driver_new.navigate.to(new_url) # add exception for 404s wait.until { driver_old.page_source.match(/<header/i) and driver_new.page_source.match(/<header/i) } ensure_logged_in page_pass = compare_css(old_url, new_url) if !page_pass puts "#{old_url} FAILED" else puts "#{old_url} PASSED" end end driver_old.quit driver_new.quit end private def compare_css(old_url, new_url) page_pass = true tags = ["h1", "h2", "h3", "h4", "h5", "h6", "span", "p", "li", "a"] #if !compare_title(old_url, new_url) # page_pass = false # end tags.map do |tag| if !compare_element(old_url, new_url, tag) page_pass = false end end if !compare_image(old_url, new_url) page_pass = false end return page_pass end def compare_title(old_url, new_url) title_pass = true styles = ["font-size", "font-family", "font-color", "line-height", "font-weight"] if old_element_present(:xpath, "//h1") old_title = driver_old.find_element(:xpath, "//h1") end if new_element_present(:xpath, "//h1") new_title = driver_new.find_element(:xpath, "//h1") end if old_title == nil || new_title == nil if old_title == nil and new_title == nil return true else binding.pry return false end end if old_title.size != new_title.size binding.pry File.open("Desktop/css_results.txt", "a") do |file| file.puts "*************************************************" file.puts "NUMBER OF H1 TAGS DO NOT MATCH" file.puts "old url: #{old_url} - #{old_title.size}" file.puts "new url: #{new_url} - #{new_title.size}" file.puts "*************************************************" end return false end old_title.size.times do |index| styles.each do |style| if old_title[index].style(style) != new_title[index].style(style) if style != "font-family" || (old_title[index].style(style) != new_title[index].style(style).split(",").first) if title_pass File.open("Desktop/css_results.txt", "a") do |file| file.puts "*************************************************" file.puts "STYLE OF H1 TAG IS DIFFERENT" file.puts "old url: #{old_url}" file.puts "new url: #{new_url}" end title_pass = false end File.open("Desktop/css_results.txt", "a") do |file| file.puts "\nstyle error: #{style}" file.puts "old title: #{old_elements[index].text} - #{old_elements[index].style(style)}" file.puts "new title: #{new_elements[index].text} - #{new_elements[index].style(style)}" end end end end end if !title_pass File.open("Desktop/css_results.txt", "a") do |file| file.puts "*************************************************" end end return title_pass end def compare_element(old_url, new_url, tag) element_pass = true styles = ["font-size", "font-family", "font-color", "line-height"] old_elements = find_old_elements(tag) new_elements = find_new_elements(tag) if (old_elements == nil) || (new_elements == nil) if (old_elements == nil) and (new_elements == nil) return true else binding.pry File.open("Desktop/css_results.txt", "a") do |file| file.puts "*************************************************" file.puts "NUMBER OF ELEMENTS DO NOT MATCH" file.puts "old url: #{old_url} - <#{tag}>" file.puts "new url: #{new_url} - <#{tag}>" file.puts "*************************************************" end return false end end if old_elements.size != new_elements.size binding.pry File.open("Desktop/css_results.txt", "a") do |file| file.puts "*************************************************" file.puts "NUMBER OF ELEMENTS DO NOT MATCH" file.puts "old url: #{old_url} - #{old_elements.size} <#{tag}>" file.puts "new url: #{new_url} - #{new_elements.size} <#{tag}>" file.puts "*************************************************" end return false end old_elements.size.times do |index| styles.each do |style| puts "old element: #{old_elements[index].style(style)} \t new element: #{new_elements[index].style(style)}" if old_elements[index].style(style) != new_elements[index].style(style) if style != "font-family" || old_elements[index].style(style) != new_elements[index].style(style).split(",").first if element_pass File.open("Desktop/css_results.txt", "a") do |file| file.puts "*************************************************" file.puts "STYLE OF ELEMENT IS DIFFERENT" file.puts "old url: #{old_url}" file.puts "new url: #{new_url}" end element_pass = false end File.open("Desktop/css_results.txt", "a") do |file| file.puts "\nstyle error: #{style}" file.puts "element: #{tag}" file.puts "old element: #{old_elements[index].text} - #{old_elements[index].style(style)}" file.puts "new element: #{new_elements[index].text} - #{new_elements[index].style(style)}" end end end end end if !element_pass File.open("Desktop/css_results.txt", "a") do |file| file.puts "*************************************************" end end return element_pass end def compare_image(old_url, new_url) image_pass = true old_images = find_old_elements("img") new_images = find_new_elements("img") if (old_images == nil) || (new_images == nil) if (old_images == nil) and (new_images == nil) return true else binding.pry File.open("Desktop/css_results.txt", "a") do |file| file.puts "*************************************************" file.puts "NUMBER OF IMAGES DO NOT MATCH" file.puts "old url: #{old_url}" file.puts "new url: #{new_url}" file.puts "*************************************************" end return false end end if old_images.size != new_images.size binding.pry File.open("Desktop/css_results.txt", "a") do |file| file.puts "*************************************************" file.puts "NUMBER OF IMAGES DO NOT MATCH" file.puts "old url: #{old_url} - #{old_images.size} images" file.puts "new url: #{new_url} - #{new_images.size} images" file.puts "*************************************************" end return false else old_images.size.times do |index| if old_images[index].size != new_images[index].size if image_pass File.open("Desktop/css_results.txt", "a") do |file| file.puts "*************************************************" file.puts "SIZE OF IMAGE IS DIFFERENT" file.puts "old url: #{old_url}" file.puts "new url: #{new_url}" end image_pass = false end File.open("Desktop/css_results.txt", "a") do |file| file.puts "old image: #{old_images[index].attribute('src')} - #{old_images[index].size}" file.puts "new image: #{new_images[index].attribute('src')} - #{new_images[index].size}" end end end end if !image_pass File.open("Desktop/css_results.txt", "a") do |file| file.puts "*************************************************" end end return image_pass end def find_old_elements(tag) if !old_element_present(:xpath, "//div[@id='content']//#{tag}") return nil end old_elements = driver_old.find_elements(:xpath, "//div[@id='content']//#{tag}") container_path = ["//div[@id='content']//nav","//div[@class='CLFormContainer']","//div[@class='map']"] empty = true bad_old_elements = nil container_path.each do |path| if old_element_present(:xpath, "#{path}//#{tag}") if empty bad_old_elements = driver_old.find_elements(:xpath, "#{path}//#{tag}") empty = false else bad_old_elements += driver_old.find_elements(:xpath, "#{path}//#{tag}") end end end if bad_old_elements != nil bad_old_elements.each do |el| old_elements.delete(el) end end if old_elements.size == 0 return nil else return old_elements end end def find_new_elements(tag) if !new_element_present(:xpath, "//div[@id='content']//#{tag}") return nil end new_elements = driver_new.find_elements(:xpath, "//div[@id='content']//#{tag}") container_path = ["//div[@id='content']//nav","//div[@class='secureform']","//div[contains(@id,'map')]", "//div[@class='offScreen']","//div[@class='photoGallery']"] empty = true bad_new_elements = nil container_path.each do |path| if new_element_present(:xpath, "#{path}//#{tag}") if empty bad_new_elements = driver_new.find_elements(:xpath, "#{path}//#{tag}") empty = false else bad_new_elements += driver_new.find_elements(:xpath, "#{path}//#{tag}") end end end if bad_new_elements != nil bad_new_elements.each do |el| new_elements.delete(el) end end if new_elements.size == 0 return nil else return new_elements end end def get_relatives driver_old.navigate.to(old_url_for("pagesitemap.xml")) wait.until { driver_old.page_source.match(/<loc>/i) } relatives = Nokogiri::HTML(driver_old.page_source).xpath("//loc") return relatives.map do |loc| loc = loc.text loc.slice!(old_domain) loc end end def ensure_logged_in if new_element_present(:id, "ctl00_ContentPlaceHolder1_txtPassword") driver_new.find_element(:id, 'ctl00_ContentPlaceHolder1_txtUsername') .send_keys($username) driver_new.find_element(:id, 'ctl00_ContentPlaceHolder1_txtPassword') .send_keys($password) driver_new.find_element(:id, 'ctl00_ContentPlaceHolder1_btnLogin').click wait.until { driver_new.page_source.match(/<header/i) } end end def old_element_present(how, what) @driver_old.manage.timeouts.implicit_wait = 0 result = @driver_old.find_elements(how, what).size() > 0 @driver_old.manage.timeouts.implicit_wait = 3 return result end def new_element_present(how, what) @driver_new.manage.timeouts.implicit_wait = 0 result = @driver_new.find_elements(how, what).size() > 0 @driver_new.manage.timeouts.implicit_wait = 3 return result end def wait Selenium::WebDriver::Wait.new(:timeout => 30) end def old_url_for(path) URI.join(old_domain, path).to_s end def new_url_for(path) URI.join(new_domain, path).to_s end end
true
2a590e623158ae5dd9038f078dda16c0765677b6
Ruby
wmwaqas/day-8-codaisseurup
/app/models/event.rb
UTF-8
639
2.5625
3
[]
no_license
class Event < ApplicationRecord belongs_to :user, optional: true has_and_belongs_to_many :categories has_many :photos, dependent: :destroy has_many :registrations, dependent: :destroy has_many :guests, through: :registrations, source: :user validates :name, presence: true validates :description, presence: true, length: { maximum: 500 } end #validate :ends_at_after_starts_at? #maybe I should make it a class method e.g. self.ends_at_after_starts_at #def ends_at_after_starts_at? #if ends_at < starts_at #errors.add :ends_at, "must be after starts_at" #end #end #new method #def bargain? #price < 30 #end
true
deb4f7ad4e32b19b9f7ca5b6fb109a8674deb71f
Ruby
dodona-edu/dodona
/test/renderers/rouge_test.rb
UTF-8
1,489
2.6875
3
[ "MIT" ]
permissive
require 'test_helper' require 'builder' class RougeTest < ActiveSupport::TestCase include Rails.application.routes.url_helpers include ApplicationHelper test 'markdown should have added class for language' do input_python = "```python3\ndef mysum(a, b, c);\n return a + b + c\n```\n" input_java = "```java\npublic int mySum(int a, int b, int c){\n return a + b + c;\n}\n```\n" input_javascript = "```javascript\nfunction mySum(a, b, c){\n return a + b + c;\n}\n```\n" [input_python, input_java, input_javascript].each do |input| assert markdown(input).include? 'class' end end test 'Rouge formatter and lexers should add classes' do input_python = { format: 'python', description: 'mysum(3, 5, 7)' } input_javascript = { format: 'javascript', description: "return fetch(url)\n .then(response => response.text())\n .then(console.log)\n .catch(handleError);\n" } input_java = { format: 'java', description: 'int x = mySum(7, 9, 42);' } [input_java, input_python, input_javascript].each do |input| builder = Builder::XmlMarkup.new builder.span(class: "code highlighter-rouge #{input[:format]}") do formatter = Rouge::Formatters::HTML.new(wrap: false) lexer = (Rouge::Lexer.find(input[:format].downcase) || Rouge::Lexers::PlainText).new builder << formatter.format(lexer.lex(input[:description])) end assert builder.html_safe.include? 'class' end end end
true
c455b9db6f5703f8b8ac2146ee37d80f2311576c
Ruby
jadeyen/CS61APrepCourse
/ch14/grandfatherClock.rb
UTF-8
274
3.4375
3
[]
no_license
def grandfather_clock block hours = Time.new.hour if hours > 12 hours -= 12 elsif hours == 0 hours = 12 else hours = hours end hours.times do block.call end end with_sounds = Proc.new do puts 'DONG!' end puts grandfather_clock(with_sounds)
true
ea93a6ae171bdc0a550200e198a8c8c242adc18e
Ruby
thejasonfile/theodinproject
/LearnToProgram/arrays.rb
UTF-8
136
3.453125
3
[]
no_license
word = gets.chomp array = [] while word.length > 0 array.push word word = gets.chomp if word.length == 0 puts array.sort end end
true
d44b330ec374b9f2c5d230a57ded7e725ce9923f
Ruby
ayush-amura/Assignments
/assignment_3.rb
UTF-8
254
3.53125
4
[]
no_license
require 'benchmark' #Summation def sum_n(n) a = n.abs+1 arr = [] sum = 0 0.upto(a) do |index| n<0 ? sum = sum - index : sum = sum + index arr << sum end return arr end p sum_n(5) p sum_n(-5) puts Benchmark.measure{ sum_n(5) }
true
02b66a5a64b83b77a089aef94464ee25a0a610ea
Ruby
cbrwizard/perfect-s-bot
/bot.rb
UTF-8
778
2.65625
3
[ "MIT" ]
permissive
require 'hipbot' require_relative 'sporty_brains' class PerfectSBot < Hipbot::Bot class << self def brains @brains ||= SportyBrains end def bot_mention @bot_mention ||= self.name end def add_brains_to_bot(response) brains.init(response: response, bot: self) end def users_mentions online_users.map { |user| user.attributes[:mention] } if online_users end def online_users Hipbot::User .all .select { |user| user.attributes[:mention] != bot_mention && user.attributes[:is_online] } end def anybody_online? online_users.length > 0 end end on /^start$/ do reply 'Resistance is futile: your butt will be in shape!' PerfectSBot.add_brains_to_bot(self) end end
true
9ad6a755886cab033f60b1c80a9106ac1ac17bf2
Ruby
DungSama/Exercise_Ruby
/ruby/basic/b1.rb
UTF-8
234
2.953125
3
[]
no_license
#Viết chương trình tìm tất cả các số chia hết cho 7 nhưng không phải bội số của 5, nằm trong đoạn 10 và 200 (tính cả 10 và 200). (10..200).each do |i| if i % 7 == 0 && i % 5 != 0 puts i end end
true
f1a4d02a93a67c72aa07e312f1372f86b7ada4ec
Ruby
leighhalliday/idioma
/spec/models/phrase_extractor_spec.rb
UTF-8
1,501
2.515625
3
[ "MIT" ]
permissive
require 'spec_helper' describe Idioma::PhraseExtractor do let(:mocked_translations) { { en: { validations: {presence: "must be present"} } } } describe "get_translations" do it "returns the translations in the locales files" do expect(Idioma::PhraseExtractor.get_translations.keys).to include(:en) end it "can accept custom backends" do backend = I18n::Backend::Simple.new allow(backend).to receive(:init_translations) allow(backend).to receive(:translations).and_return(mocked_translations) expect(Idioma::PhraseExtractor.get_translations(backend)).to eq(mocked_translations) end end describe "to_dotted_hash" do it "converts when empty" do expect(Idioma::PhraseExtractor.to_dotted_hash({})).to eq({}) end it "converts when one level" do expect(Idioma::PhraseExtractor.to_dotted_hash({name: "Name"})). to eq({"name" => "Name"}) end it "converts when many levels" do expect(Idioma::PhraseExtractor.to_dotted_hash({validations: {presence: "must be present"}})). to eq({"validations.presence" => "must be present"}) end end describe "extract" do it "returns dotted hashes of each locale" do allow(Idioma::PhraseExtractor).to receive(:get_translations).and_return(mocked_translations) extraction = Idioma::PhraseExtractor.extract expect(extraction).to eq({:en=>{"validations.presence"=>"must be present"}}) end end end
true
fe445a01b87a4b8e0fe2b03e20bb7589e609d3ed
Ruby
michaelveloso/LaunchAcademy_challenge_Day26-28
/spec/features/user_posts_a_question_spec.rb
UTF-8
3,095
2.625
3
[]
no_license
require 'rails_helper' LONG_STRING = 'The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.' feature 'user can view details of a question', %Q{ As a user I want to post a question So that I can receive help from others } do # Acceptance Criteria # # - I must provide a title that is at least 40 characters long # - I must provide a description that is at least 150 characters long # - I must be presented with errors if I fill out the form incorrectly scenario 'can navigate to form' do visit '/questions' click_link ('Add a new question!') expect(page).to have_content('New Question') end feature 'filling in form incorrectly shows errors' do scenario 'filling in title incorrectly' do visit '/questions/new' fill_in 'Description', with: LONG_STRING click_button ('Create Question') expect(page).to have_content('Title can\'t be blank') fill_in 'Title', with: 'Title too short' click_button ('Create Question') expect(page).to have_content('Title is too short (minimum is 40 characters)') end scenario 'filling in description incorrectly' do visit '/questions/new' fill_in 'Title', with: LONG_STRING click_button ('Create Question') expect(page).to have_content('Description can\'t be blank') fill_in 'Description', with: 'Descripton too short' click_button ('Create Question') expect(page).to have_content('Description is too short (minimum is 150 characters)') end scenario 'filling in duplicate title' do question = FactoryGirl.create(:question) visit '/questions/new' fill_in 'Title', with: question.title fill_in 'Description', with: question.description click_button ('Create Question') expect(page).to have_content('Title has already been taken') end end feature 'user fills in form correctly' do scenario 'filling in form correctly shows success message' do visit '/questions/new' fill_in 'Title', with: LONG_STRING fill_in 'Description', with: LONG_STRING click_button ('Create Question') expect(page).to_not have_content('Title can\'t be blank') expect(page).to_not have_content('Title is too short (minimum is 40 characters)') expect(page).to_not have_content('Description can\'t be blank') expect(page).to_not have_content('Description is too short (minimum is 150 characters)') expect(page).to_not have_content('Title has already been taken') expect(page).to have_content('Question added') end scenario 'filling in form correctly takes user to question show page' do visit '/questions/new' fill_in 'Title', with: LONG_STRING fill_in 'Description', with: LONG_STRING click_button ('Create Question') expect(page).to have_content(LONG_STRING) end end end
true
fde24f5620ce7b32154abb88979fa16df5bbce45
Ruby
dbsk11/ruby-oo-relationships-practice-auto-shop-exercise-nyc01-seng-ft-042020
/app/models/car.rb
UTF-8
872
3.09375
3
[]
no_license
class Car attr_reader :make, :model, :owner, :classification, :mechanic @@all = [] def initialize(owner, make, model, classification, mechanic) @owner = owner @make = make @model = model @mechanic = mechanic @classification = classification Car.all << self end def self.all @@all end def self.classification Car.all.map do |car| car.classification end.uniq end def self.find_mechanics(classification) Mechanic.all.select do |car| car.specialty == classification end end end #initializes with make, model, classification #cannot change make and mode #classification missing attr #classifications are unique ie: antique, exotic, clunker #deliverables #list of all cars #@@all #list of all car classifications #list of mechanics that have a specialty that matches the car classification
true
88d77c96f342ad76281d0b3724bebe42379f193a
Ruby
deepcerulean/vortex
/lib/vortex/models/player.rb
UTF-8
1,695
2.578125
3
[ "MIT" ]
permissive
module Vortex class Player < Metacosm::Model attr_accessor :name, :location, :velocity, :acceleration, :color, :updated_at, :pinged_at belongs_to :game before_create :assign_color def assign_color self.color ||= %w[ red green blue ].sample end def recompute_location t = Time.now c = current(t) update( location: c.position, velocity: c.velocity, color: color, updated_at: t ) end def ping @pinged_at = Time.now end def move(direction) t = Time.now c = current(t) p [ :player_move, direction ] vx,vy = *c.velocity return if vx.abs > move_rate if direction == :left update(velocity: [-move_rate,vy], location: c.position, updated_at: t) elsif direction == :right update(velocity: [move_rate,vy], location: c.position, updated_at: t) else raise "Invalid direction #{direction}" end end def jump p [ :player_jump! ] t = Time.now c = current(t) vx,vy = *c.velocity if vy == 0 vy = -jump_power update(velocity: [vx,vy], location: c.position, updated_at: t) end end protected def move_rate 4.5 end def jump_power 20 end private def current(t) body.at( t, obstacles: Physicist::SimpleBody.collection_from_tiles(game.world.map.grid), fixed_timestep: true, planck_time: 0.01 ) end def body Physicist::Body.new( position: location, velocity: velocity, dimensions: [2,2], t0: updated_at ) end end end
true
7f3de052f2666e970d1ba8bec517f618a02a61d3
Ruby
htlcnn/FAMILUG
/ruby/pe003.rb
UTF-8
486
3.609375
4
[ "BSD-2-Clause" ]
permissive
#!/usr/bin/env ruby class PE003 def largest_prime_factor_of(n) # dont check 2 because number given is odd factor = 3 while n != 1 while n % factor == 0 n /= factor end last = factor factor += 2 end return last end def solve bignumber = 600851475143 puts largest_prime_factor_of 13195 end end if __FILE__ == $0 pe = PE003.new pe.solve end
true
e68b72124fe2932c0a3d7c999089c26b13dfc5f2
Ruby
vedesh/oracle_chef_repo
/chef-repo/ruby_code/homework.rb
UTF-8
508
3.796875
4
[]
no_license
class MyClass attr_accessor :variable1 attr_accessor :variable2 attr_accessor :variable3 def setterMethod (variable1) @variable1 = variable1[0] @variable2 = variable2[1] @variable3 = variable3[2] return ["variable1", "variable2" , "variable3"] end end MyClassObj = MyClass.new #result1 = MyClassObj.setterMethod("10") #result2 = MyClassObj.setterMethod("10", "20") #result3 = arr = [10, 20, 30] #MyClassObj.setterMethod("10", "20", "30") MyClassObj.setterMethod(arr) puts "#{result3}"
true
c739540d44efb44f5eea11566101df7c5321a8c5
Ruby
zakkana/sample_repository
/class_sample.rb
UTF-8
439
4.03125
4
[]
no_license
class Hito def initialize(h, w) @height = h @weight = w end def bmi @weight / (@height ** 2) end def hantei puts "高い" if @height >= 1.6 puts "普通" if @height <1.6 && @height > 1.2 puts "低い" if @height <= 1.2 end end hito = Hito.new(1.6, 60) hito2 = Hito.new(1.7, 89) hito3 = Hito.new(1.2, 50) puts hito.bmi puts hito.hantei puts hito2.bmi puts hito.hantei puts hito3.bmi puts hito3.hantei
true
9f7791942db8f3dd20d5d473c881392bff2c0673
Ruby
dianamora/cli_project
/lib/characters.rb
UTF-8
778
3.234375
3
[ "MIT" ]
permissive
#where objects are created and stored for user display, aka StarWars characters class Characters attr_accessor :name, :gender, :url, :birth_year @@all = [] def initialize(name, url) @name = name @url = url @@all << self end # def name #getter # @name # end # def name=(name) #setter # @name = name # end def save @@all << self end def self.all @@all end def self.find_by_name(name) self.all.find do |character| character.name.downcase == name.downcase end end def update_character info = Api.update_character(self.url) @birth_year = info["birth_year"] @gender = info["gender"] end end
true
1f50d1dde0ddec7ddfab0df8bcd9cada8c818e1f
Ruby
jbox-web/crono
/lib/crono/cli.rb
UTF-8
3,956
2.625
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
# frozen_string_literal: true Thread.abort_on_exception = true # require external dependencies require 'optparse' # require ourself require 'crono' module Crono # Crono::CLI - The main class for the crono daemon exacutable `bin/crono` class CLI include Singleton include Util attr_accessor :config attr_accessor :launcher def initialize self.config = Config.new self.logfile = STDOUT Crono.scheduler = Scheduler.new end def parse(args = ARGV) parse_options(args) initialize_logger end def run self_read, self_write = IO.pipe sigs = %w[INT TERM] sigs.each do |sig| trap sig do self_write.puts(sig) end rescue ArgumentError puts "Signal #{sig} not supported" end # <dirty_patch> # Require those files manually since they won't be loaded by Rails # when running *bin/crono* command on app side # </dirty_patch> require_relative '../../app/models/crono/application_record' require_relative '../../app/models/crono/crono_job' load_rails Cronotab.process(File.expand_path(config.cronotab)) unless have_jobs? logger.error "You have no jobs in you cronotab file #{config.cronotab}" return end print_banner fire_event(:startup, reraise: true) launch(self_read) end private def parse_options(args) parser = OptionParser.new do |opts| opts.banner = 'Usage: crono [options]' opts.on('-C', '--cronotab PATH', "Path to cronotab file (Default: #{config.cronotab})") do |cronotab| config.cronotab = cronotab end opts.on '-e', '--environment ENV', "Application environment (Default: #{config.environment})" do |env| config.environment = env end opts.on '-p', '--port PORT', "UDP check port (Default: #{config.check_port})" do |port| config.check_port = Integer(port) end opts.on '-v', '--verbose', 'Print more verbose output' do |verbose| config.verbose = verbose.nil? ? true : verbose end end parser.parse!(args) parser end def initialize_logger Crono.logger.level = ::Logger::DEBUG if config.verbose end def load_rails ENV['RACK_ENV'] = 'none' ENV['RAILS_ENV'] = config.environment require 'rails' require File.expand_path('config/environment.rb') ::Rails.application.eager_load! end def print_banner logger.info "Loading Crono #{Crono::VERSION::STRING}" logger.info "Running in #{RUBY_DESCRIPTION}" logger.info 'Jobs:' Crono.scheduler.jobs.each do |job| logger.info "'#{job.performer}' with rule '#{job.period.description}'"\ " next time will perform at #{job.next}" end end def have_jobs? Crono.scheduler.jobs.present? end def launch(self_read) @launcher = Crono::Launcher.new(check_port: config.check_port) begin launcher.run while (readable_io = IO.select([self_read])) signal = readable_io.first[0].gets.strip handle_signal(signal) end rescue Interrupt logger.info "Shutting down" fire_event(:shutdown, reverse: true) launcher.stop logger.info "Bye!" exit(0) end end SIGNAL_HANDLERS = { # Ctrl-C in terminal "INT" => ->(cli) { raise Interrupt }, # TERM is the signal that Crono must exit. # Heroku sends TERM and then waits 30 seconds for process to exit. "TERM" => ->(cli) { raise Interrupt }, } def handle_signal(sig) logger.debug "Got #{sig} signal" SIGNAL_HANDLERS[sig].call(self) end end end
true
1394ee69b9c763a14c75e478ff2cb4d5770ac0fc
Ruby
ahmad19/gilded_rose_refactoring_kata
/lib/sulfuras.rb
UTF-8
202
2.75
3
[]
no_license
class Sulfuras attr_reader :name, :sell_in, :quality def initialize(name, sell_in, quality) @name = name @sell_in = sell_in @quality = quality end def update quality end end
true
75be8c0ced0e781f003ffb6fccc1dc6cb31c5c79
Ruby
vanessasgit/pragmatic_studio_ruby
/studio_game/studio_game.rb
UTF-8
612
2.625
3
[]
no_license
require_relative 'game' player1 = Player.new("moe") player2 = Player.new("larry", 60) player3 = Player.new("curly", 125) knuckleheads = Game.new("Knuckleheads") knuckleheads.add_player(player1) knuckleheads.add_player(player2) knuckleheads.add_player(player3) knuckleheads.play(2) knuckleheads.print_stats chipmunks = Game.new("Chipmunks") player4 = Player.new("Alvin", 70) player5 = Player.new("Simon", 80) player6 = Player.new("Theodore", 90) chipmunks.add_player(player3) chipmunks.add_player(player4) chipmunks.add_player(player5) chipmunks.add_player(player6) chipmunks.play(2) chipmunks.print_stats
true
4979b7518106d05b45cd5993917a04af7cf617b6
Ruby
diautzi/alphabetize-in-esperanto-chicago-web-career-040119
/lib/alphabetize.rb
UTF-8
254
3.546875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# how to sort an array of strings based on a non-standard alphabet! def alphabetize(arr) # code here esperanto_alphabet = "abcĉdefgĝhĥijĵklmnoprsŝtuŭvz" ascii = "@-\\" arr.sort_by do |string| string.tr(esperanto_alphabet, ascii) end end
true
a6f0434c44e2916aeff7a9fca569b40570783b18
Ruby
learn-co-students/chicago-web-080320
/02-intro-to-oo/run.rb
UTF-8
1,619
3.890625
4
[]
no_license
require 'pry' class BankAccount attr_accessor(:balance) # attr_reader :account_number # class variable # class variables are available to class methods, as well as instance methods @@all = [] def initialize(account_number) @account_number = account_number @balance = 1000 @@all << self end # class method! def self.all @@all end # self in a class method is the class itself! def self.find_by_account_number(account_number) # array of bank accounts found_bank_account = self.all.find do |bank_account_instance| # condition to return true when we find the instance we're looking for account_number == bank_account_instance.account_number end binding.pry # string of account number # find / detect # map / collect # select / find_all # binding.pry end def deposit(amount) self.balance += amount end def withdraw(amount) self.balance -= amount end def account_number "IansBank-#{@account_number}" end # instance method! def print_balance # account_number = "123" # self in an instance method is whatever instance we called the method on puts "The account #{self.account_number} has a balance of $ #{self.balance}" # this version uses "implicit" self # puts "The account #{account_number} has a balance of $ #{balance}" end end # end of BankAccount class # BankAccount.new => returns a new instance of a BankAccount # all_bank_accounts = [] b1 = BankAccount.new("123") # all_bank_accounts << b1 b2 = BankAccount.new("321") # all_bank_accounts << b2 binding.pry 0
true
b2d868ae76f253cab330e1d4db7a2f01905b17b7
Ruby
jwass91/flatiron_labs
/hs-oo-stretch-challenges-lab-precollege-se1-nyda-061515-1-master/lib/email_parser.rb
UTF-8
460
3.5625
4
[]
no_license
# Build a class EmailParser that accepts a string of unformatted # emails. The parse method on the class should separate them into # unique email addresses. The delimiters to support are commas (',') # and spaces (' '). class EmailParser def initialize(emails) @emails = emails end def parse array = [] array = @emails.split(/[" ",]/) array.delete("") array.collect{|x| x.strip} array = array.uniq array end end
true
81930ed859ab72d73eb7b7fd02aba7eda6d7c9be
Ruby
IgnesFatuus/Intro_to_Ruby
/Exercises/Small_Problems/Easy_9/grocery.rb
UTF-8
275
3.515625
4
[]
no_license
def grocery_list(list) size = list.size items = [] for i in 0...size list[i][1].times { |_| items << list[i][0] } end items end puts grocery_list([["apples", 3], ["orange", 1], ["bananas", 2]]) == ["apples", "apples", "apples", "orange", "bananas","bananas"]
true
b7e351f7d9f940414c1015285ec1c9f18564cb4e
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/bob/7802bb2362544325896d8e4fca249119.rb
UTF-8
398
4.0625
4
[]
no_license
class Bob def hey(words) blank = ->(input_string) { input_string.strip.empty? } loud = ->(input_string) { input_string == input_string.upcase } question = ->(input_string) { input_string.end_with? "?" } case words when blank "Fine. Be that way!" when loud "Woah, chill out!" when question "Sure." else "Whatever." end end end
true
33f16e2e605db69a86dc91fd4a3a32def1ffd884
Ruby
ckozus/administrate_me
/lib/administrate_me_base.rb
UTF-8
970
2.796875
3
[]
no_license
module AdministrateMeBase # El método set_module toma como parámetros el nombre de módulo a definir y # opcionalmente un hash de opciones. El hash de opciones permite reemplazar # los siguientes valores por defecto: # :caption = Nombre a mostrar en la pestaña. Por defecto se toma el nombre # del módulo en formato "humanized". # :url = Dirección del enlace en la pestaña. Por defecto se crea un # enlace al index del controller con nombre igual al del módulo. # Ej: # set_module :productos, :caption => 'Articulos', :url => activos_productos_url() # def set_module(name, options = {}) self.ame_modules ||= [] self.ame_modules << administrate_me_compose_module(name, options) end def administrate_me_compose_module(name, options = {}) { :name => name, :caption => options[:caption] || name.to_s.humanize, :url => options[:url] || {:controller => "#{name.to_s.pluralize}"} } end end
true
9932293ee08fc9f57c2060dc2f774d119b6e96fe
Ruby
itsjayheart/21_shades_of_ruby
/exo_20.rb
UTF-8
462
3.46875
3
[]
no_license
print "Choisis un nombre d'étages à une pyramide entre 20 et 25 : " number = gets.chomp.to_i pyramid_floors = "" pyramid = [pyramid_floors] 25.times do if pyramid_floors == "" pyramid_floors = pyramid_floors + "#" pyramid[0] = pyramid_floors else pyramid_floors = pyramid_floors + "#" pyramid << pyramid_floors end end floors = -1 25.times do if floors < number - 1 floors = floors + 1 puts pyramid[floors] end end
true
23691f71c1f914be88dc23e38a08ffe3dc4e3395
Ruby
ZsoltFabok/project_euler
/lib/project_euler/problems/problem_17.rb
UTF-8
834
4.21875
4
[]
no_license
module Problems # If the numbers 1 to 5 are written out in words: one, two, three, four, five, # then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. # # If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, # how many letters would be used? # # NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters # and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in # compliance with British usage. class Problem17 def initialize(number) @number = number end def self.execute new(Common::Number.new).calculate(1000) end def calculate(number) letters = "" (1..number).each do |n| letters << @number.in_letters(n) end letters.gsub(/[- ]/, "").size end end end
true
f5255dd83fff8dc25ada3d8f726ae8b2eabfa44e
Ruby
manuca/project_tracker
/spec/support/common_repository_examples.rb
UTF-8
1,293
2.59375
3
[ "MIT" ]
permissive
module ProjectTracker shared_examples "a repository" do let(:tennant) { Tennant.new("A tennant") } let(:client) { Client.new(tennant, "Some client") } let(:project) { Project.new(tennant, "Project name", client) } describe "#save" do it "saves an instance" do repository.save(project) expect(project.id).not_to be_nil expect(project.repository).to eq(repository) end end describe "#find" do it "retrieves project by id" do repository.save(project) retrieved = repository.find(project.id) expect(retrieved).to eq(project) end end describe "when adding task to a project" do let(:task_date) { Date.today } let(:worker) { Worker.new(tennant, "Dude working") } before do repository.save(project) repository.add_task(project, Task.new(worker, task_date, "12:00", "13:00", "a task")) end it "#tasks contains the stored task" do tasks = repository.tasks(project) expect(tasks.count).to eq(1) end it "#remove_task removes the task" do repository.remove_task(project, Task.new(worker, task_date, "12:00", "13:00", "a task")) expect(repository.tasks(project).count).to eq(0) end end end end
true
e3542bdd2cea19f3d13399253739a04392b6f9b8
Ruby
abarrak/except_nested
/lib/except_nested/core_ext/hash/except_nested.rb
UTF-8
1,710
3.078125
3
[ "MIT" ]
permissive
require "active_support/core_ext/object/deep_dup" require "active_support/core_ext/array/wrap" class Hash # Returns a hash that includes everything except given nested keys. # hash = { a: true, b: { x: true, y: false }, c: nil } # hash.except_nested(:b, :c) # => { a: true } # hash.except_nested(:a, b: [:x]) # => { b: { y: false }, c: nil } # hash.except_nested(:a, b: [:x, :y]) # => { c: nil } # hash # => { a: true, b: { x: true, y: false }, c: nil } # # It's useful for limiting a set of parameters to everything but a few known toggles at any depth. # @person.update(params[:person].except_nested(:admin, settings: [:secrect_key])) def except_nested(*nested_keys) deep_dup.except_nested!(*nested_keys) end # Removes the given nested keys from hash and returns it. # hash = { a: true, b: { x: true, y: false }, c: nil } # hash.except_nested!(b: [:y]) # => { a: true, b: { x: true }, c: nil } # hash # => { a: true, b: { x: true }, c: nil } def except_nested!(*nested_keys) nested_keys.each do |key| if key.is_a?(Hash) key.each do |sub_key, sub_value| if sub_value.is_a?(Array) self[sub_key].delete_if { |k, _| sub_value.include?(k) } delete(sub_key) if self[sub_key].empty? elsif sub_value.is_a?(Hash) self[sub_key].except_nested!(sub_value) else self[sub_key].except_nested!(Array.wrap(sub_value)) end end elsif key.is_a?(Array) delete_if { |k, _| k == key.first } else delete(key) end end self end end
true
ea2c8c1af2b1d70d4506992d67214066c70b048c
Ruby
erik-everardo/proyecto-de-lenguajes-de-progra-ago-dic-18
/programas/tarea12.rb
UTF-8
670
3.46875
3
[]
no_license
#Tarea 12 #Nombre: Erik Everardo Cavazos Hernandez #Matrícula: 1811290 #Clase: Lenguajes de programación V4-V6 Jueves #Docente: Ismael Pimentel print("Ingrese la cantidad de numeros deseados: ") n = gets().to_i contador_pares = 1 numeros = 0 par_actual = 2 impar_actual = 3 numero_veces_pares=1 while numeros < n for y in (1..numero_veces_pares) if numeros>=n then y=numero_veces_pares end if par_actual%2==0 && n!=numeros then print par_actual.to_s + " " numeros+=1 par_actual+=2 contador_pares+=1 end end for i in (1..3) if impar_actual%2!=0 && n!=numeros then print "-"+impar_actual.to_s + " " numeros+=1 impar_actual+=2 end end numero_veces_pares+=1 end
true
3bb6a40457c4e9fe3ec1fa9b9df831ba7ac41a55
Ruby
Tu-tu-tu/fbsd-pentest
/reporting/dradis-nessus/lib/nessus/report_item.rb
UTF-8
4,574
2.609375
3
[]
no_license
module Nessus # This class represents each of the /NessusClientData_v2/Report/ReportHost/ReportItem # elements in the Nessus XML document. # # It provides a convenient way to access the information scattered all over # the XML in attributes and nested tags. # # Instead of providing separate methods for each supported property we rely # on Ruby's #method_missing to do most of the work. class ReportItem # Accepts an XML node from Nokogiri::XML. def initialize(xml_node) @xml = xml_node end # List of supported tags. They can be attributes, simple descendans or # collections (e.g. <bid/>, <cve/>, <xref/>) def supported_tags [ # attributes :port, :svc_name, :protocol, :severity, :plugin_id, :plugin_name, :plugin_family, # simple tags :solution, :risk_factor, :description, :plugin_publication_date, :metasploit_name, :cvss_vector, :cvss_temporal_vector, :synopsis, :exploit_available, :patch_publication_date, :plugin_modification_date, :cvss_temporal_score, :cvss_base_score, :plugin_output, :plugin_version, :exploitability_ease, :vuln_publication_date, :exploit_framework_canvas, :exploit_framework_metasploit, :exploit_framework_core, # multiple tags :bid_entries, :cve_entries, :see_also_entries, :xref_entries, # compliance tags :cm_actual_value, :cm_audit_file, :cm_check_id, :cm_check_name, :cm_info, :cm_output, :cm_policy_value, :cm_reference, :cm_result, :cm_see_also, :cm_solution ] end # This allows external callers (and specs) to check for implemented # properties def respond_to?(method, include_private=false) return true if supported_tags.include?(method.to_sym) super end # This method is invoked by Ruby when a method that is not defined in this # instance is called. # # In our case we inspect the @method@ parameter and try to find the # attribute, simple descendent or collection that it maps to in the XML # tree. def method_missing(method, *args) # We could remove this check and return nil for any non-recognized tag. # The problem would be that it would make tricky to debug problems with # typos. For instance: <>.potr would return nil instead of raising an # exception unless supported_tags.include?(method) super return end # first we try the attributes: port, svc_name, protocol, severity, # plugin_id, plugin_name, plugin_family translations_table = { # @port = xml.attributes["port"] # @svc_name = xml.attributes["svc_name"] # @protocol = xml.attributes["protocol"] # @severity = xml.attributes["severity"] :plugin_id => 'pluginID', :plugin_name => 'pluginName', :plugin_family => 'pluginFamily' } method_name = translations_table.fetch(method, method.to_s) return @xml.attributes[method_name].value if @xml.attributes.key?(method_name) # then we try the children tags: solution, risk_factor, description, # plugin_publication_date, metasploit_name, cvss_vector, # cvss_temporal_vector, synopsis, exploit_available, # patch_publication_date, plugin_modification_date, cvss_temporal_score, # cvss_base_score, plugin_output, plugin_version, exploitability_ease, # vuln_publication_date, exploit_framework_canvas, # exploit_framework_metasploit, exploit_framework_core tag = @xml.xpath("./#{method_name}").first if tag return tag.text end # then the custom XML tags (cm: namespace) if method_name.starts_with?('cm_') method_name = method_name.sub(/cm_/, 'cm:compliance-').gsub(/_/, '-') cm_value = @xml.at_xpath("./#{method_name}", { 'cm' => 'http://www.nessus.org/cm' }) if cm_value return cm_value.text else return nil end end # finally the enumerations: bid_entries, cve_entries, xref_entries translations_table = { :bid_entries => 'bid', :cve_entries => 'cve', :see_also_entries => 'see_also', :xref_entries => 'xref' } method_name = translations_table.fetch(method, nil) if method_name @xml.xpath("./#{method_name}").collect(&:text) else # nothing found, the tag is valid but not present in this ReportItem return nil end end end end
true
7f4be9550f082ef39ef05ac969d4f52a64635e86
Ruby
dantelove/101_programming_foundations
/lesson_3_exercises/lesson_3_exercises_medium1_3.rb
UTF-8
134
3.171875
3
[]
no_license
# lesson_3_exercises_medium1_3.rb puts "the value of 40 + 2 is #{40 +2}." puts puts "the value of 40 + 2 is " + (40 + 2).to_s + "."
true
010bc4d8bd4ae487e303948a76805e387d33bc59
Ruby
softscienceprojects/ruby-boating-school-london-web-080519
/app/models/run.rb
UTF-8
671
2.6875
3
[]
no_license
#console.rb wouldn't load require "pry" require_relative "boatingtest.rb" require_relative "instructor.rb" require_relative "student.rb" #patrick = Student.new("Patrick") #bt1 # = student, name, status, instructor #pass_student(student, test) spongebob = Student.new("Spongebob") patrick= Student.new("Patrick") puff= Instructor.new("Ms.Puff") krabs= Instructor.new("Mr.Krabs") no_crashing = spongebob.add_boating_test("Don't Crash 101", "pending", puff) power_steering_failure = patrick.add_boating_test("Power Steering 202", "failed", puff) power_steering_pass = patrick.add_boating_test("Power Steering 201", "passed", krabs) binding.pry puts "finished testing"
true
5c6b97b3b03c9ab2c9bc30ecdff3bee462931158
Ruby
bsheehy9/ls-challanges
/easy/roman_numerals/roman_numerals.rb
UTF-8
1,056
4.3125
4
[]
no_license
=begin Problem: create a class called RomanNumerals will need 2 methods: - initialize method that takes an integer argument - to_roman which converts integer to string representation of number Examples: given as test cases Data: - integers - CONSTANT - hash for roman numberal values Algorithm: - create constant that holds values for roman numerals - figure out the different digits values (1, 10, 100, 1000) - get each using the least available roman numeral values =end class RomanNumeral attr_reader :number KEY_VALUES = { "M" => 1000, "CM" => 900, "D" => 500, "CD" => 400, "C" => 100, "XC" => 90, "L" => 50, "XL" => 40, "X" => 10, "IX" => 9, "V" => 5, "IV" => 4, "I" => 1 } def initialize(num) @number = num end def to_roman roman_numeral = '' to_convert = number KEY_VALUES.each do |letter, value| until value > to_convert roman_numeral << letter to_convert -= value end end roman_numeral end end
true
c7819f222430843a6631695443a2c65374dc1c15
Ruby
sarahtattersall/Othello
/spec_helper.rb
UTF-8
392
2.84375
3
[]
no_license
require './game' # => consequent classes class Game attr_accessor :board, :players def get_number_human_players return 2 end def get_board_size return 8 # standard size end end class Board attr_accessor :cells, :size def change_board( cells ) @cells = cells end end class Player attr_accessor :color, :count end class Cell attr_accessor :owner end
true
2baa174be13ec3d2778b84df2a13a2987e63ec06
Ruby
AHdeRojas/dryad-app
/stash/stash-notifier/app/dataset_record.rb
UTF-8
2,665
2.703125
3
[ "MIT" ]
permissive
require 'active_support/core_ext/object/to_query' require_relative './config' require 'nokogiri' class DatasetRecord attr_reader :timestamp, :merritt_id, :doi, :version, :title, :raw_xml # the static method to get records of this DatasetRecord class, this follows an activerecord like pattern def self.find(start_time:, end_time:, set: nil) start_time = start_time.utc.iso8601 end_time = end_time.utc.iso8601 # retrieve oai records opts = { 'metadata_prefix': 'stash_wrapper', from: start_time, until: end_time, set: set }.compact oai_record_response = get_oai_response(opts) return [] unless oai_record_response.class == OAI::ListRecordsResponse # convert to datset record objects for things we care about make_ds_record_array(oai_record_response) end def self.get_oai_response(opts) # get the set client = ::OAI::Client.new(Config.oai_base_url) begin url = oai_debugging_url(base_url: Config.oai_base_url, opts: opts) # url = "#{Config.oai_base_url}?#{opts.to_query}" Config.logger.info("Checking OAI feed for #{opts[:set]} -- #{url}") client.list_records(opts) rescue OAI::Exception Config.logger.info("No new records were found from OAI query: #{url}") nil rescue Faraday::ConnectionFailed Config.logger.error("Unable to connect to #{url}") nil end end def self.make_ds_record_array(oai_response) oai_response.map { |oai_record| DatasetRecord.new(oai_record) } end def initialize(oai_record) @raw_xml = oai_record.metadata.to_s nokogiri_doc = Nokogiri(@raw_xml) nokogiri_doc.remove_namespaces! @deleted = oai_record.deleted? || false @timestamp = Time.parse(oai_record.header.datestamp) @merritt_id = oai_record.header.identifier @doi = nokogiri_doc.xpath("/metadata/stash_wrapper/identifier[@type='DOI'][1]").text.strip # this version is the stash version number, not the merritt one. @version = nokogiri_doc.xpath('/metadata/stash_wrapper/stash_administrative/version/version_number[1]').text.strip @title = nokogiri_doc.xpath('/metadata/stash_wrapper/stash_descriptive/resource/titles/title[1]').text.strip end def deleted? @deleted end def self.oai_debugging_url(base_url:, opts:) # # http://uc3-mrtoai-stg.cdlib.org:37001/mrtoai/oai/v2?verb=ListRecords&from=2018-11-01T18%3A19%3A17Z&metadataPrefix=stash_wrapper&set=cdl_dryaddev&until=2019-01-24T18%3A44%3A29Z my_opts = opts.clone my_opts[:verb] = 'ListRecords' my_opts['metadataPrefix'] = my_opts[:metadata_prefix] my_opts.delete(:metadata_prefix) "#{base_url}?#{my_opts.to_query}" end end
true
795fc5a08e41da31858726a1e21e5e2e721d3f54
Ruby
nuguidricardo/grit
/lib/open3_detach.rb
UTF-8
781
2.53125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
module Open3 extend self def popen3(*cmd) pw = IO::pipe # pipe[0] for read, pipe[1] for write pr = IO::pipe pe = IO::pipe pid = fork{ # child fork{ # grandchild pw[1].close STDIN.reopen(pw[0]) pw[0].close pr[0].close STDOUT.reopen(pr[1]) pr[1].close pe[0].close STDERR.reopen(pe[1]) pe[1].close exec(*cmd) } exit!(0) } pw[0].close pr[1].close pe[1].close Process.waitpid(pid) pi = [pw[1], pr[0], pe[0]] pw[1].sync = true if defined? yield begin return yield(*pi) ensure Process.detach(pid) if pid pi.each { |p| p.close unless p.closed? } end end pi end end
true
9f973f44e70415532eca0a0a371c1e1d9ed2aa4f
Ruby
Evelyn651/udemy_ruby_courses
/OOP/project9/manager.rb
UTF-8
633
3.46875
3
[]
no_license
require "uri" require "net/http" require "json" require "../project9/coin" class Manager @@repo = {} def initialize initialize_repo end def initialize_repo response = web_scrap json = JSON.parse(response) for symbol, values in json coin = Coin.new(symbol, values['USD'], values['EUR']) @@repo[symbol] = coin end end def web_scrap url = "https://min-api.cryptocompare.com/data/pricemulti?fsym=BTC,ETH,XRP,DASH,LTC&tsyms=USD,EUR" uri = URI(url) Net::HTTP.get(uri) end def coin_list @@repo.keys end def calculate(amount, symbol, to) coin = @@repo[symbol] amount*coin.send(to.to_sym) end end
true
cf2ec7f040b290d3f68a95480fb691950e36a703
Ruby
ForensicTools/BTCompare_-475-2151_Herting
/lib/btcompare/result.rb
UTF-8
1,918
3.125
3
[ "MIT" ]
permissive
module BTCompare # Holds the result of a comparison. When Result is created its # variables are writable. It is strongly encouraged that developers # using this class run the method lock on the object as soon as # the data has been set in the object. class Result # Files have same piece count attr_accessor :same_piece_count # Contains piece ids of differences attr_accessor :difference_ids # @param parent [Comparison] Parent of the result def initialize parent @parent = parent @same_piece_count = nil @difference_ids = nil end # Locks instance variables for the object. # Specifically, undefs attr_writers. def lock self.instance_eval do undef :same_piece_count= undef :difference_ids= end end # Lists available types of diffs available # to use on these torrent files. # @return [Array<Symbol>] :notAvailable If torrent files are # deemed too different to consider for diffing. def diff_types available = [] if @parent.file_1.contains_found? and @parent.file_2.contains_found? then available.push :direct end if available.empty? then available.push :notAvailable end return available end # Generate a diff # @param type [Symbol] Type of diff to generate # @raise [InvalidDiffType] If the diff type is invalid for # the givien result # @return [Diff::Diff] The resulting diff def diff type unless diff_types.include? type then raise InvalidDiffType end case type when :direct return Diff::Direct.new self, @parent.file_1, @parent.file_2 end end # Gets the byte offset for the pieces that are different. # @return [Hash<Integer,Integer>] Piece id => offset within file def offsets to_return = {} piece_length = @parent.file_1.piece_length @difference_ids.each do |id| to_return[id] = id * piece_length end return to_return end end end
true
6050088712ef4a3efece9544939bd582c024655e
Ruby
James-C-Wilson/launchschool_organized_answers
/easy_1.rb
UTF-8
3,007
4.96875
5
[]
no_license
# Repeat Yourself # Write a method that takes two arguments, a string and a positive integer, and prints the string as # many times as the integer indicates. =begin # (Understand the) Problem: - Identify expected input and output: - input: - 2 arguments: - string - positive integer - output: the string printed as many times as the integer indicates - Make requirements explicit: - Identify Rules: - Make a Mental Model of the Problem: # - Create a method that has two parameters. One parameter, string, will be the text # that is output. The second parameter, integer, will be the number of times that the # string is output. Take the string that is input and repeat it the amount that the integer states. # In regards to the specific data structure, array, hash, etc...I don't know if either is # required for this specific problem. # Examples / Test Cases / Edge Cases: - Validate understanding of the problem: =end repeat('Hello', 3) # output would be: Hello Hello Hello # I think negative numbers and 0 would be edge cases, but I'm not really worried about them right now. # Data Structure: # - How we represent data that we will work with when converting the input to output: # - Create a method that has two parameters. One parameter, string, will be the text # that is output. The second parameter, integer, will be the number of times that the # string is output. # In regards to the specific data structure, array, hash, etc...I don't know if either is # required for this specific problem. # # create the method # parameter1 will be 'string' # parameter2 will be integer # take the word that string represents and repeat it the number of times integer is repeat('Chance', 5) Chance Chance Chance Chance Chance # A # - Steps for converting input to output: # define a method with two parameters # - parameter1 = string that the user wants repeated # - parameter2 = number of times that the string is repeated # # take the string and repeat it the number that the integer is # # => How to do this? # # def repeat('string', integer) #end # # Tip: Break the problem into sections. Make the method and see if it works. # # # # # # C def repeat(string, number) number.times do puts string end end # Here we are creating the method defintion. I originally used integer, but LS uses number # so I changed it. Not sure if number is a better term or not. Perhaps? # The times method is called on the number parameter. the do..end block of code then calls the # puts method on the string parameter. # This made me realize that you can have the parameter of a method call the specific method that # you want. I think this makes sense. I think I knew this before, but now I'm actually making it # make sense in a concrete, non-abstract mental model.
true
12f26bb347fc9dc14228162fbf0bd24c9c652e77
Ruby
ellehallal/LRTHW
/ex17.rb
UTF-8
629
3.03125
3
[]
no_license
from_file, to_file = ARGV puts "Copying from #{from_file} to #{to_file}" in_file = open(from_file); indata = in_file.read # in_file = open(from_file) # indata = in_file.read # puts "The input file is #{indata.length} bytes long" # # puts "Does the output file exist? #{File.exist?(to_file)}" # puts "Ready, hit RETURN to continue, CTRL-C to abort" # $stdin.gets outfile = open(to_file, 'w') outfile.write(indata) # puts "Alright, all done" outfile.close in_file.close #Study drills #2. Commented out some lines to make the script shorter and it still works #4. Closing files keeps memory free and is also good practice
true
68349f12ea86b9fbabe5ea05b1a758f4a055337a
Ruby
Fukkatsuso/AtCoder
/JoinedContest/ABC144B.rb
UTF-8
174
3.375
3
[]
no_license
n = gets.chomp.to_i can = false (1..9).each do |i| if n % i == 0 if n / i <= 9 can = true break end end end if can puts "Yes" else puts "No" end
true
8c7c4098eaee4036ce79bd27331bda80453cc9ee
Ruby
niw/rubies
/src/rubies.rb
UTF-8
2,126
2.8125
3
[ "MIT" ]
permissive
require "yaml" class Rubies attr_reader :base_path def initialize(*base_path) @base_path = File.expand_path(*base_path) end def run! name = ARGV.shift if /^-c/ === name name = load_rcfile(ARGV.shift) end select(name) end private def load_rcfile(path) rcfile = File.read(path) if File.basename(path) == ".rvmrc" rcfile[/^rvm ([^@]+)/, 1] else YAML.load(rcfile)["ruby"] end rescue nil end def select(name) paths = paths_without_rubies ruby_name = nil # FIXME keep original GEM_HOME gem_home = nil if name && ruby_path = ruby_path(name) ruby_name = File.basename(ruby_path) ruby_bin = File.join(ruby_path, "bin") gem_home = gem_home(ruby_name) gem_bin = File.join(gem_home, "bin") paths.unshift(gem_bin) paths.unshift(ruby_bin) end export "PATH", paths.uniq.join(":") export "GEM_HOME", gem_home export "RUBIES_RUBY_NAME", ruby_name end def export(name, value = nil) if value puts %(export #{name}="#{value}") else puts %(unset #{name}) end end def paths_without_rubies ENV["PATH"].split(/:/).reject do |path| path = File.expand_path(path) path.start_with?(base_path) end end def gem_home(ruby_name) File.join(base_path, "gems", ruby_name) end def ruby_path(name) path = find_name_in_paths(name, ruby_paths) return nil unless path File.expand_path(File.readlink(path), File.dirname(path)) rescue path end def find_name_in_paths(name, paths) name = name.split(/\W/) paths = paths.inject({}) do |hash, path| hash[File.basename(path).split(/\W/)] = path hash end keys = [] paths.keys.each do |key| return paths[key] if key == name if (0..(key.size - name.size)).find{|index| key[index, name.size] == name} keys << key end end key = keys.sort.last paths[key] if key end def ruby_paths Dir.glob(File.join(base_path, "*")).reject do |path| !File.exist?(File.join(path, "bin", "ruby")) end end end
true
4971d5629d9f5d4cc680eb19cc08f25fa76ac259
Ruby
sealink/timely
/lib/timely/date_chooser.rb
UTF-8
4,048
3.234375
3
[ "MIT" ]
permissive
# frozen_string_literal: true module Timely class DateChooser # Where is this used... so far only in one place, _date_range.html.haml # May be good to refactor this as well, after the class behaviour is refactored. INTERVALS = [ { code: 'week', name: 'week(s)', description: 'Weekdays selected will be chosen every {{n}} weeks for the date range' }, { code: 'week_of_month', name: 'week of month', description: 'Weekdays selected will be chosen in their {{ord}} occurance every month, e.g. if wednesday and thursday are selected, the first wednesday and first thursday are selected. Note: this may mean the booking is copied to Thursday 1st and Wednesday 7th' } ].freeze attr_accessor :multiple_dates, :from, :to, :select, :dates, :interval, :weekdays def initialize(options) @multiple_dates = options[:multiple_dates] || false @from = process_date(options[:from]) @to = process_date(options[:to]) @select = options[:select] @dates = options[:dates] @specific_dates = options[:specific_dates] @interval = options[:interval] @weekdays = WeekDays.new(options[:weekdays]) if @select == 'weekdays' validate end def process_date(date) case date when Date then date when NilClass then nil when String date !~ /[^[:space:]]/ ? nil : date.to_date end end # Chooses a set of dates from a date range, based on conditions. # date_info - A hash with conditions and date information # :from - The start of the date range # :to - The end of the date range # # You can either specify specific dates to be chosen each month: # :dates - A comma separated string of days of the month, e.g. 1,16 # :specific_dates - A comma separated string of dates, e.g. 26-10-2012, 03-11-2012, 01-01-2013 # # or you can specify how to select the dates # :day - A hash of days, the index being the wday, e.g. 0 = sunday, and the value being 1 if chosen # :interval - A hash of information about the interval # :level - The level/multiplier of the interval unit # :unit - The unit of the interval, e.g. w for week, mow for month of week # e.g. :level => 2, :unit => w would try to select the days of the week every fortnight, # so every friday and saturday each fornight def choose_dates # Not multiple dates - just return the From date. return [@from] unless @multiple_dates # Multiple dates - return the array, adjusted as per input all_days = (@from..@to).to_a case @select when 'days' days = @dates.gsub(/\s/, '').split(',') all_days.select { |date| days.include?(date.mday.to_s) } when 'specific_days' days = @specific_dates.gsub(/\s/, '').split(',') days.map(&:to_date) when 'weekdays' raise DateChooserException, 'No days of the week selected' if @weekdays.weekdays.empty? raise DateChooserException, 'No weekly interval selected' if @interval&.empty? all_days.select do |date| next unless @weekdays.has_day?(date.wday) case @interval[:unit] when 'week' # 0 = first week, 1 = second week, 2 = third week, etc. nth_week = (date - @from).to_i / 7 # true every 2nd week (0, 2, 4, 6, etc.) (nth_week % @interval[:level].to_i).zero? when 'week_of_month' week = @interval[:level].to_i (date.mday > (week - 1) * 7 && date.mday <= week * 7) end end else all_days end end private def validate raise DateChooserException, 'A Start Date is required' unless @from raise DateChooserException, 'Start Date is after End Date' if @multiple_dates && @to && @from > @to @to ||= @from if @multiple_dates end end class DateChooserException < RuntimeError; end end
true
752f1591750679d5b84d7530c0e1e511d38679fb
Ruby
zendesk/curlybars
/spec/integration/presenters/letter_presenter.rb
UTF-8
443
2.859375
3
[ "Apache-2.0" ]
permissive
module IntegrationTest class LetterPresenter < Curlybars::Presenter attr_reader :alphabet allow_methods :a, :b, :c, :d, :e def initialize(alphabet) @alphabet = alphabet end %i[a b c d e].each do |m| define_method(m) do present(m) end end private def present(letter) alphabet[letter].is_a?(Hash) ? LetterPresenter.new(alphabet[letter]) : alphabet[letter] end end end
true
897220a95d9e500f831b966c5e9cb70b3472b790
Ruby
gulfstream15/Week02_Day03_Lab_SnakesLadders
/specs/snakesladders_spec.rb
UTF-8
460
2.640625
3
[]
no_license
require('minitest/autorun') require('minitest/rg') require_relative('../snakesladders.rb') class SnakesLaddersTest < MiniTest::Test def test_can_create_board() snakelad = SnakesLadders.new() refute_nil(snakelad) end def test_create_snake snake1 = SnakesLadders.new() assert_equal({17=>3,13=>3}, snake1.snake) end def test_create_snake ladder1 = SnakesLadders.new() assert_equal({4=>12,8=>18}, ladder1.ladder) end end
true
5fd66be5acffe15e928dbcfb9bf2bad17ceb6587
Ruby
pogoseat/api-client-ruby
/lib/pogoseat/api_endpoint.rb
UTF-8
873
2.578125
3
[ "Apache-2.0" ]
permissive
module Pogoseat class ApiEndpoint include HTTParty base_uri Pogoseat::API_BASE_URL basic_auth ENV["POGOSEAT_API_KEY"], ENV["POGOSEAT_API_SECRET"] format :json # A helper function to verify that the API response appears successful. def self.check_response response if response.code != 200 raise "API authentication failed" end end protected # Sets each member of the opts hash as an instance variable. def set_instance_variables opts opts.each do |k,v| begin instance_variable_set "@#{k}", v # Sets the accessor for the property as well eigenclass = class<<self; self; end eigenclass.class_eval do attr_accessor k end rescue NameError => e # We'll just eat the error for now end end end end end
true
e31b8f7be610fab2d6d243f3c3ae9076a4f73c9c
Ruby
awmcf/hogwarts-lab-sinatra
/specs/hogwarts_spec.rb
UTF-8
916
2.859375
3
[]
no_license
require("minitest/autorun") require("minitest/rg") require_relative("../models/hogwarts") class TestStudent < MiniTest::Test def setup student_1_details = { "first_name" => "Cho", "second_name" => "Chang", "house" => "Ravenclaw", "age" => "23" } student_2_details = { "first_name" => "Harry", "second_name" => "Potter", "house" => "Gryffindor", "age" => "25" } student_3_details = { "first_name" => "Ron", "second_name" => "Weasley", "house" => "Gryffindor", "age" => "26" } @student_1 = Student.new(student_1_details) @student_2 = Student.new(student_2_details) @student_3 = Student.new(student_3_details) end def test_student_first_name assert_equal("Cho", @student_1.first_name) end def test_find student = Student.find(2) assert_equal("Harry", student.first_name) end end
true
c0796be4957e2558db07327e6ddc0d7d480f4fa2
Ruby
Thinknetica-SoftProject/SP-test-assignment-4-gleb-kent
/3.rb
UTF-8
841
2.578125
3
[]
no_license
## Задача №3: # # Джон добрался до этажа с бомбой, но у него на пути стоит дверь с кодовым замком и рядом бумажка с инструкциями (файл data/3.txt) # # Чтобы узнать код от замка, ему нужно для каждой строки найти разницу между наибольшим и наименьшим числами и потом сложить полученные значения # ## Требования к решению: # - Входные данные находятся в файле data/3.txt (разделитель значений - символ табуляции) # - Результат должен быть выведен в консоль командой puts # ## Решение:
true
522648fab6252eba730d2bd917df5cffee37746e
Ruby
joshsoftware/short_circuit
/solutions/auto_eval/solutions/RainerThiel_changed.rb
UTF-8
4,798
3.515625
4
[]
no_license
=begin The solution has been generalized to support basic network structures. The network can be for example a circuitboard as required for this challenge, or a map of geographical locations, or a network of people, or a model of a molecule... The network consists of nodes that are associated with one another via paths. Any path between 2 nodes, say nodes A and B will be represented twice in the network to support bi-directionality. It exists once as a path leading from A to B, associated with node A, and then as a node leading from B to A, associated with node B. Each path has a cost attribute which generalizes the expense associated with moving from the start node to the target node. The cost attribute could for eaxmple refer to the distance between two nodes, or, as the challenge requires, the resistance. A node may have any number of paths (0 to n) leading from it to link it to any number of target nodes (0 to n). The pathway traced from any node to another is referred to as a Route. There can be many routes linking a start and destination node. The network - node - path model can be useful in a large number of application over and above the RPCFN3 challenge. The solution is contained in 3 files 1. RPCFN3.rb - The main script (this file) 2. RPCFN3_classes.rb - Contains all class definitions 3. RPCFN3_tests.rb - Tests =end =begin # commented out for auto_check by ashbb PATH_RPCFN3 = [ [ 'A', 'B', 50], [ 'A', 'D', 150], [ 'B', 'C', 250], [ 'B', 'E', 250], [ 'C', 'E', 350], [ 'C', 'D', 50], [ 'C', 'F', 100], [ 'D', 'F', 400], [ 'E', 'G', 200], [ 'F', 'G', 100], ] FROM = 'A' TO = 'G' =end def get_redundant_resistors(nw) # # Get a unique list of path names. # Get the list of paths in the shortest route. # Get the difference - this is the redundant set of paths (bi-directional). # Remove the duplicates to get the required result (see below) # all_paths = (nw.path_list.collect {|p| [p.from, p.to]}) min_paths = nw.min_cost_routes.first.path_list.collect {|p| [p.from, p.to]} # # The difference (all_paths - min_paths) is the true list of redundant paths # taking into account that the network is implemented as bidirectional, so # that each path exists twice, once in each direction, from one node to the # other. # The reverse paths are therefore removed to arrive at the required output # list of redundant resistors. # redundant_resistors = (all_paths.collect {|p| p.sort.join('_')}).uniq - (min_paths.collect {|p| p.join('_')}) redundant_resistors.collect {|r| nw.path(r).to_a} end def show_results(nw) nw.routes.each {|r| puts "Route #{r.name} cost #{r.cost} pathway #{r.nodes.collect {|n| n.name + ' '}}"} puts "Minimum cost = #{nw.min_cost}, shared by routes #{(nw.min_cost_routes.collect {|r| r.name}).join(',')}" puts "Maximum cost = #{nw.max_cost}, shared by routes #{(nw.max_cost_routes.collect {|r| r.name}).join(',')}" puts "Average cost = #{nw.avg_cost}" end require 'solutions/rainer_classes' # edited for auto_check by ashbb # edited the following for auto_test by ashbb $test0 =<<EOS @end_node = 'G' @circuits = [ ['A','B',50], ['A','D',150], ['B','C',250], ['D','C',50], ['B','E',250], ['D','F',400], ['C','F',100], ['C','E',350], ['F','G',100], ['E','G',200] ] EOS $test1 =<<EOS @end_node = 'H' @circuits = [ [ 'A', 'B', 50], [ 'A', 'D', 150], [ 'B', 'C', 250], [ 'B', 'E', 250], [ 'C', 'E', 350], [ 'C', 'D', 50], [ 'C', 'F', 100], [ 'E', 'H', 200], [ 'F', 'H', 100], [ 'D', 'G', 350], [ 'G', 'F', 50], [ 'C', 'G', 30] ] EOS $test2 =<<EOS @end_node = 'D' @circuits = [ [ 'A', 'B', 10], [ 'A', 'C', 100], [ 'A', 'D', 100], [ 'B', 'C', 10], [ 'B', 'D', 100], [ 'C', 'D', 10] ] EOS $test3 =<<EOS @end_node = 'G' @circuits = [ [ 'A', 'B', 10], [ 'A', 'C', 100], [ 'A', 'D', 100], [ 'B', 'C', 10], [ 'B', 'D', 100], [ 'C', 'D', 10], [ 'B', 'E', 10], [ 'C', 'F', 10], [ 'D', 'G', 10] ] EOS def bridge_method test eval test nw = Network.new nw.import(@circuits) nw.get_routes('A', @end_node) output = get_redundant_resistors(nw) output.collect{|a, b,| a + b} end # commented out the following for auto_check by ashbb =begin nw = Network.new # Create an empty network nw.import(PATH_RPCFN3) # Load the network using data as formated in RPCFN3 nw.get_routes(FROM, TO) # Do the work. Assembles an array of all possible # routes for given start and end nodes output = get_redundant_resistors(nw) puts "[" output.each {|p| puts "\t[#{p.join(',')}]"} puts "]" #nw.import(PATHS_TO_ROME) #nw.get_routes('Paris', 'Istanbul') #show_results(nw) require 'test/unit' require 'RPCFN3_tests' =end
true
bbe35c3242cc06d29785482cae03931afb881bbf
Ruby
coi-gov-pl/revamp
/lib/revamp/cli.rb
UTF-8
2,844
2.859375
3
[ "Apache-2.0" ]
permissive
require 'micro-optparse' require 'revamp' # A command line interface class class Revamp::CLI # Executes an Revamp from CLI # # @param argv [Array] an argv from CLI # @return [Integer] a status code for program def run!(argv = ARGV) exec = parse_execution(argv) return -1 unless exec.success? exec = run_execution(exec.value) return 1 unless exec.success? 0 end protected # Parse an ARGV command line arguments # @param argv [Array] an argv from CLI # @return [Hash] options to use by application def parse(argv) options = parser.process!(argv) validate_options(options) Revamp.logger.level = Logger::INFO unless options[:verbose] options end private def validate_options(options) filenames = options[:filenames] fail ArgumentError, "You must pass filenames with `-f`. See: `#{$PROGRAM_NAME} --help`" if filenames.empty? filenames.each do |file| fail ArgumentError, "Can't read file given: #{file}" unless File.readable?(file) end outdir = options[:outdir] fail ArgumentError, "Can't write to output directory: #{@outdir}" unless File.writable?(outdir) end def parse_execution(argv) Execution.new(true, parse(argv)) rescue ArgumentError => ex Revamp.logger.fatal(ex) Execution.new(false) end def run_execution(options) require 'revamp/application' Execution.new(true, Revamp::Application.new(options).run!) rescue StandardError => ex bug = Revamp.bug(ex) Revamp.logger.fatal("Unexpected error occured, mayby a bug?\n\n#{bug[:message]}\n\n#{bug[:help]}") Execution.new(false) end def banner txt = <<-eos #{Revamp::NAME} v#{Revamp::VERSION} - #{Revamp::SUMMARY} #{Revamp::DESCRIPTION} Usage: #{$PROGRAM_NAME} [options] eos txt end def parser Parser.new do |p| p.banner = banner p.version = Revamp::VERSION p.option :release, 'A RPM release number, by default it is equal to \'1\'', default: '1' p.option :epoch, 'A RPM epoch number, by default it is equal to \'6\'', default: '6' p.option( :outdir, 'A directory to output converted packages, by default this is current directory: ' + Dir.pwd, default: Dir.pwd ) p.option :filenames, 'Files which will be processed', default: [] p.option :verbose, 'Should print all information, by default: false', default: false p.option :cleanup, 'Should temporary files be cleaned up, by default: true', default: true p.option :clobber, 'Should overwrite output converted packages, by default: false', default: false end end # An execution wrapper class Execution attr_reader :value def initialize(success, value = nil) @success = success @value = value end def success? @success == true end end end
true
5120364d17ffef1a77d88a5c85c5aaaac663f02f
Ruby
maiyama18/AtCoder
/abc/005/b.rb
UTF-8
48
3.03125
3
[]
no_license
n = gets.to_i puts (0...n).map { gets.to_i }.min
true
f5fb422b487365da801d4c4b7386880166d556de
Ruby
LukasBeaton/bond-metric
/spec/unit/service/benchmark_spec.rb
UTF-8
4,042
2.703125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
require 'spec_helper' describe Service::Benchmark do describe '#calculate_spread_to_benchmark' do before do @C1 = Struct::Bond.new('C1', 'corporate', 10.3, 530) @G1 = Struct::Bond.new('G1', 'government', 9.4, 370) end context 'success' do it 'can calculate a positive spread' do result = Service::Benchmark.calculate_spread_to_benchmark(@C1, @G1) expect(result).to eq(160) end it 'can calulate a negative spread' do @G1.basis_points = 600 result = Service::Benchmark.calculate_spread_to_benchmark(@C1, @G1) expect(result).to eq(-70) end end context 'failure' do it 'must have a corporate bond as the first parameter' do g2 = Struct::Bond.new('G2', 'government', 10.3, 555) expect{ Service::Benchmark.calculate_spread_to_benchmark(g2, @G1) }.to raise_error("ERROR: Service::Benchmark#calculate_spread_to_benchmark MUST have a corporate bond as its first parameter!") end it 'must have a government bond as the second parameter' do c2 = Struct::Bond.new('C2', 'corporate', 10.3, 555) expect{ Service::Benchmark.calculate_spread_to_benchmark(@C1, c2) }.to raise_error("ERROR: Service::Benchmark#calculate_spread_to_benchmark MUST have a government bond as its second parameter!") end end end describe '#calculate_spread_to_curve' do before do @C1 = Struct::Bond.new('C1', 'corporate', 10.3, 530) @G1 = Struct::Bond.new('G1', 'government', 9.4, 370) @G2 = Struct::Bond.new('G2', 'government', 12, 480) end context 'success' do it 'can calculate a positive spread' do result = Service::Benchmark.calculate_spread_to_curve(@C1, @G1, @G2) expect(result).to eq(122) end it 'can calulate a negative spread' do @C1.basis_points = 320 @G1.basis_points = 480 @G2.basis_points = 370 result = Service::Benchmark.calculate_spread_to_curve(@C1, @G1, @G2) expect(result).to eq(-122) end end context 'failure' do before do @C2 = Struct::Bond.new('C2', 'corporate', 10.1, 510) @G3 = Struct::Bond.new('G3', 'government', 9.5, 375) end it 'must have a corporate bond as the first parameter' do expect{ Service::Benchmark.calculate_spread_to_curve(@G3, @G1, @G2) }.to raise_error("ERROR: Service::Benchmark#calculate_spread_to_curve MUST have a corporate bond as its first parameter!") end it 'must have a government bond as the second parameter' do expect{ Service::Benchmark.calculate_spread_to_curve(@C1, @C2, @G2) }.to raise_error("ERROR: Service::Benchmark#calculate_spread_to_curve MUST have a government bond as its second parameter!") end it 'must have a government bond as the third parameter' do expect{ Service::Benchmark.calculate_spread_to_curve(@C1, @G1, @C2) }.to raise_error("ERROR: Service::Benchmark#calculate_spread_to_curve MUST have a government bond as its third parameter!") end it 'must have a first government bond with shorter term than the second government bond' do @G1.term_years = 13 expect{ Service::Benchmark.calculate_spread_to_curve(@C1, @G1, @G2) }.to raise_error("ERROR: Service::Benchmark#calculate_spread_to_curve MUST have a first government bond parameter with a term that is less than the second government bond parameter!") end it 'must have a corporate bond with a term in between the government bonds' do @C1.term_years = 13 expect{ Service::Benchmark.calculate_spread_to_curve(@C1, @G1, @G2) }.to raise_error("ERROR: Service::Benchmark#calculate_spread_to_curve MUST have a corporate bond with a term between both of the government bonds!") end end end end
true
499f2769b9c22b6e4c39c3c4640b27e353c8e5dc
Ruby
andres-arana/degree-6620-tp
/tp2/perf/analyze.rb
UTF-8
554
3.125
3
[]
no_license
require "csv" class Analyzer def initialize @stats = [] end def analyze accumulate_stats_on "build/perf/time" avg = @stats.inject { |s, e| s + e } / @stats.size puts "" puts "*************************************" puts "Average execution time: #{avg}" end private def accumulate_stats_on(file) File.open file do |f| until f.eof? f.readline data = f.readline.slice(7..11).to_f f.readline f.readline @stats.push data end end end end Analyzer.new.analyze
true
45c3832f20106ca0da7573c55e0d8d367be77003
Ruby
andie5/assignment_recursion_sprint
/lib/sum_of_digits.rb
UTF-8
473
4.4375
4
[]
no_license
# Takes an integer and returns the sum of its digits, for instance sumdig_r(103) => 4. # Recursive sum of digits def sumdig_r(n) # puts "#{n} and n /10 is #{n/10} and n%10 is #{n%10}" if (n<10) return n else return n%10 + sumdig_r(n/10) end end # Iterative sum of digits def sumdig_i(n) # Shortcut for .map on array, and for each element in the array, returns the result of calling to_i on that element. return n.to_s.chars.map(&:to_i).reduce(:+) end
true
50e74eca0b54ed13eb9acdf2bcf26bf99579d6f4
Ruby
suranyami/abbot-from-scratch
/lib/sproutcore/compiler/entry.rb
UTF-8
1,006
2.84375
3
[]
no_license
module SproutCore module Compiler # The entry is a simple abstraction that takes in a name and a body # and can extract dependencies from the body based on a pattern # # It will automatically assume that dependencies without an extension # have the same extension as the entry's file name class Entry attr_reader :name, :body DEP_REGEX = %r{\b(?:sc_)?require\(['"]([^'"]*)['"]\)} def initialize(name, body, regex = DEP_REGEX) @name, @raw_body = name, body @extension = name.include?(".") && name.split(".").last @regex = regex end def body "\n(function() {\n#{@raw_body}\n})();\n" end def dependencies @dependencies ||= begin @raw_body.scan(@regex).map do |match| dep = match.last if !dep.include?(".") && @extension dep = [match.last, @extension].join(".") end dep end end end end end end
true
1595e076e29a36b2cdf309aeb9d07bfa434ef803
Ruby
kahahope/ROR_Thinknetica
/Lesson_1/ideal_weight.rb
UTF-8
317
3.453125
3
[]
no_license
puts "Привет, как тебя зовут?" name = gets.chomp puts "Какой у тебя рост?" height = gets.to_i ideal_weight = height - 110 if ideal_weight >= 0 "#{name}, твой оптимальный вес #{ideal_weight} кг." else "#{name}, твой вес уже оптимален." end
true
21f0b4f937949c667752ff4290b5dbbafb643875
Ruby
TonyCWeng/Practice_Problems
/leetcode/ruby/11_container_with_most_water.rb
UTF-8
1,554
3.828125
4
[]
no_license
def max_area(height) left = 0 right = height.length - 1 left_wall = height[left] right_wall = height[right] most_water = max_area_helper(height, left, right) until left >= right if height[left] < height[right] until height[left] > left_wall || left >= right left += 1 end left_wall = height[left] else until height[right] > right_wall || left >= right right -= 1 end right_wall = height[right] end current_water = max_area_helper(height, left, right) most_water = current_water if current_water > most_water end most_water end def max_area_helper(height, left, right) height = [height[left], height[right]].min height * (right - left) end # In my first attempt, I thought to be clever and try to calculate as few # potential maximums by checking only when the container height increased # (as the container width decreased with every iteration). # However, all the constant work to identify the next greatest height. # Also fairly verbose. # A shorter, more succinct approach. We end up calculating the area at # every go, but there's less work overall. # The idea is to start with the widest possible container, working our way # to a thinner area at every iteration. def max_area(height) left = 0 right = height.length - 1 max = 0 while left < right current = [height[left], height[right]].min * (right - left) max = current if current > max if height[left] < height[right] left += 1 else right -= 1 end end max end
true
5c2986b7ad80d2c7453f1b6bc5034a62cde470eb
Ruby
4geru/barby
/test/codabar_test.rb
UTF-8
1,179
2.796875
3
[ "MIT" ]
permissive
require 'test_helper' require 'barby/barcode/codabar' class CodabarTest < Barby::TestCase describe 'validations' do before do @valid = Codabar.new('A12345D') end it "should be valid with alphabet rounded numbers" do assert @valid.valid? end it "should not be valid with unsupported characters" do @valid.data = "A12345E" refute @valid.valid? end it "should raise an exception when data is invalid" do lambda{ Codabar.new('A12345E') }.must_raise(ArgumentError) end end describe 'data' do before do @data = 'A12345D' @code = Codabar.new(@data) end it "should have the same data as was passed to it" do @code.data.must_equal @data end end describe 'encoding' do before do @code = Codabar.new('A01D') @code.white_narrow_width = 1 @code.black_narrow_width = 1 @code.wide_width_rate = 2 @code.spacing = 2 end it "should have the expected encoding" do @code.encoding.must_equal [ "1011001001", # A "101010011", # 0 "101011001", # 1 "1010011001", # D ].join("00") end end end
true
e3488b923992bc39a9c67d00c7478e412a2f0e6c
Ruby
ong-wei-hong/the-odin-project
/chess/lib/chess/board.rb
UTF-8
12,535
3.21875
3
[]
no_license
# frozen_string_literal: true module Chess # Board handles the board state class Board attr_reader :white_pieces, :black_pieces def initialize(info = []) @en_passant = nil initialize_board(info) initialize_moves end def to_s(selected_location = [], moves = []) to_print = " abcdefgh\n" @board.each_with_index do |row, i| to_print += "#{8 - i} " row.each_with_index do |e, j| to_print += add_color(e, i, j, selected_location, moves) end to_print += "\n" end to_print end def at(arr) @board[arr[0]][arr[1]] end def winner black = :black white = :white black = nil if @white_pieces.any? { |e| e.type == :k } white = nil if @black_pieces.any? { |e| e.type == :k } black || white end def moves(location) piece = @board[location[0]][location[1]] send(@moves[piece.type], piece.side, location) end def move(start_location, move) if move == :en_passant handle_en_passant(start_location) @en_passant = nil elsif move == :castling rook = @board[start_location[0]][start_location[1]] king_location = find_king(rook.side) king = @board[king_location[0]][king_location[1]] x = 1 x = -1 if start_location[1] < king_location[1] new_king_location = [king_location[0], king_location[1] + 2 * x] @board[new_king_location[0]][new_king_location[1]] = @board[king_location[0]][king_location[1]] @board[king_location[0]][king_location[1]] = ' ' @board[new_king_location[0]][new_king_location[1] - x] = @board[start_location[0]][start_location[1]] @board[start_location[0]][start_location[1]] = ' ' king.first_move = false rook.first_move = false else end_piece = @board[move[0]][move[1]] remove(end_piece) unless move == ' ' @board[move[0]][move[1]] = @board[start_location[0]][start_location[1]] @board[start_location[0]][start_location[1]] = ' ' post_move(start_location, move) end end def check?(side) pieces = @black_pieces pieces = @white_pieces if side == :w @board.each_with_index do |row, i| row.each_with_index do |piece, j| if pieces.include?(piece) moves = moves([i, j]) moves.each do |pos| target = @board[pos[0]][pos[1]] return true if target != ' ' && target.type == :k end end end end false end def en_passant?(location) return false unless @board[location[0]][location[1]].type == :p left_location = [location[0], location[1] - 1] right_location = [location[0], location[1] + 1] return :left if valid_move?(left_location) && @board[left_location[0]][left_location[1]] == @en_passant return :right if valid_move?(right_location) && @board[right_location[0]][right_location[1]] == @en_passant false end def castling?(location) rook = @board[location[0]][location[1]] king_location = find_king(rook.side) king = @board[king_location[0]][king_location[1]] return false if rook.type != :r || !rook.first_move || !king.first_move king_movement = 1 king_movement = -1 if location[1] < king_location[1] king_movements = [] 3.times do |i| king_movements << [king_location[0], king_location[1] + i * king_movement] end return false if enemy_attack?(rook.side, king_movements) squares_between = [] next_location = [king_location[0], king_location[1] + king_movement] until next_location == location squares_between << next_location next_location = [next_location[0], next_location[1] + king_movement] end return true if all_empty?(squares_between) false end def find_piece_location(piece) @board.each_with_index do |row, i| row.each_with_index do |curr, j| return [i, j] if curr == piece end end nil end def pawn_promotion?(end_location) (end_location[0].zero? || end_location[0] == 7) && @board[end_location[0]][end_location[1]].type == :p end def promote_pawn(end_location, type) @board[end_location[0]][end_location[1]].type = type.to_sym end def save_info white = [] black = [] @board.each_with_index do |row, i| row.each_with_index do |piece, j| if piece != ' ' && piece.side == :b black.push([i, j, piece.info]) elsif piece != ' ' && piece.side == :w white.push([i, j, piece.info]) end end end [white, black, en_passant_location] end private def en_passant_location if @en_passant @board.each_with_index do |row, i| row.each_with_index do |piece, j| return [i, j] if piece == @en_passant end end end nil end def all_empty?(squares_between) squares_between.each do |e| return false unless @board[e[0]][e[1]] == ' ' end true end def enemy_attack?(side, king_movements) pieces = @white_pieces pieces = @black_pieces if side == :w @board.each_with_index do |row, i| row.each_with_index do |piece, j| if pieces.include?(piece) moves = moves([i, j]) moves.each do |move| return true if king_movements.include?(move) end end end end false end def find_king(side) @board.each_with_index do |row, i| row.each_with_index do |piece, j| return [i, j] if piece != ' ' && piece.side == side && piece.type == :k end end end def handle_en_passant(start_location) x = 1 x = -1 if @board[start_location[0]][start_location[1]].side == :w y = 1 y = -1 if en_passant?(start_location) == :left @board[start_location[0] + x][start_location[1] + y] = @board[start_location[0]][start_location[1]] @board[start_location[0]][start_location[1]] = ' ' @board[start_location[0]][start_location[1] + y] = ' ' remove(@board[start_location[0][start_location[1] + y]]) end def post_move(start_location, end_location) @board[end_location[0]][end_location[1]].first_move = false en_passant_helper(start_location, end_location) end def en_passant_helper(start_location, end_location) @en_passant = false piece = @board[end_location[0]][end_location[1]] @en_passant = piece if piece.type == :p && (end_location[0] - start_location[0]).abs == 2 end def remove(piece) @white_pieces.delete(piece) @black_pieces.delete(piece) end def symbol(e, i, j, moves) if moves.include?([i, j]) "\e[31m#{e == ' ' ? '.' : e}\e[0m" else e.to_s end end def add_color(e, i, j, selected_location, moves) if selected_location == [i, j] "\e[42m#{e}\e[0m" elsif (i + j).even? "\e[46m#{symbol(e, i, j, moves)}\e[0m" else symbol(e, i, j, moves) end end def valid_move?(move) move[0] >= 0 && move[0] < 8 && move[1] >= 0 && move[1] < 8 end def move_at_location(side, next_move) return :invalid unless valid_move?(next_move) obj = @board[next_move[0]][next_move[1]] return :valid if obj == ' ' return :invalid if obj.side == side return :capture if obj.side != side end def continuous_movement(side, location, movement) moves = [] movement.each do |move| next_move = [location[0] + move[0], location[1] + move[1]] move_type = move_at_location(side, next_move) while move_type == :valid moves.push(next_move) next_move = [next_move[0] + move[0], next_move[1] + move[1]] move_type = move_at_location(side, next_move) end moves.push(next_move) if move_type == :capture end moves end def single_movement(side, location, movement) moves = [] movement.each do |move| next_move = [location[0] + move[0], location[1] + move[1]] moves.push(next_move) unless move_at_location(side, next_move) == :invalid end moves end def king(side, location) single_movement(side, location, [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]) end def pawn(side, location) x = 1 x = -1 if side == :w moves = [] next_move = [location[0] + x, location[1]] moves.push(next_move) if move_at_location(side, next_move) == :valid next_move = [location[0] + x + x, location[1]] moves.push(next_move) if @board[location[0]][location[1]].first_move && move_at_location(side, next_move) == :valid && @board[location[0] + x][location[1]] == ' ' [[x, 1], [x, -1]].each do |move| next_move = [location[0] + move[0], location[1] + move[1]] moves.push(next_move) if move_at_location(side, next_move) == :capture end moves end def knight(side, location) single_movement(side, location, [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]]) end def queen(side, location) bishop(side, location) + rook(side, location) end def bishop(side, location) continuous_movement(side, location, [[-1, -1], [-1, 1], [1, -1], [1, 1]]) end def rook(side, location) continuous_movement(side, location, [[-1, 0], [0, -1], [0, 1], [1, 0]]) end def initialize_moves @moves = { r: :rook, b: :bishop, q: :queen, n: :knight, p: :pawn, k: :king } end def initialize_white_pieces @white_pieces = [ Piece.new(:w, :p), Piece.new(:w, :p), Piece.new(:w, :p), Piece.new(:w, :p), Piece.new(:w, :p), Piece.new(:w, :p), Piece.new(:w, :p), Piece.new(:w, :p), Piece.new(:w, :r), Piece.new(:w, :n), Piece.new(:w, :b), Piece.new(:w, :q), Piece.new(:w, :k), Piece.new(:w, :b), Piece.new(:w, :n), Piece.new(:w, :r) ] end def initialize_black_pieces @black_pieces = [ Piece.new(:b, :r), Piece.new(:b, :n), Piece.new(:b, :b), Piece.new(:b, :q), Piece.new(:b, :k), Piece.new(:b, :b), Piece.new(:b, :n), Piece.new(:b, :r), Piece.new(:b, :p), Piece.new(:b, :p), Piece.new(:b, :p), Piece.new(:b, :p), Piece.new(:b, :p), Piece.new(:b, :p), Piece.new(:b, :p), Piece.new(:b, :p) ] end def initialize_board(info) if info.empty? initialize_white_pieces initialize_black_pieces @board = [ [ @black_pieces[0], @black_pieces[1], @black_pieces[2], @black_pieces[3], @black_pieces[4], @black_pieces[5], @black_pieces[6], @black_pieces[7] ], [ @black_pieces[8], @black_pieces[9], @black_pieces[10], @black_pieces[11], @black_pieces[12], @black_pieces[13], @black_pieces[14], @black_pieces[15] ], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [ @white_pieces[0], @white_pieces[1], @white_pieces[2], @white_pieces[3], @white_pieces[4], @white_pieces[5], @white_pieces[6], @white_pieces[7] ], [ @white_pieces[8], @white_pieces[9], @white_pieces[10], @white_pieces[11], @white_pieces[12], @white_pieces[13], @white_pieces[14], @white_pieces[15] ] ] else @board = Array.new(8) { Array.new(8) { ' ' } } @white_pieces = load_pieces(info[0]) @black_pieces = load_pieces(info[1]) if info[2] @en_passant = @board[info[2][0]][info[2][1]] end end end def load_pieces(info) arr = [] info.each do |e| arr.push(Piece.new(e[2][0], e[2][1], e[2][2])) @board[e[0]][e[1]] = arr[-1] end arr end end end
true
343a152a6310d57f0c086faf1683ab967605d9f7
Ruby
sladebot/mars-rover
/spec/unit_tests/coordinate_spec.rb
UTF-8
512
2.671875
3
[]
no_license
require 'spec_helper' describe Coordinate do before :each do @coordinate = Coordinate.new(["10", "20", "N"]) end it "There should be a valid Coordinate instance" do expect(@coordinate).to be_an_instance_of Coordinate end it "Should have one x coordinate" do expect(@coordinate.x_element).to eql(10) end it "Should have one y coordinate" do expect(@coordinate.y_element).to eql(20) end it "Should have a direction" do expect(@coordinate.direction).to eql("N") end end
true
23bbb747c75f20460f79bd8e0a49bb57f8f04a08
Ruby
curtp/initiative_tracker
/init_tracker/models/reaction_command.rb
UTF-8
2,131
2.6875
3
[ "MIT" ]
permissive
module InitTracker module Models class ReactionCommand < BaseCommand NEXT_EMOJI = '▶️'.to_s REROLL_EMOJI = '🔀'.to_s RESET_EMOJI = '🔁'.to_s STOP_EMOJI = '🗑'.to_s EMOJIS = [NEXT_EMOJI, RESET_EMOJI, REROLL_EMOJI, STOP_EMOJI] def control_emoji? InitTracker::Models::ReactionCommand::EMOJIS.include?(emoji) end def display_error? InitTrackerLogger.log.debug {"command.display_error? - checking control emoji"} # Only display if it is for a control emoji return false if !control_emoji? # Only for an init tracker embed InitTrackerLogger.log.debug {"command.display_error? - checking to see if it is an init embed"} return false if !for_initiative_embed? # Everything aligns, so display an error InitTrackerLogger.log.debug {"command.display_error? - returning true to display error"} return true end def emoji event.try(:emoji).to_s end def for_embed? begin return !event.message.embeds.empty? rescue Exception => e InitTrackerLogger.log.debug("Error checking to see if embeds are empty: #{e}") return false end end def for_initiative_embed? @_for_initiative_embed ||= is_reaction_for_initiative_embed? end def reaction_command? return true end def display_init? return false if emoji.eql?(STOP_EMOJI) return true end private def is_reaction_for_initiative_embed? begin return false if !for_embed? # Look for an init record. If found, then the reaction is for an embed return true if InitTracker::Models::Init.where(message_id: event.message.id).exists? # No message found, so have to look at the message title return event.message.embeds.first.title.start_with?(InitTracker::CommandProcessors::BaseCommandProcessor::INITIATIVE_DISPLAY_HEADER) rescue Exception => e return false end end end end end
true
57a595924d795b3570018fdefe91511a66c21435
Ruby
richardbobo1/programming-univbasics-nds-green-grocer-dc-web-030920
/grocer.rb
UTF-8
2,528
3.234375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def find_item_by_name_in_collection(name, collection) x = 0 while x < collection.length do if collection[x][:item] == name return collection[x] # else # nil end x += 1 end # Implement me first! # # Consult README for inputs and outputs end def consolidate_cart(cart) new_cart = [] i = 0 while i < cart.length new_cart_item = find_item_by_name_in_collection(cart[i][:item], new_cart) if new_cart_item != nil new_cart_item[:count] += 1 else new_cart_item = { :item => cart[i][:item], :price => cart[i][:price], :clearance => cart[i][:clearance], :count => 1 } new_cart << new_cart_item end i += 1 end new_cart end def apply_coupons(cart, coupons) x = 0 while x < coupons.length do cart_item = find_item_by_name_in_collection(coupons[x][:item], cart) couponed_item_name = "#{coupons[x][:item]} W/COUPON" cart_item_with_coupon = find_item_by_name_in_collection(couponed_item_name, cart) if cart_item && cart_item[:count] >= coupons[x][:num] if cart_item_with_coupon cart_item_with_coupon[:count] += coupons[x][:num] cart_item[:count] -= coupons[x][:num] else cart_item_with_coupon = { :item => couponed_item_name, :price => coupons[x][:cost] / coupons[x][:num], :count => coupons[x][:num], :clearance => cart_item[:clearance] } cart << cart_item_with_coupon cart_item[:count] -= coupons[x][:num] end end x += 1 end cart end def apply_clearance(cart) x = 0 while x < cart.length if cart[x][:clearance] cart[x][:price] = cart[x][:price]*0.80 cart[x][:price].round(2) end x += 1 end cart end def checkout(cart, coupons) new_cart = consolidate_cart(cart) cart_with_applied_coupons = apply_coupons(new_cart, coupons) cart_with_discounts_applied = apply_clearance(cart_with_applied_coupons) grand_total = 0 x = 0 while x < cart_with_discounts_applied.length do item_qty_times_price = cart_with_discounts_applied[x][:price] * cart_with_discounts_applied[x][:count] grand_total += item_qty_times_price x += 1 end if grand_total > 100 grand_total -= ( grand_total* 0.10) end grand_total.round(2) end
true
8bcc522f937305d35be580263a769d3127800cbc
Ruby
Va1da2/programming-languages
/part-c/section9/mixins.rb
UTF-8
2,102
3.984375
4
[]
no_license
# Programming Languages: Section 9 - Mixins module Doubler def double self + self # uses self's `+` message, not defined in Doubler end end class Pt attr_accessor :x, :y include Doubler def + other ans = Pt.new ans.x = self.x + other.x ans.y = self.y + other.y ans end end # Override standard string class to include Doubler mixin class String include Doubler end # these are probably the most common uses in the Ruby library: # Comparable and Enumerable # you define <=> and you get ==, >, <, >=, <= from the mixin # (overrides Object's ==, and adds the others) class Name attr_accessor :first, :last, :middle def initialize(first, last, middle="") @first = first @last = last @middle = middle end def <=> other l = @last <=> other.last # <=> is defined on strings return l if l != 0 f = @first <=> other.first return f if f != 0 @middle <=> other.middle end end # Note ranges are build in and very common # you define `each` and you get `map`, `any?`, etc. # (note `map` returns an array, though) class MyRange include Enumerable def initialize(low, high) @low = low @high = high end def each i = @low while i <= @high yield i i += 1 end end end # here is how module Enumerable could implement map: # (but notice Enumerable's map returns an array, # *not* another instnace of the class :( ) # def map # arr = [] # each { |x| arr.push x } # arr # end # This is more questionable style because the mixin is using an # instance variable that could clash with classes and has to be # initialized module Color def color @color end def color= c @color = c end def darken self.color = "dark " + self.color end end class Pt3D < Pt attr_accessor :z # rest of definition omitted (not so relevant) end class ColorPt < Pt include Color end class ColorPt3D < Pt3D include Color end
true
e198742b96f994c0e16042225007698b02a40318
Ruby
sinventor/pincode
/app/models/redis/base.rb
UTF-8
674
2.828125
3
[ "MIT" ]
permissive
class Redis::Base attr_accessor :value, :key, :expire class << self def key_with_prefix(key) "#{name.downcase}s:#{key}" end def get_value_by(key) Redis.current.get key_with_prefix(key) end def create(params = {}) new(params).save end def delete(key) Redis.current.del key_with_prefix(key) end def decr(key) Redis.current.decr key_with_prefix(key) end end def initialize(attrs = {}) attrs.each do |name, value| send("#{name}=", value) end end def key self.class.key_with_prefix(@key) end def save Redis.current.set(key, value, ex: expire) true end end
true
c2315dbe25b5f9341446e9e7645caca675764304
Ruby
adimichele/capybarbecue
/spec/support/test_rack_app.rb
UTF-8
2,441
2.625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
require 'rack' class TestRackApp def get_html(request) <<-HTML % request.path <html> <head><title>Test Rack App</title></head> <body> <h1>%s</h1> <div class='divclass1' id='div1'> <div class='divclass2' id='div2'> <a href='/link/1' id='link1'>click1</a> </div> </div> <div class='divclass1' id='div3'> <div class='divclass2' id='div4'> <a href='/link/2' id='link2'>click2</a> </div> </div> <div id='hidden_text'>I am <span id='hidden_portion' style='display:none;'>hidden </span>text</div> <form id='testform'> <input type='text' name='text_field' id='text_field' value='monkeys'></input> <input type='text' name='disabled_text' id='disabled_text' disabled='1'></input> <select name='select_field' id='select_field' multiple='1'> <option value="volvo" id='volvo'>Volvo</option> <option value="saab" id='saab'>Saab</option> <option value="mercedes" id='mercedes'>Mercedes</option> <option value="audi" id='audi'>Audi</option> </select> <fieldset id='fieldset1'> <input type='checkbox' id='checkbox_field' name='checkbox_field' value='raisins'></input> <input type='checkbox' id='checkbox_field2' name='checkbox_field2' value='peanuts' checked='1'></input> <input type='radio' id='male' name='sex' value='male'>Male</input> <input type='radio' id='female' name='sex' value='female'>Female</input> <input type='file' id='file_field' name='file_field'></input> </fieldset> <button type="button" name='button1' id='button1' onclick='window.location="/button/1"'>Imma button!</button> </form> <table id='table1'> <tr> <td>cell 1,1</td> <td>cell 1,2</td> </tr> <tr> <td>cell 2,1</td> <td>cell 2,2</td> </tr> </table> <iframe id='myframe' name='myframe' src='/iframe'> </iframe> </body> </html> HTML end def call(env) request = Rack::Request.new(env) if request.path == '/iframe' [200, {"Content-Type" => "text/html"}, ["<html><body><div id='inframe'></div></body></html>"]] else [200, {"Content-Type" => "text/html"}, [get_html(request)]] end end end
true
7fea86fad6a9e5251754668ae3501e8164c1509c
Ruby
ranjanisrini/guvi
/threemax.rb
UTF-8
70
3.484375
3
[]
no_license
array = [] 3.times do n = gets.chomp.to_i array.push(n) end array.max
true
fe48fe188a5680624589fc08f4280ddde5d882e0
Ruby
GLaD0S/ruby_view_server
/erb_example.rb
UTF-8
617
3.828125
4
[]
no_license
require 'erb' require 'time' =begin this method will take in slices, number of times to record the current time and a block which will be what to do with the time. =end def time alltime = Array.new slices = 10 i = 0 while i < slices.to_i do alltime.push(Time.now) i+=1 end yield end puts "How many slices of time would you like to record?" slices = gets #bockprint = { alltime.each do |e| print e end } time (slices) { print_time i = 0 while i < all_time.length do puts all_time[i] i+=1 end } =begin x = 42 template = ERB.new ("The value of x is: <%= x %>") puts template.result(binding) =end
true
4520d9d693599753b358c8256a1e1cf58d033a1c
Ruby
bronsonholden/kaprella-api
/app/services/filter_humanize_meta_service.rb
UTF-8
2,281
2.9375
3
[]
no_license
# Generates humanized expressions representing various filter expressions # to be displayed in the web application. # # TODO: Avoid using Keisan to parse expression and generate AST twice. This # is done in the query service as well. class FilterHumanizeMetaService attr_reader :model, :filters def initialize(model, filters) @model = model @filters = filters || [] end def generate meta = {} filters.each { |filter| meta[filter] = humanize_filter(filter) } meta end protected def humanize_filter(filter) ast = Keisan::Calculator.new.ast(filter) return humanize_ast(ast) end def humanize_function(ast) case ast.name when 'prop' if ast.children.first.is_a?(Keisan::AST::String) model.pretty_name(ast.children.first.value) else nil end when 'is_even' name = humanize_ast(ast.children.first) "#{name} is even" when 'is_odd' name = humanize_ast(ast.children.first) "#{name} is odd" when 'lookup_s', 'lookup_i', 'lookup_b', 'lookup_f' reflection = model.reflections.fetch(humanize_ast(ast.children.first)) prop = humanize_ast(ast.children.second) if !reflection.nil? "#{reflection.klass.model_name.human} #{prop}" end end end def humanize_comparator(ast) case ast when Keisan::AST::LogicalEqual operator = '==' when Keisan::AST::LogicalNotEqual operator = '!=' when Keisan::AST::LogicalGreaterThan operator = '>' when Keisan::AST::LogicalLessThan operator = '<' when Keisan::AST::LogicalGreaterThanOrEqualTo operator = '>=' when Keisan::AST::LogicalLessThanOrEqualTo operator = '<=' else return nil end lval = humanize_ast(ast.children.first) rval = humanize_ast(ast.children.second) return if lval.nil? || rval.nil? "#{lval} #{operator} #{rval}" end def humanize_ast(ast) case ast when Keisan::AST::LogicalOperator humanize_comparator(ast) when Keisan::AST::Function humanize_function(ast) when Keisan::AST::String ast.value when Keisan::AST::Number ast.value.to_s when Keisan::AST::Boolean ast.value.to_s else nil end end end
true
6d7a8055339d49ff967daa1c61f63c6677ed6a21
Ruby
davidverbustel/hackitten
/app/helpers/links_helper.rb
UTF-8
1,429
2.53125
3
[]
no_license
require 'embedly' require 'json' module LinksHelper def display(url) embedly_api = Embedly::API.new(key: ENV['EB_KEY']) obj = embedly_api.oembed :url => url if obj.first.type == "video" raise (obj.first.html).html_safe elsif obj.first.type == "photo" clean_url = obj.first.url.sub(/([?]fb)+$/, '') raise %Q{ <p><img src="#{clean_url}" alt="#{obj.first.title}"style="width:100%"></p> }.html_safe else %Q{ <p><img src="http://i.imgur.com/B7jmNAw.png" alt="not found" style="width:100%"></p> }.html_safe end # obj = embedly_api.oembed :url => url # puts obj[0].marshal_dump # json_obj = JSON.pretty_generate(obj[0].marshal_dump) # puts json_obj end def title(url) embedly_api = Embedly::API.new(key: ENV['EB_KEY']) obj = embedly_api.oembed :url => url (obj.first.title).html_safe end def thumbnail(url) # should be more efficient to store the thumbnail 65x65 instead of retrieving the whole file embedly_api = Embedly::API.new(key: ENV['EB_KEY']) obj = embedly_api.oembed :url => url if obj.first.type != "error" %Q{ <img class="media-object" src="#{obj.first.thumbnail_url+"?meow"}" alt="#{obj.first.title}" style="width:64px;height:64px;"> }.html_safe else %Q{ <img class="media-object" src="http://i.imgur.com/B7jmNAw.png" alt="not found" style="width:64px;height:64px;"> }.html_safe end end end
true
4d126fc1760613b5c81dfcfdfcc5724ac466a111
Ruby
jessjchang/Ruby-Object-Oriented-Problems
/lesson_1_OO_readings/ruby_oop_book_exercises/2_classes_objects_i/ex_1.rb
UTF-8
1,096
4.25
4
[]
no_license
class MyCar def initialize(year, color, model) @year = year @color = color @model = model @speed = 0 end def speed_up(num) @speed += num puts "You are accelerating by #{num} miles per hour." end def brake(num) @speed -= num puts "You are decelerating by #{num} miles per hour." end def shut_off @speed = 0 puts "You are now parked." end def current_speed puts "You are currently driving at #{@speed} miles per hour." end end new_car = MyCar.new(2020, 'gray', 'Toyota Camry') new_car.speed_up(60) # => 'You are accelerating by 60 miles per hour.' new_car.current_speed # => 'You are currently driving at 60 miles per hour.' new_car.brake(20) # => 'You are decelerating by 20 miles per hour.' new_car.current_speed # => 'You are currently driving at 40 miles per hour.' new_car.brake(20) # => 'You are decelerating by 20 miles per hour.' new_car.current_speed # => 'You are currently driving at 20 miles per hour.' new_car.shut_off # => 'You are now parked.' new_car.current_speed # => 'You are currently driving at 0 miles per hour.'
true
b5ad5746a31bd4bdfb85c9c2ffa50b627f09c1df
Ruby
BakaBBQ/LCraft
/LData/Item System/ - InventoryDisplayer.rb
UTF-8
2,746
2.609375
3
[]
no_license
class InventoryDisplayer < Window_ItemList attr_reader :inventory def initialize(rect, inventory) super(rect.x,rect.y,rect.width,rect.height) @inventory = inventory end def refresh super draw_inventory_size end def draw_inventory_size contents.font.size = 14 text = "#{inventory.compact.length}/#{inventory.max_size}" h = text_size(text).height draw_text(0, contents.height - h, contents.width,h,text,2) contents.font.size = Font.default_size end #-------------------------------------------------------------------------- # ● 查询列表中是否含有此物品 #-------------------------------------------------------------------------- def include?(item) return true end #-------------------------------------------------------------------------- # ● 绘制项目 #-------------------------------------------------------------------------- def draw_item(index) item = @data[index] #~ puts @data, $game_map.itemstacks[3][3][0] if item #~ msgbox item rect = item_rect(index) rect.width -= 4 draw_item_name(item, rect.x, rect.y, enable?(item)) draw_item_number(rect, item) end end #-------------------------------------------------------------------------- # ● 获取列数 #-------------------------------------------------------------------------- def col_max return 1 end #-------------------------------------------------------------------------- # ● 获取物品 #-------------------------------------------------------------------------- def item @data = @inventory @data && index >= 0 ? @data[index] : nil end #-------------------------------------------------------------------------- # ● 绘制物品个数 #-------------------------------------------------------------------------- def draw_item_number(rect, item) draw_text(rect, sprintf(":%2d", item.quantity) ,2) end #-------------------------------------------------------------------------- # ● 查询此物品是否可用 #-------------------------------------------------------------------------- def enable?(item) true end #-------------------------------------------------------------------------- # ● 生成物品列表 #-------------------------------------------------------------------------- def make_item_list @data = @inventory @data.push(nil) if @data.length == 0 end def cleanup puts "cleaning up!" @inventory.compact! end end
true
fc99ac924be91b844658d99bce169c790dc0c9d8
Ruby
ssone95/xport-sim
/xport_simulator.rb
UTF-8
1,895
3
3
[ "MIT" ]
permissive
require "rubygems" require "serialport" require "net/telnet" class XportSimulator SERIAL_DATA_BITS = 8 SERIAL_STOP_BITS = 1 # use a stop bit SERIAL_PARITY = SerialPort::NONE TELNET_WAITTIME = 2.0 TELNET_PROMPT = /.*/ TELNET_MODE = false def initialize(serial_port_id, baud_rate=9600) @serial_port = SerialPort.new(serial_port_id, baud_rate, SERIAL_DATA_BITS, SERIAL_STOP_BITS, SERIAL_PARITY) @telnet_connection = nil @connected = false end def listen(once=false) begin begin if raw_value = @serial_port.gets raw_value = raw_value.strip puts "Read raw value: [#{raw_value}]" case raw_value when /^C\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/\d{1,5}$/ : @telnet_connection, @connected = telnet_connect(raw_value) connected? ? @serial_port.write('C') : @serial_port.write('D') when /^(GET|POST|PUT|DELETE)\s*.*$/ : if connected? @serial_port.write(telnet_connection.cmd("#{raw_value}\n")) telnet_connection.close @connected = false end end end end while(!once) ensure @serial_port.close end end def telnet_connection @telnet_connection end def connected? @connected end private def telnet_connect(connect_command) connection_parts = connect_command.split("/") ip_address, port_no = connection_parts[0].gsub("C", ""), connection_parts[1] connected_result = false connection_result = \ Net::Telnet.new('Host' => ip_address, 'Port' => port_no, 'Waittime' => TELNET_WAITTIME, 'Prompt' => TELNET_PROMPT, \ 'Telnetmode' => TELNET_MODE) { |status| connected_result = true if status =~ /Connected/ } [connection_result, connected_result] end end
true
8e33f0ba2eacca4e2ddfdcc8a3152d51af68282c
Ruby
gurugu-learning-projects/appacademy---ruby
/recursives/reverse.rb
UTF-8
276
3.203125
3
[]
no_license
def reverse(string) return string if string.length <= 1 string[-1] + reverse(string[0...-1]) end # Test Cases p reverse("house") # => "esuoh" p reverse("dog") # => "god" p reverse("atom") # => "mota" p reverse("q") # => "q" p reverse("id") # => "di" p reverse("") # => ""
true
19c8414bc634b40113bb7528e75e6602d0cce816
Ruby
xenda/curso_rails01
/rubywarrior/alvaro-beginner/player.rb
UTF-8
2,143
3.125
3
[]
no_license
class Player attr_accessor :back_unknown, :health, :battle_spent, :fighting, :max_health, :rest_needed def taking_damage? damage = false damage = true if @health > @warrior.health end def close_enemies(list) list.select{|i| not i.captive? and (i.x - @warrior.x) < 3 } end def close_captives(list) list.select {|i| i.captive? and (i.x - @warrior.x) < 3 } end def healthy? @warrior.health.to_f > @max_health.to_f * 0.6 end def almost_dead? @warrior.health < @max_health end def initialize @back_unknown ||= "unknown" @fighting = false @rest_needed = false end def setup(warrior) @warrior = warrior @max_health ||= @warrior.health @health ||= @warrior.health end def battle_spent? @fighting end def enemies_present?(enemies) enemies.size > 0 end def captives_present?(captives) captives.size > 0 end def act(direction = :forward) if @warrior.feel(direction).empty? around = @warrior.look(direction) enemies = close_enemies(around) captives = close_captives(around) #puts enemies[0].inspect if enemies_present?(enemies) and not captives_present?(captives) @warrior.shoot! else if battle_spent? puts "Cansado" @warrior.walk!(:backward) @fighting = false @rest_needed = true elsif @rest_needed and not taking_damage? puts "Descansando" if almost_dead? @warrior.rest! else @rest_needed = false end else if taking_damage? and not healthy? @warrior.walk!(:backward) elsif not healthy? @warrior.rest! else @warrior.walk!(direction) end end end else if @warrior.feel(direction).captive? @warrior.rescue!(direction) else @warrior.attack!(direction) @fighting = true end end end def wall? @warrior.feel(:backward).wall? end def play_turn(warrior) setup(warrior) if @warrior.feel.wall? @warrior.pivot! else if @back_unknown and not wall? act(:backward) else act @back_unknown = false end @health = @warrior.health end end end
true
acd2dc25dc9ecfbd6f2e5effe8ffc64440968e28
Ruby
jdashton/glowing-succotash
/beth/lab3.leap.rb
UTF-8
482
4.21875
4
[ "MIT" ]
permissive
# frozen_string_literal: true print 'enter a starting year: ' year1 = gets.to_i print 'enter an ending year: ' year2 = gets.to_i # leap years are divisible by 4 # except when they are divisible by 100 # EXCEPT when they are divisible by 400 # puts all_years # then, we'll make a function to find if it's a leap year def leap?(year) (year % 400).zero? || year % 100 != 0 && (year % 4).zero? end (year1..year2).each do |this_year| puts this_year if leap?(this_year) end
true
369eecace7b030b6ad52e60ee92e9372cbec1f32
Ruby
wpotratz/tealeaf
/2_ruby_workbook/quiz_1_1/exc_5.rb
UTF-8
242
3.765625
4
[]
no_license
def number_check(number, lower, upper) if (lower..upper).cover?(number) then puts "Yep, that number is in between." else puts "Nope it's not" end end number_check(42, 10, 100) number_check(9, 10, 100) number_check(101, 10, 100)
true
f04696c93e053cbb53f5a06f14b666ff0fd978c3
Ruby
MasatakaKudou/Ruby_intro
/chapter_8/module_mixin.rb
UTF-8
650
3.65625
4
[]
no_license
# include module Loggable private def log(text) puts "[LOG] #{text}" end end class Product include Loggable def title log 'title is called.' 'A great movie' end end class User include Loggable def name log 'name is called.' 'Alice' end end product = Product.new p product.title user = User.new p user.name puts '-------------------------------------------' # extend module Loggable_2 def log(text) puts "[LOG] #{text}" end end class Product_2 extend Loggable_2 def self.create_products(names) log 'create_products is called.' end end Product_2.create_products([]) Product_2.log('Hello.')
true
412e23c3919dee9b7bef02e385f33a5d015b71c6
Ruby
davich/toy_robot
/lib/robot.rb
UTF-8
817
3.578125
4
[]
no_license
require_relative 'direction' require_relative 'position' class Robot def initialize(table) @table = table end def place(position, direction) return unless valid?(position, direction) @position = position @direction = direction end def move return unless valid? @position = next_position if valid?(next_position) end def left @direction = @direction.left if valid? end def right @direction = @direction.right if valid? end def report "Robot is at position #{@position}; facing direction #{@direction}" if valid? end private def next_position @position.move(@direction) end def valid?(position=@position, dir=@direction) Direction.valid?(dir) && @table.valid_position?(position) end end
true
3ef438fb34aaa469c234468f415eb38089308a1d
Ruby
EclecticKlos/Experimentations
/source/lib/parser.rb
UTF-8
763
2.828125
3
[]
no_license
require_relative '../../config/application' class Parse def initialize(file) @file = file @business_list = nil @sorted_ids = [] end def parser @business_list if @business_list != nil @business_list = [] CSV.foreach(@file) do |row| @business_list << {business_list: row[0], name: row[1], postal_code: row[5], latitude: row[6]} @business_list end @business_list end def filter_by_postal_code # puts @business_list @business_list.each_with_index do |values,index| if values[:postal_code] == "94103" || values[:postal_code] == "94105" || values[:postal_code] == "94107" @business_list_sorted_by_postal_code << values end end @business_list_sorted_by_postal_code end end
true
7e172c1230a1d1182c3ed9f108b6e8efb761032c
Ruby
colinhalexander/ruby-collaborating-objects-lab-denver-web-82619
/lib/song.rb
UTF-8
768
3.4375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class Song attr_accessor :name, :artist @@all = [] def initialize(name) @name = name @@all << self end def self.all @@all end def self.new_by_filename(filename) filename_array = parse_filename(filename) new_song = self.new(filename_array[1]) new_song.artist = Artist.new(filename_array[0]) new_song end # returns an array with [artist, song, genre] strings def self.parse_filename(filename) split_filename = filename.split(" - ") split_filename[2].slice!(".mp3") split_filename end def artist_name=(artist_name) artist = Artist.find_or_create_by_name(artist_name) artist.add_song(self) end end
true
172183bc363d6ff49c914b42dd56ba681d6f131e
Ruby
cobot/later_dude
/lib/later_dude/month_calendar.rb
UTF-8
5,492
3.046875
3
[ "MIT" ]
permissive
module LaterDude class MonthCalendar include ActionView::Helpers::CaptureHelper include ActionView::Helpers::TagHelper include ActionView::Helpers::UrlHelper attr_accessor :output_buffer, :block def initialize(year, month, options = {}, &block) @year, @month, @options = year, month, options # next_month and previous_month take precedence over next_and_previous_month @options[:next_month] ||= @options[:next_and_previous_month] @options[:previous_month] ||= @options[:next_and_previous_month] @days = Date.civil(@year, @month, 1)..Date.civil(@year, @month, -1) @block = block end def first_rendered_date beginning_of_week(@days.first) end def last_rendered_date beginning_of_week(@days.last + 1.week) - 1 end def show_days content_tag(:tr, "#{show_previous_month}#{show_current_month}#{show_following_month}".html_safe) end def show_names "#{show_month_names}#{show_day_names}".html_safe end private def show_month_names return if @options[:hide_month_name] content_tag(:tr, "#{previous_month}#{current_month}#{next_month}".html_safe, :class => 'month_names') end def show_day_names return if @options[:hide_day_names] content_tag(:tr, :class => 'day_names') do apply_first_day_of_week(day_names).inject('') do |output, day| output << content_tag(:th, include_day_abbreviation(day), :scope => 'col', :class => Date::DAYNAMES[day_names.index(day)].downcase) end.html_safe end end def show_previous_month return if @days.first.wday == first_day_of_week # don't display anything if the first day is the first day of a week "".tap do |output| beginning_of_week(@days.first).upto(@days.first - 1) { |d| output << show_day(d) } end.html_safe end def show_current_month "".tap do |output| @days.first.upto(@days.last) { |d| output << show_day(d) } end.html_safe end def show_following_month return if @days.last.wday == last_day_of_week # don't display anything if the last day is the last day of a week "".tap do |output| (@days.last + 1).upto(beginning_of_week(@days.last + 1.week) - 1) { |d| output << show_day(d) } end.html_safe end def show_day(day) content = '' renderer = DayRenderer.new(day) options = {} options[:class] = "otherMonth" if day.month != @days.first.month if @block && (@options[:yield_surrounding_days] || day.month == @days.first.month) content = renderer.to_html options, &@block else content = renderer.to_html options end # close table row at the end of a week and start a new one # opening and closing tag for the first and last week are included in #show_days content << "</tr><tr>".html_safe if day < @days.last && day.wday == last_day_of_week content end def beginning_of_week(day) diff = day.wday - first_day_of_week diff += 7 if first_day_of_week > day.wday # hackish ;-) day - diff end # @options[:previous_month] can either be a single value or an array containing two values. For a single value, the # value can either be a strftime compatible string or a proc. # For an array, the first value is considered to be a strftime compatible string and the second is considered to be # a proc. If the second value is not a proc then it will be ignored. def previous_month return unless @options[:previous_month] show_month(@days.first - 1.month, @options[:previous_month], :class => "previous") end # see previous_month def next_month return unless @options[:next_month] show_month(@days.first + 1.month, @options[:next_month], :class => "next") end # see previous_month and next_month def current_month colspan = @options[:previous_month] || @options[:next_month] ? 3 : 7 # span across all 7 days if previous and next month aren't shown show_month(@days.first, @options[:current_month], :colspan => colspan, :class => "current") end def show_month(month, format, options={}) options[:colspan] ||= 2 content_tag(:th, :colspan => options[:colspan], :class => "#{options[:class]} #{Date::MONTHNAMES[month.month].downcase}") do if format.kind_of?(Array) && format.size == 2 text = I18n.localize(month, :format => format.first.to_s).html_safe format.last.respond_to?(:call) ? link_to(text, format.last.call(month)) : text else format.respond_to?(:call) ? format.call(month) : I18n.localize(month, :format => format.to_s) end.html_safe end end def day_names @day_names ||= @options[:use_full_day_names] ? Calendar.full_day_names : Calendar.abbreviated_day_names end # => <abbr title="Sunday">Sun</abbr> def include_day_abbreviation(day) return day if @options[:use_full_day_names] content_tag(:abbr, day, :title => Calendar.full_day_names[Calendar.abbreviated_day_names.index(day)]) end def apply_first_day_of_week(day_names) names = day_names.dup first_day_of_week.times { names.push(names.shift) } names end def first_day_of_week @options[:first_day_of_week] end def last_day_of_week @options[:first_day_of_week] > 0 ? @options[:first_day_of_week] - 1 : 6 end end end
true
2a978af4c9071b6ed373a29cea6ad03a7959ada9
Ruby
sergei-kalugin/rashka
/app/helpers/author_helper.rb
UTF-8
1,022
2.671875
3
[ "MIT" ]
permissive
# Хелпер для отображения создателей сайта module AuthorHelper # Отображает данные о создателе # @note На вьюхе about/authors_container # @example # author("authors/fyodor.jpg", "Фёдор Иванищев", "http://vk.com/cbrwizard", "Разработка и борода") # # @param image [String] ссылка на изображение # @param name [String] имя человека # @param link [String] ссылка на сайт чела # @param text [String] описание # @return [HTML] блок для вьюхи def author (image, name, link, text) content_tag(:div, :class => "author_container col-md-4 col-xs-12", :data => {link: link}) do content_tag(:div, :class => "author") do content_tag(:div, :class => "image_container") do image_tag image end + content_tag(:h4) do name end + content_tag(:p) do text end end end end end
true
430e41de21f39da86f04f01957e8bcb2fb3846fe
Ruby
richardrguez/exercises
/projecteuler/07_10001st_prime.rb
UTF-8
521
4.21875
4
[]
no_license
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, # we can see that the 6th prime is 13. # # What is the 10 001st prime number? def is_prime?(n) if n <= 1 return false elsif n == 2 return true else (2..(n-1)).each do |num| if n % num == 0 return false end end end return true end def prime_10001st count = 0 number = 0 while count < 10001 count += 1 if is_prime?(number) number += 1 end puts number - 1 end prime_10001st #Answer: 104743
true
3decd5fbe4a0eea704a0a39b03ef47071da79fbb
Ruby
deisy0820/ruby
/collatz.rb
UTF-8
348
3.9375
4
[]
no_license
#Desarrolle un programa que entregue la secuencia de Collatz de un número entero: #ingreso de datos puts "ingrese un numero entero" n = gets.chomp #conversion de datos n = n.to_i foco = true while foco if n%2==0 res = n/2 puts"#{res}" n = res else n%2==1 res=n*3+1 puts"#{res}" n = res end if res == 1 foco = false end end
true
5917ee81c1dba33809bc475067219ce747f1b716
Ruby
dominicmeddick/oystercard
/spec/oystercard_spec.rb
UTF-8
2,404
3.125
3
[]
no_license
require 'oystercard' describe Oystercard do let(:entry_station) { double :station } let(:exit_station) { double :station} describe '#balance' do it 'responds to balance' do expect(subject).to respond_to(:balance) end it 'has a balance' do expect(subject.balance).to eq(0) end it 'raises an error if balance exceeds £90' do max_bal = Oystercard::MAX_BALANCE subject.top_up(max_bal) expect { subject.top_up(1) }.to raise_error "Maximum balance of #{max_bal} exceeded" end end describe '#top_up' do it 'responds to top up' do expect(subject).to respond_to(:top_up) end it 'top_up takes arguments' do expect(subject).to respond_to(:top_up).with(1).arguments end it 'tops up the card' do expect { subject.top_up 5 }.to change{ subject.balance }.by 5 end end describe '#journey' do it 'is initially not in a journey' do expect(subject).not_to be_in_journey end it 'can touch in' do subject.top_up(1) subject.touch_in(entry_station) expect(subject).to be_in_journey end it 'stores the entry station in' do subject.top_up(1) subject.touch_in(entry_station) expect(subject.entry_station).to eq entry_station end it 'can touch out' do subject.top_up(1) subject.touch_in(entry_station) subject.touch_out(exit_station) expect { subject.touch_out(exit_station) }.to change { subject.balance }.by (-Oystercard::MIN_CHARGE) expect(subject).not_to be_in_journey end it 'stores the exit station' do subject.top_up(1) subject.touch_in(entry_station) subject.touch_out(exit_station) expect(subject.exit_station).to eq exit_station end it 'will not touch in if below minimum balance' do expect { subject.touch_in(entry_station) }.to raise_error 'Insufficient balance to touch in' end end describe '#recordthejourneys' do it 'stores the entry and exit station in a hash' do subject.top_up(1) subject.touch_in(entry_station) subject.touch_out(exit_station) expect(subject.journey_list).to eq([{ entry_station => exit_station }]) end end describe '#initialize' do it 'checks that the card creates an empty journey list' do expect(subject.journey_list).to eq([]) end end end
true