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
ff120aac51dbb58dbb54eed3b48ded4399a4f3c1
Ruby
AndreLaranjeira/RottenPotatoes
/app/models/movie.rb
UTF-8
373
2.515625
3
[]
no_license
require 'active_record' class Movie < ActiveRecord::Base #self.abstract_class = true #attr_accessible :title, :rating, :description, :release_date @@all_ratings = ["G", "PG", "PG-13", "NC-17", "R"] def self.all_ratings @@all_ratings end def self.find_by_director(m) return (m.director.blank? ? [] : Movie.all.where(director: m.director)) end end
true
9791bba902a070230e98583ecf0722c0568990e1
Ruby
hollyglot/code-exercises
/ruby-exercises/test_email.rb
UTF-8
355
2.734375
3
[]
no_license
require 'test/unit' class User attr_accessor :email def initialize(email) @email = email end end # Test if user's email is unique when a User record is created class TestUserEmailUniqueness < Test::Unit::TestCase def test_email_uniqueness user = User.new('boo@bar.com') assert(true, User.where(:email => user.email).nil?) end end
true
fd587c6190271ee377253e14520459fbbf6797e2
Ruby
pooza/ginseng-core
/test/standard_error_test.rb
UTF-8
443
2.5625
3
[ "MIT" ]
permissive
module Ginseng class StandardErrorTest < TestCase def setup @standard_error = StandardError.new('test') raise 'test2' rescue => e @runtime_error = e end def test_status assert_equal(500, @standard_error.status) assert_equal(500, @runtime_error.status) end def test_to_h assert_kind_of(Hash, @standard_error.to_h) assert_kind_of(Hash, @runtime_error.to_h) end end end
true
69596c28879a1da643b6fd116e5b75b44261f444
Ruby
LipsiaGROUP/stecms-appointment-plugin
/app/models/stecms_appointment/customer.rb
UTF-8
625
2.515625
3
[ "MIT" ]
permissive
module StecmsAppointment class Customer < ActiveRecord::Base has_many :bookings, class_name: 'StecmsAppointment::Booking', foreign_key: 'stecms_appointment_customer_id' def self.search_customers(term) salon_customers = select('id, name, cell') .where("name LIKE :term OR cell LIKE :term", { term: "%#{term}%"}) salon_customers.map do |customer| customer.convert_to_hashes end end def convert_to_hashes { id: self.id, label: self.name.titleize, value: self.name.titleize, contact_number: self.cell } end end end
true
080cbb178060ddbd5a5c7f3b53d8d9b817c9ed34
Ruby
cofiem/clearly-query
/lib/clearly/query/helper.rb
UTF-8
2,577
2.8125
3
[ "MIT" ]
permissive
module Clearly module Query # Utility methods for working with Arel. class Helper class << self # Concatenate one or more strings # @param [Array<String>] args strings to concatenate # @return [Arel::Nodes::Node] def string_concat(*args) adapter = ActiveRecord::Base.connection.adapter_name.underscore.downcase case adapter when 'mysql' named_function('concat', args) when 'sqlserver' string_concat_infix('+', *args) when 'postgres' when 'sq_lite' string_concat_infix('||', *args) else fail ArgumentError, "unsupported database adapter '#{adapter}'" end end # Concatenate strings using an operator # @param [Object] operator infix operator # @param [Array<String>] args strings to concatenate # @return [Arel::Nodes::Node] def string_concat_infix(operator, *args) if args.blank? || args.size < 2 fail ArgumentError, "string concatenation requires operator and two or more arguments, given '#{args.size}'" end result = Arel::Nodes::InfixOperation.new(operator, args[0], args[1]) if args.size > 2 args.drop(2).each do |a| result = Arel::Nodes::InfixOperation.new(operator, result, a) end end result end # Construct a SQL literal. # This is useful for sql that is too complex for Arel. # @param [String] value # @return [Arel::Nodes::Node] def sql_literal(value) Arel::Nodes::SqlLiteral.new(value) end # Construct a SQL quoted string. # This is used for fragments of SQL. # @param [String] value # @return [Arel::Nodes::Node] def sql_quoted(value) Arel::Nodes.build_quoted(value) end # Construct a SQL EXISTS clause. # @param [Arel::Nodes::Node] node # @return [Arel::Nodes::Node] def exists(node) Arel::Nodes::Exists.new(node) end # Construct an Arel representation of a SQL function. # @param [String] name # @param [String, Arel::Nodes::Node] expression # @param [String] function_alias # @return [Arel::Nodes::Node] def named_function(name, expression, function_alias = nil) Arel::Nodes::NamedFunction.new(name, expression, function_alias) end end end end end
true
1219782468263c1e0bedc401074cc282844d68a2
Ruby
rpalo/advent-of-code-2017
/challenges/day21.rb
UTF-8
310
2.921875
3
[]
no_license
# frozen_string_literal: true require_relative '../lib/fractal' start = <<~HEREDOC .#. ..# ### HEREDOC rules = ARGF.read.chomp frac = Fractal.new(start, rules) frac.iterate(5) puts "# of cells on after 5 iterations: #{frac.on}" frac.iterate(13) puts "# of cells on after 18 iterations: #{frac.on}" #Y
true
e486c929bfece3dc18307c59ca83e8a106af8469
Ruby
davebirinyi/aarsiat_app
/test/models/guest_test.rb
UTF-8
1,774
2.78125
3
[]
no_license
require 'test_helper' class GuestTest < ActiveSupport::TestCase def setup @guest = Guest.new( name: "Example Guest", email: "guest@thewedding.com", song_artist: "", song_title: "") end test "should be valid" do assert @guest.valid? end test "name should be present" do @guest.name = " " assert_not @guest.valid? end test "email should be present" do @guest.email = " " assert_not @guest.valid? end test "name should not be too long" do @guest.name = "a" * 51 assert_not @guest.valid? end test "email should not be too long" do @guest.email = "a" * 244 + "@thewedding.com" assert_not @guest.valid? end test "email validation should accept valid addresses" do valid_addresses = %w[user@example.com USER@foo.COM A_US-ER@foo.bar.org first.last@foo.jp alice+bob@baz.cn] valid_addresses.each do |valid_address| @guest.email = valid_address assert @guest.valid?, "#{valid_address.inspect} should be valid" end end test "email validation should reject invalid addresses" do invalid_addresses = %w[user@example,com user_at_foo.org user.name@example. foo@bar_baz.com foo@bar+baz.com] invalid_addresses.each do |invalid_address| @guest.email = invalid_address assert_not @guest.valid?, "#{invalid_address.inspect} should be invalid" end end test "email addresses should be unique" do duplicate_guest = @guest.dup duplicate_guest.email = @guest.email.upcase @guest.save assert_not duplicate_guest.valid? end test "email addresses should be saved as lower-case" do mixed_case_email = "Foo@ExAMPle.CoM" @guest.email = mixed_case_email @guest.save assert_equal mixed_case_email.downcase, @guest.reload.email end end
true
f8cc954f0f4073479af470d215ad24b96bf4846e
Ruby
rlafranchi/myflix
/spec/models/video_spec.rb
UTF-8
1,899
2.53125
3
[]
no_license
require 'spec_helper' describe Video do it "should save" do v = Video.create(name: 'name', description: 'description' ) expect(Video.first).to eq(v) end it {should belong_to(:category)} it {should validate_presence_of(:name)} it {should validate_presence_of(:description)} it {should have_many(:reviews).order("created_at DESC")} describe "search_by_name" do it "returns empty array if no match" do futurama = Video.create(name: "Futurama", description: "Space travel") back_to_future = Video.create(name: "Back to the Future", description: "time travel") expect(Video.search_by_name("hello")).to eq([]) end it "returns an array of one video for an exact match" do futurama = Video.create(name: "Futurama", description: "Space travel") back_to_future = Video.create(name: "Back to the Future", description: "time travel") expect(Video.search_by_name("Futurama")).to eq([futurama]) end it "returns array of one video for a partial match" do futurama = Video.create(name: "Futurama", description: "Space travel") back_to_future = Video.create(name: "Back to the Future", description: "time travel") expect(Video.search_by_name("urama")).to eq([futurama]) end it "returns array of multiple vidoes for multiple matches" do futurama = Video.create(name: "Futurama", description: "Space travel") back_to_future = Video.create(name: "Back to the Future", description: "time travel", created_at: 1.day.ago) expect(Video.search_by_name("Futur")).to eq([futurama, back_to_future]) end it "searches for empy string" do futurama = Video.create(name: "Futurama", description: "Space travel") back_to_future = Video.create(name: "Back to the Future", description: "time travel", created_at: 1.day.ago) expect(Video.search_by_name("")).to eq([]) end end end
true
5517ca5047fcacb64a18d74dc65c7b1b4d621dfd
Ruby
vioif/inheritance_part1
/student.rb
UTF-8
164
3.203125
3
[]
no_license
require_relative 'people' class Student < People def initialize(name) @name = name end def name @name end def learn "I got it!" end end
true
bb69e144fa138d7c1144b341a182279188197d93
Ruby
asmuth/clip-examples
/misc/letters-cyrillic/generate.rb
UTF-8
619
2.609375
3
[]
no_license
#!/usr/bin/env ruby letters = [ ["Аа", "A"], ["Бб", "Be"], ["Вв", "V"], ["Гг", "G"], ["Дд", "D"], ["Ее", "Eh"], ["Ж", "Zh"], ["Зз", "Z"], ["Ии", "I"], ["Пп", "P"], ] letters.each_with_index do |(letter, desc)| spec = <<-EOF (layer/resize A6) (draw/text text "#{letter}" position (50% 90mm) font "Roboto Slab" font-size 172pt) (draw/text text "#{desc}" position (50% 30mm) font "Roboto" font-size 60pt) EOF IO::write("#{letter[0]}.clp", spec) `clip -e #{letter[0]}.svg #{letter[0]}.clp` end
true
49ac9f811e232fb3159d9ec4ad5978c0cbc9fed8
Ruby
derekorgan/ruby
/Terrain/twodarray.rb
UTF-8
2,070
4.125
4
[]
no_license
# A TwoDArray is a Two-Dimensional Array of a consistent width class TwoDArray attr_reader :w, :h include Enumerable include Comparable def initialize (w=0, h=0) if w > 0 and h > 0 @data = Array.new(w){ Array.new(h) } else @data = Array.new{ Array.new } end @w = w @h = h end # getter def [](x, y) @data[y][x] end # setter def []=(x,y,val) @data[y][x] = val end # allows you to push an array/row to the 2 demensional array. # all rows must be the same width def << (val) # if this is first row set the width based on size of first array to be pushed if @h == 0 @w = val.size elsif val.size != @w or val.class.to_s != 'Array' raise "Only add rows/arrays the same size as the width(#{@w})" end @data[@h] = val @h += 1 end def <=> (other) self.size <=> other.size end def map temp = TwoDArray.new(@w,@h) @data.each_index do |y| @data[y].each_index do |x| temp[x,y] = yield self[x,y] end end end def map! @data.each_index do |y| @data[y].each_index do |x| self[x,y] = yield self[x,y] end end end def each @data.each do |y| y.each do |x| yield x end end end # this returns a hash of x,y def each_index @data.each_index do |y| @data[y].each_index do |x| yield x, y end end end # this returns a hash of x,y,value def each_with_index @data.each_index do |y| @data[y].each_with_index do |val, x| yield x,y,val end end end # yeilds each row of the slice from position x,y of width w and height h def slice_rows(x,y,w,h) (y..y+h-1).each do |i| yield @data[i][x..x+w-1] end end def max to_ary.max end # simplified version of fill that only takes one argument def fill(x) @data.each do |a| a.fill x end end def clear @data.clear @w = @h = 0 end #returns the product of width and height def size @w * @h end # return flattened 1 demensional array of data def to_ary @data.flatten end def to_s s = "" @data.each do |y| s += y.join(' ') + "\n" end s end end
true
cafe0ed27db513b68d54a187539d5a7eb4682c8d
Ruby
dunn/homebrew-cmds
/cmd/brew-url.rb
UTF-8
745
2.671875
3
[]
no_license
# brew url <formula> # # List the associated URLs for the given formulae: main download link, # head, devel, bottle for the current OS. require "formula" def print_urls(f) puts "#{Tty.underline}#{f.name}.rb#{Tty.reset}" %w[stable bottle devel head].each do |source| next unless f.send(source) url = "#{Tty.bold}#{source}#{Tty.reset}" url += "\t" url += f.send(source).url if source != "bottle" && f.send(source).specs url += " #{f.send(source).specs.to_s.gsub!(/[\{\}]/,"")}" end puts url end end raise FormulaUnspecifiedError if ARGV.empty? ARGV.each do |formula| begin print_urls(Formulary.factory(formula)) rescue FormulaUnavailableError puts "No formula named '#{formula}'." end end
true
0e730be0353ba2e1ec38b0d8364675370a67918e
Ruby
aysikh/ruby-oo-object-relationships-has-many-lab
/lib/artist.rb
UTF-8
352
3.078125
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class Artist attr_reader :name @@all = [] def initialize(name) @name = name @@all << self #we want the instances of the songs...not just the name end def self.all @@all end def songs end def add_song(song) end def add_song_by_name end def self.song_count end end
true
60807731a0cf0bb55d862bebb6a912ccaa7e4669
Ruby
vsparrow/ruby-object-initialize-lab-cb-000
/lib/dog.rb
UTF-8
463
3.984375
4
[]
no_license
# Define a Dog class in lib/dog.rb that provides an #initialize method that accepts an argument for the dog's name. # That argument should be stored within a @name instance variable. # # Additionally, Dog#initialize should accept a second optional argument for the dog's breed stored in an instance variable @breed. # When none is provided, it should default to "Mutt". class Dog def initialize(name,breed="Mutt") @name=name @breed=breed end end
true
7eed722faadb4bece92e8c6a173fd43307149ee3
Ruby
davidblackwelder/test
/while.rb
UTF-8
325
4.0625
4
[]
no_license
# num = 1 # while num < 10 # puts num # num += 1 # end # puts "Please enter your name: " # name[] = gets.chomp.downcase.capitalize # while name[] != "Pam" # puts "Please enter your name: " # name = gets.chomp.downcase.capitalize # end num = rand(1..10) while num != 7 puts num num = rand(1..10) end puts "Lucky 7"
true
50df0ae4ae7d4de680ae488b4c259ce888052896
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/binary/fa54f2d009a84323889c705e1d27bcd0.rb
UTF-8
332
3.328125
3
[]
no_license
class Binary ASCII_ZERO = '0'.ord attr_accessor :binary def initialize binary self.binary = binary end def to_decimal binary.bytes.reverse_each.with_index.reduce(0) do |base10,(byte,i)| digit = byte - ASCII_ZERO return 0 unless digit.between? 0,1 base10 + ( digit * 2**i ) end end end
true
35e75c411dcca83dc14c8403df2085c7bd8ad4f2
Ruby
gilibethvega/desafio_cuentas_barajas_2
/cuentas_bancarias.rb
UTF-8
979
3.703125
4
[]
no_license
class Usuario attr_accessor :cuenta_bancaria, :nombre def initialize(nombre, cuenta_bancaria) raise ArgumentError, "Se necesita al menos una cuenta" if cuenta_bancaria.size < 1 @nombre = nombre @cuenta_bancaria = cuenta_bancaria end def saldo_total @cuenta_bancaria.map { |x| x.saldo}.sum end end class CuentaBancaria attr_accessor :banco, :numero_de_cuenta, :saldo def initialize(banco, numero_de_cuenta, saldo = 0) @banco = banco @numero_de_cuenta = numero_de_cuenta @saldo = saldo end def transferir(monto, cuenta_destino) self.saldo -= monto cuenta_destino.saldo += monto end end cuenta1 = CuentaBancaria.new("Banco de Chile", 1234,5000) cuenta2 = CuentaBancaria.new("Banco Santander", 5678, 5000) cuenta3 = CuentaBancaria.new("Banco Itaú", 0707, 20000) usuario1 = Usuario.new("Gili", [cuenta1, cuenta3]) usuario2 = Usuario.new("Giselle", [cuenta2]) puts cuenta1.transferir(5000, cuenta2) puts usuario1.saldo_total
true
9835a43b1c0f103837fbbc9a553fe1aca1846c22
Ruby
nysdin/AtCoder
/ABC/157/a.rb
UTF-8
31
2.75
3
[]
no_license
n = gets.to_i puts (n-1)/2 + 1
true
2a707f1c89c8c70431520df00d463f0bac795218
Ruby
Vjp888/backend_prework
/day_4/ex19.rb
UTF-8
1,176
4.53125
5
[]
no_license
#This is creating a parameter and setting an order for the needed information. def cheese_and_chrackers(cheese_count, boxes_of_crackers) puts "You have #{cheese_count} cheeses!" puts "You have #{boxes_of_crackers} boxes of crackers!" puts "Man that's enough for a party!" puts "Get a blanket.\n" end #This is giving the needed number in the order needed and calling for the method. puts "We can just give the method number directly:" cheese_and_chrackers(20,30) # This is setting a variable for the needed information then calling # The method while using those variables. However these variables # Will not interact with the method otherwise. puts "OR, we can use the variables from our script:" amount_of_cheese = 10 amount_of_crackers = 50 cheese_and_chrackers(amount_of_cheese, amount_of_crackers) # Doing simple math after calling the method to give it the need information puts "We can even do math inside too:" cheese_and_chrackers(10 + 20, 5 + 6) # This is grabbing the variables above and adding to them to give a new number. puts "And we can combine the two, cariables and math:" cheese_and_chrackers(amount_of_cheese + 100, amount_of_crackers + 1000)
true
eb7f5b410dff740643d279a084b2f10e368dff1c
Ruby
basicxman/rgb-tetris
/docs/planning/draw_blocks.rb
UTF-8
3,135
3.078125
3
[]
no_license
#!/usr/bin/env ruby # Andrew Horsman # Tetris Planning # Draw BlockPrototype require 'gosu' require 'set' require File.expand_path(File.dirname(__FILE__) + '/block_prototype') require File.expand_path(File.dirname(__FILE__) + '/game_config') require File.expand_path(File.dirname(__FILE__) + '/state_machine') class GameWindow < Gosu::Window def initialize super(GameConfig::window_width, GameConfig::window_height, false) self.caption = "Block Drawing Prototype | rgb-tetris" end def draw end end class TestGameWindow < GameWindow def initialize super @cur_tetromino = Tetromino.new(self, :z) @keyboard_cycle = 1 @press_queue = Set.new end def draw @cur_tetromino.draw end def update if button_down? Gosu::Button::KbEscape close end if button_down? Gosu::Button::KbLeft @cur_tetromino.state_machine.execute_if_clear(:shift_left) end if button_down? Gosu::Button::KbRight @cur_tetromino.state_machine.execute_if_clear(:shift_right) end if button_down? Gosu::Button::KbUp @cur_tetromino.state_machine.execute_if_clear(:rotate) end if button_down? Gosu::Button::KbDown @cur_tetromino.state_machine.execute_if_clear(:move_down) end @cur_tetromino.state_machine.advance_state end end class Tetromino attr_accessor :state_machine def initialize(window, block_prototype) @window = window @cur_x = 1 @cur_y = 1 @box_image = Gosu::Image.new(@window, "box.png", false) @tetromino = Tetrominoes::get_tetromino(block_prototype) @cur_orientation = :up @order = GameConfig::ORIENTATION_ORDER cycle = GameConfig::RELATIVE_STATE_CYCLE @state_machine = KeyboardStateMachine.new @state_machine.define_action(:shift_left, cycle) { move_left } @state_machine.define_action(:shift_right, cycle) { move_right } @state_machine.define_action(:move_down, cycle) { move_down } @state_machine.define_action(:rotate, cycle) { rotate } end def draw grab_blocks do |x, y| @box_image.draw(x, y, GameConfig::ZIndex::Tetromino) end end def rotate current = @order.index(@cur_orientation) current = GameConfig::ROTATION_DIRECTION == :left ? current - 1 : current + 1 current %= @order.length @cur_orientation = @order[current] end def move_down @cur_y += 1 unless @cur_y == GameConfig::WINDOW_HEIGHT_BOXES end def move_left @cur_x -= 1 unless @cur_x == 0 end def move_right @cur_x += 1 unless @cur_x == GameConfig::WINDOW_WIDTH_BOXES end private def grab_blocks @tetromino.orientations[@cur_orientation].blocks.each_value do |block| yield calculate_absolute_x(block.x), calculate_absolute_y(block.y) end end def calculate_absolute_x(relative_x) @cur_x * 30 + relative_x * 30 end def calculate_absolute_y(relative_y) @cur_y * 30 + relative_y * 30 end end window = TestGameWindow.new window.show
true
d60c82f8b31bc329fb1c395170f33453e15f5e15
Ruby
jeff235255/test_driven_development_minitest
/money.rb
UTF-8
315
3.484375
3
[]
no_license
class Money attr_reader :amount, :currency def initialize(amount, currency) @amount = amount @currency = currency end def self.dollar(amount) Money.new(amount, :USD) end def self.franc(amount) Money.new(amount, :CHF) end def self.vnd(amount) Money.new(amount, :VND) end end
true
4bff25535dd01a593345fcd5f57882a47b8b93ca
Ruby
hirayama/ruby
/awsSdkContainer/test/testmail.rb
UTF-8
1,738
2.75
3
[]
no_license
require 'aws-sdk' # Replace sender@example.com with your "From" address. # This address must be verified with Amazon SES. sender = "no-reply@hoge.jp" # Replace recipient@example.com with a "To" address. If your account # is still in the sandbox, this address must be verified. recipient = "hirayama.tomohiro@hoge.jp" # Specify a configuration set. If you do not want to use a configuration # set, comment the following variable and the # configuration_set_name: configsetname argument below. # configsetname = "ConfigSet" # Replace us-west-2 with the AWS Region you're using for Amazon SES. awsregion = "us-east-1" # The subject line for the email. subject = "test" # The HTML body of the email. htmlbody = '<h1>日本語html</h1>' # The email body for recipients with non-HTML email clients. textbody = "日本語テスト" # Specify the text encoding scheme. encoding = "UTF-8" # Create a new SES resource and specify a region ses = Aws::SES::Client.new( region: awsregion, access_key_id: '', secret_access_key: '' ) # Try to send the email. begin # Provide the contents of the email. resp = ses.send_email({ destination: { to_addresses: [ recipient, ], }, message: { body: { html: { charset: encoding, data: htmlbody, }, text: { charset: encoding, data: textbody, }, }, subject: { charset: encoding, data: subject, }, }, source: sender # Comment or remove the following line if you are not using # a configuration set }) puts "Email sent!" # If something goes wrong, display an error message. rescue Aws::SES::Errors::ServiceError => error puts "Email not sent. Error message: #{error}" end
true
f8b0b8222af32e102a8fb49a43aad1544e3301e6
Ruby
srebalaji/100DaysOfAlgorithm
/day98/abstract_factory_design_pattern.rb
UTF-8
625
3.4375
3
[]
no_license
# Abstract Factory Design Pattern. class Computer def initialize(specs) @specs = specs end def build puts "#{self.name} is created with #{self.specs}" end end class Pc < Computer attr_accessor :specs, :name def initialize(specs) @name = "Pc" @specs = specs end end class Server < Computer attr_accessor :specs, :name def initialize(specs) @name = "Server" @specs = specs end end class ComputerFactory def create_computer(computer) computer.build end end factory = ComputerFactory.new factory.create_computer(Pc.new("ram with 25gb")) factory.create_computer(Server.new("Disk space with 100gb"))
true
424cefff18b03eeaff60bc81d8e5982b1ab6b5bc
Ruby
efatsi/rails-heroicon
/lib/rails_heroicon/helper.rb
UTF-8
1,834
2.75
3
[ "MIT" ]
permissive
require "action_view" module RailsHeroicon module Helper # To add a heroicon, call <tt><%= heroicon "icon_name" %></tt> on your erb template. # Head over to https://heroicons.com to view all the icons. # # == Options # The helper method accepts mutiple arguments such as: # # === Variant # There are two types of variants: 'outline' and 'solid', the default being the 'outline'. # To specify the solid variant, call <tt><%= heroicon "icon_name", variant: "solid" %></tt> # # === HTML attributes # Any <tt>html</tt> attribute is supported, for eg: # # <tt><%= heroicon "icon_name", class: "text-gray-500", data: { controller: "icon" } %></tt> # # === Handling the icon size # Normally, if you're just using vanilla heroicons with tailwindcss, you'd set <tt>w-5 h-5</tt> as class attributes # on the svg. With this helper, you just need to set the <tt>size</tt> attribute on the icon. # # <tt><%= heroicon "icon_name", size: 20 %></tt> # # This will set the <tt>height</tt> and <tt>width</tt> attribute on the svg. # # If the variant is set as <tt>outline</tt>, size automatically defaults to 24, and if the variant is set as # <tt>solid</tt>, size automatically defaults to 20. However, this can be over-written with the <tt>size</tt> # attribute. # # == Accessibility # The helper method automatically sets <tt>aria-hidden=true</tt> if <tt>aria-label</tt> is not set, and # if <tt>aria-label</tt> is set, then <tt>role=img</tt> is set automatically. def heroicon(symbol, title: nil, **options) icon = RailsHeroicon.new(symbol, **options) title_tag = content_tag(:title, title) if title content_tag(:svg, title_tag.to_s.html_safe + icon.svg_path.html_safe, icon.options) end end end
true
397d43b780cf7edf25d635e2b7c85408a12f92b1
Ruby
Watson-Derek/RB120
/Exercises/oo_basics_classes_objects_2/public_secret.rb
UTF-8
172
3.296875
3
[]
no_license
class Person def secret=(s) @secret = s end def secret @secret end end person1 = Person.new person1.secret = 'Shh.. this is a secret!' puts person1.secret
true
4493bac8e6ba71f5c9f70a4fd8dbcd6f1ffbc10b
Ruby
pvselvan/iXperience
/exercises/d3/reverse.rb
UTF-8
187
3.65625
4
[]
no_license
array = ["apples", "bananas", "carrots", 4] # to print in reverse, just use the .reverse method index = array.length - 1 while (index >= 0) puts array[index] index = index - 1 end
true
029f738e25084147a830c83b2980b8d6667e265f
Ruby
castwide/backport
/lib/backport/client.rb
UTF-8
3,048
3.0625
3
[ "MIT" ]
permissive
require 'observer' module Backport # A client connected to a connectable Backport server. # class Client include Observable # @return [Adapter] attr_reader :adapter # @param input [IO] # @param output [IO] # @param adapter [Class, Module] # @param remote [Hash] def initialize input, output, adapter, remote = {} @in = input @out = output @mutex = Mutex.new @adapter = make_adapter(adapter, remote) @stopped = true @buffer = '' end # True if the client is stopped. # def stopped? @stopped ||= false end # Close the client connection. # # @note The client sets #stopped? to true and runs the adapter's #closing # callback. The server is responsible for implementation details like # closing the client's socket. # # @return [void] def stop return if stopped? @adapter.closing @stopped = true changed notify_observers self end # Start running the client. This method will start the thread that reads # client input from IO. # # @return [void] def start return unless stopped? @stopped = false @adapter.opening run_input_thread end # @deprecated Prefer #start to #run for non-blocking client/server methods alias run start # Handle a tick from the server. This method will check for client input # and update the adapter accordingly, or stop the client if the adapter is # closed. # # @return [void] def tick input = read @adapter.receiving input unless input.nil? end private # Read the client input. Return nil if the input buffer is empty. # # @return [String, nil] def read tmp = nil mutex.synchronize do tmp = @buffer.dup @buffer.clear end return tmp unless tmp.empty? end # @param mod_cls [Module, Class] The Adapter module or class # @param remote [Hash] Remote client data # @return [Adapter] def make_adapter mod_cls, remote if mod_cls.is_a?(Class) && mod_cls <= Backport::Adapter @adapter = mod_cls.new(@out, remote) elsif mod_cls.class == Module @adapter = Adapter.new(@out, remote) @adapter.extend mod_cls else raise TypeError, "#{mod_cls} is not a valid Backport adapter" end end # @return [Mutex] attr_reader :mutex # Start the thread that checks the input IO for client data. # # @return [void] def run_input_thread Thread.new do read_input until stopped? end end # Read input from the client. # # @return [void] def read_input begin @in.flush chars = @in.sysread(255) rescue EOFError, IOError, Errno::ECONNRESET, Errno::ENOTSOCK chars = nil end if chars.nil? stop else mutex.synchronize { @buffer.concat chars } changed notify_observers self end end end end
true
449373ea1c2f64d8dc47f4734a80a0bf46e2e146
Ruby
matthu24/app_academy_projects
/W2D3/poker/spec/player_spec.rb
UTF-8
1,161
3.1875
3
[]
no_license
require 'player' require 'deck' require 'rspec' require 'byebug' RSpec.describe Player do # before(:each) do # deck = Deck.new # deck.shuffle! # end subject(:player) do deck = Deck.new deck.shuffle! x = Player.new(deck) end describe "#initalize" do it "initializes with empty hand" do expect(player.hand).to be_empty end it "references the deck class" do expect(player.deck).to be_an_instance_of(Deck) end end describe "#make_move" do end describe "#bet" do end describe "#fold" do # expect(player.hand).to be_empty end describe "#get_cards" do it "increases cards by its input" do player.get_cards(5) expect(player.hand.length).to eq(5) expect(player.deck.length).to eq(47) end end context "after cards are dealt" do subject(:player) do deck = Deck.new deck.shuffle! player = Player.new(deck) player.get_cards(5) player end describe "#discard!" do it "decreases number of cards by one" do player.discard!(3) expect(player.hand.length).to eq(4) end end end end
true
964bc0510d1fb5948c67fb4a56a4ea55211384bc
Ruby
sidharthanc/bridgemart
/spec/models/credit_purchase_spec.rb
UTF-8
1,982
2.515625
3
[]
no_license
describe CreditPurchase, type: :model do it { is_expected.to belong_to(:organization) } it { is_expected.to belong_to(:payment_method) } it { is_expected.to have_many(:credits) } it { is_expected.to allow_value(1.to_money).for(:amount) } it { is_expected.not_to allow_value(0.to_money).for(:amount) } it { is_expected.not_to allow_value(-1.to_money).for(:amount) } it { is_expected.to be_auditable } context '#paid?' do it 'is false when not paid' do expect(subject.paid?).to be_falsey end it 'is true when paid' do subject.paid! expect(subject.paid?).to be_truthy end end context '#void!' do before do subject.organization = organizations(:metova) subject.payment_method = payment_methods(:ach) subject.amount = 200 end it 'allows the unpaid credit purchase to be voided' do expect { subject.void! }.to change(subject, :voided_at).from(nil) end it 'disallows the paid credit purchase to be voided' do subject.paid! expect { subject.void! }.not_to change(CreditPurchase.find(subject.id), :voided_at) expect(subject.errors.details[:voided_at]).to include error: :cannot_void end end describe '#to_csv' do it 'returns a csv for a collection of credit purchases' do csv = described_class.all.to_csv described_class.all.each do |credit_purchase| record = [ credit_purchase.paid_at, credit_purchase.voided_at, credit_purchase.po_number, credit_purchase.error_message, credit_purchase.processing, credit_purchase.amount, credit_purchase.amount_currency, credit_purchase.organization_id, credit_purchase.payment_method_id, credit_purchase.created_at, credit_purchase.updated_at ].join(',') expect(csv).to include record expect(csv).not_to match /translation missing/ end end end end
true
b813a8e4d811cef03fa9916eb8db9bfa09a4dc9e
Ruby
inesgs12/ruby-objects-has-many-lab-london-web-career-042219
/lib/author.rb
UTF-8
979
3.703125
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require "pry" class Author @@posts = [] attr_accessor :name, :post def initialize(name) @name = name @posts = [] #has many posts - this is all that means end # def posts #we want to go over all the posts and see the ones that belong to this instance author # Posts.all.select {|posts| post.user == self} # end def posts Post.all.select{|post| post.author == self} end def add_post(post) @posts << post @@posts << post #we push the new post into the array of posts post.author = self #we are saying that the author of this post is the same of this class instance end def add_post_by_title(post) post = Post.new(post) #take the name of the post and this will create a new one @posts << post @@posts << post #and add it to the array that we initialized post.author = self #and the post's artist is the same as the instance we are on now. end def self.post_count @@posts.length end end # binding.pry
true
923b7eed6b7a8bc650402b58766d7441be59ad1b
Ruby
tkbeili/ruby-example
/ruby/hash_from_array.rb
UTF-8
216
3.375
3
[]
no_license
greetings = ["Hello", "Hi", "Hola", "Hey", "Yo"] results = {} greetings.each do |word| results[word.to_sym] = word.length end # another way results = Hash[greetings.map {|x| [x.to_sym, x.length] }] puts results
true
3b579c595c838a779bcebb73fcce93e1df4b8213
Ruby
elbohairy/project_oop
/mastermind.rb
UTF-8
3,300
4.15625
4
[]
no_license
# Things I could still do: # => error handling--there's very little of it # => improve AI: the Odin people seem to think the MasterMind rules involve # telling you if a specific color is in the correct order or not. That is wrong. # Hence writing the AI to know whether, based on the codemaker's response, a given # color is in the correct order is hard. # However, having the AI select the colors randomly, and then, once he gets a set # of four correct colors, rearranging them until he wins is somewhat straightforward, # and I could write that. class MasterMind attr_accessor :codemaker, :codebreaker, :board def initialize @codemaker = CodeMaker.new @codebreaker = CodeBreaker.new @board = Board.new end class CodeMaker attr_accessor :code, :initial_colors def initialize @initial_colors = ["white", "black", "red", "yellow", "blue", "orange", "purple", "green"] @code = @initial_colors.sample(4) end def correct_number?(guess) color_count = 0 unique_colors = guess.uniq unique_colors.each do |color| if @code.include? color color_count += 1 end end color_count end def correct_order?(guess) order_count = 0 guess.count.times do |i| if guess[i] == @code[i] order_count += 1 end end order_count end def reply(guess) if guess == @code true else color_count = correct_number?(guess) puts "You have correctly guessed #{color_count} color(s)." order_count = correct_order?(guess) puts "And #{order_count} of those colors are in the right order." false end end def create_code puts "Choose 4 distinct colors from the following list: #{@initial_colors.join(' ')}" @code = gets.chomp.split(' ') end end class CodeBreaker attr_accessor :guess, :color_options def initialize @guess = "" end def choice(color_list, ai) if ai ai_choice(color_list) else puts "What is your guess?" @guess = gets.chomp.split() end end def ai_choice(color_list) @guess = color_list.sample(4) puts guess.join(' ') @guess end end class Board attr_accessor :correct, :turns def initialize @correct = false @turns = 12 end end def play puts "Welcome to MasterMind!\nWould you like to be the CodeMaker, or the CodeBreaker?" user_response = gets.chomp.downcase ai = false if user_response == "codemaker" @codemaker.create_code ai = true end turn_counter = @board.turns until @board.correct or (turn_counter == 0) turn_counter -= 1 guess = @codebreaker.choice(@codemaker.initial_colors, ai) feedback = @codemaker.reply(guess) if feedback puts "You win!" @board.correct = true elsif turn_counter == 0 puts "You have used up all your turns!" else puts "You have #{turn_counter} turn(s) remaining." end end puts "Game over!" end end game1 = MasterMind.new game1.play
true
fb21b242afde4d25ce3f180834568a5096224d0e
Ruby
NicciSheets/tdd_methods
/string_tdd_methods.rb
UTF-8
404
3.5
4
[]
no_license
def concat_method(first_string, second_string) first_string.concat(second_string) #this is essentially just appending the second_string into the first_string, when calling upon this method end def concat_without_method(first_string, second_string) first_string << second_string #by appending the second_string into the first_string, we have returned the same as if we have used the concat method end
true
ddf4ee11dae80a93b179ea69621529f19406d7b2
Ruby
mendokusai/lotus01
/vendor/ruby/2.1.0/gems/lotus-helpers-0.2.0/lib/lotus/helpers/html_helper/empty_html_node.rb
UTF-8
1,371
2.734375
3
[ "MIT" ]
permissive
module Lotus module Helpers module HtmlHelper # Empty HTML node # # @since 0.1.0 # @api private class EmptyHtmlNode # Attributes separator # # @since 0.1.0 # @api private ATTRIBUTES_SEPARATOR = ' '.freeze # Initialize a new empty HTML node # # @param name [Symbol,String] the name of the tag # @param attributes [Hash,NilClass] the optional tag attributes # # @return [Lotus::Helpers::HtmlHelper::EmptyHtmlNode] # # @since 0.1.0 # @api private def initialize(name, attributes) @name = name @attributes = attributes end # Resolve and return the output # # @return [String] the output # # @since 0.1.0 # @api private def to_s %(<#{ @name }#{attributes}>) end private # Resolve the attributes # # @return [String,NilClass] the tag attributes # # @since 0.1.0 # @api private def attributes return if @attributes.nil? result = [nil] @attributes.each do |name, value| result << %(#{ name }="#{ value }") end result.join(ATTRIBUTES_SEPARATOR) end end end end end
true
b6e3db76fec18d6a0034436d2be4d82e57cae972
Ruby
resant18/cohort-resources
/foundations_remote/hacker_rank_quizzes/hacker_quiz_1/coding1.rb
UTF-8
417
4.1875
4
[]
no_license
# a prime number is a numebr that is only divisibly by 1 and itself. the smallest prime number is 2. Write a method prime? # that accepts a numebr as an argument and returns a boolean indication whether or not the given number is a prime # Examples p prime?(2) # => true p prime?(3) # => true p prime?(7) # => true p prime?(9) # => false p prime?(14) # => false p prime?(0) # => false p prime?(-7) # => false
true
ee1f4f34ae4f2a8c4899f3cd0db2c5f5251af37d
Ruby
railslauncher/clamd
/lib/clamd/configuration.rb
UTF-8
545
2.515625
3
[ "MIT" ]
permissive
module Clamd class Configuration attr_accessor :host, :port, :open_timeout, :read_timeout, :chunk_size ## # Default configuration for Clamd DEFAULTS = { host: 'localhost', port: 9321, open_timeout: 5, read_timeout: 30, chunk_size: 10240 } def initialize self.host = DEFAULTS[:host] self.port = DEFAULTS[:port] self.open_timeout = DEFAULTS[:open_timeout] self.read_timeout = DEFAULTS[:read_timeout] self.chunk_size = DEFAULTS[:chunk_size] end end end
true
ed4ccfa0eacf005b32f921ba318059ac3c9c89fe
Ruby
pheen/lemur_board
/app/services/websocket_minion.rb
UTF-8
1,378
2.71875
3
[]
no_license
require 'json' class WebSocketMinion class MinionError < StandardError; end def self.setup(open_sockets, ws, current_user) minion = WebSocketMinion.new(open_sockets, ws, current_user) minion.add_to_open_sockets minion.listen_to_socket minion.write_initial_data end def initialize(open_sockets, ws, current_user) @open_sockets = open_sockets @ws = ws @current_user = current_user end def add_to_open_sockets @open_sockets << @ws end def listen_to_socket @ws.on_message do |json| msg = JSON.parse(json) create_response_for(msg) and notify_open_sockets end end def write_initial_data @ws.write(initial_data.to_json) end private def create_response_for(msg) @response = if msg['issueChallenge'] challenge = Challenge.issue(msg['issueChallenge']) or raise MinionError, 'Failed to create challenge' { :new_challenge => challenge } elsif msg['acceptChallenge'] challenge = Challenge[msg['acceptChallenge']] challenge.set(:accepted, true) false end end def notify_open_sockets @open_sockets.each do |socket| socket.write(@response.to_json) end end def initial_data { current_user: @current_user.public_attributes, users: User.all_public_attributes, challenges: Challenge.all_public_attributes } end end
true
987eb6a68b3e54a41a0d723d01eb49c4ba1a5e8a
Ruby
tessneau/OO-Animal-Zoo-dumbo-web-051319
/lib/Animal.rb
UTF-8
625
3.390625
3
[]
no_license
class Animal attr_reader :species, :nickname attr_accessor :weight, :location @@all = [] #<--LOOK HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! def initialize(species, weight, nickname) @species = species @weight = weight @nickname = nickname @location= location @@all << self end def zoo # animal = Animal.new(species,weight,nickname) # @@all << animal # self.species.zoo self.location binding.pry end def self.all @@all end def self.find_by_species(species) Animal.all.select do |animal| animal.species == species end end end
true
fd640259cd36f044f48cbea18c5d85ec1fc6cf24
Ruby
nhorton04/W3D2
/skeleton/aa-questions/question_like.rb
UTF-8
3,122
2.59375
3
[]
no_license
require_relative 'links' class QuestionLike def self.find(id) question_like_data = QuestionsDatabase.instance.execute.get_first_row(<<-SQL, id: id) SELECT * FROM question_likes WHERE question_likes.id = :id SQL QuestionLike.new(question_likes_data) end def self.likers_for_question_id(question_id) users_data = QuestionsDatabase.instance.execute(<<-SQL, question_id: question_id) SELECT * FROM users JOIN question_likes ON users.id = question_likes.user_id WHERE question_likes.question_id = :question_id SQL users_data.map {|user_data| User.new(user_data)} end def self.num_likes_for_question_id(question_id) QuestionsDatabase.instance.execute(<<-SQL, question_id: question_id) SELECT COUNT(*) AS likes FROM questions JOIN question_likes ON questions.id = question_likes.question_id WHERE question_likes.question_id = :question_id -- questions.id = :question_id SQL end def self.liked_questions_for_user_id(user_id) QuestionsDatabase.instance.execute(<<-SQL, user_id: user_id) SELECT * FROM questions JOIN question_likes ON questions.id = question_likes.question_id WHERE question_likes.user_id = :user_id SQL questions_data.map { |question_data| Question.new(question_data) } end def self.all data = QuestionsDatabase.instance.execute(<<-SQL) SELECT * FROM question_likes SQL data.map { |datum| QuestionLike.new(datum) } end def save if @id QuestionsDatabase.instance.execute(<<-SQL, id: id, user_id: user_id, question_id: question_id) UPDATE question_likes SET id = :id, user_id = :user_id, question_id = :question_id WHERE question_likes.id = :id SQL else QuestionsDatabase.instance.execute(<<-SQL, id: id, user_id: user_id, question_id: question_id) INSERT INTO question_likes (id, user_id, question_id) VALUES (:id, :user_id, :question_id) SQL @id = QuestionsDatabase.last_insert_row_id end end def delete QuestionsDatabase.instance.execute(<<-SQL, id: id) DELETE FROM question_likes WHERE question_likes.id = :id SQL end def self.most_liked_questions(n) questions_data = QuestionsDatabase.instance.execute(<<-SQL, limit: n) SELECT questions.* FROM questions JOIN question_likes ON questions.id = question_likes.question_id GROUP BY questions.id ORDER BY COUNT (*) DESC LIMIT :limit SQL questions_data.map {|question_data| Question.new(question_data)} end attr_accessor :user_id, :question_id attr_reader :id def initialize(options) @id = options["id"] @question_id = options["question_id"] @user_id = options["user_id"] end end
true
b11cb0d59c7a6e3de6a68ce8cecc0694d796f780
Ruby
logicalproof/Isolation
/Items/Resources/Radioactive.rb
UTF-8
530
2.59375
3
[]
no_license
class Radioactive include Item include Resource attr_accessor :volatility, :decay, :energy def initialize(material_name, player) @name = material_name @overall_quality = get_attribute @volatility = get_attribute @decay = get_attribute @energy = get_attribute @property_list = {:overall_quality => overall_quality, :volatility => volatility, :decay => decay, :energy => energy} player.inventory[self.name] = self end end
true
310aea4f3b8c4a07b8d9fc8b1f5bface2b43cfba
Ruby
runningonfumes/playground
/app/domain/account.rb
UTF-8
2,012
2.546875
3
[]
no_license
class Account include Entity def initialize @balance = Balance.new end def self.create(attributes) account = self.new account.apply_event :account_created, attributes.merge(:uid => new_uid) account end def deposite(amount) self.should_exist new_balance = @balance.deposite(amount) apply_event :deposite, :amount => amount, :new_balance => new_balance.amount, :account_uid => uid end def send_transfer(target, amount) self.should_exist new_balance = @balance.withdraw(amount) apply_event :transfer_sent, :target_account_uid => target, :amount => amount, :new_balance => new_balance.amount, :account_uid => uid end def receive_transfer(source, amount) self.should_exist new_balance = @balance.deposite(amount) apply_event :transfer_received, :source_account_uid => source, :amount => amount, :new_balance => new_balance.amount, :account_uid => uid end def compensate_failed_transfer(amount) self.should_exist new_balance = @balance.deposite(amount) apply_event :failed_transfer_compensated, :amount => amount, :new_balance => new_balance.amount, :account_uid => uid end private def on_account_created(event) @uid = event.data[:uid] end def on_deposite(event) @balance = Balance.new(event.data[:new_balance]) end def on_transfer_sent(event) @balance = Balance.new(event.data[:new_balance]) end def on_transfer_received(event) @balance = Balance.new(event.data[:new_balance]) end def on_failed_transfer_compensated(event) @balance = Balance.new(event.data[:new_balance]) end end
true
47cf70d4283929a51b3c56156d6d545458fe4903
Ruby
cadebward/dynamic_form_test
/app/fields/integer_field.rb
UTF-8
462
2.828125
3
[]
no_license
class IntegerField < FormField def add_validation_errors(value) unless value.blank? || value.match(/\A[+-]?\d+\Z/) form_value.errors.add :value, 'must be an integer' end int_value = value.to_i if max.present? && int_value > max.to_i form_value.errors.add :value, "can't be greater than #{max}" end return unless min.present? && int_value < min.to_i form_value.errors.add :value, "can't be less than #{min}" end end
true
a04c3c7ce4794b5655da97097704d71da93a853c
Ruby
t-akazawa/ruby-book
/lib/deep_freeze.rb
UTF-8
112
2.65625
3
[]
no_license
module Kernel def deep_freeze(obj) obj = obj.map(&:freeze) if obj.class == Array obj.freeze end end
true
3f2d352aee85039a06fc08785772044431a0da7b
Ruby
lindsaymkelly/codewars
/comp_same.rb
UTF-8
2,457
4.4375
4
[]
no_license
# Given two arrays a and b write a function comp(a, b) (compSame(a, b) in Clojure) that checks whether the two arrays have the "same" elements, with the same multiplicities. "Same" means, here, that the elements in b are the elements in a squared, regardless of the order. # Examples # Valid arrays # a = [121, 144, 19, 161, 19, 144, 19, 11] # b = [121, 14641, 20736, 361, 25921, 361, 20736, 361] # comp(a, b) returns true because in b 121 is the square of 11, 14641 is the square of 121, 20736 the square of 144, 361 the square of 19, 25921 the square of 161, and so on. It gets obvious if we write b's elements in terms of squares: # a = [121, 144, 19, 161, 19, 144, 19, 11] # b = [11*11, 121*121, 144*144, 19*19, 161*161, 19*19, 144*144, 19*19] # Invalid arrays # If we change the first number to something else, comp may not return true anymore: # a = [121, 144, 19, 161, 19, 144, 19, 11] # b = [132, 14641, 20736, 361, 25921, 361, 20736, 361] # comp(a,b) returns false because in b 132 is not the square of any number of a. # a = [121, 144, 19, 161, 19, 144, 19, 11] # b = [121, 14641, 20736, 36100, 25921, 361, 20736, 361] # comp(a,b) returns false because in b 36100 is not the square of any number of a. # Remarks # a or b might be [] (all languages). a or b might be nil or null or None (except in Haskell, Elixir, C++, Rust). # If a or b are nil (or null or None), the problem doesn't make sense so return false. # If a or b are empty the result is evident by itself. # def comp(array1, array2) # status = true # if array1.nil? || array1.empty? || array2.nil? || array2.empty? # status = false # # elsif array2.nil? || array2.empty? # # status = false # else # array1.each do |num| # # if array2.include?(num*num) == false # # status = false # # end # status = false if !array2.include?(num*num) # end # end # status # end def comp(array1, array2) return false if array1.nil? || array2.nil? || array1.length != array2.length a = array1.sort b = array2.sort b.each_with_index do |value, i| if a[i]*a[i] != value return false end end return true end # test code a = [121, 144, 19, 161, 19, 144, 19, 11] b = [121, 14641, 20736, 361, 25921, 361, 20736, 361] c = [121, 144, 19, 161, 19, 144, 19, 11] d = [132, 14641, 20736, 361, 25921, 361, 20736, 361] e = [] f = nil p comp(a, b) p comp(c, d) p comp(e, d) p comp(c, d) p comp(f, c) p comp(c, f)
true
51d0f8f423e9d4c11d9d2e8d90ea63f5e4fa45b8
Ruby
Telixia/leetcode-3
/Medium/0916-Word Subsets/Solution.rb
UTF-8
454
3.453125
3
[]
no_license
# @param {String[]} a # @param {String[]} b # @return {String[]} def word_subsets(a, b) count = [0] * 26 b.each do |sub| count_ = count_chars(sub) (0...26).each do |i| count[i] = [count[i], count_[i]].max end end a.filter { |word| count_chars(word).zip(count).all? { |c| c[0] >= c[1] } } end # @param {String} s # @return {Integer[]} def count_chars(s) count = [0] * 26 s.each_byte { |c| count[c - 97] += 1 } count end
true
0b88a88d3723226bb69e34b0c7fc74fa6f2aaa8d
Ruby
GrahamBruce84/classes_homework
/sports_team.rb
UTF-8
679
3.59375
4
[]
no_license
class SportsTeam def initialize(team_name, players, coach) @team_name = team_name @players = players @coach = coach @points = 0 end def get_team_name() @team_name end def get_player_names() @players end def get_coach_name() @coach end def get_points() @points end def set_coach_name(name) @coach = name end def adding_new_player(name) @players << name end def check_player(name) for player in @players if player == name return true else return false end end end def has_team_won(result) if result == "win" @points += 1 end end end
true
55ecb0406616fb8c9f2c957e83b90bc048731bc2
Ruby
the-wendell/insurance_calc
/run.rb
UTF-8
1,327
2.609375
3
[]
no_license
# frozen_string_literal: true ENV['CALC_ENV'] = 'production' require 'optparse' require 'rubygems' require 'bundler/setup' require 'require_all' require_all 'lib' PERSONAL_LIABILITY = 'personal_liability' DENTAL = 'dental' VALID_INSURANCE_TYPES = [DENTAL, PERSONAL_LIABILITY].freeze def personal_liability opts = CLI::OptionBuilder.personal_liability_options policy = Calculators::PersonalLiability.new(opts[:zip_code], opts[:previous_insurance] == 'true') puts CLI::PolicyPrinter.new(policy).print exit end def dental opts = CLI::OptionBuilder.dental_options policy = Calculators::Dental.new(opts[:age].to_i, opts[:public_health_insurance] == 'true') puts CLI::PolicyPrinter.new(policy).print exit end def get_quote(type) return unless VALID_INSURANCE_TYPES.include?(type) send(type) end OptionParser.new do |opts| opts.on('-z zip_code', 'test') do |v| puts v end begin get_quote(ARGV[0]) rescue Exceptions::InsuranceNotPossible => e puts e.message exit end opts.on('-h', '--help', 'Prints this help') do puts <<~STR Valid insurance options are: #{VALID_INSURANCE_TYPES.join(', ')} To see required value inputs for a given type pass -h after the type name. ex: dental -h STR exit end puts 'non-supported insurance type' end.parse!
true
77ba61a3dd2b6c778b845c48648515e9e70eef2f
Ruby
mchll05/cc_w2d3_lab
/pub.rb
UTF-8
480
3.265625
3
[]
no_license
class Pub attr_reader :name, :till @@LEGAL_AGE = 18 def initialize(pub_name, till_total) @name = pub_name @till = till_total end def add_to_till drink_price = 5 @till += drink_price end def legal_drink_age?(customer) # legal_drink_age = 18 # @a_customer >= legal_drink_age customer.age >= @@LEGAL_AGE end def can_customer_drink_more?(customer) if customer.drunkeness <= 6 return "Another sir?" else return "GET OUT!" end end end
true
9dc6c55375b19d6a31d3b897ec33389fdc86b3af
Ruby
Giagnus64/cli-applications-guessing-game-dumbo-web-071519
/guessing_game_cli.rb
UTF-8
433
4.03125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Code your solution here! def run_guessing_game comp_number = generate_random_number user_number = capture_user_input if (comp_number == user_number.to_i) puts "You guessed the correct number!" elsif user_number == "exit" puts "Goodbye!" else puts "Sorry! The computer guessed #{comp_number}." end end def generate_random_number num = rand(6) + 1 end def capture_user_input user_guess = gets.chomp end
true
e02652d773a5d7c15ab05533f5878d4294cf2dd0
Ruby
O-I/marvel
/lib/marvel/error.rb
UTF-8
325
2.640625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module Marvel module Response class Error < StandardError attr_reader :code, :status def initialize(response_hash) @code = response_hash['code'] @status = response_hash['status'] || response_hash['message'] end def to_s "#{@code} #{@status}" end end end end
true
062aa2721d8d531237a3b5e035d6a2dd30e3843d
Ruby
leebardon/ruby-enumerables-reverse-each-word-lab-london-web-012720
/reverse_each_word.rb
UTF-8
113
3.359375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def reverse_each_word(sentence) array = sentence.split(' ') array.collect {|memo| memo.reverse}.join(' ') end
true
62fdc63b793caa2c4e3bba31d27ac32d18d94e0f
Ruby
HPInc/printos-box-api-samples
/ruby/box_api.rb
UTF-8
7,656
2.65625
3
[ "MIT" ]
permissive
# © Copyright 2016 HP Development Company, L.P. # SPDX-License-Identifier: MIT require 'json' require 'net/http' require 'openssl' require 'time' #access credentials $baseUrl = "https://printos.api.hp.com/box" #use for production account #$baseUrl = "https://stage.printos.api.hp.com/box" #use for staging account $key = "" #enter your PrintOS Key here $secret = "" #enter your PrintOS Secret here #amazon fetch and upload urls $amazon_fetch_url = "" $amazon_upload_url = "" $file_to_upload = "C:\\FilePath\\FileName.pdf" #Box APIs #--------------------------------------------------------------# # Creates a Folder in Box # # Param: # folder_name - name of the created folder # recipient - name of the receiver # sender - name of the sender def create_folder(folder_name, recipient, sender) puts "Creating folder: " + folder_name folder = {:name => folder_name, :to => recipient, :from => sender} data = JSON.generate(folder) response = request_post('/api/partner/folder', data) puts response.body end # Creates a folder with the given folder and recipient/sender information and # uploads the specified files into the newly created folder # # Params: # folder_name - Folder name # recipient - Name of recipient # sender - sender of the folder def create_folder_with_files(folder_name, recipient, sender) puts "Creating folder with files." data = { "name" => folder_name, "from" => sender, "to" => recipient, "files" => [{ "name" => "Ruby_File1.pdf", "copies" => 1, "notes" => "Ruby_File1 was uploaded using Ruby", "url" => "file_url1" }, { "name" => "Ruby_File2.pdf", "copies" => 1, "notes" => "Ruby_File2 was uploaded using Ruby", "url" => "file_url2" }] }.to_json() puts data response = request_post('/api/partner/folder', data) puts response.body end # Gets information about a file in Box. # # Param: # file_id - Id of the file def get_file(file_id) puts "Getting file: " + file_id response = request_get('/api/partner/file/' + file_id) puts response.body end # Gets flows set up within Box def get_flows() puts "Getting flows" response = request_get('/api/partner/flow') puts response.body end # Gets information about a folder in Box. # # Param: # file_id - Id of the folder def get_folder(folder_id) puts "Getting folder: " + folder_id response = request_get('/api/partner/folder/' + folder_id) puts response.body end # Gets the list of available substrates set in Box. def get_substrates() puts "Getting list of substrates." response = request_get('/api/partner/substrate') puts response.body end # Gets the amazon aws upload urls for a file. # # Param: # mime_type - MIME type of the file to upload def get_upload_urls(mime_type) puts "Getting aws urls for MIME type: " + mime_type response = request_get_with_param('/api/partner/file/uploadurls', mime_type) puts response.body end # Upload a file to a specified folder in Box. # # Param: # folder_id - Id of the folder to upload to # file_url - Url of the file to upload (not a local path) def upload_file(folder_id, file_url) puts "Uploading file: " + file_url + " to folder: " + folder_id file = { :url => file_url, :name => "Ruby_File.pdf", :notes => "This was uploaded using Ruby", :copies => 1, :folderId => folder_id, # :flow => "Flow ezName" # The flow value is either the easy submit name of the flow or the _id property from get_flows() } data = JSON.generate(file) response = request_post('/api/partner/file', data) puts response.body end # Upload a file to an amazon aws url. # # Param: # file_to_upload - local file to upload to amazon # content_type - MIME type of the file (should be the same as the mime_type used to get_upload_urls) def upload_file_to_aws(file_to_upload, content_type) puts "Uploading file: " + file_to_upload + " to aws" response = request_put(file_to_upload, content_type) puts response end #Helper functions #--------------------------------------------------------------# # Creates the HMAC header to authenticate the API calls. # # Param: # method - type of http method (GET, POST, PUT) # path - api path # timestamp - time in utc format def create_hmac_auth(method, path, timestamp) str = method + ' ' + path + timestamp; sha256 = OpenSSL::Digest.new('sha256') hash = OpenSSL::HMAC.hexdigest(sha256, $secret, str) return $key + ":" + hash end #GET, POST, and PUT #--------------------------------------------------------------# # HTTP GET request # # Param: # path - api path # # Note: baseUrl + path will be the full url to call a certain api def request_get(path) timestamp = Time.now.utc.iso8601 auth = create_hmac_auth("GET", path, timestamp) uri = URI($baseUrl + path) request = Net::HTTP::Get.new(uri) request.add_field("x-hp-hmac-authentication", auth) request.add_field("x-hp-hmac-date", timestamp) request.add_field("x-hp-hmac-algorithm", "SHA256") response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https', :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |http| http.request(request) end return response end # HTTP GET request with a mime_type parameter # # Param: # path - api path # param - MIME type to be added to the end of path # # Note: +baseUrl + path + param will be the full url to get the aws urls specific to the MIME type. def request_get_with_param(path, param) timestamp = Time.now.utc.iso8601 auth = create_hmac_auth("GET", path, timestamp) uri = URI($baseUrl + path + "?mimeType=" + param) request = Net::HTTP::Get.new(uri) request.add_field("x-hp-hmac-authentication", auth) request.add_field("x-hp-hmac-date", timestamp) request.add_field("x-hp-hmac-algorithm", "SHA256") response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https', :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |http| http.request(request) end end # HTTP POST request # # Param: # path - api path # data - json data to post # # Note: baseUrl + path will be the full url to call a certain api def request_post(path, data) timestamp = Time.now.utc.iso8601 auth = create_hmac_auth("POST", path, timestamp) uri = URI($baseUrl + path) request = Net::HTTP::Post.new(uri) request.add_field("Content-Type", "application/json") request.add_field("x-hp-hmac-authentication", auth) request.add_field("x-hp-hmac-date", timestamp) request.add_field("x-hp-hmac-algorithm", "SHA256") request.body = data response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https', :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |http| http.request(request) end return response end # HTTP PUT request # # Param: # file - local file to upload # content_type - MIME type of the local file (should match amazon upload urls) def request_put(file, content_type) uri = URI($amazon_upload_url) request = Net::HTTP::Put.new(uri) request.body_stream = File.open(file) request.add_field("Content-Type", content_type) request.add_field('Content-Length', File.size(file)) response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https', :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |http| http.request(request) end return response end #Function Calls #--------------------------------------------------------------# #create_folder("Ruby_Folder", "Ruby_Receiver", "Ruby_Sender") #create_folder_with_files("Ruby_Folder", "Ruby_Receiver", "Ruby_Sender") #get_folder("FolderId") get_substrates() get_flows() get_upload_urls("application/pdf") #upload_file_to_aws($file_to_upload, "application/pdf") #upload_file("FolderId", $amazon_fetch_url) #get_file("FileId")
true
4ca0e91aea3cf1600f388d85834e8848c5174aa3
Ruby
tamycova/30DaysHR
/RUBY/Day29/Solution1.rb
UTF-8
513
3.703125
4
[]
no_license
class TestReader def initialize inp @inp = inp end def each n_tests = @inp.readline.to_i while n_tests > 0 do n_tests -= 1 yield @inp.readline.strip end end end class FunnyTester def self.funny1? s, i (s[i].ord - s[i-1].ord).abs != (s[s.length-i].ord - s[s.length-i-1].ord).abs end def self.funny? s ((1..(s.length - 1)).find { |i| funny1? s, i }).nil? end end TestReader.new(STDIN).each do |s| puts (FunnyTester.funny? s) ? "Funny" : "Not Funny" end
true
b68181e7b59e78ff0931b90a5ef1a0ee3e925074
Ruby
DanMcDonald91/Code-Clan-Work
/week_2/day_1/specs/bank_accounts_spec.rb
UTF-8
767
2.953125
3
[]
no_license
# Bank Accounts Spec require ('minitest/autorun') require('minitest/rg') require_relative('../BankAccount.rb') class TestBankAccount < MiniTest::Test def test_account_name account = BankAccount.new('Dan' , 500, 'business') account_two =BankAccount.new('Andy' , 600, 'travel') account.account_name = ('Daniel') assert_equal('Daniel' , account.account_name) assert_equal('Andy' , account_two.account_name) end def test_pay_in_to_account account = BankAccount.new('Dan' , 500, 'business') account.pay_in(1000) assert_equal(1500, account.balance) end def test_monthly_fee_business account = BankAccount.new('Dan' , 500, 'business') account.pay_monthly_fee() assert_equal(450 , account.balance) end end
true
c19ec5dfd30f7c623013542d55a08017a864e465
Ruby
osamunmun/AOJ
/vol100/sort3num.rb~
UTF-8
71
2.578125
3
[]
no_license
#!/bin/ruby arr = gets arr.split.map(&:to_i) puts arr.sort.join(" ")
true
9df79a4ac59a9f4d6e6365817def18dec1ff864f
Ruby
cghiban/broccoli
/answer
UTF-8
1,532
2.828125
3
[]
no_license
#!/usr/bin/env ruby -w =begin rdoc Question answering script. Authors: Zach Paine (znp) Mattt Thompson (mattt) Owen Yamauchi (ody) Emilie McConville (emcconvi) =end # So we don't need a long nasty line on every require $: << File.join(File.dirname(__FILE__), '/lib') $:.concat(Dir.glob(File.join(File.dirname(__FILE__), '/vendor/*/lib'))) require 'easy_answer' require 'getoptlong' require 'logger' logdir = File.join(File.dirname(__FILE__), '/log') Dir.mkdir(logdir) unless File.directory?(logdir) $logger = Logger.new(File.join(File.dirname(__FILE__), '/log/' + Time.now.strftime("ask_%m%d%Y%H%M") + ".log")) usage = "#{$0} [--verbose] article_file questions_file" $VERBOSE = false opts = GetoptLong.new(['--verbose', '-v', GetoptLong::NO_ARGUMENT]) opts.each {|opt, arg| $VERBOSE = (opt == '--verbose')} if $VERBOSE $logger = Logger.new(STDERR) $logger = Logger.new(STDOUT) end if ARGV.length != 2 puts usage exit 0 end $logger.debug "Question Answerer Started" (article, questions_file) = ARGV if !File.exists?(article) or !File.exists?(questions_file) puts usage exit 0 end $logger.debug "Loading article text" article_text = '' File.open(article) do |file| article_text = file.read end File.open(questions_file) do |file| file.each_line do |line| $logger.debug "QUESTION: " + line.chomp answer = EasyAnswer.answer(line, article_text) if answer $logger.debug "ANSWER: " + answer unless $VERBOSE puts answer else puts "Couldn't answer this question!" end end end
true
b45723cc0faa4951ac670735b858a66ee53dfd8c
Ruby
CoherentLogic/ehmp20
/chef-repo/project_cookbooks/vista/providers/fileman.rb
UTF-8
8,082
2.6875
3
[ "Apache-2.0" ]
permissive
# # Cookbook Name:: vista # Resource:: fileman # # This provider uses greenletters and PTY to automate install prompts. This can cause odd character output to :log. # # .01 must be a field in field_values # If /.*:\/\// is encountered during input, it is assumed correct # action :create do chef_gem "greenletters" require "greenletters" ruby_block "fileman:#{new_resource.file}:#{new_resource.field_values.hash}" do block do begin shell = Greenletters::Process.new("sh", :transcript => new_resource.log, :timeout => node[:vista][:shell_timeout_seconds]) shell.on(:output, /STORE THESE FIELDS IN TEMPLATE:/) do | process, match | process.write("\r") end shell.on(:output, /Are you adding .+ as\s+a new .+ \(the .*\)\?/im) do | process, match | process.write("Yes\r") end # start the shell, set up cache environment and start cache shell shell.start! shell.wait_for(:output, /sh-[0-9\.]+#/) do | process, match | process.write("#{node[:vista][:session]}\n") end # Change namespace shell.wait_for(:output, /USER>/) do | process, match | process.write("ZN \"#{node[:vista][:namespace]}\"\n") end # Set user to administrator and setup programmer environment shell.wait_for(:output, /#{node[:vista][:prompt]}/) do | process, match | process.write("S DUZ=1 D ^XUP\n") end shell.wait_for(:output, /Select OPTION NAME:/) shell << "DIEDIT\r" shell.wait_for(:output, /INPUT TO WHAT FILE:/i) do | process, match | Chef::Log.debug("Selecting file: " + new_resource.file) process.write("#{new_resource.file}\r") end field_prompt_regex = /EDIT WHICH FIELD:/i new_resource.field_values.each_key do | field | shell.wait_for(:output, field_prompt_regex) do | process, match | process.write("#{field}\r") end field_prompt_regex = /THEN EDIT FIELD:/i end # Done adding fields to edit shell.wait_for(:output, field_prompt_regex) do | process, match | process.write("\r") end # If the prompt is a confirmation prompt, the provider will respond with \r # If the file being entered is not an existing file, that confirmation prompt # means we need to retry the current value (since we responded with \r, rather than the value) value_prompt_regex = /Select.+: $/i confirmation_prompt_regex = /:.+\/\//m ok_prompt_regex = /\.\.\.OK\? Yes\/\// index = 0 field_values_array = new_resource.field_values.to_a existing_entry = false while index < field_values_array.size field_value = field_values_array[index] Chef::Log.debug(index.to_s + ":" + field_value[0] + ":" + field_value[1]) do_retry = false shell.wait_for(:output, Regexp.union(confirmation_prompt_regex, value_prompt_regex, ok_prompt_regex)) do | process, match | if confirmation_prompt_regex =~ match[0] || ok_prompt_regex =~ match[0] Chef::Log.debug("Confirmation prompt matched: " + match[0].to_s) process.write("\r") if index == 1 # if confirmation was on second prompt, then it is an existing file, and every field will be have // Chef::Log.debug("Confirmation prompt; existing entry.") existing_entry = true process.write("\r") # we still need to advance the next prompt end unless existing_entry Chef::Log.debug("Confirmation prompt; retry needed") do_retry = true # if not first prompt, then it was a confirmation prompt, and we need to retry entering the field end else process.write("#{field_value[1]}\r") end end value_prompt_regex = /.+: $/ if do_retry == false # Using retry in a ruby_block causes: # DEBUG: Line number of compile error: '0' # DEBUG: Re-raising exception: TypeError - can't convert nil into String index += 1 end end # end while shell.wait_for(:output, /Select.+:/i) do | process, match | process.write("\r") end shell.wait_for(:output, /#{node[:vista][:prompt]}/) do | process, match | process.write("h\n") end shell.wait_for(:output, /sh-[0-9\.]+#/) do | process, match | process.write("exit\n") end shell.wait_for(:exit) rescue Exception Chef::Log.info("Timeout; killing shell.") Chef::Log.debug($ERROR_INFO) Chef::Log.debug($ERROR_POSITION) shell.kill! end end # block end # ruby_block end # end :create action :update do chef_gem "greenletters" require "greenletters" ruby_block "fileman:#{new_resource.file}:#{new_resource.field_values.hash}" do block do begin shell = Greenletters::Process.new("sh", :transcript => new_resource.log, :timeout => node[:vista][:shell_timeout_seconds]) # start the shell, set up cache environment and start cache shell shell.start! shell.wait_for(:output, /sh-[0-9\.]+#/) do | process, match | process.write("#{node[:vista][:session]}\n") end # Change namespace shell.wait_for(:output, /USER>/) do | process, match | process.write("ZN \"#{node[:vista][:namespace]}\"\n") end # Set user to administrator and setup programmer environment shell.wait_for(:output, /#{node[:vista][:prompt]}/) do | process, match | process.write("S DUZ=1 D ^XUP\n") end shell.wait_for(:output, /Select OPTION NAME:/) shell << "DIEDIT\r" shell.wait_for(:output, /INPUT TO WHAT FILE:/i) do | process, match | Chef::Log.debug("Selecting file: " + new_resource.file) process.write("#{new_resource.file}\r") end field_prompt_regex = /EDIT WHICH FIELD:/i new_resource.field_values.each_key do | field | shell.wait_for(:output, field_prompt_regex) do | process, match | process.write("#{field}\r") end field_prompt_regex = /THEN EDIT FIELD:/i end # Done adding fields to edit shell.wait_for(:output, field_prompt_regex) do | process, match | process.write("\r") end value_prompt_regex = /Select.+: $/i index = 0 field_values_array = new_resource.field_values.to_a while index < field_values_array.size field_value = field_values_array[index] Chef::Log.debug(index.to_s + ":" + field_value[0] + ":" + field_value[1][0]) field = field_value[0] escape=["/", ".", "^", "$"] #list of character to escape escape.each {|char| field= field.gsub(char,"\\#{char}")} edit_prompt_regex = /#{field}: .+/i do_retry = false shell.wait_for(:output, Regexp.union(value_prompt_regex,edit_prompt_regex)) do | process, match | if edit_prompt_regex =~ match[0] process.write("#{field_value[1][1]}\r") index += 1 else process.write("#{field_value[1][0]}\r") end end end # end while shell.wait_for(:output, /Select.+:/i) do | process, match | process.write("\r") end shell.wait_for(:output, /#{node[:vista][:prompt]}/) do | process, match | process.write("h\n") end shell.wait_for(:output, /sh-[0-9\.]+#/) do | process, match | process.write("exit\n") end shell.wait_for(:exit) rescue Exception Chef::Log.info("Timeout; killing shell.") Chef::Log.debug($ERROR_INFO) Chef::Log.debug($ERROR_POSITION) shell.kill! end end # block end # ruby_block end # end :update
true
d94dc4b66c5dcd1b14349b5edda10c7b15aaf66e
Ruby
johnscancella/scribeAPI
/lib/ocr_alto.rb
UTF-8
1,726
3.109375
3
[ "MIT" ]
permissive
require 'nokogiri' module OcrAlto MARGIN = 50 # box1 overlaps box2 def self.overlap(box1, box2) ! (box1[:hpos] + box1[:width] < box2[:hpos] || box1[:hpos] > box2[:hpos] + box2[:width] || box1[:vpos] + box1[:height] < box2[:vpos] || box1[:vpos] > box2[:vpos] + box2[:height]) end # box1 encloses box2 def self.enclose(box1, box2) box1[:hpos] - MARGIN <= box2[:hpos] && box1[:hpos] + box1[:width] + MARGIN >= box2[:hpos] + box2[:width] && box1[:vpos] - MARGIN <= box2[:vpos] && box1[:vpos] + box1[:height] + MARGIN >= box2[:vpos] + box2[:height] end # extract ORC text inside of box from the ALTO file # box should have keys such as hpos, vpos, width, height # values are normalized to image with width = 1 and height = 1 def self.extract_text_from_alto(alto_url, nbox) text = "" doc = Nokogiri::XML(open(alto_url)) # ALTO XMLs may have inconsistent namespaces doc.remove_namespaces! page = doc.xpath("//Page").first page_width = page['WIDTH'].to_i page_height = page['HEIGHT'].to_i box = { hpos: nbox[:hpos] * page_width, vpos: nbox[:vpos] * page_height, width: nbox[:width] * page_width, height: nbox[:height] * page_height, } doc.xpath("//TextBlock").each do |tb| if overlap({hpos:tb['HPOS'].to_f, vpos:tb['VPOS'].to_f, width:tb['WIDTH'].to_f, height:tb['HEIGHT'].to_f}, box) tb.xpath(".//String").each do |str| if enclose(box, {hpos: str['HPOS'].to_f, vpos: str['VPOS'].to_f, width: str['WIDTH'].to_f, height: str['HEIGHT'].to_f}) text << " " << str['CONTENT'] end end end text = text.strip text << "\n" end # doc.xpath("//TextBlock").each text.strip end end
true
19779899c12d9d8469045609b73ccb91802d7223
Ruby
EmilienMottet/exercism-sol
/ruby/matrix/matrix.rb
UTF-8
370
3.28125
3
[]
no_license
# frozen_string_literal: true # Matrix class Matrix def initialize(args) lines = args.each_line n = lines.count @matrix = Array.new(n) { Array.new(n) } lines.each_with_index do |line, i| line.split.each_with_index { |cell, j| @matrix[i][j] = cell.to_i } end end def rows @matrix end def columns @matrix.transpose end end
true
6f2dd9620ccee82aa9bf218caa71e70a517cca51
Ruby
janetmndz/immersive-module-one-mini-mock-challenge-dumbo-web-071519
/console.rb
UTF-8
638
2.90625
3
[]
no_license
require 'pry' require_relative './book' require_relative './author' jane = Author.new("Jane Austen") emily = Author.new("Emily Brontë") georgette = Author.new("Georgette Heyer") sense_and_sensibility = Book.new("Sense & Sensibility", jane, 119000) emma = Book.new("Emma", jane, 155000) pride_and_prejudice = Book.new("Pride & Prejudice", jane, 87000) wuthering_heights = Book.new("Wuthering Height", emily, 122000) april_lady = Book.new("April Lady", georgette, 87000) arabella = Book.new("Arabella", georgette, 98000) the_quiet_gent = Book.new("The Quiet Gentleman", georgette, 105000) sylvester = Book.new("Sylvester", georgette, 119000) binding.pry 0
true
277c8b98f84f627d9e4263549742ccf1b49679a3
Ruby
tormaroe/fortholito
/fortholito/lexer.rb
UTF-8
1,567
3.03125
3
[]
no_license
module Fortholito TYPE_STRING = :string TYPE_FLOAT = :float TYPE_INT = :int TYPE_WORD = :word Token = Struct.new(:text, :type) do def is_word? word self.type == TYPE_WORD and self.text.chomp.strip == word end end class Lexer attr_reader :tokens def initialize source @source = source @tokens = [] @tokenizers = { /\A\"(?:[^\"\\]*(?:\\.[^\"\\]*)*)\"/ => TYPE_STRING, /\A\([^\(\)]*\)/ => :whitespace, # comment /\A(?:\-){0,1}\d+\.\d+(?:$|[ \n]+)/ => TYPE_FLOAT, /\A(?:\-){0,1}\d+(?:$|[ \n]+)/ => TYPE_INT, /\A\\ .*\n+/ => :whitespace, # comment /\A\\ .*$/ => :whitespace, # comment /\A[^ \n]+/ => TYPE_WORD, /\A\n+/ => :whitespace, /\A +/ => :whitespace } end def tokenize next_token while @source.length > 0 end def next_token @tokenizers.each do |regex, type| match = @source.scan regex if match.size > 0 consume_token match, type return end end fail_lexer end def consume_token match, type @tokens.push Token.new match[0], type unless type == :whitespace @source = @source[match[0].length..-1] end def fail_lexer raise "Unrecognized token at #{@source.inspect}" end end end
true
d75e1d5a4ea17e0ac8c29ce042e29ac337af9e67
Ruby
BrycenGit/rock_paper_scissors
/spec/rock_paper_spec.rb
UTF-8
694
2.8125
3
[ "MIT" ]
permissive
require('rspec') require('rock_paper') describe("RPS#rock_paper") do it("returns 'win' if rock is the object and scissors is the argument") do game = RPS.new() expect(game.win("rock", "scissors")).to(eq('win')) end it("returns 'win' if paper is the object and rock is the argument") do game = RPS.new() expect(game.win("paper", "rock")).to(eq('win')) end it("returns 'lose' if rock is the object and paper is the argument") do game = RPS.new() expect(game.win("rock", "paper")).to(eq('lose')) end it("returns 'draw' if rock is the object and rock is the argument") do game = RPS.new() expect(game.win("rock", "rock")).to(eq('draw')) end end
true
0e45582d0363c33867e7d72a2728c6e9424e0be5
Ruby
InsanityRadio/libatem
/examples/vision_mixer.rb
UTF-8
1,841
2.671875
3
[]
no_license
#!/bin/env ruby $AUDIO_THRESHOLD = 858803 $IP = "10.32.0.119" require_relative '../lib/atem' class VisionMixer attr_accessor :close, :wide def initialize ip, close, wide, slate @ip = ip @close = close @wide = wide @current_camera = wide[0] connect! @close.map! { | w | @atem.inputs[w] } @wide.map! { | w | @atem.inputs[w] } @slate = @atem.inputs[slate] sleep 5 loop do select_camera sleep 2 # Make the camera live then start immediately gathering data again live_camera reset_peaks sleep 5 end end def connect! @atem = ATEM.connect(@ip) @atem.use_audio_levels = true @atem.inputs[@current_camera].program end def select_camera begin if @break @new_camera = @slate raise "Done" end if @wide.include? @current_camera if Random.rand(3) == 0 @new_camera = @wide.sample raise "Done" end highest = [nil, $AUDIO_THRESHOLD] @close.each do | cam | highest = [cam, cam.audio.levels[:peak_left]] if cam.audio.levels[:peak_left] > highest[1] end if highest != nil @new_camera = highest[0] raise "Done" end end if @close.include? @current_camera if Random.rand(3) == 0 @new_camera = @wide.sample raise "Done" end @new_camera = @close.sample raise "Done" end @new_camera = @wide.sample rescue end debug "Selected camera #{@new_camera.name}" @new_camera.preview end def live_camera debug "#{@new_camera.name} is live" @new_camera.program @current_camera = @new_camera end def reset_peaks @atem.reset_audio_peaks end private def info message puts "[ INFO ] #{message}" end def debug message puts "[ DEBUG ] #{message}" if $debug end end $debug = true VisionMixer.new $IP, ['Pres', 'Gst'], ['Wide'], 'MP1'
true
dd368198d39861e8598e721a3564cc83cb43c871
Ruby
uesteibar/Ironhack-week-2
/1-monday/3-online-calculator/lib/storage/memory_handler.rb
UTF-8
211
3.0625
3
[]
no_license
class MemoryHandler def initialize(storage_provider) @storage_provider = storage_provider end def get @storage_provider.get end def put(number) @storage_provider.put(number) end end
true
6cfc8a066089fdcce25232299a2bacfc644555aa
Ruby
mnhollandplum/black_thursday
/lib/invoice.rb
UTF-8
608
2.8125
3
[]
no_license
class Invoice attr_reader :id, :customer_id, :merchant_id, :created_at attr_accessor :status, :updated_at def initialize(data) @id = data[:id].to_i @customer_id = data[:customer_id].to_i @merchant_id = data[:merchant_id].to_i @status = data[:status].to_sym @created_at = data[:created_at].to_s @updated_at = data[:updated_at].to_s end def created_at if @created_at != nil Time.parse(@created_at) end end def updated_at if @updated_at != nil Time.parse(@updated_at) end end end
true
79c6f9587d98673c7ebbfef8e2b64fa869078d34
Ruby
devarora567/basic_ruby_exercise
/reverse_sentence_words/bin/main.rb
UTF-8
93
2.765625
3
[]
no_license
require_relative '../lib/string' puts "Enter the sentence" puts gets.chomp.reverse_sentence
true
a5bcf1a6bedfc954d649a9009e98fc212fd0bc0c
Ruby
tygerbytes/runby-pace
/lib/runby_pace/run_types/tempo_run.rb
UTF-8
1,922
2.953125
3
[ "MIT" ]
permissive
# frozen_string_literal: true module Runby module RunTypes # Combines the fast and slow tempo runs into one convenient range of paces class TempoRun < RunType attr_reader :slow_pace_calculator, :fast_pace_calculator def description 'Tempo Run' end def explanation 'Ran at a comfortably hard pace that you could maintain for about an hour, if pressed. However, tempo runs are interval workouts, so you won\'t run for longer than 15-40 minutes per repetition' end def initialize @fast_pace_calculator = PaceCalculator.new(GoldenPaces.fast, 4.025) @slow_pace_calculator = PaceCalculator.new(GoldenPaces.slow, 3.725) end def lookup_pace(five_k_time, distance_units = :km) fast = @fast_pace_calculator.calc(five_k_time, distance_units) slow = @slow_pace_calculator.calc(five_k_time, distance_units) PaceRange.new(fast, slow) end # Used in testing, contains hashes mapping 5K race times with the recommended pace-per-km for this run type. class GoldenPaces def self.fast GoldenPaceSet.new('14:00': '03:07', '15:00': '03:20', '20:00': '04:21', '25:00': '05:20', '30:00': '06:19', '35:00': '07:16', '40:00': '08:12', '42:00': '08:35') end def self.slow GoldenPaceSet.new('14:00': '03:18', '15:00': '03:31', '20:00': '04:35', '25:00': '05:37', '30:00': '06:38', '35:00': '07:38', '40:00': '08:36', '42:00': '08:59') end end end end end
true
3f3ea9fdb49dcff816e823354a5dc18bc73d3640
Ruby
concow/my-collect-online-web-sp-000
/lib/my_collect.rb
UTF-8
549
3.859375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def my_collect(collection) i = 0 #initialize counter new_collection = [] #declare new array for later while i < collection.length #condition: while there is a filled array (technically our iterator) new_collection << yield(collection[i]) #[] method to grab each successive index value as we go thru loop. Then push the return value of yielded array into our new_collection array i += 1 #update counter end return new_collection #return our new array end
true
7834d05e4a03539ed1da1e4f71aa93894bebb177
Ruby
mcruger/HW2office_directory
/edit_list.rb
UTF-8
3,925
3.53125
4
[]
no_license
#1. The program takes one parameter: the bucket name for the office directory #2. It displays the cities as a numbered list and accepts appropriate numbers as input #3. It displays the employees in the selected city in a numbered list and accepts appropriate numbers as input. #4. It requests the name, office location and phone extension for the selected employee. #5. It updates the csv file and the appropriate city HTML page. #set configs #require File.expand_path(File.dirname(__FILE__) + '/proj_config') require "./s3utility" require "./office_directory_utility.rb" #check intput bucket_name = ARGV[0] unless bucket_name puts "Usage: edit_list.rb <BUCKET_NAME>" exit 1 end csv_file = "office_dir.csv" #get .csv file from bucket get_file_from_bucket(bucket_name, csv_file) #read in csv file employeeHash = read_in_csv("input.csv") #hardcoded for now, needs to find a csv file using_prog = true while using_prog == true do #output list of cities to user city_count = 1 new_emp = false puts "" puts "Enter the number for the city you want to edit, 'save' to save your changes, or 'quit' to exit." puts "" puts "0. Add New Employee" employeeHash.keys.each do |city| puts "#{city_count}. #{city}" city_count += 1 end puts "" #capture user input mod_city = STDIN.gets.chomp if mod_city == "save" #generate html pages and push to bucket gen_html_push_to_bucket(employeeHash, bucket_name) puts "" puts "Changes saved and office directory updated!" puts "" next elsif mod_city == "quit" puts "Any unsaved changes will be lost. Are you sure you want to quit?" puts "[Y/y] to quit." mod_in = STDIN.gets.chomp if mod_in.downcase == "y" puts "Goodbye!" using_prog = false break else next end elsif mod_city.to_i < 0 or mod_city.to_i > employeeHash.keys.count or mod_city.to_i.to_s != mod_city puts "Invalid entry!" puts "" next else if mod_city.to_i == 0 new_emp = true end if new_emp == false #show employees for selected city. Note that I'm subtracting 1 from mod_city b/c it isn't 0 based. no_emps = false emp_count = 1 if employeeHash.values[mod_city.to_i - 1].empty? no_emps = true puts "No Employees at this office!" puts "0. Back to Main Menu" puts "1. Enter New Employee" else puts "Enter the number for the employee you want to edit" puts "0. Back to Main Menu" employeeHash.values[mod_city.to_i - 1].each do |employee| puts "#{emp_count}. #{employee}" emp_count += 1 end end #capture user input mod_emp = STDIN.gets.chomp #kick back to main menu if 0 is entered if mod_emp == "0" next end #check for new employee option on empty offices if no_emps and mod_emp == "1" new_emp = true end end if new_emp #get updated employee details puts "You are adding a new employee.." else emp_city = employeeHash.keys[mod_city.to_i - 1] emp_name = employeeHash.values[mod_city.to_i - 1][mod_emp.to_i - 1][0] emp_ext = employeeHash.values[mod_city.to_i - 1][mod_emp.to_i - 1][1] #get updated employee details puts "You are editing #{emp_city}, #{emp_name}, #{emp_ext}" end puts "Please enter Office employee is located at..." mod_emp_city = STDIN.gets.chomp puts "Please enter employee Name..." mod_emp_name = STDIN.gets.chomp puts "Enter employee Extension..." mod_emp_extension = STDIN.gets.chomp #city move, need to move employee to a new city #check to see if city exists. create new one if it doesn't if !employeeHash.key?(mod_emp_city) employeeHash[mod_emp_city]=[] end puts mod_city #insert new record and remove one employeeHash[mod_emp_city].push [mod_emp_name, mod_emp_extension] if new_emp == false employeeHash.values[mod_city.to_i - 1].delete_at(mod_emp.to_i - 1) end puts "" puts "Record updated, remember to save your changes." puts "" end end
true
d2d6e6709405278dc744f6ae236dbe0d0e1db602
Ruby
thekindofme/price_grabber
/parsers/memory_lk_parser.rb
UTF-8
1,593
2.734375
3
[ "MIT" ]
permissive
require 'rubygems' require 'mechanize' module LPriceGrabber class MemoryLK < Parser def categories categories = [] WWW::Mechanize.new.get('http://shop.memory.lk').search("/html/body/div/table/tr[2]/td/table/tr[2]/td[2]/table//a").each do |link| if link['href'].include? 'category-list-' #there are some other unneeded stuff coming up... so this is to filter those out c = Category.new c.name = link.text.gsub(/\t|\n|\r/, ' ').strip.squeeze(" ") c.url = "http://shop.memory.lk/#{link['href']}" categories << c end end categories end =begin Parse TechWareHouse for products and their attributes and will return a array of Product objects. =end def parse products = [] agent = WWW::Mechanize.new self.categories.each do |category| page = agent.get category.url page.search("//table[@width=175]").each do |table| p = Product.new p.name = table.children[1].children[0].text p.price = table.children[3].children[2].text p.model = table.children[4].children[0].text str = table.children[5].text.gsub(/\n|\t|'/, '').strip.squeeze(" ") #this position can hold the warranty info or description if str.include? 'Warranty' p.warranty = str else p.description = str p.warranty = table.children[6].text.gsub(/\n|\t|'/, '').strip.squeeze(" ") end p.tag = category.name products << p end end products end end end
true
af699ea72dcfa657834cc0c2a07e8e239be49d9f
Ruby
kenta-s/code-snippets
/ruby/post_json_to_external_url.rb
UTF-8
376
2.796875
3
[]
no_license
require 'net/https' # example: # post_json_to_external_url("http://example.com", {text: "hello"}.to_json) def post_json_to_external_url(url, payload) uri = URI.parse(url) https = Net::HTTP.new(uri.host, uri.port) https.use_ssl = true req = Net::HTTP::Post.new(uri.request_uri) req["Content-Type"] = "application/json" req.body = payload https.request(req) end
true
23666789dc5e8adcc1cd5cd0848589f53d1b67d8
Ruby
ceh522/static_and_dynamic_testing_pda
/Static_and_Dynamic/spec/test.rb
UTF-8
861
2.84375
3
[]
no_license
require('minitest/autorun') require('minitest/reporters') Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new require_relative('../card.rb') require_relative('../card_game.rb') class CardGameTest < Minitest::Test def setup @card1 = Card.new("clubs", 4) @card2 = Card.new("spades", 1) @cards = [@card1, @card2] @card_game = CardGame.new(@cards) end def test_card_game_has_cards assert_equal(2, @card_game.cards.count) end def test_can_get_cards assert_equal([@card1, @card2], @card_game.cards) end def test_can_check_cards_for_ace cards = @card_game.cards assert_equal(true, @card_game.check_for_Ace(@cards)) end def test_can_identify_highest_card assert_equal(@card1, @card_game.highest_card(@card1, @card2)) end def test_can_get_total_value_of_cards assert_equal("You have a total of 5", @card_game.cards_total(@cards)) end end
true
a31d2802cfb20f3c8edce394847313df0113dbd5
Ruby
alexiscarlier/pdf-generator
/run.rb
UTF-8
488
2.703125
3
[]
no_license
require "prawn" require "./lib/pdf_renderer.rb" require "./lib/text_arranger" text = '.large .bold My First Document .italic .normal .paragraph This is my .large very first .regular .large .paragraph By Alexis Carlier :)' text_arranger = TextArranger.new(text) text_arranger.separate text_arranger.get_string_indexes arranged_text = text_arranger.get_arranged_text pdf = Prawn::Document.new pdf_renderer = PdfRenderer.new(arranged_text, pdf) pdf_renderer.apply_formatting pdf_renderer.render
true
0fb76b4af76b4c318ec291fe0c886555ce4325a6
Ruby
tan-wei/expectr
/lib/expectr/lambda.rb
UTF-8
3,501
3.15625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
require 'expectr' require 'expectr/interface' class Expectr # Public: The Expectr::Lambda Module defines the interface for interacting # with Proc objects in a manner which is similar to interacting with # processes. module Lambda include Expectr::Interface # Public: Initialize the Expectr Lambda interface. # # args - Hash containing Proc objects to act as reader and writer: # reader - Lambda which is meant to be interacted with as if it were # analogous to STDIN for a child process. # writer - Lambda which is meant to be interacted with as if it were # analogous to STDOUT for a child process. # # Raises TypeError if arguments aren't of type Proc. def init_interface(args) unless args[:reader].kind_of?(Proc) && args[:writer].kind_of?(Proc) raise(TypeError, Errstr::PROC_EXPECTED) end @pid = -1 @reader = args[:reader] @writer = args[:writer] end # Public: Present a streamlined interface to create a new Expectr instance. # # reader - Lambda which is meant to be interacted with as if it were # analogous to STDIN for a child process. # writer - Lambda which is meant to be interacted with as if it were # analogous to STDOUT for a child process. # args - A Hash used to specify options for the new object, per # Expectr#initialize. # # Returns a new Expectr object def self.spawn(reader, writer, args = {}) args[:interface] = :lambda args[:reader] = reader args[:writer] = writer Expectr.new(args) end # Public: Send input to the reader Proc. # # args - Arguments to pass to the reader interface. # # Returns nothing. def send(args) @reader.call(*args) end # Public: Prepare the operating environment for interact mode, set the # interact flag to true. # # Returns a Hash containing old signal handlers and tty parameters. def prepare_interact_environment env = {sig: {}} # Save old tty settings and set up the new environment env[:tty] = `stty -g` `stty -icanon min 1 time 0 -echo` # SIGINT should be sent to the child as \C-c env[:sig]['INT'] = trap 'INT' do send "\C-c" end # SIGTSTP should be sent to the process as \C-z env[:sig]['TSTP'] = trap 'TSTP' do send "\C-z" end @interact = true env end # Public: Create a Thread containing the loop which is responsible for # handling input from the user in interact mode. # # Returns a Thread containing the running loop. def interact_thread Thread.new do env = prepare_interact_environment input = '' while @interact if select([$stdin], nil, nil, 1) c = $stdin.getc.chr send c unless c.nil? end end restore_environment(env) end end private # Internal: Call the writer lambda, reading the output produced, forcing # UTF-8, appending to the internal buffer and printing to $stdout if # appropriate. # # Returns nothing. def output_loop buf = '' loop do buf.clear begin buf << @writer.call.to_s rescue Errno::EIO # Lambda is signaling that execution should end. return end process_output(buf) end end end end
true
bdfb16e69558111c53ca049f3ba0074a00c3b82e
Ruby
fayvera/student-hall
/app/models/student.rb
UTF-8
393
2.59375
3
[ "CC0-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class Student < ActiveRecord::Base has_secure_password has_many :posts has_many :student_courses has_many :courses, through: :student_courses validates_uniqueness_of(:email) def slug name = first_name + last_name name.downcase.gsub(" ", "-") end def self.find_by_slug(slug) Student.all.find{|student| student.slug == slug} end end
true
ba207df55696dcc97cb5b3823d3e0264a80b9458
Ruby
berkos/git-analyzer
/lib/git_analyzer.rb
UTF-8
1,095
2.71875
3
[ "MIT" ]
permissive
require_relative 'git_analyzer/formatter/csv' require_relative 'git_analyzer/formatter/pretty' require_relative 'git_analyzer/version' require 'date' require 'pry' module GitAnalyzer class << self def contributors(period: nil) since = generate_since_day(period) result = `git shortlog -sne#{" --since='#{since}'" unless period.nil?}` # No commits return [] if result == "" result = result.scan(/(\d+)\t(.+)\<(.+)\>/) total_commits = result.inject(0) { |sum, el| sum + el[0].to_i } result.map do |array| { commits: array[0].to_i, # floor(n) is not available in Ruby < 2.3, multiply by 10000 and then divide by 100 to keep to decimals contribution_percentage: (array.shift.to_f / total_commits * 10_000).floor.to_f / 100, name: array.shift.strip, email: array.shift } end end private def generate_since_day(period) case period when :last_week DateTime.now - 7 when :last_month DateTime.now << 1 end end end end
true
6239e6bd50d4deaf707524f23cdfb146d775cbe4
Ruby
andrewlegend/Calculator
/methods/temperature.rb
UTF-8
123
3.375
3
[]
no_license
def c_to_f(number) puts (number*9)/5+32 end c_to_f(21) def f_to_c(number) puts (number-32)*5+32 end f_to_c(15)
true
b24530108ec790672fb899d17c2b818a664a59f5
Ruby
kevinvaldek/myspeechtime
/test/speech_test.rb
UTF-8
410
2.734375
3
[]
no_license
require 'test/helper' class SpeechTest < ActiveSupport::TestCase context "words" do setup do @speech = MySpeechTime::Speech.new("I am not a talker.") end should "split the text to an array of the words" do assert_equal %w(I am not a talker.), @speech.words end should "have the length of the total words" do assert_equal 5, @speech.words.length end end end
true
fb78089d64f2c1f0b1b14636fb03a1a7f6e32bf6
Ruby
arnaldoaparicio/flash_cards
/lib/round.rb
UTF-8
1,542
4.1875
4
[]
no_license
require './lib/card' require './lib/turn' require './lib/deck' class Round attr_reader :deck, :turns, :percent, :correct_category def initialize(deck) @deck = deck @turns = [] @percent = percent @correct_category = correct_category end # Returns the first element def current_card @deck.cards[0] end # Will create a new instance of Turn with the guess as an argument # It will then take the turn instance and place it in an array # def take_turn(guess) turn = Turn.new(guess, @deck.cards[0]) @turns << turn @deck.cards.shift #deck @turns.last end def number_correct #This will grab all elements in array and see if they are correct #Any element that is correct, will be counted @turns.select { |c| c.correct? == true}.count end def percent_correct @percent = @turns.select { |c| c.correct? == true}.count.to_f / @turns.count @percent * 100 end def number_correct_by_category(corr) @correct_category = @turns.select { |corr_turn| corr_turn.correct? == true} @correct_category.select {|correct| correct.card.category == corr}.count end def turns_correct_by_category(cat) count = 0 @turns.select do |turn| if turn.card.category == cat count += 1 end end count end def percent_correct_by_category(percent_corr) number_correct num = number_correct_by_category(percent_corr).to_f den = turns_correct_by_category(percent_corr) result = (num / den) * 100 result.round end end
true
91d09effb517c351d77a80a2fb1a1976886271a1
Ruby
Njunu-sk/Ruby
/advancedloop.rb
UTF-8
218
3.046875
3
[]
no_license
arr = ["simon","paul","mark"] for employee in arr puts "Cityright llc employee :#{employee}" end puts "-----------------------------" arr.each do |employee| print "Cityright llc employee :#{employee}" end
true
968f99f5218794ebf89df6ddef2042b7d8722d64
Ruby
JoshCheek/javascript_interpreter
/lib/js_simulated_blocking/stdlib.rb
UTF-8
1,368
3.1875
3
[]
no_license
require 'js_simulated_blocking/env' require 'js_simulated_blocking/data_structures' class JsSimulatedBlocking class Stdlib # uhm, what is the toplevel object? pretty sure these vars should be strored there instead of in the env def self.global(stdout:, time:, env: env) env.declare(:console, console(env: env, stdout: stdout)) .declare(:Date, Date(env: env, time: time)) end def self.console(env:, stdout:) console = env.new_object console[:log] = env.new_internal_function name: 'console.log'.freeze do |fn_call| stdout.puts(fn_call.arguments.join ' ') end console end def self.Date(env:, time:) date = env.new_internal_function name: 'Date'.freeze do |fn_call| fn_call.this.set_internal time: time.now end date.prototype[:toString] = env.new_internal_function name: 'Date.toString'.freeze do |fn_call| # get_internal is undefined for nil... so this fn call was invoked on nil, # but should have been the date: # # new Date().toString() # # so probably the instructions we generate need to be smarter so that # the function gets bound to the obj its called on? ruby_time = fn_call.this.get_internal(:time) ruby_time.strftime "FIXME! %Y%Y%Y%Y%Y" end date end end end
true
f470f0c86426ab7eae49559ee1e539a7589edd2d
Ruby
joshuabowers/opium
/lib/opium/extensions/string.rb
UTF-8
446
2.953125
3
[ "MIT" ]
permissive
class ::String def to_bool return true if self == true || self =~ (/^(true|t|yes|y|1)$/i) return false if self == false || self.blank? || self =~ (/^(false|f|no|n|0)$/i) raise ArgumentError.new("invalid value for Boolean: \"#{self}\"") end def to_geo_point Opium::GeoPoint.new( self ) end class << self def to_ruby(object) object.to_s if object end alias_method :to_parse, :to_ruby end end
true
344b6898a81f9cd140e7f492c4bb3432a0c5a2b4
Ruby
alexventuraio/vending-machine
/lib/catalog.rb
UTF-8
115
2.546875
3
[]
no_license
class Catalog attr_reader :products def initialize(initial_catalog = []) @products = initial_catalog end end
true
f5a9eff108ef79d89b862985979b9817213513e7
Ruby
jjmora/tests-ruby
/lib/05_timer.rb
UTF-8
532
3.5625
4
[]
no_license
def time_string(s) # Cuantas veces hay 3600 = 1 h # cuantas veces hay 60 = 1 min # el resto son segundos h = 0 while s > 3600 s = s-3600 h += 1 end m = 0 while s > 60 s = s - 60 m += 1 end if h < 10 h = "0#{h}" else h ="#{h}" end if m < 10 m = "0#{m}" else m ="#{m}" end if s < 10 s = "0#{s}" else s ="#{s}" end return "#{h}:#{m}:#{s}" end #p time_string(6586)
true
b3049cd5a9bb5f399905ad5fea6a37f943dcae08
Ruby
le3ah/thirsty_plants
/app/models/day.rb
UTF-8
1,417
2.671875
3
[]
no_license
class Day def self.generate_days(args) days_ago = args[:days_ago] || 0 days_from_now = args[:days_from_now] || 7 user = args[:user] ((0 - days_ago) .. days_from_now).map do |i| Day.new(Date.parse(i.days.from_now.localtime.to_s), user) end end def initialize(date, user = nil) @date = date @user = user end def day_of_week_name @date.strftime('%A') end def css_classes class_names = 'row' class_names += ' past-day collapsible' if (@date < Date.today) class_names += ' future-day' if (@date > Date.today) class_names end def css_name @date.strftime('%b%d_%Y') end def css_id 'today' if @date.day == Time.now.day end def small_date @date.strftime('%b. %d') end def waterings Watering.joins(plant: {garden: :user_gardens}) .where(water_time: @date.beginning_of_day... @date.end_of_day) .where(plant: { garden: { user_gardens: {user: @user} } } ) end def gardens Garden.joins({plants: :waterings}, :user_gardens) .where(plants: { waterings: {water_time: @date.beginning_of_day... @date.end_of_day }}) .where(user_gardens: {user: @user}) .includes({plants: :waterings}, :user_gardens) end def waterings? waterings.any? end def check_box_type if @date.day == Time.now.day "enabled-checkbox" else "disabled-checkbox" end end end
true
2be366f11c7841114d277092f4382739ad67d277
Ruby
esparratacus/vizeer
/app/controllers/schedules_controller.rb
UTF-8
1,946
2.609375
3
[]
no_license
# Clase encargada de controlar las acciones de objetos de tipo Schedule entre la base de datos y la vista class SchedulesController < ApplicationController #Define los parámetros que son alterables por el controlador def schedule_params params.require(:schedule).permit(:id,:user_id,:dia_semana, :hora_inicio, :hora_fin) end # Método que accede a los registros de de tipo Schedule del consejero # * *Resultado* : # - Lista de objetos de tipo Schedule almacenado en la variable @horarios def index @horarios= Schedule.where :user_id => current_user.id end # CU016-R02 # Método que prepara el objeto de tipo Schedule para crearlo # * *Resultado* : # - Asigna a un objeto de tipo Schedule vacío a la variable @horario def new @dias =['lunes','martes','miercoles','jueves','viernes'] @horario=Schedule.new end # CU016-R02 # Método que agrega un objeto de tipo Schedule a la base de datos # * *Parámetros* : # - +user_params+ -> hash con la información del objeto de tipo Schedule # * *Resultado* : # - Un nuevo horario de tipo Schedule se guarda como registro en la base de datos def create @horario = Schedule.new(schedule_params) @horario.user_id=current_user.id puts "PARAMETROS------------------" puts params @horario.hora_fin = @horario.hora_inicio + 3600 if @horario.save redirect_to :schedules, :flash => { :success => 'Horario de atención creado exitosamente.' } else render :action => 'index' end end def update end # Método que elimina un registro de tipo Schedule # * *Parámetros* : # - +id+ -> identificador único del registro de tipo Schedule # * *Resultado* : # - El horario se elimina exitosamente def destroy @user = Schedule.find(params[:id]) @user.destroy redirect_to schedules_path, :flash => { :success => 'Horario eliminado correctamente.' } end end
true
285db104f7e9873e845a7db87b26fb696e1c57c0
Ruby
LHemingway/spartaClasswork
/w08d04/xml-parsing/xml-parsing.rb
UTF-8
196
2.53125
3
[]
no_license
require "nokogiri" doc = Nokogiri::XML(open('./xml_menu.xml')) # puts doc.search('price') # doc.search('food').each do |food| # p food.element_children(1.name) # end puts doc.xpath('//food')
true
07664124dbd5d7aafa3502e8e1d19a1f4902f111
Ruby
hatwell/wk2_day1_lab_homework
/lab_part_a_spec.rb
UTF-8
909
3.296875
3
[]
no_license
require('minitest/autorun') require('minitest/rg') require_relative('./lab_part_a') class StudentTest < MiniTest::Test def setup @student_1 = Student.new("Drake", 13) @student_2 = Student.new("Zlatan", 14) end def test_get_name assert_equal("Drake", @student_1.name) assert_equal("Zlatan", @student_2.name) end def test_set_name @student_1.set_name("Drizzy") assert_equal("Drizzy", @student_1.name) end def test_get_cohort assert_equal(14, @student_2.cohort) end def test_set_cohort @student_2.set_cohort(16) assert_equal(16, @student_2.cohort) end def test_student_can_talk @student_1.talk("I am talking") assert_equal(String, @student_1.talk("Words").class) end def test_say_favourite_language @student_1.say_favourite_language("Java") assert_equal("I love Java", @student_1.say_favourite_language("Java")) end end
true
2da6cd43b863f263c00b7de25668933dcfbca9bf
Ruby
Krysta110/cli-applications-jukebox-hou01-seng-ft-042020
/lib/jukebox.rb
UTF-8
2,130
4.25
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Add your code here # def prompt_user_name # puts "Enter your name:" # end # def gets_user_name # user_name = gets.strip # return user_name # end # def say_hello(name) # puts "Hi #{name}" # end # def run_jukebox # prompt_user_name # user_name = gets_user_name # say_hello(user_name) # end # run_jukebox def get_command_input #gets command # from user gets.strip end def help #displays the full list of commands $stdout.puts "I accept the following commands:" $stdout.puts "- help : displays this help message" $stdout.puts "- list : displays a list of songs you can play" $stdout.puts "- play : lets you choose a song to play" $stdout.puts "- exit : exits this program" end def list(songs) #displays a list of songs you can play # num = 1 # songs.each do |count| # puts "#{num}. #{songs[count]}" # num +=1 # end songs.each_with_index do |item, index| $stdout.puts "#{index+1}. #{item}" end end def play(songs) #lets you choose a song to play found = "no" $stdout.puts "Please enter a song name or number:" user_input = gets.strip songs.each_with_index do |item, index| index_n = index + 1 if user_input == index_n.to_s found = "yes" puts "Playing #{item}" elsif user_input == item found = "yes" puts "Playing #{item}" end end if found == "no" puts "Invalid input, please try again" end end def exit_jukebox #exits the program puts "Goodbye!" end def run(songs) # loop do users_command = " " $stdout.puts "Please enter a command:" users_command = gets.strip if users_command == "help" help elsif users_command == "list" list(songs) elsif users_command == "play" play(songs) elsif users_command == "exit" exit_jukebox else puts "That is not an accepted command" end break if users_command == "exit" end end
true
74e99e1e9fc98519052491b6b5bb980ffd21a515
Ruby
tekzsolt/introduction-to-programming
/1_The_Basics/2.rb
UTF-8
281
3.015625
3
[]
no_license
four_digit_nr = 8576 thousands = four_digit_nr / 1000 hundreds = four_digit_nr % 1000 / 100 tens = four_digit_nr % 1000 % 100 / 10 ones = four_digit_nr % 1000 % 100 % 10 # puts "Thousands: #{thousands}" # puts "Hundreds: #{hundreds}" # puts "Tens: #{tens}" # puts "Ones: #{ones}"
true
9a9bd81f932e92e255bd044fe061a7c1dd4d2d17
Ruby
celeste-gits-it/Phase_0
/week-5/group-research-methods/my_solution.rb
UTF-8
2,680
4.40625
4
[]
no_license
# Person 1 - Emmanuel include Enumerable # Person 1's solution def my_array_finding_method(source, thing_to_find) source.grep(/#{thing_to_find}/) end def my_hash_finding_method(source, thing_to_find) source.select {|k, v| v == thing_to_find}.keys end # Identify and describe the Ruby method(s) you implemented. # # # # Person 2 -Lauren def my_array_modification_method!(array, numadd) array.map!{|element| element.is_a?(Integer) ? element + numadd : element} end p my_array_modification_method!(i_want_pets,1) def my_hash_modification_method!(hash, numadd) hash.each {|k, v| hash[k] = v + 2 } end p my_hash_modification_method!(my_family_pets_ages,2) # Identify and describe the Ruby method(s) you implemented. #for the first method, I applied map so that the method would go through each element and determine if it is an integer. If so, then add the numadd argument to the element #for the second method, I simply used each method and added 2 to each value # # Person 3 - Ali def my_array_sorting_method(source) source.sort { |a, b| a.to_s <=> b.to_s } end def my_hash_sorting_method(source) source.sort_by { |k, v| v } end # Identify and describe the Ruby method(s) you implemented. # I used the built-in Ruby method sort for the array and sort_by for the hash. Both of these # require a code block. In the array, since there is a mix of strings and fixnums, I converted # each element to a string. The sort_by method is really powerful and all I had to do in the # code block was specify that it as the value (v) that needed to be sorted on. I'm sure my first # solution could be refactored, but I'm not sure you can get anything clearer or more concise # than the sort_by method for the hash. -- Ali # Person 4 - Celeste def my_array_deletion_method!(source, thing_to_delete) source.select! {|el| el.to_s.include?(thing_to_delete) == false} end def my_hash_deletion_method!(source, thing_to_delete) source.delete(thing_to_delete) return source end # Identify and describe the Ruby method(s) you implemented. # For Array deletion using RubyDocs I choose to use the .select! destructive method # .select! destructive method will iterate over and delete any element that does not meet the conditions set in the block. # The condition is set up turn each element into a string, then if the string contains the thing_to_delete it will be return false, and as a result that value will be removed. # For Hash deletion I choose the .delete method. This will remove the key/value pair from the hash based on the argument. # I added 'return source' on the next line so that it will return that instead of the deleted key value.
true
487346de987c4d15724d36eed9135e917c1769ed
Ruby
escobara/RubyPractice
/mpruby_class_obj5.rb
UTF-8
480
4.15625
4
[]
no_license
puts "Before class definition, self =#{self} " var = class Dave puts "Inside class definition, self =#{self}" def say_hello puts 'hi' end self end puts "After class definition, self =#{self} " d = var.new d.say_hello # Before class definition, self =main # Inside class definition, self =Dave # After class definition, self =main # hi # without self being referenced at the end, ruby will return undefined method for new ** # Classes don't need to have a name **
true
755cc98558c67bc8956748fd70754fa1176116d4
Ruby
andrewsheelan/bible_search
/lib/sn_snv.rb
UTF-8
1,587
2.671875
3
[]
no_license
agent = Mechanize.new page = agent.get("http://www.sinhalaholybible.com/en/read-bible-sinhala-holy-bible/read-bible-sinhala-tamil-english.html") form = agent.page.forms.first form.username='andrewsheelan' form.password='welcome123' page = form.submit form.buttons.first doc = page.parser puts "Successfully Parsed!" language = Language.find_by_ref('SN') version = Version.find_by_short_name('SNV') page_books = doc.css('#book option') page_books.each do |page_book| form = agent.page.forms[2] form.b = page_book.attr('value') page = form.submit doc = page.parser puts "Parsed.." + page_book.text page_chapters = doc.css('#chapter option') page_chapters.each do |page_chapter| form = agent.page.forms[2] form.c=page_chapter.attr('value') page = form.submit doc = page.parser puts "Parsed.." + page_book.text + "" + page_chapter.text page_verses = doc.css('.zef_bible_Chapter .zef_verse') page_verse_numbers = doc.css('.zef_bible_Chapter .zef_verse_number') page_verses.each_with_index do |page_verse, verse_index| p_verse = page_verse.text.strip p_number = page_verse_numbers[verse_index].text.strip BibleVerse.create(language_id: language.id, version_id: version.id, book_id: Book.find(page_book.attr('value')[/\d+/]).id, chapter: page_chapter.text.strip, verse: p_number, misc_data: p_verse, verse_text: "#{p_number}. #{p_verse}" ) end end end
true
51dcc3e36a6a22e0ab8f5ad1227ef328b2c6d14f
Ruby
zottwickel/data-structures_and_algorithms
/knight_moves.rb
UTF-8
1,206
3.546875
4
[]
no_license
class Board attr_accessor :coords def initialize $coords = Array.new for i in 0...8 for j in 0...8 $coords.push([i,j]) end end end end class Knight attr_accessor :pos, :prev, :moves def initialize(pos=[0,3],prev=nil,moves=[]) @pos = pos @moves = [] @prev = prev end end def next_moves(knight) nxt = knight.pos moves = [[1,-2],[1,2],[-1,-2],[-1,2],[-2,-1],[-2,1],[2,-1],[2,1]] moves.each do |x| nxt_spot = [(x[0] + nxt[0]),(x[1] + nxt[1])] if (nxt_spot[0] >= 0 && nxt_spot[0] < 8) && (nxt_spot[1] >= 0 && nxt_spot[1] < 8) new_knight = Knight.new(nxt_spot,knight) knight.moves.push(new_knight) end end end def knight_moves(start, dst) return nil if !(dst[0] >= 0 && dst[0] < 8) && (dst[1] >= 0 && dst[1] < 8) knight = Knight.new(start) moves = [] while 1 next_moves(knight) break if knight.pos == dst moves += knight.moves break if moves.length < 1 knight = moves.shift end return nil if knight.pos != dst path = [knight.pos] while (!knight.prev.nil?) path << knight.prev.pos knight = knight.prev end path.reverse! end p knight_moves([0,0], [1,2]) p knight_moves([0,0], [3,3]) p knight_moves([3,3], [0,0]) p knight_moves([1,1], [6,7])
true
f4a68aec4a231680713bf9f59e79c6558454c540
Ruby
jblas-project/jblas
/examples/complex_svd.rb
UTF-8
504
2.65625
3
[ "BSD-3-Clause" ]
permissive
require 'java' require 'jblas-1.0.3.jar' java_import 'org.jblas.ComplexDoubleMatrix' java_import 'org.jblas.DoubleMatrix' java_import 'org.jblas.Singular' Matrix = ComplexDoubleMatrix M = 4 N = 3 m = Matrix.new(M, N) for i in 0...M for j in 0...N m.put(i, j, i+j, i*j) #m.put(i, j, i+j) end end puts m.dup u, s, v = Singular.sparseSVD(m) s = Matrix.diag(s) puts "u = #{u}" puts "s = #{s}" puts "v = #{v}" puts u.mmul(s).mmul(v.transpose).sub(m).norm2() puts Singular.SVDValues(m)
true
c34ad36aaeca2377db17f2090c7dfbb9e63eb5b6
Ruby
Sillhouette/ttt-with-ai-project-v-000
/lib/players/human.rb
UTF-8
315
3.25
3
[]
no_license
## # => Player module for cleanliness purposes ## module Players ## # => Instantiates the human player ## class Human < Player ## # => Makes a move on the board based on player input ## def move(board) puts "What position do you want to move to?" gets.strip; end end end
true
f5b7d904c726d2acc2f189543b1bc2b745d55561
Ruby
JoashWalton/congregation_management_api
/spec/controllers/souls_controller_spec.rb
UTF-8
5,276
2.5625
3
[]
no_license
require 'rails_helper' # This spec was generated by rspec-rails when you ran the scaffold generator. # It demonstrates how one might use RSpec to specify the controller code that # was generated by Rails when you ran the scaffold generator. # # It assumes that the implementation code is generated by the rails scaffold # generator. If you are using any extension libraries to generate different # controller code, this generated spec may or may not pass. # # It only uses APIs available in rails and/or rspec-rails. There are a number # of tools you can use to make these specs even more expressive, but we're # sticking to rails and rspec-rails APIs to keep things simple and stable. # # Compared to earlier versions of this generator, there is very limited use of # stubs and message expectations in this spec. Stubs are only used when there # is no simpler way to get a handle on the object needed for the example. # Message expectations are only used when there is no simpler way to specify # that an instance is receiving a specific message. # # Also compared to earlier versions of this generator, there are no longer any # expectations of assigns and templates rendered. These features have been # removed from Rails core in Rails 5, but can be added back in via the # `rails-controller-testing` gem. RSpec.describe SoulsController, type: :controller do # This should return the minimal set of attributes required to create a valid # Soul. As you add validations to Soul, be sure to # adjust the attributes here as well. let(:valid_attributes) { FactoryBot.build(:soul).slice(:first_name, :middle_name, :last_name, :birth_date, :gender) # { first_name: "Kenton", middle_name: "Strosin", last_name: "Fadel", birth_date: "2019-12-25", gender: "M" } } let(:invalid_attributes) { { first_name: "", middle_name: "", last_name: "", birth_date: "", gender: "" } } # This should return the minimal set of values that should be in the session # in order to pass any filters (e.g. authentication) defined in # SoulsController. Be sure to keep this updated too. let(:valid_session) { {} } describe "GET #index" do it "returns a success response" do Soul.create! valid_attributes get :index, params: {}, session: valid_session expect(response).to be_successful end end describe "GET #show" do it "returns a success response" do soul = Soul.create! valid_attributes get :show, params: {id: soul.to_param}, session: valid_session expect(response).to be_successful end end describe "GET #new" do it "returns a success response" do get :new, params: {}, session: valid_session expect(response).to be_successful end end describe "GET #edit" do it "returns a success response" do soul = Soul.create! valid_attributes get :edit, params: {id: soul.to_param}, session: valid_session expect(response).to be_successful end end describe "POST #create" do context "with valid params" do it "creates a new Soul" do expect { post :create, params: {soul: valid_attributes}, session: valid_session }.to change(Soul, :count).by(1) end it "redirects to the created soul" do post :create, params: {soul: valid_attributes}, session: valid_session expect(response).to redirect_to(Soul.last) end end context "with invalid params" do it "returns a success response (i.e. to display the 'new' template)" do post :create, params: {soul: invalid_attributes}, session: valid_session expect(response).to be_successful end end end describe "PUT #update" do context "with valid params" do let(:new_attributes) { FactoryBot.build(:soul).slice(:first_name, :middle_name, :last_name, :birth_date, :gender) } it "updates the requested soul" do soul = Soul.create! valid_attributes put :update, params: {id: soul.to_param, soul: new_attributes}, session: valid_session soul.reload expect(soul.first_name).to eq (new_attributes['first_name']) expect(soul.last_name).to eq (new_attributes['last_name']) end it "redirects to the soul" do soul = Soul.create! valid_attributes put :update, params: {id: soul.to_param, soul: valid_attributes}, session: valid_session expect(response).to redirect_to(soul) end end context "with invalid params" do it "returns a success response (i.e. to display the 'edit' template)" do soul = Soul.create! valid_attributes put :update, params: {id: soul.to_param, soul: invalid_attributes}, session: valid_session expect(response).to be_successful end end end describe "DELETE #destroy" do it "destroys the requested soul" do soul = Soul.create! valid_attributes expect { delete :destroy, params: {id: soul.to_param}, session: valid_session }.to change(Soul, :count).by(-1) end it "redirects to the souls list" do soul = Soul.create! valid_attributes delete :destroy, params: {id: soul.to_param}, session: valid_session expect(response).to redirect_to(souls_url) end end end
true
9152144b72f13c60d61b7a87010d25dc6dd51b66
Ruby
warrenchaudhry/hometime-reservations
/app/models/guest.rb
UTF-8
432
2.53125
3
[]
no_license
class Guest < ApplicationRecord VALID_EMAIL_REGEX = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i has_many :reservations has_many :phone_numbers validates :email, :first_name, :last_name, presence: true validates_format_of :email, with: VALID_EMAIL_REGEX, allow_blank: true validates_uniqueness_of :email, case_sensitive: false, allow_blank: true def full_name [first_name, last_name].compact.join(' ') end end
true
4ee2f71c4d9cb66bf597c3a5edc0fbc89951385f
Ruby
reenz/boris_bikes
/lib/docking_station.rb
UTF-8
444
3.28125
3
[]
no_license
require_relative "bike" class DockingStation attr_reader :docked_bikes def initialize @docked_bikes = [] end def release_bike if @docked_bikes.length == 0 raise "No bike" else return @docked_bikes.pop end end def dock_bike(bike) raise "Its full" if @docked_bikes.length == 1 @docked_bikes << bike @docked_bikes.last #return last stored bike, to check bike was stored correctly end end
true
1b08164d43fb7dcb5139430d86a39160f352b56f
Ruby
hassanrehman/project_euler
/problem096.rb
UTF-8
2,609
3.609375
4
[]
no_license
require 'set' class Sudoku attr_accessor :rows, :name def initialize(rows, name=nil) @name = name @rows = rows #.map{|r| r.split("").map(&:to_i) } @indices = (0..8).to_a.product((0..8).to_a) end def to_s r = @rows.map{|r| r.each_slice(3).to_a.map(&:join).join(" ") } s = r.each_slice(3).to_a.map{|_r| _r.join("\n") }.join("\n\n") [@name, s].join("\n") end def print puts "#{self}\n\n" end def possibilities(r, c) (return [@rows[r][c]]) if @rows[r][c] != 0 #if there is a number there, that's the only possibility t = Set.new t += @rows[r].select{|_c| _c > 0 } #on row t += @rows.map{|row| row[c] }.select{|_r| _r > 0 } tl_r, tl_c = [(r / 3)*3, (c / 3)*3] t += [0, 1, 2].product([0, 1, 2]).map{|i, j| @rows[tl_r+i][tl_c+j] } #on box (0..9).to_a - t.to_a end def single_possibilities! something_found = false @indices.each do |i, j| if rows[i][j] == 0 and (_p = possibilities(i, j)).length == 1 rows[i][j] = _p[0] something_found = true end end #keep going .. until there is one such single possibility single_possibilities! if something_found end def complete? (return false) if rows.any?{|r| r.any?{|c| c == 0 } } (return false) if rows.any?{|row| row.sort.join != "123456789" } (return false) if rows.transpose.any?{|row| row.sort.join != "123456789" } #TODO: check for boxes? return true end def clone new_g = Sudoku.new( @rows.map(&:clone) ) yield(new_g) if block_given? return new_g end def solve! single_possibilities! (return true) if complete? #since the single possibilities are all accounted for .. #and it's not possible to have 0 possibilities in a sudoku .. #get the first 0 .. find it's possibilities and recurse i, j = @indices.select{|_i, _j| rows[_i][_j] == 0 }.first possibilities(i, j).each do |n| new_g = clone{|g| g.rows[i][j] = n } if new_g.solve! @rows = new_g.rows return true end end return false end def result @rows[0][0..2].join.to_i end end lines = File.read("files/p096_sudoku.txt").split("\n") grids = (0...50).map{|i| Sudoku.new( lines[ (i*10+1)..(i*10+9) ].map{|r| r.split("").map(&:to_i) }, lines[i*10] ) } ans = 0 grids.each do |g| print g.name t = Time.now resolved = g.solve! puts " done: #{resolved} took #{(Time.now - t).round(2)}s -- #{g.result}" ans += g.result end puts ans # puts grids.select(&:solve!).map(&:name).sort # g = grids[1] # g.print # puts g.solve! # g.print
true