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
9d1844a88afe9055b959e09354a7ea514c1f0faa
Ruby
RhadooPopescu/RubyStatePattern
/observer.rb
UTF-8
789
3.734375
4
[]
no_license
# == Situation == # You are a developer in a large international organisation and have been # approached by the head of human resources. # The current system is great (see below), but when you change an employee's # record only payroll get to know about it. HR need to know about it too! # == Requirement == # Update the existing system so that anyone who is interested in employee # changes gets automatically notified. class Employee attr_reader :name, :salary def initialize(name, salary, payroll) @name = name @salary = salary @payroll = payroll end def salary=(new_salary) @salary = new_salary @payroll.update(self) end end class Payroll def update(employee) puts "PAYROLL: Employee #{employee.name} salary #{employee.salary}" end end
true
f6fa728fa4de57de7ff7508e2d314af8eed6a2d3
Ruby
zlotnika/gene-expressions
/app/models/probeset.rb
UTF-8
1,057
2.78125
3
[]
no_license
class Probeset < ActiveRecord::Base # attr_accessible :probeset_id validates :number, uniqueness: true, presence: true validates :gene_id, numericality: true, allow_nil: true belongs_to :gene has_many :expressions #LJ def find_expression(body_part_id) ex = self.expressions.where("tissue_id = #{body_part_id}").first # has to have .first, because this otherwise returns an array return ex end def get_means() expressions = self.expressions mean_array = [] if expressions for ex in expressions tissue_id = ex.tissue_id tissue = Tissue.find(tissue_id).name mean = ex.mean wee_array = [mean, tissue] mean_array.push(wee_array) end return mean_array else return 0 end end # => Expression(id: integer, mean: float, standard_deviation: float, probeset_id: integer, tissue_id: integer, created_at: datetime, updated_at: datetime) #1.9.3-p362 :064 > ex.class() # returning: => ActiveRecord::Relation # but I want an Expression object end
true
a8c355299523f0853d1b9b4dc6416eeaf59977b1
Ruby
snltd/wavefront-sdk
/lib/wavefront-sdk/support/parse_time.rb
UTF-8
1,261
3
3
[ "BSD-2-Clause" ]
permissive
# frozen_string_literal: true require 'time' module Wavefront # # Parse various times into integers. This class is not for direct # consumption: it's used by the mixins parse_time method, which # does all the type sanity stuff. # class ParseTime attr_reader :t, :ms # param t [Numeric] a timestamp # param ms [Bool] whether the timestamp is in milliseconds # def initialize(time, in_ms = false) @t = time @ms = in_ms end # @return [Fixnum] timestamp # def parse_time_fixnum t end # @return [Integer] timestamp # def parse_time_integer t end # @return [Fixnum] timestamp # def parse_time_string return t.to_i if t.match?(/^\d+$/) @t = Time.parse("#{t} #{Time.now.getlocal.zone}") parse_time_time end # @return [Integer] timestamp # def parse_time_time if ms t.to_datetime.strftime('%Q').to_i else t.strftime('%s').to_i end end def parse_time_datetime parse_time_time end def parse! method = "parse_time_#{t.class.name.downcase}".to_sym send(method) rescue StandardError raise Wavefront::Exception::InvalidTimestamp, t end end end
true
be32265369c8f3fac22875fc43b97af2ac897a03
Ruby
yzlin/Omazing
/Rakefile
UTF-8
818
2.8125
3
[ "MIT" ]
permissive
class String def self.colorize(text, color_code) "\e[#{color_code}m#{text}\e[0m" end def red self.class.colorize(self, 31) end def green self.class.colorize(self, 32) end end desc 'Run the tests' task :test do verbose = ENV['VERBOSE'] ret = test_scheme('Omazing', 'Omazing', verbose) puts "\n\n\n" if verbose puts "Mac: #{ret == 0 ? 'PASSED'.green : 'FAILED'.red}" exit ret end def test_scheme(workspace, scheme, verbose=false) ret = -1 output = `xcodebuild -workspace #{workspace}.xcworkspace -scheme #{scheme} clean test 2>&1` for line in output.lines if line == "** TEST SUCCEEDED **\n" puts line.green ret = 0 elsif line == "** TEST FAILED **\n" puts line.red ret = 1 else puts line if verbose end end return ret end
true
55465fb3fe544374471aaef2adf2d5079c1a625f
Ruby
LHJE/tech_challenges
/find_the_odd_int/lib/odd_int.rb
UTF-8
143
2.859375
3
[]
no_license
class OddInt def find_it(array) array.sort.find do |unit| if array.count(unit) % 2 == 1 unit end end end end
true
9bd2329ca4c352185141133940799a447b1ea682
Ruby
jferoman/flowers
/app/models/block_color_flower.rb
UTF-8
2,550
2.578125
3
[]
no_license
class BlockColorFlower < ApplicationRecord validates :usage, inclusion: { in: [ true, false ] } validates :block_id, uniqueness: { scope: [:flower_id, :color_id] } belongs_to :block belongs_to :flower belongs_to :color class << self def import file_path blocks_color_flowers = [] errors = [] CSV.foreach(file_path, { encoding: "iso-8859-1:utf-8", headers: true, converters: :all, header_converters: lambda { |h| I18n.transliterate(h.downcase.gsub(' ','_'))}} ) do |row| color_id = (Color.find_by(name: row["color"].to_s.upcase).id rescue nil) if color_id.nil? errors << { initial_values: row.to_h, error: "Color #{row["color"]} no encontrado." } next end flower_id = (Flower.find_by(name: row["flor"].to_s.upcase).id rescue nil) if flower_id.nil? errors << { initial_values: row.to_h, error: "Flor: #{row["flor"]} no encontrada." } next end block_id = (Block.find_by(name: row["bloque"].to_s.upcase).id rescue nil) if block_id.nil? errors << { initial_values: row.to_h, error: "Bloque: #{row["bloque"]} no encontrado." } next end blocks_color_flower = BlockColorFlower.find_by(block_id: block_id, flower_id: flower_id, color_id: color_id) if !blocks_color_flower.nil? errors << { initial_values: row.to_h, error: "El resgsitro #{row["color"]}, #{row["flor"]}, #{row["bloque"]} ya existe." } next end blocks_color_flowers << { usage: (row["uso"] == 1 ? true : false), color_id: color_id, block_id: block_id, flower_id: flower_id } end if errors.empty? BlockColorFlower.bulk_insert values: blocks_color_flowers else csv_with_errors errors end end private def csv_with_errors blocks_color_flowers_list attributes = %w{bloque color flor uso errores} file_path = "db/tmp_files/errores_uso_bloques.csv" CSV.open(file_path, "wb") do |csv| csv << attributes blocks_color_flowers_list.each do |data| csv << [data[:initial_values].values, data[:error]].flatten end end file_path end end end
true
42fc979546bf070a5751f390f64c6001ee95c85c
Ruby
apfeltee/siteget
/sget.rb
UTF-8
9,487
2.71875
3
[]
no_license
#!/usr/bin/ruby require "uri" require "json" require "yaml" require "digest" require "fileutils" require "optparse" require "http" require "nokogiri" require "trollop" SGET_DEFAULTS = { useragent: "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.80 Safari/537.36", } module Utils def self.mkclean(olds) s = olds.scrub.gsub(/[^[:ascii:]]/, "").gsub(/[^[:alnum:].-]/, "-") %w(- _ .).each do |c| dup = Regexp.new(Regexp.quote(c) + "{2,}") while (w=s.match(dup)) != nil do s.gsub!(dup, c) end end s.gsub!(/^[-_.]/, "") return s end def self.mkname(url, selextension=nil) # get url components (for query string) purl = URI.parse(url) extension = File.extname(purl.path) basename = File.basename(purl.path, extension) # make a "clean" name ... #cleanname = (basename + (purl.query ? purl.query : "")).gsub(/[^0-9A-Za-z]/, "-").gsub(/^-/, "") cleanname = mkclean(basename + (purl.query ? purl.query : "")) # if filename exceeds a certain length, turn it into a hash sum instead # (rather than trying to figure out how to create a unique filename, even by shrinking ...) # appends the first 10 characters from the original cleanname, to ease identification if cleanname.length > 500 then #mlog("filename is too long, using hashsum instead") #cleanname = cleanname[0 .. 10] + Digest::MD5.hexdigest(cleanname) hexdg = Digest::MD5.hexdigest(cleanname) cleanname = sprintf("%s-%s", cleanname[0 .. 20], hexdg[0 .. 8]) end # create a physical location for the file to be written to if (selextension == nil) || (extension.length == 0) || (extension == "") then extension = "unknown" end if (extension.length > 0) && (extension[0] == ".") then extension = extension[1 .. -1] end return (cleanname + "." + extension) end end class HTTPClient attr_accessor :response def initialize(url, params={}, method: "get", follow: true, timeout: 5, headers: {}) #HTTP.get(url, params: params).follow() #@response = HTTP.send(method) @response = HTTP.timeout(:global, :write => timeout, :connect => timeout, :read => timeout ).headers(headers).follow(follow).send(method, url) end def _verify stcode = @response.code if stcode != 200 then raise "HTTP status error (expected 200, got #{stcode})" end end def body return @response.body end def code return @response.code end def ok? return (@response.code == 200) end def failed? return (ok? == false) end def to_file(path) _verify dirp = File.dirname(path) FileUtils.mkdir_p(dirp) unless File.directory?(dirp) File.open(path, "wb") do |fh| # a neat feature of http.rb is that it only retrieves # the header at first -- which makes HTTP queries very lightweight. # the actual body is downloaded later (http.rb calls it streaming), # and here's a prime example of how useful this actually is! while true do data = @response.readpartial break if (data == nil) fh.write(data) end end end end class Selector attr_accessor :selector, :node, :extension, :post def initialize(expr, rnode, extension="file", post=nil) @selector = expr @node = rnode @extension = extension @post = post end end class SiteGet # most of these are *static* attempts at figuring out where resources are. # ideally, this should be done dynamically; i.e., checking response headers, and # even having to partially interpret javascript, especially since things like coffeescript # imply that a resource that looks like garbage could end up being code that gets preprocessed... # same thing goes for SVG, et al. so this is as good as it gets. # sorry :-( @@selectors = [ # javascript {sel: "script[src]", rep: "src", ext: "js", post: nil}, #JSPostProcessor # fucking twitter {sel: "link[href][as=script]", rep: "href", ext: "js", post: nil}, # images {sel: "img", rep: "src", ext: nil}, {sel: "image", rep: "src", ext: nil}, {sel: "img[data-thumb]", rep: "data-thumb", ext: nil, post: nil}, {sel: "img[data-src]", rep: "data-src", ext: nil, post: nil}, {sel: "input[src][type=image]", rep: "src", ext: nil, post: nil}, # css {sel: "link[rel=stylesheet][href]", rep: "href", ext: "css", post: nil}, # CSSPostProcessor # favicons {sel: "link[rel*=icon][href]", rep: "href", ext: nil, post: nil}, {sel: "link[rel*=shortcut][href]", rep: "href", ext: nil, post: nil}, ] def initialize(uri, opts) $stdout.sync = false @opts = opts @site = geturl(uri.to_s) @parsed = uri @flog = {info: {}, urls: []} FileUtils.mkdir_p(@opts.destination) end def mlog(fmt, *args) #$stdout << "-- " << str << "\n" $stderr.printf("-- %s\n", sprintf(fmt, *args)) end def writelog File.open(File.join(@opts.destination, "url-log.json"), "wb") do |fh| fh.write(JSON.pretty_generate(@flog)) end end def geturl(url, **kwargs) mlog("downloading %p ...", url) #res = HTTP.follow(true).get(url) res = HTTPClient.new(url, headers: {"User-Agent" => @opts.useragent}) if res.failed? then mlog("failed? HTTP code=%d", res.code) return nil end return res end # this monstrosity of a function parses and (re)creates URLs, based on whether # they are relative, absolute, or remote. # input is the URL, and the selector hash, returns the generated local destination. # will download the file is the local destination does not exist yet. def mkurl(oldurl, selector) mlog("checking %p ...", oldurl) url = oldurl # yes, technically one can include a resource from FTP. # some people actually do that. # but you really shouldn't. if oldurl.match(/^(https?|ftp)/) or (autoscm = oldurl.match(/^\/\//)) then if autoscm then # in case of "//somehost.com/..." urls, just create an absolute url by # reusing the scheme from the mothership url = @parsed.scheme + ":" + oldurl end else # macgyver the url together from the mothership scheme and host url = String.new url << @parsed.scheme << "://" << @parsed.host # if the url starts with a slash, it's an absolute path (i.e., "/blah/something.js") if oldurl.match(/^\//) then url << oldurl else # otherwise, it's a relative one (i.e., "subdir/whatever/thing.js") url << File.dirname(@parsed.path) if ((url[-1] != "/") && (oldurl[0] != "/")) then url << "/" end url << oldurl end end localdest = File.join(@opts.resdir, Utils.mkname(url, selector)) fulldest = File.join(@opts.destination, localdest) # coincidentally, the local url is the same as the file dest. whudathunkit @flog[:urls] << {url: url, local: fulldest} if File.file?(fulldest) then return localdest end response = geturl(url) if response then mlog("storing as %p", fulldest) FileUtils.mkdir_p(File.join(@opts.destination, @opts.resdir)) response.to_file(fulldest) return localdest end raise Exception, "bad response from geturl?" end def parse removeme = %w(crossorigin integrity) @flog[:info][:mainpage] = @parsed.to_s body = @site.body.to_s main = Nokogiri::HTML(body) @@selectors.each do |selector| # iterate over each selector mlog("++ processing selector %p ...", selector[:sel]) if (nodes = main.css(selector[:sel])) then nodes.each do |node| removeme.each do |rm| node.remove_attribute(rm) end url = node[selector[:rep]] if url != nil then localurl = mkurl(url, selector) mlog("rewriting %p", url) # modify the node with the new url # gotta love nokogiri node[selector[:rep]] = localurl end end end end # write the shite to file File.open(File.join(@opts.destination, @opts.htmlfile), "w") do |fh| fh << main.to_html end end end begin #opts = Trollop::options do # opt :destination, "Use <destination> as directory to store website", default: ".", type: :string # opt :htmlfile, "Use <htmlfile> instead of index.html", default: "index.html", type: :string # opt :resdir, "Use <resdir> instead of 'res' as resources directory name", default: "res", type: :string #end opts = OpenStruct.new({ destination: nil, htmlfile: "index.html", resdir: "res", }) prs = OptionParser.new{|prs| prs.on("-d<s>", "--destination=<s>", "Use <destination> as directory to store website"){|s| opts.destination = s } prs.on("-f<s>", "--htmlfile=<s>", "Use <htmlfile> instead of index.html"){|s| opts.htmlfile = s } prs.on(nil, "--resdir=<s>", "Use <resdir> instead of 'res' as resources directory name"){|s| opts.resdir = s } } prs.parse! if ARGV.length > 0 then arg = ARGV.shift uri = URI.parse(arg) if opts.destination.nil? then opts.destination = uri.host end sg = SiteGet.new(uri, opts) begin sg.parse ensure sg.writelog end elsif ARGV.length > 1 then puts "can only process one URL at a time!" else puts "usage: sget <URL>" end end
true
935d0a8d2641dfa165cef04d384584f0758d50a9
Ruby
buzzamus/jalapeno
/lib/jalapeno/musics.rb
UTF-8
679
3.140625
3
[]
no_license
module Musics quotes = ["I hurt myself today to see if I still feel. I focus on the pain. The only thing that's real", "If there's a bustle in your hedgerow, Don't be alarmed now, It's just a spring clean for the May Queen", "Nothing's gonna change my world", "The world is a game to be played", "Time takes a cigarette, puts it in your mouth", "Don't critize what you can't understand", "I feel like i'm looking for my soul, like a poor man looking for gold", "I know that I was born and I know that i'll die. The in between is mine", "War, children, it's just a shot away"] QUOTE = quotes[rand(0..quotes.length - 1)] end
true
9ede2be3f0d2e8d73e8bf646eac85bff785b4040
Ruby
Raphael-dln/THP-Ruby
/exo_05.rb
UTF-8
1,964
3.78125
4
[]
no_license
# Affiche "On va compter le nombre d'heures de travail à THP" puts "On va compter le nombre d'heures de travail à THP" # Va afficher travail : 550 (multiplication de 10 heures, 5 jours et 11 semaines) puts "Travail : #{10 * 5 * 11}" # Affiche ce qui est entre "" + Multiplication du précédent nombre par 60 pour afficher le nombre de minutes puts "En minutes ça fait : #{10 * 5 * 11 * 60}" #Affiche "Et en secondes" puts "Et en secondes ?" # Multiplication par 60 pour connaître le nombre de secondes puts 10 * 5 * 11 * 60 * 60 # Affiche ce qui est marqué entre guillemets (text only) puts "Est-ce que c'est vrai que 3 + 2 < 5 - 7 ?" # Affiche ce qui est entre "" + avec "<", Ruby calcule directement si l'affirmation est vraie ou fausse et affiche le résultat uniquement puts 3 + 2 < 5 - 7 # Affiche ce qui est entre "" + La commande #{3 + 2} additionne 3 et 2 et affiche directement le résultat (5) dans le terminal puts "Ça fait combien 3 + 2 ? #{3 + 2}" # Affiche ce qui est entre "" + La commande #{5 -7} soustraint 7 à 5 et affiche directement le résultat (-2) dans le terminal puts "Ça fait combien 5 - 7 ? #{5 - 7}" # Affiche ce qui est marqué entre guillemets (text only) puts "Ok, c'est faux alors !" # Affiche ce qui est marqué entre guillemets (text only) puts "C'est drôle ça, faisons-en plus :" # Affiche ce qui est marqué entre guillemets puis calcule si l'équation est vraie ou fausse (ici vraie) puts "Est-ce que 5 est plus grand que -2 ? #{5 > -2}" # Affiche ce qui est marqué entre guillemets puis calcule si l'équation est vraie ou fausse (ici vraie) puts "Est-ce que 5 est supérieur ou égal à -2 ? #{5 >= -2}" # Affiche ce qui est marqué entre guillemets puis calcule si l'équation est vraie ou fausse (ici fausse) puts "Est-ce que 5 est inférieur ou égal à -2 ? #{5 <= -2}" # La variable #{} affiche le résultat de l'opération ou de l'équation contenu entre les crochets plutôt que l'opération elle-même
true
b8b489db9d86accb5ee7713bffa03cae1f6d76f1
Ruby
taisukef/micro_mruby_for_lpc1114
/for2.0/blink5.rb
UTF-8
47
2.75
3
[ "BSD-3-Clause" ]
permissive
loop do a = :puts puts -1000 #break end
true
f3ffb0daa39a6b271421d4e8b06ac69b9d460c7b
Ruby
esimonian/codeexamples
/ruby1.rb
UTF-8
1,592
3.9375
4
[]
no_license
# Determine if a sentence is a pangram class Pangram VERSION = 1 def self.is_pangram?(str) ans = ['a'..'z'] - str.downcase.chars ans.empty? end end # Find the difference between the sum of the squares # and the square of the sums of the first N natural numbers class Squares VERSION = 2 def initialize(num) @num = (0..num) end def square_of_sum @num.reduce(:+)**2 end def sum_of_squares @num.reduce { |a, e| a + e**2 } end def difference square_of_sum - sum_of_squares end end # Pling, Plang, Plong class Raindrops VERSION = 1 def self.convert(n) answer = '' answer += 'Pling' if n % 3 == 0 answer += 'Plang' if n % 5 == 0 answer += 'Plong' if n % 7 == 0 return n.to_s if answer.empty? answer end end # Calculate the date that someone turned or will celebrate their 1 Gs anniversary. class Gigasecond VERSION = 1 @gigasecond = 10**9 def self.from(bday) bday + @gigasecond end end # Given a DNA strand it returns its RNA complement (per RNA transcription). class Complement VERSION = 3 def self.of_dna(dna) raise ArgumentError, 'Not valid DNA' if dna =~ /[^GCTA]/ dna.tr('GCTA', 'CGAU') end end # Calculate the Hamming difference between two DNA strands class Hamming VERSION = 1 def self.compute(string1, string2) string1 = string1.split("") string2 = string2.split("") if string1.length != string2.length raise ArgumentError, "Unequal lengths" else answer = string1.zip(string2).map{|x, y| x==y} answer.count(false) end end end
true
700c22632d38d4584defd844c22454212ab4ff83
Ruby
niorio/Chess
/lib/computer_player.rb
UTF-8
2,194
3.390625
3
[]
no_license
class ComputerPlayer attr_reader :color def initialize(board) @color = :b @board = board end def play_turn @possible = possible_moves return checkmate_move unless checkmate_move.nil? return check_moves.sample unless check_moves.empty? return good_trade.sample unless good_trade.empty? return safe_moves.sample unless safe_moves.empty? return attack_moves.sample unless attack_moves.empty? @possible.sample end def check_moves check_moves = [] @possible.each do |move| duped_board = @board.dup duped_board.move(move[0],move[1]) if duped_board.in_check?(:w) check_moves << move end end check_moves end def checkmate_move @possible.each do |move| duped_board = @board.dup duped_board.move(move[0],move[1]) return move if duped_board.checkmate?(:w) end nil end def possible_moves possible_moves = [] @board.collect_pieces(color).each do |piece| piece.valid_moves.each {|move| possible_moves << [piece.position, move] } end possible_moves end def safe_moves safe_moves = [] @possible.each do |move| duped_board = @board.dup duped_board.move(move[0],move[1]) opponent_color = color == :w ? :b : :w all_possible_moves = [] duped_board.collect_pieces(opponent_color).each do |piece| all_possible_moves += piece.valid_moves end unless all_possible_moves.include?(move[1]) safe_moves << move end end safe_moves end def good_trade good_trades = [] @possible.each do |move| base_val = @board[move[0]].class::VALUE new_val = @board[move[1]].nil? ? 0 : @board[move[1]].class::VALUE if new_val >= base_val good_trades << move end end good_trades end def attack_moves possible_attacks = @possible.select do |move| !@board[move[1]].nil? end possible_attacks.sort! {|move| @board[move[1]].class::VALUE} possible_attacks.reverse best_val = @board[possible_attacks[0][1]].class::VALUE possible_attacks.select{|move| move[1].class::VALUE >= best_val} end end
true
197c7b84fe0149a4a730b433ddd1f0f91aca1a79
Ruby
reedstonefood/flamme_rubuge
/lib/flamme_rubuge/race.rb
UTF-8
2,057
3.265625
3
[]
no_license
module FlammeRubuge # A race, or game class Race class InvalidPlayerDetailsError < StandardError; end attr_reader :players, :track, :state # players_details looks like {name: "Bob", color: :red, cyclists: [SPRINTER, ROLLER]} # The elements of cyclist array must be part of Cyclist.TYPES def initialize(player_details, track) validate_player_details(player_details) @players = [] create_players(player_details) @track = track.map { |square| FlammeRubuge::Square.new(square) } # a valid track is an Array of Squares. @turns = [Turn.new(self)] @state = :undefined end def current_turn @turns.last end def next_turn new_turn = Turn.new(self) @turns << new_turn new_turn end def create_starting_grid(method, params = nil) if method == :random random_starting_grid elsif method == :strict_order assign_cyclists_to_startzone(params) else raise NotImplementedError, method end end private def create_players(player_details) player_details.each do |player| cyclists = player[:cyclists].map do |cyclist_type| cyclist_type[:klass].new end players << Player.new(player[:color], player[:name], cyclists) end end def validate_player_details(player_details) player_details.each do |player| missing_keys = %i[name color cyclists] - player.keys raise InvalidPlayerDetailsError missing_keys unless missing_keys.empty? end end def random_starting_grid cyclists = @players.map(&:cyclists).flatten.shuffle assign_cyclists_to_startzone(cyclists) end def assign_cyclists_to_startzone(cyclists) startzone.each do |square| break if cyclists.empty? while (spare_lane = square.empty_lane) spare_lane.occupant = cyclists.shift break if cyclists.empty? end end end def startzone track.filter(&:start?).reverse end end end
true
2f37816f8559dc1a5bcd377436fe3af5dec4f40d
Ruby
adamhundley/black_thursday
/lib/invoice_item.rb
UTF-8
716
2.890625
3
[]
no_license
class InvoiceItem attr_reader :invoice_item attr_accessor :item, :invoice def inspect "#<#{self.class}>" end def initialize(invoice_item) @invoice_item = invoice_item end def item_id invoice_item[:item_id] end def id invoice_item[:id].to_i end def invoice_id invoice_item[:invoice_id].to_i end def created_at Time.parse(invoice_item[:created_at]) end def updated_at Time.parse(invoice_item[:updated_at]) end def quantity invoice_item[:quantity].to_i end def unit_price invoice_item[:unit_price] end def unit_price_to_dollars (unit_price / 100.0).round(2) end def revenue unit_price_to_dollars * quantity end end
true
3ca950ac8b805ff2477b654d93c5721dbfd29e65
Ruby
Leandro01832/ruby
/12_07_2019aula16/Abstrata.rb
UTF-8
223
2.671875
3
[]
no_license
class Abstrata def initialize raise "classe não pode ser instanciada, somente herdada, classe abstrata" end def teste1 raise "não implementada" end def teste2 "este é um teste 2" end end
true
71a15a68bc156336dde700eedc2b0ac01e7f98d2
Ruby
anandu/Test
/t3_check.rb
UTF-8
366
2.703125
3
[]
no_license
#!/usr/bin/ruby -w unless ARGV.length == 2 puts "Usage: ./check.rb value2reach startinputl" exit end count = ARGV[0].to_i count1 = ARGV[1].to_i t = 0 #puts count #puts count1 while count != count1 t = t + 1 count = count + t puts count if count != count1 t += 1 count -= t puts count end end puts "reached to", count # count += 1 #end
true
757d5136a331873cbffba1d6d740b1fd52e6a22b
Ruby
maritimememory/kwk-l1-ruby-2-meal-choice-lab-kwk-students-l1-stl-061818
/meal_choice.rb
UTF-8
654
4.34375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Here's an example of a 'snacks' method that returns the meal choice passed in to it and defaults to "cheetos" if nothing is passed in. def snacks(food="Cheetos") "Any time, is the right time for #{food}!" end # Define breakfast, lunch and dinner methods that return the meal choice passed into them. If nothing is passed in, it shoud default to the foods on the readme (frosted flake, grilled cheese, salmon) def meal(breakfast = "frosted flakes", lunch = "grilled cheese", dinner = "salmon") puts "Morning is the best time for #{breakfast}!" puts "Noon is the best time for #{lunch}!" puts "Evening is the best time for #{dinner}!" end meal
true
f8cccdf6f9dff766d288fdbbfb5620ac0e9e3ca8
Ruby
akchalasani1/myruby
/examples/RubyMonk/sum_of_cubes.rb
UTF-8
170
3.8125
4
[]
no_license
# Returns the sum of cubes for a given Range a through b. def sum_of_cubes(a, b) (a..b).inject(0) { |sum, x| sum += (x*x*x) } end test = sum_of_cubes(3, 5) puts test
true
4fbb852663eb999a4497b6137f6429456dcf45ca
Ruby
Kennethjk3/2.3-Minitest_ATM
/minitest.rb
UTF-8
1,147
2.578125
3
[]
no_license
require 'minitest/autorun' require '.' require './User.rb' class TestAtm < MiniTest::Unit::TestCase def setup @user= User.new @atm= ATM.new end def self.input gets.chomp end def test_auth assert_equal true, @user.authenticate('Ken', 4567) end def test_not_auth assert_equal true, @user.authenticate('Ken', 7487) end def test_atm_prompt user = "stan" @atm.stub(:prompt, user) do assert_equal user, @atm.prompt("What's your name", "Error") end # def test_sel1 # test when 1 is selected = outputs "when....#{user_funds}" # end # # def test_menu # # assert_equal @atm.options(1, "Your Balance Is #{@user_available_fund}") # # end # def test_display_err_msg # out, _ = capture_io do # @prog.display_error # end # assert_match "Something has gone horribly wrong. This machine", out # end # # stub an instance varible # @atm = Atm.new # # # Test method. # # def test(selected_option) # # # Return a case. # # return case @selected_option # # when 1 then " " # # when 2 then " " # # when 3 then " " # # else "Invalid" # # end # # end end end
true
92b0151595b161a9405f3de1209709f6891dbee2
Ruby
Bishoy-Samwel/Telegram-Bot
/lib/bot_logic.rb
UTF-8
1,553
2.609375
3
[ "MIT" ]
permissive
require_relative './app_config' require_relative './reply' require 'telegram/bot' reply = Reply.new # rubocop: disable Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity, Metrics/MethodLength define_method :respond do |message, id, first_name = ''| unless message.nil? if message['start'] || message['Hi'] return [{ chat_id: id, text: "Hi, #{first_name} " + reply.reply_txt['welcome'], reply_markup: reply.keyboard('commands') }] elsif message['help'] return [{ chat_id: id, text: reply.reply_txt['commands'], reply_markup: reply.keyboard('commands') }] elsif message['suggest'] || message['Yes'] return [{ chat_id: id, text: reply.reply_txt['ask_category'], reply_markup: reply.keyboard('ask_category') }] elsif message['No'] || message['stop'] return [{ chat_id: id, text: "Bye, #{first_name}" }] elsif reply.scrapper.category?(message) reply.get_suggestions(message) return [{ chat_id: id, text: reply.reply_txt['suggestions'], reply_markup: reply.keyboard('show_suggestions') }] elsif reply.scrapper.recipe?(message) reply.get_recipe(message) return [{ chat_id: id, text: reply.reply_txt['recipe'], parse_mode: 'html' }, { chat_id: id, text: reply.reply_txt['another_recipes'], parse_mode: 'html', reply_markup: reply.keyboard('yes_no') }] end end end # rubocop: enable Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity, Metrics/MethodLength
true
bf78f2d213e8e40e32adaaedb7cedbc91ad75b9f
Ruby
kevino2/Bear-River-Fish
/pet_shop_start_point/customer.rb
UTF-8
510
3.75
4
[]
no_license
class Customer attr_accessor :name, :cash def initialize (name, cash) @name = name @cash = cash @pets = [] end # can use .size or .length def pet_count return @pets.count end def add_pet(new_pet) return @pets.push(new_pet) end def get_total_of_pets() total = 0 for pet in @pets total += pet.price end return total end def buy_pet(name, shop) pet = shop.find_by_name(name) if (pet != nil && @cash >= pet.price) shop.sell_pet(pet) add_pet(pet) end end
true
57dc41249f734492cc8567166563d0fe6bcb16ca
Ruby
t5krishn/ruby-2-player-game
/helpers.rb
UTF-8
306
3.5
4
[]
no_license
def getQnA() operations = ['plus', 'subtract'] num1 = rand(10) + 1 num2 = rand(10) + 1 op = rand(2) ans = 0 if (op == 0) ans = num1 + num2 else ans = num1 - num2 end question = {q: "#{num1} #{operations[op]} #{num2}", a: ans} return question end
true
3aee0b26b0f5d48931222c3dcfa0bab1b0784617
Ruby
chalt0319/looping-loop-v-000
/looping.rb
UTF-8
61
2.6875
3
[]
no_license
def looping loop do puts "Wingardium Leviosa" end end looping
true
18000a69efd5a7dcd13a07c69e5211d7691d69f9
Ruby
kmic1986/Ruby-Foundations-More-Topics
/Challenges/04 Advanced 1/simple_cipher.rb
UTF-8
950
3.609375
4
[]
no_license
# 97 - 122 class Cipher attr_reader :key def initialize(k=make_key) @key = k raise ArgumentError if k == '' k.chars.each do |e| if e.ord < 97 || e.ord > 122 raise ArgumentError end end end def encode(string) result = '' string.chars.each_with_index do |c, i| shift_amount = @key[i].ord - 97 if c.ord <= 122 - shift_amount result += (c.ord + shift_amount).chr else result += (c.ord + shift_amount - 26).chr end end result end def decode(string) result = '' string.chars.each_with_index do |c, i| shift_amount = @key[i].ord - 97 if c.ord >= 97 + shift_amount result += (c.ord - shift_amount).chr else result += (c.ord - shift_amount + 26).chr end end result end def make_key r = Random.new string = '' 100.times { |i| string += r.rand(97..122).chr } string end end
true
06a7243f543ec1d7bdb26afe07c1fc97c558cf1c
Ruby
acannie/progate
/ruby/ruby_study_1/page18/index.rb
UTF-8
282
3.375
3
[ "MIT" ]
permissive
number = 48 # 条件分岐を作成してください if number % 3 == 0 && number % 5 == 0 puts "15の倍数です" elsif number % 5 == 0 puts "5の倍数です" elsif number % 3 == 0 puts "3の倍数です" else puts "3の倍数でも5の倍数でもありません" end
true
02a5ff9f01aae689ec950bd540eb32b12d4e4646
Ruby
lexus2727/ruby-intro-to-arrays-lab-online-web-prework
/lib/intro_to_arrays.rb
UTF-8
1,508
4.21875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# instantiate_new_array def instantiate_new_array ary = Array.new # => [] end # indexing to access specific array elements def array_with_two_elements ary = Array.new Array.new(2) end # retrieving the first element from the Array def first_element(array) taylor_swift = ["Welcome to New York", "Blank Space", "Style", "Out of The Woods"] taylor_swift[0] end # retrieving the third element from the array, using a positive index def third_element(array) taylor_swift = ["Welcome to New York", "Blank Space", "Style", "Out of The Woods"] taylor_swift[2] end # retrieving the last element from the array, using a negative index def last_element(array) taylor_swift = ["Welcome to New York", "Blank Space", "Style", "Out of The Woods"] taylor_swift[-1] end # element returned from array without referencing the index number of element def first_element_with_array_methods(array) south_east_asia = ["Thailand", "Cambodia", "Singapore", "Myanmar"] south_east_asia.first end #element returned from array without referencing the index number of element def last_element_with_array_methods(array) south_east_asia = ["Thailand", "Cambodia", "Singapore", "Myanmar"] south_east_asia.last end #Using length to query about the number of elements in an array, not counting from zero def length_of_array(array) programming_languages = ["Ruby", "Javascript", "Python", "C++", "Java", "Lisp", "PHP", "Clojure"] programming_languages.length # => 8 end
true
fe439c9b0957768643e59a695fdec028af81f70f
Ruby
jflohre/goals
/app/models/quote.rb
UTF-8
490
2.578125
3
[]
no_license
# == Schema Information # # Table name: quotes # # id :integer not null, primary key # description :string(255) # name :string(255) # created_at :datetime not null # updated_at :datetime not null # class Quote < ActiveRecord::Base attr_accessible :description, :name def self.display_message Quote.pluck(:description).sample end def self.display_name(quote) Quote.where("description" => quote).pluck(:name).sample end end
true
f85759101097734efe8a59fab84ce10407d2a3fa
Ruby
guymorita/ruby_practice
/fizzbuzz.rb
UTF-8
2,499
4.21875
4
[]
no_license
def reverse_each_word(sentence) words = sentence.split(' ') y = [] words.each { |x| y << x.reverse } y.join(" ") end def square(number) number*number end def cube(number) square(number)*number end #print out all # between 1-100, if mult 3 fizz, if mult 5 buzz, if mult 10 fizzbuzz def fizzbuzz y = (1..100) y.each { |x| if x % 3 == 0 && x % 5 == 0 puts "fizzbuzz" elsif x % 3 == 0 puts "fizz" elsif x % 5 == 0 puts "buzz" else puts x end } end #calcit - calculator that can add, subtract, multiply, divide # advanced - exponents and square roots def add(x,y) x+y end def subtract(x,y) x-y end def multiply(x,y) x*y end def divide(x,y) x/y end def expo(x,y) x**y end def root(x,y) x**(1/y) end def valid_op arr = ["add", "subtract", "multiply", "divide", "exponent", "root"] if arr.include?(@operator) == false puts "Please put in a valid operator" calcit end end def valid_num if @first == 0.0 || @second == 0.0 puts "Sorry you need to put in numbers greater than 0" calcit end end def standard puts "which operator? add, subtract, multiply, divide" @operator = gets.chomp.downcase puts "first number" @first = gets.chomp.to_f puts "second number" @second = gets.chomp.to_f valid_op valid_num case @operator when "add" add(@first,@second) when "subtract" subtract(@first,@second) when "multiply" multiply(@first,@second) when "divide" divide(@first,@second) else puts "Please try again" standard end end def advanced puts "which operator? exponent, squareroot" @operator = gets.chomp.downcase puts "first number" @first = gets.chomp.to_f puts "second number" @second = gets.chomp.to_f valid_op valid_num case @operator when "exponent" expo(@first, @second) when "root" root(@first, @second) else puts "Please try again" advanced end end def calcit puts "Welcome to the calcit" puts "Enter '1' if you want standard" puts "Enter '2' if you want advanced" input = gets.chomp.to_i case input when 1 standard when 2 advanced else puts "Please try again" calcit end end def name_tag puts "what is your first name: " first = gets.chomp puts "what is your last name: " last = gets.chomp puts "what is your gender: " gender = gets.chomp puts "what is your age: " age = gets.chomp.to_i if age < 19 && gender == "female" puts "Miss #{first} #{last}" elsif age >= 19 && gender == "female" puts "Mrs #{first} #{last}" else puts "Mr #{first} #{last}" end end
true
4d1380d2e48307e3f12b23df461338fe4aca4d57
Ruby
Chris-Manna/Cool-Code
/RocksPapersScissors.rb
UTF-8
220
3.0625
3
[]
no_license
class Display ARR = [:ROCKS, :PAPERS, :SCISSORS] def initialize(first_entry,sec_entry = rand(2).round) @entry = entry.upcase.to_sym @sec_entry = sec_entry end def display_winner end def entry end end
true
e15c7bc85b16e943c39a06d6f2911ed001367bd1
Ruby
zsy056/solutions
/leetcode/240-search-a-2d-matrix-ii.rb
UTF-8
319
3.375
3
[]
no_license
# @param {Integer[][]} matrix # @param {Integer} target # @return {Boolean} def search_matrix(matrix, target) i = 0 j = matrix[0].size - 1 while i < matrix.size and j >= 0 if matrix[i][j] == target return true elsif matrix[i][j] < target i += 1 else j -= 1 end end false end
true
225baed57aea3dcf7976b50d996c908e316e3129
Ruby
murex/murex-coding-dojo
/Beirut/2015/2015-11-25-PowerDigitSum/power_digit_sum.rb
UTF-8
175
3.296875
3
[ "MIT" ]
permissive
class PowerDigitSum def compute(power) sum=0 to_power = (2**power).to_s digits = to_power.split("").each do |i| sum = sum+ i.to_i end sum end end
true
b2df4954a52c593adc38f18d559b5ec25d4b34fb
Ruby
thomasfrl/thp_jeudi
/exo_09.rb
UTF-8
211
3.46875
3
[]
no_license
puts "Bonjour, c'est quoi ton prénom ?" print "> " user_name = gets.chomp puts "Et c'est quoi ton nom de famille ?" print "> " user_familyName = gets.chomp puts "Bonjour, #{user_name} #{user_familyName} !"
true
b19809a0f25269f22175eb958fb5759aff785924
Ruby
Renestl/AAO
/1 Intro/11_hashes/hashes2.rb
UTF-8
686
4.21875
4
[]
no_license
# Hash Methods # .length # .has_key?(k) # .has_value?(v) # .keys # .values dog = { "name" => "Fido", "color" => "black", "age" => 3, "isHungry" => true, "enemies" => ["squirrel"] } # puts dog # puts dog.length # dog["name"] = "Spot" # puts dog # !!Add to array after the fact # dog["location"] = "MO" # puts dog # print dog["enemies"] << "mailman" # puts # puts dog # print dog.has_key?("color") #true # print dog.has_key?("location") #false # print dog.has_key?("Color") #false # print dog.has_value?("black") #true # print dog.has_value?(false) #false # !!Get an array of all the keys or values # print dog.keys # print dog.values # print dog.keys[1] #index into array
true
203448feaa0daa6f6998f581b5e01b7736d4167f
Ruby
eldemonstro/AdventOfCode2019
/day2/part_2.rb
UTF-8
721
3.390625
3
[]
no_license
# frozen_string_literal: true text = File.open(__dir__ + '/input.txt').read input_frozen = text.chomp.split(',').map(&:to_i).freeze nouns = (0..99) verbs = (0..99) stop = false nouns.each do |noun| verbs.each do |verb| input = input_frozen.dup input[1] = noun input[2] = verb input.each_slice(4) do |op_code, pos_x, pos_y, pos_result| x = input[pos_x] y = input[pos_y] break if op_code == 99 if op_code == 1 input[pos_result] = x + y elsif op_code == 2 input[pos_result] = x * y end end next unless input[0] == 19_690_720 puts "noun #{noun}, verb #{verb}, result #{100 * noun + verb}" stop = true end break if stop end
true
318506528a72687c8977394b019e44daed45336e
Ruby
davidbalbert/ruby_games
/001/original_spec/example_entry.rb
UTF-8
389
2.859375
3
[]
no_license
class IntegerArray def self.intersection( array_1, array_2 ) array_1 & array_2 end end class StateNameMixer def self.mix_it_up( string_set ) [ [ 'foo', 'fee' ], [ 'fee', 'foo' ] ] end end class CoinChanger def self.change_me( dollar_string ) { :pennies => 567 } end end class RomanNumeral def self.arithmetic( numeral_string ) "MMX" end end
true
77a1dfd9d1130fa20cbb91bc5d8a0f52e53856e9
Ruby
DevWarr/rails-mini-course-sprint1-mod1-student--starter
/language_screening.rb
UTF-8
204
3.078125
3
[]
no_license
def language_screening(people, language) return people.select do |person| lang_arr = person[:languages].select { |lang| lang.downcase == language.downcase} !lang_arr.empty? end end
true
898a434c1ea67061b07050abd0d16261c6a660c4
Ruby
debjohnson33/ruby-music-library-cli-v-000
/lib/music_importer.rb
UTF-8
281
2.9375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class MusicImporter attr_accessor :path def initialize(path) @path = path end def files @files ||= Dir.glob("#{path}/*.mp3").collect{ |file| file.gsub("#{path}/", "")}.sort end def import files.each do |file_name| Song.new_from_filename(file_name) end end end
true
48fd218992e017ed9c20a206ca702e0f0823e1ed
Ruby
driv3r/strainer
/lib/strainer/cli.rb
UTF-8
1,571
2.609375
3
[ "Apache-2.0" ]
permissive
require 'optparse' module Strainer class CLI def self.run(*args) parse_options(*args) if @cookbooks.empty? puts Color.red { 'ERROR: You did not specify any cookbooks!' } else @sandbox = Strainer::Sandbox.new(@cookbooks, @options) @runner = Strainer::Runner.new(@sandbox, @options) end end private def self.parse_options(*args) @options = {} parser = OptionParser.new do |options| # remove OptionParsers Officious['version'] to avoid conflicts options.base.long.delete('version') options.on nil, '--fail-fast', 'Fail fast' do |ff| @options[:fail_fast] = ff end options.on '-p PATH', '--cookbooks-path PATH', 'Path to the cookbooks' do |cp| @options[:cookbooks_path] = cp.strip end options.on '-k PATH', '--kniferb-path PATH', 'Path to the knife.rb file' do |kp| @options[:knife_rb_path] = kp.strip end options.on '-h', '--help', 'Display this help screen' do puts options exit 0 end options.on '-v', '--version', 'Display the current version' do require 'strainer/version' puts Strainer::VERSION exit 0 end end parser.load File.join(Dir.pwd, '.strainrc') # Get the cookbook names. The options that aren't read by optparser are assummed # to be cookbooks in this case. @cookbooks = [] parser.order!(args) do |noopt| @cookbooks << noopt end end end end
true
c882b6f407b602844122d0f2e59dd59483a09f8c
Ruby
forgedvision/gmat-cards
/lib/tools/terms/google-terms.rb
UTF-8
1,453
3.265625
3
[]
no_license
# Turn a list of terms into a seeds.rb file for populating the DB # Steps # 1. read the tab separated list file into an array. Terms are \n separated. # 2. randomize array. # 3. assign groups - 10 groups. # 4. start writing each element of the array into a seeds.rb file. Probably going to be pretty large. ## Card.delete_all ## ## Card.create!( ## field1: 'value', ## field2: 'value' ## ) ## require 'open-uri' require 'net/http' =begin def generate_seeds file = ARGV[0] group = ARGV[1] cards = [] shuffled_cards = [] Card = Struct.new(:term, :meaning) File.open(file) do |file| file.each do |line| term, meaning = line.chomp.split("\t") cards << Card.new(term, meaning) end end shuffled_cards = cards.shuffle file = File.new("seeds.rb","a") #file.puts "Card.delete_all" cards.each {|card| google_meaning = get_google_meaning file.puts "Card.create!(" file.puts " group_id: '#{group}'," file.puts " term: \'#{card.term}\'," file.puts " meaning: \'#{card.meaning}\'," file.puts " g_meaning: \'#{google_meaning}\'," file.puts " done: 'false'" file.puts ")" } file.close end =end def get_google_definition(term) url = "http://www.google.com/dictionary/json?callback=dict_api.callbacks.id100&q=#{term}&sl=en&tl=en&restrict=pr%2Cde&client=te" uri = URI(url) res = Net::HTTP.get_response(uri) puts res.body end get_google_definition("tacit")
true
ba3e9804ee9b46d0beffbee5325fe5ef44a5f559
Ruby
merlos/gtfs-api
/lib/gtfs_api/io/models/concerns/gtfsable.rb
UTF-8
13,121
2.734375
3
[ "MIT" ]
permissive
# The MIT License (MIT) # # Copyright (c) 2016 Juan M. Merlos, panatrans.org # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # This concern helps a GtfsApi model to import and export from and to a GTFS Feed file # # TODO add docummentation of this Concern as it is important to understand the code # # module GtfsApi module Io module Models module Concerns module Gtfsable extend ActiveSupport::Concern # # this variable is true if new_from_gtfs() is called # You can use it within model callbacks # #@from_gtfs_called def from_gtfs_called @from_gtfs_called ||= false end def from_gtfs_called=(val) @from_gtfs_called= val == true ? true : false end # # returns a hash with the cols of the row of the corresponding file. # It assigns to each key (column of the file) the value of the mapped # attribute. # # To see how to map each column to an attribute @see set_gtfs_col # # It calls the hook after_to_gtfs_feed (gtfs_feed_row) which allows the # model to override the default assignation if necessary # # returns empty hash if there is no mapping def to_gtfs gtfs_feed_row = {} return gtfs_feed_row if self.class.gtfs_cols.nil? #rehash to gtfs feed self.class.gtfs_cols.each do |model_attr,feed_col| #call send because virt. attr can only be accessed like that col_value = self.send(model_attr) col_value = col_value.to_gtfs if (col_value.is_a?(Date) || col_value.is_a?(Time)) gtfs_feed_row[feed_col] = col_value end self.after_to_gtfs(gtfs_feed_row) end # Hook. overwrite if required # it receives an standard mapping of the model attributes to gtfs feed columns # this method should be overridden if the default value of an attribute needs # to be processed. For example, a time or a date may be reformatted. # # it shall return the final gtfs_feed_row def after_to_gtfs (gtfs_feed_row) return gtfs_feed_row end # # Hook. This method is called after *_from_gtfs is called # # overwrite if required def after_from_gtfs(model_attr_hash) end # # GTFS Spec allows times > 24h, but rails does not. this is a parser # It is stored a time object with that has as 00:00:00 => '0000-01-01 00:00 +00:00(UTC)' # Times are always kept in UTC # # @param attribute_sym[Symbol] attribute that will be parsed # @param val[String] the time string in gtfs format, ex: 25:33:33 or Time objet # # # @TODO Think: if is it better to store it as an integer or timestamp? # def gtfs_time_setter(attribute_sym, val) if val.is_a? String t = Time.new_from_gtfs(val) if t.nil? errors.add(attribute_sym, :invalid) write_attribute(attribute_sym, val) return false end write_attribute(attribute_sym, t) return end write_attribute(attribute_sym, val) end #TODO # gets attribute without feed prefix # asumes that the model has a feed attribute too. def attr_without_feed_prefix (attr_sym) self[attr_sym].slice feed.prefix if self.gtfs_cols_with_prefix.include? (attr_sym) end module ClassMethods # # attribute that holds the feed association # @@gtfs_feed_attr = :feed # Hash with the relations between gtfs_api => gtfs_feed column names ordered by classes # # @example # { "class1 => { # :gtfs_api_col_name1 => :gtfs_feed_name # }, # "class2" => { # } # } @@gtfs_cols = {} # A hash with the relation between the gtfs_api class name and gtfs_feed file name # @example # { "GtfsApi::Agency" => :agency } @@gtfs_files = {} # A hash with an array with the cols that need feed prefix # @example # { "GtfsApi::Agency" => [:agency_id]} # @@gtfs_cols_with_prefix = {} # # Defines a map between GtfsApi model column name and the GTFS column spcecification. # Used for import and export # # @param model_name[Symbol] name of attr in the model # @param gtfs_feed_col[Symbol] name of the column in the GTFS feed specification. (optional) # # If model_name and gtfs_feed_col are equal you can skipt setting gtfs_feed_col # # @example # class GtfsApi::Agency < ActiveRecord::Base # include GtfsApi::Concerns::Models::Concerns::Gtfsable # set_gtfs_col :name # expected GTFS feed file column: name # set_gtfs_col :example, :test # expected GTFS feed file column: test # end def set_gtfs_col (model_attr, gtfs_feed_col = nil ) gtfs_feed_col = model_attr if gtfs_feed_col.nil? @@gtfs_cols[self] = {} if @@gtfs_cols[self].nil? @@gtfs_cols[self][model_attr] = gtfs_feed_col end # returns[Symbol] gtfs column for the model attribute def gtfs_col_for_attr(model_attr) @@gtfs_cols[self][model_attr] end #returns[Symbol] model attribute for the gtfs_col def attr_for_gtfs_col(gtfs_col) self.gtfs_attr[gtfs_col] end # # sets the columns to which shal be added the feed.prefix if set. # def set_gtfs_cols_with_prefix(gtfs_col_arr) @@gtfs_cols_with_prefix[self] = gtfs_col_arr end # Array of symbols with the gtfs columns that need a prefix # if the feed includes a prefix. # see @set_gtfs_cols_with_prefix # returns[Array] with symbols of the gtfs columns def gtfs_cols_with_prefix @@gtfs_cols_with_prefix[self].nil? ? [] : @@gtfs_cols_with_prefix[self] end # # sets the gtfs feed file name (without extension) linked to this class # Default value set is the plural of the containing class. Example Agency => :agencies # # @param gtfs_feed_file_sym[Symbol] name of the file # @example # class GtfsApi::Agency < ActiveRecord::Base # include GtfsApi::Concerns::Models::Concerns::Gtfsable # set_gtfs_file :agency # . # def set_gtfs_file (gtfs_feed_file_sym) @@gtfs_files[self] = gtfs_feed_file_sym end # Map of GtfsApi columns as keys and Gtfs feed column as values # :gtfs_api_col => :gtfs_feed_col def gtfs_cols @@gtfs_cols[self] end # # @return[Symbol] the gtfs file name symbol linked to this class # # if set_gtfs_file was not called, it returns the underscore class name # pluralized # Example: For the class GtfsApi::Agency it would return :agencies def gtfs_file @@gtfs_files[self] ||= self.to_s.split("::").last.underscore.pluralize.to_sym end # # @returns[String] the gtfs file name string linked to this class # # if set_gtfs_file was not calle => returns the underscore class name pluralized # Ex: For the class GtfsApi::Agency it would return agencies.txt # def gtfs_filename return self.gtfs_file.to_s + '.txt' end # # @return [array] list of associations between classes and filenames # def gtfs_files return @@gtfs_files end # map of gtfs_feed_col => gtfs_api_col def gtfs_attr @@gtfs_cols[self].invert unless @@gtfs_cols[self].nil? end # cols for all classes def gtfs_cols_raw @@gtfs_cols end # # This method rehashes a row from gtfs feed specs # # @example # #row example # csv_row = {:agency_id=>'M_MAD', :agency_name=>'Metro Madrid', ... } # Agency.rehash_from_gtfs_feed(csv_ro) # # output hash: {io_id: 'M_MAD", :name" => 'Metro Madrid'} # # @param csv_row[Hash] a row of one of the file feeds # @param feed[Hash/Object] a the feed object that may have the prefix string (feed.prefix) # @return [Hash] def rehash_from_gtfs(csv_row, feed = nil) model_attr_values = {} cols_with_prefix = self.gtfs_cols_with_prefix csv_row.each do |csv_col, val| #if feed is set, and it has a prefix => add the prefix if this column has the prefix. if (val != nil) && feed && feed.prefix.present? then val = feed.prefix + val if cols_with_prefix.include? (csv_col) end model_attr_values[self.attr_for_gtfs_col(csv_col)] = val if self.gtfs_cols.values.include? (csv_col) end return model_attr_values end # To create a new gtfsable object. It will assign to each gtfs_col defined # for this class to the model attributes. # # # One way to keep track of the gtfs objects that belong to a feed is by # having a belongs_to reference to another model. # # # Example: # # class Agency < ActiveRecord::Base # ... # set_gtfs_col :agency_id # belongs_to feed # ... # end # # class Feed < ActiveRecord::Base # has_many :agencies # has_many :routes # ... # end # # feed = Feed.find(1) # csv_row = {agency_id: 'agency_id'} # a = Agency.new_from_gtfs(csv_row, feed) # puts a.agency_id # # => agency_id # puts a.feed_id # # @param csv_row row with gtfs_cols of the feed # @param feed feed object that will be asigned. # # It will set the variable @from_gtfs_called to true in the object instance. # Useful to use with active record callbacks, for example, if you need to do # something before saving only if it an imported object # in the model http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html # def new_from_gtfs(gtfs_feed_row, feed = nil) model_attr_hash = self.rehash_from_gtfs(gtfs_feed_row, feed) obj = self.new(model_attr_hash) obj.from_gtfs_called = true obj.send( "#{@@gtfs_feed_attr}=", feed) if feed != nil obj.after_from_gtfs(model_attr_hash) return obj end def self.extended(base) #force set the default file @@gtfs_files[self] = self.to_s.split("::").last.underscore.pluralize.to_sym end end #ClassMethods end end end end end
true
c96abfd1f9b5c7aad593d2bba863be3a2609deef
Ruby
yorktronic/ruby
/prep-work-master/test-first-ruby-master/lib/11_dictionary.rb
UTF-8
605
3.53125
4
[]
no_license
class Dictionary def initialize(entries = {}) @ents = entries end def entries @ents end def add(ent) @ents[ent.keys[0]] = ent[ent.keys[0]] if ent.is_a?(Hash) @ents[ent] = nil if ent.is_a?(String) end def keywords @ents.keys.sort end def include?(word) @ents.has_key?(word) end def find(word) results = {} @ents.each do |ent, definition| if ent.include?(word) results[ent] = definition end end return results end def printable result = [] @ents.each do |ent, definition| result << %Q{[#{ent}] "#{definition}"} end result.sort.join("\n") end end
true
38f7f3c8055caa54cd386e3858b33a854bc0d8d5
Ruby
latentflip/ice_cube
/lib/ice_cube/time_util.rb
UTF-8
1,359
3.125
3
[ "MIT" ]
permissive
module TimeUtil LeapYearMonthDays = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] CommonYearMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # this method exists because ActiveSupport will serialize # TimeWithZone's in collections in UTC time instead of # their local time. if +time+ is a TimeWithZone, we move # it to a DateTime # Note: When converting to datetime, you microseconds get set to 0 def self.serializable_time(time) if time.respond_to?(:to_datetime) time.to_datetime else time end end def self.is_leap?(date) (date.year % 4 == 0 && date.year % 100 != 0) || (date.year % 400 == 0) end def self.days_in_year(date) is_leap?(date) ? 366 : 365 end def self.days_in_month(date) is_leap?(date) ? LeapYearMonthDays[date.month - 1] : CommonYearMonthDays[date.month - 1] end def self.ical_format(time) if time.utc? ":#{time.strftime('%Y%m%dT%H%M%SZ')}" # utc time else ";TZID=#{time.strftime('%Z:%Y%m%dT%H%M%S')}" # local time specified end end def self.ical_duration(duration) hours = duration / 3600; duration %= 3600 minutes = duration / 60; duration %= 60 repr = '' repr << "#{hours}H" if hours > 0 repr << "#{minutes}M" if minutes > 0 repr << "#{duration}S" if duration > 0 "PT#{repr}" end end
true
1195480b0be3e625ed06ca0520fa9eafd7a60985
Ruby
truonghuyen2110/iTMS-Tester-Advance-Automation
/btvn_day2/tc7.rb
UTF-8
1,439
2.59375
3
[]
no_license
require'selenium-webdriver' #1. Launch browser of your choice say., Firefox, chrome etc. driver = Selenium::WebDriver.for:chrome #2. Open this URL - https://itmscoaching.herokuapp.com/form driver.get'https://itmscoaching.herokuapp.com/form' #3. Maximize or set size of browser window. driver.manage.window.maximize puts driver.manage.window.size sleep 3 #4. Enter the form with following data: #-First name: iTMS first_name = driver.find_element(id:'first-name') first_name.send_keys("iTMS") #first_name = driver.find_element(xpath:"//input[@id='first-name']") #-Last name: Coaching #last_name = driver.find_element(id:'last-name') last_name = driver.find_element(xpath:"//input[@id='last-name']") last_name.send_keys("Coaching") #-Job Title: QA job_title = driver.find_element(id:'job-title') job_title.send_keys("QA") #-Highest level of education: College highest_level =driver.find_element(xpath:"//div[4]//div[3]") highest_level.click #-Sex: Male sex = driver.find_element(id:'checkbox-1') sex.click #-Year of experience: 2-4 options = driver.find_element(id:'select-menu') select_object = Selenium::WebDriver::Support::Select.new(options) select_object.select_by(:value,"2") #-Date: 27/10/2025 datepicker = driver.find_element(id:'datepicker') datepicker.send_keys("27/10/2025") #5. Click Submit btn_submit = driver.find_element(xpath:"//a[@class='btn btn-lg btn-primary']") btn_submit.click sleep 3 #6. Close browser driver.close
true
ad44c4611a1a60229dcbd9ba1d1a9b342e585cb9
Ruby
jlusenhop-mchs/medibot-essette
/auth_number_match/update_amisys_auth_number.rb
UTF-8
1,041
2.609375
3
[]
no_license
require 'spreadsheet' amisys_results_spreadsheet = ARGV[0] new_feature_file = File.open("#{amisys_results_spreadsheet}.feature","w") line_count = 0 old_feature_file = File.open("update_amisys_auth_number_template.feature", "r") do |f| f.each_line do |line| line_count += 1 case line_count when 9 line = "Scenario Outline: #{amisys_results_spreadsheet}" + "\n" when 3 line = "Feature: Process HealthHelp #{amisys_results_spreadsheet}" + "\n" end new_feature_file << line end f.close end book1 = Spreadsheet.open "#{amisys_results_spreadsheet}.xls" @medibot_results = book1.worksheet "#{amisys_results_spreadsheet}" @medibot_results.each do |row| if !row[61].nil? && row[61]["Amisys Auth Number = "] comments = row[61].split "Amisys Auth Number = " amisys_auth_number = comments[1].to_s essette_auth_number = row[44].to_s line = "| " + "#{essette_auth_number}" + " | " + "#{amisys_auth_number}" + " |" + "\n" new_feature_file << line end end new_feature_file.close
true
9e71cdfaf28d0ffa58fad0a065bf51f71c75e35d
Ruby
Lindseyls/betsy
/app/models/order.rb
UTF-8
1,017
2.546875
3
[]
no_license
class Order < ApplicationRecord STATUS = %w(pending paid complete cancelled) has_many :order_items, dependent: :destroy with_options if: :checking_out? do |order| order.validates :status, presence: true, inclusion: { in: STATUS } order.validates :email, presence: true order.validates :mail_adr, presence: true order.validates :cc_name, presence: true order.validates :cc_num, presence: true, numericality: {only_integer: true}, length: {is: 16} order.validates :cc_exp, presence: true order.validates :cc_cvv, presence: true, numericality: {only_integer: true}, length: {is: 3} order.validates :bill_zip, presence: true, numericality: {only_integer: true} end def checking_out? self.status != "pending" end def total_sum total = 0 self.order_items.each do |item| sub_total = item.sub_total total += sub_total end return total end def reduce_inventory self.order_items.each do |item| item.product.stock_reduction(item.quantity) end end end
true
66a1ef517974bffeeb310b11193ca898a67cc8ab
Ruby
ClementPain/Jour-7---Ruby-exercices
/exo_09.rb
UTF-8
183
3.265625
3
[]
no_license
puts "Quel est ton prénom ?" print "> " user_firstname=gets.chomp puts "Quel est ton nom ?" print "> " user_lastname=gets.chomp puts "Bonjour, #{user_firstname} #{user_lastname} !"
true
892222bc38c2c166c66f8affe76d68a9c16aedb7
Ruby
sgonyea/riak-pbclient
/lib/riakpb/content.rb
UTF-8
10,014
2.671875
3
[ "Apache-2.0" ]
permissive
require 'riakpb' require 'set' module Riakpb # Parent class of all object types supported by ripple. {Riakpb::RObject} represents # the data and metadata stored in a bucket/key pair in the Riakpb database. class Content include Util::Translation include Util::MessageCode # @return [Key] the key in which this Content is stored. attr_accessor :key # @return [String] the data stored in Riakpb at this object's key. Varies in format by content-type. attr_accessor :value alias_attribute :data, :value # @return [String] the MIME content type of the object attr_accessor :content_type # @return [String] the charset of the object attr_accessor :charset # @return [String] the content encoding of the object attr_accessor :content_encoding # @return [String] the vtag of the object attr_accessor :vtag # @return [Set<Link>] an Set of {Riakpb::Link} objects for relationships between this object and other resources attr_accessor :links # @return [Time] the Last-Modified header from the most recent HTTP response, useful for caching and reloading attr_accessor :last_mod alias_attribute :last_modified, :last_mod # @return [Time] the Last-Modified header from the most recent HTTP response, useful for caching and reloading attr_accessor :last_mod_usecs alias_attribute :last_modified_usecs, :last_mod_usecs # @return [Hash] a hash of any user-supplied metadata, consisting of a key/value pair attr_accessor :usermeta alias_attribute :meta, :usermeta attr_accessor :options # Create a new riak_content object manually # @param [Riakpb::Key] key Key instance that owns this Content (really, you should use the Key to get this) # @param [Hash] contents Any contents to initialize this instance with # @see Key#content # @see Content#load def initialize(key, options={}) @key = key unless key.nil? @links = Hash.new{|k,v| k[v] = []} @usermeta = {} @options = options self.last_mod = Time.now yield self if block_given? end def [](attribute) instance_variable_get "@#{attribute}" end # Load information for the content from the response object, Riakpb::RpbContent. # @param [RpbContent/Hash] contents an RpbContent object or a Hash. # @return [Content] self def load(content) case content when Riakpb::RpbContent, Hash, Riakpb::Content last_mod = content[:last_mod] last_mod_usecs = content[:last_mod_usecs] if not (last_mod.blank? or last_mod_usecs.blank?) self.last_mod = Time.at "#{last_mod}.#{last_mod_usecs}".to_f end @content_type = content[:content_type] unless content[:content_type].blank? @charset = content[:charset] unless content[:charset].blank? @content_encoding = content[:content_encoding] unless content[:content_encoding].blank? @vtag = content[:vtag] unless content[:vtag].blank? self.links = content[:links] unless content[:links].blank? self.usermeta = content[:usermeta] unless content[:usermeta].blank? unless content[:value].blank? case @content_type when /json/ @value = ActiveSupport::JSON.decode(content[:value]) when /octet/ @value = Marshal.load(content[:value]) else @value = content[:value] end end else raise ArgumentError, t("riak_content_type") end return(self) end def merge(content) @links.merge( self.links = content[:links] ) unless content[:links].blank? @usermega.merge( self.usermeta = content[:usermeta] ) unless content[:usermeta].blank? @content_type = content[:content_type] unless content[:content_type].blank? @value = content[:value] @charset = content[:charset] unless content[:charset].blank? @content_encoding = content[:content_encoding] unless content[:content_encoding].blank? @vtag = content[:vtag] unless content[:vtag].blank? @last_mod = content[:last_mod] @last_mod_usecs = content[:last_mod_usecs] return(self) end # Save the Content instance in riak. # @option options [Fixnum] w (write quorum) how many replicas to write to before returning a successful response # @option options [Fixnum] dw how many replicas to commit to durable storage before returning a successful response # @option options [true/false] return_body whether or not to have riak return the key, once saved. default = true def save(options={}) begin self.save!(options) rescue FailedRequest return(false) end return(true) end # Save the Content instance in riak. Raise/do not rescue on failure. # @option options [Fixnum] w (write quorum) how many replicas to write to before returning a successful response # @option options [Fixnum] dw how many replicas to commit to durable storage before returning a successful response # @option options [true/false] return_body whether or not to have riak return the key, once saved. default = true def save!(options={}) options[:content] = self options = @options.merge(options) return(true) if @key.save(options) return(false) # Create and raise Error message for this? Extend "Failed Request"? end # Internalizes a link to a Key, which will be saved on next call to... uh, save # @param [Hash] tags name of the tag, pointing to a Key instance, or an array ["bucket", "key"] # @return [Hash] links that this Content points to def link_key(tags) raise TypeError.new t('invalid_tag') unless tags.is_a?(Hash) or tags.is_a?(Array) tags.each do |tag, link| case link when Array newlink = Riakpb::RpbLink.new newlink[:bucket] = link[0] newlink[:key] = link[1] raise ArgumentError.new t('invalid_tag') if link[0].nil? or link[1].nil? @links[tag.to_s] << newlink when Riakpb::Key @links[tag.to_s] << link else raise TypeError.new t('invalid_tag') end end # tags.each do |tag, link| end alias :link :link_key # Set the links to other Key in riak. # @param [RpbGetResp, RpbPutResp] contains the tag/bucket/key of a given link # @return [Set] links that this Content points to def links=(pb_links) @links.clear case pb_links when Hash pb_links.each do |k, v| raise TypeError.new unless k.is_a?(String) if v.is_a?(Array) @links[k] += v else @links[k] << v end end when Array, Protobuf::Field::FieldArray pb_links.each do |pb_link| @links[pb_link.tag] << @key.get_linked(pb_link.bucket, pb_link.key, {:safely => true}) end else raise TypeError.new end return(@links) end def last_mod=(time_mod) @last_mod = Time.at time_mod end # @return [Riakpb::RpbContent] An instance of a RpbContent, suitable for protobuf exchange def to_pb rpb_content = Riakpb::RpbContent.new rpb_links = [] @links.each do |tag, links| links.each do |link| case link when Riakpb::RpbLink rpb_links << hlink when Riakpb::Key pb_link = link.to_pb_link pb_link.tag = tag rpb_links << pb_link end end end usermeta = [] @usermeta.each do |key,value| pb_pair = Riakpb::RpbPair.new pb_pair[:key] = key pb_pair[:value] = value usermeta << pb_pair end catch(:redo) do case @content_type when /octet/ rpb_content.value = Marshal.dump(@value) unless @value.blank? when /json/ rpb_content.value = ActiveSupport::JSON.encode(@value) unless @value.blank? when "", nil @content_type = "application/json" redo else rpb_content.value = @value.to_s unless @value.blank? end end rpb_content.content_type = @content_type unless @content_type.blank? rpb_content.charset = @charset unless @charset.blank? # || @charset.empty? rpb_content.content_encoding = @content_encoding unless @content_encoding.blank? # || @content_encoding.empty? rpb_content.links = rpb_links unless rpb_links.blank? rpb_content.usermeta = usermeta unless usermeta.blank? return(rpb_content) end # @return [String] A representation suitable for IRB and debugging output def inspect "#<#Riakpb::Content " + [ (@value.nil?) ? nil : "value=#{@value.inspect}", (@content_type.nil?) ? nil : "content_type=#{@content_type.inspect}", (@charset.nil?) ? nil : "charset=#{@charset.inspect}", (@content_encoding.nil?) ? nil : "content_encoding=#{@content_encoding.inspect}", (@vtag.nil?) ? nil : "vtag=#{@vtag.inspect}", (@links.nil?) ? nil : "links=#{@_links.inspect}", (@last_mod.nil?) ? nil : "last_mod=#{last_mod.inspect}", (@last_mod_usecs.nil?) ? nil : "last_mod_usecs=#{last_mod_usecs.inspect}", (@usermeta.nil?) ? nil : "usermeta=#{@usermeta.inspect}" ].compact.join(", ") + ">" end private end # class Content end # module Riakpb
true
da4184cb85f65a56839c6cb353a34673375b5ea2
Ruby
zackfern/adventofcode-2020
/day4/part_2.rb
UTF-8
2,238
3.65625
4
[]
no_license
#!/usr/bin/env ruby # # The problem: You've got a batch list of "passports" # Scan over the file and see how many of them are valid. # # To be valid, a passport needs the following fields: # - byr # - iyr # - eyr # - hgt # - hcl # - ecl # - pid # - cid # The passport must have all fields, but `cid` is optional, maybe? # # But wait, now we have to validate the fields themselves instead of just their presence! Gasp! # # Each passport is represented as a sequence of key:value pairs # separated by spaces or newlines. # Passports are separated by blank lines. input_path = File.join(File.dirname(__FILE__), "input.txt") file = File.read(input_path) valid_passports = 0 REQUIRED_FIELDS = %w(byr iyr eyr hgt hcl ecl pid) class Passport attr_reader :passport def initialize(passport) @passport = passport end def valid? @passport.delete "cid" @passport.keys.sort == REQUIRED_FIELDS.sort && \ @passport.all? do |key, value| valid_field?(key, value) end end def valid_field?(field, value) case field when "byr" value.to_i.between?(1920, 2002) when "iyr" value.to_i.between?(2010, 2020) when "eyr" value.to_i.between?(2020, 2030) when "hgt" # If cm, the number must be at least 150 and at most 193. # If in, the number must be at least 59 and at most 76. unit = value[-2..-1] if unit == "cm" value.to_i.between?(150, 193) elsif unit == "in" value.to_i.between?(59, 76) end when "hcl" # a # followed by exactly six characters 0-9 or a-f. value.match? /#[0-9a-f]{6}/ when "ecl" %w(amb blu brn gry grn hzl oth).include?(value) when "pid" # a nine-digit number, including leading zeroes. value.match? /^\d{9}$/ else false end end end this_passport = {} file.each_line do |line| if line == "\n" valid_passports += 1 if Passport.new(this_passport).valid? this_passport = {} else results = line.scan /((?<k>\S*):(?<v>\S*))\s/ this_passport.merge!(results.to_h) end end unless this_passport.empty? valid_passports += 1 if Passport.new(this_passport).valid? end puts "# of valid passports: #{valid_passports}"
true
18e24d85488f1b022025dec4ed65475e93cbda03
Ruby
balalnaeem/launch-school-101-lessons
/exercises/easy_4/8.rb
UTF-8
1,433
4.75
5
[]
no_license
=begin Write a method that takes a String of digits, and returns the appropriate number as an integer. The String may have a leading + or - sign; if the first character is a +, your method should return a positive number; if it is a -, your method should return a negative number. If no sign is given, you should return a positive number. In: A positive or negative sting integer Out: Appropriate integer Al: -use the method from previous exercise -define a new method (two args = string, base) -check if the string has a preceding symbol -in case, there is no symbol or positive symbol, use the string to integer method -if there is negative symbol, chop it off, use the string to integer method and multiply the result with -1 =end # require 'pry' INTEGER = { '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'a' => 10, 'b' => 11, 'c' => 12, 'd' => 13, 'e' => 14,'f' => 15 } def string_to_integer(str, base=10) str.downcase.chars.inject(0) { |result, ele| result * base + INTEGER[ele] } end def string_to_signed_integer(str, base=10) if str.chars.include?('-') || str.chars.include?('+') sign = str.slice!(0) end if sign == '-' string_to_integer(str) * -1 else string_to_integer(str) end end puts string_to_signed_integer('4321') == 4321 puts string_to_signed_integer('-570') == -570 puts string_to_signed_integer('+100') == 100
true
8572ccb5b36e985df4bdb19113b35c53856e43be
Ruby
jedld/natural_20
/lib/natural_20/cli/builder/rogue_builder.rb
UTF-8
1,932
2.515625
3
[ "MIT" ]
permissive
module Natural20::RogueBuilder def rogue_builder(_build_values) @class_values ||= { attributes: [], saving_throw_proficiencies: %w[dexterity intelligence], equipped: %w[leather_armor dagger dagger], inventory: [], tools: ['thieves_tools'], expertise: [] } @class_values[:expertise] = prompt.multi_select(t('builder.rogue.expertise'), min: 2, max: 2) do |q| @values[:skills].each do |skill| q.choice t("builder.skill.#{skill}"), skill end q.choice t('builder.skill.thieves_tools'), 'thieves_tools' end starting_equipment = [] starting_equipment << prompt.select(t('builder.rogue.select_starting_weapon')) do |q| q.choice t('object.rapier'), :rapier q.choice t('object.shortsword'), :shortsword end starting_equipment << prompt.select(t('builder.rogue.select_starting_weapon_2')) do |q| q.choice t('object.shortbow_and_quiver'), :shortbow_and_quiver q.choice t('object.shortsword'), :shortsword end starting_equipment.each do |equip| case equip when :rapier @class_values[:inventory] << { qty: 1, type: 'rapier' } when :shortbow_and_quiver @class_values[:inventory] += [{ type: 'shortbow', qty: 1 }, { type: 'arrows', qty: 20 }] end end shortswords = starting_equipment.select { |a| a == :shortword }.size if shortswords > 0 @class_values[:inventory] << { type: 'shortsword', qty: shortswords } end result = Natural20::DieRoll.parse(@class_properties[:hit_die]) @values[:max_hp] = result.die_count * result.die_type.to_i + modifier_table(@values.dig(:ability, :con)) @class_values end end
true
6c8f3441a11d571e227431ae3b0d1e71fdddf7f8
Ruby
rtyenriques/oo-banking-onl01-seng-pt-050420
/lib/bank_account.rb
UTF-8
389
3.171875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class BankAccount attr_reader :name attr_accessor :balance, :status def initialize(name) @name = name @balance = 1000 @status = "open" end def deposit(money) @balance += money end def display_balance "Your balance is $#{@balance}." end def valid? if @status == "open" && @balance > 0 true else false end end def close_account @status = "closed" end end
true
dfd13c4cf24eb54f5714df8c5be80c61a5c13b31
Ruby
Tasoxanadu/Ruby_test
/furigana_ruby/test0.rb
UTF-8
554
3.53125
4
[]
no_license
class Communication def greet answer = gets.chomp if answer == "Hello" puts "「Hello」" else puts "「......」" end end end communication1 = Communication.new communication1.greet class Workplacecommunication < Communication def greeting puts "ここは私の職場で合っていますか?はい/いいえ?" answer = gets.chomp if answer == "はい" puts "「おはようございます」" else puts "「……………」" end end end workplace = Workplacecommunication.new
true
64782e78b0a7dc68b55b99b0431b7a59d5abf75b
Ruby
pradeep-elangovan91/bitmap_editor
/spec/bitmap_editor_spec.rb
UTF-8
1,141
2.6875
3
[]
no_license
require './lib/bitmap_editor' describe BitmapEditor do context "executing the bitmap editor run function" do bme = BitmapEditor.new it "should fail when an invalid file is provided" do expect { bme.run "invalidfile.txt" }.to output("please provide correct file\n").to_stdout end it "should continue when a valid file is provided" do expect { bme.run "./examples/spec_test.txt" }.to output("Bitmap not yet created\n").to_stdout end it "should initialize a bitmap when a valid bitmap coordinates is given" do expect { bme.run "./examples/spec_createbitmap3*3.txt"}.to output("New Bitmap created of size :: (3 * 3)\n").to_stdout end it "should fail to initialize a bitmap when an invalid bitmap coordinates is given" do expect { bme.run "./examples/spec_invalidbitmap3*-1.txt"}.to output("invalid bitmap size (3,-1)\n").to_stdout end it "should fail to executeCommand when trying to run without a bitmap being created" do bme2 = BitmapEditor.new expect { bme2.run "./examples/spec_printbitmap.txt"}.to output("Bitmap not yet created\n").to_stdout end end end
true
d3fd0518a88425240db3f761f605f6be2ffd6feb
Ruby
scottmacphersonmusic/FizzBuzz
/spec/arbitrary_spec.rb
UTF-8
1,046
2.703125
3
[]
no_license
require 'spec_helper' require 'arbitrary' describe "arb_fizz" do it "can handle the standard" do fizz = arb_fizz 15, 3 => "Fizz", 5 => "Buzz" fizz[15].must_equal "FizzBuzz" fizz[5].must_equal "Buzz" fizz[3].must_equal "Fizz" fizz[8].must_equal "8" fizz[0].must_equal "0" end it "meets client specification" do fizz = arb_fizz 110, 3 => "Fizz", 5 => "Buzz", 7 => "Sivv" fizz[105].must_equal "FizzBuzzSivv" fizz[19].must_equal "19" fizz[17].must_equal "17" fizz[15].must_equal "FizzBuzz" fizz[10].must_equal "Buzz" end it "can handle much arbitrary input" do doge = arb_fizz 100, 4 => "Such", 5 => "Very", 3 => "Joy", 7 => "Wow", 11 => "Amazement" doge[99].must_equal "JoyAmazement" doge[55].must_equal "VeryAmazement" doge[60].must_equal "SuchVeryJoy" doge[47].must_equal "47" doge[21].must_equal "JoyWow" doge[20].must_equal "SuchVery" doge[7].must_equal "Wow" doge[8].must_equal "Such" doge[2].must_equal "2" end end
true
2e8bb5e4435ea2d44776ffac1e0a3f297211ea71
Ruby
edmundwright/appacademy-prep
/test-first-ruby/lib/08_book_titles.rb
UTF-8
513
3.515625
4
[]
no_license
class Book def initialize @title = nil end def titleize(str) little_words = %w{a an and as at but by en for if in nor of on or per the to vs over} transformed_words = str.split(" ").each_with_index.map do |word, index| if little_words.include?(word) && index!=0 word else word.capitalize end end transformed_words.join(" ") end def title=(new_title) @title = titleize(new_title) end def title @title end end
true
6c389285bb5978866d7e1a488b2c24d36862ac4b
Ruby
Vertalab/deplobotre
/lib/trello_release_bot/git_logger.rb
UTF-8
470
2.5625
3
[]
no_license
module TrelloReleaseBot module GitLogger EOC = "\n\n|EOC|\n\n".freeze # @param [String] branch name # @param [String] git revision rage eg: 'd9c41e946832..cf2707e17ff2dd' def self.commits(repo_path, revission_rage) raw_logs = `cd #{repo_path} && git log #{revission_rage} --format="%H %B#{EOC}"` raw_logs.split(EOC + "\n").map do |raw_log| { id: raw_log[/^[^\s]*/], message: raw_log[/(?<=\s)(.|\s)*/] } end end end end
true
3832446e6715064bcdde2dea5e07f381b86b01d2
Ruby
NateGiesing/sorting_suite
/insertion_sort.rb
UTF-8
704
3.28125
3
[]
no_license
def insertion_sort(array) sort = [array[0]] #require 'pry'; binding.pry sorted = [] array.delete_at(0) array.each do |i| #for i in array sort_index = 0 while sort_index < sort.length if i <= sort[sort_index] sort.insert(sort_index,i) break elsif sort_index == sort.length-1 sort.insert(sort_index+1,i) break end sort_index+=1 end # puts "last_index-" + last_index.to_s # puts "array-" + array.inspect #puts sort.inspect end sort end #array = [1, 5, 3, 4, 6, 2] array = (["d", "b", "a", "c"]) p insertion_sort(array)
true
e92eb9ddbc87d26ce81d5019f1481c7da40be562
Ruby
Su0414/ruby-objects-has-many-through-lab-v-000
/lib/doctor.rb
UTF-8
413
3.3125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Doctor attr_accessor :name, :appointments def initialize(name) @name = name @appointments = [] end def add_appointment(appointment_instance) @appointments << appointment_instance appointment_instance.doctor = self end def appointments @appointments end def patients self.appointments.collect do |appt| appt.patient end end end
true
cbd785db16695272af3f027866e50f247cd7a643
Ruby
paul-r-ml/funkr
/lib/funkr/types/container.rb
UTF-8
504
2.96875
3
[]
no_license
require 'funkr/categories' module Funkr module Types class Container include Funkr::Categories def initialize(value) @value = value end def unbox; @value; end def to_s; format("{- %s -}", @value.to_s); end include Functor def map(&block) self.class.new(yield(@value)) end include Monoid extend Monoid::ClassMethods def mplus(c_y) self.class.new(@value.mplus(c_y.unbox)) end end end end
true
a2d5313760120cfd443343fccae792f77c3116f8
Ruby
Gloumix/my_super_test_project
/my_super_test_project/lib/00_hello.rb
UTF-8
84
2.984375
3
[]
no_license
def hello return "Hello!" end def greet(machin) return "Hello, #{machin}!" end
true
60980e59e008262dcab09802cda9faf1bdab3b18
Ruby
kane7890/ruby-music-library-cli-online-web-ft-051319
/lib/musiclibrarycontroller.rb
UTF-8
3,645
3.59375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class MusicLibraryController def initialize(path = './db/mp3s') # binding.pry music_importer = MusicImporter.new(path) music_importer.import end def call puts "Welcome to your music library!" puts "To list all of your songs, enter 'list songs'." puts "To list all of the artists in your library, enter 'list artists'." puts "To list all of the genres in your library, enter 'list genres'." puts "To list all of the songs by a particular artist, enter 'list artist'." puts "To list all of the songs of a particular genre, enter 'list genre'." puts "To play a song, enter 'play song'." puts "To quit, type 'exit'." choices =[] exitflg = false until choices.last == "exit" do puts "What would you like to do?" choices << gets.chomp end choices.each do |choice| if choice == "list songs" self.list_songs elsif choice == "list artists" self.list_artists elsif choice == "list genres" self.list_genres elsif choice == "list artist" self.list_songs_by_artist elsif choice == "list genre" self.list_songs_by_genre elsif choice == "play song" self.play_song elsif choice == "exit" 0 end end # artist = Artist.find_by_name(choice) # if artist == nil # puts "No such artist" # end end def list_songs index = 1 sortsongs = Song.all.sort {|a, b| a.name <=> b.name} # binding.pry sortsongs.each do |song| puts "#{index}. #{song.artist.name} - #{song.name} - #{song.genre.name}" index += 1 end sortsongs end def list_artists index = 1 sortartists = Artist.all.sort {|a, b| a.name <=> b.name} # binding.pry sortartists.each do |artist| puts "#{index}. #{artist.name}" index += 1 end end def list_genres index = 1 Genre.all.sort {|a, b| a.name <=> b.name}.each do |genre| puts "#{index}. #{genre.name}" index += 1 end end def list_songs_by_artist puts "Please enter the name of an artist:" ainput = gets.chomp chosenartist = Artist.find_by_name(ainput) index = 1 if chosenartist != nil Song.all.select {|song| song.artist.name == chosenartist.name}.sort {|a, b| a.name <=> b.name}.each do |song_a| puts "#{index}. #{song_a.name} - #{song_a.genre.name}" index += 1 end end end def list_songs_by_genre puts "Please enter the name of a genre:" ginput = gets.chomp chosengenre = Genre.find_by_name(ginput) index = 1 if chosengenre != nil Song.all.select {|song| song.genre.name == chosengenre.name}.sort {|a, b| a.name <=> b.name}.each do |song_g| puts "#{index}. #{song_g.artist.name} - #{song_g.name}" # binding.pry index += 1 end end end def play_song # songlist=self.list_songs songlist = Song.all.sort {|a, b| a.name <=> b.name} # songlist = self.list_songs puts "Which song number would you like to play?" songinput = gets.strip songindex = songinput.to_i - 1 # binding.pry if songindex > 0 && songindex < songlist.length songselect = songlist[songindex] # binding.pry puts "Playing #{songselect.name} by #{songselect.artist.name}" end end end
true
b43c09cd7e3b103ab5387451ff1bedaeeb2afa3d
Ruby
lpmiller/looping-break-gets-001-prework-web
/levitation_quiz.rb
UTF-8
185
3.25
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def levitation_quiz loop do puts "What is the spell that enacts levitation?" answer = gets.chomp break if answer == "Wingardium Leviosa" end puts "You passed the quiz!" end
true
8b64075b256b3ac318dfbc84b1102cd47e1b8e3b
Ruby
maxckelly/codeAcademyBootCamp
/week-01/day-2-GIT-Ruby.rb
UTF-8
6,116
4.4375
4
[]
no_license
# Git cloning - To clone a repo you must get the repo https//: # However once you have SSH setup you should always use that. # git remote -v - This checks if you're connected to the repo # fetch and pull are the same words # -- How to setup SSH on your computer -- # Step One: Open a tab for - https://github.com/settings/keys # Step Two: Open a tab for - https://help.github.com/en/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent#generating-a-new-ssh-key # Step Three: Paste ssh-keygen -t rsa -b 4096 -C "your_email@example.com" into your terminal # Step Four: Follow through the steps. DON'T NEED TO ENTER A PASSWORD # Step Five: Once you have followed the steps and completed cd back to home # Step Six: Once in home cd .ssh # Step Seven: ls # Step Eight: cat id_rsa.pub # Step Nine: What is displayed is your key. Copy the key from the start of ssh-rsa to the end of your email # Step Ten: Go back to https://github.com/settings/keys and hit create new key # Step Eleven: Paste the key into the area and add a title. # DONE # -- GIT How to push to a branch -- # Git checkout -b branch name - This creates a new branch # Git status - checks any changes you've made to the files # Git add . # Git status # Git commit -m "comment" - Commits changes to the branch # Git checkout <branch_name> to go back to the branch you want - e.g. git checkout master # -- GIST -- # gist <file_name> - This simply pushes code to your gist. It will return a link which you can click to. # -- How to navigate amongst the repos -- # Git checkout branch name - e.g. git checkout master - This will move be back to master. Or git checkout branch # -- String Concatination -- # String concatination merges two string togther. For example: # p "String" + "Concatination" # -- String interplation -- # ALways use the quotes when you're using string interplation. This is for Ruby. # first_name = "Max" # last_name = "Kelly" # p "My name is #{first_name} #{last_name}" # -- Ways to print -- # The below three are mainly used to print to the terminal # 1. print # 2. puts # 3. p # puts "This is \n puts" # p "This is p" # print "This is print" # -- Escaped Characters -- # https://en.wikibooks.org/wiki/Ruby_Programming/Strings # Escaped characters are things like - new line, !, @, #, $, %, &, *, () etc... # Escaped characters can only be used with puts # To use these characters you can use \n (\n makes a new line) # -- Conversions Methods -- # Converting Integer - .to_i # Converting String - .to_s # Converting float - .to_f # See below for how you use: # You can check what the datatype is by using .class - See below # String - Integer # p string_number = "10" # Defines a varible # p string_number.class # Says its a string # int_number = string_number.to_i # Changes the string to integer # p int_number.class # prints saying its a integer # Integer - String # another_number = 100 # p another_number.class # another_number_to_string = another_number.to_s # p another_number_to_string.class # Integer - Float # another_number = 100 # p another_number.class # another_number_to_string = another_number.to_f # p another_number_to_string.class # -- More Methods -- # .chomp - This removes the line and any escape characters See below on how it works # .chomp - always returns a string to convert to a integer you use .to_i - name = gets.chomp.to_i # name = gets # p name # name = gets.chomp # p name # .stripe - This removes the spaces # name = "Max " # p name # p name.strip # -- Increasing a integar on a string -- # siblings = 3 # siblings = siblings + 1 #or # siblings += 1 # You can alos increase it in the sentance like the below # puts "Total sibilings: #{siblings + 1}" # -- Operators -- # Operators are ways to return either true or false # >= - Greater than or equal too. # <= - Less than or equal too # < - Greater than # > - Less than # && - means and if this is... - Used in if statements mainly # || - This means "or" - So if x or y # Example of operators: # "Max" == "Kelly" - false the two datatypes aren't the same # 1 >= 100 - returns false # 1 < 100 - returns true # You can also make it so the operates always appear as the oppisite. See below # 1 != 2 - this returns true because. Where if we removed ! it would return false as 1 is not equal to 2 # -- If statements -- # An If statement must always has an end # Basic Examples of if statements # ExampleOne: # name = "Max" #if (name == "Max") # puts "Hello World" #else # puts "Go away" #end # ExampleTwo: #if 100 < 99 # puts "Hello World" #else # puts "Nope this si wrong" #end # ExampleThree: #if (100 < 99 # puts "Hello World" #elsif 200 > 99 # puts "Nope this is wrong" #else # puts "true" #end # if you're && or || you need to put the varible on the other end - see example # p "How many coffees do you have per day?" # print "> " # coffees = gets.chomp.capitalize.to_i # if (coffees == 0 || coffees == "zero") # puts "Saving $$!" # elsif (coffees == 1 || coffees == "one") # puts "A little bit of caffeine doesn't hurt!" # elsif (coffees == 2 || coffees == "two") # puts "I need my coffee hit" # elsif (coffees == 3 || coffees == "three") # puts "Hmm it's getting a bit much" # else (coffees < 3) # puts "AHH so much caffeine" # end
true
4e76652ea95a02c4ca04c9171a8aa48164c9fb88
Ruby
DoiTaiki/AtCoder_answers_by_ruby
/ARC_126/a.rb
UTF-8
1,880
2.9375
3
[]
no_license
number_of_test_case = gets.chomp.to_i test_cases = [] number_of_test_case.times do test_cases << gets.chomp.split.map(&:to_i) end number_of_sticks = [] i = 0 while i < number_of_test_case number_of_stick = 0 comparison_with_N3_and_N4_result = test_cases[i][1] <=> test_cases[i][2] * 2 comparison_with_N2_and_N3_result = test_cases[i][0] <=> test_cases[i][1] comparison_with_N2_and_N4_result = test_cases[i][0] * 2 <=> test_cases[i][2] # N3, N4のみで作り、余りがない場合 if comparison_with_N3_and_N4_result == 0 number_of_stick = test_cases[i][2] + test_cases[i][0] / 5 # N3が余る場合 elsif comparison_with_N3_and_N4_result == 1 number_of_stick += test_cases[i][2] test_cases[i][1] -= test_cases[i][2] * 2 # N2, N3のみで作り、余りがない場合 if comparison_with_N2_and_N3_result == 0 number_of_stick += test_cases[i][0] / 2 # N2が余る場合 elsif comparison_with_N2_and_N3_result == 1 number_of_stick += test_cases[i][1] / 2 test_cases[i][0] -= test_cases[i][1] / 2 * 2 number_of_stick += test_cases[i][0] / 5 if test_cases[i][0] >= 5 # N3が余る場合 else number_of_stick += test_cases[i][0] / 2 end # N4が余る場合 else number_of_stick += test_cases[i][1] / 2 test_cases[i][2] -= test_cases[i][1] / 2 # N2, N4のみで作り、余りがない場合 if comparison_with_N2_and_N4_result == 0 number_of_stick += test_cases[i][0] # N2が余る場合 elsif comparison_with_N2_and_N4_result == 1 number_of_stick += test_cases[i][2] / 2 test_cases[i][0] -= test_cases[i][2] * 2 number_of_stick += test_cases[i][0] / 5 if test_cases[i][0] >= 5 # N4が余る場合 else number_of_stick += test_cases[i][0] end end number_of_sticks << number_of_stick i += 1 end puts number_of_sticks
true
bf1a1ca639c5a610f9c4fddd228f0fca0273f37c
Ruby
rhannequin/old-space-api
/sinatra/models/Parent.rb
UTF-8
825
2.671875
3
[ "Apache-2.0" ]
permissive
require 'open-uri' require 'nokogiri' class Parent attr_accessor :uri attr_accessor :config def initialize(config) @config = config end def load documents = [] @urls.each do |uri| file = get_content(uri) documents << Nokogiri::HTML(file.read.gsub("&nbsp;", ' ')) end documents end def to_label(str) return str.strip.downcase.gsub(':', '').gsub(' ', '_').gsub('(', '').gsub(')', '').to_sym end def add_params(params) @urls.map! { |uri| uri + '?' + params.map{ |k, v| "#{k}=#{v}" }.join('&') } end def get_content(uri) proxy = @config.proxy_use ? { proxy_http_basic_authentication: [ "#{@config.proxy_url}:#{@config.proxy_port}", @config.proxy_username, @config.proxy_password ] } : {} open uri, proxy end end
true
62941094ed63af990df52d109e6bfd0e29857847
Ruby
diego-aslz/report_logic
/spec/app/my_report.rb
UTF-8
671
2.765625
3
[]
no_license
Record = Struct.new(:id, :name) FIRST_DECORATOR = ->(value) { value + 3 } SECOND_DECORATOR = ->(value) { value / 2 } class MyReport < ReportLogic::Base session :header do field 'ID' field 'Name' end collection_session :rows do |record| value record.id value record.name end def my_own_rows collection.map do |record| fields do value record.id end end end session :test_context do value context_value end session :decorated do field 'A', 1, decorate_name: ->(name) { name + 'B' }, decorate_value: [FIRST_DECORATOR, SECOND_DECORATOR] end def context_value 'A' end end
true
ca01e5b66128a74d45d580f2d676603e5b69b609
Ruby
waco/geocoder_ruby
/geocoder.rb
UTF-8
1,928
3.234375
3
[ "MIT" ]
permissive
require 'rubygems' require 'net/http' require 'cgi' require 'json' require 'ostruct' class Geocoder BASE_URL = "http://maps.google.com/maps/api/geocode/json" # Google Geocoder APIへのリクエスト結果をパースして受け取る # jsonのみでxmlは対応していません # # - parameters: Geocoder APIで利用できるパラメータをハッシュで指定します # 詳しくは次を参照 http://code.google.com/intl/ja/apis/maps/documentation/geocoding/#GeocodingRequests # # - format: 受け取るデータのフォーマットを指定します(オプション, デフォルト: 'json') # 'json', 'j': パースされたjsonを返します # 'raw', 'rj': そのままのjsonを返します # 'openstruct', 'o': openstruct形式で返します # # 例) # Geocoder.geocode( :address => 'Tokyo' ) # Geocoder.geocode({ :address => 'Tokyo' }, 'openstruct') def self.geocode(parameters, format = 'json') type = type.to_s # :sensorは必須オプション parameters = { :sensor => 'false' }.merge(parameters) query = parameters.collect{ |k,v| "#{k}=#{CGI::escape(v.to_s)}" }.join('&') url = URI.parse("#{BASE_URL}?#{query}") response = Net::HTTP.get(url) # パース開始 begin case format.to_s when 'json', 'j' data = JSON::parse(response) when 'openstruct', 'o' json = JSON::parse(response) data = self.recursive_ostruct(json) when 'raw', 'r' data = response end rescue data = 'could not parse' end return data end private def self.recursive_ostruct(data) if data.instance_of? Hash data.each { |k, v| data[k] = recursive_ostruct(v) } data = OpenStruct.new data elsif data.instance_of? Array data.each_with_index { |k, i| data[i] = recursive_ostruct(k) } end data end end
true
104829aa2a167cf8cfe8e10035ef457e4db6d3b0
Ruby
benjaminsunderland/TicTacToe
/lib/board.rb
UTF-8
1,208
3.734375
4
[]
no_license
class Board attr_accessor :grid, :turn WINNING_COMBINATIONS = [[0, 1, 2], [3, 4, 5], [0, 3, 6], [6, 7, 8], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]].freeze def initialize @grid = Array.new(3) { Array.new(3) { nil } } @turn = 0 end def player_make_move(row, col, player) raise "You can't do that!" if off_board?(row, col) || position_taken?(row, col) @grid[row][col] = player next_turn end def off_board?(row, col) (row < 0 || row > 2) || (col < 0 || col > 2) end def next_turn @turn += 1 end def position_taken?(row, col) (@grid[row][col].nil?) ? (return false) : (return true) end def current_turn @turn.even? ? (return 'X') : (return 'O') end def three_in_a_row? flat_board = @grid.flatten x_matches = flat_board.each_index.select { |i| flat_board[i] == 'X' } o_matches = flat_board.each_index.select { |i| flat_board[i] == 'O' } WINNING_COMBINATIONS.each do |line| if (line - x_matches).empty? return true elsif (line - o_matches).empty? return true end end false end end
true
9250ac966a5bd2e5fc8ee6baff2310fc4a85db71
Ruby
andrewsapa/intro-ruby-book
/flow_control/exercise2.rb
UTF-8
479
4.625
5
[]
no_license
# 2. Write a method that takes a string as argument. The method should return # a new, all-caps version of the string, only if the string is longer than 10 # characters. Example: change "hello world" to "HELLO WORLD". # (Hint: Ruby's String class has a few methods that would be helpful. # Check the Ruby Docs!) def upcase(string) if string.length > 10 puts string.upcase else puts string end end upcase("Adrian") upcase("Weclome to the jungle")
true
dd759a8ae7ea7bb2fc9a44778edad033d83b174b
Ruby
shawn42/chessbox
/src/behaviors/hoverable.rb
UTF-8
742
2.96875
3
[]
no_license
require 'behavior' # # Hoverable adds callbacks for when the mouse is hovering over an actor. # Will call actor.mouse_(enter|exit)(x,y) by default, # but can be told what methods to call # has_behavior :hoverable # or # has_behavior :hoverable => {:enter => :my_hover_method, :exit => :my_exit_method} # class Hoverable < Behavior DEFAULT_CALLBACKS = { :enter => :mouse_enter, :exit => :mouse_exit, } def setup hover_opts = opts.merge DEFAULT_CALLBACKS enter_callback = hover_opts[:enter] exit_callback = hover_opts[:exit] @hover_manager = @actor.stage.stagehand(:hover) @hover_manager.register @actor, enter_callback, exit_callback end def removed @hover_manager.unregister @actor end end
true
1181618d877dbc1fb16a0d3e1068f78099f88fd3
Ruby
mdeskin/project-euler-power-digit-sum-e-000
/lib/project_euler_power_digit_sum.rb
UTF-8
215
3.390625
3
[]
no_license
def power_digit_sum(x,n) count = 0 sum = 0 product = x ** n product_str = product.to_s until product_str.slice(count).nil? sum = sum + product_str.slice(count).to_i count += 1 end sum end
true
1f57aa0ab664b300339e484135b84035ddb76249
Ruby
alf-tool/alf-core
/spec/unit/alf-types/ordering/test_reverse.rb
UTF-8
902
2.53125
3
[ "MIT" ]
permissive
require 'spec_helper' module Alf describe Ordering, "reverse" do subject{ ordering.reverse } context 'on an empty ordering' do let(:ordering){ Ordering.new([]) } it{ should eq(ordering) } end context 'on a singleton asc ordering' do let(:ordering){ Ordering.new([[:name, :asc]]) } it{ should eq(Ordering.new([[:name, :desc]])) } end context 'on a singleton desc ordering' do let(:ordering){ Ordering.new([[:name, :desc]]) } it{ should eq(Ordering.new([[:name, :asc]])) } end # # name, id => name, id # b, 12 a, 13 # a, 10 a, 10 # a, 13 b, 12 # context 'on a mixed ordering' do let(:ordering){ Ordering.new([[:name, :desc], [:id, :asc]]) } it{ should eq(Ordering.new([[:name, :asc], [:id, :desc]])) } end end # Ordering end # Alf
true
2e02fd2eb93e42461570a8b53ac0e0047cb57440
Ruby
alikewmk/emoji_ranking
/scripts/plot.rb
UTF-8
622
2.640625
3
[]
no_license
require 'nyaplot' x = []; y = []; theta = 0.6; a=1 File.open('2000_svm_result.txt').each_line do |line| item = line.split(" ") y << item[1].to_f/item[2].to_f theta += 0.1 end # word_count/1000 in data base x = [16.593, 8.016, 5.863, 4.959, 4.315, 3.477, 2.958, 2.86, 2.727, 2.344] plot = Nyaplot::Plot.new line = plot.add(:line, x, y) sc = plot.add(:scatter, x, Array.new(10){0.005}) sc.shape(["triangle-up"]) sc.color('#00A37A') sc.title('Emoji SVM Models') line.title('Frequency in training data') plot.legend(true) plot.y_label("Precison") plot.x_label("Frequency (*1000)") plot.export_html("test.html")
true
da7d55acdd9b77e2fe58f0a8ad158336ac940903
Ruby
Leadformance/tm4b
/spec/broadcast_spec.rb
UTF-8
3,376
2.78125
3
[]
no_license
#coding : utf-8 require 'spec_helper' describe TM4B::Broadcast do before do @broadcast = TM4B::Broadcast.new @broadcast.recipients = "+1 213 555-0100" @broadcast.originator = "tm4btest" @broadcast.message = "hello world" end it "should return an encoded string if 'plain' encoding if selected" do @broadcast.message = "ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïñòóôõöùúûüýÿ" @broadcast.encoding = :plain @broadcast.parameters["msg"].should == "AAAAAACEEEEIIIINOOOOOUUUUYaaaaaaceeeeiiiinooooouuuuyy" end it "should return valid string even if it's not UTF8 compliant" do @broadcast.message = "\xE2" @broadcast.encoding = :plain @broadcast.parameters["msg"].should == "" end it "should return valid string even if it's not UTF8 compliant" do @broadcast.message = "\xE2" @broadcast.encoding = :unicode @broadcast.parameters["msg"].should == "" end it "should replace undefined chars by nothing" do @broadcast.message = "’" @broadcast.encoding = :unicode @broadcast.parameters["msg"].should == "" end it "should strip nondigits from the recipient" do @broadcast.recipients.should == ["12135550100"] end it "should assign 'plain' as the encoding by default" do @broadcast.encoding.should == :plain end it "should assign :concatenation_graceful as the default splitting method" do @broadcast.split_method.should == :concatenation_graceful end it "should raise an exception when trying to pass an invalid split method" do lambda do @broadcast.split_method = :foo end.should raise_error "invalid splitting method: foo" end it "should raise an exception if trying to assign an originator of 0 characters" do lambda do @broadcast.originator = "" end.should raise_error "originator must be between 1 and 11 characters long" end it "should raise an exception when trying to pass an invalid encoding" do lambda do @broadcast.encoding = :foo end.should raise_error "invalid encoding: foo" end it "should define parameters for the api" do @broadcast.recipients = ["+1 (213) 555-0100", "+1 (213) 555-0101"] @broadcast.route = "foo" @broadcast.simulated = true @broadcast.parameters.should == { "version" => "2.1", "type" => "broadcast", "to" => "12135550100|12135550101", "from" => "tm4btest", "msg" => "hello world", "data_type" => "plain", "split_method" => 8, "route" => "foo", "sim" => "yes" } end it "should assign result data from a raw xml response body" do @broadcast.raw_response = <<-EOS <result> <broadcastID>MT0017295001</broadcastID> <recipients>1</recipients> <balanceType>GBP</balanceType> <credits>5.0</credits> <balance>5995.0</balance> <neglected>-</neglected> </result> EOS @broadcast.broadcast_id.should == "MT0017295001" @broadcast.recipient_count.should == "1" @broadcast.balance_type.should == "GBP" @broadcast.credits.should == 5 @broadcast.balance.should == 5995 @broadcast.neglected.should == "-" end end
true
7d8e90078dcaadcd58c4ee92a9bc64162969822b
Ruby
sergio-bobillier/bdd-rails-workout
/spec/features/friendships_spec.rb
UTF-8
3,055
2.515625
3
[]
no_license
require 'rails_helper' RSpec.shared_context 'A pair of users exist and one of them is logged-in' do before do @john = User.create!(first_name: 'John', last_name: 'Doe', email: 'john.doe@example.com', password: 'password') @sarah = User.create!(first_name: 'Sarah', last_name: 'Joseph', email: 'sarah.joseph@example.com', password: 'password') login_as @john end end RSpec.shared_context 'One of the users is following the other' do before do Friendship.create(user: @john, friend: @sarah) end end RSpec.feature 'Following friends' do include_context 'A pair of users exist and one of them is logged-in' scenario 'A signed-in user visits the home page and follows another user' do visit '/' expect(page).to have_content @john.full_name expect(page).to have_content @sarah.full_name # A user can't follow himself. expect(page).not_to have_link 'Follow', href: "#{friendships_path(friend_id: @john.id)}" # A user can follow other users. link = "a[href='#{friendships_path(friend_id: @sarah.id)}']" find(link).click # A user can't cannot follow a user he is already following. expect(page).not_to have_link 'Follow', href: "#{friendships_path(friend_id: @sarah.id)}" end end RSpec.feature 'Show followed friends' do include_context 'A pair of users exist and one of them is logged-in' include_context 'One of the users is following the other' scenario 'A user visits the "My Lounge" page and sees a list of his friends' do visit '/' click_link 'My Lounge' expect(page).to have_content 'My friends' expect(page).to have_link @sarah.full_name expect(page).to have_link 'Unfollow' end end RSpec.feature "Show a friend's workout" do include_context 'A pair of users exist and one of them is logged-in' include_context 'One of the users is following the other' before do @ex1 = @sarah.exercises.create(duration_in_min: 74, workout: 'Weight lifting routine', workout_date: Date.today - 1.day) @ex2 = @sarah.exercises.create(duration_in_min: 55, workout: 'Weight lifting routine', workout_date: Date.today) end scenario "A user sees a friend's workout" do visit '/' click_link 'My Lounge' click_link @sarah.full_name expect(page.current_path).to eq friendship_path(@john.current_friendship(@sarah)) expect(page).to have_content @ex2.workout expect(page).to have_css 'div#chart' end end RSpec.feature "Unfollow friends" do include_context 'A pair of users exist and one of them is logged-in' include_context 'One of the users is following the other' scenario 'A user unfollows a friend' do visit '/' click_link 'My Lounge' page_current_path = page.current_path expect(page).to have_content @sarah.full_name link = "a[href='#{friendship_path(@john.current_friendship(@sarah).id)}'][data-method=delete]" find(link).click expect(page.current_path).to eq page_current_path expect(page).to have_content "#{@sarah.full_name} unfollowed." expect(page).not_to have_link @sarah.full_name end end
true
ad9e7545e095a66a5df0da6e985cf42ecb26a89e
Ruby
atri-konami/kyo-pro
/atcoder/abc/060/a.rb
UTF-8
113
3.359375
3
[]
no_license
a,b,c = gets.chomp.split if a[a.length-1] == b[0] && b[b.length-1] == c[0] puts 'YES' else puts 'NO' end
true
da638d115bdc5fe4165c239597a0c523a67e0212
Ruby
DavidSerfaty/exos-mario
/exo_16.rb
UTF-8
149
3.546875
4
[]
no_license
puts "Quel age as-tu ?" birth = gets.chomp.to_i x = birth y = 0 while y < birth puts "Il y a #{x} ans, tu avais #{y} ans" y += 1 x -= 1 end
true
a86248b3ef6dbdda6f519c70ed58456a31987a96
Ruby
BryantWyatt/learning_the_well_grounded_rubyist
/ch10/get_matches_with_find.rb
UTF-8
1,008
3.921875
4
[]
no_license
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] puts(numbers.find{|n| n > 5}) numbers_with_nill = [1, 2, 3, nil, 4, 5, 6] puts(numbers_with_nill.find{|n| n.nil?}) # Will always find nil regards if it succeeds or fails. puts() puts('Find all values in the number array greater than 5') puts(numbers.find_all{|n| n > 5}) puts() puts('Find all values in the numbers array greater than 100') puts(numbers.select{|n| n > 100}) colors = %w{red orange yellow green blue indigo violet} puts() puts('Locate all colors in the color array with the letter \'o\'') puts(colors.grep(/o/)) miscellany = [75, 'hello', 10...20, 'goodbye'] puts() puts('Print all strings in the \'miscellany\' array') puts(miscellany.grep(String)) puts() puts('Print all numbers in the \'miscellany\' array') puts(miscellany.grep(50..100)) puts() puts('Grep and capitalize each item in the array that has an \'o\'') puts(colors.grep(/o/) {|color| color.capitalize}) puts() puts('Group by example:') puts(colors.group_by{|color| color.size})
true
e5e2c456102b9b686464d65b6c19c6e65c5bac17
Ruby
kemper/queuez
/lib/queuez/initializer.rb
UTF-8
1,114
2.515625
3
[ "MIT" ]
permissive
module Queuez class Initializer attr_reader :servers def initialize @servers = [] end #TODO: doesn't make sense for client middleware to be at this level def initialize!(config_hash) config_hash[:queues].each do |queue_config| @servers << build_server(queue_config) end end def build_server(queue_config) server = nil Queuez.configure(queue_config[:name]) do |config| config.client_middleware do |chain| chain.add(Queuez::Middleware::CreateBackgroundJob) end config.producer_middleware do |chain| chain.add(Queuez::Middleware::ProduceWork) chain.add(Queuez::Middleware::EnqueueProducedWork) end config.consumer_middleware do |chain| chain.add(Queuez::Middleware::DequeueProducedWork) chain.add(Queuez::Middleware::JobWorker) end server = Queuez::Server.new(config) end server end def start_all servers.each { |s| s.start_async } end def stop_all servers.each { |s| s.stop } end end end
true
83cfa2b2073d970c5d0f0a6ed511a688cd8f9c49
Ruby
Williamug/getting-started-with-ruby
/price.rb
UTF-8
603
4.125
4
[]
no_license
def total(prices) amount = 0 # process eacb price prices.each do |price| # add the current price to the total amount += price end amount # return the final total end def refund(prices) amount = 0 prices.each do |price| amount -= price # refund the current price end amount end def show_discounts(prices) prices.each do |price| amount_off = price / 3.0 # format and print the current discount puts format("Your discount: $%.2f", amount_off) end end prices = [3.99, 25.00, 8.99] puts format("%.2f", total(prices)) puts format("%.2f", refund(prices)) show_discounts(prices)
true
4b9ab9d13471ce0fff28a749f4354bac3f5406fe
Ruby
idynkydnk/connect_four
/spec/board_spec.rb
UTF-8
10,409
3.59375
4
[]
no_license
require "board" describe Board do context "sets a 7x6 grid" do it "sets 7 rows" do board = Board.new expect(board.grid.length).to be(7) end it "sets 6 columns inside each row" do board = Board.new board.grid.each do |row| expect(row.length).to be(6) end end end context "each cell should be nil or a game piece" do it "all cells are nil" do board = Board.new expect(board.grid[0][0]).to be(nil) expect(board.grid[2][3]).to be(nil) expect(board.grid[6][0]).to be(nil) end end describe ".place_piecee" do it "places a piece into a column 1-7" do board = Board.new object = double("object") board.place_piece(1, object) expect(board.grid[0][0]).to eql(object) expect(board.grid[0][1]).to eql(nil) end it "places a piece to the second row when first row is occupied" do board = Board.new object = double("object") board.place_piece(1, object) board.place_piece(1, object) expect(board.grid[0][1]).to eql(object) end it "places piece in last row" do board = Board.new object = double("object") 6.times do board.place_piece(1, object) end expect(board.grid[0][5]).to eql(object) end it "places piece in last column" do board = Board.new object = double("object") board.place_piece(7, object) expect(board.grid[6][0]).to eql(object) end end describe ".winner?" do it "returns true with four in a row vertically in first column" do board = Board.new object = double("object", :color => "blue") 4.times do board.place_piece(1, object) end expect(board.winner?(object)).to be(true) end it "returns true with four in a row vertically and up a row" do board = Board.new blue_object = double("blue_object", :color => "blue") red_object = double("red_object", :color => "red") board.place_piece(1, blue_object) 4.times do board.place_piece(1, red_object) end expect(board.winner?(red_object)).to be(true) end it "returns true with four in a row vertically a few columns over" do board = Board.new blue_object = double("blue_object", :color => "blue") red_object = double("red_object", :color => "red") board.place_piece(4, red_object) board.place_piece(4, red_object) 4.times do board.place_piece(4, blue_object) end expect(board.winner?(blue_object)).to be(true) end it "returns true with four in a row vertically top right corner" do board = Board.new blue_object = double("blue_object", :color => "blue") red_object = double("red_object", :color => "red") board.place_piece(7, red_object) board.place_piece(7, red_object) 4.times do board.place_piece(7, blue_object) end expect(board.winner?(blue_object)).to be(true) end it "returns false with no pieces on the board" do board = Board.new blue_object = double("blue_object", :color => "blue") expect(board.winner?(blue_object)).to be(false) end it "returns false if the other color has four in a row" do board = Board.new blue_object = double("blue_object", :color => "blue") red_object = double("red_object", :color => "red") board.place_piece(6, red_object) board.place_piece(6, red_object) 4.times do board.place_piece(6, blue_object) end expect(board.winner?(red_object)).to be(false) end it "returns true if four in a row horizontally" do board = Board.new blue_object = double("blue_object", :color => "blue") board.place_piece(1, blue_object) board.place_piece(2, blue_object) board.place_piece(3, blue_object) board.place_piece(4, blue_object) expect(board.winner?(blue_object)).to be(true) end it "returns true if four in a row horizontally and up a few rows" do board = Board.new blue_object = double("blue_object", :color => "blue") red_object = double("red_object", :color => "red") 3.times do board.place_piece(1, blue_object) board.place_piece(2, blue_object) board.place_piece(3, blue_object) board.place_piece(4, blue_object) end board.place_piece(1, red_object) board.place_piece(2, red_object) board.place_piece(3, red_object) board.place_piece(4, red_object) expect(board.winner?(red_object)).to be(true) end it "returns true if four in a row horizontally and up and over a little" do board = Board.new blue_object = double("blue_object", :color => "blue") red_object = double("red_object", :color => "red") 1.times do board.place_piece(3, blue_object) board.place_piece(4, blue_object) board.place_piece(5, blue_object) board.place_piece(6, blue_object) end board.place_piece(3, red_object) board.place_piece(4, red_object) board.place_piece(5, red_object) board.place_piece(6, red_object) expect(board.winner?(red_object)).to be(true) end it "returns true if four in a row horizontally and up and over a lot" do board = Board.new blue_object = double("blue_object", :color => "blue") red_object = double("red_object", :color => "red") 5.times do board.place_piece(4, blue_object) board.place_piece(5, blue_object) board.place_piece(6, blue_object) board.place_piece(7, blue_object) end board.place_piece(4, red_object) board.place_piece(5, red_object) board.place_piece(6, red_object) board.place_piece(7, red_object) expect(board.winner?(red_object)).to be(true) end it "returns true if four in a row diagonally up" do board = Board.new blue_object = double("blue_object", :color => "blue") red_object = double("red_object", :color => "red") board.place_piece(2, red_object) 2.times { board.place_piece(3, red_object) } 3.times { board.place_piece(4, red_object) } board.place_piece(1, blue_object) board.place_piece(2, blue_object) board.place_piece(3, blue_object) board.place_piece(4, blue_object) expect(board.winner?(blue_object)).to be(true) end it "returns true if four in a row diagonally up and over a little" do board = Board.new blue_object = double("blue_object", :color => "blue") red_object = double("red_object", :color => "red") 2.times { board.place_piece(4, red_object) } 3.times { board.place_piece(5, red_object) } 4.times { board.place_piece(6, red_object) } 5.times { board.place_piece(7, red_object) } board.place_piece(4, blue_object) board.place_piece(5, blue_object) board.place_piece(6, blue_object) board.place_piece(7, blue_object) expect(board.winner?(blue_object)).to be(true) end it "returns true if four in a row diagonally down" do board = Board.new blue_object = double("blue_object", :color => "blue") red_object = double("red_object", :color => "red") 5.times { board.place_piece(1, red_object) } 4.times { board.place_piece(2, red_object) } 3.times { board.place_piece(3, red_object) } 2.times { board.place_piece(4, red_object) } board.place_piece(1, blue_object) board.place_piece(2, blue_object) board.place_piece(3, blue_object) board.place_piece(4, blue_object) expect(board.winner?(blue_object)).to be(true) end it "returns true if four in a row diagonally down and over a little" do board = Board.new blue_object = double("blue_object", :color => "blue") red_object = double("red_object", :color => "red") 5.times { board.place_piece(4, red_object) } 4.times { board.place_piece(5, red_object) } 3.times { board.place_piece(6, red_object) } 2.times { board.place_piece(7, red_object) } board.place_piece(4, blue_object) board.place_piece(5, blue_object) board.place_piece(6, blue_object) board.place_piece(7, blue_object) expect(board.winner?(blue_object)).to be(true) end end describe ".print_board" do it "prints a blank board" do board = Board.new expect { board.print_board }.to output("| | | | | | | |\n| | | | | | | |\n| | | | | | | |\n| | | | | | | |\n| | | | | | | |\n| | | | | | | |\n").to_stdout end it "prints board with one red piece in the first column" do board = Board.new red_object = double("red_object", :color => "red") board.place_piece(1, red_object) expect { board.print_board }.to output("| | | | | | | |\n| | | | | | | |\n| | | | | | | |\n| | | | | | | |\n| | | | | | | |\n|\e[31m#{"\u25cf"}\e[0m| | | | | | |\n").to_stdout end it "prints board with one red first, 2 blue in third, red and blue in fifth" do board = Board.new red_object = double("red_object", :color => "red") blue_object = double("blue_object", :color => "blue") board.place_piece(1, red_object) 2.times { board.place_piece(3, blue_object) } board.place_piece(5, red_object) board.place_piece(5, blue_object) expect { board.print_board }.to output("| | | | | | | |\n| | | | | | | |\n| | | | | | | |\n| | | | | | | |\n| | |\e[34m#{"\u25cf"}\e[0m| |\e[34m#{"\u25cf"}\e[0m| | |\n|\e[31m#{"\u25cf"}\e[0m| |\e[34m#{"\u25cf"}\e[0m| |\e[31m#{"\u25cf"}\e[0m| | |\n").to_stdout end end describe ".full_board?" do it "returns false if board is not full" do board = Board.new expect(board.full_board?).to be(false) end it "returns true if board is full" do board = Board.new red_object = double("red_object", :color => "red") 6.times { board.place_piece(1, red_object) } 6.times { board.place_piece(2, red_object) } 6.times { board.place_piece(3, red_object) } 6.times { board.place_piece(4, red_object) } 6.times { board.place_piece(5, red_object) } 6.times { board.place_piece(6, red_object) } 6.times { board.place_piece(7, red_object) } expect(board.full_board?).to be(true) end end end
true
23b0bdfecebb7217f00b6ea492b6e4e4bff2c969
Ruby
purvakaranjawala/doctor_app
/config/prefix_tree.rb
UTF-8
618
3.59375
4
[]
no_license
class Node attr_reader :value, :next attr_accessor :word def initialize(value) @value = value @word = false @next = [] end end class Tree def initialize @root = Node.new("*") end def add_word(word) letters = word.chars base = @root letters.each { |letter| base = add_character(letter, base.next) } base.word = true end def find_word(word) letters = word.chars base = @root word_found = letters.all? { |letter| base = find_character(letter, base.next) } yield word_found, base if block_given? base end end
true
88062d652a422766f6b315a4e7f426cdfe1c2cc3
Ruby
marcdif/ISE337
/ruby/hw2/submission/treasure-hunt.rb
UTF-8
6,809
3.625
4
[]
no_license
# Marc DiFilippo - 111420881 # ISE 337 HW2 Part 3 class Console def initialize(player, narrator) @player = player @narrator = narrator end def show_room_description @narrator.say "-----------------------------------------" @narrator.say "You are in room #{@player.room.number}." @player.explore_room @narrator.say "Exits go to: #{@player.room.exits.join(', ')}" end def ask_player_to_act actions = {"m" => :move, "s" => :shoot, "i" => :inspect } accepting_player_input do |command, room_number| @player.act(actions[command], @player.room.neighbor(room_number)) end end private def accepting_player_input @narrator.say "-----------------------------------------" command = @narrator.ask("What do you want to do? (m)ove or (s)hoot?") unless ["m","s"].include?(command) @narrator.say "INVALID ACTION! TRY AGAIN!" return end dest = @narrator.ask("Where?").to_i unless @player.room.exits.include?(dest) @narrator.say "THERE IS NO PATH TO THAT ROOM! TRY AGAIN!" return end yield(command, dest) end end class Narrator def say(message) $stdout.puts message end def ask(question) print "#{question} " $stdin.gets.chomp end def tell_story yield until finished? say "-----------------------------------------" describe_ending end def finish_story(message) @ending_message = message end def finished? !!@ending_message end def describe_ending say @ending_message end end ## MY CODE class Room def initialize(number) @number = number @hazards = [] @neighbors = [] end def empty?() empty = true @hazards.each do |x| if x != nil empty = false break end end empty end def has?(hazard) has = false @hazards.each do |x| if x == hazard has = true break end end has end def add(hazard) @hazards[@hazards.size] = hazard end def remove(hazard) i = -1 @hazards.each do |x| i = i + 1 if x == hazard break end end if i != -1 @hazards[i] = nil end end def connect(room, first = true) if @neighbors.size < 3 @neighbors[@neighbors.size] = room if first room.connect(self, false) end end end def neighbor(number) nbr = nil @neighbors.each do |x| if x.number == number nbr = x break end end nbr end def random_neighbor() @neighbors.sample() end def exits() exits = [] i = 0 @neighbors.each do |x| exits[i] = x.number i = i + 1 end exits end def safe?() # if it and no neighbors have hazards safe = have_hazards @neighbors.each do |x| if !x.have_hazards safe = false break end end safe end def have_hazards() safe = true @hazards.each do |x| if x != nil safe = false break end end safe end attr_reader :number, :neighbors, :hazards end class Cave def initialize() @rooms = [] end def add_room(num) room = Room.new(num) @rooms[num-1] = room room end def print_hazards() @rooms.each do |room| room.hazards.each do |hzd| puts "#{hzd} in #{room.number}!" end end end def self.dodecahedron() cave = Cave.new one = cave.add_room(1) two = cave.add_room(2) thr = cave.add_room(3) fur = cave.add_room(4) fiv = cave.add_room(5) six = cave.add_room(6) svn = cave.add_room(7) ate = cave.add_room(8) nin = cave.add_room(9) ten = cave.add_room(10) lvn = cave.add_room(11) tlv = cave.add_room(12) ttn = cave.add_room(13) ftn = cave.add_room(14) vtn = cave.add_room(15) stn = cave.add_room(16) svt = cave.add_room(17) atn = cave.add_room(18) ntn = cave.add_room(19) nty = cave.add_room(20) #1 one.connect(two) one.connect(fiv) one.connect(ate) #2 two.connect(thr) two.connect(ten) #3 thr.connect(fur) thr.connect(tlv) #4 fur.connect(fiv) fur.connect(ftn) #5 fiv.connect(six) #6 six.connect(svn) six.connect(vtn) #7 svn.connect(ate) svn.connect(svt) #8 ate.connect(lvn) #9 nin.connect(ten) nin.connect(tlv) nin.connect(ntn) #10 ten.connect(lvn) #11 lvn.connect(nty) #12 tlv.connect(ttn) #13 ttn.connect(ftn) ttn.connect(atn) #14 ftn.connect(vtn) #15 vtn.connect(stn) #16 stn.connect(svt) stn.connect(atn) #17 svt.connect(nty) #18 atn.connect(ntn) #19 ntn.connect(nty) cave end def room(num) @rooms[num-1] end def random_room() @rooms.sample() end def move(hazard, from_room, to_room) if from_room.has?(hazard) from_room.remove(hazard) to_room.add(hazard) end end def add_hazard(hazard, count) rand = @rooms.sample(count) rand.each do |x| if !(x.has?(hazard)) x.add(hazard) end end end def room_with(hazard) room = nil @rooms.each do |x| if x.has?(hazard) room = x break end end room end def entrance() entrance = nil @rooms.each do |x| if x.safe? entrance = x end end entrance end end class Player def initialize() @senses = Hash.new @encounters = Hash.new @actions = Hash.new @room = nil end def sense(hazard, &block) @senses[hazard] = block end def encounter(hazard, &block) @encounters[hazard] = block end def action(action, &block) @actions[action] = block end def enter(room) @room = room @room.hazards.each do |x| enc = @encounters[x] if enc != nil enc.call end end end def explore_room() if @room == nil return end @room.neighbors.each do |nbr| nbr.hazards.each do |x| sense = @senses[x] if sense != nil sense.call() end end end end def act(action, room) action = @actions[action] if action != nil action.call(room) end end attr_reader :room end
true
6ec3a9a18223681b62bf3379defb0ee63ba05e70
Ruby
champagnepappi/ruby
/HeadFirstRuby/chapter7/hashtst.rb
UTF-8
228
3.328125
3
[]
no_license
elements = {"O" => "Oxygen", "Na" => "Sodium"} puts elements["O"] puts elements["Na"] #add value to an existing hash elements["Ne"] = "Neon" puts elements["Ne"] elements.each do |element,count| puts "#{element}:#{count}" end
true
05f7048855154ea3e41572f449661727a7c89830
Ruby
transcriptic/ups-shipping
/lib/ups_shipping/address.rb
UTF-8
772
2.625
3
[]
no_license
require "nokogiri" module Shipping class Address ADDRESS_TYPES = %w{residential commercial po_box} attr_accessor :address_lines, :city, :state, :zip, :country, :type def initialize(options={}) @address_lines = options[:address_lines] @city = options[:city] @state = options[:state] @zip = options[:zip] @country = options[:country] @type = options[:type] end def build(xml) xml.Address { xml.AddressLine1 @address_lines[0] xml.City @city xml.StateProvinceCode @state xml.PostalCode @zip xml.CountryCode @country } end def to_xml() builder = Nokogiri::XML::Builder.new do |xml| build(xml) end builder.to_xml end end end
true
4a6248a632ab67415b00f6917b7b82bb85ed6afc
Ruby
huyettcp/project_2_crossword
/spec/models/word_spec.rb
UTF-8
577
2.59375
3
[]
no_license
# require 'spec_helper' # describe Word do # before :each do # @word = Word.new(name: "Beer") # @photo = Photo.new(url: "google") # @word.photos << @photo # end # describe "#name" do # it "should return the correct word" do # @word.name.should eq("Beer") # end # it "should reuturn a photo" # @word.photos.should eq(Photo) # end # end describe Word do it { validate_presence_of(:name) } it { should allow_value("coffee").for(:name) } it { validate_presence_of(:photo_id) } it { should have_many(:photos) } end
true
b2651962003bebfdf8ebc2063915b4c3d92f2048
Ruby
Infogroep/imp
/util/playlist/vlcinterface.rb
UTF-8
2,334
3.1875
3
[ "MIT" ]
permissive
## # An implementation of the IMediaPlayer interface. # This class launches the VideoLAN VLC Media Player as a subprocess # in remote mode and communicates with it to play media. class VLCInterface ## # Spawns a VLC process and initializes the connection def initialize(on_media_end) @vlc = IO.popen("vlc --fullscreen -I rc","r+") @vlc.puts 'set prompt ""' @vlc.puts 'set prompt' @vlc.gets @vlc.gets @vlc.gets @mutex = Mutex.new @end_checker = Thread.new do while true @mutex.lock if @should_be_playing and not is_playing? @should_be_playing = false @mutex.unlock on_media_end.call else @mutex.unlock end sleep 0.200 end end end ## # Closes the connection to VLC. This invalidates the VLCInterface object. def close @vlc.close end ## # Play a media file/stream def add(uri) synchronized do puts "Playing #{uri}" @vlc.puts "add #{uri}" puts "Waiting for play" wait_for_play true puts "OK" end end ## # Start playback def play synchronized do @vlc.puts "play" wait_for_play true end end ## # Stop playback def stop synchronized do @vlc.puts "stop" wait_for_play false end end ## # Pause playback def pause synchronized do @vlc.puts "pause" end end ## # Check if playback is active def is_playing? synchronized do @vlc.puts "is_playing" a = @vlc.gets a.to_i == 1 end end ## # Get the title of the current media def get_title synchronized do @vlc.puts "get_title" @vlc.gets.to_s end end ## # Get the current position in the media in seconds def get_time synchronized do @vlc.puts "get_time" @vlc.gets.to_i end end ## # Get the length of the current media in seconds def get_length synchronized do @vlc.puts "get_length" @vlc.gets.to_i end end ## # Skip to a certain time in the current media def seek(seconds) synchronized do @vlc.puts "seek #{seconds}" end end ## # Set the VLC volume def volume(x) synchronized do @vlc.puts "volume #{x}" end end private def wait_for_play(status) until status == is_playing? sleep 0.020 # do nothing end @should_be_playing = status end private def synchronized if @mutex.owned? yield else @mutex.synchronize do yield end end end end
true
c980c14646b167420462e1b1e6cb1c543f36928b
Ruby
profan/advent-of-code-2015
/8-2.rb
UTF-8
431
3.0625
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require "matrix" results = File.open("8.input", 'r').reduce(Vector[0, 0]) do |acc, line| chomped = line.chomp.dump escaped = chomped.scan(/\\((?:[xX][0-9a-fA-F]{2})|(?:\\|"))/).reduce(0) do |sum, m| str = m.first sum + str.size end acc + Vector[chomped.length, (chomped.length-2) - escaped] end puts "characters in code #{results[0]} - characters in memory #{results[1]}: #{results[0] - results[1]}"
true
4d81768b87d1c5f6b613d6ba6b2bcb4893fb77f0
Ruby
piyushkp/ShippingInfo
/lib/ups/UpsInfo.rb
UTF-8
11,951
2.640625
3
[ "MIT" ]
permissive
require 'date' require 'time' require 'rexml/document' require 'net/http' require 'net/https' require 'rubygems' require 'active_support' module Fedex # Provides a simple api to to ups's time in transit service. class UpsInfo TEST_URL = "https://wwwcie.ups.com/ups.app/xml" # UPS Production URL PRODUCTION_URL = "https://onlinetools.ups.com/ups.app/xml" XPCI_VERSION = '1.0002' DEFAULT_CUTOFF_TIME = 14 DEFAULT_TIMEOUT = 30 DEFAULT_RETRY_COUNT = 3 DEFAULT_COUNTRY_CODE = 'US' DEFAULT_UNIT_OF_MEASUREMENT = 'LBS' def initialize(access_options) @order_cutoff_time = access_options[:order_cutoff_time] || DEFAULT_CUTOFF_TIME @timeout = access_options[:timeout] || DEFAULT_TIMEOUT @retry_count = access_options[:retry_count] || DEFAULT_CUTOFF_TIME @access_xml = generate_xml({ :AccessRequest => { :AccessLicenseNumber => access_options[:access_license_number], :UserId => access_options[:user_id], :Password => access_options[:password] } }) @transit_from_attributes = { :AddressArtifactFormat => { :PoliticalDivision2 => access_options[:sender_city], :PoliticalDivision1 => access_options[:sender_state], :CountryCode => access_options[:sender_country_code] || DEFAULT_COUNTRY_CODE, :PostcodePrimaryLow => access_options[:sender_zip] } } @rate_from_attributes = { :Address => { :City => access_options[:sender_city], :StateProvinceCode => access_options[:sender_state], :CountryCode => access_options[:sender_country_code] || DEFAULT_COUNTRY_CODE, :PostalCode => access_options[:sender_zip] } } end def getPrice (options) @url = options[:mode] == "production" ? PRODUCTION_URL : TEST_URL + '/Rate' #@url = options[:url] + '/Rate' # build our request xml xml = @access_xml + generate_xml(build_price_attributes(options)) #puts xml # attempt the request in a timeout delivery_price = 0 begin Timeout.timeout(@timeout) do response = send_request(@url, xml) delivery_price = response_to_price(response) end delivery_price end end def getTransitTime(options) @url = options[:mode] == "production" ? PRODUCTION_URL : TEST_URL + '/TimeInTransit' #@url = options[:url] + '/TimeInTransit' # build our request xml pickup_date = calculate_pickup_date options[:pickup_date] = pickup_date.strftime('%Y%m%d') xml = @access_xml + generate_xml(build_transit_attributes(options)) # attempt the request in a timeout delivery_dates = {} attempts = 0 begin Timeout.timeout(@timeout) do response = send_request(@url, xml) delivery_dates = response_to_map(response) end # We can only attempt to recover from Timeout errors, all other errors # should be raised back to the user rescue Timeout::Error => error if(attempts < @retry_count) attempts += 1 retry else raise error end end delivery_dates end private # calculates the next available pickup date based on the current time and the # configured order cutoff time def calculate_pickup_date now = Time.now day_of_week = now.strftime('%w').to_i in_weekend = [6,0].include?(day_of_week) in_friday_after_cutoff = day_of_week == 5 and now.hour > @order_cutoff_time # If we're in a weekend (6 is Sat, 0 is Sun,) or we're in Friday after # the cutoff time, then our ship date will move if(in_weekend or in_friday_after_cutoff) pickup_date = now # if we're in another weekday but after the cutoff time, our ship date # moves to tomorrow elsif(now.hour > @order_cutoff_time) pickup_date = now else pickup_date = now end end # Builds a hash of transit request attributes based on the given values def build_transit_attributes(options) # set defaults if none given options[:total_packages] = 1 unless options[:total_packages] # convert all options to string values options.each_value {|option| option = options.to_s} transit_attributes = { :TimeInTransitRequest => { :Request => { :RequestAction => 'TimeInTransit', :TransactionReference => { :XpciVersion => XPCI_VERSION } }, :TotalPackagesInShipment => options[:total_packages], :ShipmentWeight => { :UnitOfMeasurement => { :Code => options[:unit_of_measurement] || DEFAULT_UNIT_OF_MEASUREMENT }, :Weight => options[:weight], }, :PickupDate => options[:pickup_date], :TransitFrom => @transit_from_attributes, :TransitTo => { :AddressArtifactFormat => { :PoliticalDivision2 => options[:city], :PoliticalDivision1 => options[:state], :CountryCode => options[:country_code] || DEFAULT_COUNTRY_CODE, :PostcodePrimaryLow => options[:zip], } } } } end # Builds a hash of price attributes based on the given values def build_price_attributes(options) # convert all options to string values options.each_value {|option| option = options.to_s} rate_attributes = { :RatingServiceSelectionRequest => { :Request => { :RequestAction => 'Rate', :RequestOption => 'Rate', :TransactionReference => { :XpciVersion => '1.0'} }, :PickupType => { :Code => '01' }, :CustomerClassification => {:Code => '01'}, :Shipment => { :Shipper => @rate_from_attributes, :ShipTo => {:Address => { :City => options[:city], :StateProvinceCode => options[:state], :PostalCode => options[:zip], :CountryCode => options[:country_code]} }, :Service => {:Code => '03'}, :Package => {:PackagingType => {:Code => '02'}, :PackageWeight => {:Weight => options[:weight], :UnitOfMeasurement => 'LBS'} } } } } end # generates an xml document for the given attributes def generate_xml(attributes) xml = REXML::Document.new xml << REXML::XMLDecl.new emit(attributes, xml) xml.root.add_attribute("xml:lang", "en-US") xml.to_s end # recursively emits xml nodes under the given node for values in the given hash def emit(attributes, node) attributes.each do |k,v| child_node = REXML::Element.new(k.to_s, node) (v.respond_to? 'each_key') ? emit(v, child_node) : child_node.add_text(v.to_s) end end # Posts the given data to the given url, returning the raw response def send_request(url, data) uri = URI.parse(url) http = Net::HTTP.new(uri.host, uri.port) if uri.port == 443 http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE end response = http.post(uri.path, data) response.code == '200' ? response.body : response.error! end # converts the given raw xml response to a map of local service codes # to estimated delivery dates def response_to_map(response) response_doc = REXML::Document.new(response) response_code = response_doc.elements['//ResponseStatusCode'].text.to_i raise "Invalid response from ups:\n#{response_doc.to_s}" if(!response_code || response_code != 1) delivery_date = 0 service_codes_to_delivery_dates = {} response_code = response_doc.elements.each('//ServiceSummary') do |service_element| service_code = service_element.elements['Service/Code'].text if(service_code == "GND") date_string = service_element.elements['EstimatedArrival/Date'].text pickup_date = service_element.elements['EstimatedArrival/PickupDate'].text #time_string = service_element.elements['EstimatedArrival/Time'].text #delivery_date = Time.parse("#{date_string}") delivery_date = (Time.parse(date_string) - Time.parse(pickup_date)) / 86400 #service_codes_to_delivery_dates[ "UPS 12"+ service_code + " Transit Days"] = delivery_date end end delivery_date #response end def response_to_price(response) #puts response response_doc = REXML::Document.new(response) response_code = response_doc.elements['//ResponseStatusCode'].text.to_i raise "Invalid response from ups:\n#{response_doc.to_s}" if(!response_code || response_code != 1) delivery_rate = 0 delivery_rate = response_doc.elements['//RatedShipment/TotalCharges/MonetaryValue'].text.to_f delivery_rate #response end def self.state_from_zip(zip) zip = zip.to_i { (99500...99929) => "AK", (35000...36999) => "AL", (71600...72999) => "AR", (75502...75505) => "AR", (85000...86599) => "AZ", (90000...96199) => "CA", (80000...81699) => "CO", (6000...6999) => "CT", (20000...20099) => "DC", (20200...20599) => "DC", (19700...19999) => "DE", (32000...33999) => "FL", (34100...34999) => "FL", (30000...31999) => "GA", (96700...96798) => "HI", (96800...96899) => "HI", (50000...52999) => "IA", (83200...83899) => "ID", (60000...62999) => "IL", (46000...47999) => "IN", (66000...67999) => "KS", (40000...42799) => "KY", (45275...45275) => "KY", (70000...71499) => "LA", (71749...71749) => "LA", (1000...2799) => "MA", (20331...20331) => "MD", (20600...21999) => "MD", (3801...3801) => "ME", (3804...3804) => "ME", (3900...4999) => "ME", (48000...49999) => "MI", (55000...56799) => "MN", (63000...65899) => "MO", (38600...39799) => "MS", (59000...59999) => "MT", (27000...28999) => "NC", (58000...58899) => "ND", (68000...69399) => "NE", (3000...3803) => "NH", (3809...3899) => "NH", (7000...8999) => "NJ", (87000...88499) => "NM", (89000...89899) => "NV", (400...599) => "NY", (6390...6390) => "NY", (9000...14999) => "NY", (43000...45999) => "OH", (73000...73199) => "OK", (73400...74999) => "OK", (97000...97999) => "OR", (15000...19699) => "PA", (2800...2999) => "RI", (6379...6379) => "RI", (29000...29999) => "SC", (57000...57799) => "SD", (37000...38599) => "TN", (72395...72395) => "TN", (73300...73399) => "TX", (73949...73949) => "TX", (75000...79999) => "TX", (88501...88599) => "TX", (84000...84799) => "UT", (20105...20199) => "VA", (20301...20301) => "VA", (20370...20370) => "VA", (22000...24699) => "VA", (5000...5999) => "VT", (98000...99499) => "WA", (49936...49936) => "WI", (53000...54999) => "WI", (24700...26899) => "WV", (82000...83199) => "WY" }.each do |range, state| return state if range.include? zip end raise ShippingError, "Invalid zip code" end end end
true
5f2e0b74f988858e5bb131769933d63c1a098a24
Ruby
poise/poise-spec
/lib/poise_spec/patcher.rb
UTF-8
10,058
2.546875
3
[ "Apache-2.0" ]
permissive
# # Copyright 2015-2016, Noah Kantrowitz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'chef/resource' module PoiseSpec # Utility methods to patch a resource or provider class in to Chef for the # duration of a block. # # @since 1.0.0 # @api private module Patcher # Patch a class in to Chef for the duration of a block. # # @param name [String, Symbol] Name to create in snake-case (eg. :my_name). # @param klass [Class] Class to patch in. # @param mod [Module] Optional module to create a constant in. # @param block [Proc] Block to execute while the patch is available. # @return [void] def self.patch(name, klass, mod=nil, &block) patch_descendants_tracker(klass) do patch_node_map(name, klass) do patch_priority_map(name, klass) do patch_handler_map(name, klass) do patch_recipe_dsl(name, klass) do if mod patch_module(mod, name, klass, &block) else block.call end end end end end end end # Perform any post-class-creation cleanup tasks to deal with compile time # global registrations. # # @since 1.0.4 # @param name [String, Symbol] Name of the class that was created in # snake-case (eg. :my_name). # @param klass [Class] Newly created class. # @return [void] def self.post_create_cleanup(name, klass) # Remove from DSL. Chef::DSL::Resources.remove_resource_dsl(name) if defined?(Chef::DSL::Resources.remove_resource_dsl) # Remove from DescendantsTracker. Chef::Mixin::DescendantsTracker.direct_descendants(klass.superclass).delete(klass) # Remove from the priority and handler maps. {priority: priority_map_for(klass), handler: handler_map_for(klass)}.each do |type, map| if map # Make sure we add name in there too because anonymous classes don't # get a handler map registration by default. removed_keys = remove_from_node_map(map, klass) | [name.to_sym] # This ivar is used down in #patch_*_map to re-add the correct # keys based on the class definition. klass.instance_variable_set(:"@halite_original_#{type}_keys", removed_keys) end end # Remove from the global node map. if defined?(Chef::Resource.node_map) removed_keys = remove_from_node_map(Chef::Resource.node_map, klass) # Used down in patch_node_map. klass.instance_variable_set(:@halite_original_nodemap_keys, removed_keys) end end # Patch an object in to a global namespace for the duration of a block. # # @param mod [Module] Namespace to patch in to. # @param name [String, Symbol] Name to create in snake-case (eg. :my_name). # @param obj Object to patch in. # @param block [Proc] Block to execute while the name is available. # @return [void] def self.patch_module(mod, name, obj, &block) class_name = Chef::Mixin::ConvertToClassName.convert_to_class_name(name.to_s) if mod.const_defined?(class_name, false) old_class = mod.const_get(class_name, false) # We are only allowed to patch over things installed by patch_module raise "#{mod.name}::#{class_name} is already defined" if !old_class.instance_variable_get(:@poise_patch_module) # Remove it before setting to avoid the redefinition warning mod.send(:remove_const, class_name) end # Tag our objects so we know we are allowed to overwrite those, but not other stuff. obj.instance_variable_set(:@poise_patch_module, true) mod.const_set(class_name, obj) begin block.call ensure # Same as above, have to remove before set because warnings mod.send(:remove_const, class_name) mod.const_set(class_name, old_class) if old_class end end # Patch an object in to Chef's DescendantsTracker system for the duration # of a code block. # # @param klass [Class] Class to patch in. # @param block [Proc] Block to execute while the patch is available. # @return [void] def self.patch_descendants_tracker(klass, &block) begin # Re-add to tracking. Chef::Mixin::DescendantsTracker.store_inherited(klass.superclass, klass) block.call ensure # Clean up after ourselves. Chef::Mixin::DescendantsTracker.direct_descendants(klass.superclass).delete(klass) end end # Patch a class in to its node_map. This is not used in 12.4+. # # @param name [Symbol] Name to patch in. # @param klass [Class] Resource class to patch in. # @param block [Proc] Block to execute while the patch is available. # @return [void] def self.patch_node_map(name, klass, &block) return block.call unless defined?(klass.node_map) begin # Technically this is set to true on >=12.4, but this should work. keys = klass.instance_variable_get(:@halite_original_nodemap_keys) | [name.to_sym] keys.each do |key| klass.node_map.set(key, klass) end block.call ensure remove_from_node_map(klass.node_map, klass) end end # Patch a resource in to Chef's recipe DSL for the duration of a code # block. This is a no-op before Chef 12.4. # # @param name [Symbol] Name to patch in. # @param klass [Class] Resource class to patch in. # @param block [Proc] Block to execute while the patch is available. # @return [void] def self.patch_recipe_dsl(name, klass, &block) return block.call unless defined?(Chef::DSL::Resources.add_resource_dsl) && klass < Chef::Resource begin Chef::DSL::Resources.add_resource_dsl(name) block.call ensure Chef::DSL::Resources.remove_resource_dsl(name) end end # Patch a class in to the correct priority map for the duration of a code # block. This is a no-op before Chef 12.4. # # @since 1.0.4 # @param name [Symbol] Name to patch in. # @param klass [Class] Resource or provider class to patch in. # @param block [Proc] Block to execute while the patch is available. # @return [void] def self.patch_priority_map(name, klass, &block) priority_map = priority_map_for(klass) return block.call unless priority_map begin # Unlike patch_node_map, this has to be an array! klass.instance_variable_get(:@halite_original_priority_keys).each do |key| priority_map.set(key, [klass]) end block.call ensure remove_from_node_map(priority_map, klass) end end # Patch a class in to the correct handler map for the duration of a code # block. This is a no-op before Chef 12.4.1. # # @since 1.0.7 # @param name [Symbol] Name to patch in. # @param klass [Class] Resource or provider class to patch in. # @param block [Proc] Block to execute while the patch is available. # @return [void] def self.patch_handler_map(name, klass, &block) handler_map = handler_map_for(klass) return block.call unless handler_map begin klass.instance_variable_get(:@halite_original_handler_keys).each do |key| handler_map.set(key, klass) end block.call ensure remove_from_node_map(handler_map, klass) end end private # Find the global priority map for a class. # # @since 1.0.4 # @param klass [Class] Resource or provider class to look up. # @return [nil, Chef::Platform::ResourcePriorityMap, Chef::Platform::ProviderPriorityMap] def self.priority_map_for(klass) if defined?(Chef.resource_priority_map) && klass < Chef::Resource Chef.resource_priority_map elsif defined?(Chef.provider_priority_map) && klass < Chef::Provider Chef.provider_priority_map end end # Find the global handler map for a class. # # @since 1.0.7 # @param klass [Class] Resource or provider class to look up. # @return [nil, Chef::Platform::ResourceHandlerMap, Chef::Platform::ProviderHandlerMap] def self.handler_map_for(klass) if defined?(Chef.resource_handler_map) && klass < Chef::Resource Chef.resource_handler_map elsif defined?(Chef.provider_handler_map) && klass < Chef::Provider Chef.provider_handler_map end end # Remove a value from a Chef::NodeMap. Returns the keys that were removed. # # @since 1.0.4 # @param node_map [Chef::NodeMap] Node map to remove from. # @param value [Object] Value to remove. # @return [Array<Symbol>] def self.remove_from_node_map(node_map, value) # Sigh. removed_keys = [] # 12.4.1+ switched this to a private accessor and lazy init. map = if node_map.respond_to?(:map, true) node_map.send(:map) else node_map.instance_variable_get(:@map) end map.each do |key, matchers| matchers.delete_if do |matcher| # In 12.4+ this value is an array of classes, before that it is the class. if matcher[:value].is_a?(Array) matcher[:value].include?(value) else matcher[:value] == value end && removed_keys << key # Track removed keys in a hacky way. end # Clear empty matchers entirely. map.delete(key) if matchers.empty? end removed_keys end end end
true
cd79b9c474585142d497432116e4ce84657ff7c0
Ruby
Tkam13/atcoder-problems
/abc159/e.rb
UTF-8
237
2.734375
3
[]
no_license
h,w,k = gets.chomp.split.map(&:to_i) chos = h.times.map{gets.chomp.split.map(&:to_i)} (2 ** (h-1)).times do |n| sum = 0 idx = Array.new(h, 0) (h-1).times do |j| sum += n[j] idx[j+1] = idx[j] + n[j] end p sum p idx end
true
b7648a90c9d414a92e7a8c950125c79b0be2ee5c
Ruby
judo2000/RB101_Programming_Foundations
/lesson_4/double_odd_numbers.rb
UTF-8
1,001
4.28125
4
[]
no_license
def double_odd_numbers(numbers) doubled_numbers = [] counter = 0 loop do break if counter == numbers.size current_number = numbers[counter] current_number *= 2 if current_number.odd? doubled_numbers << current_number counter += 1 end doubled_numbers end # Note that we are working with a method that # does not mutate its argument and instead # returns a new array. We can call it like so: my_numbers = [1, 4, 3, 7, 2, 6] puts double_odd_numbers(my_numbers) puts # not mutated puts "not mutated #{my_numbers}" puts # Try coding a solutio that doubles numbers # that have odd indicies: def double_odd_index(numbers) doubled_numbers = [] counter = 0 loop do break if counter == numbers.size current_number = numbers[counter] current_number *= 2 if counter.odd? doubled_numbers << current_number counter += 1 end doubled_numbers end puts double_odd_index(my_numbers) puts # not mutated puts "not mutated #{my_numbers}"
true
abc7a3ba19da55a0bb196414991127d4e67c731b
Ruby
uemurm/ruby
/POH_lite/lite.rb
UTF-8
811
3.4375
3
[]
no_license
class Combinations < Array def initialize(n) for i in 0...2**n @comb = [] for j in 0...n @comb[j] = ( (i % 2**(j+1) ) >= 2**j ) ? true : false end self.push(@comb) end end end Company = Struct.new(:nEngineers, :fee) companies = [] nEngineersRequired = gets.to_i nCompanies = gets.to_i for idx in 0...nCompanies s = gets.split(" ") s0 = s[0].to_i s1 = s[1].to_i c = Company.new(s0, s1) companies.push(c) end combs = Combinations.new(nCompanies) feeTotals = [] combs.each{|comb| nEngineersTotal = 0 feeTotal = 0 comb.each_with_index{|is_true, i| if is_true nEngineersTotal += companies[i].nEngineers feeTotal += companies[i].fee end } feeTotals.push(feeTotal) if nEngineersTotal >= nEngineersRequired } puts feeTotals.min
true
6c77618450607263672b03565230e96dc440a9c4
Ruby
dshankland/codeclan_w3_cinema
/console.rb
UTF-8
1,879
2.65625
3
[]
no_license
require('pry-byebug') require_relative('models/customer') require_relative('models/film') require_relative('models/ticket') require_relative('models/screening') Ticket.delete_all() Screening.delete_all() Customer.delete_all() Film.delete_all() customer1 = Customer.new({'name' => 'Ann Campbell', 'funds' => 50}) customer1.save() customer2 = Customer.new({'name' => 'Anne McKendry', 'funds' => 100}) customer2.save() customer3 = Customer.new({'name' => 'David McAllister', 'funds' => 80}) customer3.save() customer4 = Customer.new({'name' => 'John Moir', 'funds' => 60}) customer4.save() film1 = Film.new({'title' => 'Captain Marvel', 'price' => 11}) film1.save() film2 = Film.new({'title' => 'Pet Sematary', 'price' => 9}) film2.save() film3 = Film.new({'title' => 'Dumbo', 'price' => 10}) film3.save() screening1 = Screening.new({'film_id' => film1.id, 'showtime' => '12:00', 'capacity' => 20, 'customer_count' => 0}) screening1.save() screening2 = Screening.new({'film_id' => film1.id, 'showtime' => '15:00', 'capacity' => 20, 'customer_count' => 0}) screening2.save() screening3 = Screening.new({'film_id' => film2.id, 'showtime' => '17:15', 'capacity' => 20, 'customer_count' => 0}) screening3.save() screening4 = Screening.new({'film_id' => film2.id, 'showtime' => '20:15', 'capacity' => 20, 'customer_count' => 0}) screening4.save() screening5 = Screening.new({'film_id' => film3.id, 'showtime' => '11:30', 'capacity' => 20, 'customer_count' => 0}) screening5.save() screening6 = Screening.new({'film_id' => film3.id, 'showtime' => '14:30', 'capacity' => 20, 'customer_count' => 0}) screening6.save() # ticket1 = Ticket.new({'customer_id' => customer1.id, 'screening_id' => screening1.id}) # ticket1.save() customer1.buys_ticket(screening1) customer2.buys_ticket(screening2) customer3.buys_ticket(screening2) customer4.buys_ticket(screening5) customer1.buys_ticket(screening6) binding.pry nil
true
2b91c74b03af2d4cfd59eeef82c2af758c5d2461
Ruby
sherrynganguyen/jungle-rails
/spec/models/user_spec.rb
UTF-8
3,072
2.625
3
[]
no_license
require 'rails_helper' RSpec.describe User, type: :model do subject { described_class.new( :firstname => "Pikachu", :lastname => "Pokemon", :email => "TEST@TEST.com", :password => "1234567", :password_confirmation => "1234567" ) } describe 'Validations' do it "should have same password and password confirmation" do expect(subject.password).to eq(subject.password_confirmation) end it 'validates uniqueness of email' do @user_with_same_email = subject.dup @user_with_same_email.save puts subject.lowercase_email puts @user_with_same_email.email expect(subject.lowercase_email)==(@user_with_same_email.email) end it "is not valid without a first name" do subject.firstname = nil expect(subject).to_not be_valid expect(subject.errors.full_messages).to include("Firstname can't be blank") end it "is not valid without a last name" do subject.lastname = nil expect(subject).to_not be_valid expect(subject.errors.full_messages).to include("Lastname can't be blank") end it "is not valid without a email" do subject.email = nil expect(subject).to_not be_valid expect(subject.errors.full_messages).to include("Email can't be blank") end it "is not valid without password" do subject.password = nil expect(subject).to_not be_valid expect(subject.errors.full_messages).not_to be_empty end it "is not valid without password confirmation" do subject.password_confirmation = nil expect(subject).to_not be_valid expect(subject.errors.full_messages).not_to be_empty end it "is not valid without a password less than 6 characters" do subject.password = "123" expect(subject).to_not be_valid expect(subject.errors.full_messages).to include("Password is too short (minimum is 6 characters)") end it "is not valid without a password more than 14 characters" do subject.password = "12346456423423424234" expect(subject).to_not be_valid expect(subject.errors.full_messages).to include("Password is too long (maximum is 14 characters)") end end describe '.authenticate_with_credentials' do it "signs in with correct email and password " do subject.save user = User.authenticate_with_credentials("TEST@TEST.COM", "1234567") expect(subject)==(user) end it "will not sign in with either wrong email or password" do subject.save user = User.authenticate_with_credentials("test@test.com", "1232224567") expect(subject)!=nil end it "authenticated successfully even with a few spaces before and/or after their email address" do subject.save user = User.authenticate_with_credentials(" test@test.com ", "1234567") expect(subject)==user end it "authenticated successfully even with wrong case in their email address" do subject.save user = User.authenticate_with_credentials("test@TEST.com", "1234567") expect(subject)==user end end end
true
768f1d48b923d4a7a071aee1cef96ce0ee9882f7
Ruby
holywyvern/carbuncle
/gems/carbuncle-doc-ext/mrblib/hash.rb
UTF-8
160
2.71875
3
[ "Apache-2.0" ]
permissive
# A hash represents a dictionary of key, value pairs. # Each key can only have one value, but each value can be set to as many keys as you like. class Hash end
true
294c40556dfdb7d4f1b90c98dfa7f6a365b90509
Ruby
nejcik/AkademiaRebased
/task_1_TICTACTOE/board.rb
UTF-8
2,641
3.5625
4
[]
no_license
require_relative 'point' class Board attr_accessor :points_weights, :game_board, :max_size def initialize(size = 3) @points_weights = Array.new(size){ Array.new(size, 0) } create_game_board @max_size = size end def create_game_board(size=3) size = 2 * size + 1 game_board_init = Array.new(size){ Array.new(size, 0) } game_board_init.each_index do |i| game_board_init[i].each_index do |j| if i % 2 == 0 || i == 0 game_board_init[i][j] = "-" elsif j%2 == 0 || j == 0 game_board_init[i][j] = "|" else game_board_init[i][j] = " " end end end num=1 game_board_init.each_index do |i| if i%2 != 0 game_board_init[i].unshift(num) num += 1 else game_board_init[i].unshift(" ") end end letters=create_array_with_letters(game_board_init[1].length) game_board_init.unshift(letters) game_board_init.each_index do |i| game_board_init[i].push("\n") end @game_board = game_board_init end def create_array_with_letters(len) a_ascii = 65 alphabet_row = Array.new(len) alphabet_row.each_index do |i| if i%2 == 0 && i! = 0 alphabet_row[i] = a_ascii.chr a_ascii += 1 else alphabet_row[i] = " " end end end def add_point(point) @points_weights[point.x][point.y] = point.weight x_= point.extended_index(point.x) y_= point.extended_index(point.y) @game_board[x_][y_] = point.symbol end def is_win(max_size = 3) sum=0 # find in rows points_weights.each_index do |i| points_weights[i].each_index do |j| sum += points_weights[i][j] end # puts "rows #{sum}" if check_sum(sum, max_size) return true end sum=0 end # find in columns for j in 0..max_size-1 for i in 0..max_size-1 sum += points_weights[i][j] end # puts "cols #{sum}" if check_sum(sum, max_size) return true end sum = 0 end # find in [0][0] [1][1] [2][2] j = 0 i = 0 sum=points_weights[i][j]+points_weights[i+1][j+1]+points_weights[i+2][j+2] # puts "diag1 #{sum}" if check_sum(sum, max_size) return true end sum = 0 # find in [0][2] [1][1] [2][0] j = max_size -1 i = 0 sum=points_weights[i][j] + points_weights[i+1][j-1] + points_weights[i+2][j-2] # puts "diag2 #{sum}" if check_sum(sum, max_size) return true end sum = 0 return false end def check_sum(sum, max_size) if sum == max_size || sum == -max_size # puts "We have a winner!" win = true #tutaj "jump" do konczonej gry end win end def board_to_show board = game_board.flatten.join end end
true
29ec60815e0d78a939ca6de0ca123b4e8111fbea
Ruby
michael-danello/RB101
/easy9/double_double.rb
UTF-8
469
3.3125
3
[]
no_license
def twice(num) num_string = num.to_s num_size = num_string.size if num_size.even? && num_string[0..num_size/2-1] == num_string[num_size/2..-1] num else num * 2 end end puts twice(37) == 74 puts twice(44) == 44 puts twice(334433) == 668866 puts twice(444) == 888 puts twice(107) == 214 puts twice(103103) == 103103 puts twice(3333) == 3333 puts twice(7676) == 7676 puts twice(123_456_789_123_456_789) == 123_456_789_123_456_789 puts twice(5) == 10
true
d9f1a7015541412d523787ac47580bf50126566f
Ruby
NomadicNibbler/foodtruck_be
/spec/services/food_truck_service_spec.rb
UTF-8
3,238
2.65625
3
[]
no_license
require "rails_helper" RSpec.describe "Food_truck_service_api" do describe "class methods" do it "returns all the possible regions", :vcr do data = FoodTruckService.get_regions expect(data.status).to eq(200) regions = parse(data) expect(regions).to be_an(Array) expect(regions.count).to eq(77) expect(regions.first).to be_a(Hash) expect(regions.first[:identifier]).to eq('abbotsford') expect(regions.first[:latitude]).to eq(49.0504377) expect(regions.first[:longitude]).to eq(-122.3044697) expect(regions.first[:name]).to eq("Abbotsford") end it "when given a location it returns all the food trucks in the area", :vcr do region_identifier = 'vancouver' trucks = FoodTruckService.get_schedules_by_city(region_identifier) expect(trucks.first[1]).to be_a(Hash) expect(trucks.first[1][:description_short]).to eq("Authentic, author gourmet Mexican made with the finest ingredients hand picked.") expect(trucks.first[1][:description]).to eq("Arturo's unique recipes are a fusion of Spanish and traditional Mexican. Clean, simple and healthy Mexican food. Only 3 people prepare the food we serve to our clients, from the local produce and local butcher, there is not third parties when it comes to prepare our dishes. We closely follow Health Authority guidances and protocols to operate our business. We have been serving take out food at open spaces since 2010, and we will continue doing it, safety is our priority.") expect(trucks.first[1][:name]).to eq("arturosmexico2go") expect(trucks.first[1][:region]).to eq("vancouver") expect(trucks.first[1][:phone]).to eq("(604) 202-4043") expect(trucks.first[1][:email]).to eq("info@arturos2go.com") expect(trucks.first[1][:twitter]).to eq("arturomexico2go") expect(trucks.first[1][:facebook]).to eq("arturosmexico2go") expect(trucks.first[1][:instagram]).to eq("arturos2go") expect(trucks.first[1][:name]).to eq("arturosmexico2go") expect(trucks.first[1][:payment_methods]).to eq(["cash", "credit_card", "debit_card", "apple_pay"]) expect(trucks.first[1][:images][:logo_small]).to eq("https://cdn.streetfoodapp.com/images/arturos-to-go/logo/1.90w.png") expect(trucks.first[1][:open]).to be_an(Array) expect(trucks.first[1][:open].length).to eq(6) expect(trucks.first[1][:open].first.keys).to eq([:start, :end, :display, :updated, :latitude, :longitude]) end end describe "sad paths" do it "handles HTML return" do region_identifier = 'rochester' trucks = FoodTruckService.get_schedules_by_city(region_identifier) expect(trucks). to eq([]) end # xit "returns a 404 for integers" do # trucks = FoodTruckService.get_schedules_by_city("2345") # require "pry"; binding.pry # expect(trucks.status).to eq(404) # end # # xit "returns a 404 for invalid" do # trucks = FoodTruckService.get_schedules_by_city("hello") # # expect(trucks.status).to eq(404) # end # # it "returns a 404 if not a valid city" do # trucks = FoodTruckService.get_schedules_by_city("worcester") # # expect(trucks.status).to eq(404) # end end end
true
0e9e58e8644af1adad879d5d7da8ce25d942b424
Ruby
tafujino/vcreport
/lib/vcreport/report/c3js.rb
UTF-8
2,716
2.5625
3
[ "Apache-2.0" ]
permissive
# frozen_string_literal: true require 'json' module VCReport module Report module C3js class Column # @return [Symbol] attr_reader :id # @return [String] attr_reader :label # @return [Boolean] attr_reader :is_categorical # @param id [Symbol] # @param label [String] # @param is_categorical [Boolean] def initialize(id, label, is_categorical = false) @id = id @label = label @is_categorical = is_categorical end end class Data # @return [Array<Hash>] attr_reader :entries # @param entries [Array<Hash>] def initialize(entries) @entries = entries end # @param key_and_value [Hash{ Symbol => Object }] # @return [Data] def select(**key_and_value) entries = @entries.filter_map do |e| next nil unless key_and_value.all? { |k, v| e[k] == v } e end Data.new(entries) end # @param cols [Array<Column>] # @return [Array<Array>>] def rows(*cols) @entries.inject([cols.map(&:label)]) do |a, e| a << e.values_at(*cols.map(&:id)) end end # @param cols [Array<Column>] # @param x [C3js::Column] # @param bindto [String] # @param x_axis_label_height [Integer] # @return [String] def bar_chart_json(*cols, x:, bindto:, x_axis_label_height:) row_data = rows(*cols) chart = { bindto: "##{bindto}", data: { x: x.label, rows: row_data, type: 'bar' }, axis: { x: { type: 'category', tick: { rotate: 90, multiline: false }, height: x_axis_label_height } }, zoom: { enabled: true }, legend: { show: false } } chart.deep_stringify_keys! JSON.generate(chart) end # @param cols [Array<Column>] # @param x [C3js::Column] # @param bindto [String] # @param x_axis_label_height [Integer] # @return [String] def bar_chart_html(*cols, x:, bindto:, x_axis_label_height:) json = bar_chart_json( *cols, x: x, bindto: bindto, x_axis_label_height: x_axis_label_height ) <<~HTML <div id = "#{bindto}"></div> <script>c3.generate(#{json})</script> HTML end end end end end
true