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
77de6e25db3d0d1ca8bb3238d412ce4903822547
Ruby
a-woodworth/ls_projects
/oop_book/section_4/exercise_7.rb
UTF-8
573
4.65625
5
[]
no_license
# Create a class 'Student' with attributes name and grade. Do NOT make the grade getter public, # so joe.grade will raise an error. Create a better_grade_than? method, that you can call # like so... # puts "Well done!" if joe.better_grade_than?(bob) class Student def initialize(name, grade) @name = name @grade = grade end def better_grade_than?(other_student) grade > other_student.grade end protected def grade @grade end end joe = Student.new('Joe', 70) bob = Student.new('Bob', 65) puts "Well done!" if joe.better_grade_than?(bob)
true
0cb9f0e9c059b3877387ba0d0cd257eb480d442a
Ruby
zoexanos/programming-univbasics-4-array-simple-array-manipulations-part-2-chi01-seng-ft-062220
/lib/intro_to_simple_array_manipulations.rb
UTF-8
1,069
3.125
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def using_concat(array, array2) array.concat(array2) end my_favorite_things = ["raindrops on roses", "whiskers on kittens"] more_favs = ["sports cars", "flatiron school"] using_concat(my_favorite_things, more_favs) def using_insert(array, object) array.insert(4, object) end list_of_programming_languages = ["Ruby", "JavaScript", "Java", "C#", "Objective C", "C++", "PHP"] another_language = "Python" using_insert(list_of_programming_languages, another_language) def using_uniq(array) array.uniq end haircuts = ["Pixie", "Bob", "Mohawk", "Crew Cut", "Linka", "Wheeler", "Bob"] using_uniq(haircuts) def using_flatten(array) array.flatten end instruments = ["Saxophone", ["Piano", "Trumpet"], "Violin", "Drums", "Flute"] using_flatten(instruments) def using_delete(array, object) array.delete(object) end instructors = ["Josh", "Steven", "Sophie", "Steven", "Amanda", "Steven"] using_delete(instructors, "Steven") def using_delete_at(array, index) array.delete_at(index) end famous_robots = ["Johnny 5", "R2D2", "Robocop"] using_delete_at(famous_robots, 2)
true
2d6850f83d21f721f6062de80262074fa00ed8ff
Ruby
kwalendzik/anagram-detector-online-web-pt-081219
/lib/anagram.rb
UTF-8
184
3.453125
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# Your code goes here! class Anagram attr_accessor :word def initialize(word) @word = word end def match(array) array.select { |x| x.chars.sort == @word.chars.sort} end end
true
2c5936e27cc34601a69fa2a85b6b44aa70156a66
Ruby
jclosure/seeker
/lib/seeker.rb
UTF-8
2,142
2.71875
3
[]
no_license
require 'whois' require 'active_support' require 'active_record' def smart_require name begin require name rescue LoadError puts "unable to load #{name} from gem cache. falling back to local directory." path = File.expand_path("#{name}.rb", File.dirname(__FILE__)) require path end end smart_require 'hash_extensions' smart_require 'retryable' class Seeker attr_accessor :out, :options def initialize options = {} @options = options.options_merge :suffix => '.com', :delimeter => ' ' @client = Whois::Client.new(:timeout => 5) self.set_out end def set_out @out = $stdout @out = yield if block_given? end def work_file(infile, outfile, suffix = nil, delimeter = nil) begin @file = open(infile) @out = open(outfile, 'w') while line = @file.gets if block_given? yield(line) else #assume args[2] is the split delimiter and args[3] is the suffix (eg: tld) self.work_list(line.split(delimeter)) { |word| word + (suffix || @options[:suffix]) } end end ensure @file.close if @file @out.close if @outfile self.set_out end end def work_list(*list) list = list[0] if list[0].is_a? Array rescue list #handles when list items are not splatted list.each do | domain_name | domain_name = yield(domain_name) if block_given? begin retryable(:tries => 1, :on => StandardError) do self.probe_availability domain_name end rescue => e #puts e.backtrace end end end def probe_availability domain_name @out = yield if block_given? begin puts 'probing: ' + domain_name.to_s if (r = @client.query(domain_name.to_s.strip)) if (r.available?) puts 'available: ' + domain_name.to_s @out.puts domain_name.to_s.strip @out.flush end end rescue => e puts e.message raise e end end end # class ActiveRecord::Base # include Seeker #see: http://railscasts.com/episodes/135-making-a-gem # end
true
bcc61f50df50e39c228536f023e3122b22fc7b62
Ruby
Coolagin/patterns_doc
/creational/abstract_factory/abstract_factory.rb
UTF-8
1,024
3.453125
3
[]
no_license
# Создание фабрики для реализации 1 class RealisationFactory1 def create_button Realisation_1.new end end # Создание фабрики для реализации 2 class RealisationFactory2 def create_button Realisation_2.new end end # Базовый клас class BaseClass attr_accessor :caption end # Реализация класса class Realisation_1 < BaseClass def render puts "I`m Realisation_1 #{@caption}" end end # Реализация класса class Realisation_2 < BaseClass def render puts "I`m Realisation_2 #{@caption}" end end class Application def initialize(factory) button = factory.create_button button.caption = 'Start' button.render end end class ApplicationRunner def self.run Application.new(self.createSpecificFactory) end def self.createSpecificFactory if use_realisation_1 RealisationFactory1.new else RealisationFactory2.new end end end ApplicationRunner.run
true
b261fb6f9477928b9cb2b8c46a648ad3d015e215
Ruby
marcusg/foreign_key_validation
/lib/foreign_key_validation/validator.rb
UTF-8
1,344
2.640625
3
[ "MIT" ]
permissive
module ForeignKeyValidation class Validator attr_accessor :collector, :object def initialize(collector, object) self.collector = collector self.object = object end def validate to_enum(:invalid_reflection_names).map {|n| attach_error(n) }.any? end private def invalid_reflection_names(&block) (validate_with || []).each do |reflection_name| next unless keys_present?(reflection_name) yield reflection_name if keys_different?(reflection_name) end end def key_on_relation(relation) object.public_send(relation).try(validate_against_key) end def key_on_object object.try(validate_against_key) end def keys_present?(relation) key_on_object.present? and key_on_relation(relation).present? end def keys_different?(relation) key_on_object != key_on_relation(relation) end def attach_error(reflection_name) object.errors.add(validate_against_key, error_message(reflection_name)) end def error_message(reflection_name) ForeignKeyValidation.configuration.error_message.call(validate_against_key, reflection_name, object) end def validate_against_key collector.validate_against_key end def validate_with collector.validate_with end end end
true
db6fcc238d461131c9b8b7e446fc6159ba8bd89a
Ruby
melborne/itunes_track
/lib/itunes_track.rb
UTF-8
1,639
2.71875
3
[ "MIT" ]
permissive
require 'appscript' require 'csv' require 'ostruct' require 'itunes_track/version' include Appscript class ItunesTrack ATTRS = %i(name time artist album genre rating played_count year composer track_count track_number disc_count disc_number lyrics) require 'itunes_track/cli' class Track < OpenStruct end class << self def build(*attrs, &blk) tracks.clear @attrs = attrs.empty? ? ATTRS : attrs track_attrs = [] itunes_tracks(&blk).each do |track| track_attrs << begin @attrs.inject({}) do |h, attr| val = track.send(attr).get rescue '' if val.is_a?(String) && val.encoding.to_s!='UTF-8' val = val.force_encoding('UTF-8') end h[attr.intern] = val h end end end tracks.push *track_attrs.map { |attrs| Track.new attrs } end def full_build(&blk) build(*track_properties, &blk) end def tracks @tracks ||= [] end def itunes @itunes ||= app('iTunes').tracks end def itunes_tracks(&blk) block_given? ? itunes.get.select(&blk) : itunes.get end def size(&blk) itunes_tracks(&blk).size end def track_properties itunes.properties.map(&:intern) end def to_csv(path, attrs=@attrs) raise 'Should be built first' if tracks.empty? CSV.open(path, 'wb') do |csv| csv << attrs tracks.each { |t| csv << attrs.map{ |attr| t.send attr } } end rescue => e puts "Something go wrong during csv building: #{e}" end end end ITunesTrack = ItunesTrack
true
8e5ac599508d3ad8a86a91219c5612330caa5fba
Ruby
metalefty/rubygem-fradium
/lib/fradium.rb
UTF-8
4,232
2.65625
3
[ "MIT" ]
permissive
require "fradium/version" require 'securerandom' require 'sequel' require 'time' class Fradium class UserAlreadyExistsError < StandardError; end class UserNotFoundError < StandardError; end class UsernameEmptyError < StandardError; end class CorruptedUserDatabaseError < StandardError; end def initialize(params) @params = params @sequel = Sequel.connect(@params) end def user_exists?(username) find_user(username).count > 0 end def all_users @sequel[:radcheck].where{attribute.like '%-Password'} end def create_user(username) raise UsernameEmptyError if username&.empty? raise UserAlreadyExistsError if user_exists?(username) password = Fradium.generate_random_password @sequel[:radcheck].insert(username: username, attribute: 'Cleartext-Password', op: ':=', value: password) end def find_user(username) raise UsernameEmptyError if username&.empty? reult = @sequel[:radcheck].where(username: username).where{attribute.like '%-Password'} end def modify_user(username) raise UsernameEmptyError if username&.empty? raise UserNotFoundError unless user_exists?(username) password = Fradium.generate_random_password target = find_user(username) raise CorruptedUserDatabaseError if target.count > 1 target.update(value: password, attribute: 'Cleartext-Password') end def expiry @sequel[:radcheck].where(attribute: 'Expiration') end def expired_users now = Time.now # a little bit redundant but for consistency id = @sequel[:radcheck].where(attribute: 'Expiration').collect{|e| e[:id] if Time.now > Time.parse(e[:value])} @sequel[:radcheck].where(id: id) end def expire_user(username) set_expiration(username, Time.now) end def unexpire_user(username) raise UsernameEmptyError if username&.empty? raise UserNotFoundError unless user_exists?(username) @sequel[:radcheck].where(username: username, attribute: 'Expiration').delete end def is_expired?(username) expiration_date = query_expiration(username)&.fetch('value') return false if expiration_date.nil? || expiration_date.empty? # if expiration info not found, not expired yet Time.now > Time.parse(expiration_date) end def set_expiration(username, expiration_date) expiration_info = query_expiration(username) value = '' if expiration_date.instance_of?(Time) value = expiration_date.strftime("%d %b %Y %H:%M:%S") else value = Time.parse(expiration_date).strftime("%d %b %Y %H:%M:%S") end if expiration_info.nil? # add new entry @sequel[:radcheck].insert(username: username, attribute: 'Expiration', op: ':=', value: value) else # update existing entry expiration_info.update(value: value) end end def dbconsole case @sequel.adapter_scheme when :mysql2 # I know this is not safe. Kernel.exec({'MYSQL_PWD' => @params['password']}, 'mysql', "--pager=less -SF", "--user=#{@params['username']}", "--host=#{@params['host']}" , "#{@params['database']}") when :postgres Kernel.exec({'PGPASSWORD' => @params['password']}, 'psql', "--username=#{@params['username']}", "--dbname=#{@params['database']}", "--host=#{@params['host']}") when :sqlite Kernel.exec('sqlite3', @params) end end def self.generate_random_password(length=10) r = SecureRandom.urlsafe_base64.delete('-_') while r.length < length r << SecureRandom.urlsafe_base64.delete('-_') end r[0..length-1] end #private def query_expiration(username) raise UsernameEmptyError if username&.empty? raise UserNotFoundError unless user_exists?(username) r = @sequel[:radcheck].where(username: username, attribute: 'Expiration') raise CorruptedUserDatabaseError if r.count > 1 return nil if r.count == 0 # if no expiration info found return nil if r&.first[:value]&.empty? r end end
true
89fa8c3535e7d7e92704327d87c037bee4bffe94
Ruby
littlemove/barometer
/lib/barometer/data/sun.rb
UTF-8
969
3.234375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module Barometer class Data::Sun attr_reader :rise, :set def initialize(rise=nil, set=nil) raise ArgumentError unless (rise.is_a?(Data::LocalTime) || rise.nil?) raise ArgumentError unless (set.is_a?(Data::LocalTime) || set.nil?) @rise = rise @set = set end def rise=(time) raise ArgumentError unless (time.is_a?(Data::LocalTime) || time.nil?) @rise = time end def set=(time) raise ArgumentError unless (time.is_a?(Data::LocalTime) || time.nil?) @set = time end def nil? !(@rise || @set) end def after_rise?(time) raise ArgumentError unless time.is_a?(Data::LocalTime) time >= @rise end def before_set?(time) raise ArgumentError unless time.is_a?(Data::LocalTime) time <= @set end def to_s output = [] output << "rise: #{rise}" if rise output << "set: #{set}" if set output.join(', ') end end end
true
59c5d9259d66453699e594701440fdebff373165
Ruby
lonewolf28/Coding
/Ruby/ctrl_flow.rb
UTF-8
719
3.5
4
[]
no_license
#!/home/raj/.rbenv/shims/ruby #puts "enter the first word you can think of: " #words = %w(apple orange banana) #response = words.collect do |w| #print w + ">" #response = gets.chomp #if response.size == 0 then #redo #end #response #end #puts "#{response}" def factorial(n) begin raise ArgumentError.exception("The arg should be more than one") if n < 1 rescue => e puts "#{e.message}" exit end return 1 if n == 1 n * factorial(n-1) end #puts factorial(0) def explode raise "bam" if rand(10) == 0 end def risky begin 10.times do explode end rescue TypeError puts $! end "hello" end def defuse begin puts risky rescue RuntimeError => e puts e.message end end defuse
true
930074be73daa4024bb81763178356243a15a73a
Ruby
codeodor/with
/lib/with.rb
UTF-8
2,896
2.8125
3
[ "MIT" ]
permissive
require 'with_sexp_processor' require 'parse_tree' class With VERSION = "0.0.2" def self.object(the_object, &block) @the_object = the_object @original_context = block.binding anonymous_class = Class.new anonymous_class.instance_eval { define_method("the_block", block) } anonymous_class_as_sexp = ParseTree.translate(anonymous_class) our_block_sexp = anonymous_class_as_sexp[3][2][2] our_block_sexp = transform(our_block_sexp) transformed_block = lambda { eval(WithSexpProcessor.new.process(our_block_sexp)) } #, block.binding) } transformed_block.call end private def self.convert_single_statement_to_block(node) node = [:block, node] if node[0] != :block return node end def self.statements_to_process [:dasgn_curr, :lasgn, :fcall, :vcall] end def self.transform( node ) node = convert_single_statement_to_block node node.each_with_index do |statement, i| next if i == 0 statement_type = statement[0] statement = self.method("transform_#{statement_type.to_s}").call(statement) if statements_to_process.include? statement_type node[i] = statement end return node end def self.transform_dasgn_curr statement var_name = statement[1].to_s value = statement[2] new_method = (var_name+"=").to_sym #binds to original context since we lose original_object name and cannot eval in that context value[1] = eval(value[1].to_s, @original_context) if (value[0]==:lvar || value[0]==:vcall) && !@the_object.respond_to?(value[1].to_s) if value[0]==:fcall func = value[1] args = value[2] arg_list = "" args.each_with_index do |arg, j| next if j == 0 arg[1] = eval(arg[1].to_s, @original_context) if arg[0] != :lit arg_list << arg[1].to_s arg_list << "," if j < args.length-1 end funcall = "#{func}(#{arg_list})" value=[:lit, eval(funcall, @original_context)] end statement = [:attrasgn, [:lvar, :the_object], new_method, value] end def self.transform_lasgn statement method = statement[2][1] if @the_object.respond_to?(method) lvar = statement[1] statement = [:lasgn, lvar, [:call, [:lvar, :the_object], method]] end end def self.transform_fcall statement method = statement[1] args = statement[2] args.each_with_index do |arg, j| next if j == 0 arg[1] = eval(arg[1].to_s, @original_context) if arg[0] == :lvar && !@the_object.respond_to?(arg[1].to_s) end statement = [:call, [:lvar, :the_object], method, args] end def self.transform_vcall statement method = statement[1] statement = [:call, [:lvar, :the_object], method] end end
true
c9ff39d81a51c48544ee4c86b2f0e8454ff7b624
Ruby
rodrigomanhaes/dweller
/lib/dweller/state.rb
UTF-8
552
2.96875
3
[ "MIT" ]
permissive
module Dweller module State attr_reader :name, :acronym, :region class DwellerCity; include Dweller::City; end def cities @state_hash[:subregions].map do |city_hash| city = DwellerCity.new city.send "city_hash=", city_hash city end end def city(name) cities.find {|c| c.name == name } end private def state_hash=(hash) @state_hash = hash @name = @state_hash[:name] @acronym = @state_hash[:acronym] @region = @state_hash[:region] end end end
true
c58067d4d8c905dccfbb72d39a5d3323cab5fe8c
Ruby
Sheikh-Inzamam/AppAcademy-1
/poker/lib/game.rb
UTF-8
879
3.6875
4
[]
no_license
require 'deck' require 'hand' require 'player' class Game #game is the dealer #should handle UI, progression of the game, blinds (small and big) #initializes with game deck #asks how many players there are #builds pot from players #takes ante from each player #until game_over--One player gets all the money, everyone else broke #deck is shuffled #each player is dealt their hand(five cards) #betting round loop #each player choose to bet, fold, see/call current bet, or raise #opportunity to get new cards #ask each player if they want to discard up to three cards #deal out to each player as many cards as they discarded #betting round loop again #all remaining players then reveal their hands #gives money to player with strongest hand #congratulate players. say how much winning player takes home. end
true
14ee9d92819da2a29db9bd6fcdeae1de097bfcd1
Ruby
Lycoris/Project-Euler
/121-130/124.rb
UTF-8
436
3.421875
3
[]
no_license
# http://projecteuler.net/problem=124 # # require 'prime' def e(n, limit) k = Hash.new limit.times {|i| k[rad(i + 1)] = [] if k[rad(i + 1)] == nil k[rad(i + 1)] << i + 1 } sum = 0 i = 0 until sum > n or sum == n i += 1 sum += k[i].size if k[i] != nil end return k[i][-((sum - n) + 1)] end def rad(n) r = 1 n.prime_division.each {|i| r *= i[0]} return r end puts "Answer: #{e(10000,100000)}" # Answer: 21417
true
56fd7ac3adfc1319e46f032b4e7299004b6f2b0d
Ruby
hasumin71/rensyu
/drill_63.rb
UTF-8
297
4.3125
4
[]
no_license
#1,2,3が全て配列内に入っていれば「True」それ以外は「False」と出力されるメソッドを作りましょう。 def array123(nums) if nums.include?(1) && nums.include?(2) && nums.include?(3) puts "True" else puts "False" end end array123([1,2,3,4,5,6])
true
746a123d87a8c0e6b915db4b800e9e3699a4dcff
Ruby
FSlyne/Ruby
/threads/thread_class.rb
UTF-8
337
3.765625
4
[]
no_license
class MyClass def run while 1<2 do print "Hello" sleep(2) end end end threads = [] # start creating active objects by creating an object and assigning # a thread to each threads << Thread.new { MyClass.new.run } # now we're done just wait for all objects to finish .... threads.each { |t| t.join }
true
c439ddd2bde41c4978363e03ffac296ec6067136
Ruby
luisbilecki/desafio-blumpa
/spec/support/ricky_and_morty_api/ricky_and_morty_mock.rb
UTF-8
797
2.609375
3
[]
no_license
module RickyAndMortyMock BASE_URL = 'https://rickandmortyapi.com' def mock_get_character(id:, success: true) content = read_json('./spec/support/ricky_and_morty_api/character_response.json') stub = stub_request(:get, "#{BASE_URL}/api/character/#{id}") if success stub.to_return(status: 200, body: content) else stub.to_return(status: [404, 'Not Found']) end end def mock_get_episode(id:, success: true) content = read_json('./spec/support/ricky_and_morty_api/episode_response.json') stub = stub_request(:get, "#{BASE_URL}/api/episode/#{id}") if success stub.to_return(status: 200, body: content) else stub.to_return(status: [404, 'Not Found']) end end private def read_json(file) IO.read(file) end end
true
1555f35bb4936a013a03ec20e62c51b0780adbf5
Ruby
CompanyCam/fancy-count
/lib/fancy_count/adapter.rb
UTF-8
526
2.671875
3
[ "MIT" ]
permissive
# frozen_string_literal: true module FancyCount class Adapter def initialize(name, config) @name = name @config = config end def increment counter.increment end def decrement counter.decrement end def change(value) counter.value = value end def reset counter.value = 0 end def value counter.value end def delete counter.delete end private def counter raise "Not yet implemented" end end end
true
c950ebbbc56f0c665eb7ff20236d7a55db6d9506
Ruby
honzasp/ropucha
/spec/ropucha/parser/subroutines_spec.rb
UTF-8
2,124
2.703125
3
[]
no_license
require 'spec_helper' describe Ropucha::Parser do include_context "parser" describe "subroutine definitions and calls" do it "parses a no-parameter procedure definition" do @program = <<-END procedure do() x = y end END sexp.should == [:ropucha, [ [:procedure_def, "do", [], [ [:assign, [:var, "x"], [:var, "y"]] ]] ]] end it "parses a many-parameter procedure definition" do @program = <<-END procedure do(x,y,z) a = 1 end END sexp.should == [:ropucha, [ [:procedure_def, "do", ["x", "y", "z"], [ [:assign, [:var, "a"], [:number, 1]] ]] ]] end it "parses a no-parameter function definition" do @program = <<-END function time() return 2012 end END sexp.should == [:ropucha, [ [:function_def, "time", [], [ [:return, [:number, 2012]] ]] ]] end it "parses a many-parameter function definition" do @program = <<-END function count(a, b, c, d) return a end END sexp.should == [:ropucha, [ [:function_def, "count", ["a", "b", "c", "d"], [ [:return, [:var, "a"]] ]] ]] end it "parses a subroutine call with no arguments" do @program = <<-END main foo() end END sexp.should == [:ropucha, [ [:main, [ [:call, "foo", []] ]] ]] end it "parses a function call with many arguments" do @program = <<-END main bar(a, 42, b) end END sexp.should == [:ropucha, [ [:main, [ [:call, "bar", [[:var, "a"], [:number, 42], [:var, "b"]]] ]] ]] end it "parses a function call as an expression" do @program = <<-END main x = a + square(3) end END sexp.should == [:ropucha, [ [:main, [ [:assign, [:var, "x"], [:+, [:var, "a"], [:call, "square", [[:number, 3]]]]] ]] ]] end end end
true
d43aa0dbcd1a5cb9eedf0314f709e343af0b3261
Ruby
asciiman/bowling1978
/test/models/throw_test.rb
UTF-8
425
2.671875
3
[]
no_license
require 'test_helper' class ThrowTest < ActiveSupport::TestCase test "newly initialized" do current_throw = Throw.new assert_equal(0, current_throw.score) end test "some down" do current_throw = Throw.new(pins_down: "110101101") assert_equal(6, current_throw.score) end test "all down" do current_throw = Throw.new(pins_down: "1111111111") assert_equal(10, current_throw.score) end end
true
404b5a705b97ba2562ecc18b63998913b1d0203c
Ruby
cgoodmac/ruby
/labs/dinner_time/dinner_time.rb
UTF-8
1,087
3.75
4
[]
no_license
require 'pry' load 'food.rb' load 'protein.rb' load 'carb.rb' dinner = [] puts "Create a (p)rotein, (c)arb, or (q)uit?" prompt = gets.chomp while prompt != 'q' case prompt when 'p' puts "What kind of protein?" animal_type = gets.chomp when 'c' puts "What kind of carb?" grain_type = gets.chomp end puts "Calories?" calories = gets.chomp.to_i puts "Servings?" servings = gets.chomp.to_i puts "Prep time?" preptime = gets.chomp.to_i case prompt when 'p' p1 = Protein.new(animal_type, calories, servings, preptime) dinner << p1 when 'c' c1 = Carb.new(grain_type, calories, servings, preptime) dinner << c1 end puts "Create a (p)rotein, (c)arb, or (q)uit?" prompt = gets.chomp end # Calculate total calories and preptime total_calories = 0 total_preptime = 0 dinner.each do |i| total_calories = total_calories + (i.calories * i.servings) end dinner.each do |i| total_preptime = total_preptime + i.preptime end puts "Dinner items: #{dinner.join(', ')}" puts "Total calories: #{total_calories}" puts "Total prep time in mins: #{total_preptime}"
true
5fa9da8323e6210f10f950fb37caf0c9677f2252
Ruby
WillowGardener/plant-directory-new
/lib/plant.rb
UTF-8
1,266
2.984375
3
[]
no_license
require 'pg' class Plant attr_reader(:attributes, :name, :id) def initialize(attributes) @attributes = attributes @name = attributes[:name] @id = attributes[:id] end def save results = DB.exec("INSERT INTO plants (plant_name) VALUES ('#{@name}') RETURNING id;") @id = results.first['id'].to_i end def self.all results = DB.exec("SELECT * FROM plants;") plants = [] results.each do |r| plant_name = r['plant_name'] id = r['id'].to_i plants << Plant.new({:name => plant_name, :id => id}) end plants end def ==(another_plant) self.name == another_plant.name end def delete DB.exec("DELETE FROM plants WHERE id = (#{self.id})") end def update(new_name) DB.exec("UPDATE plants SET plant_name = ('#{new_name}') WHERE id = ('#{self.id}')") @name = new_name end def all_traits all_traits = [] results = DB.exec("select traits.* from plants join plant_traits on (plants.id = plant_traits.plant_id) join traits on (plant_traits.trait_id = traits.id) where plants.id = ('#{self.id}')") results.each do |r| all_traits << Trait.new({:trait => r['trait_name'], :id => r['id'].to_i}) end # all_traits = all_traits.sort all_traits end end
true
679355de9edf7566f4a9950634e60312e3aec88a
Ruby
ScottGarman/vmfloaty
/lib/vmfloaty/utils.rb
UTF-8
3,322
2.734375
3
[ "Apache-2.0" ]
permissive
require 'vmfloaty/pooler' class Utils # TODO: Takes the json response body from an HTTP GET # request and "pretty prints" it def self.format_hosts(hostname_hash) host_hash = {} hostname_hash.delete("ok") domain = hostname_hash["domain"] hostname_hash.each do |type, hosts| if type != "domain" if hosts["hostname"].kind_of?(Array) hosts["hostname"].map!{|host| host + "." + domain } else hosts["hostname"] = hosts["hostname"] + "." + domain end host_hash[type] = hosts["hostname"] end end host_hash.to_json end def self.generate_os_hash(os_args) # expects args to look like: # ["centos", "debian=5", "windows=1"] # Build vm hash where # # [operating_system_type1 -> total, # operating_system_type2 -> total, # ...] os_types = {} os_args.each do |arg| os_arr = arg.split("=") if os_arr.size == 1 # assume they didn't specify an = sign if split returns 1 size os_types[os_arr[0]] = 1 else os_types[os_arr[0]] = os_arr[1].to_i end end os_types end def self.get_vm_info(hosts, verbose, url) vms = {} hosts.each do |host| vm_info = Pooler.query(verbose, url, host) if vm_info['ok'] vms[host] = {} vms[host]['domain'] = vm_info[host]['domain'] vms[host]['template'] = vm_info[host]['template'] vms[host]['lifetime'] = vm_info[host]['lifetime'] vms[host]['running'] = vm_info[host]['running'] vms[host]['tags'] = vm_info[host]['tags'] end end vms end def self.prettyprint_hosts(hosts, verbose, url) puts "Running VMs:" vm_info = get_vm_info(hosts, verbose, url) vm_info.each do |vm,info| domain = info['domain'] template = info['template'] lifetime = info['lifetime'] running = info['running'] tags = info['tags'] || {} tag_pairs = tags.map {|key,value| "#{key}: #{value}" } duration = "#{running}/#{lifetime} hours" metadata = [template, duration, *tag_pairs] puts "- #{vm}.#{domain} (#{metadata.join(", ")})" end end def self.get_all_token_vms(verbose, url, token) # get vms with token status = Auth.token_status(verbose, url, token) vms = status[token]['vms'] if vms.nil? raise "You have no running vms" end running_vms = vms['running'] running_vms end def self.prettyprint_status(status, message, pools, verbose) pools.select! {|name,pool| pool['ready'] < pool['max']} if ! verbose width = pools.keys.map(&:length).max pools.each do |name,pool| begin max = pool['max'] ready = pool['ready'] pending = pool['pending'] missing = max - ready - pending char = 'o' puts "#{name.ljust(width)} #{(char*ready).green}#{(char*pending).yellow}#{(char*missing).red}" rescue => e puts "#{name.ljust(width)} #{e.red}" end end puts puts message.colorize(status['status']['ok'] ? :default : :red) end # Adapted from ActiveSupport def self.strip_heredoc(str) min_indent = str.scan(/^[ \t]*(?=\S)/).min min_indent_size = min_indent.nil? ? 0 : min_indent.size str.gsub(/^[ \t]{#{min_indent_size}}/, '') end end
true
83d43cbc980b2f80584606e1463234ea0c777b13
Ruby
grahamedgecombe/lancat
/lib/lancat/receiver.rb
UTF-8
1,447
2.78125
3
[ "ISC" ]
permissive
require 'socket' require 'ipaddr' module Lancat class Receiver def initialize(verbose, timeout, output) @verbose = verbose @timeout = timeout @output = output end def start STDERR.puts 'Waiting for broadcasts...' if @verbose addr = nil port = nil # wait for multicast packet to find the port number/IP address of the # other end multicast_sock = UDPSocket.new(Socket::AF_INET) begin ips = IPAddr.new(MULTICAST_ADDR).hton + IPAddr.new('0.0.0.0').hton multicast_sock.setsockopt(Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, ips) multicast_sock.bind(Socket::INADDR_ANY, MULTICAST_PORT) # TODO add support for receive timeout msg, addr = multicast_sock.recvfrom(2) port = msg.unpack('S>')[0] addr = addr[3] ensure multicast_sock.close end # connect to that IP/port over TCP, read until EOF and write the data to # @output STDERR.puts "Connecting to #{addr}:#{port}..." if @verbose client = TCPSocket.new(addr, port) begin STDERR.puts 'Reading data...' if @verbose loop do begin data = client.readpartial(4096) @output.write(data) rescue EOFError break end end ensure client.close end STDERR.puts 'Transfer complete.' if @verbose end end end
true
787662d04720a55e79a8f6429f2bc3ad2323da38
Ruby
swanandp/gcj
/2013/round_1b/a.rb
UTF-8
1,137
3.0625
3
[]
no_license
#!/usr/bin/env ruby # a # https://code.google.com/codejam/contest/2434486/dashboard $:.unshift File.dirname(__FILE__) require 'shortest_path' def solvable?(arr, start) solvable = true sum = start (arr + [0]).each do |a| solvable = sum > a break unless solvable sum += a end solvable end outfile = ARGV.first.gsub('.in', '.out') f = File.open(outfile, 'wb') infile = File.open(ARGV.first) cases = infile.readline.strip.to_i cases.times do |c| # solve here a, n = infile.readline.strip.split(' ').map(&:to_i) motes = infile.readline.strip.split(' ').map(&:to_i).sort if solvable?(motes, a) f.puts "Case ##{c + 1}: 0" elsif a == 1 f.puts "Case ##{c + 1}: #{n}" else sum = a operations = 0 best_answer = n motes.each_with_index do |mote, i| if sum > mote sum += mote next end best_answer = [n, operations + motes.length - i].min while sum <= mote sum += sum - 1 operations += 1 end sum += mote end f.puts "Case ##{c + 1}: #{[operations, best_answer].min}" end end f.close
true
d58799c37807bd2a2e002c08a3d40536ec0f21e2
Ruby
eosin-kramos/Ruby-Exercises-
/hello.rb
UTF-8
182
2.796875
3
[ "MIT" ]
permissive
# hello.rb, written by Kevin Ramos # This program follows the instructions from the # UC Berkeley Extension Coding Boot Camp puts "Today, I wrote code" puts "And I'm a coding machine..."
true
3a6d785f073722cfb129e3388ec39cdd6753bef8
Ruby
parkesma/nutrition_software
/app/models/meal.rb
UTF-8
892
3.046875
3
[]
no_license
class Meal < ActiveRecord::Base before_save :capitalize before_create :capitalize belongs_to :user has_many :food_assignments, dependent: :destroy validates :name, presence: true validates :time, presence: true def carbs total = 0 self.food_assignments.each do |fa| total += fa.food.carbs_per_exchange * fa.number_of_exchanges end total end def protein total = 0 self.food_assignments.each do |fa| total += fa.food.protein_per_exchange * fa.number_of_exchanges end total end def fat total = 0 self.food_assignments.each do |fa| total += fa.food.fat_per_exchange * fa.number_of_exchanges end total end def kcals total = 0 self.food_assignments.each do |fa| total += fa.food.kcals_per_exchange * fa.number_of_exchanges end total end private def capitalize self.name = self.name.titleize if !self.name.blank? end end
true
4627dd216f99fa3afe670eca0c62595c69dcf5b1
Ruby
ZeroPivot/dragonruby-zif
/app/lib/zif/sprites/serializable.rb
UTF-8
1,076
2.96875
3
[ "MIT" ]
permissive
# Throw this file into your app folder, like app/lib/serializable.rb # # In your main.rb or wherever you require files: # require 'app/lib/serializable.rb' # # In each class you want to automatically serialize: # class Foo # include Serializable # ... # end module Zif # A mixin for automatically definining #serialize based on instance vars with setter methods # If you have circular references in ivars (Foo.bar <-> Bar.foo), make sure one of the classes overrides # #exclude_from_serialize and specifies the attr. module Serializable def inspect serialize.to_s end def to_s serialize.to_s end def serialize attrs = {} instance_variables.each do |var| str = var.to_s.gsub('@', '') next if exclude_from_serialize.include? str attrs[str.to_sym] = instance_variable_get var if respond_to? "#{str}=" end attrs end # Override this method to exclude attrs from serialization / printing def exclude_from_serialize %w[args] # Too much spam end end end
true
84eb9829cc2d8a9740f0326cee656c3ca2f8d87e
Ruby
ben-garcia/the_odin_projects
/ruby/ruby_on_the_web/a_simple_server.rb
UTF-8
990
3.1875
3
[]
no_license
require 'socket' require 'json' # Get sockets from stdlib server = TCPServer.open(2000) # Socket to listen on port 2000 loop do client = server.accept client.puts(Time.now.ctime) request = client.gets.split(" ") if request[0] == "GET" if File.exists? request[1][1..-1] string = File.read request[1][1..-1] client.puts "#{request[2]} 200 OK\r\nDate: #{Time.now.ctime}\r\nContent-Type: text/html\r\nContent-Length: #{string.length}\r\n#{string}" else client.puts "#{request[2]} 404 NOT FOUND" end elsif request[0] == "POST" json_object = JSON.parse(request[3]) params = {name: json_object["viking"]["name"], email: json_object["viking"]["email"]} f = File.open("thanks.html", "r") thanks = f.read f.close thanks.gsub!("<%= yield %>", "<li>Name: #{params[:name]}</li><li>Email: #{params[:email]}</li>") client.puts thanks end client.puts "Closing the connection. Bye!" client.close end
true
f97f78a800d9b3cb910e83776293d862ce153145
Ruby
goodfairy/gblearn_ruby
/compcls.rb
UTF-8
637
2.734375
3
[]
no_license
class Computer < Host ## # initialize Computer by user data, or default data # # default data sets Computer's ip address 127.0.0.1 without host name and default mode pc (personal computer) # data option - Computer ip address, Computer name,Computer mode # def initialize(ipaddress = '127.0.0.1', dnsname = '', service = 'pc') super(ipaddress, dnsname) @service = service end ## # return Computer host ip address and host name and mode ( example > 'server1'='192.168.1.100' Servise: (RDP Server 1C 8.2) ) def getinfo super @info = @info + ' Servise: (' + @service.to_s + ')' @info end end
true
647d51056371921397a3063b69c9f88fc9ba8017
Ruby
JenStrong/chitter-challenge
/spec/user_spec.rb
UTF-8
869
2.8125
3
[]
no_license
require 'user' require 'pry' describe User do describe '.create' do it 'creates a new user' do user = User.create(username: 'user1', name: 'name1', email: 'email@gmail.com', password: 'password123') expect(user.id).not_to be_nil end end describe '.all' do it 'returns all users, wrapped in a User instance' do user = User.create(username: 'user1', name: 'name1', email: 'email@gmail.com', password: 'password123') expect(User.all.map(&:id)).to include user.id end end describe '.find' do it 'finds a user by ID' do user = User.create(username: 'user1', name: 'name1', email: 'email@gmail.com', password: 'password123') expect(User.find(user.id).username).to eq user.username end end describe '.find' do it 'returns nil if there is no ID given' do expect(User.find(nil)). to eq nil end end end
true
88d7ae7e0870340b449a0c36fca3c4b1c4c73602
Ruby
bhatarchanas/mcsmrt_mod
/final_parsing.rb
UTF-8
2,457
2.765625
3
[]
no_license
require 'trollop' opts = Trollop::options do opt :blastfile, "File with blast information.", :type => :string, :short => "-b" opt :otuutaxfile, "File with OTU table and utax information.", :type => :string, :short => "-u" opt :outfile, "Output file with OTU names, OTU counts, lineage and blast results.", :type => :string, :short => "-o" end blast_file = File.open(opts[:blastfile], "r") otu_utax_file = File.open(opts[:otuutaxfile], "r") out_file = File.open(opts[:outfile], "w") blast_file_hash = {} blast_file.each do |line| line_split = line.split("\t") #puts line_split[0] # get the otu name which will be the key of the hash key = line_split[0].split(";")[0] # Check if strain info is there in query, also get the query name! if line.include?("strain=") strain = line_split[1].split(";")[2].split("=")[1] query = line_split[1].split(";")[1].split("=")[1] else strain = "NA" query = line_split[1] end # Check if 16s completeness is there in query if line.include?("complete=") complete = line_split[1].split(";")[3].split("=")[1] else complete = "NA" end # Get the percent identity and alignment length percent_identity = line_split[2] alignment_length = line_split[3] # populate the hash blast_file_hash[key] = [query, strain, complete, percent_identity, alignment_length] end #puts blast_file_hash header = File.open(otu_utax_file, &:readline) header_split = header.split("\t")[0..-2].join("\t") out_file.puts(header_split+"\tdomain\tdomain_conf\tphylum\tphylum_conf\tclass\tclass_conf\torder\torder_conf\tfamily\tfamily_conf\tgenus\tgenus_conf\tspecies\tspecies_conf\tblast_query\tblast_strain\tblast_16s_completeness\tblast_percent_identity\tblast_alignment_length") otu_utax_file.each_with_index do |line, index| if index == 0 next else line_split = line.split("\t") key = line_split[0] capture_array = /d:([^(]+)\(([^)]+)\),p:([^(]+)\(([^)]+)\),c:([^(]+)\(([^)]+)\),o:([^(]+)\(([^)]+)\),f:([^(]+)\(([^)]+)\),g:([^(]+)\(([^)]+)\),s:([^(]+)\(([^)]+)\)/.match(line) #puts capture_array[1]+"\t"+capture_array[2]+"\t"+capture_array[3]+"\t"+capture_array[4]+"\t"+capture_array[5]+"\t"+capture_array[6]+"\t"+capture_array[7]+"\t"+capture_array[8]+"\t"+capture_array[9]+"\t"+capture_array[10]+"\t"+capture_array[11]+"\t"+capture_array[12]+"\t"+capture_array[13] out_file.puts(line_split[0..-2].join("\t")+"\t"+capture_array[1..-1].join("\t")+"\t"+blast_file_hash[key][0..-1].join("\t")) end end
true
2884e7ce55383522b62e0f79bdb3f6d93d37a14b
Ruby
stephencelis/scantron
/lib/scantron/scanners/date_scanner.rb
UTF-8
480
2.75
3
[ "MIT" ]
permissive
require 'scantron' require 'date' class DateScanner < Scantron::Scanner days = Date::DAYNAMES * '|' days << "|(?:#{Date::ABBR_DAYNAMES * '|'})\\b\\.?" months = Date::MONTHNAMES.compact * '|' months << "|(?:#{Date::ABBR_MONTHNAMES.compact * '|'})\\b\\.?" human = /\b(?:(#{days}),? )?\b(#{months})( \d{1,2}\b,?)?( \d{2,4})?/i rule :human, human do |r| Date.parse r.to_s end rule :iso8601, /\b\d{4}-\d{2}-\d{2}\b/ do |r| Date.parse r.to_s end end
true
c2503c9e0cd1b30d2f86b4585b908f7cc7eb3e55
Ruby
pact-foundation/pact_broker
/lib/pact_broker/pacts/selector.rb
UTF-8
11,417
2.578125
3
[ "MIT" ]
permissive
require "pact_broker/hash_refinements" module PactBroker module Pacts # rubocop: disable Metrics/ClassLength class Selector < Hash using PactBroker::HashRefinements PROPERTY_NAMES = [:latest, :tag, :branch, :consumer, :consumer_version, :environment_name, :fallback_tag, :fallback_branch, :main_branch, :matching_branch, :currently_supported, :currently_deployed] def initialize(properties = {}) properties.without(*PROPERTY_NAMES).tap { |it| warn("WARN: Unsupported property for #{self.class.name}: #{it.keys.join(", ")} at #{caller[0..3]}") if it.any? } merge!(properties) end def resolve(consumer_version) ResolvedSelector.new(self.to_h.without(:fallback_tag, :fallback_branch), consumer_version) end def resolve_for_fallback(consumer_version) ResolvedSelector.new(self.to_h, consumer_version) end def resolve_for_environment(consumer_version, environment, target = nil) ResolvedSelector.new(self.to_h.merge({ environment: environment, target: target }.compact), consumer_version) end # Only currently used to identify the currently_deployed from the others in # verifiable_pact_messages, so don't need the "for_consumer" sub category # rubocop: disable Metrics/CyclomaticComplexity def type if latest_for_main_branch? :latest_for_main_branch elsif latest_for_branch? :latest_for_branch elsif matching_branch? :matching_branch elsif currently_deployed? :currently_deployed elsif currently_supported? :currently_supported elsif in_environment? :in_environment elsif latest_for_tag? :latest_for_tag elsif all_for_tag? :all_for_tag elsif overall_latest? :overall_latest else :undefined end end # rubocop: enable Metrics/CyclomaticComplexity def main_branch= main_branch self[:main_branch] = main_branch end def matching_branch= matching_branch self[:matching_branch] = matching_branch end def tag= tag self[:tag] = tag end def branch= branch self[:branch] = branch end def latest= latest self[:latest] = latest end def latest self[:latest] end def fallback_tag= fallback_tag self[:fallback_tag] = fallback_tag end def fallback_branch= fallback_branch self[:fallback_branch] = fallback_branch end def fallback_tag self[:fallback_tag] end def fallback_branch self[:fallback_branch] end def consumer= consumer self[:consumer] = consumer end def consumer self[:consumer] end def currently_deployed= currently_deployed self[:currently_deployed] = currently_deployed end def currently_deployed self[:currently_deployed] end def currently_deployed? !!currently_deployed end def currently_supported= currently_supported self[:currently_supported] = currently_supported end def currently_supported self[:currently_supported] end def currently_supported? !!currently_supported end def environment_name= environment_name self[:environment_name] = environment_name end def environment_name self[:environment_name] end def in_environment? !!environment_name end def self.overall_latest new(latest: true) end def self.for_main_branch new(main_branch: true) end def self.latest_for_tag(tag) new(latest: true, tag: tag) end def self.latest_for_branch(branch) new(latest: true, branch: branch) end def self.latest_for_tag_with_fallback(tag, fallback_tag) new(latest: true, tag: tag, fallback_tag: fallback_tag) end def self.latest_for_branch_with_fallback(branch, fallback_branch) new(latest: true, branch: branch, fallback_branch: fallback_branch) end def self.all_for_tag(tag) new(tag: tag) end def self.all_for_tag_and_consumer(tag, consumer) new(tag: tag, consumer: consumer) end def self.latest_for_tag_and_consumer(tag, consumer) new(latest: true, tag: tag, consumer: consumer) end def self.latest_for_branch_and_consumer(branch, consumer) new(latest: true, branch: branch, consumer: consumer) end def self.latest_for_consumer(consumer) new(latest: true, consumer: consumer) end def self.for_currently_deployed(environment_name = nil) new( { currently_deployed: true, environment_name: environment_name }.compact ) end def self.for_currently_supported(environment_name = nil) new( { currently_supported: true, environment_name: environment_name }.compact ) end def self.for_currently_deployed_and_consumer(consumer) new(currently_deployed: true, consumer: consumer) end def self.for_currently_deployed_and_environment_and_consumer(environment_name, consumer) new(currently_deployed: true, environment_name: environment_name, consumer: consumer) end def self.for_currently_supported_and_environment_and_consumer(environment_name, consumer) new(currently_supported: true, environment_name: environment_name, consumer: consumer) end def self.for_environment(environment_name) new(environment_name: environment_name) end def self.for_environment_and_consumer(environment_name, consumer) new(environment_name: environment_name, consumer: consumer) end def self.from_hash hash new(hash) end def for_consumer(consumer) self.class.new(to_h.merge(consumer: consumer)) end def latest_for_main_branch? !!main_branch end def fallback_tag? !!fallback_tag end def fallback_branch? !!fallback_branch end def main_branch self[:main_branch] end def tag self[:tag] end def branch self[:branch] end def matching_branch self[:matching_branch] end def matching_branch? !!matching_branch end def overall_latest? !!(latest? && !tag && !branch && !main_branch && !currently_deployed && !currently_supported && !environment_name) end # Not sure if the fallback_tag logic is needed def latest_for_tag? potential_tag = nil if potential_tag !!(latest && tag == potential_tag) else !!(latest && !!tag) end end # Not sure if the fallback_tag logic is needed def latest_for_branch? potential_branch = nil if potential_branch !!(latest && branch == potential_branch) else !!(latest && !!branch) end end def all_for_tag_and_consumer? !!(tag && !latest? && consumer) end def all_for_tag? !!(tag && !latest?) end def == other other.class == self.class && super end # rubocop: disable Metrics/CyclomaticComplexity def <=> other if overall_latest? || other.overall_latest? overall_latest_comparison(other) elsif latest_for_branch? || other.latest_for_branch? branch_comparison(other) elsif latest_for_tag? || other.latest_for_tag? latest_for_tag_comparison(other) elsif tag || other.tag tag_comparison(other) elsif currently_deployed? || other.currently_deployed? currently_deployed_comparison(other) elsif currently_supported? || other.currently_supported? currently_supported_comparison(other) elsif consumer || other.consumer consumer_comparison(other) else 0 end end # rubocop: enable Metrics/CyclomaticComplexity private def overall_latest_comparison(other) if overall_latest? == other.overall_latest? 0 else overall_latest? ? -1 : 1 end end def branch_comparison(other) if latest_for_branch? == other.latest_for_branch? branch <=> other.branch else latest_for_branch? ? -1 : 1 end end def currently_deployed_comparison(other) if currently_deployed? == other.currently_deployed? environment_name <=> other.environment_name else currently_deployed? ? -1 : 1 end end def currently_supported_comparison(other) if currently_supported? == other.currently_supported? environment_name <=> other.environment_name else currently_supported? ? -1 : 1 end end def latest_for_tag_comparison(other) if latest_for_tag? == other.latest_for_tag? tag <=> other.tag else latest_for_tag? ? -1 : 1 end end def tag_comparison(other) if tag && other.tag if tag == other.tag consumer_comparison(other) else tag <=> other.tag end else tag ? -1 : 1 end end def consumer_comparison(other) if consumer && other.consumer consumer <=> other.consumer else consumer ? -1 : 1 end end def latest? !!self[:latest] end end class ResolvedSelector < Selector using PactBroker::HashRefinements PROPERTY_NAMES = Selector::PROPERTY_NAMES + [:consumer_version, :environment, :target] def initialize(properties = {}, consumer_version) properties.without(*PROPERTY_NAMES).tap { |it| warn("WARN: Unsupported property for #{self.class.name}: #{it.keys.join(", ")} at #{caller[0..3]}") if it.any? } merge!(properties.merge(consumer_version: consumer_version)) end def consumer_version self[:consumer_version] end def environment self[:environment] end def == other super && consumer_version == other.consumer_version end def <=> other comparison = super if comparison == 0 consumer_version.order <=> other.consumer_version.order else comparison end end def currently_deployed_comparison(other) if currently_deployed? == other.currently_deployed? production_comparison(other) else currently_deployed? ? -1 : 1 end end def currently_supported_comparison(other) if currently_supported? == other.currently_supported? production_comparison(other) else currently_supported? ? -1 : 1 end end def production_comparison(other) if environment.production? == other.environment.production? environment.name <=> other.environment.name else environment.production? ? 1 : -1 end end end # rubocop: enable Metrics/ClassLength end end
true
7c45e023bfdccbb0eb8bed40f2ec778878a46aea
Ruby
leviwilson/mohawk
/lib/mohawk/accessors.rb
UTF-8
13,783
2.78125
3
[ "MIT" ]
permissive
module Mohawk module Accessors # # Defines the locator indicating the top-level window that will be used # to find controls in the page # # @example # window(:title => /Title of Some Window/) # # @param [Hash] locator for the top-level window that hosts the page # def window(locator) define_method(:which_window) do locator end end def required_controls(*controls) define_method(:wait_until_present) do |context=nil| controls.each do |control| super() begin wait_until { send("#{control}_view").exist? } rescue Mohawk::Waiter::WaitTimeout raise "Control #{control} was not found on the #{self.class} screen" end end end end # # Defines a locator indicating a child container that is a descendant of # the top-level window # # @example # parent(:id => 'someOtherContainer') # # @param [Hash] locator for a more specific parent container # def parent(locator) define_method(:parent_container) do locator end end # # Generates methods to enter text into a text field, get its value # and clear the text field # # @example # text(:first_name, :id => 'textFieldId') # # will generate 'first_name', 'first_name=' and 'clear_first_name' methods # # @param [String] name used for the generated methods # @param [Hash] locator for how the text is found # def text(name, locator) define_method("#{name}") do adapter.text(locator).value end define_method("#{name}=") do |text| adapter.text(locator).set text end define_method("clear_#{name}") do adapter.text(locator).clear end define_method("enter_#{name}") do |text| adapter.text(locator).enter text end define_method("#{name}_view") do adapter.text(locator).view end end # # Generates methods to click on a button as well as get the value of # the button text # # @example # button(:close, :value => '&Close') # # will generate 'close' and 'close_value' methods # # @param [String] name used for the generated methods # @param [Hash] locator for how the button is found # def button(name, locator) define_method("#{name}") do |&block| adapter.button(locator).click &block end define_method("#{name}_value") do adapter.button(locator).value end define_method("#{name}_view") do adapter.button(locator).view end end # # Generates methods to get the value of a combo box, set the selected # item by both index and value as well as to see the available options # # @example # combo_box(:status, :id => 'statusComboBox') # # will generate 'status', 'status=', 'select_status', and 'status_options' methods # # @param [String] name used for the generated methods # @param [Hash] locator for how the combo box is found # # === Aliases # * combobox # * dropdown / drop_down # def combo_box(name, locator) define_method("#{name}") do adapter.combo(locator).value end define_method("#{name}=") do |item| adapter.combo(locator).with(:combo_box).set item end alias_method "select_#{name}", "#{name}=" define_method("#{name}_options") do adapter.combo(locator).options end define_method("#{name}_view") do adapter.combo(locator).view end end # # Generates methods to get the value of a list box, set the selected # item by both index and value as well as to see the available options # # @example # select_list(:status, :id => 'statusListBox') # # will generate 'status', 'status_selections', 'status=', 'select_status','clear_status' and 'status_options' methods # # @param [String] name used for the generated methods # @param [Hash] locator for how the list box is found # # === Aliases # * selectlist # * list_box # def select_list(name, locator) define_method("#{name}") do adapter.select_list(locator).value end define_method("clear_#{name}") do |item| adapter.select_list(locator).clear item end define_method("#{name}_selections") do adapter.select_list(locator).values end define_method("#{name}=") do |item| adapter.select_list(locator).set item end alias_method "select_#{name}", "#{name}=" define_method("#{name}_options") do adapter.select_list(locator).options end define_method("#{name}_view") do adapter.select_list(locator).view end end # # Generates methods to get/set the value of a checkbox as well as # to get the text value of the control # # @example # checkbox(:include, :id => 'checkBoxId') # # will generate 'include', 'include=' and 'include_value' methods # # @param [String] name used for the generated methods # @param [Hash] locator for how the checkbox is found # def checkbox(name, locator) define_method("#{name}") do adapter.checkbox(locator).checked? end define_method("#{name}=") do |should_check| adapter.checkbox(locator).set_check should_check end define_method("#{name}_value") do adapter.checkbox(locator).value end define_method("#{name}_view") do adapter.checkbox(locator).view end end # # Generates methods to set a radio button as well as see if one # is selected # # @example # radio(:morning, :id => 'morningRadio') # # will generate 'morning' and 'morning?' methods # # @param [String] name used for the generated methods # @param [Hash] locator for how the radio is found # def radio(name, locator) define_method("#{name}") do adapter.radio(locator).set end define_method("#{name}?") do adapter.radio(locator).set? end define_method("#{name}_view") do adapter.radio(locator).view end end # # Generates methods to get the value of a label control # # @example # label(:login_info, :id => 'loginInfoLabel') # # will generate a 'login_info' method # # @param [String] name used for the generated methods # @param [Hash] locator for how the label is found # def label(name, locator) define_method("#{name}") do adapter.label(locator).value end define_method("#{name}_view") do adapter.label(locator).view end end # # Generates methods to work with link controls # # @example # link(:send_info_link, :id => 'sendInfoId') # # will generate 'send_info_link_text' and 'click_send_info_link' methods # # @param [String] name used for the generated methods # @param [Hash] locator for how the label is found # def link(name, locator) define_method("#{name}_text") do adapter.link(locator).value end define_method("click_#{name}") do adapter.link(locator).click end define_method("#{name}_view") do adapter.link(locator).view end end # Generates methods to work with menu items # # @example # menu_item(:some_menu_item, :path => ["Path", "To", "A", "Menu Item"]) # # will generate a 'some_menu_item' method to select a menu item # # @param [String] name used for the generated methods # @param [Hash] locator for how the label is found # def menu_item(name, locator) define_method("click_#{name}") do adapter.menu_item(locator).click end alias_method "#{name}", "click_#{name}" end # Generates methods for working with table or list view controls # # @example # table(:some_table, :id => "tableId") # # will generate 'some_table', 'some_table=', 'some_table_headers', 'select_some_table', 'clear_some_table', # # find_some_table and 'some_table_view' methods to get an Enumerable of table rows, # # select a table item, clear a table item, return all of the headers and get the raw view # # @param [String] name used for the generated methods # @param [Hash] locator for how the label is found # # === Aliases # * listview # * list_view # def table(name, locator) define_method("#{name}") do adapter.table(locator) end define_method("#{name}=") do |which_item| adapter.table(locator).select which_item end define_method("add_#{name}") do |hash_info| adapter.table(locator).add hash_info end define_method("select_#{name}") do |hash_info| adapter.table(locator).select hash_info end define_method("find_#{name}") do |hash_info| adapter.table(locator).find_row_with hash_info end define_method("clear_#{name}") do |hash_info| adapter.table(locator).clear hash_info end define_method("#{name}_headers") do adapter.table(locator).headers end define_method("#{name}_view") do adapter.table(locator).view end end # Generates methods for working with tree view controls # # @example # tree_view(:tree, :id => "treeId") # # will generate 'tree', 'tree=', 'tree_items', 'expand_tree_item' and 'collapse_tree_item' # # methods to get the tree value, set the tree value (index or string), get all of the # # items, expand an item (index or string) and collapse an item (index or string) # # @param [String] name used for the generated methods # @param [Hash] locator for how the label is found # # === Aliases # * treeview # * tree # def tree_view(name, locator) define_method("#{name}") do adapter.tree_view(locator).value end define_method("#{name}=") do |which_item| adapter.tree_view(locator).select which_item end define_method("#{name}_items") do adapter.tree_view(locator).items end define_method("expand_#{name}_item") do |which_item| adapter.tree_view(locator).expand which_item end define_method("collapse_#{name}_item") do |which_item| adapter.tree_view(locator).collapse which_item end define_method("#{name}_view") do adapter.tree_view(locator).view end end # Generates methods for working with spinner controls # # @example # spinner(:age, :id => "ageId") # # will generate 'age', 'age=' methods to get the spinner value and # # set the spinner value. # # @param [String] name used for the generated methods # @param [Hash] locator for how the spinner control is found # def spinner(name, locator) define_method(name) do adapter.spinner(locator).value end define_method("#{name}=") do |value| adapter.spinner(locator).value = value end define_method("increment_#{name}") do adapter.spinner(locator).increment end define_method("decrement_#{name}") do adapter.spinner(locator).decrement end define_method("#{name}_view") do adapter.spinner(locator).view end end # Generates methods for working with tab controls # # @example # tabs(:tab, :id => "tableId") # # will generate 'tab', 'tab=' and 'tab_items' methods to get the current tab, # # set the currently selected tab (Fixnum, String or RegEx) and to get the # # available tabs to be selected # # @param [String] name used for the generated methods # @param [Hash] locator for how the tab control is found # def tabs(name, locator) define_method(name) do adapter.tab_control(locator).value end define_method("#{name}=") do |which| adapter.tab_control(locator).selected_tab = which end define_method("#{name}_items") do adapter.tab_control(locator).items end define_method("#{name}_view") do adapter.tab_control(locator) end end def control(name, locator) define_method("#{name}_value") do adapter.value_control(locator).value end define_method("#{name}=") do |value| adapter.value_control(locator).set value end define_method("click_#{name}") do |&block| adapter.value_control(locator).click &block end define_method("#{name}_view") do adapter.value_control(locator).view end end # combo_box aliases alias_method :combobox, :combo_box alias_method :dropdown, :combo_box alias_method :drop_down, :combo_box # select_list aliases alias_method :selectlist, :select_list alias_method :list_box, :select_list # table aliases alias_method :listview, :table alias_method :list_view, :table # tree_view aliases alias_method :treeview, :tree_view alias_method :tree, :tree_view end end
true
43c009e586e0654fc0683274dd0ef894c7b4419c
Ruby
webguyian/nanoblog
/lib/helpers/blogging.rb
UTF-8
176
2.78125
3
[]
no_license
require 'time' def grouped_articles sorted_articles.group_by do |a| [ Time.parse(a[:created_at]).strftime("%B"), Time.parse(a[:created_at]).year ] end.sort.reverse end
true
82add4a33e90100fdf42917e0e3110c6bcb72704
Ruby
joshmrallen/ruby-enumerables-reverse-each-word-lab-nyc-web-030920
/reverse_each_word.rb
UTF-8
210
3.703125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def reverse_each_word(string) string_array = string.split reversed_words = string_array.collect {|word| word.reverse} reversed_string = reversed_words.join(" ") return reversed_string end
true
e340003a78e00cc9de0fdf9ef65eb564bed0e8cc
Ruby
essa/portwarp
/lib/portwarp/utils.rb
UTF-8
1,989
2.546875
3
[ "MIT" ]
permissive
require 'net/https' module PortWarp module Utils def start_http(url_str, verb, &block) url = URI.parse(url_str) http = Net::HTTP.new(url.host, url.port) http.use_ssl = true if url.scheme == 'https' http.verify_mode = OpenSSL::SSL::VERIFY_NONE if $options['ssl-verify-none'] 5.times do $log.debug "starting http #{verb} #{url_str}" begin http.start do |http| $log.debug "started http #{verb} #{url_str}" v = Net::HTTP.const_get(verb) req = v.new(url.path) block.call(http, req) end rescue Errno::ECONNREFUSED $log.warn "error on http #{verb} #{url_str}" p $! sleep 1 $log.warn "retry on http #{verb} #{url_str}" end end end def socket_to_piping(sock, url) i_pipe, o_pipe = IO.pipe t1 = Thread.start do begin while true buf = sock.readpartial(1024) #$log.debug "putting to #{url} #{buf}" o_pipe.write buf o_pipe.flush end rescue EOFError end $log.debug "reading from socket end" end t2 = Thread.start do $log.debug "putting to #{url} start" start_http(url, :Put) do |http, req| req.body_stream = i_pipe req["Transfer-Encoding"] = "chunked" http.request(req) end $log.debug "putting to #{url} end" end [t1, t2] end def piping_to_socket(url, sock) t1 = Thread.start do start_http(url, :Get) do |http, req| $log.debug "getting from #{url} start" http.request req do |response| response.read_body do |chunk| #$log.debug "getting from #{url} #{chunk}" sock.write chunk sock.flush end end end $log.debug "getting from #{url} end" end [t1] end end end
true
4411f81bf2b108e96fe487b7416af72c31d9ddc6
Ruby
nassimbka/rails-longest-word-game
/app/controllers/games_controller.rb
UTF-8
1,947
3.1875
3
[]
no_license
# Fuck Rubocop require 'open-uri' require 'json' class GamesController < ApplicationController def new @letters = [] 10.times do @letters << ('A'..'Z').to_a.sample end end def score @attempt = params[:word] @grid = params[:letters] @game_result = score_and_message(@attempt, @grid) end private def included?(attempt, grid) attempt.upcase!.chars.all? { |letter| attempt.count(letter) <= grid.count(letter) } end def english_word?(word) url = "https://wagon-dictionary.herokuapp.com/#{word}" serialized_spellcheck_result = open(url).read spellcheck_result = JSON.parse(serialized_spellcheck_result) spellcheck_result['found'] ? true : false end def score_and_message(attempt, grid) if included?(attempt, grid) if !english_word?(attempt) [0, 'Not an English word!'] else # score = compute_score(attempt, time) # [score, 'Well done!'] "Congratulations! #{attempt} is a valid English word!" end else [0, 'Not in the grid!'] end end end ######################### # def included?(attempt, grid) # attempt.upcase!.chars.all? { |letter| attempt.count(letter) <= grid.count(letter) } # end # # check presence des lettres dans la grille proposee # def compute_score(attempt, time) # time > 20 ? 0 : attempt.length * 5 / time # end # # calcul du score OK # def english_word?(word) # url = "https://wagon-dictionary.herokuapp.com/#{word}" # serialized_spellcheck_result = open(url).read # spellcheck_result = JSON.parse(serialized_spellcheck_result) # spellcheck_result["found"] ? true : false # end # def score_and_message(attempt, grid, time) # if included?(attempt, grid) # if !english_word?(attempt) # [0, 'Not an English word!'] # else # score = compute_score(attempt, time) # [score, 'Well done!'] # end # else # [0, 'Not in the grid!'] # end # end
true
fa286bc83b0ae94ded8519f1b7c1617b020dd3be
Ruby
medericgb/18-08-2021
/book.rb
UTF-8
566
3.671875
4
[]
no_license
class Book attr_accessor :title, :author def initialize(title, author) @title = title @author = author end def title p @title end def author p @author end def get_title p "Title: #{@title}" end def get_author p "Author: #{@author}" end end pp = Book.new("Pride and Prejudice", "Jane Austen") h = Book.new("Hamlet", " William Shakespeare") wp = Book.new("War and Peace", "Leo Tolstoy") hp = Book.new("Harry Potter", "J.K. Rowling") hp.title # "Harry Potter" hp.author # "J.K. Rowling" hp.get_title # "Title: Harry Potter" hp.get_author # "Author: J.K. Rowling"
true
c73eed3925cbed291fd4840dd1ca9be3db0f5ed1
Ruby
mfeniseycopes/the-dba
/lib/associatable.rb
UTF-8
2,740
3
3
[]
no_license
require_relative 'searchable' require 'active_support/inflector' # base AssocOptions class class AssocOptions attr_accessor( :foreign_key, :class_name, :primary_key ) # create new AssocOptions instance with name and options def initialize(name, custom_options = {}) # custom_options need not define all options options = defaults(name) options.merge!(custom_options) if custom_options.is_a?(Hash) options.each do |option, value| self.send("#{option}=", value) end end # provides access to the class attributes, methods def model_class class_name.constantize end end # creates belongs_to association options class BelongsToOptions < AssocOptions def defaults(name) { class_name: name.to_s.camelcase, foreign_key: "#{name}_id".to_sym, primary_key: :id, } end end # creates has_many association options class HasManyOptions < AssocOptions def initialize(name, klass, custom_options = {}) options = defaults(name, klass) options.merge!(custom_options) if custom_options.is_a?(Hash) options.each do |option, value| self.send("#{option}=", value) end end def defaults(name, klass) { class_name: name.to_s.camelcase.singularize, foreign_key: "#{klass.downcase}_id".to_sym, primary_key: :id, } end end # creates association instance methods module Associatable # creates an instance method on the class by the same name as the provided association name, returns instance matching association def belongs_to(name, options = {}) self.assoc_options[name] = BelongsToOptions.new(name, options) define_method(name) do options = self.class.assoc_options[name] key_val = self.send(options.foreign_key) options .model_class .where(options.primary_key => key_val) .first end end # creates an instance method on the class by the same name as the provided association name, returns instance of all matching associations def has_many(name, options = {}) self.assoc_options[name] = HasManyOptions.new(name, self.name, options) define_method(name) do options = self.class.assoc_options[name] key_val = self.send(options.primary_key) options .model_class .where(options.foreign_key => key_val) end end # creates an instance method on the class by the same name as the provided association name, returns instance matching through association def has_one_through(name, through_name, source_name) self.send(:define_method, name) do self.send(through_name).send(source_name) end end def assoc_options @assoc_options ||= {} @assoc_options end end
true
384f8446ae39d2ad65e9e456e7616e25788db0ce
Ruby
davidtadams/advent-of-code
/2020/day_9/part2.rb
UTF-8
630
3.3125
3
[]
no_license
# frozen_string_literal: true input = File.read('./input.txt').split("\n").map(&:to_i) invalid_number = 85_848_519 current_index = 0 contiguous_range = [] while current_index < input.size sum = 0 search_range = input[current_index..] end_index = nil search_range.each_with_index do |number, index| sum += number if sum == invalid_number end_index = current_index + index break elsif sum > invalid_number break end end if end_index contiguous_range = input[current_index..end_index] break end current_index += 1 end puts contiguous_range.max + contiguous_range.min
true
85975c600e168ebf438d5c61c52776b05129fa9b
Ruby
CorainChicago/traveling_salesman
/test/traveling_salesman_test.rb
UTF-8
1,025
2.96875
3
[ "MIT" ]
permissive
require 'minitest/autorun' require 'traveling_salesman' class TravelingSalesmanTest < Minitest::Test class FirstCheck < Minitest::Test def setup @cities = [[1, 2], [3, 4], [8, 7], [10, 12], [2, 4]] @tsp = TravelingSalesman.new(@cities) @expected = [[3, 4], [8, 7], [10, 12], [2, 4], [1, 2]] end def tear_down end def test_distribution assert_equal 32.00, @tsp.dist.round(2) end def test_route assert_equal (@tsp.route == @expected || @tsp.route == @expected.reverse), true end end class SecondCheck < Minitest::Test def setup @cities = [[1,1], [8,4], [10, 11], [4, 5], [3,3], [5,6], [3,2]] @tsp = TravelingSalesman.new(@cities) @answer_route = [[1, 1], [3, 3], [4, 5], [5, 6], [10, 11], [8, 4], [3, 2]] end def test_distribution assert_equal 31.23, @tsp.dist.round(2) end def test_route assert_equal (@tsp.route == @answer_route || @tsp.route == @answer_route.reverse), true end end end
true
a1260935122f525e35743138904145781a1cd752
Ruby
onkis/stativus-rb
/tests/add_state.rb
UTF-8
1,291
2.90625
3
[ "MIT" ]
permissive
require 'test/unit' require Dir.pwd()+'/tests/test_states' class AddState < Test::Unit::TestCase def setup @statechart = Stativus::Statechart.new @statechart.add_state(A) @statechart.add_state(B) @statechart.add_state(C) @statechart.start("B") @statechart.goto_state("B", Stativus::DEFAULT_TREE) @statechart.goto_state("C", Stativus::DEFAULT_TREE) @default_tree = @statechart.all_states[Stativus::DEFAULT_TREE] end #end setup def test_states_were_added assert(true, "Sanity check") assert_equal(1, @statechart.all_states.keys.length, "should have one tree") assert_equal(3, @statechart.all_states[Stativus::DEFAULT_TREE].keys.length, "should have 3 states in default tree") assert_instance_of(A, @default_tree["A"], "should have an A") assert_instance_of(B, @default_tree["B"], "should have an B") assert_instance_of(C, @default_tree["C"], "should have an C") end def test_state_has_proper_settings a = @default_tree["A"] b = @default_tree["B"] assert(a.has_concurrent_substates, "a should have concurrent sub states") assert_equal("A", b.parent_state, "a is the parent of B") assert_equal(["B", "C"], a.substates, "a should have 2 substates") end end
true
162e9af79000146238fd13693e40b161f25d3894
Ruby
hrdwdmrbl/e-shipper-ruby
/test/unit/quote_test.rb
UTF-8
1,498
2.625
3
[ "MIT" ]
permissive
require File.expand_path("#{File.dirname(__FILE__)}/../test_helper") class QuoteTest < MiniTest::Test def test_valid_quote quote = EShipper::Quote.new({:service_id => '123', :service_name => 'fake service'}) assert quote.validate! assert_equal '123', quote.service_id assert_equal 'fake service', quote.service_name end def test_invalid_quote quote = EShipper::Quote.new assert_raise(ArgumentError) { quote.validate! } quote = EShipper::Quote.new({:invalid => "invalid"}) assert_raise(ArgumentError) { quote.validate! } end def test_description_render_html_of_the_content_of_a_quote quote = EShipper::Quote.new({:service_id => '123', :service_name => 'fake service', :service_id => '4', :service_name => 'puralator express', :transport_mode => 'plane', :transit_days => '2', :currency => 'CAD', :base_charge => '4.12', :fuel_surcharge => '2.0', :total_charge => '6.12' }) html = quote.description assert html.include?('plane') assert html.include?('2') assert html.include?('CAD') assert html.include?('4.12') assert html.include?('2.0') assert html.include?('6.12') refute html.include?('fake service') quote_with_empty_attr = EShipper::Quote.new({:service_id => '123', :service_name => 'fake service', :service_id => '4', :service_name => 'puralator express', :transport_mode => ''}) html = quote_with_empty_attr.description refute html.include?('transport_mode') end end
true
8bf6514d2f80e20afa3bfe9f896d5dd0b7f23ece
Ruby
patmccler/ruby-collaborating-objects-lab-pca-001
/lib/song.rb
UTF-8
519
3.140625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Song attr_accessor :name, :artist @@all = [] def initialize name @name = name @@all << self end def artist_name @artist ? @artist.name : nil end def self.all @@all end def artist_name=(name) @artist = Artist.find_or_create_by_name name end def self.new_by_filename(filename) parse = /^(.*)\s\-\s(.*)\s\-\s(.*)\./.match(filename).captures artist = parse[0] song_name = parse[1] song = new(song_name) song.artist_name = artist song end end
true
4373570b80f7b21ac9ba4125ae454dd0096a035c
Ruby
codefoundry/svn
/lib/svn/apr_utils.rb
UTF-8
8,233
2.6875
3
[ "Apache-2.0" ]
permissive
require 'rubygems' require 'ffi' module Svn #:nodoc: class AprHash < FFI::AutoPointer # when used as key length, indicates that string length should be used HASH_KEY_STRING = -1 include Enumerable attr_accessor :keys_null_terminated alias_method :keys_null_terminated?, :keys_null_terminated def initialize( ptr, key_type, val_type, keys_null_terminated=true) super( ptr ) @key_type = key_type @val_type = val_type @pointers = [] @keys_null_terminated = keys_null_terminated end class << self # creates a new apr_hash_t that contains +contents+, if given def create( key_type, val_type, pool=RootPool ) ptr = C.create( pool ) new( ptr, key_type, val_type ) end def create_from( rb_hash, key_type, val_type, pool=RootPool ) create( key_type, val_type, pool ).copy_from( rb_hash ) end def release( ptr ) # memory will be released with the allocation pool end end module C extend FFI::Library ffi_lib ['libapr-1', 'libapr-1.so.0'] typedef :pointer, :index typedef :pointer, :out_pointer typedef :long, :apr_ssize typedef Pool, :pool typedef AprHash, :hash # lifecycle functions # returns a :pointer instead of a :hash because AprHash#create needs to # add extra args to the ruby instantiation attach_function :create, :apr_hash_make, [ :pool ], :pointer # pool accessor -- returns a Pointer instead of a Pool because Pool # objects will destroy the pool when they are garbage collected. If the # pool was created in SVN, we should never destroy it and if the pool was # created elsewhere, then we should let the original instance destroy it. # This means that the function here should not actually return a Pool. attach_function :pool, :apr_hash_pool_get, [ :hash ], :pointer # size attach_function :count, :apr_hash_count, [ :hash ], :uint # getter/setter methods attach_function :get, :apr_hash_get, # hash key klen [ :hash, :pointer, :apr_ssize ], :pointer attach_function :set, :apr_hash_set, # hash key klen val (NULL = delete entry) [ :hash, :pointer, :apr_ssize, :pointer ], :void # iteration functions attach_function :first, :apr_hash_first, [ :pool, :hash ], :index attach_function :next, :apr_hash_next, [ :index ], :index attach_function :this, :apr_hash_this, [ :index, :out_pointer, :out_pointer, :out_pointer ], :void end # use the above C module for the source of bound functions bind_to C # bound method definitions bind :size, :to => :count # because pool returns a Pointer and not a Pool as is expected, make it # private so others can't use it. bind :pool private :pool def each_pair # outgoing pointers for keys and values key_ptr = FFI::MemoryPointer.new( :pointer ) # apr_ssize_t => ssize_t => platform-specific long len_ptr = FFI::MemoryPointer.new( :long ) val_ptr = FFI::MemoryPointer.new( :pointer ) # initialize a hash index to the first entry iter = C.first( pool, self ) while !iter.null? # get the key, key length, and val C.this( iter, key_ptr, len_ptr, val_ptr ) # read the key key_len = len_ptr.read_long key = Utils.content_for( key_ptr.read_pointer, @key_type, key_len ) # yield the key and value yield key, Utils.content_for( val_ptr.read_pointer, @val_type ) if block_given? # advance to the next iteration iter = C.next( iter ) end end def []( key ) val = nil # keep val in scope if key.is_a?( String ) && keys_null_terminated? val = C.get( self, key, HASH_KEY_STRING ) elsif key.respond_to? :size val = C.get( self, key, key.size ) elsif key.respond_to? :length val = C.get( self, key, key.length ) else raise ArgumentError, "Invalid key #{key}: cannot determine length" end Utils.content_for( val, @val_type ) end def []=( key, val ) val_ptr = Utils.pointer_for( val, @val_type ) # because the pointers passed in are referenced in native code, keep # track of the pointers so they aren't garbage collected until this hash # is destroyed @pointers << val_ptr if key.is_a?( String ) && keys_null_terminated? C.set( self, key, HASH_KEY_STRING, val_ptr ) elsif key.respond_to? :size C.set( self, key, key.size, val_ptr ) elsif key.respond_to? :length C.set( self, key, key.length, val_ptr ) else raise ArgumentError, "Invalid key #{key}: cannot determine length" end val end def copy_from( rb_hash ) rb_hash.each_pair do |key, val| self[ key ] = val end self end def to_h rb_hash = {} each_pair do |key, val| rb_hash[ key ] = val end rb_hash end end class AprArray < FFI::AutoPointer include Enumerable def initialize( ptr, type ) super( ptr ) @type = type @pointers = [] end class << self # creates a new AprArray of +nelts+ elements of +type+; allocation is done # in +pool+, which defaults to Svn::RootPool def create( type, nelts, pool=RootPool ) ptr = C.create( pool, nelts, FFI::Pointer.size ) new( ptr, type ) end def create_from( rb_arr, type, pool=RootPool ) create( type, rb_arr.size ).copy_from( rb_arr ) end def release # memory will be released with the allocation pool end end module C extend FFI::Library ffi_lib ['libapr-1', 'libapr-1.so.0'] typedef :pointer, :index typedef :pointer, :out_pointer typedef :long, :apr_ssize typedef Pool, :pool typedef AprArray, :array # allocation # returns a :pointer instead of a :array because AprArray#create needs to # add extra args to the ruby instantiation attach_function :create, :apr_array_make, [ :pool, :int, :int ], :pointer # empty? attach_function :is_empty, :apr_is_empty_array, [ :array ], :int # modifier methods attach_function :push, :apr_array_push, [ :array ], :pointer attach_function :pop, :apr_array_pop, [ :array ], :pointer end # helper procs for method binding test_c_true = Proc.new { |i| i == 1 } # use the above C module for the source of bound functions bind_to C # bound method definitions bind :empty?, :to => :is_empty, :before_return => test_c_true def push( el ) # turn element into a pointer ptr = Utils.pointer_for( el, @type ) # get the array element location and write ptr there location = C.push( self ) location.write_pointer( ptr ) # because the pointers passed in are referenced in native code, keep # track of the pointers so they aren't garbage collected until this hash # is destroyed @pointers << ptr el end alias_method :add, :push alias_method :<<, :push def copy_from( arr ) arr.each do |el| self << el end self end def pop location = C.pop( self ) Utils.content_for( location.read_pointer, @type ) end # these are commented out because they don't work. it doesn't look like APR # array accesses happen this way. # def []( num ) # num = num.to_i # Utils.content_for( get_pointer( num * FFI::Pointer.size ), @type ) # end # # def []=( num, val ) # num = num.to_i # # ptr = Utils.pointer_for( val, @type ) # put_pointer( num * FFI::Pointer.size, ptr ) # # val # end end end
true
3c69db68fe5f44c5dc897f5b224b20b0886d74ee
Ruby
markj9/econ_view
/lib/econ_view/rdcg_indicator.rb
UTF-8
512
2.65625
3
[]
no_license
module EconView class RDCGIndicator < EconomicIndicator DOMESTIC_CREDIT_GROWTH = :"sodd.." def compute_value(country) domestic_credit_growth = courier.measurement_for(DOMESTIC_CREDIT_GROWTH, country) cpi = courier.measurement_for(CPI, country) if !valid_measurement?(domestic_credit_growth) || !valid_measurement?(cpi) return nil end result = (domestic_credit_growth.most_recent_value.to_f/100 + 1)/(cpi.most_recent_value.to_f/100 + 1) * 100 -100 result.round(1) end end end
true
b3414565d57a82ba588ab6a194e7e05d7de81438
Ruby
spy1031/simple-twitter
/app/models/tweet.rb
UTF-8
351
2.515625
3
[]
no_license
class Tweet < ApplicationRecord validates_length_of :description, maximum: 140 belongs_to :user ,counter_cache: true has_many :replies ,dependent: :destroy has_many :likes ,dependent: :destroy has_many :liked_users ,through: :likes,dependent: :destroy ,source: :user def is_like?(user) self.liked_users.include?(user) end end
true
6ba56dedd6b0940678e0fad093f103cdc026bafa
Ruby
DrXyclo/ttt-5-move-rb-online-web-sp-000
/bin/move
UTF-8
357
3.265625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
#!/usr/bin/env ruby require_relative '../lib/move.rb' # Code your CLI Here puts "Welcome to Tic Tac Toe!" board = [" ", " ", " ", " ", " ", " ", " ", " ", " "] display_board(board) puts "Where yould you like to go?" input = gets.strip input_to_index(input) index = input.to_i-1 move(board, index, character = "X") display_board(board)
true
641e7bbb6aff5b8c273fe60cd404fb54c9b85cc6
Ruby
9toon/hacker_rank
/spec/sherlock_and_anagrams_spec.rb
UTF-8
378
2.625
3
[]
no_license
require_relative "../problem/sherlock_and_anagrams" describe "Problem sherlock_and_anagrams" do it { expect(sherlockAndAnagrams('abba')).to eq(4) } it { expect(sherlockAndAnagrams('abcd')).to eq(0) } it { expect(sherlockAndAnagrams('ifailuhkqq')).to eq(3) } it { expect(sherlockAndAnagrams('kkkk')).to eq(10) } it { expect(sherlockAndAnagrams('cdcd')).to eq(5) } end
true
14d47fae08664ac2966896934db6e30fe235bd40
Ruby
zachalewel/array_practice
/index_of_arrays.rb
UTF-8
291
3.5
4
[]
no_license
#!/usr/bin/env ruby def index_of_first_uniq(array) counts = Hash.new(0) puts counts array.each{|i| counts[i]+= 1} array.each_with_index do |number,index| return index if counts[number] == 1 end return nil end array = [2, 4, 3, 2, 5, 9, 4, 1] puts index_of_first_uniq(array)
true
859e702e1c325cd40686f034a5e539b8530e901e
Ruby
prettymuchbryce/princessfrenzy
/websocketserver/warp.rb
UTF-8
252
2.953125
3
[]
no_license
class Warp WARP_UP = "WARP_UP" WARP_LEFT = "WARP_LEFT" WARP_RIGHT = "WARP_RIGHT" WARP_DOWN = "WARP_DOWN" WARP = "WARP" attr_accessor :x, :y, :level, :type def initialize(x,y,level,type) @x = x; @y = y @level = level @type = type end end
true
1259b626a70d308adaabb820188b85e1c6c409cc
Ruby
sebaquevedo/desafiolatam
/guia_array_hash/ejercicio7.rb
UTF-8
220
3.203125
3
[ "MIT" ]
permissive
require 'pp' a = [1,2,3,9,12,31, "domingo"] b = ["lunes","martes","miércoles","jueves","viernes","sábado","domingo"] #1 concatenar p a.concat b # #2 union p a | b # #3 interseccion p a & b #4 p a.zip b
true
705c0fce8c014657e29a7af4a01933b0f15ff585
Ruby
rowlandjl/LaunchAcademy-Price_of_Admission
/price_of_admission.rb
UTF-8
281
2.953125
3
[]
no_license
adultPrice = 12.80 childPrice = 4.00 numAdults = 4.00 numChild = 2.00 totalAdult = adultPrice * numAdults totalChild = childPrice * numChild finalTotal = totalAdult + totalChild perPerson = finalTotal / numAdults puts "Total: $#{finalTotal}" puts "Total Per Adult: $#{perPerson}"
true
af95295e31a382889e654b74293e9c68701e2eb0
Ruby
stephr3/library
/spec/book_spec.rb
UTF-8
4,143
2.890625
3
[ "MIT" ]
permissive
require('spec_helper') describe(Book) do describe('#title') do it "returns the title of the book" do test_book = Book.new({:id => nil, :title => '19Q4',:author => 'Haruki Murakami', :year_published => '2009'}) expect(test_book.title()).to(eq('19Q4')) end end describe('#id') do it "returns the id of the book" do test_book = Book.new({:id => nil, :title => '19Q4',:author => 'Haruki Murakami', :year_published => '2009'}) test_book.save() expect(test_book.id().class()).to(eq(Fixnum)) end end describe('.all') do it 'is an empty array at first' do expect(Book.all()).to(eq([])) end end describe('#==') do it 'compares two books by title and id to see if they are the same' do test_book1 = Book.new({:id => 1, :title => '19Q4',:author => 'Haruki Murakami', :year_published => '2009'}) test_book2 = Book.new({:id => 1, :title => '19Q4',:author => 'Haruki Murakami', :year_published => '2009'}) test_book1.eql?(test_book2) end end describe('#save') do it 'saves a book' do test_book = Book.new({:id => nil, :title => '19Q4',:author => 'Haruki Murakami', :year_published => '2009'}) test_book.save() expect(Book.all()).to(eq([test_book])) end end describe('.find_by_title') do it 'locates books with a given title' do test_book1 = Book.new({:id => nil, :title => '19Q4',:author => 'Haruki Murakami', :year_published => '2009'}) test_book2 = Book.new({:id => nil, :title => 'Bossypants',:author => 'Tina Fey', :year_published => '2011'}) test_book1.save() test_book2.save() expect(Book.find_by_title(test_book1.title())).to(eq([test_book1])) end end describe('.find_by_author') do it 'locates books with a given author' do test_book1 = Book.new({:id => nil, :title => '19Q4',:author => 'Haruki Murakami', :year_published => '2009'}) test_book2 = Book.new({:id => nil, :title => 'Bossypants',:author => 'Tina Fey', :year_published => '2011'}) test_book1.save() test_book2.save() expect(Book.find_by_author(test_book1.author())).to(eq([test_book1])) end end describe('.find_by_id') do it 'locates a book with a given id' do test_book1 = Book.new({:id => nil, :title => '19Q4',:author => 'Haruki Murakami', :year_published => '2009'}) test_book2 = Book.new({:id => nil, :title => 'Bossypants',:author => 'Tina Fey', :year_published => '2011'}) test_book1.save() test_book2.save() expect(Book.find_by_id(test_book1.id())).to(eq(test_book1)) end end describe('#update') do it 'lets the user update some of the attributes of the book' do test_book1 = Book.new({:id => nil, :title => '19Q4',:author => 'Haruki Murakami', :year_published => '2009'}) test_book1.save() test_book1.update({:author => 'Jo Bob'}) expect(test_book1.author()).to(eq('Jo Bob')) expect(test_book1.title()).to(eq('19Q4')) end it("lets you add patrons to a book") do book = Book.new({:id => nil, :title => '19Q4',:author => 'Haruki Murakami', :year_published => '2009'}) book.save() patron = Patron.new({:id => nil, :name => 'Mr. Rogers',:phone => '503-250-2173'}) patron.save() book.update({:patron_ids => [patron.id()]}) expect(book.patrons()).to(eq([patron])) end end describe("#patrons") do it("returns all of the patrons for a book") do book = Book.new({:id => nil, :title => '19Q4',:author => 'Haruki Murakami', :year_published => '2009'}) book.save() patron = Patron.new({:id => nil, :name => 'Mr. Rogers',:phone => '503-250-2173'}) patron.save() book.update({:patron_ids => [patron.id()]}) expect(book.patrons()).to(eq([patron])) end end describe('#delete') do it 'lets the user delete a book' do test_book1 = Book.new({:id => nil, :title => '19Q4',:author => 'Haruki Murakami', :year_published => '2009'}) test_book2 = Book.new({:id => nil, :title => 'Bossypants',:author => 'Tina Fey', :year_published => '2011'}) test_book1.save() test_book2.save() test_book1.delete() expect(Book.all()).to(eq([test_book2])) end end end
true
e99e5d876f48b25a7af4a00a980b44dbdb552561
Ruby
mcgraths7/TeamValor
/app/services/trader.rb
UTF-8
346
2.609375
3
[]
no_license
class Trader def initialize(trade_request) @trade_request = trade_request end def execute user_1 = @trade_request.give.user user_2 = @trade_request.take.user @trade_request.give.user = user_2 @trade_request.take.user = user_1 @trade_request.give.save @trade_request.take.save end end
true
e94c8485653afc42e1f38f5002420602304dd281
Ruby
RobertoBarros/batch46_cookbook
/cookbook.rb
UTF-8
751
3.453125
3
[]
no_license
require 'csv' class Cookbook def initialize(csv_file) @recipes =[] @csv = csv_file load end def all @recipes end def list(index) @recipes[index] end def add(recipe) @recipes << recipe save end def destroy(index) @recipes.delete_at(index) save end def save CSV.open(@csv, 'wb') do |csv| @recipes.each do |recipe| csv << [recipe.name, recipe.description, recipe.cook_time, recipe.done, recipe.difficulty] end end end private def load CSV.foreach(@csv) do |row| recipe = Recipe.new(row[0], row[1]) recipe.cook_time = row[2] recipe.done = (row[3] == 'true') recipe.difficulty = row[4] @recipes << recipe end end end
true
fa1dd434ac84a0ebbc4952f0f866eda832723d40
Ruby
ngeballe/ls-exercises-challenges
/medium2/other files/other practice/logs.rb
UTF-8
898
4.0625
4
[]
no_license
def time_to_run start_time = Time.now yield end_time = Time.now puts "That took #{end_time - start_time} seconds" end def average_time_to_run(num_times = 5) time_recordings = [] num_times.times do start_time = Time.now yield time_to_run = Time.now - start_time time_recordings << time_to_run end average_time = time_recordings.reduce(:+) / num_times puts "Average time: #{average_time}" end def primes_below(ending_number) result = [] (2..ending_number).each do |num| result << num if prime?(num) end result end def prime?(number) return false if number.even? divisor = 3 while divisor < Math.sqrt(number) # next if divisor.even? return false if number % divisor == 0 # divisor.odd? ? divisor += 2 : divisor += 1 divisor += 2 end true end # time_to_run { primes_below(10**5) } average_time_to_run { primes_below(10**4) }
true
a4a7a661646b95cb1b4af3bffd5b2d50c16678ba
Ruby
rcm32000/denver_puplic_library
/test/library_test.rb
UTF-8
2,944
3.078125
3
[]
no_license
require './test/test_helper' require './lib/library' require './lib/Author' class LibraryTest < Minitest::Test def setup @dpl = Library.new @charlotte_bronte = Author.new({first_name: 'Charlotte', last_name: 'Bronte'}) @charlotte_bronte.add_book('Jane Eyre', 'October 16, 1847') @jane_eyre = @charlotte_bronte.books[0] @charlotte_bronte.add_book('Villette', '1853') @villette = @charlotte_bronte.books[1] @harper_lee = Author.new({first_name: 'Harper', last_name: 'Lee'}) @harper_lee.add_book('To Kill a Mockingbird', 'July 11, 1960') @mockingbird = @harper_lee.books[0] end def test_it_exists assert_instance_of Library, @dpl end def test_it_starts_empty assert_equal [], @dpl.books end def test_it_can_add_a_book assert_equal [], @dpl.books @dpl.add_to_collection(@jane_eyre) assert_instance_of Book, @dpl.books[0] assert_equal 'Jane Eyre', @dpl.books[0].title end def test_it_can_add_multiple_books assert_equal [], @dpl.books @dpl.add_to_collection(@jane_eyre) assert_instance_of Book, @dpl.books[0] assert_equal 'Jane Eyre', @dpl.books[0].title @dpl.add_to_collection(@villette) assert_instance_of Book, @dpl.books[1] assert_equal 'Villette', @dpl.books[1].title @dpl.add_to_collection(@mockingbird) assert_instance_of Book, @dpl.books[2] assert_equal 'To Kill a Mockingbird', @dpl.books[2].title end def test_library_inludes_books_in_collection @dpl.add_to_collection(@jane_eyre) @dpl.add_to_collection(@villette) @dpl.add_to_collection(@mockingbird) assert @dpl.include?('To Kill a Mockingbird') refute @dpl.include?("A Connecticut Yankee in King Arthur's Court") end def test_it_has_a_card_catalogue @dpl.add_to_collection(@jane_eyre) @dpl.add_to_collection(@villette) @dpl.add_to_collection(@mockingbird) assert_equal 'Bronte', @dpl.card_catalogue[0].author_last_name assert_equal 'Bronte', @dpl.card_catalogue[1].author_last_name assert_equal 'Lee', @dpl.card_catalogue[2].author_last_name end def test_find_by_author @dpl.add_to_collection(@jane_eyre) @dpl.add_to_collection(@villette) @dpl.add_to_collection(@mockingbird) title1 = @dpl.find_by_author('Charlotte Bronte')['Charlotte Bronte'][0].title title2 = @dpl.find_by_author('Charlotte Bronte')['Charlotte Bronte'][1].title assert_equal 'Jane Eyre', title1 assert_equal 'Villette', title2 end def test_find_by_pulication_date @dpl.add_to_collection(@jane_eyre) @dpl.add_to_collection(@villette) @dpl.add_to_collection(@mockingbird) title1 = @dpl.find_by_pulication_date('1960')['1960'][0].title title2 = @dpl.find_by_pulication_date('1982')['1982'] assert_equal 'To Kill a Mockingbird', title1 assert_nil title2 end end
true
9eeb382be73ba35c29b9914e4c8b1f31b8508b51
Ruby
djblairjones/Cash_Register
/lib/change_functions.rb
UTF-8
1,594
3.640625
4
[]
no_license
class ChangeMaker def totalchange(price, payment) puts ChangeMaker.class puts payment.class change = (payment - price) return "No Change Required!" if change == 0.0 return "Customer payment is insufficient!" if change < 0 return change end def changedenom(tot_change) dollars = tot_change.to_i.floor(2) cents = ((tot_change.to_i - dollars) * 100).round #hundreds hundreds_num = dollars/100 dollars = dollars - (hundreds_num * 100) #fifties fifties_num = dollars/50 dollars = dollars - (fifties_num * 50) #twenties twenties_num = dollars/20 dollars = dollars - (twenties_num * 20) #tens tens_num = dollars/10 dollars = dollars - (tens_num * 10) #fives fives_num = dollars/5 dollars = dollars - (fives_num * 5) #ones ones_num = dollars #change Quarters quarters_num = cents/25 cents = cents - (quarters_num * 25) #dimes dimes_num = cents/10 cents = cents - (dimes_num * 10) #nickels nickels_num = cents/5 cents = cents - (nickels_num * 5) #pennies pennies_num = cents change_text = "The total Change Amount is: Hundreds: #{hundreds_num} Fifties: #{fifties_num} Twenties: #{twenties_num} Tens: #{tens_num} Fives: #{fifties_num} Ones: #{ones_num} Quarters: #{quarters_num} Dimes: #{dimes_num} Nickels: #{nickels_num} Pennies: #{pennies_num}" return change_text end end
true
311b32a2c43429fd596b6131d5420c8123f0204f
Ruby
hgaard/7-languages
/ruby/hash-tree.rb
UTF-8
660
4
4
[]
no_license
#Change of original tree to accept a hash for initialization class Tree attr_accessor :children, :node_name def initialize(tree) tree.each_pair{|name,children| @node_name = name, @children = children} end def visit_all(&block) visit &block children.each { |c| c.visit_all &block} end def visit(&block) block.call self end end hash_tree = {'Ole' => {'Jakob' => {'Frode' => {}, 'Arne' => {} }, 'Louise' => {'Carla' => {}, 'Oskar' => {} }}} ruby_tree = Tree.new(hash_tree) puts "visiting a node" ruby_tree.visit { |node| puts node.node_name} puts "visiting entire tree" ruby_tree.visit_all { |node| puts node.node_name}
true
f972a476c1b59d09bc74dbba71342c79da455bfb
Ruby
lesliehawk/RB109
/Small_Problems/Easy_4/05.rb
UTF-8
551
4.46875
4
[]
no_license
# Multiples of 3 and 5 # Write a method that searches for all multiples of 3 or 5 # that lie between 1 and some other number, # and then computes the sum of those multiples. # For instance, if the supplied number is 20, # the result should be 98 (3 + 5 + 6 + 9 + 10 + 12 + 15 + 18 + 20). # You may assume that the number passed in is an integer greater than 1. def multisum(number) (1..number).select { |num| num % 3 == 0 || num % 5 == 0 }.sum end # Examples p multisum(3) == 3 p multisum(5) == 8 p multisum(10) == 33 p multisum(1000) == 234168
true
6ba86bb6a5265dea7513c2f04632fe975d842065
Ruby
Hitaishini/ananth-bajaj-backend
/app/models/booking_time_control.rb
UTF-8
2,115
2.65625
3
[]
no_license
class BookingTimeControl < ApplicationRecord def self.book_time_control_method(params) #for Category and Day date = params[:date].to_datetime week_day = params[:date].to_datetime.strftime("%A").downcase.capitalize #for time #days = Time.days_in_month(m, y) time = DateTime.parse(params[:time]).strftime("%H:%M") #current_day = params[:current_date].to_datetime current_day = Date.today.to_datetime #for days prior date_minus = (date - current_day).to_i #Date.today + #for days prior #date_minus = (date.day + date.month * date.year) - (current_day.day + current_day.month * current_day.year) @book_time_control = BookingTimeControl.where('category = ? AND weekday = ?', params[:category], week_day).first if @book_time_control if date_minus >= @book_time_control.days_prior if params[:count] == 0 if time >= @book_time_control.open_time.strftime("%H:%M") && time <= @book_time_control.end_time.strftime("%H:%M") return true #return { message: "go with the booking", status: true } #BookingSlotControl.slot_count(params) else return { message: "Selected time slot not available.Please make a booking between #{@book_time_control.open_time.strftime("%I:%M%p")} to #{@book_time_control.end_time.strftime("%I:%M%p")}", status: false } end else return { message: "Selected booking slot not available. Please make a booking On or After #{week_day}, #{params[:date]} between #{@book_time_control.open_time.strftime("%I:%M%p")} to #{@book_time_control.end_time.strftime("%I:%M%p")}", status: false } end else date_asd = params[:date].to_datetime + 1.day params[:date] = date_asd.strftime("%d-%m-%Y") params[:count] += 1 BookingTimeControl.book_time_control_method(params) end else return {message: "there is no record on this day for this category. please change your date", status: false } end end end
true
8e89145c7f9446b8d2f66da026a918f06e567701
Ruby
DeUsman/object-relations-assessment-web-031317
/app/models/customer.rb
UTF-8
926
3.15625
3
[]
no_license
class Customer < Review attr_accessor :first_name, :last_name, :reviews @@ALL = [] def initialize(first_name, last_name) @first_name = first_name @last_name = last_name @reviews = [] @@ALL.push(self) end def full_name "#{first_name} #{last_name}" end def self.all return @@ALL end def self.find_by_name(name) a = name.split(" ") @@ALL.find do |customer| customer.first_name == a.first && customer.last_name == a.last end end def self.find_all_by_first_name(name) @@ALL.select do |customer| customer.first_name == name end end def self.all_names full_name = [] @@ALL.each do |customer| full_name.push("#{customer.first_name} #{customer.last_name}") end full_name end def add_review(restaurant, content) content = Review.new(self, restaurant) self.reviews.push(content) restaurant.reviews.push(content) end end
true
db8254009089c6fabb69d08c472db643e49503e0
Ruby
mmanousos/ruby-small-problems
/ruby_basics/user_input/ten.rb
UTF-8
4,023
4.75
5
[]
no_license
# 10. Opposites Attract =begin Write a program that requests two integers from the user, adds them together, and then displays the result. Furthermore, insist that one of the integers be positive, and one negative; however, the order in which the two integers are entered does not matter. Do not check for positive/negative requirement until after both integers are entered, and start over if the requirement is not met. You may use the following method to validate input integers: def valid_number?(number_string) number_string.to_i.to_s == number_string && number_string.to_i != 0 end Examples: $ ruby opposites.rb >> Please enter a positive or negative integer: 8 >> Please enter a positive or negative integer: 0 >> Invalid input. Only non-zero integers are allowed. >> Please enter a positive or negative integer: -5 >> 8 + -5 = 3 $ ruby opposites.rb >> Please enter a positive or negative integer: 8 >> Please enter a positive or negative integer: 5 >> Sorry. One integer must be positive, one must be negative. >> Please start over. >> Please enter a positive or negative integer: -7 >> Please enter a positive or negative integer: 5 -7 + 5 = -2 =end =begin # pseudocode define two variables to hold our two user-provided values Can use 2 loops or a nested loop for this because the order doesn't matter. but 2 loops requires checking after each entry instead of waiting for both values to be gathered. loop: ask for two numbers, requesting that one is positive and one is negative assign each to a variable check if one is positive and one is negative. break if true. if false, print an error messgae print the calculation (number1 + number2 = sum) =end def valid_number?(number_string) number_string.to_i.to_s == number_string && number_string.to_i != 0 end num1 = nil num2 = nil # two loops =begin loop { puts '>> What is your first positive or negative number?' num1 = gets.chomp break if valid_number?(num1) puts '>> Invalid input. Only non-zero integers are allowed.' } loop { puts '>> What is your second positive or negative number?' num2 = gets.chomp break if valid_number?(num2) puts '>> Invalid input. Only non-zero integers are allowed.' } num1 = num1.to_i num2 = num2.to_i if (((num1 < 0) || (num2 < 0)) && ((num1 > 0) || (num2 > 0))) # one value is positive and other is negative (but only 1) puts "#{num1} + #{num2} = #{num1 + num2}" =end # nested loop =begin loop { puts '>> Please give me a positive or negative number: ' num1 = gets.chomp if !(valid_number?(num1)) puts '>> Invalid input. Only non-zero integers are allowed.' else loop { puts '>> Please give me a positive or negative number: ' num2 = gets.chomp if valid_number?(num2) break else puts '>> Invalid input. Only non-zero integers are allowed.' end } end num1 = num1.to_i num2 = num2.to_i break if (((num1 < 0) || (num2 < 0)) && ((num1 > 0) || (num2 > 0))) # one value is positive and other is negative (but only 1) } puts "#{num1} + #{num2} = #{num1 + num2}" =end # method (to call within loop) def get_num puts '>> Please give me a positive or negative number: ' num = gets.chomp if !(valid_number?(num)) puts '>> Invalid input. Only non-zero integers are allowed.' end num = num.to_i end # course version of method includes a loop which makes sense so you can keep checking if someone just isn't paying attention that it needs to be an integer. =begin def get_num loop puts '>> Please give me a positive or negative number: ' num = gets.chomp return num = num.to_i if valid_number?(num) puts '>> Invalid input. Only non-zero integers are allowed.' end end =end loop { num1 = get_num num2 = get_num break if (((num1 < 0) || (num2 < 0)) && ((num1 > 0) || (num2 > 0))) # one value is positive and other is negative (but only 1) # break if first_number * second_number < 0 more streamlined way to check for negative number puts '>> Please try again: one number must be positive and one negative.' } puts "#{num1} + #{num2} = #{num1 + num2}"
true
ca0a28bb21723c64a091369e53bf6f6a1509a8da
Ruby
TylerMcKenzie/phase-0
/errors.rb
UTF-8
6,929
4.3125
4
[ "MIT" ]
permissive
# Analyze the Errors # I worked on this challenge [by myself, with: ]. # I spent [#] hours on this challenge. # cartmans_phrase = "Screw you guys " + "I'm going home." # This error was analyzed in the README file. # def cartman_hates(thing) # while true # puts "What's there to hate about #{thing}?" # end # This is a tricky error. The line number may throw you off. # 1. What is the name of the file with the error? # The name of the file is errors.rb # 2. What is the line number where the error occurs? # The line number where the error occurs is 169 # 3. What is the type of error message? # The message type is "syntax error" # 4. What additional information does the interpreter provide about this type of error? # The extra information that is provided is "unexpected end-of-input, expecting keyword_end" # 5. Where is the error in the code? # The error in the code is on line 16 because the method is not closed out correctly # 6. Why did the interpreter give you this error? # The interpreter gave me this error because it reads the rest of the body of this file as part of the method. #south_park # 1. What is the line number where the error occurs? # 34 # 2. What is the type of error message? # in '<main': # 3. What additional information does the interpreter provide about this type of error? # undefined local variable or method 'south_park' for main:Object # 4. Where is the error in the code? # the error is in the code on line 34 as 'south_park' is not defined as a variable or a method # 5. Why did the interpreter give you this error? # the interpreter gave me this error because it had nothing to assign to 'south_park' #cartman() # 1. What is the line number where the error occurs? # 49 # 2. What is the type of error message? # in '<main>' # 3. What additional information does the interpreter provide about this type of error? # undefined method 'cartman' for main:Object # 4. Where is the error in the code? # the error is the line 49 # 5. Why did the interpreter give you this error? # I received this error because there is no method described as 'cartman' # --- error ------------------------------------------------------- # def cartmans_phrase # puts "I'm not fat; I'm big-boned!" # end # cartmans_phrase('I hate Kyle') # 1. What is the line number where the error occurs? # 64 # 2. What is the type of error message? # in 'cartmans_phrase' # 3. What additional information does the interpreter provide about this type of error? # wrong number of arguments (1 for 0) # 4. Where is the error in the code? # in line 68 and the error in the code is that when the method is being run the user input an argument when the method does not call for any variables and simply outputs to the terminal # 5. Why did the interpreter give you this error? # you received this message because the interpreter tries to input 'I hate Kyle' but has nowhere to put it into # --- error ------------------------------------------------------- =begin def cartman_says(offensive_message) puts offensive_message end cartman_says =end # 1. What is the line number where the error occurs? # line 83 # 2. What is the type of error message? # in 'cartman_says' # 3. What additional information does the interpreter provide about this type of error? # wrong number of arguments (o for 1) # 4. Where is the error in the code? # in line 87 in '<main>', and the error is that the method on line 87 is trying to puts the variable to the console but the variable is not defined # 5. Why did the interpreter give you this error? # the interpreter gives you this error because the method asks for 1 argument and the interpreter is given 0 # --- error ------------------------------------------------------- =begin def cartmans_lie(lie, name) puts "#{lie}, #{name}!" end cartmans_lie('A meteor the size of the earth is about to hit Wyoming!') =end # 1. What is the line number where the error occurs? # line 106 # 2. What is the type of error message? # in 'cartmans_lie' # 3. What additional information does the interpreter provide about this type of error? # wrong number of arguments (1 for 2) # 4. Where is the error in the code? # the error is in lin 110 # 5. Why did the interpreter give you this error? # missing another argument # --- error ------------------------------------------------------- # 5 * "Respect my authoritay!" # 1. What is the line number where the error occurs? # line 127 # 2. What is the type of error message? # in '*' # 3. What additional information does the interpreter provide about this type of error? # String can't be coerced into Fixnum (TypeError) # 4. Where is the error in the code? # the errors are in line 127 # 5. Why did the interpreter give you this error? # we received this error because the operation is being done on a string and can't do that... Smart right?... Moreover it needed to be an object or a method or also have another operation done to it, like puts # --- error ------------------------------------------------------- # amount_of_kfc_left = 20/0 # 1. What is the line number where the error occurs? # on line 142 # 2. What is the type of error message? # in '/' # 3. What additional information does the interpreter provide about this type of error? # divided by 0 (ZeroDivisionError) # 4. Where is the error in the code? # in line 142 # 5. Why did the interpreter give you this error? # CANNOT, REPEAT, CANNOT DIVIDE BY 0! WORLD WILL BE DESTROYED!! # --- error ------------------------------------------------------- # require_relative "cartmans_essay.md" # 1. What is the line number where the error occurs? # line 158 # 2. What is the type of error message? # in 'require_relative' # 3. What additional information does the interpreter provide about this type of error? # cannot load such file -- /vagrant/phase-0/cartmans_essay.md (LoadError) # 4. Where is the error in the code? # in line 158 # 5. Why did the interpreter give you this error? # there was no file found so it could not load the file # --- REFLECTION ------------------------------------------------------- # Write your reflection below as a comment. #Which error was the most difficult to read? #The first one got me for like an hour #How did you figure out what the issue with the error was? #I added an 'end' at the end of the file and got no errors(after commenting out everything) #Were you able to determine why each error message happened based on the code? # I did not have too much trouble aside from that first problem this was a good excersise #When you encounter errors in your future code, what process will you follow to help you debug? #I suppose that when I run into errors in my code I'll ask myself these 5 questions to solve my problems.
true
4d3d88d5c12a4d506fe739ad62d558633395ef48
Ruby
NickEdwin/b2-mid-mod
/spec/models/park_spec.rb
UTF-8
674
2.5625
3
[]
no_license
RSpec.describe Park do describe 'validations' do it { should validate_presence_of :name } it { should validate_presence_of :admission_price } end describe 'relationships' do it { should have_many :rides } end describe 'helper method test' do it 'uses #avg_thrill_rating to find average thrill rating of all rides' do park1 = Park.create({name: "Adventure Land", admission_price: 50}) ride1 = park1.rides.create({name: "Scream Machine", thrill_rating: 10, park_id: park1.id}) ride2 = park1.rides.create({name: "Carousel Fun Time", thrill_rating: 5, park_id: park1.id}) expect(park1.avg_thrill_rating).to eq(7.5) end end end
true
f34cdf63463143e52a53588c6b9110f79cfd1325
Ruby
dcousette/learn_to_program
/old_roman_numerals.rb
UTF-8
455
4.09375
4
[]
no_license
#old_roman_numerals.rb def numeralizer number i = 1 v = 5 x = 10 l = 50 c = 100 d = 500 m = 1000 if number > 0 && number <= 3000 puts "This is a start" number % divisor == 0 if else end # take number in # do something # get to numeral_value # numeral_number # number else puts "Please enter a number between 1 and 3000" end end numeralizer 0 numeralizer 3001 numeralizer 2000
true
dabbfafc6cbe74b020167ca09f03054387177bd5
Ruby
alexmcbride/futureprospects
/app/helpers/decisions_helper.rb
UTF-8
1,709
2.53125
3
[]
no_license
# * Name: Alex McBride # * Date: 24/05/2017 # * Project: Future Prospects # Module for decision controller helpers. These are functions that can be called in views. module DecisionsHelper # Displays a decision stage sidebar item. # # @param text [String] the text of the stage. # @param selected [Boolean] whether the stage is selected. # @param completed [Boolean] whether the stage is completed. # @return [String] def decision_stage_item(text, selected, completed=false) content_tag(:div, class: "list-group-item#{' active' if selected}") do concat(text) if selected concat(icon('arrow-circle-right', class: 'pull-right', style: 'font-size: 15pt;')) end if completed concat(icon('check', class: 'pull-right', style: 'color: green; font-size: 18pt;')) end end end # Displays a list item for the decisions controller. # # @param selection [CourseSelection] the course selection to display. # @return [String] the HTML to be displated. def decision_list_item(selection) content_tag(:div, class: 'list-group-item list-group-item-heading', style: 'background-color: #F5F5F5; clear: both;') do yield if block_given? concat(content_tag(:h4, style: 'margin-top: 6px;') do concat(content_tag(:strong, truncate(selection.course.title, length: 60))) concat('&nbsp;'.html_safe) concat(content_tag(:small, selection.course.college.name, style: 'color: #787878;')) end) concat(content_tag(:p, selection.college_offer.nil? ? 'Decision pending...' : selection.college_offer.humanize)) concat(selection.note.present? ? content_tag(:p, selection.note) : '&nbsp;'.html_safe) end end end
true
3c727e08c0eada08dacb1a4472566946e3a155d9
Ruby
ddcunningham/RnGG
/lib/RnGG/game_turn.rb
UTF-8
490
3.03125
3
[]
no_license
require_relative 'player' require_relative 'die' require_relative 'treasure' module RnGG module GameTurn def self.take_turn(player) die = Die.new case die.roll when 1..2 player.blam when 3..4 puts "#{player.name} was skipped." when 5..6 player.heal else puts "OH GOD WHY IS THIS HERE I AM NOT GOOD WITH COMPUTER" end treasure = TreasureTrove.randomloot player.found_loot(treasure) end end end
true
a9435c6484b477f56a4723900f4d30413e654e42
Ruby
ByrneGR/projects
/W3D2/memory_puzzle/game.rb
UTF-8
992
3.65625
4
[]
no_license
require_relative "board.rb" class Game def initialize(player, size=4) @board = Board.new(size) @board.populate @player = player @previous_guess = nil end def make_guess(pos) if @previous_guess.nil? @previous_guess = pos @board.reveal(pos) else if @board[pos] == @board[@previous_guess] @board.reveal(pos) @previous_guess = nil else @board.reveal(pos) p @board.render @board[pos].hide @board[@previous_guess].hide @previous_guess = nil sleep(2) end end end def play until @board.won? p @board.render puts "Enter you guess; Example 0 2" pos = gets.chomp.split.map(&:to_i) self.make_guess(pos) end end end game = Game.new("blahh", 2) game.play
true
be8bf8429e0f3d89099d10a0d000281252945965
Ruby
arunshariharan/trello-cards-search
/start_search.rb
UTF-8
1,702
2.90625
3
[]
no_license
require 'pp' require 'trello' require 'stopwords' require 'net/http' require 'amatch' require_relative 'Configuration/trello_configuration' require_relative 'Configuration/user_configuration' require_relative 'Input/input' require_relative 'Populator/populator' require_relative 'Curator/curator' require_relative 'Matcher/similarity_matcher' require_relative 'Output/output' require_relative 'Status/status' include UserConfiguration include TrelloConfiguration # Set required data and configure Trello UserConfiguration.set_data TrelloConfiguration.start # Retrieve variables to pass onto different classes member_name = UserConfiguration.member_name board_name = UserConfiguration.board_name similarity_value = UserConfiguration.similarity_value entered_name = Input.get @status = Status.new main_thread = Thread.start { # Ask Populator to set the right board populator = Populator.new(member_name, board_name) # Populate lists in the selected board total_lists = populator.populate_lists # Exclude unwanted lists curator = Curator.new(total_lists) curated_lists = curator.curate_lists # Populate cards from selected lists card_list = populator.populate_cards(curated_lists) # Match entered text with curated cards using a similarity matching # Algorithm - here I am passing Levenshtein matcher = SimilarityMatcher.new(card_list, @status) result = matcher.find_distance('levenshtein', entered_name, similarity_value) # Display result to the user Output.display(result) } wait_thread = Thread.start { Output.display_wait_message } wait_sub_thread = Thread.start { Output.display_progress(@status) } main_thread.join wait_thread.join wait_sub_thread.join
true
73d7cf8a73ff18f5329470303d8ea4c6726f0473
Ruby
DJCarlosValdez/curso-web
/ruby/challenges-custom/c1.rb
UTF-8
1,672
4.0625
4
[]
no_license
# def find_duplicates(array) # array2 = [] # array3 = [] # array.each do |x| # if !array2.include?(x) # array2 << x # elsif array2.include?(x) # array3 << x # end # end # p array3 # end # numbers = [1,2,2,3,4,5] # find_duplicates(numbers) #--------------------------------------------------------------------------------------------------------- # def valid_word?(char, word) # array1 = char.sort! # array2 = word.split(//).sort! # if (array1 == array2) # p true # else # p false # end # end # word = "orange" # characters = %w(e n g a r o) # valid_word?(characters, word) #--------------------------------------------------------------------------------------------------------- def no_yelling (string) array1 = string.split(//).reverse! array2 = array1 symbols = "a" array1.each_with_index do |x, i| if x == "!" || x == "?" if !symbols.include?(x) symbols = x end elsif symbols.include?(x) array2.delete_at(1) end end p array2.reverse!.join end no_yelling("What went wrong?????????") #➞ "What went wrong?" no_yelling("Oh my goodness!!!") #➞ "Oh my goodness!" no_yelling("I just!!! can!!! not!!! believe!!! it!!!") #➞ "I just!!! can!!! not!!! believe!!! it!" # Only change repeating punctuation at the end of the sentence. no_yelling("Oh my goodness!") #➞ "Oh my goodness!" # Do not change sentences where there exists only one or zero exclamation marks/question marks. no_yelling("I just cannot believe it.") #➞ "I just cannot believe it."
true
5bc0b8ca88ba822b0c69d3300e8ee2bce20ca442
Ruby
wooisland/LRHW
/ex4.rb
UTF-8
544
3.171875
3
[]
no_license
cars = 100 spance_in_a_car = 4.0 drivers = 30 passengers = 90 cars_not_dirven = cars - drivers cars_driven = drivers carpool_capacity = cars_driven * spance_in_a_car average_passenger_per_car = passengers /cars_driven puts "There are #{cars} available." puts "There are only #{drivers} drivers available." puts "There will be #{cars_not_dirven} emtpy cars today." puts "We can transport #{carpool_capacity} people today." puts "We have #{passengers} passengers to carpool today." puts "We need to put #{average_passenger_per_car} in each car."
true
df6fc5ff9fa8d323ad5d4d5d4de05bcd97b2a8dd
Ruby
carusocr/bcast
/streaming/twitter/harvest_tweet_by_id.rb
UTF-8
692
3.125
3
[]
no_license
# given a single tweet ID, collect associated text # prints Twitter error message if tweet isn't available require 'twitter' abort "Enter numeric Tweet ID." unless ARGV[0] =~ /^[0-9]+$/ tweet_id = ARGV[0] client = Twitter::REST::Client.new do |config| config.consumer_key = "YOUR_CONSUMER_KEY" config.consumer_secret = "YOUR_CONSUMER_SECRET" config.access_token = "YOUR_ACCESS_TOKEN" config.access_token_secret = "YOUR_ACCESS_SECRET" end def collect_single_tweet(tweet_id,client) status = client.status(tweet_id) rescue Twitter::Error => e puts e.message else puts status.text.gsub("\t","").gsub("\n","") end collect_single_tweet(tweet_id,client)
true
075520b3fee1e6e15254a2affcadfc264309b558
Ruby
smoip/wamibrew
/app/services/hops_arrays.rb
UTF-8
480
3.3125
3
[]
no_license
class HopsArrays attr_accessor :hops def initialize(hops) @hops = hops end def hops_to_array hop_ary = [] unless @hops[:aroma].nil? @hops[:aroma].each do |aroma_hash| hop_ary << aroma_hash.to_a end hop_ary = hop_ary.flatten(1) end hop_ary.unshift(@hops[:bittering].to_a[0]) end def hop_names_to_array hops_ary = hops_to_array.flatten.keep_if { |x| x.class == Hop } hops_ary.collect { |hop| hop.name } end end
true
fcd0d994bbaf406c175b35a574c3d3fcc6f98528
Ruby
chriskuck/aoc2020
/day18/main.rb
UTF-8
452
3.15625
3
[]
no_license
require 'pry' require './bad_equation.rb' require './mult_dom_equation.rb' exit(1) unless !ARGV[0].nil? && File.exist?(ARGV[0]) eqs = File.read(ARGV[0]).split("\n") ans = eqs.map do |eq| puts "#{eq} = #{BadEquation.new(eq).eval}" BadEquation.new(eq).eval end puts "Part 1: #{ans.inject(:+)}" binding.pry ans = eqs.map do |eq| puts "#{eq} = #{MultDomEquation.new(eq).eval}" MultDomEquation.new(eq).eval end puts "Part 2: #{ans.inject(:+)}"
true
1895d845a5358de5710fbf6c94222d0191cf5f5f
Ruby
ethanpoole/Linguistic-Explorer
/app/models/search_results/comparisons.rb
UTF-8
1,588
2.609375
3
[ "MIT" ]
permissive
module SearchResults module Comparisons attr_reader :search_comparison def result_rows=(result_rows) self.result_groups = result_rows.group_by { |row| row.parent_id } self.result_groups.values.map! { |row| row.map! { |r| r.child_id }.compact! } @search_comparison = true end def result_rows(parent_attr_names, child_attr_names = []) [].tap do |rows| self.results.each do |result| parent, child = result.parent, result.child next unless parent parent_map = parent.column_map(parent_attr_names) if child.nil? rows << ResultRow.new(parent_map) else rows << ResultRow.new(parent_map, child.column_map(child_attr_names)) end end end end class ResultRow # parent_map is array of [parent_id, attrs*] # child_map is array of [child_id, attrs*] def initialize(parent_map, child_map = []) @parent_map, @child_map = parent_map, child_map end def attrs # include all but first column in map (id) (parent_attrs + child_attrs).compact end def parent_attrs ((@parent_map.slice(1, @parent_map.length)) || []).compact end def child_attrs ((@child_map.slice(1,@child_map.length)) || []).compact end def eql?(result_row) attrs == result_row.attrs end def hash attrs.hash end def parent_id @parent_map[0] end def child_id @child_map[0] end end end end
true
245969379f1b87faa4ef3bc43fe196d2a5b1cdbb
Ruby
factcondenser/leetcode_solutions
/014_longest_common_prefix.rb
UTF-8
642
3.375
3
[]
no_license
# @param {String[]} strs # @return {String} def longest_common_prefix(strs) return '' if strs.nil? || strs.length == 0 prefix = strs.first i = 1 while i < strs.length do while strs[i].index(prefix) != 0 do prefix = prefix[0..-2] end i += 1 end prefix end # @param {String[]} strs # @return {String} # def longest_common_prefix(strs) # return '' if !sxtrs[0] # char = strs[0][0] # new_strs = strs.each_with_object([]) do |str, arr| # break if !str[0] || str[0] != char # arr << str[1, str.length - 1] # end # new_strs&.length == strs.length ? char + longest_common_prefix(new_strs) : '' # end
true
7397b1d0c410d295541512fefd6ee7ed848bfebd
Ruby
delosiliana/thinknetica
/lesson_9/main.rb
UTF-8
9,850
3.453125
3
[]
no_license
require_relative './lib/accessors' require_relative './lib/manufacturer' require_relative './lib/validation' require_relative './lib/instance_counter' require_relative './lib/route' require_relative './lib/station' require_relative './lib/train' require_relative './lib/passenger' require_relative './lib/cargo' require_relative './lib/carriage' require_relative './lib/carriage_cargo' require_relative './lib/carriage_passenger' class Main attr_accessor :station, :trains, :train, :route, :stations, :number, :name, :carriage, :type, :carriages, :num include Validation def initialize @stations = [] @trains = [] @routes = [] @carriages = [] end def menu puts '________________________________________________________________' puts '| |' puts '| Вас приветствует служба управлением поездов и станций |' puts '|Введите пожалуйста номер действия которое вы хотите выполнить:|' puts '| 1 - Создать станцию. |' puts '| 2 - Просмотреть список станций |' puts '| 3 - Просмотреть список поездов на станции |' puts '| 4 - Создать поезд |' puts '| 5 - Прицепить вагон к поезду |' puts '| 6 - Отцепить вагон от поезда |' puts '| 7 - Создать маршрут |' puts '| 8 - Добавить станцию в маршрут |' puts '| 9 - Удалить станцию из маршрута |' puts '| 10 - Назначить маршрут поезду |' puts '| 11 - Переместить поезд по маршруту вперед |' puts '| 12 - Переместить поезд по маршруту назад |' puts '| 13 - Посмотреть данные о поезде |' puts '| 00 - Выход из меню |' puts '|______________________________________________________________|' puts 'Вы выбираете:' input = gets.chomp.to_i case input when 1 create_station when 2 station_list when 3 trains_list when 4 create_train when 5 to_attach_carriage when 6 to_unhook_carriage when 7 create_route when 8 add_station_route when 9 delete_station_route when 10 to_appoint_route when 11 move_forward when 12 move_back when 13 info_train when 0o0 abort else puts 'Вы ввели неправильное значение команды' menu end end private def create_station puts 'Введите название станции: ' name = gets.chomp.capitalize @station = Station.new(name) @stations << station puts "Станция #{name} создана" menu rescue RuntimeError => e puts e.message menu end def station_list stations.each { |station| puts station.name } || 'Станций не существует' end def show_trains trains.each { |train| puts train.number } || 'Поездов пока не существует' end def info_train show_trains puts 'Выберите поезд информация о котором ваc интересует:' selected_train.each_carriage { |carriage| puts carriage.to_s } menu end def trains_list station_list puts 'Выберите станцию на которой хотите посмотреть поезда:' input = gets.chomp.capitalize index = @stations.find_index { |station| station.name == input } current_station = @stations[index] current_station.each_train { |_train| puts "Номер:#{@train.number} тип:#{@train.class} вагонов:#{@train.carriages.size}" } menu end def create_train puts 'Выберите какой поезд вы хотите создать?' puts '1 - пассажирский' puts '2 - грузовой' input = gets.chomp.to_i case input when 1 puts 'Для создания пассажирского поезда, введите номер поезда ' number = gets.chomp @train = Passenger.new(number) @trains << train puts "Поезд номер #{number} пассажирского типа создан" menu when 2 puts 'Для создания грузового поезда, введите номер поезда' number = gets.chomp @train = Cargo.new(number) @trains << train puts "Поезд номер #{number} грузового типа создан" menu end rescue RuntimeError => e puts e.message menu end def invalid_number puts 'Некорректный номер' end def selected_train number = gets.chomp index = @trains.find_index { |train| train.number == number } index.nil? ? invalid_number && menu : @train = @trains[index] end def invalid_name puts 'Неккоретное имя' end def to_attach_carriage menu_carriage puts 'Выберите поезд(по номеру) к которому хотите прицепить вагон:' selected_train.add_carriage(carriage) puts "К #{@train.number} прицеплен вагон #{carriage.class} кол-во вагонов - #{@train.carriages.size}" menu rescue RuntimeError, TypeError => e puts e.message retry end def menu_carriage puts 'Выберите какой вагон вы хотите прицепить?' puts '1 - пассажирский' puts '2 - грузовой' input = gets.chomp.to_i case input when 1 puts 'Для создания пассажирского вагона введите номер вагона' num = gets.chomp puts 'Для создания пассажирского вагона введите количество мест' seats = gets.chomp @carriage = CarriagePassenger.new(num, seats) when 2 puts 'Для создания пассажирского вагона введите номер вагона' num = gets.chomp puts 'Для создания грузового вагона введите объем' capacity = gets.chomp @carriage = CarriageCargo.new(num, capacity) else puts 'Вы ввели неправильный тип вагона' menu end end def to_unhook_carriage puts 'Выберите поезд(по номеру) от которого хотите отцепить вагон:' selected_train.remove_carriage puts "От поезда #{@train.number} отцеплен вагон типа #{@carriage.type}" puts "Кол-во вагонов - #{@train.carriages.size}" menu end def create_route station_list puts 'Выберете начальную станцию маршрута из списка:' input = gets.chomp.capitalize index = @stations.find_index { |station| station.name == input } first = @stations[index] puts 'Выберите конечную станцию маршрута из списка:' input = gets.chomp.capitalize index = @stations.find_index { |station| station.name == input } last = @stations[index] @route = Route.new(first, last) @routes << @route puts "Маршрут #{route.stations} создан" menu rescue RuntimeError, TypeError => e puts e.message retry end def add_station_route station_list puts 'Выберите название станции, которую хотите добавить' input = gets.chomp.capitalize index = @stations.find_index { |station| station.name == input } station = @stations[index] @route.add_station(station) puts "Станция #{station} в маршрут #{route.stations} добавлена " menu end def delete_station_route station_list puts 'Введите название станции, которую хотите удалить' input = gets.chomp.capitalize index = @stations.find_index { |station| station.name == input } station = @stations[index] @route.delete_station(station) puts "Станция #{@station} удалена из маршрута #{route.stations}" menu end def to_appoint_route puts 'Введите номер поезда, к которому хотите присвоить маршрут' selected_train.route_train(route) puts "Поезд #{train.number} имеет маршрут #{route.stations.first.name} - #{route.stations.last.name}" menu end def move_forward puts 'Введите номер поезда, который хотите отправить вперед' selected_train.move_next puts "Поезд #{train.number} прибыл на станцию #{@train.current_station.name}" menu end def move_back puts 'Введите номер поезда, который хотите отправить назад' selected_train.move_previous puts "Поезд #{train.number} прибыл на станцию #{@train.current_station.name}" menu end end
true
49d27b0bb9c5633a110366fb7954e463e58466c2
Ruby
PhilipVigus/oystercard-weds
/lib/oystercard.rb
UTF-8
1,081
3.34375
3
[]
no_license
class Oystercard attr_reader :balance, :min_balance, :entry_station STARTING_BALANCE = 0 CARD_LIMIT = 90 MINIMUM_BALANCE = 1 def initialize(balance = STARTING_BALANCE) @balance = balance @journeys_taken = [] @current_journey = nil end def top_up(num) raise "you cannot top up #{num} as it brings your card over the limit" if @balance + num > CARD_LIMIT @balance += num end def touch_in(station) @current_journey = Journey.new @current_journey.start(station) @entry_station = station if @balance < MINIMUM_BALANCE raise "Insufficient balance to touch in" elsif @balance >= MINIMUM_BALANCE @in_system = true ##get rid of in_system? end end def touch_out(station) deduct @current_journey.finish(station) @journeys_taken << @current_journey @entry_station = nil end def in_journey? if @current_journey.complete? false else true end end def previous_journeys @journeys_taken end private def deduct @balance -= MINIMUM_BALANCE end end
true
cff4ca59e2e01c3eaf43e5e4ecf6722439b55d00
Ruby
amihays/aa-materials
/w1d2/sudoku/board.rb
UTF-8
1,214
3.578125
4
[]
no_license
require_relative "tile.rb" class Board def initialize(grid) @grid = grid end def self.from_file(file_path) lines = File.readlines(file_path).map { |line| line.chomp } values = lines.map { |line| line.split('') } grid = values.map { |row| row.map { |value| Tile.new(value) } } Board.new(grid) end def []=(position,value) @grid[position[0]][position[1]].value = value end def render puts @grid.map { |row| row.map { |tile| tile.to_s }.join(" ") }.join("\n") end def solved? return false if @grid.any? { |row| !section_solved?(row) } return false if @grid.transpose.any? { |column| !section_solved?(column) } return false if squares.any? { |square| !section_solved?(square) } true end def section_solved?(section_array) values = section_array.map { |tile| tile.value.to_i }.sort values == (1..9).to_a end def squares flattened_squares = [] 3.times do |i| row_start = i * 3 3.times do |j| column_start = j * 3 square = @grid.map { |row| row[column_start...column_start + 3] }[row_start...row_start + 3] flattened_squares << square.flatten end end flattened_squares end end
true
61895d1614f74c87ca1932619c9b7aea37476675
Ruby
mviceral/IceSlotController
/BBB_Sampler/DutObj.rb
UTF-8
9,623
2.53125
3
[ "MIT" ]
permissive
# require_relative 'AllDuts' require_relative '../lib/SharedMemory' require_relative '../lib/SharedLib' # ----------------- Bench mark string length so it'll fit on GitHub display without having to scroll ---------------- SetupAtHome_DutObj = false # So we can do some work at home class DutObj FaultyTcu = "Faulty Tcu" def initialize() @statusResponse = Array.new(TOTAL_DUTS_TO_LOOK_AT) @sharedMem = SharedMemory.new() # End of 'def initialize()' end def setTHCPID(keyParam,uart1Param,temParam) tbr = "" # tbr - to be returned uartStatusCmd = "#{keyParam}:\n" uart1Param.write("#{uartStatusCmd}"); # `echo \"w #{uartStatusCmd}\" >> uart.log` sleep(0.01) uartStatusCmd = "#{temParam}\n" b = uartStatusCmd uart1Param.write("#{uartStatusCmd}"); sleep(0.01) # `echo \"w #{uartStatusCmd}\" >> uart.log` return tbr end def self.getTcuStatusV(dutNumParam,uart1Param,gPIO2) getTcuStatus(dutNumParam,uart1Param,gPIO2,"V") end def self.getTcuStatusS(dutNumParam,uart1Param,gPIO2) getTcuStatus(dutNumParam,uart1Param,gPIO2,"S") end def self.getTcuStatus(dutNumParam,uart1Param,gPIO2,singleCharParam) # puts "Checking dutNumParam='#{dutNumParam}' #{__LINE__}-#{__FILE__}" if SetupAtHome_DutObj == true # puts "dutNumParam='#{dutNumParam}' SetupAtHome='#{SetupAtHome}' singleCharParam='#{singleCharParam}' #{__LINE__}-#{__FILE__}" if singleCharParam == "V" tbr = "@25.000,RTD100,p6.00 i0.60 d0.15,mpo255, cso101, V2.2" else heating = "0" rValue = Random.rand(100)+1 if (rValue) > 50 heating = "1" end # puts "rValue='#{rValue}', heating='#{heating}' #{__LINE__}-#{__FILE__}" # tbr = "@#{Random.rand(2)},#{30+Random.rand(3)}.#{Random.rand(1000)},#{70+Random.rand(3)}.#{Random.rand(1000)},#{heating},#{Random.rand(256)},Ok" tbr = "@1,#{30+Random.rand(3)}.#{Random.rand(1000)},#{70+Random.rand(3)}.#{Random.rand(1000)},#{heating},#{Random.rand(256)},Ok" #tbr = "@0,30.376,71.840,1,250,Ok" end return tbr end gPIO2.etsRxSel(dutNumParam) tbr = "" # tbr - to be returned uartStatusCmd = "#{singleCharParam}?\n" uart1Param.write("#{uartStatusCmd}"); keepLooping = true notFoundAtChar = true # # Code block for ensuring that status request is sent and the expected response is received. # line = "" # while keepLooping begin complete_results = Timeout.timeout(2) do # it was 0.1 before keepLooping = true while keepLooping c = uart1Param.readchar if notFoundAtChar # Some funky character sits in the buffer, and this code will not take the data # until the beginning of the character is '@' if c=="@" notFoundAtChar = false line += c end else if c!="\n" line += c else tbr = line line = "" keepLooping = false end end end =begin uart1Param.each_line { |line| tbr = line # puts "dut#{dutNumParam} line='#{line}' #{__LINE__}-#{__FILE__}" # `echo \"r #{line}\" >> uart.log` keepLooping = false # loops out of the keepLooping loop. break if line =~ /^@/ # loops out of the each_line loop. } =end end rescue Timeout::Error # puts "\n\n\n\nTimed out Error. dutNumParam=#{dutNumParam}" # SharedLib.pause "Whacked out","#{__LINE__}-#{__FILE__}" uart1Param.disable # uart1Param variable is now dead cuz it timed out. uart1Param = UARTDevice.new(:UART1, 115200) # replace the dead uart variable. tbr = FaultyTcu =begin # puts "Flushing out ThermalSite uart." keepLooping2 = true while keepLooping2 begin complete_results = Timeout.timeout(1) do uart1Param.each_line { |line| # puts "' -- ${line}" } end rescue Timeout::Error # puts "Done flushing out ThermalSite uart." uart1Param.disable # uart1Param variable is now dead cuz it timed out. uart1Param = UARTDevice.new(:UART1, 115200) # replace the dead uart variable. keepLooping2 = false # loops out of the keepLooping loop. end end uart1Param.write("#{uartStatusCmd}"); # Resend the status request command. # # Place code here for handling hiccups. # =end end =begin # puts "dutNumParam=#{dutNumParam}, tbr=#{tbr} #{__LINE__}-#{__FILE__}" if tbr.force_encoding("UTF-8").ascii_only? return tbr else "" end =end sleep(0.01) # Commenting this line to see if the polling will be faster and the code would still work. # puts "getTcuStatus(#{dutNumParam})='#{tbr}' #{__LINE__}-#{__FILE__}" return tbr #end end def poll(dutNumParam, uart1Param,gPIO2,tcusToSkip,tsdParam) @statusResponse[dutNumParam] = DutObj::getTcuStatusS(dutNumParam, uart1Param,gPIO2) if tsdParam["SlotMode"] == SharedLib::InRunMode #if tsdParam["RanAt"]<=Time.now.to_i # puts "\n\n\n\nRunning the TEST. #{__LINE__}-#{__FILE__}" # @statusResponse[dutNumParam][1] = "0" # tsdParam["RanAt"] += 60 # do it again for another minute. #end #puts "(#{tsdParam["RanAt"]-Time.now.to_i}) dutNumParam='#{dutNumParam}' @statusResponse[dutNumParam]='#{@statusResponse[dutNumParam]}' #{__LINE__}-#{__FILE__}" if @statusResponse[dutNumParam][1] == "0" if SetupAtHome_DutObj == false `echo \"#{Time.new.inspect} dut='#{dutNumParam}' is getting re-blasted. #{__LINE__}-#{__FILE__}\" >> /mnt/card/ErrorLog.txt` # puts "\n\n\n\nExecuted the re-blast. #{__LINE__}-#{__FILE__}" ThermalSiteDevices.setTHCPID(uart1Param,"T",tcusToSkip,tsdParam["T"]) ThermalSiteDevices.setTHCPID(uart1Param,"H",tcusToSkip,tsdParam["H"]) ThermalSiteDevices.setTHCPID(uart1Param,"C",tcusToSkip,tsdParam["C"]) ThermalSiteDevices.setTHCPID(uart1Param,"P",tcusToSkip,tsdParam["P"]) ThermalSiteDevices.setTHCPID(uart1Param,"I",tcusToSkip,tsdParam["I"]) ThermalSiteDevices.setTHCPID(uart1Param,"D",tcusToSkip,tsdParam["D"]) ThermalSiteDevices.setTcuToRunMode(tcusToSkip,gPIO2) end end else end # puts "poll @statusResponse[#{dutNumParam}] = '#{@statusResponse[dutNumParam]}'" end def saveAllData(parentMemory, tcusToSkip, timeNowParam) dutNum = 0; allDutData = ""; while dutNum<TOTAL_DUTS_TO_LOOK_AT do # # Get the string index [1..-1] because we're skipping the first character '@' # Parse the data out. # if @statusResponse[dutNum].nil? == false && tcusToSkip[dutNum].nil? == true # Old code # SD card just got plugged in. DutObj got re-initialized. # # puts "@statusResponse[dutNum].nil? == true - skipping out of town. #{__FILE__} - #{__LINE__}" # return allDutData += "|#{dutNum}" allDutData += @statusResponse[dutNum] # puts "#{__LINE__}-#{__FILE__} @statusResponse[dutNum]='#{@statusResponse[dutNum]}'" end # puts "@statusResponse[#{dutNum}] = #{@statusResponse[dutNum]}" dutNum +=1; # End of 'while dutNum<TOTAL_DUTS_TO_LOOK_AT do' end # timeNow = Time.now.to_i # allDutData = "-BBB#{timeNow}"+allDutData allDutData = "-"+allDutData # puts "Poll A #{Time.now.inspect}" # @sharedMem.WriteDataTcu(allDutData,"#{__LINE__}-#{__FILE__}") # puts "#{__LINE__}-#{__FILE__} allDutData='#{allDutData}'" parentMemory.WriteDataTcu(allDutData,"#{__LINE__}-#{__FILE__}") # puts "Poll B #{Time.now.inspect}" # End of 'def poll()' end # End of 'class DutObj' end # 160
true
7d15de8847b801b628b6680d9c848b23fed27c16
Ruby
kromoser/my-each-v-000
/my_each.rb
UTF-8
187
3.421875
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def my_each(array) # put argument(s) here i = 0 while i < array.length yield array[i] i += 1 end array end collection = [1,2,3,4] my_each(collection) do |i| i end
true
252e4cdad722ddc3a486b9cdc777f5ccd25ec2a5
Ruby
jordan-creyelman/ruby-morpion
/lib/app/board.rb
UTF-8
2,227
3.203125
3
[]
no_license
require 'bundler' Bundler.require require_relative 'boardCase.rb' class Board attr_accessor :array def initialize boardcase = Boardcase.new @array = boardcase.case end def placement_pions(position,symbole) @array[position] =symbole end def win if @array[0]=="x"&& @array[1]=="x"&& @array[2]=="x" || @array[0]=="o"&& @array[1]=="o"&& @array[2]=="o" return true elsif @array[3]=="x"&& @array[4]=="x"&& @array[5]=="x" || @array[3]=="o"&& @array[4]=="o"&& @array[5]=="o" return true elsif @array[6]=="x"&& @array[7]=="x"&& @array[8]=="x" || @array[6]=="o"&& @array[7]=="o"&& @array[8]=="o" return true elsif @array[0]=="x"&& @array[3]=="x"&& @array[6]=="x" || @array[0]=="o"&& @array[3]=="o"&& @array[6]=="o" return true elsif @array[1]=="x"&& @array[4]=="x"&& @array[7]=="x" || @array[1]=="o"&& @array[4]=="o"&& @array[7]=="o" return true elsif @array[2]=="x"&& @array[5]=="x"&& @array[8]=="x" || @array[2]=="o"&& @array[5]=="o"&& @array[8]=="o" return true elsif @array[0]=="x"&& @array[4]=="x"&& @array[8]=="x" || @array[0]=="o"&& @array[4]=="o"&& @array[8]=="o" return true elsif @array[2]=="x"&& @array[4]=="x"&& @array[6]=="x" || @array[2]=="o"&& @array[4]=="o"&& @array[6]=="o" return true else return false end end def plateau() puts "\n\n" puts ' ' * 10 + '-' * 19 puts ' ' * 10 + ('|' + ' ' * 5) * 3 + '|' puts ' ' * 10 + "| #{array[0]} | #{array[1]} | #{array[2]} |" puts ' ' * 10 + ('|' + ' ' * 4 + '1') + ('|' + ' ' * 4 + '2') + ('|' + ' ' * 4 + '3') + '|' puts ' ' * 10 + '-' * 19 puts ' ' * 10 + ('|' + ' ' * 5) * 3 + '|' puts ' ' * 10 + "| #{array[3]} | #{array[4]} | #{array[5]} |" puts ' ' * 10 + ('|' + ' ' * 4 + '4') + ('|' + ' ' * 4 + '5') + ('|' + ' ' * 4 + '6') + '|' puts ' ' * 10 + '-' * 19 puts ' ' * 10 + ('|' + ' ' * 5) * 3 + '|' puts ' ' * 10 + "| #{array[6]} | #{array[7]} | #{array[8]} |" puts ' ' * 10 + ('|' + ' ' * 4 + '7') + ('|' + ' ' * 4 + '8') + ('|' + ' ' * 4 + '9') + '|' puts ' ' * 10 + '-' * 19 end end
true
e7052ed70d20ab7a50d0895d6bc466a360340c2f
Ruby
mochnatiy/loc-invite
/loc-invite.rb
UTF-8
527
2.875
3
[ "MIT" ]
permissive
require File.expand_path('../lib/hash.rb', __FILE__) require File.expand_path('../app/point.rb', __FILE__) require File.expand_path('../app/processes/customers/select_nearest.rb', __FILE__) # Dublin office location office_location = Point.new(53.339428, -6.257664) # Required distance in kilometers preferred_distance = 100 nearest_customers = Customers::SelectNearest.call( start_point: office_location, distance: preferred_distance ) nearest_customers.each do |customer| puts "#{customer.id}, #{customer.name}" end
true
757a096188b92dd3bf07761bf7648d62f412762a
Ruby
mariomanzoni/Enterprise-Recipes-with-Ruby-and-Rails
/code/testing/rspec/rspecsample/vendor/plugins/rspec_on_rails/spec_resources/helpers/explicit_helper.rb
UTF-8
696
2.859375
3
[ "MIT" ]
permissive
#--- # Excerpted from "Enterprise Recipes for Ruby and Rails", # published by The Pragmatic Bookshelf. # Copyrights apply to this code. It may not be used to create training material, # courses, books, articles, and the like. Contact us if you are in doubt. # We make no guarantees that this code is fit for any purpose. # Visit http://www.pragmaticprogrammer.com/titles/msenr for more book information. #--- module ExplicitHelper def method_in_explicit_helper "<div>This is text from a method in the ExplicitHelper</div>" end # this is an example of a method spec'able with eval_erb in helper specs def prepend(arg, &block) concat(arg, block.binding) + block.call end end
true
b808ecd919c26ca7ad387d031e77061f57df275e
Ruby
TotallyBullshit/metatrader-multilang
/ruby/order.rb
UTF-8
1,097
2.703125
3
[]
no_license
class Mql class Order Types = [:buy, :sell, :buylimit, :buystop, :selllimit, :sellstop] BUY, SELL = *(0..1) attr_reader :ticket def initialize s, ticket @s, @ticket = s, ticket end def lots @s.send(108, @ticket).first end def profit @s.send(109, @ticket).first end def comment @s.send(OrderComment, @ticket).first end def magic_number @s.send(111, @ticket).first end def symbol @s.send(120, @ticket).first end def swap @s.send(121, @ticket).first end def type Types[@s.send(124, @ticket).first] end def open_time Time.at @s.send(102, @ticket).first end def close_time Time.at @s.send(103, @ticket).first end def close slippage=12, color=Color::NONE @s.send(100, @ticket, lots, (type == :buy ? @s.bid : @s.ask), slippage, color).first end end def orders Array(send(119)).map {|ticket| Order.new self, ticket } end end
true
8555025d92967b85e6a6dac7cb6efcf0ffd624f7
Ruby
NahueFaluotico/Rubot
/company.rb
UTF-8
966
3.265625
3
[]
no_license
require_relative 'Robots/flyer' require_relative 'Robots/humanoid' require_relative 'Robots/miner' require_relative 'person' puts "Construyendo robots...\n\n" flyer_robot_1 = Flyer.new('Flyer Robot One') humanoid_robot_1 = Humanoid.new ('Humanoid Robot One') miner_robot_1 = Miner.new ('Miner Robot One') flyer_robot_2 = Flyer.new('Flyer Robot Two') puts "Lanzando los robots...\n\n" flyer_robot_1.release! humanoid_robot_1.release! miner_robot_1.release! person_1 = Person.new('Jhon') person_2 = Person.new('Rachel') puts "Habilidades de los tipos de robots:" Flyer.show_abilities Humanoid.show_abilities Miner.show_abilities puts "\n\n Comprando robots..." flyer_robot_1.buy!(person_1) humanoid_robot_1.buy!(person_2) miner_robot_1.buy!(person_1) flyer_robot_2.buy!(person_2) puts "\n\n Propiedades de los robots:" flyer_robot_1.show_distance(100) humanoid_robot_1.show_distance(100) miner_robot_1.show_distance(100) puts "\n\nReporte:" Robot.show_report
true
52193327f8cca1498cb673c1cdcaf110467fe1cc
Ruby
compose-ui/megatron.rb
/app/helpers/megatron/docs_helper.rb
UTF-8
3,325
2.65625
3
[ "MIT" ]
permissive
module Megatron module DocsHelper DEMO_DEFAULTS = { type: :slim, class: 'demo', tag: :div } def demo(title=nil, options={}, &block) if title.is_a? Hash options = title title = nil end options = DEMO_DEFAULTS.merge(options) content_tag options[:tag], class: options[:class] do rand = SecureRandom.hex(5) concat content_tag(:header, class: 'demo-header') { if title concat content_tag(:h3, class: 'demo-heading', id: heading_id(title)){ title } end if options[:toggle] concat content_tag(:a, href: '#', class: 'demo-source-toggle', 'data-toggle' => "#source-#{rand}, #demo-#{rand}"){ 'source' } else concat content_tag(:a, href: '#', class: 'demo-source-toggle', 'data-toggle' => "#source-#{rand}"){ 'source' } end } concat code(options[:type], id: "source-#{rand}", class: 'hidden') { lines = extract_code(block, 'demo_box') } concat content_tag(:div, id: "demo-#{rand}", &block) end end def demo_box(title, options={}, &block) options[:class] = "#{options[:class]} demo-box" options[:class] << ' padded' unless options[:padded] == false options[:toggle] = true demo(title, options, &block) end def strip_description(lines) start = lines.find_index{|x| x=~/=\s*demo_description/} if start spaces = spaces_at_beginning(lines[start]) count = lines[start+1 .. -1].take_while { |line| spaces_at_beginning(line) > spaces }.size lines.slice!(start..start+count) end lines end # Ouptut a linkable heading # def heading(*args) content = args.pop # Default to h3 tag = args.pop || :h3 content_tag(tag.to_sym, class: 'link-heading', id: heading_id(content)) do concat content end end def heading_id(title) title.gsub(/\W/, '-').downcase end def demo_description(&block) content_tag :div, class: 'demo-description', &block end def code(lang, options = {}, &block) classes = ["language-#{lang}"] classes << options.delete(:class) if options[:class] content_tag(:pre, options.merge(class: classes), &block) end def markdown(&block) text = extract_code(block, 'markdown') #text = content_tag('div', {}, &block).gsub('<div>','') Kramdown::Document.new(text).to_html.html_safe end def markdown_table(classname='doc-table', &block) markdown(&block).gsub(/<table/, "<table class='#{classname}'").html_safe end def extract_code(block, marker) filename, start_line = block.source_location lines = File.readlines(filename) start_line -= 1 until lines[start_line] =~ /#{marker}/ start_line += 1 end spaces = spaces_at_beginning(lines[start_line]) lines = lines[start_line + 1 .. -1] lines = lines.take_while { |line| spaces_at_beginning(line) > spaces || line.match(/^\n\s*$/) } .map { |line| line.sub(%r{^\s{#{spaces + 2}}}, '') } strip_description(lines).join("") end def spaces_at_beginning(str) str[/\A */].size end end end
true
8054f0f3baca07b5a9cad48add2cdc9cd9277f30
Ruby
m1kshay/Alina
/Lessons/Lesson_9/train.rb
UTF-8
2,058
3.375
3
[]
no_license
require_relative 'company_manufacturer' require_relative 'instance_counter' require_relative 'validation' class Train include CompanyManufacturer include InstanceCounter include Validation attr_reader :number, :type, :speed, :route, :wagons @@trains_number = {} TRAIN_NUMBER = /^\w{3}-?\w{2}$/ def initialize(number, type) @number = number @speed = 0 @type = type validate! @current_station_index = 0 @route = [] @wagons = [] @@trains_number[number] = self register_instance end def wagons_block @wagons.each { |wagon| yield(wagon) } def self.find(number) @@trains_number[number] end def increase_speed(n) @speed += n end def decrease_speed(n) @speed -= n @speed = 0 if @speed < 0 end def stop @speed = 0 end def attach_wagon(wagon) wagons.push(wagon) if speed.zero? && wagon.type == self.type end def detach_wagon(wagon) wagons.pop if speed.zero? end def add_route(route) @route = route @current_station_index = 0 current_station.attach_train(self) end def current_station @route.stations[@current_station_index] end def previous_station return unless @current_station_index.positive? @route.stations[@current_station_index - 1] end def next_station @route.stations[@current_station_index + 1] end def go_next return if next_station.nil? current_station.detach_train(self) @current_station_index += 1 current_station.attach_train(self) end def go_previous return if previous_station.nil? current_station.detach_train(self) @current_station_index -= 1 current_station.attach_train(self) end def info number end private def validate! validate_number_empty! validate_train_number! end def validate_number_empty! raise ArgumentError, "Number can't be empty" if @number.empty? end def validate_train_number! raise ArgumentError, "Number '#{@number}' has no valid format" if @number !~ TRAIN_NUMBER end end
true
f72322bb5db558b5d3fe474ba794a191b881e24b
Ruby
soilman/soilt
/lib/tasks/import_trucks.rake
UTF-8
479
2.671875
3
[]
no_license
require 'csv' namespace :csv do desc "Import CSV Data" task :import_trucks => :environment do csv_file_path = 'db/fixtures/trucks.csv' CSV.foreach(csv_file_path) do |row| truck_count = 1 Truck.create!({ :company_id => row[0], :number => row[1], :plate => row[2] }) truck_count += 1 puts "Truck number #{truck_count} added!" end end end # 'rake csv:import_trucks' => to run this rake task
true
f707a071f8248353a87b26828cce967d344d7637
Ruby
deguzman22/premierespeakers_exam
/xml_parser.rb
UTF-8
2,120
2.625
3
[]
no_license
require 'xmlsimple' # there have no b029 and b041 on XML file class XmlParser def call parse_xml end private def parse_xml xml = File.read 'ACdelta20061pt2.xml' data = XmlSimple.xml_in xml data['product'].each do |product| @text = <<-TEXT isbn: #{product['productidentifier'][3]['b244'][9]} if its sibling #{product['productidentifier'][3]['b221'][0]} is 15 title: #{product['title'][0]['b203'][0]} subtitle: b029 publishing status: #{product['b394'][0]['content']} language: #{product['language'][0]['b252'][0]} publisher name: #{product['publisher'][0]['b081'][0]} author: is a contributor; #{product['contributor'][0]['b039'][0]} or #{product['contributor'][0]['b040'][0]} or b041 if its sibling #{product['contributor'][0]['b035'][0]} is A01 number of pages: #{product['b061'][0]} publication_date: #{product['b003'][0]} product_form: #{product['b012'][0]} price: #{product['supplydetail'][0]['price'][6].nil? ? nil : product['supplydetail'][0]['price'][6]['j151'][0]} description: #{product['othertext'][0]['d104'][0]['content']} height: measure #{product['measure'][0]['c094'][0]} if its sibbling #{product['measure'][0]['c093'][0]} is 01 length: measure #{product['measure'][2]['c094'][0]} if its sibbling #{product['measure'][2]['c093'][0]} 03 width: measure #{product['measure'][2]['c094'][0]} if its sibbling #{product['measure'][2]['c093'][0]} is 03 weight: measure #{product['measure'][3]['c094'][0]} if its sibbling #{product['measure'][3]['c093'][0]} is 08 bisac_code: #{product['b064'].nil? ? nil : product['b064'][0]} bisac_code2: #{!product['subject'].nil? && product['subject'][0].key?('b069') ? product['subject'][0]['b069'][0] : nil} bisac_code3: #{product['subject'].nil? ? nil : product['subject'][0]['b070']} media_file: #{!product['mediafile'].nil? && product['mediafile'][0].key?('f117') ? product['mediafile'][0]['f117'][0] : nil} TEXT puts @text end end end x = XmlParser.new x.call
true
9a82f886726ac063456a57d62747868e74e24dcf
Ruby
gf3/celluloid
/lib/celluloid/tasks.rb
UTF-8
1,165
2.84375
3
[ "MIT" ]
permissive
module Celluloid # Asked to do task-related things outside a task class NotTaskError < StandardError; end # Trying to resume a dead task class DeadTaskError < StandardError; end # Tasks are interruptable/resumable execution contexts used to run methods class Task class TerminatedError < StandardError; end # kill a running task # Obtain the current task def self.current Thread.current[:celluloid_task] or raise NotTaskError, "not within a task context" end # Suspend the running task, deferring to the scheduler def self.suspend(status) Task.current.suspend(status) end # Create a new task def initialize(type) @type = type @status = :new end end class TaskSet include Enumerable def initialize @tasks = Set.new end def <<(task) @tasks += [task] end def delete(task) @tasks -= [task] end def each(&blk) @tasks.each &blk end def first @tasks.first end def empty? @tasks.empty? end end end require 'celluloid/tasks/task_fiber' require 'celluloid/tasks/task_thread'
true
e7a339de6c4fe735eb76e0ade7e61449bf685341
Ruby
denza/workers
/test/pool_test.rb
UTF-8
1,149
2.734375
3
[ "MIT" ]
permissive
require 'test_helper' class PoolTest < Minitest::Test def test_basic_usage pool = Workers::Pool.new successes = [] pool.size.times do pool.perform { successes << true } end assert(pool.dispose(5)) assert(Array.new(pool.size, true), successes) end def test_exception_during_perform pool = Workers::Pool.new success = false (pool.size * 3).times { pool.perform { raise 'uh oh' }} pool.perform { success = true } pool.dispose assert(success) end def test_contracting pool = Workers::Pool.new orig_size = pool.size pool.contract(orig_size / 2) assert_equal(orig_size / 2, pool.size) ensure pool.dispose end def test_expanding pool = Workers::Pool.new orig_size = pool.size pool.expand(orig_size * 2) assert_equal(orig_size * 3, pool.size) ensure pool.dispose end def test_resizing pool = Workers::Pool.new orig_size = pool.size pool.resize(orig_size * 2) assert_equal(orig_size * 2, pool.size) pool.resize(orig_size / 2) assert_equal(orig_size / 2, pool.size) ensure pool.dispose end end
true
cc25c1fca47f1766075d825bd3a8e00bcad70fcd
Ruby
Dfelix02/ruby-oo-object-relationships-has-many-through-lab-nyc04-seng-ft-071220
/lib/genre.rb
UTF-8
341
3.3125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Genre attr_reader :name @@all = [] def initialize(song_genre) @name = song_genre @@all << self end def songs Song.all.select{|song_info|song_info.genre == self} end def self.all @@all end def artists songs.map{|artist_info| artist_info.artist} end end
true
ea7118f625c6d2491d32b4fcc66461e4aae7a226
Ruby
agarcher/fight-engine
/fighters/assassin.rb
UTF-8
113
2.703125
3
[]
no_license
require_relative 'fighter' class Assassin < Fighter def attack_power (@attack_power * 1.7).ceil end end
true
c5939e0487d00c4cba192076cc87ddae6b04a118
Ruby
davidmjiang/assignment_sinatra_basics
/modules/helpers.rb
UTF-8
408
3.578125
4
[]
no_license
module Helpers def win?(input) input = input.downcase win = { 'rock' => 'scissors', 'paper' => 'rock', 'scissors' => 'paper' } game_move = win.keys.sample if input == game_move "Tie. Computer chose #{game_move}" elsif win[input] == game_move "Win. Computer chose #{game_move} " else win[game_move] == input "Lose. Computer chose #{game_move}" end end end
true
ef7270b2a1e515796d94d5ff48292d8beaec3b90
Ruby
mathieujobin/isrubyfastyet
/Rakefile
UTF-8
1,465
2.703125
3
[]
no_license
require File.expand_path('../isrubyfastyet', __FILE__) require 'simple_stats' desc "Is the benchmark producing consistent ouput? Show how different the last result vs. the median of the 5 previous results for stable rubies" task :variability do offset = (ENV['OFFSET'] ? ENV['OFFSET'].to_i : 0) previous_count = (ENV['PREVIOUS'] ? ENV['PREVIOUS'].to_i : 5) benchmark_variabilites = BenchmarkResultSet.all.map do |benchmark| puts puts benchmark.name variabilities = Ruby.all_stable.map do |ruby| ruby_results = benchmark.results_by_rvm_name(ruby.rvm_name).map(&:to_f).compact last_result = ruby_results[offset-1] previous_results = ruby_results[0..(offset-2)].last(previous_count) previous_results = previous_results.median variability = (last_result - previous_results) / previous_results puts "%s: %.2f%%" % [ruby.rvm_name, variability * 100.0] variability end absolute_variabilities = variabilities.map(&:abs) benchmark_variability = variabilities[absolute_variabilities.find_index(absolute_variabilities.max)] puts " max: %.2f%%" % [benchmark_variability * 100.0] benchmark_variability end absolute_benchmark_variabilities = benchmark_variabilites.map(&:abs) suite_variability = benchmark_variabilites[absolute_benchmark_variabilities.find_index(absolute_benchmark_variabilities.max)] puts puts "suite: %.2f%%" % [suite_variability * 100.0] puts end
true