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
d18f8130f703f88faf84e6e5da25abf89bfc12c1
Ruby
codyloyd/cli_chess
/game/Player.rb
UTF-8
552
3.859375
4
[]
no_license
require "./game/GameBoard" class Player attr_accessor :name, :color def initialize(name, color) @name = name @color = color end def input_to_array(input_string) #this method will convert the user's string (example a1,b3) #into an appropriate input for GameBoard.move_piece ([0,1],[1,3]) array = input_string.split(",").map{ |x| x.scan(/./)} array.map{ |x,y| [8 - y.to_i, x.ord - 97] } end def check_if_own_piece #this method should check if the Player has selected one of their own pieces to move end def user_input end end
true
2570419e1e4c6a16b0246869b5234a0e69fecade
Ruby
zeisler/attr_permit
/lib/attr_permit.rb
UTF-8
5,092
2.84375
3
[ "MIT" ]
permissive
require 'active_support/core_ext/big_decimal' class AttrPermit class << self def permissible_methods @permissible_methods ||= [] end def mapped_methods @mapped_methods ||= [] end def attr_permit(*permissible_methods) self.permissible_methods.concat [*permissible_methods, *get_super_permissible_methods] self.permissible_methods.each do |meth| send(:define_method, meth) do call_method(meth) end attr_writer meth unless public_instance_methods.include?("#{meth}=") end end def map_attributes(map_hash) map_hash.each do |to, from| map_attribute to, from end end def map_attribute(to, from) self.mapped_methods.concat [*to, *get_super_mapped_methods] if from.is_a? Proc send(:define_method, to) do source.instance_exec(&from) end else send(:define_method, to) do call_method(from) end end end protected def get_super_permissible_methods superclass.permissible_methods unless superclass == AttrPermit end def get_super_mapped_methods superclass.mapped_methods unless superclass == AttrPermit end end protected attr_reader :source public def initialize(source=nil) @source = source update(source) end def update(source) return if source.nil? source = OpenStruct.new(source) if source.class <= Hash self.class.permissible_methods.each do |meth| send("#{meth}=", source.send(meth)) if source.respond_to? meth end end def call_method(meth) callable = instance_variable_get("@#{meth}") instance_variable_set("@#{meth}", callable.call) if callable.respond_to?(:call) instance_variable_get("@#{meth}") end protected :call_method def map_hash(big_decimal_as_string: false, all_values_as_string: false) hasher([*self.class.mapped_methods], big_decimal_as_string, all_values_as_string) end def permit_hash(big_decimal_as_string: false, all_values_as_string: false) hasher([*self.class.permissible_methods], big_decimal_as_string, all_values_as_string) end def to_hash(big_decimal_as_string: false, all_values_as_string: false) hasher([*self.class.permissible_methods, *self.class.mapped_methods], big_decimal_as_string, all_values_as_string) end alias_method :to_h, :to_hash def non_nil_values(hash_type=:to_hash) hash = {} send(hash_type).each { |k, v| hash[k] = v unless v.nil? } hash end def ==(obj) self.hash == obj.hash end def is_equivalent?(obj) self_hash = self.to_hash obj_hash = obj.to_hash self_hash.each { |k, v| self_hash[k] = v.to_s } obj_hash.each { |k, v| obj_hash[k] = v.to_s } self_hash == obj_hash end def hash self.to_hash.hash end def to_enum copy = self.dup copy.singleton_class.send(:include, Enumerable) def copy.each(&block) self.class.permissible_methods.each do |item| block.call(public_send(item)) end end copy end private attr_reader :big_decimal_as_string, :all_values_as_string def big_decimal_as_string_convert(object) val = if big_decimal_as_string object.to_s if object.class <= BigDecimal end return object if val.nil? val end def all_values_as_string_convert(object) val = if all_values_as_string object.to_s if object.respond_to?(:to_s) end return object if val.nil? val end def to_hash_object(object) if object.respond_to?(:to_hash) && object.class <= AttrPermit value = object.to_hash(big_decimal_as_string: big_decimal_as_string, all_values_as_string: all_values_as_string) end if object.respond_to?(:to_hash) && !(object.class <= AttrPermit) value = object.to_hash end return object if value.nil? value end def array_to_hash(object) if object.class <= Array value = object.map do |v| to_hash_object(v) end end return object if value.nil? value end def hasher(methods, big_decimal_as_string, all_values_as_string) @big_decimal_as_string = big_decimal_as_string @all_values_as_string = all_values_as_string hash = {} methods.each do |var| value = send(var) value = to_hash_object(value) value = big_decimal_as_string_convert(value) value = all_values_as_string_convert(value) value = array_to_hash(value) hash[var] = value end hash end end class AttrPermitLazy < AttrPermit def self.attr_permit(*permissible_methods) self.permissible_methods.concat [*permissible_methods, *get_super_premissible_methods] self.permissible_methods.each do |meth| send(:define_method, meth) do callable = instance_variable_get("@#{meth}") instance_variable_set("@#{meth}", callable.call) if callable.respond_to?(:call) instance_variable_get("@#{meth}") end attr_writer meth unless public_instance_methods.include?("#{meth}=") end end end
true
838d0afdbe160a519381c9e28d6ef566a6ce35a6
Ruby
seishingithub/api_spike
/weather_data.rb
UTF-8
1,415
3.640625
4
[]
no_license
require 'faraday' require 'json' require 'pp' require 'date' require 'pry' response = Faraday.get 'http://api.openweathermap.org/data/2.5/weather?q=Boulder,%20co' response2 = Faraday.get 'http://api.openweathermap.org/data/2.5/forecast/daily?q=Boulder,%20co&units=imperial' JSON.parse(response.body) JSON.parse(response2.body) response response2 @coord = JSON.parse(response.body) # display current weather for Boulder, CO current_weather = @coord["weather"].first["description"] @coord2 = JSON.parse(response2.body) # get 7-day forecast for Boulder, CO def daily_forecast(info) info["weather"][0]["description"] end def daily_expected_temp(info) info["temp"]["day"].to_i end def daily_minimum_temp(info) info["temp"]["min"].to_i end def daily_maximum_temp(info) info["temp"]["max"].to_i end def day_of_week(info) unix_time = info["dt"] #unix_time is assigned the value of info at 'dt' date = DateTime.strptime(unix_time.to_s, '%s') #date is assigned the date(DateTime) parsed from unix_time date.strftime('%A') #.?? => 'Monday' (what is date?) end puts "The current weather for Boulder, CO is #{current_weather}." puts "The 7-day forecast is as follows:" @coord2['list'].map do |info| puts "#{day_of_week(info)}, we expect #{daily_forecast(info)} with #{daily_expected_temp(info)} degrees with a minimum of #{daily_minimum_temp(info)} and a maximum of #{daily_maximum_temp(info)}." end
true
b2fe5427707362df1156dd32010aa37f01f3840a
Ruby
MiriamGomez2/ejerciciosRuby
/Persona.rb
UTF-8
865
3.484375
3
[]
no_license
#Miriam Gomez class Persona def initialize (nombre,genero,edad) @miNombre = nombre @miGenero = genero @miEdad = edad end def setNombre(nombre) @miNombre = nombre end def getNombre return @miNombre end def setGenero(genero) @miGenero = genero end def getGenero return @miGenero end def setEdad(edad) @miEdad = edad end def getEdad return @miEdad end end myPersona = Persona.new("ana","femenino","11") puts "Teclea el nombre de la Persona" myPersona.setNombre(gets.chomp) puts "Teclea el genero de la Persona" myPersona.setGenero(gets.chomp) puts "Teclea la Edad de la Persona" myPersona.setEdad(gets.chomp) puts "El nombre es: #{myPersona.getNombre}" puts "El genero es: #{myPersona.getGenero}" puts "La edad es: #{myPersona.getEdad}"
true
8a00e6338e4b99fbd909a7a90a82765da0ae451a
Ruby
leifg/riese
/test/test_riese.rb
UTF-8
4,094
3.3125
3
[ "MIT" ]
permissive
require 'minitest/autorun' require 'riese' require 'turn' class TestRiese < MiniTest::Unit::TestCase # #initialize def test_that_assignment_is_stored_correctly subject = Riese::Fraction.new 1, 2 assert_equal 1, subject.numerator assert_equal 2, subject.denominator end def test_that_fraction_is_reduced_on_initialization subject = Riese::Fraction.new 30, 90 assert_equal 1, subject.numerator assert_equal 3, subject.denominator end def test_that_zero_is_correctly_reduced_on_initialization subject = Riese::Fraction.new 0, 99 assert_equal 0, subject.numerator assert_equal 1, subject.denominator end def test_that_negative_fraction_is_correctly_normalized subject = Riese::Fraction.new 1, -2 assert_equal -1, subject.numerator assert_equal 2, subject.denominator end def test_that_negative_numerator_and_denominator_are_correctly_normalized subject = Riese::Fraction.new -10, -20 assert_equal 1, subject.numerator assert_equal 2, subject.denominator end def test_that_zero_denominator_raises_error assert_raises(ZeroDivisionError) { Riese::Fraction.new(1, 0) } end # Riese::Fraction.init def test_initialization_from_integer assert_equal Riese::Fraction.new(23, 1), Riese::Fraction.init(23) end def test_initialization_from_nil assert_raises(TypeError) {Riese::Fraction.init(nil)} end # #== def test_that_2_fractions_with_same_numerator_denumerator_are_equal subject = Riese::Fraction.new 1, 2 assert_equal Riese::Fraction.new(1, 2), subject end def test_that_2_fractions_with_the_same_value_are_equal subject = Riese::Fraction.new 1, 5 assert_equal Riese::Fraction.new(20, 100), subject end def test_that_nil_is_unequal_to_fraction refute_equal Riese::Fraction.new(1, 2), nil end # #inverse def test_that_inverse_for_simple_fraction_works_correctly assert_equal Riese::Fraction.new(100, 1), Riese::Fraction.new(1, 100).inverse end def test_that_inverse_for_zero_raises_error assert_raises(ZeroDivisionError){ Riese::Fraction.new(0, 1).inverse } end # #+ def test_that_addition_works_for_simple_fraction assert_equal Riese::Fraction.new(3, 4), Riese::Fraction.new(1, 2) + Riese::Fraction.new(1, 4) end def test_that_addition_works_for_integer assert_equal Riese::Fraction.new(5, 2), Riese::Fraction.new(1, 2) + 2 end def test_that_addition_raises_error_on_adding_nil assert_raises(TypeError) { Riese::Fraction.new(1, 2) + nil } end # #- def test_that_subtraction_works_for_simple_fraction assert_equal Riese::Fraction.new(1, 20), Riese::Fraction.new(1, 10) - Riese::Fraction.new(1, 20) end def test_that_subtraction_works_for_integer assert_equal Riese::Fraction.new(-1, 2), Riese::Fraction.new(1, 2) - 1 end def test_that_subtraction_raises_error_on_subtracting_nil assert_raises(TypeError) { Riese::Fraction.new(3, 4) - nil } end # #* def test_that_multiplication_works_for_simple_fraction assert_equal Riese::Fraction.new(8, 15), Riese::Fraction.new(2, 3) * Riese::Fraction.new(4, 5) end def test_that_multiplication_works_for_integer assert_equal Riese::Fraction.new(4, 3), Riese::Fraction.new(2, 3) * 2 end def test_that_multiplication_works_for_negative_integer assert_equal Riese::Fraction.new(-4, 3), Riese::Fraction.new(2, 3) * -2 end def test_that_multiplication_raises_error_on_multiplying_by_nil assert_raises(TypeError) { Riese::Fraction.new(5, 6) * nil } end # #/ def test_that_division_works_for_simple_fraction assert_equal Riese::Fraction.new(1, 2), Riese::Fraction.new(1, 4) / Riese::Fraction.new(1, 2) end def test_that_division_works_for_integer assert_equal Riese::Fraction.new(1, 20), Riese::Fraction.new(1, 10) / 2 end def test_that_division_by_zero_raises_error assert_raises(ZeroDivisionError) { Riese::Fraction.new(1, 2) / 0 } end def test_that_diviosn_raises_error_on_dividin_by_nil assert_raises(TypeError) { Riese::Fraction.new(7, 8) / nil } end end
true
53abb9aedff2e81c3c001331f1537f74aec9612d
Ruby
lizamcpherson/Liza.McPherson.lizamcpherson01
/exercises/d3/recipes.rb
UTF-8
832
3.203125
3
[]
no_license
hash = { pancakes: { description: "like toast but better", ingredients: ["flour", "eggs", "butter"], steps: ["add mix", "stir", "cook"] }, omelettes: { description: "eggs with yummy stuff", ingredients: ["eggs", "bacon", "cheese"], steps: ["mix eggs", "add ingredients", "cook"] }, fruit_smoothie: { description: "pretty self explanatory tbh", ingredients: ["strawberries", "blueberries", "yogurt", "ice"], steps: ["put ingredients in blender", "blend", "enjoy"] } } hash.each do |key, value| puts key value.each do |key, value| puts key puts value end end # 1. Hash in ingredients # Hash<Symbol, Array<String>> # 2. Hash<Hash, Array<Integers>> # 3. Array<Hash<Array<String>, Symbol> # 4. Hash # Hash<Symbol, Hash<(Symbol, String), (Symbol, Array<String>), (Symbol, Array<String>)>>
true
2db74a86c484491f6927d0dc08a6c584bf2795de
Ruby
Clearcover/rdkafka-ruby
/lib/rdkafka/producer/delivery_handle.rb
UTF-8
2,110
2.765625
3
[ "MIT" ]
permissive
module Rdkafka class Producer # Handle to wait for a delivery report which is returned when # producing a message. class DeliveryHandle < FFI::Struct layout :pending, :bool, :response, :int, :partition, :int, :offset, :int64 REGISTRY = {} def self.register(address, handle) REGISTRY[address] = handle end def self.remove(address) REGISTRY.delete(address) end # Whether the delivery handle is still pending. # # @return [Boolean] def pending? self[:pending] end # Wait for the delivery report or raise an error if this takes longer than the timeout. # If there is a timeout this does not mean the message is not delivered, rdkafka might still be working on delivering the message. # In this case it is possible to call wait again. # # @param timeout_in_seconds [Integer, nil] Number of seconds to wait before timing out. If this is nil it does not time out. # # @raise [RdkafkaError] When delivering the message failed # @raise [WaitTimeoutError] When the timeout has been reached and the handle is still pending # # @return [DeliveryReport] def wait(timeout_in_seconds=60) timeout = if timeout_in_seconds Time.now.to_i + timeout_in_seconds else nil end loop do if pending? if timeout && timeout <= Time.now.to_i raise WaitTimeoutError.new("Waiting for delivery timed out after #{timeout_in_seconds} seconds") end sleep 0.1 next elsif self[:response] != 0 raise RdkafkaError.new(self[:response]) else return DeliveryReport.new(self[:partition], self[:offset]) end end end # Error that is raised when waiting for a delivery handle to complete # takes longer than the specified timeout. class WaitTimeoutError < RuntimeError; end end end end
true
956de84b2f55066263852df9f3077aa83636e9cd
Ruby
alanrubin/top-parsers-WCFG-MySQL
/src/probability_normalizer.rb
UTF-8
145
2.515625
3
[]
no_license
class ProbabilityNormalizer def normalize(weight) weight == 0.0 ? -9.223372036854776E18 : -(Math.log(weight)*10).round.to_i end end
true
10694b4f09a04a9a4abe86e118cf93b2e5ed489b
Ruby
maximkoo/ruby-repo
/Noko/readnoko.rb
UTF-8
798
2.65625
3
[]
no_license
# # http://www.nokogiri.org/tutorials/parsing_an_html_xml_document.html # require 'nokogiri' #Создаем XML-ресурс для Nokogiri a='' a<<File.open('1.xml').read; b=Nokogiri::XML(a) #или вот так doc = File.open("1.xml") { |f| Nokogiri::XML(f) } puts b.xpath('//value') #вроде оператора extract в PLSQL, возвращает XML, #обрезаный до тэга puts b.xpath('//value').class b.xpath('//value').each do |x| # при этом он ещё и коллекция Nokogiri::XML::NodeSet puts x.content.strip!; #strip удаляет пробелы, потому что сами они не удаляются end; puts b.xpath('//value/@xxx') #значение атрибута ххх из всех тегов
true
7aed5ec90444591d998bafeef48713bc0293b7c7
Ruby
jasoares/euro2012_score_simulator
/app/models/team.rb
UTF-8
2,192
2.734375
3
[]
no_license
class Team < ActiveRecord::Base belongs_to :group has_many :home_scores, :class_name => "Score", :foreign_key => "home_team_id" has_many :away_scores, :class_name => "Score", :foreign_key => "away_team_id" attr_accessible :name, :group UEFA_RANKING = [ "England", "Spain", "Germany", "Italy", "Portugal", "France", "Russia", "Netherlands", "Ukraine", "Greece", "Denmark", "Czech Rep.", "Poland", "Croatia", "Sweden", "Rep. of Ireland", ] def draws(scores=self.scores) scores.count { |s| s.draw? } end def goal_dif(scores=self.scores) goals_for(scores) - goals_ag(scores) end def goals_ag(scores=self.scores) scores.inject(0) { |sum, s| sum += s.goals_ag(self) } end def goals_for(scores=self.scores) scores.inject(0) { |sum, s| sum += s.goals_for(self) } end def flag_img "#{name.downcase.gsub(" ", "_").gsub(".", "")}.gif" end def losses(scores=self.scores) scores.count { |s| s.loss?(self) } end def matches(scores=self.scores) scores.length end def points(scores=self.scores) scores.inject(0) do |pts, s| pts += s.win?(self) ? 3 : s.loss?(self) ? 0 : 1 end end def ranking UEFA_RANKING.index(name) end def scores home_scores + away_scores end def to_s self.name end def wins(scores=self.scores) scores.count { |s| s.win?(self) } end def <=>(o) return o.points - points unless o.points == points tied_teams = group.teams_with_points(self.points) scores = group.scores_between(tied_teams) return o.points(scores) - points(scores) unless o.points(scores) == points(scores) or tied_teams.length > 2 return o.goal_dif(scores) - goal_dif(scores) unless o.goal_dif(scores) == goal_dif(scores) return o.goals_for(scores) - goals_for(scores) unless o.goals_for(scores) == goals_for(scores) return o.goal_dif - goal_dif unless o.goal_dif == goal_dif return o.goals_for - goals_for unless o.goals_for == goals_for return ranking < o.ranking ? -1 : 1 end def ==(o) name == o.name end end
true
25fa5956b9b9c85284a8fc34f9fcd713e0a2c6eb
Ruby
rorymckinley/rubyfuza2013
/test_threads.rb
UTF-8
347
2.8125
3
[]
no_license
require 'net/http' require 'uri' t = Time.now uri = URI.parse("http://google.com/") Net::HTTP.get_response(uri) puts "Test: #{Time.now - t}" 80.times do |i| Thread.new {response = Net::HTTP.get_response(uri); print "Thread no #{i} got #{response.code}\n" } end Thread.list.each { |t| t.join unless t == Thread.current } puts Time.now - t
true
5f88c404d8e306b7274c0a21620f2541bfc3a543
Ruby
ValentinaPanic/square_array-onl01-seng-pt-050420
/square_array.rb
UTF-8
189
3.515625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def square_array(arrays) new_numbers = [] arrays.each do |x| new_numbers.push (x * x) end new_numbers end #def square_array(new_numbers) # new_numbers. do {|x| x * x } # end #end
true
2a865fc97e4bc62ec8e59c01d4505d96c1d6473c
Ruby
astrails/debitcredit
/app/models/debitcredit/item.rb
UTF-8
576
2.578125
3
[ "MIT" ]
permissive
module Debitcredit class Item < ApplicationRecord belongs_to :entry belongs_to :account validates :entry, :account, presence: true validates :amount, numericality: {greater_than_or_equal_to: 0} scope :debit, ->{where(debit: true)} scope :credit, ->{where(debit: false)} def credit? !debit? end def value_for_balance credit?? amount : -amount end def kind debit?? :debit : :credit end def inverse self.class.new account: account, entry: entry, amount: amount, debit: credit? end end end
true
fe03f2a15bca1e9b8f71c3e3f5ed3c437939e488
Ruby
sauloperez/sensors-app
/db/seeds.rb
UTF-8
648
2.625
3
[]
no_license
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) # require 'random-location' ref_point = [41.38563, 2.16872] 6.times do |i| coords = RandomLocation.near_by(ref_point[0], ref_point[1], 20000) coords.map! { |c| c.round(5) } Sensor.create(latitude: coords[0], longitude: coords[1], type: ["solar", "wind"].sample, active: [true, false].sample) end
true
96ee8d27acd7a92bc8d87054cf813bc0ceedf29b
Ruby
Eskat0n/GraduationWork
/code/lib/extensibility/components_base/test_runner_component.rb
UTF-8
686
2.796875
3
[ "Unlicense", "MIT" ]
permissive
require_relative 'component.rb' class TestRunnerComponent < Component def self.base_type 'TestRunner' end def run_tests raise NotImplementedError, "Run tests method must be implemented by #{type}" end end class TestResult attr_accessor :failed, :tests, :time, :target attr_reader :errors def initialize @errors = [] end def add_error file, line, name, operator @errors << FailedTest.new(file, line, name, operator) end def success? @errors.empty? end end class FailedTest attr_reader :file, :line, :name, :operator def initialize file, line, name, operator @file, @line, @name, @operator = file, line, name, operator end end
true
9a312b7413347333cc7da3f395d8e3d632c67a61
Ruby
jonasmedcapital/clinics
/app/repositories/operations/products/clinics/taker_repository.rb
UTF-8
1,351
2.578125
3
[]
no_license
class Operations::Products::Clinics::TakerRepository < Base def self.build(attrs) obj = entity.new obj.clinic_id = attrs["clinic_id"] obj.taker_id = attrs["taker_id"] obj.taker_type = TAKER_TYPE[attrs["taker_type"]] obj.taker_number = attrs["taker_number"] obj.taker_name = attrs["taker_name"] return obj end def self.all_active entity.where(active: true) end def self.list_all(takers) mapper.map_all(takers) end def self.read(taker) mapper.map(taker) end def self.find_by_id(id) entity.find_by(id: id) end def self.all_active_clinic(clinic_id) entity.where(active: true, clinic_id: clinic_id).order(:created_at) end def self.find_taker(taker) taker_type = taker.taker_type taker_id = taker.taker_id taker_type.constantize.find(taker_id) end private def self.entity "Operation::Product::Clinic::Taker".constantize end def self.mapper "Operations::Products::Clinics::TakerMapper".constantize end TAKER_TYPE = { "account" => "User::Account::Entity", "company" => "User::Company::Entity" } UNTAKER_TYPE = { "User::Account::Entity" => "account", "User::Company::Entity" => "company" } TAKER_NFEIO = { "User::Account::Entity" => "NaturalPerson", "User::Company::Entity" => "LegalEntity" } end
true
1ea555f3a2659b60726f42a4e6565b5d08cea77e
Ruby
elpadrinoIV/blackjack
/test/test_jugador_tramposo.rb
UTF-8
4,008
2.734375
3
[]
no_license
require File.dirname(__FILE__) + '/helper.rb' require 'jugador_tramposo' require 'game' class TestJugadorTramposo < Test::Unit::TestCase def setup @game = Game.new @jugador = JugadorTramposo.new(1000, @game) @game.agregar_jugador(@jugador) end def teardown # nada... end def test_debe_pedir_si_no_se_pasa_con_la_siguiente_carta # # Croupier 10 6 (16) # # Jugador 10 6 (16) # Siguiente carta: 4 (debe pedir) valores_cartas = [10, 10, 6, 6, 4] valores_cartas.reverse! cartas = Array.new valores_cartas.each{ |valor_carta| cartas << Carta.new(Mazo::NUMEROS[0], Mazo::PALOS[0], valor_carta) } @game.reemplazar_cartas_con_estas(cartas) @jugador.apostar @game.repartir assert(@jugador.pedir_carta?, "El jugador debe pedir carta porque no se pasa si pide otra") end def test_debe_plantar_si_se_pasa_con_la_siguiente_carta # # Croupier 10 6 (16) # # Jugador 10 6 (16) # Siguiente carta: 8 (no debe pedir) valores_cartas = [10, 10, 6, 6, 8] valores_cartas.reverse! cartas = Array.new valores_cartas.each{ |valor_carta| cartas << Carta.new(Mazo::NUMEROS[0], Mazo::PALOS[0], valor_carta) } @game.reemplazar_cartas_con_estas(cartas) @jugador.apostar @game.repartir assert(false == @jugador.pedir_carta?, "El jugador no debe pedir carta porque se pasa si pide otra") end def test_debe_pagar_seguro_si_croupier_tiene_blackjack # # Croupier A 10 (21) # # Jugador 10 6 (16) # Siguiente carta: 3 valores_cartas = [10, 11, 6, 10, 3] valores_cartas.reverse! cartas = Array.new valores_cartas.each{ |valor_carta| cartas << Carta.new(Mazo::NUMEROS[0], Mazo::PALOS[0], valor_carta) } @game.reemplazar_cartas_con_estas(cartas) @jugador.apostar @game.repartir assert(@jugador.pagar_seguro?, "El jugador debe pagar seguro porque el croupier tiene blackjack") end def test_no_debe_pagar_seguro_si_croupier_no_tiene_blackjack # # Croupier A 8 (19) # # Jugador 10 6 (16) # Siguiente carta: 3 valores_cartas = [10, 11, 6, 8, 3] valores_cartas.reverse! cartas = Array.new valores_cartas.each{ |valor_carta| cartas << Carta.new(Mazo::NUMEROS[0], Mazo::PALOS[0], valor_carta) } @game.reemplazar_cartas_con_estas(cartas) @jugador.apostar @game.repartir assert(false == @jugador.pagar_seguro?, "El jugador no debe pagar seguro porque el croupier no tiene blackjack") end def test_debe_duplicar_si_le_gana_al_croupier_y_croupier_tiene_17_o_mas # si el croupier tiene 17 o mas (no puede pedir carta) y duplicando le gana, debe duplicar # # Croupier 10 7 (21) # # Jugador 6 5 (11) # Siguiente carta: 9 (debe duplicar porque gana) valores_cartas = [6, 10, 5, 7, 9] valores_cartas.reverse! cartas = Array.new valores_cartas.each{ |valor_carta| cartas << Carta.new(Mazo::NUMEROS[0], Mazo::PALOS[0], valor_carta) } @game.reemplazar_cartas_con_estas(cartas) @jugador.apostar @game.repartir assert(@jugador.duplicar?, "El jugador debe duplicar porque gana seguro") end def test_no_debe_duplicar_si_no_le_gana_al_croupier_y_croupier_tiene_17_o_mas # si el croupier tiene 17 o mas (no puede pedir carta) y duplicando no le gana, no debe duplicar # # Croupier 10 7 (21) # # Jugador 6 5 (11) # Siguiente carta: 4 (no debe duplicar porque pierde) valores_cartas = [6, 10, 5, 7, 4] valores_cartas.reverse! cartas = Array.new valores_cartas.each{ |valor_carta| cartas << Carta.new(Mazo::NUMEROS[0], Mazo::PALOS[0], valor_carta) } @game.reemplazar_cartas_con_estas(cartas) @jugador.apostar @game.repartir assert(false == @jugador.duplicar?, "El jugador no debe duplicar porque pierde seguro") end end
true
4349347c4beb1e677a9a33fc7d6a945f1086164c
Ruby
lsamano/collections_practice-dumbo-web-121018
/collections_practice.rb
UTF-8
653
3.90625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def sort_array_asc(array) array.sort end def sort_array_desc(array) array.sort do |a, b| b <=> a end end def sort_array_char_count(array) array.sort_by{|word| word.length} end def swap_elements(array) array[1],array[2] = array[2],array[1] array end def reverse_array(array) array.reverse end def kesha_maker(array) new_array = [] array.each do |word| word[2] = "$" end array end def find_a(array) array.keep_if { |word| word.start_with?("a") } end def sum_array(array) array.inject { |a, b| a + b } end def add_s(array) array.each_with_index.map do |word, index| index != 1 ? word += "s" : word end end
true
753675d3a9faf7ed77ab36fb91e1ed237f41835d
Ruby
Telixia/leetcode-3
/Medium/0831-Masking Personal Information/Solution.rb
UTF-8
434
3.09375
3
[]
no_license
# @param {String} s # @return {String} def mask_pii(s) s.include?('@') ? mask_email(s) : mask_phone(s) end # @param {String} s # @return {String} def mask_email(s) first, remain = s.downcase.split('@') first[0] + '*****' + first[-1] + '@' + remain end # @param {String} s # @return {String} def mask_phone(s) s.delete!('+( )-') s.size == 10 ? '***-***-' + s[-4..] : '+' + '*' * (s.size - 10) + '-***-***-' + s[-4..] end
true
0b4d4a09110304cf47ab7a0cf759cc7138a5128f
Ruby
rails/rails
/activejob/lib/active_job/queue_adapters/sucker_punch_adapter.rb
UTF-8
1,615
2.546875
3
[ "MIT", "Ruby" ]
permissive
# frozen_string_literal: true require "sucker_punch" module ActiveJob module QueueAdapters # = Sucker Punch adapter for Active Job # # Sucker Punch is a single-process Ruby asynchronous processing library. # This reduces the cost of hosting on a service like Heroku along # with the memory footprint of having to maintain additional jobs if # hosting on a dedicated server. All queues can run within a # single application (e.g. \Rails, Sinatra, etc.) process. # # Read more about Sucker Punch {here}[https://github.com/brandonhilkert/sucker_punch]. # # To use Sucker Punch set the queue_adapter config to +:sucker_punch+. # # Rails.application.config.active_job.queue_adapter = :sucker_punch class SuckerPunchAdapter def enqueue(job) # :nodoc: if JobWrapper.respond_to?(:perform_async) # sucker_punch 2.0 API JobWrapper.perform_async job.serialize else # sucker_punch 1.0 API JobWrapper.new.async.perform job.serialize end end def enqueue_at(job, timestamp) # :nodoc: if JobWrapper.respond_to?(:perform_in) delay = timestamp - Time.current.to_f JobWrapper.perform_in delay, job.serialize else raise NotImplementedError, "sucker_punch 1.0 does not support `enqueued_at`. Please upgrade to version ~> 2.0.0 to enable this behavior." end end class JobWrapper # :nodoc: include SuckerPunch::Job def perform(job_data) Base.execute job_data end end end end end
true
37ab67e8ad39fb1935033ed81f89f01e3e20a40f
Ruby
burnt43/active-record-bulk-ops
/lib/active-record-bulk-ops.rb
UTF-8
7,707
2.703125
3
[]
no_license
module ActiveRecord module BulkOps class << self def comparable_ruby_version @comparable_ruby_version ||= RUBY_VERSION.split('.').map{|x| sprintf("%02d", x)}.join end end module Insertion # NOTE: The constructor takes a collection of records that have not yet # been saved to the database. We make a few assumptions for the sake # of speed: # 1. We assume that everything in the collection is an unsaved instance of # ActiveRecord::Base. # 2. We assume that the table we are INSERTing into has 'created_at' and # 'updated_at' timstamp columns. # 3. We assume that all records in the collection have the same columns # dirty. We only look at the first record and what columns are dirty # and we assume every other record has the same columns dirty. # If need be we can add options to the constructor to allow handling these # assumptions. class Insertor # The STRING_SIZE_THRESHOLD should be a power of 2 less than the # ALLOCATED_STRING_SIZE. ALLOCATED_STRING_SIZE = 2**24 STRING_SIZE_THRESHOLD = 2**23 def initialize( collection=[], override_attributes: {}, touch_created_at: false, touch_updated_at: false, set_all_columns: false ) @collection = collection return if @collection.empty? # add the timestamp columns to the override attributes complete_override_attributes = if touch_created_at || touch_updated_at timestamp = @collection[0].send(:current_time_from_proper_timezone) {created_at: timestamp, updated_at: timestamp}.merge(override_attributes) else override_attributes end # find the class for this collection. the collection needs to be # homogenous for the insert to work. @insertion_class = @collection[0]&.class # Create a set of all column names that we will be setting with out # INSERT command. column_names = if set_all_columns @insertion_class.column_names.reject do |column_name| column_name == 'id' end else # find the minimal set of columns we need to set @collection[0].send(:keys_for_partial_write).to_set end # find the active record representation of the database columns # we need to set @columns = @insertion_class.columns.select { |c| column_names.member?(c.name) } # convert the override_attributes into usable mysql values converted_override_attributes = Hash[ complete_override_attributes.stringify_keys.map do |key, value| converted_value = @insertion_class.defined_enums.dig(key, value.to_s) || value [key, @insertion_class.connection._quote(converted_value)] end ] # map active record columns to the values we will set for all records. @override_column_values = Hash[ @insertion_class .columns .select { |c| converted_override_attributes.key?(c.name) } .map { |c| [c, converted_override_attributes[c.name]] } ] end def insert! # send each 'INSERT INTO' to the mysql server insert_line_hash.values.each do |mysql_string| @insertion_class.connection.execute(mysql_string) end end private def insert_line_hash return @insert_line_hash if @insert_line_hash return {} if @collection.empty? # keep track of different indices column_index = 0 columns_max_index = (@columns.size + @override_column_values.size) - 1 insert_line_hash_index = 0 item_max_index = @collection.size - 1 # create the prefix 'INSERT INTO...' for each SQL INSERT line insert_line_prefix = String.new insert_line_prefix << "INSERT INTO `#{@insertion_class.table_name}` (" (@columns + @override_column_values.keys).each do |column| insert_line_prefix << "`#{column.name}`" unless column_index == columns_max_index insert_line_prefix << ',' end column_index += 1 end insert_line_prefix << ') VALUES ' # create a hash that maps indices to mysql strings. we don't want # this to be an array, because arrays will be contiguous in memory # and this will reduce memory operators and should be faster as a # hash insert_line_hash = { 0 => String.new(ActiveRecord::BulkOps.comparable_ruby_version > "020600" ? {capacity: ALLOCATED_STRING_SIZE} : {}) } current_insert_line = insert_line_hash[insert_line_hash_index] current_insert_line << insert_line_prefix # add mysql records @collection.each_with_index do |item, item_index| current_insert_line << '(' column_index = 0 # normal columns we must convert to a string that mysql understands @columns.each do |column| # If this column represents an enum, then we have to convert # to the integer value for the string, otherwise mysql will # interpret this as a 0 for the value no matter what. column_value_with_enum_conversion = if @insertion_class.defined_enums.key?(column.name) @insertion_class.defined_enums.dig(column.name, item.send(column.name)) else item.send(column.name) end # Convert the value of the column to something mysql understands. column_value_for_db = @insertion_class .connection ._quote(column.cast_type.type_cast_for_database(column_value_with_enum_conversion)) current_insert_line << "#{column_value_for_db}" unless column_index == columns_max_index current_insert_line << ',' end column_index += 1 end # override columns have already been converted to mysql string @override_column_values.values.each do |value| current_insert_line << "#{value}" unless column_index == columns_max_index current_insert_line << ',' end column_index += 1 end current_insert_line << ')' # check if the current mysql string is over the threshold. if so, # then we add a new string to the hash and allocate space for it # and start adding values to the new string. if we're under the # threshold, then we just add a comma and continue on filling this # string up. if insert_line_hash[insert_line_hash_index].size > STRING_SIZE_THRESHOLD insert_line_hash_index += 1 insert_line_hash[insert_line_hash_index] = String.new(ActiveRecord::BulkOps.comparable_ruby_version > "020600" ? {capacity: ALLOCATED_STRING_SIZE} : {}) current_insert_line = insert_line_hash[insert_line_hash_index] current_insert_line << insert_line_prefix elsif item_index != item_max_index current_insert_line << ',' end end @insert_line_hash = insert_line_hash end end end end end
true
b37858af1772443b53bba673bf1acffa480f8c85
Ruby
FionaDL/gif-upload
/app/models/gif.rb
UTF-8
657
2.71875
3
[]
no_license
class Gif < ApplicationRecord has_one_attached :file validates :file, size: { less_than: 10.megabytes , message: 'is not given between size' } has_many :rankings has_many :labels, through: :rankings def labels_string=(value) if value == "" return "" else result = [] labels = value.split(",") puts labels labels.each do |label_string| new_label = label_string.strip lbl = Label.find_by(name: new_label) if lbl.present? result << lbl else result << Label.new(name: new_label) end end self.labels = result end labels end end
true
dd831df603b6b323b8d17000332726620556b480
Ruby
sgibbons/partially
/partially.rb
UTF-8
679
3.09375
3
[ "MIT" ]
permissive
class Proc NOBIND = (MATCH_ONE, MATCH_ALL = :_, :*) def partially(*args_now) uncurried = self lambda do |*args_later| arity = args_now.include?(MATCH_ALL) ? (args_now.size + args_later.size - 1) : args_now.size evaluated = uncurried.curry(arity) args_now.each do |arg| evaluated = NOBIND.include?(arg) ? evaluated[args_later.pop] : evaluated[arg] if arg == MATCH_ALL args_later.each do |late_arg| evaluated = evaluated[late_arg] end break end end evaluated end end end class Symbol def partially(*args_now) self.to_proc.partially(*args_now) end end
true
18fe12a9764509f0ba8c7d850074507d81ba5027
Ruby
rterrabh/rdf
/dataset/rails/activesupport/lib/active_support/core_ext/integer/time.rb
UTF-8
319
2.765625
3
[ "MIT", "Ruby" ]
permissive
require 'active_support/duration' require 'active_support/core_ext/numeric/time' class Integer def months ActiveSupport::Duration.new(self * 30.days, [[:months, self]]) end alias :month :months def years ActiveSupport::Duration.new(self * 365.25.days, [[:years, self]]) end alias :year :years end
true
ba582a1abe440cccb5c42f115d3b78af870779a4
Ruby
joshwalsh/Permutations
/permutations.rb
UTF-8
1,458
3.859375
4
[]
no_license
testNumber = "321" class Permutations def initialize(number_to_permutate) @number_to_permutate = number_to_permutate end def possibilities low_end = find_lowest_possible_value high_end = find_highest_possible_value matches = [] (low_end..high_end).each do |value| if matches? value matches << value end end matches end def number_of_iterations (find_lowest_possible_value..find_highest_possible_value).count end private def matches?(number_to_test) test_array = number_as_array(number_to_test) match_array = number_as_array(@number_to_permutate) match_array.delete_if { |i| test_array.include?(i) } match_array.count == 0 end def find_lowest_possible_value values = number_as_array @number_to_permutate values = values.sort array_as_number values end def find_highest_possible_value values = number_as_array @number_to_permutate values = values.sort values = values.reverse array_as_number values end def number_as_array(number) number.to_s.split(//) end def array_as_number(array) array.join() end end app = Permutations.new(testNumber) start_time = Time.new puts "Getting permutations of: " + testNumber puts "Iterating over " + app.number_of_iterations.to_s + " possibilities" puts app.possibilities.inspect finish_time = Time.now puts "-----" puts "Time elapsed: " + (finish_time - start_time).to_s
true
2663373a33a8f7aab614e8c7dc4a1468c6aaa402
Ruby
CassiaCaris/calculadora_ruby
/calculadora_basica.rb
UTF-8
738
4.5
4
[]
no_license
puts "Calculadora" puts "-----------" puts "Escolha a operacao!" puts "1 Adicao" puts "2 Subtracao" puts "3 Divisao" puts "4 Multiplicacao" puts "Digite um numero?" n1 = gets.chomp().to_f puts "Digite o Numero da Operacao escolhida?" operacao = gets.chomp().to_i puts "Digite o segundo numero?" n2 = gets.chomp().to_f if operacao == 1 sum = n1 + n2 puts "#{n1} + #{n2} = #{sum}" elsif operacao == 2 menos = (n1 - n2) * -1 puts "#{n1} - #{n2} = #{menos}" elsif operacao == 3 if n2 != 0 div = n1 / n2 puts "#{n1} / #{n2} = #{div.round(2)}" else puts "Divisao Invalida! Numero nao pode ser dividido por 0!" end elsif operacao == 4 multi = n1 * n2 puts "#{n1} * #{n2} = #{multi}" end
true
46bed5e2c7819435a7dfeb2242c34a8182e3fea4
Ruby
Clark-W-Griswold/vets-api
/lib/common/models/concerns/active_record_cache_aside.rb
UTF-8
2,586
2.84375
3
[ "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
# frozen_string_literal: true module Common # Cache Aside pattern for caching an ActiveRecord::Base db record in redis. # # Requires the model mixing it in to: # - be an ActiveRecord::Base class # - implement a #cache? method # # Expects the model mixing it in to: # - set the config by calling redis and redis_ttl # - call the do_cached_with with the desired unique key # - require this class # # @see app/models/account.rb for sample usage # module ActiveRecordCacheAside extend ActiveSupport::Concern REDIS_CONFIG = Rails.application.config_for(:redis).freeze included do unless self < ActiveRecord::Base raise ArgumentError, 'Class composing Common::ActiveRecordCacheAside must be an ActiveRecord' end def self.redis(namespace) @redis_namespace = Redis::Namespace.new(namespace, redis: Redis.current) end def self.redis_ttl(ttl) @redis_namespace_ttl = ttl end # Returns the cached ActiveRecord object that is cached by the passed in key. # # If the db record is already cached, it will return that. If it is not, # it will cache the yielded record before returning it. # # @param key [String] The unique key that will be concatenated with the # redis_namespace, to be used together as the Redis key # @return [ActiveRecord::Base] Returns a database record that inherits # from ActiveRecord::Base # # rubocop:disable Security/MarshalLoad def self.do_cached_with(key:) cached = @redis_namespace.get(key) return Marshal.load(cached) if cached record = yield raise NoMethodError, 'The record class being cached must implement #cache?' unless record.respond_to?(:cache?) cache_record(key, record) if record.cache? record end # rubocop:enable Security/MarshalLoad # Caches the passed ActiveRecord db record, caching it with the # passed key. Also sets the caches expiration based on the # @redis_namespace_ttl that is set in the mixed in model class. # # @param key [String] The unique key that will be concatenated with the # redis_namespace, to be used together as the Redis key # @param record [ActiveRecord::Base] The ActiveRecord::Base db record to be cached # def self.cache_record(key, record) serialized = Marshal.dump(record) @redis_namespace.set(key, serialized) @redis_namespace.expire(key, @redis_namespace_ttl) end end end end
true
9e7ad4e0ff0a972ebab363ace6dc8cc57a5d0ac7
Ruby
ali-mohamed/web-parser
/app/models/parser.rb
UTF-8
753
2.78125
3
[]
no_license
require 'readability' require 'open-uri' require 'json' class Parser def self.parse_div_contents_into_array(content) body = [] content.children.each do |f| if f.name == 'div' inner_content = parse_div_contents_into_array(f) else inner_content = f.inner_html end body << inner_content if inner_content.length != 0 end body end def self.parse(url) source = open(url).read content = Nokogiri::HTML::DocumentFragment.parse(Readability::Document.new(source, remove_empty_nodes: true).content) article = { title: Readability::Document.new(source, remove_empty_nodes: true).title } article[:content] = parse_div_contents_into_array(content) json = article.to_json end end
true
76d3f3140c0bddec922da57293da2c4ba73b039e
Ruby
nitinsavant/ruby_exercises
/ruby_challenges/octal.rb
UTF-8
344
3.453125
3
[]
no_license
class Octal attr_reader :octal def initialize(digits) @octal = test_valid_input(digits) end def to_decimal decimal = 0 1.upto(octal.length) do |num| decimal += (octal[-num].to_i * 8 ** (num-1)) end decimal end private def test_valid_input(digits) digits =~ /[a-zA-Z8-9]/ ? "0" : digits end end
true
5d894a502035df700cfea1050fa1d1dd2c0741bd
Ruby
zhujiale2/HITS-Project
/patent-app/lib/assets/patents/cites.rb
UTF-8
478
2.796875
3
[]
no_license
cite = Hash.new([]) IO.foreach("cite75_99.csv"){|cit| a = cit.to_i b = cit[8..100].to_i cite[a] = cite[a]+[b] } puts "loaded" for i in 11..69 pats = Array.new File.open("pat#{i}.csv", "r") do |patFile| pats = patFile.readlines() end citeFile = File.new("cite#{i}.txt", "a") for j in 0..pats.size-1 code = pats[j].to_i citeFile.puts("#{code}") for k in 0..cite[code].size-1 citeFile.print("#{cite[code][k]} ") end citeFile.puts() end citeFile.close end
true
7252da5e1707d982e3202474f92a1956dc1fbaf1
Ruby
soutaro/jack_and_the_elastic_beanstalk
/lib/jack_and_the_elastic_beanstalk/runner.rb
UTF-8
1,580
2.59375
3
[]
no_license
module JackAndTheElasticBeanstalk class Runner attr_reader :stdin attr_reader :stdout attr_reader :stderr attr_reader :logger def initialize(stdin:, stdout:, stderr:, logger:) @stdin = stdin @stdout = stdout @stderr = stderr @paths = [Pathname.pwd] @logger = logger end def paths id = "#{inspect}:paths".to_sym unless Thread.current[id] Thread.current[id] = @paths.dup end Thread.current[id] end def chdir(dir) paths.push dir yield ensure paths.pop end def pwd paths.last end def each_line(string, prefix: nil) Array(string).flat_map {|s| s.split(/\n/) }.each do |line| if prefix yield "#{prefix}: #{line}" else yield line end end end def capture3(*commands, options: {}, env: {}) logger.debug("jeb") { commands.inspect } Open3.capture3(env, *commands, { chdir: pwd.to_s }.merge(options)).tap do |out, err, status| logger.debug("jeb") { status.inspect } each_line(out, prefix: "stdout") do |line| logger.debug("jeb") { line } end each_line(err, prefix: "stderr") do |line| logger.debug("jeb") { line } end end end def capture3!(*commands, options: {}, env: {}) out, err, status = capture3(*commands, options: options, env: env) unless status.success? raise "Faiiled to execute command: #{commands.inspect}" end [out, err] end end end
true
1d6c780558c6e073c7c441af5694b645bf5f82c8
Ruby
lucignolo/events1617
/provaOttobre0.rb
UTF-8
1,254
2.75
3
[]
no_license
#!/usr/local/bin/ruby base0 = "@book.update_attribute(XXX,YYY)" provaHash = Hash(titolo: Hash(ok: ["titolononbidone","titoloqualunque"], nok: ["titolobidone"]), copie: Hash(ok: [1, 2, 50] , nok: [0, -1]), deposito: Hash(ok: [false] , nok: [true]) ) p provaHash.inspect provaHash.each do |kcond, vcond| p kcond p vcond vcond[:ok].each.with_index do |valore, indice| p "---...---...#{valore.inspect} #{indice}" base0 = "@book.update_attribute(XXX,YYY)" nomeCampo = "'#{kcond.to_s}'" modiA = base0.gsub(/XXX/, nomeCampo) # case kcond when :titolo valoreCampo = "'#{valore}'" modif = modiA.gsub(/YYY/, valoreCampo) when :copie valoreCampo = valore.to_s modif = modiA.gsub(/YYY/, valoreCampo) when :deposito valoreCampo = 'false' if !valore valoreCampo = 'true' if valore modif = modiA.gsub(/YYY/, valoreCampo) else modif = "non calcolato" end puts "gen: #{modif}" end # vcond[:nok].each.with_index do |valore, indice| p "===...---...#{valore.inspect} #{indice}" #gen_modificaAttributo(kcond, valore) end end
true
85c50b603b8e93de11e33e3cbd8e314bfb3d2de1
Ruby
strychemi/assignment_file_ops_sprint
/dictionary_loader.rb
UTF-8
516
3.296875
3
[]
no_license
class DictionaryLoader def self.load(dictionary_file) return false unless File.exists?(dictionary_file) # check if dictionary_file is a valid path dictionary = Dictionary.new File.open(dictionary_file).each do |line| word = line.strip dictionary.add_word(word) end puts "Dictionary successfully loaded" puts "Your dictionary contains #{dictionary.size} words." puts "Word frequency starting by letter:" dictionary.display_letter_frequencies dictionary end end
true
172b190bca4bf6b657de14d144922c4646536d84
Ruby
Lo1176/codewar
/test.rb
UTF-8
250
3.328125
3
[]
no_license
def solution(number) # put your solution here divisible_numbers = [] for n in 1..number if n % 3 == 0 || n % 5 == 0 divisible_numbers.push(n) end divisible_numbers.sum end end puts solution(10) puts "____" puts divisible_numbers
true
522724eaf9c2bf729475df14cf6083dda645e36b
Ruby
Srjordao/One-Bit-Code
/OperadoresMatematicos.rb
UTF-8
181
3.28125
3
[]
no_license
+ (Adição) – (Subtração) * (Multiplicação) / (Divisão) % (Módulo) ** (Expoente) #soma 5+5 = 10 #menos 1-1 = 0 #multi 2*2 = 4 #divisao 2/2 = 1 #modulo 10%3 = #expo 2**3
true
6f9f4132a22c90456fe3b460e2a162ad3caaf25e
Ruby
nergdnvlt-zz/euler_poker
/test/game_test.rb
UTF-8
14,202
3.21875
3
[]
no_license
require 'minitest/autorun' require 'minitest/pride' require 'pry' require './lib/game.rb' class GameTest < MiniTest::Test def test_it_exists game = Game.new('5H 5C 6S 7S KD 2C 3S 8S 8D TD') assert_instance_of Game, game end def test_it_makes_two_hands game = Game.new('5H 5C 6S 7S KD 2C 3S 8S 8D TD') player_1 = game.player_1 player_2 = game.player_2 assert_equal player_1.cards[0].card, '5H' assert_equal player_1.cards[1].card, '5C' assert_equal player_1.cards[2].card, '6S' assert_equal player_1.cards[3].card, '7S' assert_equal player_1.cards[4].card, 'KD' assert_equal player_2.cards[0].card, '2C' assert_equal player_2.cards[1].card, '3S' assert_equal player_2.cards[2].card, '8S' assert_equal player_2.cards[3].card, '8D' assert_equal player_2.cards[4].card, 'TD' end def test_royal_flush_wins_player_1 game = Game.new('TS JS QS KS AS 9D TD JD QD KD') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_royal_flush_wins_player_2 game = Game.new('9D TD JD QD KD TC JC QC KC AC') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_both_have_royal_flush game = Game.new('TS JS QS KS AS TC JC QC KC AC') winner = game.winner assert_equal 'tie', winner end def test_straight_flush_player_1 game = Game.new('9D TD JD QD KD 3C 2C TC 8C AC') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_straight_flush_player_2 game = Game.new('9D 9C 9S KS KD 2C 3C 4C 5C 6C') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_tie_straight_flush_player_1 game = Game.new('6D 7D 8D 9D TD 2C 3C 4C 5C 6C') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_tie_straight_flush_player_2 game = Game.new('6D 7D 8D 9D TD 7C 8C 9C TC JC') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_real_tie_straight_flush game = Game.new('6D 7D 8D 9D TD 6C 7C 8C 9C TC') winner = game.winner assert_equal 'tie', winner end def test_four_of_a_kind_player_1 game = Game.new('8D 8S 8H 8C KD 3C 3D TC 9D AC') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_four_of_a_kind_player_2 game = Game.new('5D 8S 8H 8C KD 3C 3D 3S 3H AC') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_four_of_a_kind__tie_player_1 game = Game.new('8D 8S 8H 8C KD 3C 3D 3S 3H AC') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_four_of_a_kind__tie_player_2 game = Game.new('8D 8S 8H 8C KD 9C 9D 9S 9H AC') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_full_house_player_1 game = Game.new('8D 8S 8H KC KD 3C 3D TC 9D AC') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_full_house_player_2 game = Game.new('8D 8S 6H KC KD 3C 3D 3S AD AC') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_full_house_tie_player_1 game = Game.new('8D 8S 8H KC KD 3C 3D 3S AD AC') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_full_house_tie_player_2 game = Game.new('8D 8S 8H KC KD TC TD TS AD AC') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_flush_player_1 game = Game.new('2D 4D 5D TD KD 3C 3D TC 9D AC') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_flush_player_2 game = Game.new('2C 4S 5D TD KD 2D 3D TD 9D AD') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_tie_flush_player_1 game = Game.new('2D 4D 5D TD KD 3C 2C TC 9C 6C') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_tie_flush_player_2 game = Game.new('2D 4D 5D TD KD 3C 2C TC 9C AC') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_nested_tie_flush_player_1 game = Game.new('2D 4D 5D QD KD 3C 2C 8C TC KC') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_nested_tie_flush_player_2 game = Game.new('2D 4D 5D 9D KD 3C 2C 8C TC KC') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_double_nested_tie_flush_player_1 game = Game.new('2D 4D 8D QD KD 3C 2C 7C TC KC') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_double_nested_tie_flush_player_2 game = Game.new('2D 4D 8D QD KD 3C 2C TC QC KC') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_triple_nested_tie_flush_player_1 game = Game.new('2D 4D 8D QD KD 3C 2C 8C TC KC') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_triple_nested_tie_flush_player_2 game = Game.new('2D 4D 8D QD KD 5C 2C 8C TC KC') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_quad_nested_tie_flush_player_1 game = Game.new('3D 4D 8D QD KD 4C 2C 8C QC KC') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_quad_nested_tie_flush_player_2 game = Game.new('2D 4D 8D QD KD 4C 3C 8C QC KC') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_straight_player_1 game = Game.new('2C 3S 5D 4D 6D 2D 3D TH 9C AD') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_straight_player_2 game = Game.new('AC 2D 3H 8S 7S 8D 9D TH JC QD') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_straight_tie_player_1 game = Game.new('3H 4S 5S 6C 7D 2C 3S 5D 4D 6D') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_straight_tie_player_2 game = Game.new('3H 4S 5S 6C 7D 5C 6S 7D 8D 9D') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_straight_tie_no_winner game = Game.new('3H 4S 5S 6C 7D 3C 4C 5D 6D 7S') winner = game.winner assert_equal 'tie', winner end def test_three_of_a_kind_player_1 game = Game.new('3H 3C 3D 2C 7D 2D 2C 5D 6H 7S') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_three_of_a_kind_player_1 game = Game.new('3H 3C AD 4C 7D 2D 2C 2S 6H 7S') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_three_of_a_kind__tie_player_1 game = Game.new('3H 3C 3D 2C 7D 2D 2C 2S 6H 7S') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_three_of_a_kind__tie_player_2 game = Game.new('3H 3C 3D 2C 7D 4D 4C 4S 6H 7S') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_two_pair_player_1 game = Game.new('3H 3C 4D 4C 7D 2D 2C 5D 6H 7S') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_two_pair_player_2 game = Game.new('3H 2C 4D 4C 7D 2D 2C 5D 5H 7S') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_two_pair_tie_player_1 game = Game.new('3H 3C 5D 5C 7D 2D 2C 4H 4S 7S') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_two_pair_tie_player_2 game = Game.new('3H 3C 5D 5C 7D 2D 2C 6H 6S 7S') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_two_pair_nested_tie_player_1 game = Game.new('3H 3C 4D 4C 8D 2D 2C 4H 4S 7S') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_two_pair_nested_tie_player_2 game = Game.new('2H 2C 4D 4C 8D 3D 3C 4H 4S 7S') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_two_pair_double_nested_tie_player_1 game = Game.new('3H 3C 4D 4C 9D 3D 3S 4H 4S 8S') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_two_pair_double_nested_tie_player_2 game = Game.new('3H 3C 4D 4C 8D 3D 3S 4H 4S TS') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_two_pair_double_nested_tie_no_winner game = Game.new('3H 3C 4D 4C 8D 3D 3S 4H 4S 8S') winner = game.winner assert_equal 'tie', winner end def test_one_pair_player_1 game = Game.new('3H 3C 2D 4C 7D 2D 3C 5D 6H 7S') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_one_pair_player_2 game = Game.new('3H 8C 2D 4C 7D 2D 5C 5D 6H 7S') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_one_pair_tie_player_1 game = Game.new('3H 3C 2D 4C KD 2D 2C 5D 6H 7S') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_one_pair_tie_player_2 game = Game.new('3H 3C 2D 4C KD 8D 8C 5D 6H 7S') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_one_pair_first_tie_player_1 game = Game.new('3H 3C 2D 4C KD 3D 3C 5D 6H 7S') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_one_pair_first_tie_player_2 game = Game.new('3H 3C 2D 4C QD 3D 3C 5D 6H KS') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_one_pair_double_tie_player_1 game = Game.new('3H 3C 2D QC KD 3D 3C 5D 6H KS') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_one_pair_double_tie_player_2 game = Game.new('3H 3C 2D 4C KD 3D 3C 5D QH KS') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_one_pair_triple_tie_player_1 game = Game.new('3H 3C TD QC KD 3D 3C 5D QH KS') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_one_pair_triple_tie_player_2 game = Game.new('3H 3C 2D QC KD 3D 3C 5D QH KS') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_one_pair_triple_tie_no_winner game = Game.new('3H 3C 5S QC KD 3D 3C 5D QH KS') winner = game.winner assert_equal 'tie', winner end def test_high_card_player_1 game = Game.new('3H 8C 2D 4C KD 2D 3C 5D 6H 7S') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_high_card_player_2 game = Game.new('3H 8C 2D 4C QD 2D 3C 5D 6H KS') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_high_card_first_tie_player_1 game = Game.new('3H 8C 2D JC KD 2D 3C 5D 6H KS') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_high_card_first_tie_player_2 game = Game.new('3H 8C 2D TC KD 2D 3C 5D JH KS') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_high_card_second_tie_player_1 game = Game.new('3H 8C 2D JC KD 2D 3C 5D JH KS') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_high_card_second_tie_player_2 game = Game.new('3H 8C 2D JC KD 2D 3C TD JH KS') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_high_card_triple_tie_player_1 game = Game.new('4H 8C 2D JC KD 2D 3C 8D JH KS') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_high_card_triple_tie_player_2 game = Game.new('3H 2C TD JC KD 2D 5C TD JH KS') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_high_card_quad_tie_player_1 game = Game.new('4H 8C 3D JC KD 2D 4C 8D JH KS') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_high_card_quad_tie_player_2 game = Game.new('5H 2C TD JC KD 4D 5C TD JH KS') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_high_card_last_tie_no_winner game = Game.new('4H 8C 3D JC KD 3S 4C 8D JH KS') winner = game.winner assert_equal 'tie', winner end def test_hand_1 game = Game.new('5H 5C 6S 7S KD 2C 3S 8S 8D TD') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_hand_2 game = Game.new('5D 8C 9S JS AC 2C 5C 7D 8S QH') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_hand_3 game = Game.new('2D 9C AS AH AC 3D 6D 7D TD QD') player_2 = game.player_2 winner = game.winner assert_equal player_2, winner end def test_hand_4 game = Game.new('4D 6S 9H QH QC 3D 6D 7H QD QS') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end def test_hand_5 game = Game.new('2H 2D 4C 4D 4S 3C 3D 3S 9S 9D') player_1 = game.player_1 winner = game.winner assert_equal player_1, winner end end
true
c0b3f0684b0f1eb48c8a0956194b0f8f96f7f6dd
Ruby
morgano24/fullstack-challenges
/03-AR-Database/03-ActiveRecord-Basics/04-Seed-API/db/seeds.rb
UTF-8
385
2.796875
3
[]
no_license
require "json" require "rest-client" # TODO: Write a seed to insert 10 posts in the database fetched from the Hacker News API. response = RestClient.get "https://hacker-news.firebaseio.com/v0/topstories.json" posts = eval(response)[0...10] posts.to_a.each do |n| resp = RestClient.get("https://hacker-news.firebaseio.com/v0/item/#{n}.json?print=pretty") p JSON.parse(resp) end
true
9525537930485daee74c1622952d052f064896f6
Ruby
dladowitz/night-market
/app/models/event.rb
UTF-8
2,066
2.53125
3
[]
no_license
# == Schema Information # # Table name: events # # id :integer not null, primary key # name :string(255) not null # guests :integer not null # user_id :integer # location :string(255) # start_date :date # end_date :date # budget :integer # gluten_free :boolean # vegetarian :boolean # vegan :boolean # created_at :datetime # updated_at :datetime # class Event < ActiveRecord::Base #TODO should move boolean options like vegan and needs_ice out to something else validates :name, presence: true validates :guests, presence: true, numericality: true validates :user_id, presence: true, numericality: true validates_datetime :start_date, :end_date #TODO change these to start and end belongs_to :user has_many :meals has_many :supplies def overbudget? current_spend > budget if current_spend && budget end def current_spend total = meals_cost + supplies_cost end def cost_overage current_spend - budget if current_spend > budget end def supplies_cost total = 0 supplies.each do |supply| total += supply.cost if supply.cost end total || 0 end def get_cost_items items = meals.where("cost is not ?", nil) items += supplies.where("cost is not ?", nil) end def show_warnings? meals.each do |meal| return true if meal.warning_messages.present? && !meal.ignore_warnings end return false end def missing_supplies # not sure why this doesn't work # supplies.where("purchased = ? OR purchased = ?", false, nil) missing_supplies = supplies.where(purchased: nil) missing_supplies += supplies.where(purchased: false) return missing_supplies end #TODO create spec def recommended_supply_count ((guests * meals.count) + (0.15 * guests * meals.count)).round end private def meals_cost total = 0 meals.each do |meal| total += meal.cost if meal.cost end total || 0 end end
true
1b8c9e971b61548b1a5cd28b430b4eac057f76c6
Ruby
joecarlyon/imgur_uploader
/spec_helper.rb
UTF-8
1,074
2.6875
3
[]
no_license
require 'selenium-webdriver' require 'rspec' # Import all files from a given directory, so nothing needs to get updated once adding/removing from there Dir[File.dirname(__FILE__) + '/pages/*.rb'].each {|file| require_relative file} # Let's restrict this to Firefox because it's only a code sample # def setup if ENV['BROWSER'] == 'firefox' $driver = Selenium::WebDriver.for :firefox elsif ENV['BROWSER'] == 'chrome' $driver = Selenium::WebDriver.for :chrome else puts 'The only valid browser options are [firefox | chrome]' end end # Make sure to exit the browser after each test # def teardown $driver.quit end RSpec.configure do |c| c.before :each do setup end c.after :each do teardown end c.after :suite do puts 'All tests have ran' end end # Helper method to load Imgur # def load_imgur $driver.navigate.to 'https://imgur.com/' end # Helper method to return the title of the current page # def get_page_title $driver.title end # Helper method to get the current URL # def get_page_url $driver.current_url end
true
04871cb1ba285f484421000300266db1b1b99d80
Ruby
Diogomsantoss/delivery_tools
/lib/shipping_watcher/trackers/correios_tracker.rb
UTF-8
2,529
2.640625
3
[]
no_license
require 'correios-sro-xml' # This is a Pure Ruby Object class, its methods return clean data, to be stored in the database # It sums the three arguments and returns that value. # class CorreiosTracker #shipped #transit #delivered #failed COMMON_STATES = [2,3,4,5,6,7,8,9,10,12,19,20,21,22,23,24,25,26,28,32,33,34,35,36,37,38,40,41,42,43,45,46,47,48,49,50,51,52,53,55,56,57,58,59,69] TIPOS = { 1 => {'BDE' => [], 'BDI' => [], 'BDR' => [], 'BLQ' => [], 'CAR' => [], 'CD' => [], 'CMT' => [], 'CO' => [], 'CUN' => [], 'DO' => [], 'EST' => [], 'FC' => [], 'IDC' => [], 'LDI' => [], 'LDE' => [], 'OEC' => [], 'PAR' => [], 'PMT' => [], 'PO' => [0,1,9], 'RO' => [], 'TRI' => []}, 2 => {'BDE' => [], 'BDI' => [], 'BDR' => [], 'BLQ' => [], 'CAR' => [], 'CD' => [0,1,2,3], 'CMT' => [0], 'CO' => [1], 'CUN' => [0,1], 'DO' => [0,1,2], 'EST' => [1,2,3,4,5,6,9], 'FC' => [2,3], 'IDC' => [], 'LDI' => [], 'LDE' => [], 'OEC' => [0], 'PAR' => [15,16,17,18], 'PMT' => [1], 'PO' => [], 'RO' => [0,1], 'TRI' => [0]}, 3 => {'BDE' => [0, 1], 'BDI' => [0, 1], 'BDR' => [0, 1], 'BLQ' => [], 'CAR' => [], 'CD' => [], 'CMT' => [], 'CO' => [], 'CUN' => [], 'DO' => [], 'EST' => [], 'FC' => [], 'IDC' => [], 'LDI' => [], 'LDE' => [], 'OEC' => [], 'PAR' => [], 'PMT' => [], 'PO' => [], 'RO' => [], 'TRI' => []}, 4 => {'BDE' => COMMON_STATES, 'BDI' => COMMON_STATES, 'BDR' => COMMON_STATES, 'BLQ' => [1], 'CAR' => [], 'CD' => [], 'CMT' => [], 'CO' => [], 'CUN' => [], 'DO' => [], 'EST' => [], 'FC' => [1,4,5,7], 'IDC' => [1,2,3,4,5,6,7,8,9], 'LDI' => [1,2,3,14], 'LDE' => [], 'OEC' => [], 'PAR' => [], 'PMT' => [], 'PO' => [], 'RO' => [], 'TRI' => []} } @user @password @tracking_code @sro def initialize(user, password, code) @user = user @password = password @tracking_code = code end def valid? get_sro.nil? ? false : true end def status index = TIPOS.map do |o| o.last[get_sro.events[0].type].grep(get_sro.events[0].status.to_i).any? ? o.first : next end if index.compact!.length == 1 index.first else 4 end end def log {snapshot: get_sro.to_json, code: @tracking_code, message: get_sro.events[0].description, status_id: status} end private def get_tracking Correios::SRO::Tracker.new(user: @user, password: @password) end def get_sro @sro ||= get_tracking.get(@tracking_code) end def get_webservice_response Hash.from_xml(Correios::SRO::WebService.new(get_tracking).request!) end end
true
910079fa5a843ac8d8eebfa881a10a50256e40c7
Ruby
domi10momo/TravelApp
/app/models/course_param.rb
UTF-8
378
2.78125
3
[]
no_license
class CourseParam def initialize @model_course_id = 0 @route_id = 0 # course_routesテーブルのid @order_number = 0 # 観光順序を表す値 end def upper_course_id @model_course_id += 1 end def upper_route_id @route_id += 1 end def upper_order_number @order_number += 1 end def order_reset @order_number = 0 end end
true
2f3c53bc868861ecf424d68fe22743444f8c4c4f
Ruby
gkosae/spreadshot
/lib/spreadshot/reader.rb
UTF-8
5,574
3.140625
3
[ "MIT" ]
permissive
module Spreadshot class Reader # @param [Hash] options # @option options [Symbol, Spreadshot::ReaderBackend] :backend # The reader backend to use or the id if one of the provided backends # @option options [Hash] :backend_options # Required if one of the provided backends is used # * :headers (Boolean) [true] Specifies whether the spreadsheet to be read contains headers. Will be ignored if the backend doesn't provide this option (E.g. SmarterCSV expects headers) # * :worksheet_index (Integer) [0] The index of the worksheet to be read. Used for the RubyXL backend # * :cell_index_to_field_mapper (Hash<Integer, [String, Symbol]>) A hash which maps each cell in a row of the spreadsheet to a key in the result hash created for that row. Must be provided for the RubyXL backend # # @example # reader = Spreadshot::Reader.new(backend: :smarter_csv) # # reader = Spreadshot::Reader.new(backend: :ruby_xl, worksheet_index: 0, cell_index_to_field_mapper: {0 => :H1, 1 => :H2, 2 => :H3, 3 => :H4}) # # xlsx_backend = Spreadshot::Backends::RubyXLBackend.new(worksheet_index: 0, cell_index_to_field_mapper: {0 => :H1, 1 => :H2, 2 => :H3, 3 => :H4}) # reader = Spreadshot::Reader.new(backend: xlsx_backend) def initialize(options) set_backend(options[:backend], options[:backend_options]) end # Set the backend to use # # @param [Symbol, Spreadshot::Backends::ReaderBackend] backend # The new backend or id of one of the provided backends # @param [Hash] backend_options # Required if one of the provided backends is used # @option backend_options [Boolean] :headers # Specifies whether the spreadsheet to be read contains headers. # Will be ignored if the backend doesn't provide this option (E.g. SmarterCSV expects headers) # Defaults to true # @option backend_options [Integer] :worksheet_index # The index of the worksheet to be read. Used for the RubyXL backend. # Defaults to 0 # @option backend_options [Hash<Integer, [Symbol, String]>] :cell_index_to_field_mapper # A hash which maps each cell in a row of the spreadsheet to a key in the # result hash created for that row. Used for the RubyXL backend. # Must be provided # # @raise [Spreadshot::BackendNotFound] # If no backend is provided or if one of the provided backends is not specified # # @example # reader = Spreadshot::Reader.new(backend: :ruby_xl, worksheet_index: 0, cell_index_to_field_mapper: {0 => :H1, 1 => :H2, 2 => :H3, 3 => :H4}) # csv_backend = Spreadshot::Backends::SmarterCSVBackend.new # reader.set_backend(csv_backend) def set_backend(backend, backend_options = {}) @backend = (backend.is_a?(Spreadshot::Backends::ReaderBackend)) ? backend : build_backend( backend, backend_options ) raise Spreadshot::BackendNotFound if @backend.nil? end # Reads data from the specified spreadsheet # # @param [String] path_to_spreadsheet # # @yield [row_index, row_data] # @yieldparam [Integer] row_index # The index of the current row being read. The first row has an index of 1 # @yieldparam [Hash] row_data # A hash representation of the data read from the current row # # @note This method delegates actual reading to the backend # # @example # reader = Spreadshot::Reader.new(backend: :ruby_xl, worksheet_index: 0, cell_index_to_field_mapper: {0 => :H1, 1 => :H2, 2 => :H3, 3 => :H4}) # reader.read('spreadshot_test.xlsx'){|row_index, row_data| puts "#{row_index} - #{row_data}"} # # Sample output # 2 - {:H1=>11, :H2=>22, :H3=>33, :H4=>44} # 3 - {:H1=>111, :H2=>222, :H3=>333, :H4=>444} # 4 - {:H1=>1111, :H2=>2222, :H3=>3333, :H4=>4444} def read(path_to_spreadsheet) @backend.read(path_to_spreadsheet) {|row_index, row_data| yield(row_index, row_data)} end private # Creates a reader backend using the backend (id) and options/backend_options provided in #initialize or #set_backend # # @param [Symbol] backend_id the id(key) of the desired backend # @param [Hash] backend_options # options to build the backend with # @option backend_options [Boolean] :headers # Specifies whether the spreadsheet to be read contains headers. # Will be ignored if the backend doesn't provide this option (E.g. SmarterCSV expects headers) # Defaults to true # @option backend_options [Integer] :worksheet_index # The index of the worksheet to be read. Used for the RubyXL backend. # Defaults to true # @option backend_options [Hash<Integer, [Symbol, String]>] :cell_index_to_field_mapper # A hash which maps each cell in a row of the spreadsheet to a key in the # result hash created for that row. Used for the RubyXL backend. # Must be provided # # @return [Spreadshot::Backends::ReaderBackend] def build_backend(backend_id, backend_options = {}) backend_options ||= {} return provided_backends[backend_id].call(backend_options) rescue NoMethodError return nil end # The provided backends # # @return [Hash] def provided_backends { smarter_csv: ->(backend_options){ Spreadshot::Backends::SmarterCSVBackend.new(backend_options) }, ruby_xl: ->(backend_options){ Spreadshot::Backends::RubyXLBackend.new(backend_options) }, } end end end
true
fc0f6853d9a0e0f1bb661d313c7bcb0660bb1858
Ruby
zendesk/biz
/spec/day_time_spec.rb
UTF-8
7,818
2.953125
3
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
# frozen_string_literal: true RSpec.describe Biz::DayTime do subject(:day_time) { described_class.new(day_second(hour: 9, min: 53, sec: 27)) } context 'when initializing' do context 'with a valid integer-like value' do it 'is successful' do expect { described_class.new('1') }.not_to raise_error end end context 'with an invalid integer-like value' do it 'fails hard' do expect { described_class.new('1one') }.to raise_error ArgumentError end end context 'with a non-integer value' do it 'fails hard' do expect { described_class.new([]) }.to raise_error TypeError end end context 'with a negative value' do it 'fails hard' do expect { described_class.new(-1) }.to raise_error ArgumentError end end context 'when a zero value' do it 'is successful' do expect { described_class.new(0).day_second }.not_to raise_error end end context 'when the value is the number of seconds in a day' do it 'is successful' do expect { described_class.new(Biz::Time.day_seconds) }.not_to raise_error end end context 'when the value is more than the number of seconds in a day' do it 'fails hard' do expect { described_class.new(Biz::Time.day_seconds + 1) }.to raise_error ArgumentError end end end describe '.from_time' do let(:time) { Time.utc(2006, 1, 1, 9, 38, 47) } it 'creates a day time from the given time' do expect(described_class.from_time(time)).to eq( described_class.new(day_second(hour: 9, min: 38, sec: 47)) ) end end describe '.from_hour' do it 'creates a day time from the given hour' do expect(described_class.from_hour(9)).to eq( described_class.new(day_second(hour: 9)) ) end end describe '.from_minute' do it 'creates a day time from the given from' do expect(described_class.from_minute(day_minute(hour: 9, min: 10))).to eq( described_class.new(day_second(hour: 9, min: 10)) ) end end describe '.from_timestamp' do context 'when the timestamp is not a timestamp' do let(:timestamp) { 'timestamp' } it 'raises a configuration error' do expect { described_class.from_timestamp(timestamp) }.to raise_error Biz::Error::Configuration end end context 'when the timestamp is in `H:MM` format' do let(:timestamp) { '5:35' } it 'raises a configuration error' do expect { described_class.from_timestamp(timestamp) }.to raise_error Biz::Error::Configuration end end context 'when the timestamp is in `HH:M` format' do let(:timestamp) { '12:3' } it 'raises a configuration error' do expect { described_class.from_timestamp(timestamp) }.to raise_error Biz::Error::Configuration end end context 'when the timestamp is in `HH:MM:S` format' do let(:timestamp) { '11:35:3' } it 'raises a configuration error' do expect { described_class.from_timestamp(timestamp) }.to raise_error Biz::Error::Configuration end end context 'when the timestamp is in `HH:MM` format' do let(:timestamp) { '21:43' } it 'returns the appropriate day time' do expect(described_class.from_timestamp(timestamp)).to eq( described_class.new(day_second(hour: 21, min: 43)) ) end end context 'when the timestamp is in `HH:MM:SS` format' do let(:timestamp) { '10:55:23' } it 'returns the appropriate day time' do expect(described_class.from_timestamp(timestamp)).to eq( described_class.new(day_second(hour: 10, min: 55, sec: 23)) ) end end end describe '.midnight' do it 'creates a day time that represents midnight' do expect(described_class.midnight).to eq( described_class.new(day_second(hour: 0)) ) end end describe '.endnight' do it 'creates a day time that represents the end-of-day midnight' do expect(described_class.endnight).to eq( described_class.new(day_second(hour: 24)) ) end end describe '#day_second' do it 'returns the number of seconds into the day' do expect(day_time.day_second).to eq day_second(hour: 9, min: 53, sec: 27) end end describe '#hour' do it 'returns the hour' do expect(day_time.hour).to eq 9 end end describe '#minute' do it 'returns the minute' do expect(day_time.minute).to eq 53 end end describe '#second' do it 'returns the second' do expect(day_time.second).to eq 27 end end describe '#day_minute' do it 'returns the number of minutes into the day' do expect(day_time.day_minute).to eq 593 end end describe '#for_dst' do context 'when the day time is midnight' do let(:day_time) { Biz::DayTime.midnight } it 'returns a day time one hour later' do expect(day_time.for_dst).to eq described_class.new(day_second(hour: 1)) end end context 'when the day time is noon' do let(:day_time) { Biz::DayTime.new(day_second(hour: 12)) } it 'returns a day time one hour later' do expect(day_time.for_dst).to eq described_class.new(day_second(hour: 13)) end end context 'when the day time is one hour before endnight' do let(:day_time) { Biz::DayTime.new(day_second(hour: 23)) } it 'returns a midnight day time' do expect(day_time.for_dst).to eq described_class.midnight end end context 'when the day time is less than one hour before endnight' do let(:day_time) { Biz::DayTime.new(day_second(hour: 23, min: 40)) } it 'returns a day time just after midnight' do expect(day_time.for_dst).to eq( described_class.new(day_second(hour: 0, min: 40)) ) end end context 'when the day time is endnight' do let(:day_time) { Biz::DayTime.endnight } it 'returns a day time one hour after midnight' do expect(day_time.for_dst).to eq described_class.new(day_second(hour: 1)) end end end describe '#timestamp' do context 'when the hour and minute are single-digit values' do subject(:day_time) { described_class.new(day_second(hour: 4, min: 3)) } it 'returns a zero-padded timestamp' do expect(day_time.timestamp).to eq '04:03' end end context 'when the hour and minute are double-digit values' do subject(:day_time) { described_class.new(day_second(hour: 15, min: 27)) } it 'returns a correctly formatted timestamp' do expect(day_time.timestamp).to eq '15:27' end end end context 'when performing comparison' do context 'and the compared object is an earlier day time' do let(:other) { described_class.new(day_second(hour: 9, min: 53, sec: 26)) } it 'compares as expected' do expect(day_time > other).to eq true end end context 'and the compared object is the same day time' do let(:other) { described_class.new(day_second(hour: 9, min: 53, sec: 27)) } it 'compares as expected' do expect(day_time == other).to eq true end end context 'and the other object is a later day time' do let(:other) { described_class.new(day_second(hour: 9, min: 53, sec: 28)) } it 'compares as expected' do expect(day_time < other).to eq true end end context 'and the compared object is not a day time' do let(:other) { 1 } it 'is not comparable' do expect { day_time < other }.to raise_error ArgumentError end end end end
true
b416bf0939aad0b859f9823e718dbce025a0ff1c
Ruby
spemmons/rails-example
/app/controllers/api/jog_time_controller.rb
UTF-8
3,255
2.515625
3
[]
no_license
class Api::JogTimeController < ApiController before_filter :authorize_user before_action :set_user before_action :set_jog_time,except: [:index,:create,:weekly_summary] def index scope = @user.jog_times scope = scope.limit(params[:limit]) if params[:limit] and params[:limit].to_i > 0 scope = scope_by_sort(scope,params[:sort]) scope = scope_by_date_range(scope,params[:from],params[:to]) render inline: scope.all.to_a.to_json end def show return missing_jog_time unless @jog_time render inline: @jog_time.to_json end def create jog_time = @user.jog_times.create(valid_params) if jog_time.errors.any? render(status: :unprocessable_entity,json: jog_time.errors.to_a) else render inline: jog_time.to_json end end def update return missing_jog_time unless @jog_time if @jog_time.update_attributes(valid_params) render inline: @jog_time.to_json else render(status: :unprocessable_entity,json: @jog_time.errors.to_a) end end def destroy return missing_jog_time unless @jog_time @jog_time.delete render inline: @jog_time.to_json end def weekly_summaries result,current_week,end_of_week = [],[],nil @user.jog_times.order('date asc').each do |jog_time| if jog_time.date < (end_of_week ||= jog_time.date.end_of_week) current_week << jog_time else result << build_weekly_summary(current_week) current_week = [jog_time] end_of_week = jog_time.date.end_of_week end end result << build_weekly_summary(current_week) unless current_week.empty? render inline: result.to_json end protected def authorize_user authorize!(:manage,:user) if params[:user_id] authorize!(:manage,:jog_time) end def set_user @user = params[:user_id] ? User.find_by_id(params[:user_id]) : current_user end def set_jog_time @jog_time = @user.jog_times.find_by_id(params[:id]) end def missing_jog_time render(status: :unprocessable_entity,json: ['No jog time given']) end def valid_params params.require(:jog_time).permit(:date,:duration,:distance) rescue {} end def scope_by_sort(scope,sort) case sort when nil then scope when 'speed' then scope.order('(distance/duration) desc') else scope.order("#{sort} desc") end end def scope_by_date_range(scope,from,to) return scope unless from and to scope.where('date between ? and ?',from,to) end def build_weekly_summary(jog_times) distances,durations,speeds = [],[],[] jog_times.each do |jog_time| distances << jog_time.distance durations << jog_time.duration speeds << jog_time.distance / jog_time.duration end { date: jog_times.first.date.beginning_of_week, count: jog_times.length, distance_min: distances.min, distance_max: distances.max, distance_mean: distances.sum / distances.length, duration_min: durations.min, duration_max: durations.max, duration_mean: durations.sum / durations.length, speed_min: speeds.min, speed_max: speeds.max, speed_mean: speeds.sum / speeds.length, } end end
true
e3093f58068ac91a2949a3a3bb7b4365014e0eb9
Ruby
clbustos/dirty-memoize
/spec/dirty_memoize_spec.rb
UTF-8
2,836
2.984375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') class ExpensiveClass attr_writer :x, :y include DirtyMemoize def initialize @a=nil @b=nil @x='x' @y='y' end def set_a(aa) @a=aa end def compute @a=@x @b=@y end def a "@a=#{@a}" end def b "@b=#{@b}" end dirty_writer :x, :y dirty_memoize :a, :b end class ExpensiveClass2 < ExpensiveClass DIRTY_COMPUTE=:compute2 def compute2 @a=@x+".2" end end describe DirtyMemoize, "extended object" do before do @ec=ExpensiveClass.new end subject { @ec } context "when instanciated" do it { should be_dirty} it "should initialize with number of computation to 0" do @ec.compute_count.should==0 end it "read inmediatly the correct value" do @ec.a.should=='@a=x' end end context "when reads 'dirty' attributes " do before do @ec.a end it 'call compute' do @ec.compute_count.should==1 end it{ should_not be_dirty} it "call compute once and only once" do 5.times {@ec.a} @ec.compute_count.should==1 end end context "calls dirty writers before dirty getter" do before do @ec.x="cache" end it { should be_dirty} it "doesn't compute anything" do @ec.compute_count.should==0 end it "doesn't change internal variables" do @ec.instance_variable_get("@a").should be_nil end end describe "when calls dirty getter after call dirty writer" do before do @ec.x="cache" @ec.a end it { @ec.should_not be_dirty} it "calls compute only once" do @ec.compute_count.should==1 end it "set value of internal variable" do @ec.instance_variable_get("@a").should=='cache' end it 'set getter method with a different value' do @ec.a.should=='@a=cache' end end describe "uses cache" do before do @ec.x='cache' @ec.a @ec.set_a('not_cache') end it "changing internal doesn't start compute" do @ec.compute_count.should==1 end it {should_not be_dirty} it "doesn't change cache value" do @ec.a.should=='@a=cache' end describe "when cleaning cache" do before do @ec.clean_cache end it {@ec.should be_dirty} it "doesn't call compute" do @ec.compute_count.should==1 end describe "when get dirty attribute" do it "returns correct value and call compute again" do @ec.a.should=='@a=cache' @ec.compute_count.should==2 end end end end describe "could call other computation method" do it "using DIRTY_COMPUTER" do @ec2=ExpensiveClass2.new @ec2.x='cache' @ec2.a.should=='@a=cache.2' @ec2.compute_count.should==1 end end end
true
acc2a86c4f50cfe07541cd458f4a654484d66b6c
Ruby
dzunk/spiralizer
/lib/spiralizer/result.rb
UTF-8
513
3.140625
3
[ "MIT" ]
permissive
module Spiralizer class Result def initialize(value) @raw_value = value end def valid! raise NumericElementError if raw_value.match? /[0-9]/ raise LowercaseElementError if raw_value.match? /[a-z]/ raise InvalidElementError unless raw_value.match? /^[A-Z\s]*$/ true end def valid? valid! rescue false end def value raw_value.downcase end def to_s value end private attr_reader :raw_value end end
true
14e7b5401dcaf877224e408a57654b7878d9059b
Ruby
Romu-Muroga/docking
/app/helpers/application_helper.rb
UTF-8
1,904
2.546875
3
[]
no_license
module ApplicationHelper # Highlight current link def cp(path) 'current' if current_page?(path) end def posts_index_page?(target_controller, target_action) 'current' if target_controller == 'posts' && (target_action == 'index' || target_action == 'search') end def my_page?(target_controller, target_action) 'current' if target_controller == 'users' && target_action == 'show' end def linked_post_picture(post) if post.picture.present? link_to post_path(post) do image_tag(post.picture.image.url, class: 'img-responsive') end else link_to post_path(post) do image_tag('/images/default2.jpg', class: 'img-responsive') end end end def linked_user_picture(user) if user.picture.present? link_to user_path(user) do image_tag(user.picture.image.url, class: 'img-responsive') end else link_to user_path(user) do image_tag('/images/default.png', class: 'img-responsive') end end end # instance: Post or User def no_link_picture(instance) if instance.picture.present? image_tag(instance.picture.image.url, class: 'img-responsive') elsif instance.class == User image_tag('/images/default.png', class: 'img-responsive') else image_tag('/images/default2.jpg', class: 'img-responsive') end end # Link hashtags def render_with_hashtags(remarks) # gsub:第1引数に正規表現のパターンを指定してブロックを渡すと、パターンにマッチする部分をすべて取り出して繰り返しブロックを実行します。 # マッチした部分はブロックの戻り値に置き換わり、新しい文字列が返ります。 remarks.gsub(/[##][\w\p{Han}ぁ-ヶヲ-゚ー]+/) { |word| link_to word, "/posts/hashtag/#{word.tr('#', '#').delete('#')}" }.html_safe end end
true
d24314b17365a7469336210fda7c2000531fc8e0
Ruby
scottmacphersonmusic/data_structures
/spec/features/linked_list/to_s_spec.rb
UTF-8
362
3.03125
3
[ "MIT" ]
permissive
require 'spec_helper' require 'linked_list' describe LinkedList do before do # Given a linked list with several nodes @list = LinkedList.new 7 temp = @list.head @list.head = Node.new(4, Node.new(5, Node.new(6, temp))) end it "to_s prints all values in comma-separated list" do proc { @list.to_s }.must_output "4, 5, 6, 7\n" end end
true
6b74c2b0f777542288ba31a4d07f4846c3466b5e
Ruby
pyrat/gravatar
/lib/attributes.rb
UTF-8
2,538
2.6875
3
[ "MIT" ]
permissive
# # Mixin for ActiveRecord::Base classes. Will add a gravatar(..) method # which returns the URL of the gravatar resource associated to the model's # instance. # # Author:: Juris Galang (mailto:jurisgalang@gmail.com) # Copyright:: Copyright (c) 2010 Juris Galang # License:: MIT License # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # module Gravatar module Attributes AVATAR_URL = "http://www.gravatar.com/avatar" SECURE_AVATAR_URL = "https://secure.gravatar.com/avatar" module Rating G = 'g' PG = 'pg' R = 'r' X = 'x' end module DefaultImage GRAVATAR = 'd' IDENTICON = 'identicon' MONSTERID = 'monsterid' WAVATAR = 'wavatar' end # Return the gravatar URL associated with the model's instance. # options:: Options used to build the URL to access the model's gravatar resource. # This will override the options specified in the +has_gravatar+ declaration. def gravatar(options={}) configuration = gravatar_options configuration.update(options) if options.is_a? Hash if configuration[:default] =~ /^(https?:\/\/|\/)/i configuration[:default] = CGI::escape(configuration[:default]) end url = configuration.delete(:ssl) == true ? SECURE_AVATAR_URL : AVATAR_URL email = "#{self.send(configuration[:attr])}".downcase id = Digest::MD5.hexdigest(email) params = configuration.collect{ |k, v| "#{k}=#{v}" }.join('&') "#{url}/#{id}?#{params}" end end end
true
a0a155dbfe5688d181a50676159f9eedbc9d9390
Ruby
asg0451/Teensy-Mixer
/client.rb
UTF-8
1,835
2.828125
3
[]
no_license
#!/usr/bin/env ruby ## # client.rb -- the client program for my Teensy-based mixer thing # author: Miles Frankel (miles.frankel at gmail.com) ## # require 'pry' require 'serialport' def inputs_readout # TODO: check for failure inputs = `pactl list sink-inputs` inp_list = (inputs.split(/Sink Input/)).map do |s| s.lstrip.rstrip if s != '' end .compact inp_nums = inp_list.map do |s| s.match(/^#([0-9]+)/).captures end .flatten prog_name = inp_list.map do |s| s.match(/application.process.binary = "([a-zA-Z0-9\-_]+)"/).captures end .flatten Hash[prog_name.zip(inp_nums)] end def update_stream_vol(num, vol) %x(pactl set-sink-input-volume #{num} #{vol}%) end def update_prog_vol(name, vol) streams = inputs_readout update_stream_vol(streams[name], vol) end def setstty(dev = '/dev/ttyACM0', baud = 115_200) # set the serial output of the teensy properly. %x(stty -F #{dev} cs8 #{baud} ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts) nil end def setup_serial(dev = '/dev/ttyACM0', baud = 115_200) setstty(dev, baud) # required i think data_bits = 8 stop_bits = 1 parity = SerialPort::NONE SerialPort.new(dev, baud, data_bits, stop_bits, parity) end def main sp = setup_serial # use default values while (line = sp.gets.chomp) trap('INT') do # trap ctrl-c and close connection gracefully sp.close puts 'Exiting...' exit end vols = line.split(' ').map(&:to_f) puts vols.to_s + "\n\n" # for debugging # temporary; TODO: hash to store which slider goes to which program inputs_readout.each_with_index do |(k, _a), i| # convert 10-bit num into percent volume = ((vols[i] / 1024) * 100).to_i update_prog_vol(k, volume) end end sp.close end main
true
2ddec07f2344181343a3d2b81cba3fd5369f96e0
Ruby
apoc64/analyzip
/app/presenters/zips_index_presenter.rb
UTF-8
730
2.609375
3
[]
no_license
class ZipsIndexPresenter < Presenter def initialize(current_user) set_user(current_user) set_default_map @card1 = find_high_incomes @card2 = find_low_incomes @card3 = find_high_pops end def page_title 'US Zip Codes - AnalyZip' end private def find_high_incomes cp = CardPresenter.new('Highest Incomes', 'card-1') set_currency_collection(cp, Zip.highest_incomes, ZipDecorator) end def find_low_incomes cp = CardPresenter.new('Lowest Incomes', 'card-2') set_currency_collection(cp, Zip.lowest_incomes, ZipDecorator) end def find_high_pops cp = CardPresenter.new('Highest Pops', 'card-3') set_delimiter_collection(cp, Zip.highest_pops, ZipDecorator) end end
true
d48e2ce36abd062a0a7bc6a3455e02994489e6e4
Ruby
Hawk1n5/TUCTF_2016_write_up
/pwn/woo/exp.rb
UTF-8
1,008
2.75
3
[]
no_license
#!/usr/bin/env ruby require '~/Tools/pwnlib' local = false#true if local host, port = '127.0.0.1', 4444 else host, port = '104.196.15.126', 15050 end def bring(index, type, name) @r.recv_until("Enter your choice:") @r.send("#{index}\n") @r.send("#{type}\n") @r.send("#{name}\n") @r.recv_until("Menu Options:") end def delete(index) @r.recv_until("Enter your choice:") @r.send("4\n") @r.recv_until("Which element do you want to delete?") @r.send("#{index}\n") end def secret() @r.recv_until("Enter your choice:") @r.send("4919\n") puts @r.recv(65535) puts @r.recv(65535) puts @r.recv(65535) puts @r.recv(65535) puts @r.recv(65535) end def p64(*addr) return addr.pack("Q*") end def p32(*addr) return addr.pack("L*") end PwnTube.open(host, port) do |r| @r=r flag = 0x4008dd bring(1, 1, "aaaa") bring(1, 1, "bbbb") bring(3, 1, "aaaabbbbcccc#{p32(3)+p64(0x0000000200000000,0x0000000000020fc1)}") delete(1) bring(1, 1, "a"*16+p64(0x100000000, 0x21, flag)) #delete(1) secret() end
true
73f314dd6251c74c2a00512896922599768f8233
Ruby
jwaldrip/navigable_hash
/spec/helpers/helper_methods.rb
UTF-8
1,294
2.5625
3
[ "MIT" ]
permissive
module NavigableHash::HelperMethods def test_key_with_dot_notation(key, hash) case (value = hash[key]) when Hash value.keys.each { |key| test_key_with_dot_notation key, hash } end describe "##{key}" do it "should call navigate" do navigable.stub(:navigate) navigable.send(key) end it "should have a valid value" do expect(navigable.send key).to eq hash[key] end end end def test_key_with_symbol_notation(key, hash) case (value = hash[key]) when Hash value.keys.each { |key| test_key_with_dot_notation key, hash } end describe "##{key}" do it "should call navigate" do navigable.stub(:navigate) navigable[key.to_sym] end it "should have a valid value" do expect(navigable[key.to_sym]).to eq hash[key] end end end def test_key_with_string_notation(key, hash) case (value = hash[key]) when Hash value.keys.each { |key| test_key_with_dot_notation key, hash } end describe "##{key}" do it "should call navigate" do navigable.stub(:navigate) navigable[key.to_s] end it "should have a valid value" do expect(navigable[key.to_s]).to eq hash[key] end end end end
true
caf8e7ce7801316be1e6655f96905808047b96c2
Ruby
l-plan/soccer_bet
/app/models/team.rb
UTF-8
981
2.640625
3
[]
no_license
class Team < ApplicationRecord has_many :winners, -> { winner }, class_name: "Bet::Team", inverse_of: :team has_many :redcards, -> { redcard }, class_name: "Bet::Team", inverse_of: :team has_many :finalists, -> { finale }, class_name: 'Bet::Team', inverse_of: :team has_many :semifinalists, -> { semifinal }, class_name: 'Bet::Team', inverse_of: :team has_many :quarterfinalists, -> { quarterfinal }, class_name: 'Bet::Team', inverse_of: :team has_many :eightfinalists, -> { eightfinal }, class_name: 'Bet::Team', inverse_of: :team def self.winner Team.find_by(winner: true) end def self.redcard Team.find_by(red: true) end def calculate_winner winners.each{|x| x.update_attribute(:score, 15)} end def reset_winner_scores winners.each{|x| x.update_attribute(:score, nil)} end def calculate_redcard redcards.each{|x| x.update_attribute(:score, 5)} end def reset_redcard_scores redcards.each{|x| x.update_attribute(:score, nil)} end end
true
e37d1e2491fb416ab938cf49a38de8db66a07e8b
Ruby
MassICTBV/nlexch-slanger
/benchmark.rb
UTF-8
4,266
2.546875
3
[]
no_license
#!/usr/bin/env ruby require 'pusher' require 'pusher-client' require 'json' require 'uri' require 'optparse' options = { api_uri: 'http://api.pusherapp.com:80', ws_uri: 'ws://ws.pusherapp.com:80', num: 1, messages: 10, payload_size: 20, send_rate: 10 } OptionParser.new do |opts| opts.on '-c', '--concurrency NUMBER', 'Number of clients' do |k| options[:num] = k.to_i end opts.on '-n', '--messages NUMBER', 'Number of messages' do |k| options[:messages] = k.to_i end opts.on '-i', '--app_id APP_ID', "Pusher application id" do |k| options[:app_id] = k end opts.on '-k', '--app_key APP_KEY', "Pusher application key" do |k| options[:app_key] = k end opts.on '-s', '--secret SECRET', "Pusher application secret" do |k| options[:app_secret] = k end opts.on '-a', '--api_uri URI', "API service uri (Default: http://api.pusherapp.com:80)" do |uri| options[:api_uri] = URI(uri) end opts.on '-w', '--websocket_uri URI', "WebSocket service uri (Default: ws://ws.pusherapp.com:80)" do |uri| options[:ws_uri] = URI(uri) end opts.on '--size NUMBER', 'Payload size in bytes. (Default: 20)' do |s| options[:payload_size] = s.to_i end opts.on '--send-rate NUMBER', 'Message publish rate. (Default: 10)' do |r| options[:send_rate] = r.to_i end opts.on '--subscribe', 'Only subscribe.' do |s| options[:subscribe] = true end opts.on '--publish', 'Only publish.' do |s| options[:publish] = true end end.parse! unless options[:app_id] && options[:app_key] && options[:app_secret] puts "You must provide all of app ID, key, secret, run #{$0} -h for more help." exit 1 end PusherClient.logger = Logger.new File.open('pusher_client.log', 'w') stats = Hash.new {|h, k| h[k] = []} def puts_summary(stats, num, total, size, send_rate, total_elapsed=nil) latencies = stats.values.flatten latency_avg = latencies.inject(&:+) / latencies.size latency_mid = latencies.sort[latencies.size/2] puts "\n*** Summary (clients: #{num}, messages total/rate: #{total}/#{send_rate}, payload size: #{size})***\n" puts "Message received: %d (%.2f%%)" % [latencies.size, latencies.size.to_f*100/(num*total)] puts "Total time: #{total_elapsed}s" if total_elapsed puts "avg latency: #{latency_avg}s" puts "min latency: #{latencies.min}s" puts "max latency: #{latencies.max}s" puts "mid latency: #{latency_mid}" end unless options[:publish] sockets = options[:num].times.map do |i| sleep 0.1 received_total = 0 socket = PusherClient::Socket.new( options[:app_key], ws_host: options[:ws_uri].host, ws_port: options[:ws_uri].port, wss_port: options[:ws_uri].port, encrypted: options[:ws_uri].scheme == 'wss' ) socket.connect(true) socket.subscribe('benchmark') socket['benchmark'].bind('bm_event') do |data| payload = JSON.parse data latency = Time.now.to_f - payload['time'].to_f stats[i] << latency received_total += 1 puts "[#{i+1}.#{received_total}] #{data[0,60]}" socket.disconnect if received_total == options[:messages] end socket end channels = sockets.map {|s| s['benchmark'] } sleep 0.5 until channels.all?(&:subscribed) end on_signal = ->(s) { puts_summary(stats, options[:num], options[:messages], options[:payload_size], options[:send_rate]); exit 0 } Signal.trap('INT', &on_signal) Signal.trap('TERM', &on_signal) Pusher.app_id = options[:app_id] Pusher.key = options[:app_key] Pusher.secret = options[:app_secret] Pusher.scheme = options[:api_uri].scheme Pusher.host = options[:api_uri].host Pusher.port = options[:api_uri].port ts = Time.now unless options[:subscribe] count = 0 sleep_time = 1.0/options[:send_rate] while count < options[:messages] count += 1 payload = { time: Time.now.to_f.to_s, id: count, data: '*'*options[:payload_size] } Pusher.trigger_async('benchmark', 'bm_event', payload) sleep sleep_time end end unless options[:publish] threads = sockets.map {|s| s.instance_variable_get('@connection_thread') } threads.each(&:join) end te = Time.now puts_summary(stats, options[:num], options[:messages], options[:payload_size], options[:send_rate], te-ts) unless options[:publish]
true
bf1d70f3ebbae62a6b4aad9abf2799abb0b541e8
Ruby
floriandejonckheere/advent-of-code
/2020/1/solution.rb
UTF-8
347
3.5
4
[]
no_license
#!/usr/bin/env ruby # frozen_string_literal: true numbers = File .read("./input.txt") .split("\n") .map(&:to_i) # Part one a, b = numbers.permutation(2).find { |a, b| a + b == 2020 } puts "#{a} * #{b} = #{a * b}" # Part two a, b, c = numbers.permutation(3).find { |a, b, c| a + b + c == 2020 } puts "#{a} * #{b} * #{c} = #{a * b * c}"
true
22371771060b447ed1bfa6b4df1cae282baf0c0e
Ruby
alexignat/ruby_fundamentals_part1
/exercise1.rb
UTF-8
299
4.1875
4
[]
no_license
# puts puts 2 puts 3 puts 2 != 3 # single quotes puts "Betty's pie shop" puts 'Betty\'s pie shop' # playing with strings puts "Hello\t\tworld" # \t tabs puts "Hello\b\b\b\b\bGoodbye world" #\b backspaces puts "Hello\rStart over world" #\ carriage return puts "1. Hello\n2. World" #\ new line
true
34633caa20021a9d8e2235b52b75584de80a86eb
Ruby
smeds1/Ruby_Practice
/Unit5/randomMonth.rb
UTF-8
179
3.125
3
[]
no_license
#Sam Smedinghoff #3/13/18 #randomMonth.rb months = ['January','February','March','April','May','June','July', 'August','September','October','November','December'] puts months[rand(12)]
true
54c0447cdecb1a41cb84683a60bc607f24f3f004
Ruby
satoknj/chapex
/lib/chapex/parser/lexer.rb
UTF-8
3,016
2.890625
3
[ "MIT" ]
permissive
module Chapex module Parser # Tokenize input string to consume it with racc class Lexer Lexicality = Struct.new(:expression, :token, :invoke) attr_reader :tokens SCOPE = /\b(public|protected|private|global)\b/ KEYWORDS = %i[ virtual abstract class implements extends final override static if else true false for do while ].freeze KEYWORD = /\b(#{KEYWORDS.join('|')})\b/ SHARING = /\b(with|without)\b\s\bsharing\b/ EXPRESSIONS = [ Lexicality.new(SCOPE, :SCOPE, :emit), Lexicality.new(KEYWORD, :KEYWORD, :emit_keyword), Lexicality.new(SHARING, :SHARING, :emit), Lexicality.new(/{/, :L_CB, :emit), Lexicality.new(/}/, :R_CB, :emit), Lexicality.new(/\(/, :L_RB, :emit), Lexicality.new(/\)/, :R_RB, :emit), Lexicality.new(/\./, :DOT, :emit), Lexicality.new(/,/, :COMMA, :emit), Lexicality.new(/==/, :DBL_EQUAL, :emit), Lexicality.new(/<=/, :GREATER_EQUAL, :emit), Lexicality.new(/</, :GREATER, :emit), Lexicality.new(/>=/, :LESS_EQUAL, :emit), Lexicality.new(/>/, :LESS, :emit), Lexicality.new(/=/, :EQUAL, :emit), Lexicality.new(/;/, :SEMI, :emit), Lexicality.new(/:/, :COLON, :emit), Lexicality.new(/\+\+/, :INCREAMENT, :emit), Lexicality.new(/--/, :DECREAMENT, :emit), Lexicality.new(/\+/, :PLUS, :emit), Lexicality.new(/-/, :MINUS, :emit), Lexicality.new(/\*/, :MULTIPLY, :emit), Lexicality.new(%r{\/}, :DIVIDE, :emit), Lexicality.new(/%/, :REMAINDER, :emit), Lexicality.new(/'.*?'/, :S_LITERAL, :emit), Lexicality.new(/[0-9]+/, :N_LITERAL, :emit), Lexicality.new(/\b\w+\b/, :IDENT, :emit), Lexicality.new(/\[.+?\]/m, :SOQL, :emit), Lexicality.new(/\s+?/) ].freeze def initialize(str) @tokens = [] @scanner = StringScanner.new(str) end def tokenize until @scanner.eos? EXPRESSIONS.each do |lex| @scanner.scan(lex.expression) next if skip?(lex) add_token(lex) break end end end private def skip?(lex) return true unless @scanner.matched return true if lex.token.nil? false end def add_token(lex) send(lex.invoke, lex.token) end def emit(type) token = [type, token_value] @tokens.push(token) end def emit_keyword(_) token = [matched_to_type, token_value] @tokens.push(token) end def token_value TokenValue.new( @scanner.matched, @scanner.pointer - @scanner.matched_size, @scanner.pointer - 1 ) end def matched_to_type @scanner.matched.upcase.to_sym end end end end
true
c9a14ca36cfeb3c1e557e45b15fde8ec1b1c1258
Ruby
mfilej/pv181
/homework/05-standards/pad.rb
UTF-8
215
2.546875
3
[]
no_license
#!/usr/bin/env ruby $LOAD_PATH.unshift File.join(File.dirname(__FILE__), 'lib') require "padding" puts "ANSI:" Padding::ANSI.pad(open(ARGV[0]).read) puts "\n\n" puts "PKCS:" Padding::PKCS.pad(open(ARGV[0]).read)
true
9b66b4ed2e9f16e2651c90119642637d4ba65f29
Ruby
katiebugsings/cli-data-gem-assessment-v-000
/henry_ford/lib/henry_ford/village.rb
UTF-8
210
2.65625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Village attr_accessor :restaurants def initialize(restaurants) self.restaurants = [] @restaurants = restaurants end def self.all @@all end def save @@all << self end end
true
94de64aab9ea8356c8f331190b0416fd916a8dcb
Ruby
ypadron/skillcrush-104
/always_three_argument.rb
UTF-8
221
3.390625
3
[]
no_license
puts "Give me a number, please." input_number = gets.to_i def always_three_argument(input_number) puts 'still ALWAYS ' + (((input_number + 5) * 2 - 4) / 2 - input_number).to_s end always_three_argument(input_number)
true
017c6c96732cedc1614cb4f726c9aa55da16106d
Ruby
MosheBerman/oop-1
/1.3/Car.rb
UTF-8
681
3.78125
4
[ "MIT" ]
permissive
=begin Moshe Berman Professor Zhou CISC 3150 Spring 2014 Assignment 1.3 =end class Car attr :gasLevel attr :fuelEfficiency def initialize(fuelEfficiency) @fuelEfficiency = fuelEfficiency @gasLevel = 0 end # Returns the amount of gas def addGas(gasToAdd) self.gasLevel += gasToAdd end # Adds gas def getGas() return self.gasLevel end # Simulates driving car for a given distance # and reduces the amount of gase based on the # fuelEfficiency. def drive(distanceInMiles) gasToRemove = self.fuelEfficiency * distanceInMiles self.fuelLevel -= gasToRemove # Ensure we don't go below zero gas self.fuelLevel = [self.fuelLevel, 0].max end end
true
9dc008ad7c0ec036ea447371eab654b916208262
Ruby
nickrim/qa_repo
/ITA/hw_13/lib/script_13_07.rb
UTF-8
571
2.96875
3
[]
no_license
# ======================================================================== puts "" puts "Script \s\s\s\s: " + __FILE__.chop.chop.chop # ======================================================================== # Description = "This is a description of the script" # Name = "Nick Krimnus" # Email = "your@email.com" # ======================================================================== puts "" str="" ARGV.each do |i| str+=i str+=" " end reg=/[A-Z][a-z]+\s[A-Z][a-z]+/ name=str.match reg puts "His name is: \"#{name}\""
true
db6e3afaec1b3ac7790626078a0b7e3b57d3c822
Ruby
mattbryce93/CodeClan-Course
/week_01/day_2/what_animal.rb
UTF-8
197
3.75
4
[]
no_license
p "What animal are you?" name = gets.chomp.downcase if (name == "chicken") p "This is my favourite animal!" elsif (name == "kitten") p "I love kittens!" else p "Not my favourite animal." end
true
c3200577de0bada5afbec268436dcacade3888bd
Ruby
stephenprill/hangry-angular
/server/app/services/restaurant_service.rb
UTF-8
402
2.828125
3
[]
no_license
class RestaurantService def initialize(restaurant_client) @restaurant_client = restaurant_client end def find(attrs) restaurant_client.find_by_location( latitude: attrs[:latitude], longitude: attrs[:longitude] ).map do |restaurant_data| Restaurant.new(restaurant_data) end end private attr_reader :restaurant_client end
true
5fdbe188ac1b33489a9195d48982f1acf8a1ab6a
Ruby
Tanzi11/nyc-pigeon-organizer-dc-web-082718
/nyc_pigeon_organizer.rb
UTF-8
384
3
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def nyc_pigeon_organizer(data) pigeon_list = {} data.each do |attribute_category, attribute_values| attribute_values.each do |attribute_value, names| names.each do |name| pigeon_list[name] ||= {} pigeon_list[name][attribute_category] ||= [] pigeon_list[name][attribute_category] << attribute_value.to_s end end end pigeon_list end
true
a645ab629fe23a0fb4eee4599ee83107bc1b3e94
Ruby
rgrier104/reverse-each-word-v-000
/reverse_each_word.rb
UTF-8
228
3.4375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def reverse_each_word(string) array = string.split(' ') reverse_array = [] array.each do |word| reverse_array << word.reverse end array.collect do |word| word.reverse end return reverse_array.join(" ") end
true
edf67bd82ffbfbae9b57e2639c7e68da58c06574
Ruby
elastic/docs
/resources/asciidoctor/lib/alternative_language_lookup/listing.rb
UTF-8
4,126
2.515625
3
[]
no_license
# frozen_string_literal: true require_relative 'alternative' require_relative '../log_util' module AlternativeLanguageLookup ## # Information about a listing in the original document. class Listing RESULT_SUFFIX = '-result' RESULT_SUFFIX_LENGTH = RESULT_SUFFIX.length include LogUtil attr_reader :block attr_reader :lang attr_reader :is_result attr_reader :alternatives def initialize(block) @block = block @lang = block.attr 'language' return unless @lang @is_result = @lang.end_with? RESULT_SUFFIX lookups = block.document.attr 'alternative_language_lookups' @alternatives = lookups[key_lang] @listing_index = nil # We'll look it up when we need it @colist_offset = 1 end def process return unless alternatives block.attributes['digest'] = digest found_langs = [] alternatives.each do |lookup| add_alternative_if_present found_langs, lookup end report found_langs cleanup_original_after_add found_langs unless found_langs.empty? end def add_alternative_if_present(found_langs, lookup) return unless (found = lookup.index[digest]) # TODO: we can probably cache this. There are lots of dupes. alt_lang = lookup.alternative_lang_for @is_result alternative = Alternative.new document, alt_lang, found[:path] alternative_listing = alternative.listing @block.parent return unless alternative_listing alternative_colist = alternative.colist @block.parent insert alternative_listing, alternative_colist found_langs << lookup.alternative_lang end def insert(alternative_listing, alternative_colist) find_listing unless @listing_index parent.blocks.insert @listing_index, alternative_listing @listing_index += 1 return unless alternative_colist parent.blocks.insert @listing_index + @colist_offset, alternative_colist @colist_offset += 1 end def find_listing # Find the right spot in the parent's blocks to add any alternatives: # right after this block's callouts if it has any, otherwise just after # this block. @listing_index = parent.blocks.find_index(@block) if @listing_index # While we're here check if there is a callout list. colist = parent.blocks[@listing_index + 1] @colist = colist&.context == :colist ? colist : nil else message = "Invalid document: parent doesn't include child!" error location: source_location, message: message # In grand Asciidoctor tradition we'll *try* to make some # output though @listing_index = 0 @colist = nil end end def cleanup_original_after_add(found_langs) # We're obligated to reindex the sections inside parent because we've # chaged its blocks. parent.reindex_sections # Add some roles which will translate into classes to the original # listing block and the callout. We'll use these to hide the default # language when you pick an override language. has_roles = found_langs.map { |lang| "has-#{lang}" }.join ' ' @block.attributes['role'] = "default #{has_roles}" return unless @colist @colist.attributes['role'] = "default #{has_roles} lang-#{@lang}" end def report(found_langs) report = document.attr 'alternative_language_report' report&.report self, found_langs summary = document.attr 'alternative_language_summary' summary&.on_listing self, found_langs end def parent @block.parent end def document @block.document end def source_location @block.source_location end def source @source ||= @block.source end def digest @digest ||= Digest::MurmurHash3_x64_128.hexdigest source end ## # `key_lang` normalises `lang` into the lookup key for alternatives. def key_lang if @is_result @lang[0, @lang.length - RESULT_SUFFIX_LENGTH] else @lang end end end end
true
18e16529bafc56eb68c44048469aa7baa9e95952
Ruby
queso/status
/app/models/status.rb
UTF-8
360
2.8125
3
[]
no_license
class Status < ActiveRecord::Base attr_protected :up validates :up, :inclusion => {:in => [true, false], :message => "status can't be blank"} def status up ? "up" : "down" end def status=(status) matcher = status.to_s.downcase if matcher == "up" self.up = true elsif matcher == "down" self.up = false end end end
true
2d5e39a1c15effa443ee9395daf8e1c5f6349b31
Ruby
anicholson/json_schema_tools
/lib/schema_tools/modules/read.rb
UTF-8
2,784
2.6875
3
[ "MIT" ]
permissive
# encoding: utf-8 require 'active_support' require 'active_support/core_ext/hash/indifferent_access' require 'active_support/core_ext/string/inflections' module SchemaTools module Modules # Read schemas into a hash module Read # Variable remembering already read-in schema's # { # :invoice =>{schema} # :credit_note =>{schema} # } # } # @return [Hash{String=>Hash{Symbol=>HashWithIndifferentAccess}}] def registry @registry ||= {} end def registry_reset @registry = nil end # Read a schema and return it as hash. You can supply a path or the # global path defined in #SchemaTools.schema_path is used. # Schemata returned from cache in #registry to prevent filesystem # round-trips. The cache can be resented with #registry_reset # # @param [String|Symbol] schema name to be read from schema path directory # @param [String|Hash] either the path to retrieve schema_name from, # or a Schema in Ruby hash form # @return[HashWithIndifferentAccess] schema as hash def read(schema_name, path_or_schema=nil) schema_name = schema_name.to_sym return registry[schema_name] if registry[schema_name] if path_or_schema.is_a? ::Hash path = nil plain_data = path_or_schema.to_json elsif path_or_schema.is_a?(::String) || path_or_schema.nil? path = path_or_schema file_path = File.join(path || SchemaTools.schema_path, "#{schema_name}.json") else raise ArgumentError, "Second parameter must be a path or a schema!" end plain_data ||= File.open(file_path, 'r'){|f| f.read} schema = ActiveSupport::JSON.decode(plain_data).with_indifferent_access if schema[:extends] extends = schema[:extends].is_a?(Array) ? schema[:extends] : [ schema[:extends] ] extends.each do |ext_name| ext = read(ext_name, path) # current schema props win schema[:properties] = ext[:properties].merge(schema[:properties]) end end registry[ schema_name ] = schema end # Read all available schemas from a given path(folder) and return # them as array # # @param [String] path to schema files # @return [Array<HashWithIndifferentAccess>] array of schemas as hash def read_all(path=nil) schemas = [] file_path = File.join(path || SchemaTools.schema_path, '*.json') Dir.glob( file_path ).each do |file| schema_name = File.basename(file, '.json').to_sym schemas << read(schema_name, path) end schemas end end end end
true
2e4562d894b93b7fa89a2c41b18cf40d3c135871
Ruby
nickdiaz57/oh_seven
/lib/component.rb
UTF-8
449
3
3
[ "MIT" ]
permissive
class Component attr_accessor :name, :engineers extend Concerns @@all = [] def initialize(name) @name = name @engineers = [] end def self.all @@all end def save @@all << self end def add_engineer(engi) engi.components << self unless engi.components.include?(self) @engineers << engi unless @engineers.find {|e| e == engi} end end
true
c77d0e92a090c18199595d10119c57197fa6d451
Ruby
alemohamad/book-of-ruby
/08 - Passing Arguments and Returning Values/default_args.rb
UTF-8
395
3.78125
4
[]
no_license
# The Book of Ruby - http://www.sapphiresteel.com def aMethod( a=10, b=20, c=100, *d ) return a, b, c, d end def anotherMethod( greeting="Hello", name="friend" ) return "#{greeting}, #{name}" end p( aMethod ) p( aMethod( 1,2 ) ) p( aMethod( 1,2,3 ) ) p( aMethod( 1,2,3,4,6 ) ) p( anotherMethod ) p( anotherMethod( "Goodye" ) ) p( anotherMethod( "Toodlepip!","Bertie" ) )
true
5af1d3bf441e0e912a4c553a05cb4b9a3702acbd
Ruby
dsauerbrun/climbcation
/app/models/post.rb
UTF-8
888
2.609375
3
[]
no_license
def is_numeric(o) true if Integer(o) rescue false end class Post < ActiveRecord::Base has_paper_trail belongs_to :forum_thread belongs_to :user DestinationCategoryName = 'Destinations' def self.createNewPost(content, user_id, forum_thread_id) if !is_numeric(forum_thread_id) # must looks like this is a comment for a location so we need to get or create the thread categoryDestination = Category.find_by_name(DestinationCategoryName) forum_thread_id = ForumThread.createThread(forum_thread_id, 1, categoryDestination.id).id end newPost = self.create(content: content, user_id: user_id, forum_thread_id: forum_thread_id) newPost end def edit(newContent, user_id) if (self.user_id == user_id) self.content = newContent self.save! else raise 'You do not have permissions to edit this comment.' end end end
true
2613d7b8afe17c07e1ce486c841507e69fdba001
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/hamming/6ebe118219c34ccf999effdd8b0b2d72.rb
UTF-8
259
3.28125
3
[]
no_license
class Hamming def self.compute(source, mutation) shortest_length = [source, mutation].map(&:length).min distance = 0 shortest_length.times do |i| if source[i] != mutation[i] distance += 1 end end distance end end
true
24b07b6d2bae9547f0585d39ddc17b4964c9539c
Ruby
mazamachi/sentence2graph
/sentence2graph.rb
UTF-8
2,228
3.265625
3
[]
no_license
require 'cabocha' require 'gviz' class Sentence2Graph attr_accessor :parser, :gv def initialize @parser = CaboCha::Parser.new @gv = Gviz.new end # 空白を含まないものを文節に分解して配列にする def parse_string_to_array(str) if str.match("\s") raise "str must be one line" end tree = self.parser.parse(str) return tree.toString(CaboCha::FORMAT_TREE).force_encoding("utf-8").gsub(" ","").gsub("EOS","").gsub(/-*D *\|?/,"").split end # 文章を与えられたら文節に分解して返す def parse_sentence_to_array(str) return str.gsub(" ","").split.map{|s| self.parse_string_to_array(s)}.flatten end def generate_link_array(str) # {あ=>["い", "う"], か=>["き", "く"]}みたいなやつ words = parse_sentence_to_array(str) words.unshift("START") words.push("END") from_to_array = {} len = words.length words.each_with_index do |word, index| if from_to_array[word] == nil from_to_array[word] = [] end if index==len-1 break end from_to_array[word] << words[index+1] end from_to_array end def generate_graph_from_sentence(str, filename=:graph, filetype=:png, layout="dot") words = parse_sentence_to_array(str) links = generate_link_array(str) len = words.length edge_style = ["bold", "solid", "dashed", "dotted"] self.gv.graph do global layout: layout, overlap:false, splines:true links.each do |from, ar| node make_sym(from), label: from, fontsize: 20*(ar.length/2+1) ar.uniq.each_with_index do |to, index| route make_sym(from) => make_sym(to) edge (make_sym(from).to_s+"_"+make_sym(to).to_s).to_sym, style: edge_style[index%4] node make_sym(to), label: to end end # words.each_with_index do |word, index| # if index==len-1 # break # end # route make_sym(word) => make_sym(words[index+1]) # node make_sym(word), label: word # end # node make_sym(words.last), label: words.last end self.gv.save(filename, filetype) end end def make_sym(str) str.to_s.split("").map(&:ord).join.to_sym end
true
894acf6467f3ed8563b0d9e364abe6fb559c1ba5
Ruby
itggot-emil-babayev/standard-biblioteket
/lib/quicksort.rb
UTF-8
421
4.09375
4
[]
no_license
# Public: Sorts an Array with the Quicksort algorithm # # arr - The Array that will be sorted # # Examples # # quicksort([7,3,1,3]) # # => [1,3,3,7] # # Returns the sorted Array def quicksort(arr) return arr if arr.length <= 1 pivot = arr.pop smaller = arr.map{|x| x if x <= pivot}.compact bigger = arr.map{|x| x if x > pivot}.compact return quicksort(smaller) + [pivot] + quicksort(bigger) end
true
d219d4f4a489b6b127ba06f9ec9b7ef798534d95
Ruby
odangitsdjang/cat_rental
/app/models/cat.rb
UTF-8
1,004
2.75
3
[]
no_license
# == Schema Information # # Table name: cats # # id :integer not null, primary key # birth_date :date not null # color :string not null # name :string not null # sex :string(1) not null # description :text not null # created_at :datetime not null # updated_at :datetime not null # class Cat < ApplicationRecord COLORS = %w(blue red green orange yellow indigo violet purple turquoise white black ) validates :birth_date, :color, :name, :sex, :description, presence: true validates :color, inclusion: { in: COLORS, message: "%{value} is not a valid color" } validates :sex, inclusion: { in: %w(m f M F), message: "%{value} is not a valid sex" } has_many :rentals, primary_key: :id, foreign_key: :cat_id, class_name: :CatRentalRequest, dependent: :destroy def age ((Date.today - birth_date)/365).to_i end def colors COLORS end end
true
f4176f9154413622a60385ca8d97a387cdf4cbca
Ruby
kmac02/phase-0-tracks
/ruby/hashes.rb
UTF-8
2,764
3.96875
4
[]
no_license
#Declare keys (with empty values) in questionnaire questionnaire = { name: "", age: "", #integer family_size: "", #integer children_under_10: "", #boolean decor_theme: "", number_of_rooms: "", #integer need_new_walls: "", #boolean has_pets: "", #boolean number_of_pets: "" #integer } #Ask user to begin filling out questionnaire puts "Please begin entering client information." # Create prompt for each key, apply the new value to the key puts "Client's name:" name = gets.chomp questionnaire[:name] = name puts "Client's age:" age = gets.chomp questionnaire[:age] = age.to_i puts "How many people in the family?" family_size = gets.chomp questionnaire[:family_size] = family_size.to_i puts "Does the client have children under the age of 10?" kids_under_ten = gets.chomp questionnaire[:children_under_10] = kids_under_ten == "yes" || kids_under_ten == "y" # factoring here makes this boolean (i.e. *when* kids under ten is equal to yes, questionnaire[:children_under_10] is true.) puts "What decor theme?" decor = gets.chomp questionnaire[:decor_theme] = decor puts "How many rooms?" room_number = gets.chomp questionnaire[:number_of_rooms] = room_number.to_i puts "Does the client need new walls?" needs_walls = gets.chomp questionnaire[:need_new_walls] = needs_walls == "yes" || needs_walls == "y" puts "Does the client have pets?" pets = gets.chomp if questionnaire[:has_pets] = pets == "yes" || pets == "y" puts "How many?" pet_number = gets.chomp questionnaire[:number_of_pets] = pet_number.to_i else questionnaire[:has_pets] = false questionnaire[:number_of_pets] = nil end # print out the client info questionnaire.each { |key, value| puts "Client info: #{key}: #{value}"} p questionnaire puts "Enter the key to make any updates or enter none if complete." update_answer = gets.chomp # Separate booleans, integers, and strings if update_answer == "none" #does nothing #### edit integer elsif update_answer == "age" || update_answer == "family_size" || update_answer == "number_of_rooms" || update_answer == "number_of_pets" key_to_update = update_answer.to_sym puts "Enter new value:" questionnaire[key_to_update] = gets.chomp.to_i ##### edit boolean elsif update_answer == "children_under_10" || update_answer == "need_new_walls" || update_answer == "has_pets" key_to_update = update_answer.to_sym puts "Enter new value:" new_value = gets.chomp questionnaire[key_to_update] = new_value questionnaire[key_to_update] = new_value == "yes" || pets == "y" ##### edit string else # to_sym to make string a symbol key_to_update = update_answer.to_sym puts "Enter new value:" questionnaire[key_to_update] = gets.chomp end p questionnaire
true
dcf9c3aab5fb81f79df8093fb9e2e87c15c5660e
Ruby
whatsrupp/gilded-rose
/spec/quality_updater_spec.rb
UTF-8
4,488
2.703125
3
[]
no_license
describe Quality do let (:quality) {described_class.new} describe '#set_item' do it 'updates the old item with a new item' do item = Item.new("Sulfuras, Hand of Ragnaros", 0, 80) expect(quality.item).not_to eq(item) quality.set_item (item) expect(quality.item).to eq(item) end end describe 'Item Type:' do describe 'Legendary' do describe 'Sulfuras' do it 'does not drop in quality' do item = Item.new("Sulfuras, Hand of Ragnaros", 0, 80) quality.update(item) expect(item.quality).to eq 80 end end end describe 'Depreciator' do context 'within sell by date' do it 'decreases by 1' do item = Item.new('Chboys Chips', 20, 20) quality.update(item) expect(item.quality).to eq 19 end it 'but not past 50' do item = Item.new( 'Chboys Chips', 20, 0) quality.update(item) expect(item.quality).to eq 0 end end context 'after sell by date' do it 'decreases by 2' do item = Item.new( 'Chboys Chips', 0, 20) quality.update(item) expect(item.quality).to eq 18 end it 'but not past 50' do item = Item.new( 'Chboys Chips', 0, 0) quality.update(item) expect(item.quality).to eq 0 end end end describe 'Appreciator' do describe 'Backstage Passes' do context 'before concert' do context '11 days or more to go' do it 'quality increases by 1' do item = Item.new( "Backstage passes to a TAFKAL80ETC concert", 11, 20) quality.update(item) expect(item.quality).to eq 21 end it 'but not past 50' do item = Item.new( "Backstage passes to a TAFKAL80ETC concert", 11, 50) quality.update(item) expect(item.quality).to eq 50 end end context '6-10 days days to go' do it 'quality increases by 2' do item = Item.new( "Backstage passes to a TAFKAL80ETC concert", 6, 20) quality.update(item) expect(item.quality).to eq 22 end it 'but not past 50' do item = Item.new( "Backstage passes to a TAFKAL80ETC concert", 6, 49) quality.update(item) expect(item.quality).to eq 50 end end context '5 days left' do it 'quality increases by 3' do item = Item.new( "Backstage passes to a TAFKAL80ETC concert", 5, 20) quality.update(item) expect(item.quality).to eq 23 end it 'but not past 50' do item = Item.new( "Backstage passes to a TAFKAL80ETC concert", 5, 48) quality.update(item) expect(item.quality).to eq 50 end end end context 'after concert' do it 'drop to 0 quality' do item = Item.new( "Backstage passes to a TAFKAL80ETC concert", 0, 20) quality.update(item) expect(item.quality).to eq 0 end end end describe 'Finely Aged Brie' do it 'increases in quality' do item = Item.new( "Aged Brie", 5, 20) quality.update(item) expect(item.quality).to eq 21 end it 'but not past 50' do item = Item.new( "Aged Brie", 5, 50) quality.update(item) expect(item.quality).to eq 50 end end end describe 'Conjured' do xit 'drops by 2 quality' do item = Item.new( 'Conjured Chboys Chips', 20, 20) quality.update(item) expect(item.quality).to eq 18 end end end end
true
379ff41c2e0cb0a46c8128a6098d218fdb65b997
Ruby
SudhakerVeerendraManikonda/Mocking_WebService
/test/net_asset_value_test.rb
UTF-8
3,130
2.75
3
[]
no_license
$:.unshift(File.join(File.dirname(__FILE__), '..', 'src')) $:.unshift '..' require 'simplecov' SimpleCov.start require 'net_asset_value' require 'test/unit' require 'stringio' class NetAssetValueTest < Test::Unit::TestCase def setup @asset = NetAssetValue.new end def test_canary assert true end def test_calculate_net_asset_value_for_a_symbol assert_equal(100, @asset.calculate_net_asset_value(20, 5)) end def test_calculate_net_asset_value_for_zero_shares assert_equal(0, @asset.calculate_net_asset_value(0, 40)) end def test_calculate_net_asset_value_with_price_zero assert_equal(0, @asset.calculate_net_asset_value(20, 0)) end def test_calculate_total_worth assert_equal(15, @asset.calculate_total_worth([1, 2, 3, 4, 5])) end def test_calculate_total_worth_with_empty_worth_list assert_equal(0, @asset.calculate_total_worth([])) end def test_retrieve_price_for_symbol_GOOG @asset.send(:define_singleton_method, :request_web_service) { |symbol| 99.99 } assert_equal(99.99, @asset.retrieve_price_for_a_symbol('GOOG')) end def test_retrieve_price_for_symbol_YHOO @asset.send(:define_singleton_method, :request_web_service) { |symbol| 34.50 } assert_equal(34.50, @asset.retrieve_price_for_a_symbol('YHOO')) end def test_retrieve_price_for_invalid_symbol @asset.send(:define_singleton_method, :request_web_service) { |symbol| 0 } assert_equal(0, @asset.retrieve_price_for_a_symbol('abc')) end def test_retrieve_price_when_web_service_throws_RuntimeError @asset.send(:define_singleton_method, :request_web_service) { |symbol| raise RuntimeError } assert_equal(0, @asset.retrieve_price_for_a_symbol('YHOO')) end def test_retrieve_price_when_web_service_throws_TimeOutError @asset.send(:define_singleton_method, :request_web_service) { |symbol| raise TimeoutError } assert_equal(0, @asset.retrieve_price_for_a_symbol('YHOO')) end def test_retrieve_price_when_web_service_throws_OtherErrors @asset.send(:define_singleton_method, :request_web_service) { |symbol| Error } assert_equal(0, @asset.retrieve_price_for_a_symbol('YHOO')) end def test_generate_report_for_worth symbols_price_shares = {:GOOG => ["35.5","100"], :YHOO => ["99.99", "50"]} expected_output = {"YHOO 50 99.99" => 4999.5, "GOOG 100 35.5" => 3550.0}, 8549.5 assert_equal(expected_output, @asset.generate_report_for_worth(symbols_price_shares)) end def test_get_a_response_from_webservice_for_YHOO symbol = 'YHOO' response = @asset.request_web_service(symbol) assert(response > 0) end def test_get_a_response_from_webservice_for_invalid_symbol symbol = '*&^%' assert_equal('Sorry, the page you requested was not found.', @asset.request_web_service(symbol)) end end
true
3438b2c5be2d89899bf8727fa1c126501cfd2ace
Ruby
drjolo/RubyLearning
/week_4/exercise4-Swap_File_Contents.rb
UTF-8
343
2.78125
3
[]
no_license
def file_swap( pathA, pathB ) pathC = File.dirname(pathA) + '/.temp' move( pathA, pathC ) move( pathB, pathA ) move( pathC, pathB ) end def move( old_path, new_path ) File.link( old_path, new_path ) File.delete( old_path ) end if __FILE__ == $0 pathA, pathB = 'docs/first.txt', 'docs/second.txt' file_swap( pathA, pathB ) end
true
0f9df5fed1ed66b4d68ddc34d9f78993b39e260a
Ruby
albertbahia/wdi_june_2014
/w02/d02/liza_ramo/Pets/Dog.rb
UTF-8
319
3.140625
3
[]
no_license
class Dog < Pet attr_reader(:ear_type) def initialize(name, age, owner, ear_type) # @name = name # @age = age # @owner = owner super(name, age, owner) @foods_eaten = [] @ear_type = ear_type end def eat(food) return "Woof" end def sleep() @hours_slept += 1 end end
true
997fa8fc919ac4d44e5992db46b0532083cfd07e
Ruby
bosh/CompilerConstruction
/lib/Buffer.rb
UTF-8
2,691
3.5
4
[]
no_license
class Buffer attr_accessor :contents, :current, :current_head, :style def initialize(str, dirty = false, style = :default) @contents = str.strip @current = @current_head = 0 @style = style clean! unless dirty #Heh heh heh end def clean!; @contents.gsub!(/\{.*?(\}|\z)/m, "") end #Strip {} comments def finished?; @current_head >= @contents.length end def advance; @current += 1 end def back_up; @current -= 1 end def update_head; @current_head = @current end def lookahead #Returns the character one ahead of the lookahead if @current+1 < @contents.size Token.new(@contents[@current+1,1]) #token so that it can call the _? methods else nil end end def get_next_token if finished? : return nil end #Returns a nil if past end and still being called token = Token.new("") @current = @current_head #make certain that current == head to start with token << @contents[@current, 1] if token.quote? advance until (lookahead == nil || lookahead.quote?) advance text = @contents[@current_head..@current] token = Token.new(text, "LITERAL", text) advance #should be right update_head elsif token.digit? advance while lookahead && lookahead.digit? if lookahead && lookahead.identifier_tail? #if it's a nonterminal that is also a nondigit text = @contents[@current_head..@current] update_head puts "INT Token: #{text} is followed by nondigits (#{lookahead.text}). Terminating run." exit(0) end text = @contents[@current_head..@current] token = Token.new(text, "INT", text) advance #should be right update_head elsif token.identifier_head? advance while lookahead && lookahead.identifier_tail? text = @contents[@current_head..@current] token = Token.new(text, "ID", text) advance #this bit might be factorable too.. what about token.assemble or something update_head elsif token.symbol? if lookahead && Token.new(token << lookahead.text).symbol? : advance end text = @contents[@current_head..@current] token = Token.new(text, "SYMBOL", text) advance update_head elsif token.whitespace? advance while lookahead && lookahead.whitespace? advance update_head token = get_next_token #recursion, not great, but should be impossible to get more than one level deep else puts "Token: #{token.text} was not recognized as valid. Terminating run." exit(0) end token end end
true
f78312b695a52101eba06de15f04e5d70cb9f9e2
Ruby
m-rwash/ruby-hackerrank
/array_selection.rb
UTF-8
467
4.03125
4
[]
no_license
# https://www.hackerrank.com/challenges/ruby-array-selection/problem def select_arr(arr) # select and return all odd numbers from the Array variable `arr` arr.select{|n| n.odd?} end def reject_arr(arr) # reject all elements which are divisible by 3 arr.reject{|n| n%3==0} end def delete_arr(arr) # delete all negative elements arr.delete_if{|n| n<0} end def keep_arr(arr) # keep all non negative elements ( >= 0) arr.keep_if{|n| n>=0} end
true
a15ea055c8d3cacae88cd15e51cf7418187104b9
Ruby
Jenietoc/Ruby_kommit_course
/Arrays II/The_each_with_index_Method.rb
UTF-8
444
4
4
[]
no_license
colors = %w[Red Blue Green Yellow] colors.each_with_index do |color, index| puts "Moving on index number #{index}" puts "The current color is #{color}" end =begin Write a loop that iterates over a numeric array Output the PRODUCT of each number a and its index position =end fives = [5, 10, 15, 20, 25] fives.each_with_index do |number, i| puts "The current value is #{number} at index #{i}" puts number * i end
true
feae47ad3914345e9eed6e3464c881c670c9b651
Ruby
Cowskin/Design-patterns
/patterns_explain/模板方法模式/report.rb
UTF-8
2,026
3.203125
3
[]
no_license
# -*- coding: utf-8 -*- class Report def initialize @title= 'Monthly Report' @text = ['Things are going','really ,really well.'] end # 这个是模板方法的组合,只放在模板类里面,子类不重载,其他方法可能被重载 # 这个抽象的基类通过模板方法来控制高端的处理流程 def output_report output_start output_head output_body_start output_body output_body_end output_end end # 实用钩子方法之前 # def output_start # raise 'Called abstract method: output_start' # end # def output_head # raise 'Called abstract method: output_head' # end # def output_body_start # raise 'Called abstract method: output_body_start' # end # def output_body # @text.each do |line| # output_line line # end # end # def output_line # raise 'Called abstract method: output_line' # end # def output_body_end # raise 'Called abstract method: output_body_end' # end # def output_end # raise 'Called abstract method: output_end' # end # 实用钩子方法后 # 在模板方法模式中,可以被具体类重载的非抽象方法被成为钩子方法 # 钩子方法允许具体类 # 1. 重载基础实现用来处理不通的任务 # 2. 简单的接受默认实现 # 基类通常定义钩子方法完全是为了让具体子类了解正在发生什么事情 # 如: 当report类调用 output_start时,它就是告诉子类:我们已经准备好了,如果你还有什么需要处理的,就现在做! # 这些钩子方法通常是空的,他们的存在仅仅是为了让子类了解正在发生什么事情 def output_start end def output_head output_line @title #默认实现 end def output_body_start end def output_body @text.each do |line| output_line line end end def output_line raise 'Called abstract method: output_line' end def output_body_end end def output_end end
true
82afb5ee987eb2cfd712b54780053db9b1496fbc
Ruby
Reksford/ruby-book-exercises
/hashes/exercise8.rb
UTF-8
416
3.75
4
[]
no_license
=begin NoMethodError: undefined method `keys' for Array This error is the result of calling the #keys method on an Array object which has no keys method available to it. #keys is a method for hash objects. array_of_hashes = [{key: "value"}, {a: "apple"}, {one: 1, two: 2, three: 3}] array_of_hashes.keys #throws NoMethodError array_of_hashes[2].keys #returns an array containing the keys [:one, :two, :three] =end
true
09e1991b7fe9dd95071a7305c97c53003f2ace8b
Ruby
buntine/Bolverk-Assembler
/test/functional/lexer.rb
UTF-8
7,617
3.03125
3
[]
no_license
require 'test/unit' require File.join(File.dirname(__FILE__), "../..", "lib", "asm") class LexerTest < Test::Unit::TestCase # This is easy. We just need to scan a few programs and verify that # the lexer responds appropriately. def setup path = lambda { |file| File.join(File.dirname(__FILE__), "data", file) } @program_a = Bolverk::ASM::Lexer.new(Bolverk::ASM::Stream.new(File.read(path.call("valid_a.basm")))) @program_b = Bolverk::ASM::Lexer.new(Bolverk::ASM::Stream.new(File.read(path.call("valid_b.basm")))) @program_c = Bolverk::ASM::Lexer.new(Bolverk::ASM::Stream.new(File.read(path.call("invalid_a.basm")))) @program_d = Bolverk::ASM::Lexer.new(Bolverk::ASM::Stream.new(File.read(path.call("valid_d.basm")))) end def test_program_a_has_correct_number_of_tokens @program_a.scan assert(@program_a.tokens.length == 22, "Expected 22 tokens") end def test_program_a_saves_tokens_after_scanning @program_a.scan assert(@program_a.tokens.is_a?(Array), "Expected token data to be available") end # We just need to look for a few, not all of them. def test_program_a_has_correct_tokens @program_a.scan token_a = @program_a.tokens[0] token_b = @program_a.tokens[9] token_c = @program_a.tokens[10] token_d = @program_a.tokens[15] assert(token_a.type == :keyword, "Expected :keyword at token 1") assert(token_b.type == :number, "Expected :number at token 9") assert(token_c.type == :comma, "Expected :comma at token 10") assert(token_d.type == :number, "Expected :number at token 15") assert(token_a.value == "VALL", "Expected value 'VALL' at token 1") assert(token_b.value == "1", "Expected value '1' at token 9") assert(token_c.value == ",", "Expected value ',' at token 10") assert(token_d.value == "3", "Expected value '3' at token 15") end def test_program_a_reports_tokens_on_the_correct_line @program_a.scan assert(@program_a.tokens[1].line == 2, "Expected token[1] to be on line 2") assert(@program_a.tokens[6].line == 3, "Expected token[6] to be on line 3") assert(@program_a.tokens[12].line == 4, "Expected token[12] to be on line 4") assert(@program_a.tokens[13].line == 4, "Expected token[13] to be on line 4") assert(@program_a.tokens[15].line == 5, "Expected token[15] to be on line 5") end def test_program_a_ends_with_trailing_pseudotoken @program_a.scan eof_token = @program_a.tokens.last assert(eof_token.type == :eof) end def test_program_a_has_only_one_eof_token @program_a.scan eofs = @program_a.tokens.find_all { |t| t.type == :eof } assert_equal(eofs.length, 1) end def test_lexer_gave_program_a_one_halt_mnemonic @program_a.scan # Should have been placed before the final :eof token. assert(@program_a.tokens[-2].value.downcase == "halt", "Expected compiler to add HALT") end def test_program_b_has_correct_number_of_tokens @program_b.scan assert(@program_b.tokens.length == 24, "Expected 24 tokens") end def test_program_b_saves_tokens_after_scanning @program_b.scan assert(@program_b.tokens.is_a?(Array), "Expected token data to be available") end # We just need to look for a few, not all of them. def test_program_b_has_correct_tokens @program_b.scan token_a = @program_b.tokens[0] token_b = @program_b.tokens[3] token_c = @program_b.tokens[9] token_d = @program_b.tokens[10] token_e = @program_b.tokens[16] assert(token_a.type == :keyword, "Expected :keyword at token 1") assert(token_b.type == :char, "Expected :char at token 4") assert(token_c.type == :number, "Expected :number at token 10") assert(token_d.type == :comma, "Expected :comma at token 11") assert(token_e.type == :keyword, "Expected :keyword at token 17") assert(token_a.value == "VALL", "Expected value 'VALL' at token 1") assert(token_b.value == "H", "Expected value 'H' at token 4") assert(token_c.value == "2", "Expected value '2' at token 10") assert(token_d.value == ",", "Expected value ',' at token 11") assert(token_e.value == "STOR", "Expected value 'STOR' at token 17") end def test_program_b_reports_tokens_on_the_correct_line @program_b.scan assert(@program_b.tokens[1].line == 3, "Expected token[1] to be on line 3") assert(@program_b.tokens[6].line == 4, "Expected token[6] to be on line 4") assert(@program_b.tokens[15].line == 6, "Expected token[15] to be on line 6") assert(@program_b.tokens[17].line == 7, "Expected token[17] to be on line 7") assert(@program_b.tokens[19].line == 7, "Expected token[19] to be on line 7") assert(@program_b.tokens[20].line == 8, "Expected token[20] to be on line 8") end def test_program_b_ends_with_trailing_pseudotoken @program_b.scan eof_token = @program_b.tokens.last assert(eof_token.type == :eof) end def test_program_b_has_only_one_eof_token @program_b.scan eofs = @program_b.tokens.find_all { |t| t.type == :eof } assert_equal(eofs.length, 1) end def test_lexer_gave_program_b_one_halt_mnemonic @program_b.scan # Should have been placed before the final :eof token. assert(@program_b.tokens[-2].value.downcase == "halt", "Expected compiler to add HALT") end def test_program_c_dies_with_lexical_error assert_raise Bolverk::ASM::LexicalError do @program_c.scan end end def test_program_d_has_correct_number_of_tokens @program_d.scan assert(@program_d.tokens.length == 26, "Expected 26 tokens") end def test_program_d_saves_tokens_after_scanning @program_d.scan assert(@program_d.tokens.is_a?(Array), "Expected token data to be available") end # We just need to look for a few, not all of them. def test_program_a_has_correct_tokens @program_d.scan token_a = @program_d.tokens[0] token_b = @program_d.tokens[9] token_c = @program_d.tokens[10] token_d = @program_d.tokens[7] assert(token_a.type == :keyword, "Expected :keyword at token 1") assert(token_b.type == :number, "Expected :number at token 10") assert(token_c.type == :comma, "Expected :comma at token 11") assert(token_d.type == :char, "Expected :char at token 8") assert(token_a.value == "VALL", "Expected value 'VALL' at token 1") assert(token_b.value == "2", "Expected value '2' at token 10") assert(token_c.value == ",", "Expected value ',' at token 11") assert(token_d.value == "i", "Expected value 'i' at token 9") end def test_program_d_reports_tokens_on_the_correct_line @program_d.scan assert(@program_d.tokens[1].line == 5, "Expected token[1] to be on line 5") assert(@program_d.tokens[6].line == 6, "Expected token[6] to be on line 6") assert(@program_d.tokens[12].line == 8, "Expected token[12] to be on line 8") assert(@program_d.tokens[13].line == 9, "Expected token[13] to be on line 9") assert(@program_d.tokens[15].line == 9, "Expected token[15] to be on line 9") end def test_program_d_ends_with_trailing_pseudotoken @program_d.scan eof_token = @program_d.tokens.last assert(eof_token.type == :eof) end def test_program_d_has_only_one_eof_token @program_d.scan eofs = @program_d.tokens.find_all { |t| t.type == :eof } assert_equal(eofs.length, 1) end def test_lexer_did_not_give_program_d_one_halt_mnemonic @program_d.scan # This program already has a HALT, so it should not have been added by the compiler. assert(@program_d.tokens[-2].value.downcase != "halt", "Expected compiler to NOT add HALT") end end
true
f252cb6a062242329de607a9558b7fb21fd1cbcd
Ruby
CodingDojoDallas/ruby_dec_2018
/andrew_barstow/ruby_fundamentals/human.rb
UTF-8
589
3.46875
3
[]
no_license
class Human attr_accessor :health, :strength, :stealth, :intelligence def initialize @strength = 3 @stealth = 3 @intelligence = 3 @health = 100 init_extension end def attack(character, damage = 10) #pass a character object here with a health attribute. can be inheritted, or can be a duck type begin character.health -= damage rescue => e puts "cannot attack something with no health!" puts e.message end end def init_extension self end end
true
736712d1f9ef5650c2a07660de27405ddf2f7c23
Ruby
Mohafizz/Tealeaf_Lesson_1
/calculator.rb
UTF-8
964
4.34375
4
[]
no_license
#Code up your own calculator from the lecture. Make sure you can run it from the command line. Save the calculator file in a directory, #and initialize the directory as a git repository. Make sure this isn't nested in another existing git repository. Then, push this git #repository to Github. def output(msg) puts "*****#{msg}*****" end output "Please key in first integer." int1 = gets.chomp output "You have entered #{int1}. Please key in the second integer." int2 = gets.chomp output "You have entered #{int2}. Please select the operation: 1)Add, 2)Subtract, 3)Multiply and 4)Divide" choice = gets.chomp answer = case choice #choice must take in strings instead of integers! when '1' int1.to_i + int2.to_i when '2' int1.to_i - int2.to_i when '3' int1.to_i * int2.to_i when '4' int1.to_f / int2.to_f else output "You have entered an invalid number. Please choose only 1-4." end output "You have entered #{choice}. The answer is #{answer}"
true
5f021155e1463a2983859d4a47fd9d4c18082a1f
Ruby
gabrielrigon/schommunity
/config/initializers/constantine.rb
UTF-8
1,357
2.640625
3
[ "MIT" ]
permissive
#:nodoc: module Constantine def self.included(base) base.extend(ClassMethods) end #:nodoc: module ClassMethods def constantine(attributte = :name) return unless table_exists? all.each do |item| constant_name = item.try(attributte) .remove_non_ascii_and_spaces_and_number_start.upcase .to_sym const_set(constant_name, item.id) unless const_defined?(constant_name) end end def invoke(model, constant_obj) Constantine.invoke(model, constant_obj) end end def self.invoke(model, constant_obj) if constant_obj.class == Array values = constant_obj.map do |obj| constant_value(model, obj) end values else constant_value(model, constant_obj) end end def self.invoke!(model, constant_obj) result = invoke(model, constant_obj) return result unless (result.class == Array && result.include?(0)) || result.zero? raise NameError, 'uninitialized constant' end def self.constant_value(model, object) constant_name = object.to_s.upcase model.const_defined?(constant_name) ? model.const_get(constant_name) : 0 end def invoke(model, constant_obj) Constantine.invoke(model, constant_obj) end end ActiveRecord::Base.class_eval { include Constantine }
true
925d86c04561f53953ef496769f7f3e5060598da
Ruby
yhara/sinatra_project_template
/app/controllers/books_controller.rb
UTF-8
1,162
2.515625
3
[ "MIT" ]
permissive
class MyApp < Sinatra::Base get '/books' do session["ct"] ||= 0; session["ct"] += 1 @books = Book.order(updated_at: :desc) slim :'books/index' end get '/books/new' do @book = Book.new slim :'books/new' end get '/books/:id' do @book = Book.find_by!(id: params[:id]) slim :'books/show' end post '/books' do @book = Book.new(title: params[:title]) if @book.save @flash[:notice] = "Created record: #{@book.title}" redirect "/books/#{@book.id}" else @flash[:alert] = "Failed to save record: #{@book.errors.messages.inspect}" slim :'books/new' end end get '/books/:id/edit' do @book = Book.find_by!(id: params[:id]) slim :'books/edit' end put '/books/:id' do @book = Book.find_by!(id: params[:id]) @book.title = params[:title] if @book.save @flash[:notice] = "Updated record: #{@book.title}" redirect "/books/#{@book.id}" else slim :'books/edit' end end delete '/books/:id' do book = Book.find_by!(id: params[:id]) book.destroy @flash[:notice] = "Deleted record: #{book.title}" redirect "/books" end end
true
66a01b64286ca8ec80915053df8b2185df4bcf4e
Ruby
mjvsha/collections-iteration
/ex3.rb
UTF-8
965
4.375
4
[]
no_license
=begin Print out the first two performing artists in that array. For each of your favourite movies, print out a sentence about when the movie was released. For example: Avatar came out in 2009. Mean Girls came out in 2004. The Matrix came out in 1999. Sort and reverse the array of ages of your family. Save it and print it to the screen. See if you can sort and reverse the array on one line! Add "Beauty and the Beast" movie to your hash of movies information, but with a twist: the movie was released both in 1991 and in 2017. Print it out. =end print artists[0] print artists[1] puts "#{movies}" movies = { "Kai Po Che"=> 2013, "City of God"=> 2002, "Braveheart"=> 1995 } movies.each do |movie, year| puts "#{movie} came out in #{year}" end #movie and year arethe local variables within this code block #therefore they will only exist through the iteration ages = [21, 27, 17, 22] ages.sort.reverse movies["Beauty and the Beast"] = 1991, 2017
true
87f1e6687cac54c065476cd90c89496c2593473c
Ruby
sllimnnodnarb/sep-assignments
/02-algorithms/03-sort-algorithms/bucket.rb
UTF-8
571
3.3125
3
[]
no_license
class BucketSort require_relative 'insertion_sort' def self.sort(array, bucket_size) bucket_count = ((array.max - array.min) / bucket_size).floor + 1 buckets = Array.new(bucket_count) (0..buckets.length - 1).each do |i| buckets[i] = [] end (0..array.length - 1).each do |i| buckets[((array[i] - array.min) / bucket_size).floor].push(array[i]) end array.clear (0..buckets.length - 1).each do |i| InsertionSort.sort buckets[i] buckets[i].each do |value| array.push(value) end end end end
true
f900e16c449582a63e449aeeb7f02899067bb6c1
Ruby
lburl01/tasks_sinatra
/tasks_api.rb
UTF-8
1,113
2.6875
3
[]
no_license
require 'sinatra' require_relative 'task' require 'json' get '/api/tasks' do if !params['completed'].nil? Task.where(completed: params['completed']).to_json elsif !params['search'].nil? Task.where("description like ?", "%#{params['search']}%").to_json elsif !params['sort'].nil? Task.order(priority: :asc).to_json else Task.all.to_json end end get '/api/tasks/:id' do task = Task.find_by_id(params['id']) if task.nil? halt(404) end task.to_json(methods: :description) end post '/api/tasks' do Task.create(description: params['description'], priority: params['priority'], completed: params['completed']).to_json #if i have to_json here, it won't save; get an error that it's an undefined method on a string object status 201 end put '/api/tasks/:id' do t = Task.find_by(id: params[:id]) if t.nil? halt(404) end t.update( description: params['description'], priority: params['priority'], completed: params['completed'] ).to_json end delete '/api/tasks/:id' do t = Task.find_by(id: params[:id]) if t.nil? halt(404) end t.destroy end
true
656d6774ea03feb03b7b7af3e1f975371e2ec86a
Ruby
rkh/nii
/nii-rbnf/lib/nii/rbnf/parser.rb
UTF-8
1,577
2.6875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# frozen_string_literal: true class Nii::RBNF # @api internal class Parser # PUBLIC_RULESET = /\s*%([\w\-]+)\s*:\s*/m # PRIVATE_RULESET = /\s*%%([\w\-]+)\s*:\s*/m # RULE = /\s*([^%\s\:\;][^\:\;]*)?;\s*/ SET = %r{ \s* (?<prefix>%%?) (?<name>[\w\-]+) : \s* }mx SIMPLE = %r{ \s* (?!%) '? (?<body>[^:;]*) ; }mx RULE = %r{ \s* (?<descriptor>[\w\-\.,/]+) : \s* '? (?<body>(?:[^;]|'.)*) ; \s* }mx # @see RBNF.load def parse(source, file_name) rule_sets = [] tokenize(source, file_name).each do |type, descriptor, body| case type when :set klass = body == 'lenient-parse' ? LenientParse : RuleSet rule_sets << klass.new(body, prefix: descriptor, private: descriptor == '%%') when :rule rule_sets.last.add_rule(descriptor, body) else raise end end Compiler.new(rule_sets, file_name) end # @see #parse def tokenize(source, file_name) scanner = StringScanner.new(source) tokens = [] until scanner.eos? case when scanner.scan(SET) then tokens << [:set, scanner[:prefix], scanner[:name]] when scanner.scan(SIMPLE) then tokens << [:rule, nil, scanner[:body]] when scanner.scan(RULE) then tokens << [:rule, scanner[:descriptor], scanner[:body]] else raise SyntaxError, "unexpected character: #{scanner.peek(1).inspect}" end end tokens.unshift([:set, '%', 'default']) if tokens.first&.first != :set tokens end end end
true
93f9c36c423551486857c867bd7333f86f9cfd2b
Ruby
ryoma123/competitive-programming
/atcoder/abc152/abc152_c.rb
UTF-8
148
2.921875
3
[]
no_license
n = gets.to_i a = gets.split.map(&:to_i) num = 0 min = 200000 (0...n).each do |i| if a[i] <= min num += 1 min = a[i] end end puts num
true
e4d7f08a8fbd77d58c65192d7782c2d0498162fd
Ruby
Nevillealee/recharge_checkout_webhook
/app/services/un_tagger.rb
UTF-8
4,130
2.59375
3
[]
no_license
# Internal: Using subscription or customer json recieved from recharge, # remove 'recurring_subscription' tag from matching shopify customer object # if customer no longer has an active subscription. class UnTagger def initialize(id, type, obj) @my_id = id @id_type = type @cust = obj my_token = ENV['RECHARGE_ACTIVE_TOKEN'] @my_header = { "X-Recharge-Access-Token" => my_token } end def remove shop_url = "https://#{ENV['ACTIVE_API_KEY']}:#{ENV['ACTIVE_API_PW']}@#{ENV['ACTIVE_SHOP']}.myshopify.com/admin" ShopifyAPI::Base.site = shop_url if @id_type == 'subscription' # link subscription_id to its recharge customer. # returns a hash array recharge_customer = RechargeCustomer.find_by_sql( "SELECT rc.* FROM recharge_customers rc INNER JOIN recharge_subscriptions rs ON rc.id = CAST(rs.customer_id AS BIGINT) WHERE rs.id = '#{@my_id}';" ) cust_id = recharge_customer[0]["id"] Resque.logger.info "(subscription)found recharge customer id: #{cust_id}" shopify_id = recharge_customer[0]["shopify_customer_id"] my_url = "https://api.rechargeapps.com/subscriptions?customer_id=#{cust_id}&status=ACTIVE" response = HTTParty.get(my_url, :headers => @my_header) my_response = JSON.parse(response.body) # subs_array is now an array of hashes with string keys subs_array = my_response['subscriptions'] if subs_array.size <= 0 sleep 5 my_shopify_cust = ShopifyAPI::Customer.find(shopify_id) my_tags = my_shopify_cust.tags.split(",") my_tags.map! {|x| x.strip} Resque.logger.info "tags before: #{my_shopify_cust.tags.inspect}" my_tags.delete_if {|x| x.include?('recurring_subscription')} my_shopify_cust.tags = my_tags.join(",") my_shopify_cust.save Resque.logger.info "tags after: #{my_shopify_cust.tags.inspect}" Resque.logger.info "tag removed" else Resque.logger.info subs_array.inspect Resque.logger.info "tags will not be removed, customer has #{subs_array.size} other ACTIVE subscriptions" end elsif @id_type == 'customer' begin Resque.logger.info '(customer) block reached in Untagger worker' # id_type of customer refers to recharge customer object id recharge_url = "https://api.rechargeapps.com/customers/#{@my_id}" recharge_response = HTTParty.get(recharge_url, :headers => @my_header) parsed_recharge_response = JSON.parse(recharge_response.body) recharge_cust = parsed_recharge_response['customer'] Resque.logger.info "shopify customer id: #{recharge_cust['shopify_customer_id']}" my_url = "https://api.rechargeapps.com/subscriptions?customer_id=#{@my_id}&status=ACTIVE" response = HTTParty.get(my_url, :headers => @my_header) my_response = JSON.parse(response.body) subs_array = my_response['subscriptions'] Resque.logger.info "subs_array = #{subs_array.inspect}" Resque.logger.info "number of subscriptions: #{subs_array.size}" # only remove tags if customer deactivated AND doesnt have other active subs if subs_array.size <= 0 changes_made = false sleep 5 my_shopify_cust = ShopifyAPI::Customer.find(recharge_cust['shopify_customer_id']) my_tags = my_shopify_cust.tags.split(",") Resque.logger.info "tags before: #{my_shopify_cust.tags.inspect}" my_tags.map! {|x| x.strip} my_tags.each do |x| if x.include?('recurring_subscription') my_tags.delete(x) changes_made = true end end if changes_made my_shopify_cust.tags = my_tags.join(",") Resque.logger.info "changes made, tags after: #{my_shopify_cust.tags.inspect}" my_shopify_cust.save end end rescue => e Resque.logger.info "error: #{e.message}" end else Resque.logger.info "type: '#{@id_type}' parameter not recognized.." end end end
true
127f3b985010a3c25c9aed4859dd6fb5f2312050
Ruby
philwilt/data-structs-algs
/lib/array_sorter.rb
UTF-8
1,447
3.453125
3
[]
no_license
class Array def insertion_sort! (1..size - 1).each do |i| j = i while j > 0 && (self[j - 1] > self[j]) self[j - 1], self[j] = self[j], self[j - 1] j -= 1 end end end def merge_sort ms_sort(self) end def quick_sort q_sort(self) end def radix_sort rad_sort(self, 1, find_max(self)) end private def find_max(arr) max = 0 arr.each { |e| max = e if e > max } max end def rad_sort(arr, exp, max) return arr if exp > max buckets = [[],[],[],[],[],[],[],[],[],[]] arr.each do |el| digit = (el / exp) % 10 buckets[digit] << el end rad_sort(buckets.flatten, exp * 10, max) end def q_sort(arr) return arr if arr.size <= 1 small = [] large = [] pindex = rand(arr.size) pivot = arr[pindex] arr.each_with_index do |el, index| next if index == pindex small << el if el <= pivot large << el if el > pivot end small = q_sort(small) small + [pivot] + q_sort(large) end def ms_sort(arr) return arr if arr.size == 1 split = (arr.size / 2).to_i left = ms_sort(arr.slice(0, split)) right = ms_sort(arr.slice(split, arr.size)) ms_merge(left, right) end def ms_merge(left, right) sorted = [] until left.empty? || right.empty? sorted.push(left.first <= right.first ? left.shift : right.shift) end sorted + left + right end end
true