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
8e6c8dd32226e426f0a902b28099305660d2e6a9
Ruby
VectorMC/Website
/lib/cacher.rb
UTF-8
515
2.921875
3
[ "MIT" ]
permissive
# Write a key-value pair to the rails cache. def set_cache(var, value, time) Rails.cache.write(var, value, :expires_in => time) value end # Get a value from the rails cache. # If the cache does not contain the key, the default will be used. def get_cache(var, default = nil) stored = Rails.cache.read(var) stored == nil ? default : stored end # Clear the rails cache. def reset_cache(var) Rails.cache.delete(var) end # Check if a key is in the cache. def is_in_cache(var) Rails.cache.exist?(var) end
true
46888ca3077cc10e477e9cc425f84ca08404dc79
Ruby
RomanADavis/challenges
/exercism/ruby/run-length-encoding/run_length_encoding.rb
UTF-8
716
2.984375
3
[]
no_license
class RunLengthEncoding def self.encode(string) last = encoding = '' count = 0 string.chars.each do |char| count += 1 if last == char unless last == char encoding += "#{count > 1 ? count : ""}#{last}" last, count = char, 1 end end encoding + "#{count > 1 ? count : ""}#{last}" end def self.decode(message) index = 0 output = "" while index < message.length number = "" while message[index].to_i.to_s == message[index] number += message[index] index += 1 end output += message[index] * (number.empty? ? 1 : number.to_i) index += 1 end output end end module BookKeeping VERSION = 2 end
true
03388511fe6576fae63edcffbbeff3eeb359f2b4
Ruby
shin1rok/atcoder
/ABC124/D/answer.rb
UTF-8
351
3.09375
3
[]
no_license
N, K = gets.chomp.split S = gets.chomp.split("") puts N puts K p S # N = 14 # K = 2 # S = ["1", "1", "1", "0", "1", "0", "1", "0", "1", "1", "0", "0", "1", "1"] # # 0の数を数える(連続している場合は1つとしてカウント) # 0の数がKより小さい場合、逆立ちしている人は全員 # # 0の数がKより大きい場合 #
true
33a5e24a3fa51259a3e40773ce58e0443fafbdda
Ruby
JoesGitCode/WK2_D3_Snowman_Lab
/game.rb
UTF-8
938
3.265625
3
[]
no_license
class Game attr_reader :player, :hidden_word attr_accessor :guessed_letters def initialize(player, hidden_word, guessed_letters) @player = player @hidden_word = hidden_word @guessed_letters = guessed_letters end def show_hidden_word_display return @hidden_word.display end def update_display word_array = @hidden_word.become_array_word p word_array display_array = @hidden_word.become_array_display p display_array updated_display = display_array[word_array.index(@player.take_a_guess)] = @player.take_a_guess "'#{update_display.join("")}'" end def player_starts_guessing while @hidden_word.display != @hidden_word.word || @player.lives != 0 hidden_word = show_hidden_word_display p "This is your hidden word: #{hidden_word}" p "Please guess a letter" @player.take_a_guess() end p "You win!" end end
true
22281e4bea974d9498beacc9c783fe831e547db6
Ruby
nelgau/intent
/lib/intent/parsing/transformer.rb
UTF-8
1,271
2.8125
3
[]
no_license
module Intent class Transformer attr_reader :source attr_reader :source_lines attr_reader :lines def initialize(source) @source = source @source_lines = source.lines.to_a @lines = [] @scope_stack = [] @spacing_scopes = Set.new end def output lines.join end def reset lines.clear end def emit_structural(scope, &block) add_empty_line if should_space? @scope_stack << scope @spacing_scopes << scope if scope.should_space? case scope.type when :begin yield when *(Parser::STRUCTURAL_TYPES - [:begin]) lines << source_lines[scope.first_line - 1] yield lines << source_lines[scope.last_line - 1] end @scope_stack.pop @spacing_scopes.delete(scope) add_empty_line if should_space? end def emit_terminal(scope) add_empty_line lines.concat(source_lines[scope.first_line - 1..scope.last_line - 1]) add_empty_line end private def current_scope @scope_stack.last end def should_space? @spacing_scopes.include?(current_scope) end def add_empty_line lines << "\n" unless lines.last == "\n" || lines.empty? end end end
true
fefc017ab8c1ee08715d87a097f393dc174be165
Ruby
NathanSadler/epicode_1
/leetspeak/lib/leetspeak.rb
UTF-8
565
3.4375
3
[]
no_license
require('pry') class String def leetspeak leet_phrase = [] self.split('').each do |letter| if (letter == 'e') leet_phrase.append('3') elsif (letter == 'o') leet_phrase.append('0') elsif (letter == 'I') leet_phrase.append('1') elsif (letter == 's') if (leet_phrase.length == 0 || leet_phrase[-1] == ' ') leet_phrase.append('s') else leet_phrase.append('z') end else leet_phrase.append(letter) end end foo = leet_phrase.join end end
true
a3dfb48a556b07bc221fc62e644a3f0f83c2af81
Ruby
hubenias/disco
/lib/discount/items_qty.rb
UTF-8
320
2.90625
3
[]
no_license
module Discount class ItemsQty PERCENTAGE = 0.05 DISCOUNT_QTY = 3 class << self def calculate(order) discount = 0 order.order_lines.each do |l| next if l.qty < DISCOUNT_QTY discount += l.price * PERCENTAGE end discount end end end end
true
74ba40ee5b11260bb7d5ac07ff87e80dc44e1190
Ruby
christianlarwood/ruby_small_problems
/live_coding_exercises/all_substrings.rb
UTF-8
761
4.3125
4
[]
no_license
=begin Write a method that finds all substrings in a string, no 1 letter words. algorithm: - iterate over the string starting from the first character using a range - iterate over the string starting from the first character - if substring.size > 1 then add it to our new array - return new array =end def substrings(string) result = [] (0...string.size).each do |index| (index...string.size).each do |index2| result << string[index..index2] if string[index..index2].size > 1 end end result end p substrings("band") == ['ba', 'ban', 'band', 'an', 'and', 'nd'] p substrings("world") == ['wo', 'wor', 'worl', 'world', 'or', 'orl', 'orld', 'rl', 'rld', 'ld'] p substrings("ppop") == ['pp', 'ppo', 'ppop', 'po', 'pop', 'op']
true
0fc09a8f0ec802f3c2dc29f70a20550976ddc379
Ruby
jarrettkong/flash_cards
/lib/card_generator.rb
UTF-8
230
2.703125
3
[]
no_license
# frozen_string_literal: true require 'csv' require_relative './card' class CardGenerator attr_accessor :cards def initialize(filename) csv = CSV.read(filename) @cards = csv.map { |data| Card.new(*data) } end end
true
aa93203e710452d431a677e2b1bdf1656bfe6109
Ruby
tinamarfo16/My-travel-diary-
/Mytraveldiary.rb
UTF-8
742
2.921875
3
[]
no_license
require 'sinatra' <<<<<<< HEAD get('/') do "Hello" end get('/:name') do @name = params[:name] # @name erb :hello end get('/bye/:name') do name = params[:name] "Goodbye " + name end get('/bye/:name/day') do @name = params[:name] "Hello " + name + "Have a good day" @time = 'day' erb :hello end get('/bye/:name/night') do @name = params[:name] "Hello " + name + "Have a good night" @time = 'night' ======= get ('/') do erb :hello end get ('/:name') do @name = params[:name].capitalize >>>>>>> origin/master erb :hello end post('/signup') do <<<<<<< HEAD puts params[:name] puts params[:email] "All OK" ======= puts params[:name] puts params[:email] "Thank you for sharing your holiday!" >>>>>>> origin/master end
true
263a6d6436b64f9c280b7fcd93a056af826d601e
Ruby
vladplotnikov/Bootcamp_Notes
/week6/day4/student/student.rb
UTF-8
444
3.859375
4
[]
no_license
class Student def initialize (first_name, last_name, score) @first_name, @last_name, @score = first_name, last_name, score end def full_name "#{@first_name} #{@last_name}" end def grade if @score >= 90 "A" elsif @score >= 75 "B" elsif @score >= 60 "C" elsif @score >= 50 "D" else "F" end end end
true
d33d7780b6dd0816e04f9f41d06ea8a5d18c802d
Ruby
silvanagv/oxford-comma-001-prework-web
/lib/oxford_comma.rb
UTF-8
331
3.421875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def oxford_comma(array) if array.length == 1 array.join elsif array.length == 2 array.join(" and ") elsif array.length >= 3 x = 0 string = "" array_length = array.length while x < (array.length - 1) string += "#{array[x]}, " x += 1 end string += "and #{array[x]}" end end
true
ca610c5c5eca6af8e2f2419ae89fbb2ec7fbf4d8
Ruby
louisaspicer/lrthw
/chap15/ex1.rb
UTF-8
526
4
4
[]
no_license
print "please enter filename you would like to read: " filename = gets.chomp #a new variable is created, which is the opened file 'filename' #open takes a parameter and returns a value which you can set to your own variable #this makes a "File object" txt = open(filename) #prints out what the filename from the ARGV is. puts "Here's your file #{filename}:" #prints out the txt files contents print txt.read #important to close files when you are done with them txt.close #checking file is actually closed print txt.read
true
de0744d15cce389d1d3b14cb9fa520870920f4fc
Ruby
rationality6/team_randomizer
/team.rb
UTF-8
1,063
3.375
3
[]
no_license
require 'sinatra' require 'sinatra/reloader' def randomiz(team_array, how_many, method) team_array_rand = team_array.shuffle array_result = [] team_count = 1 how_many = (team_array.length / Float(how_many)).ceil if method == 'teamcount' # how_many = team_array.length / how_many if method == 'teamcount' slice = team_array_rand.each_slice(how_many).to_a for team in slice array_result << { team_count => team } team_count += 1 end array_result end def radio_numberpercount(i) if i == 'numberpercount' 'checked' else '' end end def radio_teamcount(i) if i == 'teamcount' 'checked' else '' end end # print randomiz([1, 2, 3, 4, 5, 6, 7, 8], 3, 'teamcount') $randomiz = {} get '/' do erb :index end post '/' do $get_people = params[:names].to_s @people = $get_people.split(',') @method = params[:method] # radio button @how_many = params[:how_many].to_i # teams or people based on method $randomiz = randomiz(@people, @how_many, @method) # 2 will be the count split how_many erb :index end
true
32a6ddacdbc6250f619081706863b1deab896797
Ruby
DeCode2018/badges-and-schedules-dc-web-082718
/conference_badges.rb
UTF-8
1,788
3.65625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# conference_badges # #badge_maker # should return a formatted badge (FAILED - 1) def badge_maker(name) return "Hello, my name is #{name}." end # #batch_badge_creator # should return a list of badge messages (FAILED - 2) # should not hard-code response (FAILED - 3) def batch_badge_creator(attendee) # the below code would work more effectively but since I found it somewhere else I decided to use another method to prove to myself I could do it on my own. Since the collect method saves the results automatically to a new array, it doesnt require the extra step I needed to do with the .each method. # attendee.collect do |i| # badge_maker(i) # end badges =[] attendee.each {|i| badges.push badge_maker(i)} return badges end ############################################################################### # # #assign_rooms # # should return a list of welcome messages and room assignments (FAILED - 4) # # should not hard-code the response (FAILED - 5 # def assign_rooms(attendee) badges = [] attendee.each.with_index(1) { |val,index| badges.push "Hello, #{val}! You'll be assigned to room #{index}!"} return badges end ################################################################################ # #printer # should puts the list of badges and room_assignments (FAILED - 6) # def printer(attendee) batch_badge_creator(attendee).each do |x| puts x #interates through the attendee array to out"puts" the list of badges created by "batch_badge_creator" end assign_rooms(attendee).each do |x| puts x #interates through the attendee array to out"puts" the room assignment list created by "assign_rooms" end end ################################################################################
true
c5bc5182ee7decc3b5214dd3943d3ad1223039bb
Ruby
dmexe/r4r
/lib/r4r/windowed_adder.rb
UTF-8
2,924
3.0625
3
[ "MIT" ]
permissive
# require 'concurrent/thread_safe/util/adder' # require 'concurrent/atomic/atomic_fixnum' module R4r # A Ruby port of the finagle's WindowedAdder. # # @see https://github.com/twitter/util/blob/master/util-core/src/main/scala/com/twitter/util/WindowedAdder.scala # @see https://github.com/ruby-concurrency/concurrent-ruby/blob/master/lib/concurrent/thread_safe/util/adder.rb class WindowedAdder # Creates a time-windowed version of a {Concurrent::ThreadSafe::Util::Adder]. # # @param [Fixnum] range_ms the range of time in millisecods to be kept in the adder. # @param [Fixnum] slices the number of slices that are maintained; a higher # number of slices means finer granularity but also more memory # consumption. Must be more than 1. # @param [R4r::Clock] clock the current time. for testing. # # @raise [ArgumentError] if slices is less then 1 # @raise [ArgumentError] if range is nil # @raise [ArgumentError] if slices is nil def initialize(range_ms:, slices:, clock: nil) raise ArgumentError, "range_ms cannot be nil" if range_ms.nil? raise ArgumentError, "slices cannot be nil" if slices.nil? raise ArgumentError, "slices must be positive" if slices.to_i <= 1 @window = range_ms.to_i / slices.to_i @slices = slices.to_i - 1 @writer = 0 #::Concurrent::ThreadSafe::Util::Adder.new @gen = 0 @expired_gen = 0 #::Concurrent::AtomicFixnum.new(@gen) @buf = Array.new(@slices) { 0 } @index = 0 @now = (clock || R4r.clock) @old = @now.call end # Reset the state of the adder. def reset @buf.fill(0, @slices) { 0 } @writer = 0 @old = @now.call end # Increment the adder by 1 def incr add(1) end # Increment the adder by `x` def add(x) expired if (@now.call - @old) >= @window @writer += x end # Retrieve the current sum of the adder # # @return [Fixnum] def sum expired if (@now.call - @old) >= @window value = @writer i = 0 while i < @slices value += @buf[i] i += 1 end value end private def expired # return unless @expired_gen.compare_and_set(@gen, @gen + 1) # At the time of add, we were likely up to date, # so we credit it to the current slice. @buf[@index] = sum_and_reset @index = (@index + 1) % @slices # If it turns out we've skipped a number of # slices, we adjust for that here. nskip = [((@now.call - @old) / @window) - 1, @slices].min if nskip > 0 r = [nskip, @slices - @index].min @buf.fill(@index, r) { 0 } @buf.fill(0, nskip - r) { 0 } @index = (@index + nskip) % @slices end @old = @now.call @gen += 1 end def sum_and_reset sum = @writer @writer = 0 sum end end end
true
cac5aaab90561e37cd263330fea11fcd75b2a2b9
Ruby
mehlah/neo4j-playground
/friends-path.rb
UTF-8
1,625
3.5
4
[]
no_license
require 'rubygems' require 'neography' @neo = Neography::Rest.new def create_person(name) @neo.create_node("name" => name) end def make_mutual_friends(node1, node2) @neo.create_relationship("friends", node1, node2) @neo.create_relationship("friends", node2, node1) end def degrees_of_separation(start_node, destination_node) paths = @neo.get_paths(start_node, destination_node, {"type"=> "friends", "direction" => "in"}, depth=4, algorithm="allSimplePaths") paths.each do |p| p["names"] = p["nodes"].collect { |node| @neo.get_node_properties(node, "name")["name"] } end end mehdi = create_person('Mehdi') kevin = create_person('Kevin') antoine = create_person('Antoine') marie = create_person('Marie') foof = create_person('Foof') clement = create_person('Clement') make_mutual_friends(mehdi, kevin) make_mutual_friends(kevin, marie) make_mutual_friends(kevin, foof) make_mutual_friends(marie, foof) make_mutual_friends(mehdi, antoine) make_mutual_friends(kevin, antoine) make_mutual_friends(mehdi, clement) degrees_of_separation(mehdi, marie).each do |path| puts "#{(path["names"].size - 1 )} degrees: " + path["names"].join(' => friends => ') end # Output # 2 degrees: Mehdi => friends => Kevin => friends => Marie # 3 degrees: Mehdi => friends => Kevin => friends => Foof => friends => Marie # 3 degrees: Mehdi => friends => Antoine => friends => Kevin => friends => Marie # 4 degrees: Mehdi => friends => Antoine => friends => Kevin => friends => Foof => friends => Marie
true
7cc5e8d9db05ba2ce1be11218b0d16a9b258de41
Ruby
Tubbz-alt/planner-core
/db/migrate/20110219174507_update_phone_numbers.rb
UTF-8
604
2.546875
3
[ "Apache-2.0" ]
permissive
require 'person' require 'address' require 'postal_address' require 'phone_number' class UpdatePhoneNumbers < ActiveRecord::Migration def self.up # Go through the people and extract those that have a phone number in their address people = Person.where('postal_addresses.phone is not null').includes(:postal_addresses) people.each do |person| person.postal_addresses.each do |addr| phone = person.phone_numbers.new phone.number = addr.phone phone.phone_type_id = PhoneTypes[:Home].id end person.save end end def self.down end end
true
d6858d8e999582b343aa4da171a17e5f485673a6
Ruby
lukefraenza/LearnRuby
/Part1/2_Ruby.new/intro_5.rb
UTF-8
196
3.40625
3
[]
no_license
def say_goodnight(name) result = "good night, " + name return result end # Time for bed... puts say_goodnight("John-Boy") puts say_goodnight("Mary-Ellen") puts "And good night, \n\t\tGrandma"
true
3a58577ba719f3b39ce2900f52505e95be3dfbcc
Ruby
johnhamelink/xdefaults_to_termite
/option.rb
UTF-8
121
2.609375
3
[ "MIT" ]
permissive
class Option attr_accessor :key, :value def initialize(key, value) self.key, self.value = key, value end end
true
6b571836e605cd1b5b8f7cff52b28240a9dcfd3d
Ruby
jchamberlain909/ruby-objects-has-many-through-lab-dc-web-060418
/lib/artist.rb
UTF-8
537
3.640625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Artist @@all =[] attr_accessor :name, :songs def initialize (name) @name = name @songs = [] self.class.all << self end def new_song (name, genre) song =Song.new(name, self, genre) self.songs << song song end def genres genres = [] self.songs.each do |song| if(!genres.include? song.genre) genres << song.genre end end genres end def self.all @@all end end
true
1b28223e371c0a69641b97305e38c24e81b680f4
Ruby
EthWorks/ethereum.rb
/lib/ethereum/deployment.rb
UTF-8
1,310
2.703125
3
[ "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
module Ethereum class Deployment DEFAULT_TIMEOUT = 300.seconds DEFAULT_STEP = 5.seconds attr_accessor :id, :contract_address, :connection, :deployed, :mined attr_reader :valid_deployment def initialize(txid, connection) @id = txid @connection = connection @deployed = false @contract_address = nil @valid_deployment = false end def mined? return true if @mined @mined = @connection.eth_get_transaction_by_hash(@id)["result"]["blockNumber"].present? @mined ||= false end def check_deployed return false unless @id contract_receipt = @connection.eth_get_transaction_receipt(@id) result = contract_receipt["result"] has_contract_address = result && result["contractAddress"] @contract_address ||= result["contractAddress"] if has_contract_address has_contract_address && result["blockNumber"] end def deployed? @valid_deployment ||= check_deployed end def wait_for_deployment(timeout: DEFAULT_TIMEOUT, step: DEFAULT_STEP) start_time = Time.now loop do raise "Transaction #{@id} timed out." if ((Time.now - start_time) > timeout) yield if block_given? return true if deployed? sleep step end end end end
true
5e9f7b13f8da7652c8aa9751f4be8c0b4daec590
Ruby
kalbasit/.nixpkgs
/overlays/all/zsh-config/bin/find-duplicates
UTF-8
1,000
3.09375
3
[]
no_license
#!/usr/bin/env ruby require 'fileutils' require 'digest/md5' class DuplicateFiles attr_reader :files attr_reader :md5_to_files def initialize(dir) @base_dir = dir _scan_for_files @base_dir _hash_files end def scan_for_duplicates @duplicate_files ||= Hash.new @md5_to_files.each do |v| if v[1].size > 1 @duplicate_files[v[0]] = v[1] end end @duplicate_files end private def _scan_for_files(dir) @files ||= Array.new @md5_to_files ||= Hash.new Dir.glob(dir + File::Separator + '*').each do |f| if !File.directory? f @files << f else _scan_for_files f end end end def _hash_files @files.each do |f| digest = Digest::MD5.file(f) @md5_to_files[digest.to_s] ||= Array.new @md5_to_files[digest.to_s] << f end end end df = DuplicateFiles.new(FileUtils.getwd) duplicates = df.scan_for_duplicates if duplicates duplicates.each do |v| puts "#{v[0]} #{v[1][0]}" for f in 1...v[1].size puts "\t#{v[1][f]}" end end end
true
e90af5b87ccbcc766e1afa14ca3c509ec70329eb
Ruby
gkpacker/exercism-ruby
/gigasecond/gigasecond.rb
UTF-8
227
2.734375
3
[]
no_license
module BookKeeping VERSION = 6 # Where the version number matches the one in the test. end class Gigasecond def self.from(time_utc) year_gigasecond = time_utc.to_i + (10**9) Time.at(year_gigasecond).utc end end
true
8caaec0673d9341df3b5072e2004dfff71607895
Ruby
dannynpham/cryptocurrencycoinbot
/helpers/currency.rb
UTF-8
1,437
2.9375
3
[ "Apache-2.0" ]
permissive
require 'open-uri' require 'money' I18n.config.available_locales = :en module Currency URL = "https://api.coinmarketcap.com/v1/ticker/?limit=500" def get_symbols(text, trigger_word) text.gsub(trigger_word, '').strip.upcase.split(' ') end def get_coinwatch_currencies currencies = {} JSON.parse(open(URL).read).each do |currency| currencies[currency['symbol']] = currency end return currencies end def get_return_currency(symbol, currency) if currency && currency['name'] && currency['price_usd'] { name: currency['name'], price: currency['price_usd'] } elsif currency { name: symbol, message: 'Unknown error getting price' } else { name: symbol, message: 'Unknown currency' } end end def get_return_currencies(symbols, currencies) symbols.map{ |symbol| get_return_currency(symbol, currencies[symbol]) } end def currency_message(currency) return "Unknown error." unless currency.is_a?(Hash) && currency[:name] if currency[:price] price = Money.new(100 * currency[:price].to_f, "USD") "#{currency[:name]} is currently valued at #{price.format}" elsif currency[:message] "#{currency[:name]} - #{currency[:message]}" else "#{currency[:name]} - Unknown error" end end def currencies_message(currencies) currencies.map{ |currency| currency_message(currency) }.join("\n") end end helpers Currency
true
cf7142fd34c65c64097ea78f3efb32d97134cae6
Ruby
egamasa/study
/ruby-cherry-book/Section4/4-5-2_range_more_less.rb
UTF-8
460
3.796875
4
[]
no_license
### n以上m以下、n以上m未満 の判定 ### # 不等号 def liquid?(temperature) 0 <= temperature && temperature < 100 end p liquid?(-1) #=> false p liquid?(0) #=> true p liquid?(99) #=> true p liquid?(100) #=> false # 範囲オブジェクト def liquid_range?(temperature) (0...100).include?(temperature) end p liquid_range?(-1) #=> false p liquid_range?(0) #=> true p liquid_range?(99) #=> true p liquid_range?(100) #=> false
true
1586fb4553254d3ef20f706c451c9cd0865e9a75
Ruby
jemc/wires
/spec/base/channel_spec.rb
UTF-8
16,345
2.546875
3
[]
no_license
require 'spec_helper' describe Wires::Channel do # A Channel object to operate on subject { Wires::Channel.new 'channel' } # Some common objects to operate with let(:event) { Wires::Event.new } let(:event2) { :other_event[] } let(:a_proc) { Proc.new { nil } } let(:b_proc) { Proc.new { true } } let(:names) {['channel', 'Channel', 'CHANNEL', :channel, :Channel, :CHANNEL, /channel/, /Channel/, /CHANNEL/, ['channel'], [:channel], [/channel/], '*', Object.new, Hash.new]} let(:event_patterns) { [ :dog, :*, Wires::Event.new, :dog[55], :dog[55,66], :dog[arg1:32], :dog[55,arg1:32], [:dog,:wolf,:hound,:mutt] ] } # Convenience function for creating a set of channels by names def channels_from names names.map{|x| Wires::Channel[x]} end # Clean out channel list between each test before { Wires::Channel.router = Wires::Router::Default Wires::Channel.router.clear_channels } describe ".new / #initialize" do it "creates exactly one unique instance for each unique name" do past_channels = [] for name in names past_channels << (c = Wires::Channel.new(name)) expect(Wires::Channel.new(name)).to equal c end expect(past_channels.map(&:name)).to match_array names end it "assigns new/existing objects in a threadsafe way" do for n in 1..5 threads = [] channels = [] for m in 0..100 threads[m] = Thread.new {channels<<Wires::Channel.new(n)} end threads.each &:join expect(channels.uniq.size).to eq 1 end end def loop_gc_with_timeout start_time = Time.now refs = [] loop { # loop until one of the channel name objects is gone refs << Ref::WeakReference.new(Object.new) chan = Wires::Channel.new refs.last.object yield chan if block_given? GC.start break if refs.map(&:object).map(&:nil?).any? raise Timeout::Error if Time.now-0.5 > start_time } end it "doesn't prevent the name object from being garbage collected" do expect { loop_gc_with_timeout }.not_to raise_error end it "will prevent the name object from being garbage collected"\ " if a handler has been registered" do expect { loop_gc_with_timeout { |chan| chan.register event, &a_proc }}.to raise_error Timeout::Error end it "won't prevent the name object from being garbage collected"\ " if all handlers have been unregistered" do expect { loop_gc_with_timeout { |chan| chan.register event, &a_proc a_proc.unregister }}.not_to raise_error end it "will prevent the name object from being garbage collected"\ " if not all handlers have been unregistered" do expect { loop_gc_with_timeout { |chan| chan.register event, &a_proc chan.register event, &b_proc a_proc.unregister }}.to raise_error Timeout::Error end end describe "#handlers" do its(:handlers) { should be_an Array } its(:handlers) { should be_empty } its(:handlers) { subject.register event, &a_proc should_not be_empty } end describe "#register" do its(:handlers) { subject.register event, &a_proc should include [[event], a_proc] } its(:handlers) { subject.register event, event2, &a_proc should include [[event, event2], a_proc] } around { |ex| Ref::Mock.use { ex.run } } it "returns the registered proc" do expect(subject.register(event, &a_proc)).to eq a_proc end it "attaches an #unregister method to the returned proc" do return_val = subject.register(event, &a_proc) expect(return_val.unregister).to eq [subject] expect(subject.handlers).to eq [] expect(return_val.unregister).to eq [] expect(subject.handlers).to eq [] end it "attaches an #unregister method that works for "\ "all Channels with that proc registered within" do chan1 = Wires::Channel[Object.new] chan2 = Wires::Channel[Object.new] return_val = subject.register(event, &a_proc) return_val1 = chan1.register(event, &a_proc) return_val2 = chan2.register(event, &a_proc) expect(return_val1).to eq return_val expect(return_val2).to eq return_val expect(return_val.unregister).to match_array [subject, chan1, chan2] expect(return_val.unregister).to eq [] expect(subject.handlers).to eq [] expect(chan1.handlers).to eq [] expect(chan2.handlers).to eq [] end it "can hold a weak reference instead if requested" do bucket = [] return_val = subject.register event, weak:true do bucket << 88 end expect(return_val).to be_a Proc subject.fire! event; expect(bucket.count).to eq 1 subject.fire! event; expect(bucket.count).to eq 2 Ref::Mock.gc subject.fire! event; expect(bucket.count).to eq 2 end end describe "#unregister" do its(:handlers) { "with a matching proc, unregisters the registration of it" subject.register event, &a_proc subject.unregister &a_proc should be_empty } its(:handlers) { "with a matching proc, unregisters all registrations of it" subject.register event, &a_proc subject.register :other_event, &a_proc subject.register :yet_another_event, &a_proc subject.unregister &a_proc should be_empty } its(:handlers) { "with a non-matching proc, does nothing" subject.register event, &a_proc subject.unregister &Proc.new{nil} should_not be_empty } it "returns true/false to indicate if an unregistration occurred" do expect(subject.unregister(&a_proc)).to eq false subject.register event, &a_proc expect(subject.unregister(&a_proc)).to eq true end end describe "#receivers" do before { channels_from names } its(:receivers) { should eq Wires::Router::Default.get_receivers subject } end describe "#=~" do let(:channels) { channels_from names } it "returns true/false to indicate if 'a' is a receiver of 'b'" do for a in channels for b in channels (Wires::Channel.router.get_receivers(b).include? a) ? (expect(a).to be =~ b) : (expect(a).not_to be =~ b) end end end end describe ".router" do specify { expect(Wires::Channel.router).to eq Wires::Router::Default } end describe ".router=" do around { Wires::Channel.router = Wires::Router::Simple; channels_from names} before { Wires::Channel.router = Wires::Router::Default } specify { expect(Wires::Channel.router).to eq Wires::Router::Simple } its(:receivers) { should eq Wires::Router::Simple.get_receivers subject } end describe "#fire" do it "fires the given event to handlers registered on"\ " receivers of the given channel" do channels = channels_from(names) received = [] channels.each { |c| c.register(:event) { received << c } } channels.reject{|c| c.name.is_a? Regexp}.each do |channel| channel.fire :event, blocking:true expect(received).to match_array channel.receivers received.clear end end it "fires the given event to handlers listening for"\ " an event pattern matching the fired event (see Event#=~)" do received = [] event_patterns.each { |e| subject.register(e) { received << e } } event_patterns.reject{|e| e.is_a? Array}.each do |e| subject.fire e, blocking:true expect(received).to match_array (event_patterns.select { |e2| a = Wires::Event.list_from(e2) b = Wires::Event.list_from(e) a.map{|x| x=~b.first}.any? }) received.clear end end it "calls the hooks registered in :@before_fire and :@after_fire" do flop = false last_ran = :after_2 b1_hook = Wires::Channel.add_hook(:@before_fire) do |evt, chan| expect(evt).to eq event expect(chan).to eq subject.name expect(last_ran).to eq :after_2 last_ran = :before_1 end b2_hook = Wires::Channel.add_hook(:@before_fire) do |evt, chan| expect(evt).to eq event expect(chan).to eq subject.name expect(last_ran).to eq :before_1 last_ran = :before_2 end subject.register event do expect(last_ran).to eq :before_2 last_ran = :actual flop = !flop end a1_hook = Wires::Channel.add_hook(:@after_fire) do |evt, chan| expect(evt).to eq event expect(chan).to eq subject.name expect(last_ran).to eq :actual last_ran = :after_1 end a2_hook = Wires::Channel.add_hook(:@after_fire) do |evt, chan| expect(evt).to eq event expect(chan).to eq subject.name expect(last_ran).to eq :after_1 last_ran = :after_2 end # Note that after_hooks are only guaranteed to happen after # the call to #fire, not after the handlers are executed; # therefore, they are only guaranteed to execute after the # handlers when blocking is set to true subject.fire event, blocking:true; expect(flop).to be true subject.fire event, blocking:true; expect(flop).to be false # Repeal all four hooks Wires::Channel.remove_hook(:@after_fire, &a1_hook) Wires::Channel.remove_hook(:@after_fire, &a2_hook) Wires::Channel.remove_hook(:@before_fire, &b1_hook) Wires::Channel.remove_hook(:@before_fire, &b2_hook) end end describe "#fire" do let(:on_method) { Proc.new { |e,c,&blk| c.register e,&blk } } let(:fire_method) { Proc.new { |e,c,**kw| c.fire e,**kw } } it_behaves_like "a non-blocking fire method" end describe "#fire!" do let(:on_method) { Proc.new { |e,c,&blk| c.register e,&blk } } let(:fire_method) { Proc.new { |e,c,**kw| c.fire! e,**kw } } it_behaves_like "a blocking fire method" end describe "#sync_on" do let(:freed) { [] } before { subject.register :tie_up do |e| sleep 0.05 freed << self subject.fire :free_up[*e.args,**e.kwargs] end } let!(:start_time) { Time.now } def elapsed_time; Time.now - start_time; end def should_timeout(duration) elapsed = elapsed_time expect(elapsed).to be < duration+0.1 expect(elapsed).to be >= duration end def should_not_timeout(duration) elapsed = elapsed_time expect(elapsed).to be < duration end it "can wait within a block until a given event is fired on the channel" do subject.sync_on :free_up do subject.fire :tie_up expect(freed).to be_empty end expect(freed).to_not be_empty end it "always returns nil" do return_val = subject.sync_on :free_up do subject.fire :tie_up end expect(return_val).to eq nil end it "is re-entrant to allow matching blocking fire within" do subject.sync_on :free_up do subject.fire! :free_up end end it "can wait with a timeout" do subject.sync_on :free_up, timeout:0.2 do subject.fire :nothing expect(freed).to be_empty end expect(freed).to be_empty should_timeout 0.2 end it "can wait with extra conditions" do subject.sync_on :free_up, timeout:0.2 do |s| subject.fire :tie_up[1,2,3] s.condition { |e| e.args.include? 1 } s.condition { |e,c| e.args.include? 2; expect(c).to eq subject.name } end expect(freed).to_not be_empty should_not_timeout 0.2 end it "will timeout when extra conditions are not met" do subject.sync_on :free_up, timeout:0.2 do |s| subject.fire :tie_up[1,2,3] s.condition { |e| e.args.include? 1 } s.condition { |e| e.args.include? 999 } # won't be met end expect(freed).to_not be_empty should_timeout 0.2 end it "can wait with one or more blocks to execute on the matching event" do bucket1, bucket2 = [], [] subject.sync_on :free_up do |s| subject.fire :tie_up[1,2,3] s.condition { |e| e.args.include? 1 } s.condition { |e| e.args.include? 2 } s.execute { |e| bucket1 << e } s.execute { |e,c| bucket2 << e; expect(c).to eq subject.name } end expect(bucket1).to match_array [:free_up[1,2,3]] expect(bucket2).to match_array [:free_up[1,2,3]] end it "will not run the execute blocks if the wait timed out" do bucket1, bucket2 = [], [] subject.sync_on :free_up, timeout:0.2 do |s| subject.fire :tie_up[1,2,3] s.condition { |e| e.args.include? 1 } s.condition { |e| e.args.include? 999 } # won't be met s.execute { |e| bucket1 << e } s.execute { |e| bucket2 << e } end expect(bucket1).to be_empty expect(bucket2).to be_empty should_timeout 0.2 end it "can wait at an explicit point within the block" do subject.sync_on :free_up do |s| subject.fire :tie_up expect(freed).to be_empty expect(s.wait).to eq :free_up[] expect(freed).to_not be_empty end expect(freed).to_not be_empty end it "can wait at an explicit point with a timeout" do subject.sync_on :free_up do |s| subject.fire :tie_up expect(freed).to be_empty expect(s.wait(0.2)).to eq :free_up[] expect(freed).to_not be_empty end expect(freed).to_not be_empty end it "can wait at an explicit point, giving nil if timed out" do subject.sync_on :free_up do |s| subject.fire :nothing expect(s.wait(0.2)).to eq nil expect(freed).to be_empty end expect(freed).to be_empty should_timeout 0.2 end it "can wait at an explicit point using the default timeout" do subject.sync_on :free_up, timeout:0.2 do |s| expect(s.wait).to eq nil end should_timeout 0.2 end it "can wait at an explicit point using some other timeout" do subject.sync_on :free_up, timeout:500 do |s| expect(s.wait(0.2)).to eq nil end should_timeout 0.2 end it "can wait multiple explicit times" do subject.sync_on :free_up do |s| subject.fire :tie_up[1,2,3] expect(freed.count).to be 0 expect(s.wait(0.2)).to eq :free_up[1,2,3] subject.fire :tie_up[4,5,6] expect(freed.count).to be 1 expect(s.wait(0.2)).to eq :free_up[4,5,6] expect(freed.count).to be 2 expect(s.wait(0.2)).to eq nil end end it "will queue up matching events for additional waits" do subject.sync_on :free_up do |s| expect(freed.count).to be 0 3.times { subject.fire! :tie_up } expect(freed.count).to be 3 3.times { expect(s.wait(0.2)).to eq :free_up } expect(s.wait(0.2)).to eq nil end end it "lets exceptions raised from within an execute block pass out" do expect { subject.sync_on :free_up do |s| subject.fire :tie_up s.execute { raise RuntimeError, 'whoops' } end }.to raise_error RuntimeError, /whoops/ end it "lets exceptions raised from within a condition block pass out" do expect { subject.sync_on :free_up do |s| subject.fire :tie_up s.condition { raise RuntimeError, 'whoops' } end }.to raise_error RuntimeError, /whoops/ end end end
true
ed38b36b63376c681bc989b64ddee9187141c62f
Ruby
a6ftcruton/addycaddy
/lib/csv_importer.rb
UTF-8
171
2.640625
3
[]
no_license
require 'csv' require 'net/http' class CSVImporter attr_reader :uri def initialize(uri) @uri = uri end def read_file Net::HTTP.get(uri) end end
true
ea22d7001b728cf100849ce1502a7242f590a537
Ruby
mattrayner/givepuppi.es
/spec/models/puppies_spec.rb
UTF-8
1,757
2.921875
3
[]
no_license
require 'rails_helper' RSpec.describe Puppy do before :each do when_i_create_a_number_of_puppies end describe 'can search by orientation' do before :each do and_i_search_by_orientation end it '.horizonal' do there_are_five_horizontal_puppies end it '.vertical' do there_are_three_vertical_puppies end it '.square' do there_are_four_square_puppies end end describe 'can search by disabled status' do it '.disabled' do there_are_five_disabled_puppies end it '.enabled' do there_are_twelve_enabled_puppies end end end # Create a number of puppies for each of the orientations we can have. # # @author Matt Rayner def when_i_create_a_number_of_puppies create_list :puppy, 5, orientation: 'hor' create_list :puppy, 3, orientation: 'ver' create_list :puppy, 4, orientation: 'squ' create_list :puppy, 5, disabled: true end # Get a collection of puppies for each of the orientations possible. # # @author Matt Rayner def and_i_search_by_orientation @horizontal = Puppy.enabled.horizontal @vertical = Puppy.enabled.vertical @square = Puppy.enabled.square end # @author Matt Rayner def there_are_five_horizontal_puppies expect(@horizontal.size).to eql 5 end # @author Matt Rayner def there_are_three_vertical_puppies expect(@vertical.size).to eql 3 end # @author Matt Rayner def there_are_four_square_puppies expect(@square.size).to eql 4 end # Get a collection of disabled puppies and check the number # # @author Matt Rayner def there_are_five_disabled_puppies expect(Puppy.disabled.size).to eql 5 end # Get a collection of enabled puppies and check the number # # @author Matt Rayner def there_are_twelve_enabled_puppies expect(Puppy.enabled.size).to eql 12 end
true
e931300c9ee9f50d6701c0efaad3a01c55fc320f
Ruby
GetPhage/phage
/lib/phage/scan/arp-snmp.rb
UTF-8
1,000
2.8125
3
[ "MIT" ]
permissive
require 'snmp' require 'pp' # https://github.com/hallidave/ruby-snmp module Scan class ArpSNMP include Enumerable attr :collection def initialize(host) @host = host @collection = [] end def perform SNMP::Manager.open(host: @host) do |manager| manager.walk('ipNetToMediaPhysAddress.3') do |row| @collection.push { ipv4: "", mac_address: row[:value] } end end end protected def find_interface(ip_address) # search for ipAdEntIfIndex.10.0.1.1, returns the index of the interface end def extract_ipv4(str) str.match /(\d+\.\d+\.\d+\.\d+)^/ if match match[1] end end def ethernet_to_s(value) value.map { |b| sprintf(", 0x%02X",b) }.join(':') # show hex # line = a.map { |b| sprintf(", 0x%02X",b) }.join # http://stackoverflow.com/questions/8350171/convert-string-to-hexadecimal-in-ruby end end end
true
42068f372611482d29c927aa89520ccf745a09b0
Ruby
annieyshin/ruby_animal_shelter
/spec/customer_spec.rb
UTF-8
3,256
2.875
3
[]
no_license
require("rspec") require("pg") require("animal_shelter") require("spec_helper") require('pry') require('customer') describe(Customer) do describe(".all") do it("is empty at first") do expect(Customer.all()).to(eq([])) end end end describe('#save') do it('adds a customer to the array of saved customers') do test_customer = Customer.new({:id => nil, :customer_name => 'Pepper Shakington', :phone_number => '714-871-7895', :animal_type_preference => "cat", :animal_breed_preference=> "siamese"}) test_customer.save() expect(Customer.all()).to(eq([test_customer])) end end # describe("#animal_name") do # it("lets you read the animal name and information") do # test_animal = Animal.new({:id => 1, :animal_name => 'Charlie', animal_gender: 'female', :date_of_admittance => "06/06/2006", :animal_type => "cat", :animal_breed => "siamese"}) # expect(test_animal.animal_name()).to(eq("Charlie")) # end # end # describe("#list_all_animal_information") do # it("lets you read the animal name and information") do # test_animal = Animal.new({:id => 1, :animal_name => 'Charlie', animal_gender: 'female', :date_of_admittance => "06/06/2006", :animal_type => "cat", :animal_breed => "siamese"}) # expect(test_animal.list_all_animal_information()).to(eq([{:id=>1, :animal_name=>"Charlie", :animal_gender=>"female", :date_of_admittance=>"06/06/2006", :animal_type=>"cat", :animal_breed=>"siamese"}])) # end # end # describe("#list_all_animal_information") do # it("lets you read the animal name and information") do # test_animal = Animal.new({:id => 1, :animal_name => 'Charlie', animal_gender: 'female', :date_of_admittance => "06/06/2006", :animal_type => "cat", :animal_breed => "siamese"}) # test_animal.save() # test_animal2 = Animal.new({:id => 2, :animal_name => 'Mookie', animal_gender: 'male', :date_of_admittance=>"06/06/2006", :animal_type => "dog", :animal_breed => "chow chow"}) # test_animal2.save() # expect(Animal.all()).to(eq([test_animal, test_animal2])) # end # end # describe("#sort_date_of_admittance") do # it("will sort all animals by the day they were admitted") do # test_animal = Animal.new({:id => 1, :animal_name => 'Charlie', animal_gender: 'female', :date_of_admittance => "06/06/2012", :animal_type => "cat", :animal_breed => "siamese"}) # test_animal.save() # test_animal2 = Animal.new({:id => 2, :animal_name => 'Mookie', animal_gender: 'male', :date_of_admittance=>"06/06/2006", :animal_type => "dog", :animal_breed => "chow chow"}) # test_animal2.save() # expect(Animal.sort_date_of_admittance()).to(eq([test_animal2, test_animal])) # end # end # # describe('#==') do # it('is the same task if it has the same description') do # test_animal = Animal.new({:id => 1, :animal_name => 'Charlie', animal_gender: 'female', :date_of_admittance => "06/06/2006", :animal_type => "cat", :animal_breed => "siamese"}) # test_animal2 = Animal.new({:id => 1, :animal_name => 'Charlie', animal_gender: 'female', :date_of_admittance => "06/06/2006", :animal_type => "cat", :animal_breed => "siamese"}) # expect(test_animal).to(eq(test_animal2)) # end # end # end
true
52623c847f60c079d0c9b0232d0c5658f773f59e
Ruby
michaelporter/Vinyl
/bin/vinyl.rb
UTF-8
923
2.5625
3
[]
no_license
#!/usr/bin/env ruby $: << File.join(File.dirname(__FILE__), "/..") require 'lib/vinyl/album.rb' require 'lib/vinyl/artist_solo.rb' require 'lib/vinyl/artist_group.rb' require 'lib/vinyl/menu.rb' require 'lib/vinyl/migration.rb' require 'lib/vinyl/utility.rb' require 'lib/vinyl/database_operations.rb' include Menu include Utility::CommandTools db = SQLite3::Database.open("my_vinyl.db") # maybe a global here would be worth it Album.set_db(db) Artist.set_db(db) res = {} case ARGV[0] when "new", "New", "Add", "add" terminator { new_stuff(ARGV) } when "change", "update" terminator { update_stuff(ARGV) } when "find" terminator { find_stuff(ARGV) } when "migrate" terminator { DatabaseOperations::migrate } when /\w+/i # be able to simply type in a name and return search results; if artists are found, returns information about them puts ARGV.inspect Process.exit else terminator { prompt_menu } end
true
611b7797055e0306406f72fab3ee71b29d30d5b1
Ruby
dpantic/rubylearning_37
/3wk/11-exercise.rb
UTF-8
123
3.59375
4
[]
no_license
collection = [12, 23, 456, 123, 4579].each do |num| print "#{ num } \tis" num.even? ? puts(" even") :puts(" odd") end
true
82f800fd6a006f4d304a03e27785e5cb3d5a5fdf
Ruby
compwron/lc
/roman-to-integer.rb
UTF-8
850
3.75
4
[]
no_license
# @param {String} s # @return {Integer} def roman_to_int(s) m = { "I" => 1, "V" => 5, "X" => 10, "L" => 50, "C" => 100, "D" => 500, "M" => 1000, } pieces = s.split('') skip_ = false sum = 0 pieces.each_with_index do |c, idx| curr = m[c] if idx == pieces.count - 1 if skip_ skip_ = false else sum += curr end else n = pieces[idx + 1] nex = m[n] if curr < nex sum += nex - curr skip_ = true else if skip_ skip_ = false else sum += curr skip_ = false end end end end sum end p roman_to_int('III') == 3 p roman_to_int('IV') == 4 p roman_to_int('IX') == 9 p roman_to_int('LVIII') == 58 p roman_to_int('MCMXCIV')#, roman_to_int('MCMXCIV') == 1994
true
9f6a04f06d3656c5c60c5b1b7769a816992ea0d7
Ruby
mattdvhope/postit_template
/lib/sluggable.rb
UTF-8
2,490
3.25
3
[]
no_license
module Sluggable # This code is extracted from post.rb, category.rb & user.rb models. Use 'self.class.' to work with all three classes. extend ActiveSupport::Concern included do before_save :generate_slug! class_attribute :slug_column # Used to save the col_name below. end def generate_slug! #.slug method comes from the 'slug' column in the 'posts' table. the_slug = to_slug(self.send(self.class.slug_column.to_sym)) # 1. We first generated/sluggify a new slug | self.send(self.class.slug_column.to_sym) is the replacement for 'self.title' or 'self.name' or 'self.username'. obj = self.class.find_by slug: the_slug # 2. We then look in our db for an already-existing slug of the_slug's [same] name. count = 2 while obj && obj != self # We're saying here... "While the obj exists, but it's not the same object as we're dealing with. We don't want to append an additional number if we're dealing with the same obj object." the_slug = append_suffix(the_slug, count) #the_slug + "-" + count.to_s obj = self.class.find_by slug: the_slug count += 1 end self.slug = the_slug.downcase #this is set as a variable, but is not yet saved to the DB. Thus, you'll need '.save' in the next line; but better yet, you can save it to the ActiveRecord call-back. end def append_suffix(str, count) if str.split('-').last.to_i != 0 return str.split('-').slice(0...-1).join('-') + "-" + count.to_s else return str + "-" + count.to_s end end def to_slug(name) name.strip.downcase.gsub(/\s*[^a-z0-9]\s*/, '-').gsub /-+/, "-" end # to_param evalutes to id by default (like in posts/_post.html.erb in post_path(post) [where 'post' is the argument rather than post.id]). def to_param # This overwrites the 'to_param' method (That is called by default in the views with something like: 'edit_post_path(@post)'). It is overridden so that the slug can be executed. self.slug #.slug method comes from the 'slug' column in the 'posts' table. end module ClassMethods def sluggable_column(col_name) # We're trying to expose a class method for the class that's including this module to set the column name to use; then we're saving the column name to an attribute ('class_attribute', above) that we can now reference in our code here, in our instance methods. self.slug_column = col_name # This assigns the perticular class' column name to the class_attribute above. end end end
true
bc203fb7d6255e07732844e15c4930130f371fd0
Ruby
egaichet/ElementWar
/test/models/castle_test.rb
UTF-8
1,024
2.890625
3
[]
no_license
require 'test_helper' class CastleTest < MiniTest::Test def test_can_populate_castle_rooms castle = Castle.new([foe, foe, foe]) assert_equal ['left', 'middle', 'right'], castle.available_rooms end def test_room_with_dead_character_is_not_available castle = Castle.new([dead_foe, foe, foe]) assert_equal ['middle', 'right'], castle.available_rooms end def test_hero_is_at_center_at_beginning castle = Castle.new([]) assert_equal 'center', castle.current_room end def test_hero_can_move castle = Castle.new([]) castle.hero_move_to!('left') assert_equal 'left', castle.current_room end def test_can_give_foe_at_position expected = foe castle = Castle.new([expected, foe, foe]) castle.hero_move_to!('left') assert_equal expected, castle.current_foe end private def foe CharacterBuilder.build(attributes: { hit_points: 50, speed: 50}) end def dead_foe CharacterBuilder.build(attributes: { hit_points: 0, speed: 50}) end end
true
8c6a7a68d21182dd9c9889eb87d26d413e7f9525
Ruby
harrison-blake/black_thursday
/test/invoice_item_repository_test.rb
UTF-8
2,707
2.875
3
[]
no_license
require 'minitest/autorun' require 'minitest/pride' require './lib/invoice_item_repository' require './lib/sales_engine' require './lib/sales_analyst' require './lib/invoice_item' require 'time' require 'bigdecimal' class InvoiceItemRepositoryTest < Minitest::Test def setup merchant_path = './data/merchants.csv' item_path = './data/items.csv' invoice_items_path = './data/invoice_items.csv' customers_path = './data/customers.csv' transactions_path = './data/transactions.csv' invoices_path = './data/invoices.csv' locations = { items: item_path, merchants: merchant_path, invoice_items: invoice_items_path, customers: customers_path, transactions: transactions_path, invoices: invoices_path } @engine = SalesEngine.new(locations) @invoice_item_repo = InvoiceItemRepository.new('./data/mock_invoice_items.csv', @engine) end def test_it_exists_and_has_attributes assert_instance_of InvoiceItemRepository, @invoice_item_repo assert_equal './data/mock_invoice_items.csv', @invoice_item_repo.path assert_instance_of SalesEngine, @invoice_item_repo.engine end def test_it_can_return_all_invoice_items assert_instance_of Array, @invoice_item_repo.all assert_equal 19, @invoice_item_repo.all.length end def test_find_by_id assert_instance_of InvoiceItem, @invoice_item_repo.find_by_id(3) assert_equal 263_451_719, @invoice_item_repo.find_by_id(3).item_id end def test_find_all_by_item_id assert_instance_of Array, @invoice_item_repo.find_all_by_item_id(263_515_158) assert_equal 1, @invoice_item_repo.find_all_by_item_id(263_454_779).count end def test_find_all_by_invoice_id assert_instance_of Array, @invoice_item_repo.find_all_by_invoice_id(1_234_567_890) assert_equal 4, @invoice_item_repo.find_all_by_invoice_id(2).count end def test_create_creates_new_invoice_items attributes = { item_id: 7, invoice_id: 8, quantity: 1, unit_price: BigDecimal(10.99, 4), created_at: Time.now.to_s, updated_at: Time.now.to_s } @invoice_item_repo.create(attributes) assert_instance_of InvoiceItem, @invoice_item_repo.all.last assert_equal 20, @invoice_item_repo.all.length end def test_update_can_update_our_invoice_items attributes = { quantity: 13 } @invoice_item_repo.update(3, attributes) assert_equal 13, @invoice_item_repo.find_by_id(3).quantity end def test_delete_can_delete_invoice_items assert_equal 3, @invoice_item_repo.find_by_id(3).id @invoice_item_repo.delete(3) assert_nil @invoice_item_repo.find_by_id(3) end end
true
d041dc43bd0daf5e0e39517ee1fc70a2276b500f
Ruby
TashaGor/ruby_lessons
/lesson_4/task_1.rb
UTF-8
1,024
3.984375
4
[]
no_license
puts "Введите число для выполнения расчета" num = gets.chomp.to_i #while i = 1 summ_number = 0.0 while i < num do summ_number = summ_number + i i += 1 end puts "Сумма цикла while равна #{summ_number}" puts "Среднее арифметическое равно #{summ_number / num}" #until i = 1 summ_number = 0.0 until i >= num do summ_number = summ_number + i i += 1 end puts "Сумма цикла until равна #{summ_number}" puts "Среднее арифметическое равно #{summ_number / num}" #for summ_number = 0.0 for n in 1...num summ_number = summ_number + n end puts "Сумма цикла for равна #{summ_number}" puts "Среднее арифметическое равно #{summ_number / num}" #each summ_number = 0.0 (1...num).each do |i| summ_number = summ_number + i end puts "Сумма цикла each равна #{summ_number}" puts "Среднее арифметическое равно #{summ_number / num}"
true
2ed5cb844bfa795113ab680d5b6a73f08ceb774e
Ruby
aivakhnenko/ror_blackjack
/main.rb
UTF-8
191
2.515625
3
[]
no_license
require_relative 'interface' class Main def initialize @interface = Interface.new end def start interface.start end private attr_reader :interface end Main.new.start
true
9d20cc2f41f54dcb754a848d57af0780798d5f21
Ruby
ironllama/adventofcode2018
/aoc-03a.rb
UTF-8
1,299
3.171875
3
[]
no_license
# allLineString = %[#1 @ 1,3: 4x4 # #2 @ 3,1: 4x4 # #3 @ 5,5: 2x2 # ] # allLinesArr = allLineString.split("\n") allLinesArr = File.read('aoc-03.in').split("\n") # p allLinesArr oneDimension = 1000 # wholeFabric = Array.new(oneDimension, Array.new(oneDimension, 0)); # Every inner array is a reference to the same array. Ugh wholeFabric = Array.new(oneDimension) { Array.new(oneDimension, 0) } # wholeFabric.each { |thisArr| p thisArr.object_id } # Check to be sure we're not just using the same empty array everywhere. overlap = 0 allLinesArr.each do |thisLine| allTokens = thisLine.split(" ") startPointArr = allTokens[2].chomp(":").split(",").map!(&:to_i) lengthsArr = allTokens[3].split("x").map!(&:to_i) (startPointArr[0]..(startPointArr[0] + lengthsArr[0] - 1)).each.with_index do |value_x, idx_x| (startPointArr[1]..(startPointArr[1] + lengthsArr[1] - 1)).each_with_index do |value_y, idx_y| # p "X: #{value_x} Y: #{value_y} CURR: #{wholeFabric[value_x][value_y]}" wholeFabric[value_x][value_y] += 1 overlap += 1 if wholeFabric[value_x][value_y] == 2 end end # wholeFabric.each { |thisArr| p thisArr.join } # Checking progress end # wholeFabric.each { |thisArr| p thisArr.join } puts "OVERLAP: #{overlap}"
true
9dc616e3e85dac2e02b2e5da17c13b07cc68046c
Ruby
lukaswet/My-Ruby-first-steps
/bak/1/app1/app5.rb
UTF-8
130
3.28125
3
[]
no_license
print "Enter your name: " name = gets puts "Hello, " + name puts "" print "Enter your age: " age = gets puts "Your age is " + age
true
d2a6e51b27cd9707f0ea0c9cbd7f74888071ac8a
Ruby
night1ightning/ruby_course
/listen4/cli/routes/route/route_station_add.rb
UTF-8
1,233
3.015625
3
[]
no_license
class Cli::RouteStationAdd < Cli::BaseCommands def info super 'Добавить станцию в маршрут' end protected attr_reader :route, :available_stations def params_valid? self.route = keeper.get_current_object stations = keeper.get_collection_by_type(:station) self.available_stations = stations - route.stations if available_stations.empty? info_message "\nНужно добавить станции" return false end true end def command Cli::StationList.new.show_table(route.stations, 'Станции маршрута') Cli::StationList.new.show_table(available_stations, 'Список не привязанных станций') print "\n№ непривязанной станции: " id = gets.to_i save(id) if valid?(id) end private attr_writer :route, :available_stations def valid?(id) if available_stations[id] return true end error_message "\n№ не верен" false end def save(id) station = available_stations[id] route.take_point_station(station) result_message "В маршрут \"#{route}\" добавлена станция \"#{station}\"\n" end end
true
21b436302b63cebe612050615e83ccab5196e928
Ruby
jai-singhal/djangopy
/vendor/bundle/ruby/2.3.0/gems/rmagick-2.16.0/doc/ex/cbezier6.rb
UTF-8
1,264
2.65625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license" ]
permissive
#!/usr/bin/env ruby -w require 'rmagick' imgl = Magick::ImageList.new imgl.new_image(400, 300, Magick::HatchFill.new('white','lightcyan2')) gc = Magick::Draw.new # Draw Bezier curve gc.stroke('red') gc.stroke_width(2) gc.fill_opacity(0) gc.bezier(50,150, 50,50, 200,50, 200,150, 200,250, 350,250, 350,150) # Draw filled circles for the control points gc.fill('gray50') gc.stroke('gray50') gc.fill_opacity(1) gc.circle(50,50, 53,53) gc.circle(200,50, 203,53) gc.circle(200,250, 203,253) gc.circle(350,250, 353,253) # Draw circles on the points the curve passes through gc.fill_opacity(0) gc.circle(50,150, 53,153) gc.circle(200,150, 203,153) gc.circle(350,150, 353,153) # Draw the gray lines between points and control points gc.line(50,50, 50,150) gc.line(200,50, 200,250) gc.line(350,150, 350,250) # Annotate gc.font_weight(Magick::NormalWeight) gc.font_style(Magick::NormalStyle) gc.fill('black') gc.stroke('transparent') gc.text(30,170, "'50,150'") gc.text(30, 40, "'50,50'") gc.text(180,40, "'200,50'") gc.text(210,155,"'200,150'") gc.text(180,270,"'200,250'") gc.text(330,270,"'350,250'") gc.text(330,140,"'350,150'") gc.draw(imgl) imgl.border!(1,1, 'lightcyan2') imgl.write('cbezier6.gif') exit
true
939289b198c16eedc3ef151d7f39d1fd92b744e0
Ruby
aaaronlopez/hairsalonpro
/app/models/appointment.rb
UTF-8
2,983
2.625
3
[]
no_license
require 'google_calendar' class Appointment < ApplicationRecord include GoogleCalendar belongs_to :customer validates :start_time, presence: true validates :end_time, presence: true validate :start_cannot_be_greater_than_end, :time_cannot_be_in_the_past, :appointments_cannot_be_greater_than_limit #validate :appointment_during_working_hours validate :appointment_cannot_overlap @@REMINDER_TIME = 30.minutes @@open_times = [nil, [8, 18], [8, 18], [8, 18], [8, 18], [8, 18]] @@open_days = [false, true, true, true, true, true, false] @@appt_minute_limit = 90 @@open_hour = 8 @@close_hour = 16 def start_cannot_be_greater_than_end if start_time >= end_time errors.add(:start_time, "must be before end") end end def time_cannot_be_in_the_past if start_time < Time.now errors.add(:start_time, "can't be in the past") end if end_time < Time.now errors.add(:end_time, "can't be in the past") end end def appointment_during_working_hours if not @@open_days[start_time.wday] errors.add(:start_time, "must be on an open day") elsif start_time.hour < @@open_times[start_time.wday][0] or start_time.hour > @@open_times[start_time.wday][1] errors.add(:start_time, "must be during working hours") elsif end_time.hour < @@open_times[start_time.wday][0] or end_time.hour > @@open_times[start_time.wday][1] errors.add(:end_time, "must be during working hours") else end end def appointments_cannot_be_greater_than_limit if ((end_time - start_time) / 60) > @@appt_minute_limit errors.add(:start_time, " and end time difference must be less than or equal to #{@appt_minute_limit} minutes.") end end def appointment_cannot_overlap # TODO: Change variables to global constants. day_start = Time.new(start_time.year, start_time.month, start_time.day, 8, 0, 0).iso8601 day_end = Time.new(start_time.year, start_time.month, start_time.day, 16, 0, 0).iso8601 events_by_day = list_events_by_time(day_start, day_end) events_by_day.each do |event| a = event[0].utc + Time.zone_offset('PST') b = event[1].utc + Time.zone_offset('PST') if end_time >= a and start_time <= b errors.add(:start_time, " and end time interfere with current schedule.") end end end def reminder client = Twilio::REST::Client.new Rails.application.secrets.twilio_account_sid, Rails.application.secrets.twilio_auth_token time_str = ((self.time).localtime).strftime("%I:%M%p on %b. %d, %Y") reminder = "Hi #{self.customer.name}. Just a reminder that you have an appointment coming up at #{time_str}." message = @client.account.messages.create( :from => TWILIO_NUMBER, :to => self.customer.phone_number, :body => reminder, ) puts message.to end def when_to_run time - @@REMINDER_TIME end # handle_asynchronously :reminder, :run_at => Proc.new { |i| i.when_to_run } end
true
2ab40627be6b61ffc29015ed28696adaea0dcd4a
Ruby
jojo89/tic_tac_toe
/spec/lib/layout_analyzer_spec.rb
UTF-8
2,543
2.890625
3
[]
no_license
require 'spec_helper.rb' RSpec.shared_examples "completed_board" do before do allow(subject).to receive(:layout).and_return(layout) end context "with a turn that doesn't win the game " do it "returns nil" do expect(subject.three_in_a_row?(1, 2)).to eq(false) end end context "with a turn that wins the game " do it "it returns true" do expect(subject.three_in_a_row?(1, 1)).to eq(true) end end end describe LayoutAnalyzer do subject { described_class.new(3) } let(:ex) { cell = Cell.new; cell.mark("|x|") ; cell} let(:oh) { cell = Cell.new; cell.mark("|o|") ; cell} before do allow(subject).to receive(:layout).and_return(layout) end describe "#create_turn?" do context "when the opposing team has a potential win" do let(:layout) { [ [Cell.new, Cell.new, oh], [Cell.new, Cell.new, ex], [oh , ex, ex], ] } it "returns a blocking turn" do expect(subject.create_turn("x").row).to eq(1) expect(subject.create_turn("x").column).to eq(1) end end context "when team has a potential win" do let(:layout) { [ [oh, Cell.new, Cell.new], [Cell.new, ex, ex], [oh , Cell.new, ex], ] } it "returns a winning turn" do expect(subject.create_turn("x").row).to eq(0) expect(subject.create_turn("x").column).to eq(2) end end end describe "#board_completed?" do context "diagnol forward" do let(:layout) { [ [Cell.new, Cell.new, oh], [Cell.new, oh, ex], [oh , ex, ex], ] } it_behaves_like "completed_board" end context "diagnol backword" do let(:layout) { [ [oh, Cell.new, ex], [Cell.new, oh, ex], [ex , ex, oh], ] } it_behaves_like "completed_board" end context "vertical" do let(:layout) { [ [oh, oh, ex ], [Cell.new, oh, ex ], [ex , oh, Cell.new], ] } it_behaves_like "completed_board" end context "horizontal" do let(:turn) { Turn.new(0, 2, "o") } let(:layout) { [ [oh, oh, oh ], [Cell.new, oh, ex ], [ex , oh, Cell.new], ] } it_behaves_like "completed_board" end end end
true
33ccf411410a70e18a512ae1a5fcfbd490cc728f
Ruby
abhaved/alarm-clock
/application_controller.rb
UTF-8
383
2.546875
3
[]
no_license
require 'bundler' require_relative 'models/riddle.rb' Bundler.require class MyApp < Sinatra::Base get '/' do $question = riddle erb :index end post '/results' do riddle = params[:riddle] @answer = params[:answer] if answer_method(@answer, riddle) == true erb :results else $question = riddle erb :wrong end end end
true
ba0bf8ec5166bfff6114aba2af29fee4ca21289e
Ruby
JunKikuchi/ht2p
/lib/ht2p/client/response.rb
UTF-8
1,436
2.75
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
class HT2P::Client::Response extend Forwardable def_delegators :@header, :[], :[]= attr_reader :code, :header alias :headers :header HAS_BODY = [:get, :post, :put, :delete, :trace] def initialize(client) @client, @code, @header = client, *HT2P::Header.load(client) @body = if HAS_BODY.include? @client.request.method.to_s.downcase.to_sym if @header['transfer-encoding'].to_s.downcase == 'chunked' Chunked.new @client else Transfer.new @client, @header['content-length'].to_i end else Empty.new end end def receive(&block) if block_given? block.call self else read end end def read(length=nil) @body.read length end class Transfer def initialize(client, size) @client, @size = client, size end def read(length=nil) if @size.nil? @client.read length elsif @size > 0 length ||= @size length = @size if @size < length @size -= length @client.read length else nil end end end class Chunked < Transfer def initialize(client) super client, nil parse_size end def read(length=nil) parse_size if @size <= 0 super length end def parse_size @size = @client.gets.chop!.hex end private :parse_size end class Empty def read(length=nil) nil end end end
true
f5662e51f859679f2b1aeff45bb674b496679ca8
Ruby
xfbs/euler
/src/050-consecutive-prime-sum/ruby/src/solver.rb
UTF-8
692
3.640625
4
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'euler/prime' module Solver # find the prime smaller than max that is the sum of the most consecutive # primes. def self.solve(max) primes = Euler::Prime.new # find the maximum amount of consecutive primes that you can add up to be # smaller than max, and their sum. max_len = 0 sum_pre = 0 primes.each do |p| break if (p + sum_pre) > max max_len += 1 sum_pre += p end max_len.downto(2).each do |len| sum = sum_pre sum_pre -= primes.nth(len - 1) (len..max_len).each do |i| return sum if primes.check? sum sum -= primes.nth(i - len) sum += primes.nth(i) end end end end
true
1d857beb0fdad255143c1740385805a35954994b
Ruby
jkalu1/todo-ruby-basics-dc-web-051319
/lib/ruby_basics.rb
UTF-8
263
2.765625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def division(num1, num2) sum = num1/num2 end def assign_variable(value) puts (value) end def argue end def greeting (greeting, name) greeting + "" + name end def return_a_value end def last_evaluated_value end def pizza_party"cheese" puts () end
true
674e32af1ce2dffc0c64ad2e39c6f3bc88553792
Ruby
astro/remcached
/lib/remcached/packet.rb
UTF-8
8,190
2.875
3
[ "Apache-2.0" ]
permissive
require 'remcached/pack_array' module Memcached class Packet ## # Initialize with fields def initialize(contents={}) @contents = contents (self.class.fields + self.class.extras).each do |name,fmt,default| self[name] ||= default if default end end ## # Get field def [](field) @contents[field] end ## # Set field def []=(field, value) @contents[field] = value end ## # Define a field for subclasses def self.field(name, packed, default=nil) instance_eval do @fields ||= [] @fields << [name, packed, default] end end ## # Fields of parent and this class def self.fields parent_class = ancestors[1] parent_fields = parent_class.respond_to?(:fields) ? parent_class.fields : [] class_fields = instance_eval { @fields || [] } parent_fields + class_fields end ## # Define an extra for subclasses def self.extra(name, packed, default=nil) instance_eval do @extras ||= [] @extras << [name, packed, default] end end ## # Extras of this class def self.extras parent_class = ancestors[1] parent_extras = parent_class.respond_to?(:extras) ? parent_class.extras : [] class_extras = instance_eval { @extras || [] } parent_extras + class_extras end ## # Build a packet by parsing header fields def self.parse_header(buf) pack_fmt = fields.collect { |name,fmt,default| fmt }.join values = PackArray.unpack(buf, pack_fmt) contents = {} fields.each do |name,fmt,default| contents[name] = values.shift end new contents end ## # Parse body of packet when the +:total_body_length+ field is # known by header. Pass it at least +total_body_length+ bytes. # # return:: [String] remaining bytes def parse_body(buf) if self[:total_body_length] < 1 buf, rest = "", buf else buf, rest = buf[0..(self[:total_body_length] - 1)], buf[self[:total_body_length]..-1] end if self[:extras_length] > 0 self[:extras] = parse_extras(buf[0..(self[:extras_length]-1)]) else self[:extras] = parse_extras("") end if self[:key_length] > 0 self[:key] = buf[self[:extras_length]..(self[:extras_length]+self[:key_length]-1)] else self[:key] = "" end self[:value] = buf[(self[:extras_length]+self[:key_length])..-1] rest end ## # Serialize for wire def to_s extras_s = extras_to_s key_s = self[:key].to_s value_s = self[:value].to_s self[:extras_length] = extras_s.length self[:key_length] = key_s.length self[:total_body_length] = extras_s.length + key_s.length + value_s.length header_to_s + extras_s + key_s + value_s end protected def parse_extras(buf) pack_fmt = self.class.extras.collect { |name,fmt,default| fmt }.join values = PackArray.unpack(buf, pack_fmt) self.class.extras.each do |name,fmt,default| @self[name] = values.shift || default end end def header_to_s pack_fmt = '' values = [] self.class.fields.each do |name,fmt,default| values << self[name] pack_fmt += fmt end PackArray.pack(values, pack_fmt) end def extras_to_s values = [] pack_fmt = '' self.class.extras.each do |name,fmt,default| values << self[name] || default pack_fmt += fmt end PackArray.pack(values, pack_fmt) end end ## # Request header: # # Byte/ 0 | 1 | 2 | 3 | # / | | | | # |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7| # +---------------+---------------+---------------+---------------+ # 0| Magic | Opcode | Key length | # +---------------+---------------+---------------+---------------+ # 4| Extras length | Data type | Reserved | # +---------------+---------------+---------------+---------------+ # 8| Total body length | # +---------------+---------------+---------------+---------------+ # 12| Opaque | # +---------------+---------------+---------------+---------------+ # 16| CAS | # | | # +---------------+---------------+---------------+---------------+ # Total 24 bytes class Request < Packet field :magic, 'C', 0x80 field :opcode, 'C', 0 field :key_length, 'n' field :extras_length, 'C' field :data_type, 'C', 0 field :reserved, 'n', 0 field :total_body_length, 'N' field :opaque, 'N', 0 field :cas, 'Q', 0 def self.parse_header(buf) me = super me[:magic] == 0x80 ? me : nil end class Get < Request def initialize(contents) super({:opcode=>Commands::GET}.merge(contents)) end class Quiet < Get def initialize(contents) super({:opcode=>Commands::GETQ}.merge(contents)) end end end class Add < Request extra :flags, 'N', 0 extra :expiration, 'N', 0 def initialize(contents) super({:opcode=>Commands::ADD}.merge(contents)) end class Quiet < Add def initialize(contents) super({:opcode=>Commands::ADDQ}.merge(contents)) end end end class Set < Request extra :flags, 'N', 0 extra :expiration, 'N', 0 def initialize(contents) super({:opcode=>Commands::SET}.merge(contents)) end class Quiet < Set def initialize(contents) super({:opcode=>Commands::SETQ}.merge(contents)) end end end class Delete < Request def initialize(contents) super({:opcode=>Commands::DELETE}.merge(contents)) end class Quiet < Delete def initialize(contents) super({:opcode=>Commands::DELETEQ}.merge(contents)) end end end class Stats < Request def initialize(contents) super({:opcode=>Commands::STAT}.merge(contents)) end end class NoOp < Request def initialize super(:opcode=>Commands::NOOP) end end end ## # Response header: # # Byte/ 0 | 1 | 2 | 3 | # / | | | | # |0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7| # +---------------+---------------+---------------+---------------+ # 0| Magic | Opcode | Key Length | # +---------------+---------------+---------------+---------------+ # 4| Extras length | Data type | Status | # +---------------+---------------+---------------+---------------+ # 8| Total body length | # +---------------+---------------+---------------+---------------+ # 12| Opaque | # +---------------+---------------+---------------+---------------+ # 16| CAS | # | | # +---------------+---------------+---------------+---------------+ # Total 24 bytes class Response < Packet field :magic, 'C', 0x81 field :opcode, 'C', 0 field :key_length, 'n' field :extras_length, 'C' field :data_type, 'C', 0 field :status, 'n', Errors::NO_ERROR field :total_body_length, 'N' field :opaque, 'N', 0 field :cas, 'Q', 0 def self.parse_header(buf) me = super me[:magic] == 0x81 ? me : nil end end end
true
6e57298199ec18996f3484be671c417b5b3de22d
Ruby
ndelforno/object_oriented_programming-sept-10th
/exercise1.rb
UTF-8
336
3.203125
3
[]
no_license
class BankAccount def initialize(balance,interest_rate) @balance = balance @interest_rate = interest_rate end def deposit(ammount) @balance = @balance + ammount end def withdraw(ammount) @balance = @balance - ammount end def gain_interest @balance = @balance + (@balance * @interest_rate) end end
true
7db7524f00b31a221c4962bbff8e4f8a289ce784
Ruby
DavidHuie/corleone
/lib/corleone/server.rb
UTF-8
1,566
2.5625
3
[ "MIT" ]
permissive
class Corleone::Server def initialize(emitter, collector, uri) @emitter = emitter @collector = collector @uri = uri @runner_args = @emitter.runner_args @registry = Corleone::Registry.new end def logger Corleone.logger end def log(type, message) logger.send(type, message) return end def check_in(name) logger.debug("worker checking in: #{name}") @registry.check_in(name) end def check_out(name) logger.debug("worker checking out: #{name}") @registry.remove(name) end def get_runner_args if @runner_args logger.debug("emitting runner args message: #{@runner_args.payload}") end @runner_args end def get_item return Corleone::Message::ZeroItems.new if @emitter.empty? message = @emitter.pop logger.debug("emitting item message: #{message.payload}") message end def return_result(result) if result.instance_of?(Corleone::Message::Result) logger.debug("result message received: #{result.payload}") @collector.process_result(result.payload) return end raise "result error: #{result}" end def finished? @emitter.empty? && @registry.finished? end def kill @thread.kill end def alive? kill if finished? value = @thread.alive? value end def start logger.info("starting server") DRb.start_service(@uri, self) @thread = DRb.thread end def summarize @collector.summarize end def ping; end def wait loop { alive? ? Kernel.sleep(0.1) : break } end end
true
a6f66829b7d498ffd61cc74a7405454fe5ba9fdc
Ruby
rsupak/tc-challenges
/UnSpecdFiles/fold_array/lib/fold_array.rb
UTF-8
525
4.1875
4
[]
no_license
# In this challenge you have to write a method that folds a given array # of integers by the middle x-times. For example when [1,2,3,4,5] is folded # 1 times, it gives [6,6,3] and when folded two times it gives [9,6]. def fold_array(array, folds) return array if folds.zero? new_array = [] new_array << array.shift + array.pop until array.length <= 1 new_array << array.pop if array.length == 1 fold_array(new_array, folds - 1) end if $PROGRAM_NAME == __FILE__ arr = [1, 2, 3, 4, 5] p fold_array(arr, 3) end
true
4c403487bc54e56cfac7f52612f3140d660a85ab
Ruby
Schmitze333/odin-testfirst-ruby
/04_pig_latin/pig_latin.rb
UTF-8
606
3.8125
4
[]
no_license
def change_word(word) vowels = %w(a e i o u) two_letter_beginnings = %w(ch qu th br) three_letter_beginnings = %w(thr sch squ) if vowels.include? word[0] word + "ay" elsif index = three_letter_beginnings.index(word[0...3]) word[3..-1] + three_letter_beginnings[index] + "ay" elsif index = two_letter_beginnings.index(word[0...2]) word[2..-1] + two_letter_beginnings[index] + "ay" else # word starts with 1 consonant word[1..-1] + word[0] + "ay" end end def translate(string) words = string.split pig_words = words.map { |w| change_word(w) } pig_words.join(' ') end
true
2ce7925ba6b720f337f468957255d3d44c2fd16b
Ruby
rarvear/E7CP1A1
/Ej2.rb
UTF-8
257
2.671875
3
[]
no_license
productos = { 'bebida' => 850, 'chocolate' => 1200, 'galletas' => 900, 'leche' => 750 } productos.each { |producto, _or_valor| puts producto } productos['cereal'] = 2200 productos['bebida'] = 2000 prod = productos.to_a productos.delete('galletas')
true
37bac381214e2956dc824743dff13bf8828125b4
Ruby
jtsang586/SDET10
/rspec/calc/spec/calc.rb
UTF-8
192
3.21875
3
[]
no_license
class Calculator def add(num1,num2) num1 + num2 end def minus(num1,num2) num1 - num2 end def divide(num1,num2) num1 / num2 end def multiply(num1,num2) num1 * num2 end end
true
d123353fe5688326135c4f83ec138ad3e6a1c936
Ruby
tehAnswer/RoR
/Agile Web Development/depot/app/helpers/application_helper.rb
UTF-8
1,148
2.609375
3
[]
no_license
module ApplicationHelper def notice_color(notice) if notice type = type_notice(notice) message = message_notice(type, notice) div_tag_head = "<div class=\"alert alert-#{type} alert-dismissable\">" cross_button = "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">&times;</button>" notice_tag = div_tag_head + cross_button + message + "</div>" notice_tag.to_s.html_safe end end def type_notice(notice) downcased = notice.downcase if downcased.include? 'error' or downcased.include? 'invalid' or downcased.include? 'no' return 'danger' elsif downcased == t('thanks').downcase or downcased.include? 'success' return 'success' elsif downcased.include? 'hey' return 'warning' else return 'info' end end def message_notice(type, notice) messages = { :danger => t('danger_header'), :success => t('success_header'), :warning => t('warning_header'), :info => t('info_header') } "<strong>#{messages[type.to_sym]}!</strong> #{notice}" end private :type_notice, :message_notice end
true
0c3a3ba9bd663532883d3ef58a4fa2f32b10f615
Ruby
funkomatic/ns-ramaze-ext
/tests/ramaze/helper/banana_form.rb
UTF-8
26,498
2.6875
3
[]
no_license
############################################################################### ## File branched from Ramaze::Helper::BlueForm spec tests and updated for ## BananaForm features. ## Use it from the gem root by issuing the rake tests command ############################################################################### require 'lib/ext/ramaze/helper/banana_form.rb' require 'tempfile' require 'bacon' Bacon.summary_at_exit describe BF = Ramaze::Helper::BananaForm do extend BF ## Inherited from a very strange comparision from BlueForm def assert(expected, output) left = expected.to_s.gsub(/\s+/, ' ').gsub(/>\s+</, '><').strip right = output.to_s.gsub(/\s+/, ' ').gsub(/>\s+</, '><').strip nodiff = left.scan(/./).sort == right.scan(/./).sort unless ( nodiff ) puts "\nERROR in comparaison\n" puts "EXPECTED : #{left}" puts "RETURNED : #{right}" end nodiff.should == true end #################################################################### ## Basic form specs #################################################################### it 'makes form with method' do out = form(:method => :post) assert(<<-FORM, out) <form method="post"></form> FORM end it 'makes form with method and action' do out = form(:method => :post, :action => '/') assert(<<-FORM, out) <form method="post" action="/"></form> FORM end it 'makes form with method, action, and name' do out = form(:method => :post, :action => '/', :name => :spec) assert(<<-FORM, out) <form method="post" action="/" name="spec"> </form> FORM end it 'makes form with class and id' do out = form(:class => :foo, :id => :bar) assert(<<-FORM, out) <form class="foo" id="bar"> </form> FORM end it 'makes form with legend' do out = form(:method => :get){|f| f.legend('The Form') } assert(<<-FORM, out) <form method="get"> <fieldset> <legend>The Form</legend> </fieldset> </form> FORM end #################################################################### ## input_text specs #################################################################### it 'makes form with input_text(label, name, value)' do out = form(:method => :get){|f| f.input_text 'Username', :username, 'mrfoo' } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-username" class="text_label">Username</label> <input type="text" name="username" class="text_input" id="form-username" value="mrfoo" /> </p> </fieldset> </form> FORM end it 'makes form with input_text(label, name, value) and no errors in encart' do out = form(:method => :get ){|f| f.input_text 'Username', :username, 'mrfoo' } #puts "\nGENERATED:\n#{out}" assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-username" class="text_label">Username</label> <input type="text" name="username" class="text_input" id="form-username" value="mrfoo" /> </p> </fieldset> </form> FORM end it 'makes form with input_text(label, name)' do out = form(:method => :get){|f| f.input_text 'Username', :username } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-username" class="text_label">Username</label> <input type="text" name="username" class="text_input" id="form-username" /> </p> </fieldset> </form> FORM end it 'makes form with input_text(label, name, value, hash)' do out = form(:method => :get){|f| f.input_text 'Username', :username, nil, :size => 10 } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-username" class="text_label">Username</label> <input size="10" type="text" name="username" class="text_input" id="form-username" /> </p> </fieldset> </form> FORM end it 'makes form with input_text(label, name, value, hash) specifiying class' do out = form(:method => :get){|f| f.input_text 'Username', :username, nil, :size => 10, :class=>'funky' } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-username" class="text_label">Username</label> <input size="10" type="text" name="username" class="funky" id="form-username" /> </p> </fieldset> </form> FORM end it 'makes form with input_text(label, name, value, hash) specifiying class for input and label' do out = form(:method => :get){|f| f.input_text 'Username', :username, nil, :size => 10, :class=>'funky' , :class_label=>"echofunky" } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label class="echofunky" for="form-username">Username</label> <input type="text" class="funky" size="10" name="username" id="form-username" /> </p> </fieldset> </form> FORM end #################################################################### ## input_password specs #################################################################### it 'makes form with input_password(label, name)' do out = form(:method => :get){|f| f.input_password 'Password', :password } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-password" class="text_label">Password</label> <input type="password" name="password" class="text_input" id="form-password" /> </p> </fieldset> </form> FORM end it 'makes form with input_password(label, name, hash) setting class' do out = form(:method => :get){|f| f.input_password 'Password', :password, :class=>'funky' } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-password" class="text_label">Password</label> <input type="password" name="password" class="funky" id="form-password" /> </p> </fieldset> </form> FORM end it 'makes form with input_password(label, name, hash) setting class for input and label' do out = form(:method => :get){|f| f.input_password 'Password', :password, :class=>'funky' , :class_label => 'echofunky' } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-password" class="echofunky">Password</label> <input type="password" name="password" class="funky" id="form-password" /> </p> </fieldset> </form> FORM end #################################################################### ## input_submit specs #################################################################### it 'makes form with input_submit()' do out = form(:method => :get){|f| f.input_submit } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <input type="submit" class="button_submit" /> </p> </fieldset> </form> FORM end it 'makes form with input_submit(value)' do out = form(:method => :get){|f| f.input_submit 'Send' } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <input type="submit" class="button_submit" value="Send" /> </p> </fieldset> </form> FORM end it 'makes form with input_submit(value, hash)' do out = form(:method => :get){|f| f.input_submit 'Send', :class=>'funky' } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <input type="submit" class="funky" value="Send" /> </p> </fieldset> </form> FORM end #################################################################### ## input_checkbox specs #################################################################### it 'makes form with input_checkbox(label, name)' do out = form(:method => :get){|f| f.input_checkbox 'Assigned', :assigned } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-assigned" class="checkbox_label">Assigned</label> <input type="checkbox" name="assigned" class="checkbox_input" id="form-assigned" /> </p> </fieldset> </form> FORM end it 'makes form with input_checkbox(label, name, nil, hash) setting class' do out = form(:method => :get){|f| f.input_checkbox 'Assigned', :assigned, nil, :class=>'funky' } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-assigned" class="checkbox_label">Assigned</label> <input type="checkbox" name="assigned" class="funky" id="form-assigned" /> </p> </fieldset> </form> FORM end it 'makes form with input_checkbox(label, name, nil, hash) setting class for input and label' do out = form(:method => :get){|f| f.input_checkbox 'Assigned', :assigned, nil, :class=>'funky', :class_label => 'echofunky' } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-assigned" class="echofunky">Assigned</label> <input type="checkbox" name="assigned" class="funky" id="form-assigned" /> </p> </fieldset> </form> FORM end it 'makes form with input_checkbox(label, name, checked = false)' do out = form(:method => :get){|f| f.input_checkbox 'Assigned', :assigned, false } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-assigned" class="checkbox_label">Assigned</label> <input type="checkbox" name="assigned" class="checkbox_input" id="form-assigned" /> </p> </fieldset> </form> FORM end it 'makes form with input_checkbox(label, name, checked = false, hash)' do out = form(:method => :get){|f| f.input_checkbox 'Assigned', :assigned, false, :class=>'funky' } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-assigned" class="checkbox_label">Assigned</label> <input type="checkbox" name="assigned" class="funky" id="form-assigned" /> </p> </fieldset> </form> FORM end it 'makes form with input_checkbox(label, name, checked = true)' do out = form(:method => :get){|f| f.input_checkbox 'Assigned', :assigned, true } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-assigned" class="checkbox_label">Assigned</label> <input type="checkbox" name="assigned" class="checkbox_input" id="form-assigned" checked="checked" /> </p> </fieldset> </form> FORM end it 'makes form with input_checkbox(label, name, checked = true, hash)' do out = form(:method => :get){|f| f.input_checkbox 'Assigned', :assigned, true, :class=>'funky' } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label class="checkbox_label" for="form-assigned">Assigned</label> <input checked="checked" type="checkbox" class="funky" name="assigned" id="form-assigned" /> </p> </fieldset> </form> FORM end it 'makes form with input_checkbox(label, name, checked = nil)' do out = form(:method => :get){|f| f.input_checkbox 'Assigned', :assigned, nil } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-assigned" class="checkbox_label">Assigned</label> <input type="checkbox" name="assigned" class="checkbox_input" id="form-assigned" /> </p> </fieldset> </form> FORM end #################################################################### ## textarea specs #################################################################### it 'makes form with textarea(label, name)' do out = form(:method => :get){|f| f.textarea 'Message', :message } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-message" class="area_label">Message</label> <textarea name="message" id="form-message" class="area_input"></textarea> </p> </fieldset> </form> FORM end it 'makes form with textarea(label, name, value)' do out = form(:method => :get){|f| f.textarea 'Message', :message, 'stuff' } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-message" class="area_label">Message</label> <textarea name="message" id="form-message" class="area_input">stuff</textarea> </p> </fieldset> </form> FORM end it 'makes form with textarea(label, name, value, hash) setting class' do out = form(:method => :get){|f| f.textarea 'Message', :message, 'stuff', :class=>'funky' } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-message" class="area_label">Message</label> <textarea class="funky" name="message" id="form-message">stuff</textarea> </p> </fieldset> </form> FORM end it 'makes form with textarea(label, name, value, hash) setting class for input and label' do out = form(:method => :get){|f| f.textarea 'Message', :message, 'stuff', :class=>'funky', :class_label => 'echofunky' } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-message" class="echofunky">Message</label> <textarea class="funky" name="message" id="form-message">stuff</textarea> </p> </fieldset> </form> FORM end #################################################################### ## input_file specs #################################################################### it 'makes form with input_file(label, name)' do out = form(:method => :get){|f| f.input_file 'Avatar', :avatar } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-avatar" class="file_label">Avatar</label> <input type="file" name="avatar" class="file_input" id="form-avatar" /> </p> </fieldset> </form> FORM end it 'makes form with input_file(label, name, hash) setting class' do out = form(:method => :get){|f| f.input_file 'Avatar', :avatar, :class=>'funky' } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-avatar" class="file_label">Avatar</label> <input type="file" name="avatar" class="funky" id="form-avatar" /> </p> </fieldset> </form> FORM end it 'makes form with input_file(label, name, hash) setting class for field and label' do out = form(:method => :get){|f| f.input_file 'Avatar', :avatar, :class=>'funky', :class_label => 'echofunky' } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-avatar" class="echofunky">Avatar</label> <input type="file" name="avatar" class="funky" id="form-avatar" /> </p> </fieldset> </form> FORM end #################################################################### ## input_hidden specs #################################################################### it 'makes form with input_hidden(name)' do out = form(:method => :get){|f| f.input_hidden :post_id } assert(<<-FORM, out) <form method="get"> <fieldset> <input type="hidden" name="post_id" /> </fieldset> </form> FORM end it 'makes form with input_hidden(name, value)' do out = form(:method => :get){|f| f.input_hidden :post_id, 15 } assert(<<-FORM, out) <form method="get"> <fieldset> <input type="hidden" name="post_id" value="15" /> </fieldset> </form> FORM end #################################################################### ## select specs #################################################################### servers_hash = { :webrick => 'WEBrick', :mongrel => 'Mongrel', :thin => 'Thin', } it 'makes form with select(label, name, values) from hash' do out = form(:method => :get){|f| f.select 'Server', :server, servers_hash } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-server" class="select_label">Server</label> <select id="form-server" size="1" name="server"> <option class="select_input" value="webrick">WEBrick</option> <option class="select_input" value="mongrel">Mongrel</option> <option class="select_input" value="thin">Thin</option> </select> </p> </fieldset> </form> FORM end it 'makes form with select(label, name, values) with selection from hash' do out = form(:method => :get){|f| f.select 'Server', :server, servers_hash, :selected => :mongrel } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-server" class="select_label">Server</label> <select id="form-server" size="1" name="server"> <option class="select_input" value="webrick">WEBrick</option> <option class="select_input" value="mongrel" selected="selected">Mongrel</option> <option class="select_input" value="thin">Thin</option> </select> </p> </fieldset> </form> FORM end servers_array = %w[ WEBrick Mongrel Thin] it 'makes form with select(label, name, values) from array' do out = form(:method => :get){|f| f.select 'Server', :server, servers_array } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-server" class="select_label">Server</label> <select id="form-server" size="1" name="server"> <option class="select_input" value="WEBrick">WEBrick</option> <option class="select_input" value="Mongrel">Mongrel</option> <option class="select_input" value="Thin">Thin</option> </select> </p> </fieldset> </form> FORM end it 'makes form with select(label, name, values) with selection from array' do out = form(:method => :get){|f| f.select 'Server', :server, servers_array, :selected => 'Mongrel' } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-server" class="select_label">Server</label> <select id="form-server" size="1" name="server"> <option class="select_input" value="WEBrick">WEBrick</option> <option class="select_input" value="Mongrel" selected="selected">Mongrel</option> <option class="select_input" value="Thin">Thin</option> </select> </p> </fieldset> </form> FORM end it 'makes form with select(label, name, values) with selection from array and styling' do out = form(:method => :get){|f| f.select 'Server', :server, servers_array, :selected => 'Mongrel' , :class=>'funky' , :class_label=>'echofunky' } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label for="form-server" class="echofunky">Server</label> <select id="form-server" size="1" name="server"> <option class="funky" value="WEBrick">WEBrick</option> <option class="funky" value="Mongrel" selected="selected">Mongrel</option> <option class="funky" value="Thin">Thin</option> </select> </p> </fieldset> </form> FORM end #################################################################### ## radio specs #################################################################### it 'makes form with radio(label, name, values) with selection from array' do out = form(:method => :get){|f| f.radio 'Server', :server, servers_array, :checked => 'Mongrel' } assert(<<-FORM, out) <form method="get"> <fieldset> <p> <label class="radio_label" for="form-server-0"><input type="radio" class="radio_input" value="WEBrick" id="form-server-0" name="server" />WEBrick</label> <label class="radio_label" for="form-server-1"><input type="radio" class="radio_input" value="Mongrel" id="form-server-1" name="server" checked="checked" />Mongrel</label> <label class="radio_label" for="form-server-2"><input type="radio" class="radio_input" value="Thin" id="form-server-2" name="server" />Thin</label> </p> </fieldset> </form> FORM end #################################################################### ## Error Handling : most of the BananaForm features are tested here #################################################################### ## ## Create a form containing text input fields, ## that will display the error summary ## and change the class of labels and fields to default values ## it 'creates form with error summary, default styling' do form_error :username, 'invalid username' out = form(:method => :get){|f| f.input_text 'Username', :username } assert(<<-FORM, out) <form method="get"> <div class="form_error_summary" id="form_error_summary"> <h2>1 error(s) prohibited this form from being saved</h2> <p>Following fields reported errors:</p> <ul> <li>username : invalid username</li> </ul> </div> <fieldset> <p> <label class="text_label_error" for="form-username">Username</label> <input type="text" class="text_input_error" name="username" id="form-username" /> </p> </fieldset> </form> FORM end ## Same as previous using radio buttons fields it 'creates form with radio(label, name, values) with selection and error summary' do form_error :server, 'invalid server' out = form(:method => :get ){|f| f.radio 'Server', :server, servers_array, :checked => 'Mongrel' } assert(<<-FORM, out) <form method="get"> <fieldset> <div class="form_error_summary" id="form_error_summary"> <h2>1 error(s) prohibited this form from being saved</h2> <p>Following fields reported errors:</p> <ul><li>server : invalid server</li></ul> </div> <p> <label class="radio_label" for="form-server-0"><input type="radio" class="radio_input" value="WEBrick" name="server" id="form-server-0" />WEBrick</label> <label class="radio_label" for="form-server-1"><input type="radio" checked="checked" class="radio_input_error" value="Mongrel" name="server" id="form-server-1" />Mongrel</label> <label class="radio_label" for="form-server-2"><input type="radio" class="radio_input" value="Thin" name="server" id="form-server-2" />Thin</label> </p> </fieldset> </form> FORM end ## ## Create a form containing text input fields, ## that will display the error summary with options ## and change the class of labels and fields to default values ## it 'creates form with error sumary, options provided' do form_error :username, 'invalid username' #error_encart_content out = form(:method => :get, :error_summary_id=>'funky_id', :error_summary_class => 'funky_class', :error_summary_title => 'Funky title', :error_summary_subtitle => 'Funky Subtitle') {|f| f.input_text 'Username', :username } #puts "GOT :\n#{out}\n" assert(<<-FORM, out) <form method="get"> <div class="funky_class" id="funky_id"> <h2>Funky title</h2> <p>Funky Subtitle</p> <ul> <li>username : invalid username</li> </ul> </div> <fieldset> <p> <label for="form-username" class="text_label_error">Username</label> <input type="text" class="text_input_error" name="username" id="form-username" /> </p> </fieldset> </form> FORM end ## Create a form containing an error summary where both summary and ## css style classes are provided it 'creates form with error summary, options provided for summary,label and field' do form_error :username, 'invalid username' #error_encart_content out = form(:method => :get, :error_summary_id=>'funky_id', :error_summary_class => 'funky_class', :error_summary_title => 'Funky title', :error_summary_subtitle => 'Funky Subtitle') {|f| f.input_text 'Username', :username, nil, :class=>'funky',:class_label => 'echofunky' } assert(<<-FORM, out) <form method="get"> <div class="funky_class" id="funky_id"> <h2>Funky title</h2> <p>Funky Subtitle</p> <ul> <li>username : invalid username</li> </ul> </div> <fieldset> <p> <label class="echofunky_error" for="form-username">Username</label> <input class="funky_error" type="text" name="username" id="form-username" /> </p> </fieldset> </form> FORM end ## Create a form containing an error summary where all is parametered it 'creates form with error summary, options provided for summary,label and field full override' do form_error :username, 'invalid username' #error_encart_content out = form(:method => :get, :error_summary_id=>'funky_id', :error_summary_class => 'funky_class', :error_summary_title => 'Funky title', :error_summary_subtitle => 'Funky Subtitle') {|f| f.input_text('Username', :username, nil, :class=>'funky', :class_error => 'tagada', :class_label=>'echofunky', :class_label_error=>'echo_pfunk') } assert(<<-FORM, out) <form method="get"> <div class="funky_class" id="funky_id"> <h2>Funky title</h2> <p>Funky Subtitle</p> <ul> <li>username : invalid username</li> </ul> </div> <fieldset> <p> <label class="echo_pfunk" for="form-username">Username</label> <input type="text" class="tagada" name="username" id="form-username" /> </p> </fieldset> </form> FORM end end
true
51f67bf7f915a4d930a482039c45bb68598ce1ac
Ruby
Linzeur/codeable-exercises
/week-2/extended-project/banzai/todo-list/cli.rb
UTF-8
799
3.046875
3
[]
no_license
# define global variable $bd_name = File.expand_path('../', __FILE__) + '/bd.txt' def read_file File.read($bd_name).split("\n").map { |line| line.split(" - ").map(&:strip) } end def save_file(tasks) newTasks = tasks.map { |fil| fil.join(' - ') }.join("\n") File.write($bd_name, newTasks) end def write(task) list_task = read_file last_index = (list_task[list_task.length - 1][0]).to_i new_task = [(last_index + 1).to_s, task] list_task << new_task save_file(list_task) show end def delete(id) list_task = read_file new_tasks = list_task.select { |task| task[0] != id } if new_tasks == list_task puts "No existe tarea" return "No existe tarea" end puts "Borrando task #{id}" save_file(new_tasks) show end def show File.read($bd_name).split("\n") end
true
34bbeb1c288ce50066ae27e9032d5c330379df3d
Ruby
project-kotinos/BathHacked___energy-sparks
/spec/lib/amr_usage_spec.rb
UTF-8
7,342
2.796875
3
[ "MIT" ]
permissive
require 'rails_helper' require 'amr_usage.rb' describe 'AmrUsage' do let!(:school) { FactoryBot.create :school } let(:supply){ :electricity } let!(:electricity_meter_1) { FactoryBot.create :electricity_meter, school_id: school.id } let!(:electricity_meter_2) { FactoryBot.create :electricity_meter, school_id: school.id } let!(:gas_meter_1) { FactoryBot.create :gas_meter, school_id: school.id } let!(:last_week) { Date.today - 7.days..Date.today - 1.days } let!(:week_before) { Date.today - 14.days..Date.today - 8.days } before(:each) do [last_week, week_before].each do |week| week.each do |date| AmrValidatedReading.create!(meter_id: electricity_meter_1.id, reading_date: date, kwh_data_x48: generate_readings(100, 200), status: 'ORIG', one_day_kwh: 300) AmrValidatedReading.create!(meter_id: electricity_meter_2.id, reading_date: date, kwh_data_x48: generate_readings(150, 200), status: 'ORIG', one_day_kwh: 350) AmrValidatedReading.create!(meter_id: gas_meter_1.id, reading_date: date, kwh_data_x48: generate_readings(10, 20), status: 'ORIG', one_day_kwh: 30) end end end def generate_readings(reading_for_1am, reading_for_11pm) readings = Array.new(48, 0.0) readings[1] = reading_for_1am readings[45] = reading_for_11pm readings end describe '#daily_usage' do context 'school has no meters for the supply' do it 'sets the usage value to zero for each day' do # test with invalid supply supply = 999 expect(school.daily_usage(supply: supply, dates: last_week).inject(0) { |a, e| a + e[1] }).to eq 0 end end context 'if no readings are found for the date' do it 'sets the usage value to zero' do # start the day before there are meter readings dates_no_readings = Date.today - 30.days..Date.today - 30.days expect(school.daily_usage(supply: supply, dates: dates_no_readings)[0][1]).to eq 0 end end it 'returns a total of all reading values for each date in the date array' do expect(school.daily_usage(supply: supply, dates: last_week)).to eq [ [Date.today - 7.days, 650.0], [Date.today - 6.days, 650.0], [Date.today - 5.days, 650.0], [Date.today - 4.days, 650.0], [Date.today - 3.days, 650.0], [Date.today - 2.days, 650.0], [Date.today - 1.days, 650.0] ] end end describe '#last_reading_date' do context 'no previous readings are found' do it "returns nil" do new_school = FactoryBot.create :school expect(new_school.last_reading_date(:electricity, Date.today)).to be_nil end end context "readings are found" do it "returns a date" do expect(school.last_reading_date(:electricity, Date.today)).to be_a_kind_of Date end it "returns the last date on/before the date specified" do expect(school.last_reading_date(:electricity, Date.today)).to eq Date.today - 1.days #should be the day before expect(school.last_reading_date(:electricity, Date.today - 8.days)).to eq Date.today - 9.days end end end describe '#earliest_reading_date' do context 'no previous readings are found' do it "returns nil" do new_school = FactoryBot.create :school expect(new_school.earliest_reading_date(:electricity)).to be_nil end end context "readings are found" do it "returns a date" do expect(school.earliest_reading_date(:electricity)).to be_a_kind_of Date end it "returns the earliest reading" do expect(school.earliest_reading_date(:electricity)).to eq week_before.first end end end describe '#last_friday_with_readings' do context 'no previous readings are found' do it "returns nil" do new_school = FactoryBot.create :school expect(new_school.last_friday_with_readings(:electricity)).to be_nil end end context "readings are found on a Friday" do it "returns a date" do expect(school.last_friday_with_readings(:electricity)).to be_a_kind_of Date end it "returns a Friday" do expect(school.last_friday_with_readings(:electricity).friday?).to be_truthy end it "returns the last Friday" do expect(school.last_friday_with_readings(:electricity)).to be_between(last_week.first, last_week.last) end end end describe "#day_most_usage" do context 'no previous readings are found' do it "returns nil" do new_school = FactoryBot.create :school expect(new_school.day_most_usage(:electricity)).to be_nil end end context "readings are found" do before(:each) do # Update the last one, else sort doesn't work as they all have the same value AmrValidatedReading.order(:reading_date).last.update(one_day_kwh: 400) end it "returns an array whose first element is the date" do expect(school.day_most_usage(:electricity)[0]).to be_a_kind_of Date end it "returns an array whose second element is the value" do expect(school.day_most_usage(:electricity)[1]).to be_a_kind_of Float end it "returns the expected value" do expect(school.day_most_usage(:electricity)[0]).to eql(Date.yesterday) expect(school.day_most_usage(:electricity)[1].to_i).to eql(750) end end end describe "#last_full_week" do it "returns a date range" do expect(school.last_full_week(:electricity)).to be_a_kind_of Range expect(school.last_full_week(:electricity).first).to be_a_kind_of Date expect(school.last_full_week(:electricity).last).to be_a_kind_of Date end it "returns a range of five dates" do expect(school.last_full_week(:electricity).to_a.size).to eq 5 end it "starts with a Monday" do expect(school.last_full_week(:electricity).first.monday?).to be_truthy end it "ends with a Friday" do expect(school.last_full_week(:electricity).last.friday?).to be_truthy end end describe "#hourly_usage" do context 'school has no meters for the supply' do it 'sets the usage value to zero for each day' do # test with invalid supply supply = 999 expect(school.hourly_usage_for_date(supply: supply, date: Date.today - 1.day).inject(0) { |a, e| a + e[1] }).to eq 0 end end def results_array(reading_for_1am, reading_for_11pm) readings = generate_readings(reading_for_1am, reading_for_11pm) readings.each_with_index.map { |reading, index| [AmrUsage::MINUTES[index], reading] } end context 'school has meters for this supply' do it 'returns the average usage for each reading time across all dates' do expect(school.hourly_usage_for_date(supply: supply, date: Date.today - 1.day)).to eq results_array(250, 400) end end end describe ".this_week" do context 'no date is provided' do it "defaults to the current date" do expect(AmrUsage.this_week.to_a).to include Date.current end it "starts on a Saturday" do expect(AmrUsage.this_week.first.saturday?).to be_truthy end it "ends on a Friday" do expect(AmrUsage.this_week.last.friday?).to be_truthy end end end end
true
e66b2c9e9bc6cb1c912033fc07f4bfd12979d63c
Ruby
Megumi-0712/Ruby_practice-part2
/pop-test.rb
UTF-8
136
3.609375
4
[]
no_license
test1 = [0,1,2,3,4] puts test1.pop test2 = [0,1,[2,3],4,] test2.pop puts test2.pop a = ["愛","友情","慈愛"] a.pop puts a.pop
true
3d528d9265f57f30f44586336fe828af9fc9d3c1
Ruby
hyperwing/SetGameInRuby
/Utilities/set_functions.rb
UTF-8
3,661
3.359375
3
[]
no_license
# File created 09/04/2019 by Sri Ramya Dandu # File renamed 09/18/2019 by Neel Mansukhani to set_functions.rb # Edited 09/05/2019 by Leah Gillespie # Edited 09/06/2019 David Wing # Edited 09/06/2019 by Neel Mansukhani # Edited 09/07/2019 by Sharon Qiu # Edited 09/07/2019 by Neel Mansukhani # Edited 09/07/2019 by Sri Ramya Dandu # Edited 09/08/2019 by Sharon Qiu # Edited 09/08/2019 by Neel Mansukhani # Edited 09/09/2019 by David Wing # Edited 09/09/2019 by Sharon Qiu # Edited 09/09/2019 by David Wing # Edited 09/09/2019 by Sri Ramya Dandu # Edited 09/10/2019 by Sri Ramya Dandu # Edited 09/12/2019 by Leah Gillespie # Edited 09/12/2019 by David Wing # Edited 09/14/2019 by Neel Mansukhani # Edited 09/15/2019 by Sri Ramya Dandu # Edited 09/15/2019 by David Wing # Edited 09/16/2019 by Sri Ramya Dandu # Edited 09/18/2019 by Neel Mansukhani # Created 09/04/2019 by Sri Ramya Dandu # Edited 09/18/2019 by Neel Mansukhani: Moved functions to module module SetFunctions # Created 09/04/2019 by Sri Ramya Dandu # Edited 09/07/2019 by Sri Ramya Dandu: Optimized the checking method - made function concise # Checks if the 3 cards are a valid set or not. To be a valid set, all 3 cards must either have the same # attribute or all different attributes for each of the following attributes: number, color,shape,shade. # @param card1, card2, card3 to evaluate whether they form a set or not # @returns true if cards form a valid set, false otherwise # @updates $score def is_a_set?(cards) # The sum when adding one number 3 times or adding 3 consecutive numbers is divisible by 3. # This represents having all the same attribute or all different attributes. # Adding any other 3 number combo of 1,2,3 will result in a value not divisible by 3, failing to be a set. (cards[0].number + cards[1].number + cards[2].number) % 3 == 0 && (cards[0].color + cards[1].color + cards[2].color) % 3 == 0 && (cards[0].shape + cards[1].shape + cards[2].shape) % 3 == 0 && (cards[0].shade + cards[1].shade + cards[2].shade) % 3 == 0 end # Created 09/06/2019 by David Wing # Edited 09/07/2019 by David Wing # Edited 09/08/2019 by David Wing # Edited 09/09/2019 by Sri Ramya Dandu: changed cardsShowing to a global variable # Edited 09/12/2019 by David Wing: Optimized table searching # Edited 09/16/2019 by Sri Ramya Dandu: replaced for loops with ruby convention # Given an Array of the displayed cards, checks if there is a set # Returns an empty Array if there is not a set. If there is set, it returns # an array holding the 3 cards that form the set def valid_table(cards_showing) # make hash of all table cards # id is the key, location is the value table_hash = Hash.new return [] if cards_showing.length < 1 (0...cards_showing.length).each {|i| table_hash[cards_showing[i].id] = i} (0...cards_showing.length).each do |card1| (1...cards_showing.length).each do |card2| if card1 == card2 #skip if same card next end # Find attributes of the last card needed # Using the attributes of any two cards, you can determine what the final card would be that would make a set # This finds the attributes of that last card, which is later used to see if that card is available card_to_find = 27 * ((6- cards_showing[card1].number - cards_showing[card2].number) % 3) card_to_find += 9 * ((6- cards_showing[card1].color - cards_showing[card2].color) %3) card_to_find += 3 * ((6- cards_showing[card1].shape - cards_showing[card2].shape) %3) card_to_find += (6-cards_showing[card1].shade - cards_showing[card2].shade) %3 # cardToFind is now the card ID for the last card return [card1, card2, table_hash[card_to_find]] if table_hash.include? card_to_find end end return [] end end
true
be4680ee97580b629216de7f4cb992b70d3bdc20
Ruby
markbiz41/Assignments
/19.rb
UTF-8
1,121
4.5
4
[]
no_license
# Note for this exercise, follow these simplified pig latin rules # If the first letter is a vowel, add "way" to the end # If the first letter is a consonant, move it to the end and add "ay" class PigLatin VOWELS = %w(a e i o u) def self.pigatize(a) # Check to see if the first letter is a vowel, if not it's a consonant if PigLatin.starts_with_vowel(a[0]) # this is placeholder code and should take action based on it starting with a vowel pigatized_text = a + "way" else # this is placeholder code and should take action based on it starting with a consonant pigatized_text = a[1..-1] + a[0] + "ay" end return pigatized_text end # Check to see if the first letter is a vowel def self.starts_with_vowel(first_letter) return VOWELS.include?(first_letter) # this should determine if it starts with a vowel end end class String def pigatize PigLatin.pigatize(self) end end puts "Please enter a word and I will translate to pig latin" text = gets.chomp puts "Pigatize: #{text.pigatize}" # puts "foo".pigatize # puts PigLatin.pigatize("foo")
true
e4d04066a066d57b13a11f68297fc23057b17ba5
Ruby
apperen/NPDV-1
/lessons1-7/lesson7/07-3.rb
UTF-8
469
3.171875
3
[]
no_license
# encoding: utf-8 choice = nil # будет повторяться пока пользователь не введет 1 ИЛИ 2 ИЛИ 3 until (choice == 1 || choice == 2 || choice == 3) puts "введите число: 1 – да, 2 – нет, 3 – иногда, и нажмите Enter" choice = gets.chomp.to_i end # Адаптируйте под ваши имена переменных и набор разрешенных значений. # ...
true
4ce2ce78f95598b291306cba73f488d53c2b833f
Ruby
ClaytonWong/cw-toy-robot
/get_input.rb
UTF-8
236
3.5625
4
[]
no_license
def get_input() input = gets.upcase.strip # Read input from user, change it to upper case and remove spaces inputs = input.to_s.split(" ") # Split input up into pieces marked by spaces return inputs end # End get_input definition
true
d30fca60b0935af4522e811dd839748b64c1d876
Ruby
ivanionut/old-study
/ruby/containers-blocks-and-iterators/hash_test.rb
UTF-8
711
3.203125
3
[]
no_license
require 'test-unit' class HashTest < Test::Unit::TestCase def test_1 h = {'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine'} p h.length p h['dog'] h['cow'] = 'bovine' h[0] = 0 h['cat'] = 999 p h end def test_2 h = {'dog' => 'canine', 'cat' => 'feline', 'donkey' => 'asinine'} p h j = {:dog => 'canine', :cat => 'feline', :donkey => 'asinine'} p j k = {dog: 'canine', cat: 'feline', donkey: 'asinine'} p k end def test_3 h = {'A' => 1} h.each_key {|k| p k.object_id} #tutte le volte che lancio il test cambia la stringa, ne istanzia un'altra h = {A: 1} h.each_key {|k| p k.object_id} # qua è sempre uguale end end
true
daf4e691ada0469075a70f1594877fbabe5e51dc
Ruby
larskotthoff/assurvey
/web/convert.rb
UTF-8
3,500
2.546875
3
[]
no_license
#!/usr/bin/env ruby # encoding: UTF-8 require 'rubygems' require 'json' TEX = ARGV[0] BBL = ARGV[1] # key: citation key # value: [short citation (stuff in \bibitem), full citation] bibs = {} agg = "" doneski = true IO.readlines(BBL).each { |b| bp = b.strip if bp =~ /^\\bibitem/ or not doneski doneski = false if bp.empty? m = agg.strip.scan(/^\\bibitem\[.*\\citeauthoryear\{.*\}(\{.+?\})(\{[0-9a-z]+\})\]\{(.+?)\}\s*(.+)$/m) if m.empty? puts agg else bibs[m[0][2]] = [m[0][0] + " " + m[0][1], m[0][3]] end agg = "" doneski = true else if bp =~ /%$/ agg += bp.chomp('%') else agg += bp + " " end end end } lines = [] headers = ["citation", "domain", "features", "predict what", "predict how", "predict when", "portfolio"] lit = [] agg = "" doneski = true IO.readlines(TEX).each { |t| if t =~ /^\\citeA/ or not doneski doneski = false agg += (agg.empty? ? "" : " ") + t.strip if agg[-2..-1] == "\\\\" lines << agg[0..-3] agg = "" doneski = true end end } transformations = [[/\\"i/, 'ï'], [/\\\^i/, 'î'], [/\\'o/, 'ó'], [/\\'i/, 'í'], [/\\'c/, 'ć'], [/\\'a/, 'á'], [/\\'A/, 'Á'], [/\\'e/, 'é'], [/\\'E/, 'É'], [/\\`e/, 'è'], [/\\\^e/, 'ê'], [/\\v\{c\}/, 'č'], [/\\va/, 'ǎ'], [/\\c\{c\}/, 'ç'], [/\\"u/, 'ü'], [/\\"o/, 'ö'], [/\\ss/, 'ß'], [/\\~n/, 'ñ'], [/\\~a/, 'ã'], [/\\_/, '_'], [/\\ /, ' '], [/\\\//, ''], [/\$(.+?)\$/, '<i>\1</i>'], [/\\citeA\{(.+?)\}/, '\1'], [/\\emph\{(.+?)\}([.,])/, '<i>\1</i>\2'], [/\{\\em (.+?)\}([.,~])/, '<i>\1</i>\2'], [/~/, '&nbsp;'], [/\\newblock /, '<br/>'], [/\\sc /, ''], [/--/, '&mdash;'], [/\\&/, '&amp;'], [/\{\\natexlab\{.+?\}\}/, ''], [/\\penalty0 /, ''], [/\\mbox\{(.+?)\}/, '\1'], # catchall, twice for nested stuff [/\{(.+?)\}/, '\1'], [/\{(.+?)\}/, '\1']] lines.each { |l| transformations.each{ |t| l.gsub!(t[0], t[1]) } } bibs.values.each { |l| transformations.each{ |t| l[0].gsub!(t[0], t[1]) l[1].gsub!(t[0], t[1]) } } lines.each { |l| parts = l.split(/\s*&\s*/) year = parts[0].split(',')[0].split(/_/)[-1].to_i h = {"year" => year} h["citation"] = {"short" => parts[0].split(/,/).collect { |s| bibs[s][0] }.join(", "), "long" => parts[0].split(/,/).collect { |s| bibs[s][1] }.join("<br/><br/>")} (1..parts.length-1).each { |i| h[headers[i]] = parts[i] } lit << h } puts lit.to_json #puts (["year"] + headers).join(",") #lit.each { |l| # years = l["citation"]["short"].scan(/[0-9]{4}/) # years.each { |y| # puts ([y] + [""] + headers[1..-1].collect { |h| l[h].gsub(/,/, "") }).join(",") # } #}
true
fa3bb03ec2a2eabb3b2f7e20ef8c1af7419af305
Ruby
sarojinidehuri/RoRAssignments
/19-05/ass5.rb
UTF-8
225
3.421875
3
[]
no_license
puts "print the num for a pyramid: " star= gets.chomp.to_i star1=0 (0...star).each do |i| (0...i).each do |j| print " " end (0...star-star1).each do |j| print "* " end star1 += 1 puts "" end
true
3914b06d7d8a100a3ac7bc57f03307ee6305546e
Ruby
ruslanrozhkov/drone
/lib/gyroscope.rb
UTF-8
411
2.96875
3
[]
no_license
# gyroscope.rb require 'observer' class Gyroscope include Observable attr_reader :x, :y, :z def initialize @x, @y, @z = 0, 0, 0 end def vectors {x: @x, y: @y, z: @z} end def x=(x) return if @x == x @x = x changed notify_observers(Time.now, vectors) end def y=(y) return if @y == y @y = y changed notify_observers(Time.now, vectors) end end
true
f38ae0bb199c445a070495ba7b150a3b890b4269
Ruby
Danieleclima/ruby-objects-has-many-lab-online-web-pt-031119
/lib/author.rb
UTF-8
336
2.84375
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class Author attr_accessor :name def initialize (name) @name = name end def posts Post.all end def add_post (posts) posts.author = self end def add_post_by_title (post_title) new_post = Post.new (post_title) new_post.author = self end def self.post_count Post.all.count end end
true
8956df74d6aa39876966eaf72424701577d7fcae
Ruby
yutof/bib
/src/Deck.rb
UTF-8
518
3.796875
4
[]
no_license
#!/usr/bin/ruby class Deck def initialize() @deck = Array.new end def Add(card) @deck << card end def Shuffle() @deck.shuffle! end def Draw() @deck.pop end def IsEmpty() @deck.empty? end def IsNotEmpty() @deck.empty? == false end def Length() @deck.length end def GetDeckAverageValue() total = 0.0 @deck.each { |c| total += c.GetValue()} total/@deck.length end def Dump() str = "" @deck.each { |c| str = str + "\n#{c.ToString()}"} puts str end end
true
3f6c2d2c340467be6d3ce80828c449d316e2d5ae
Ruby
manhgn/ruby_repo
/chapters/2_variables/name.rb
UTF-8
365
4.25
4
[]
no_license
#exercise one# puts "Hey! Type in your name!" text = gets.chomp puts "Hello! #{text}" #exercise three# 10.times {puts text} #exercise four# puts "What's your first name?" first = gets.chomp puts "What's your last name?" last = gets.chomp puts "#{first} #{last}" #exercise five# #the first prints 3 and the second gives an error because x is created in the block#
true
8f8a35ab58b0f54174258406ad4a578ca9b5c319
Ruby
apidigital/roart
/lib/roart/core/array.rb
UTF-8
137
2.609375
3
[ "WTFPL" ]
permissive
class Array def to_hash h = Hash.new self.each do |element| h.update(element.to_sym => nil) end h end end
true
89a7a591b6e7b4891969170c63b6c29f89e8b889
Ruby
Papankr/-7
/2/test.rb
UTF-8
349
2.671875
3
[]
no_license
#!/usr/bin/env ruby require 'test/unit' require '/Users/tenzy/Desktop/lab7/main2' # Test for part2 class Test2 < Test::Unit::TestCase def setup @box = Box.new(10, 10, 10) end def test_1 assert @box.is_a? Board end def test_2 assert_equal(1000, @box.volume) end def test_3 assert_equal(100, @box.surface) end end
true
95e8f78d6c3e040ad7fb14a22d345c0215fa28d7
Ruby
EJLarcs/my-each-web-0715-public
/my_each.rb
UTF-8
365
3.890625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def my_each(array) counter = 0 while counter < array.length #length on an array tells you about of strings in array yield array[counter] #yielding item in the array and then it comes back counter += 1 end array end #when you have to puts from an array as well as return it you must #also call it at the end #my_each(item) do |item| # puts item #end
true
22f0b7d58eb7ef72d73785f1f83bc5dbd7181c7e
Ruby
bartoszkopinski/ghstats
/spec/ghstats/stats_spec.rb
UTF-8
1,551
2.546875
3
[ "MIT" ]
permissive
require "ostruct" require "spec_helper" require "ghstats/stats" module GHStats class DummyAPIClient REPOS = { "rubyist" => %w{Ruby JavaScript PHP Ruby}, "inactive" => [], "unknown" => [nil, nil, "C++"], "mixed" => ["Swift", "Swift", "Objective-C", "Objective-C"], } def initialize(*); end def repos(username) REPOS[username].map do |l| OpenStruct.new(language: l) end end end describe Stats do describe "#most_common_language" do context "for a user with Ruby repos" do subject { described_class.new("rubyist", DummyAPIClient) } it "returns Ruby as the most common language" do expect(subject.most_common_language).to eq("Ruby") end end context "for a user with no repos" do subject { described_class.new("inactive", DummyAPIClient) } it "returns nil as the most common language" do expect(subject.most_common_language).to be_nil end end context "for a user with many unrecognized repos" do subject { described_class.new("unknown", DummyAPIClient) } it "ignores unknown languages" do expect(subject.most_common_language).to eq("C++") end end context "for a user with more than one most common language" do subject { described_class.new("mixed", DummyAPIClient) } it "returns the most recent language" do expect(subject.most_common_language).to eq("Swift") end end end end end
true
3bfe815505183fe21fb9863de35a0cf894a44b9f
Ruby
iamyevesky/Ruby2048
/2048.rb
UTF-8
7,422
3
3
[]
no_license
['io/console', 'colorize'].each{ |g| require g } @achievements = { 16 => 'Unlock the 16 Tile', 32 => 'Unlock the 32 Tile', 64 => 'Unlock the 64 Tile', 128 => 'Unlock the 128 Tile', 256 => 'Unlock the 256 Tile', 512 => 'Unlock the 512 Tile', 1_024 => 'Unlock the 1024 Tile', 2_048 => 'Unlock the 2048 Tile', 4_096 => 'Unlock the 4096 Tile', 8_192 => 'Unlock the 8192 Tile', 16_384 => 'Unlock the 16384 Tile', "Score 500" => 'Earn more than 500 points', "Score 1000" => 'Earn more than 1000 points', "Score 2000" => 'Earn more than 2000 points', "Score 5000" => 'Earn more than 5000 points', "Score 10000" => 'Earn more than 10000 points', "HIGHEST SCORE" => 'Earn more than 20000 points' } @unlocked = [] @board = Array.new(4) { [0, 0, 0, 0] } @scores = [0] @tiles = [16, 32, 64, 128, 256, 512, 1_024, 2_048, 4_096, 8_192, 16_384] @numbers = [0, 2, 4, 8].concat(@tiles) @milestones = [500, 1_000, 2_000, 4_000, 8_000, 16_000] @colors = %i(white white light_red red light_yellow yellow light_cyan cyan light_green green light_blue blue light_magenta magenta) def game_score @board.flatten.inject(:+) end def high_score [game_score, @scores.max].max end def colorize_score game_score.to_s.yellow end def show_score puts "\t\t Score: #{game_score == high_score ? colorize_score : game_score} " << "High Score: #{game_score == high_score ? colorize_score : high_score} " << "Achievements: #{@unlocked.count}" puts "\t\t ________________________________________" end def draw_board show_score (0..3).each do |x| print "\t\t| " (0..3).each { |y| print colorize_number(@board[x][y]) << '| ' } puts '' end puts '' end def new_tile tile = [*1..2].sample * 2 x = [*0..3].sample y = [*0..3].sample (0..3).each do |i| (0..3).each do |j| x1 = (x + i) % 4 y1 = (y + j) % 4 if @board[x1][y1] == 0 @board[x1][y1] = tile return true end end end end def colorize_number(num) number = '%4.4s' % num color = '' colors_array = [@numbers.zip(@colors)].flatten(1) for i in 0..colors_array.length-1 color = number.colorize(colors_array[i][1]) if num == colors_array[i][0] end color.underline end # Receive and process user input def receive_input input = '' controls = %w(a s d w) until controls.include?(input) input = STDIN.getch abort 'escaped' if input == "\e" end input end def flip_board @board.transpose.map(&:reverse) end # Creates a new line after the user enters a direction def shift_left(line) new_line = [] line.each { |line| new_line << line unless line.zero? } new_line << 0 until new_line.size == 4 new_line end # Moves tiles to the left def move_left new_board = Marshal.load(Marshal.dump(@board)) (0..3).each do |i| (0..3).each do |j| (j..2).each do |k| if @board[i][k + 1] == 0 next elsif @board[i][j] == @board[i][k + 1] @board[i][j] = @board[i][j] * 2 @board[i][k + 1] = 0 end break end end @board[i] = shift_left(@board[i]) end @board == new_board ? false : true end # Move tiles to the right def move_right @board.each(&:reverse!) action = move_left @board.each(&:reverse!) action end # Move tiles down def move_down @board = flip_board action = move_left 3.times { @board = flip_board } action end # Move tiles up def move_up 3.times { @board = flip_board } action = move_left @board = flip_board action end # If a player reaches the final tile, 16384, they win def win_checker @board.flatten.max == 16_384 end # Checks which direction the player can move def loss_checker new_board = Marshal.load(Marshal.dump(@board)) option = move_right || move_left || move_up || move_down unless option @board = Marshal.load(Marshal.dump(new_board)) return true end @board = Marshal.load(Marshal.dump(new_board)) false end def get_tiles 2.times { new_tile } draw_board end def make_move direction = receive_input case direction when 'a' then action = move_left when 'd' then action = move_right when 'w' then action = move_up when 's' then action = move_down end new_tile if action end def move_sequence until win_checker make_move draw_board if loss_checker @win = false break end end end def greeting puts "\n\t\t Welcome to 2048!" puts "\n\t\t RULES" puts "\n\t\t Match powers of 2 by connecting ajacent identical numbers." puts "\n\t\t CONTROLS" puts "\n\t\t a - Move left" puts "\t\t d - Move right" puts "\t\t w - Move up" puts "\t\t s - Move down" puts "\n" end # Event Sequence for every game def play greeting get_tiles move_sequence end def unlock_tiles @tiles.each do |tile| unless @unlocked.include?(@achievements[tile]) @unlocked << @achievements[tile] if (@board.flatten.include?(tile)) end end end def reach_milestones @milestones.each do |milestone| unless @unlocked.include?(@achievements["Score #{milestone}"]) @unlocked << @achievements["Score #{milestone}"] if game_score >= milestone end end end def highest_honor unless @unlocked.include?(@achievements['HIGHEST SCORE']) @unlocked << @achievements['HIGHEST SCORE'] if game_score >= 20_000 end end def earn_achievements unlock_tiles reach_milestones highest_honor end def win_message puts "\t\t Congratulations! You reached the FINAL tile!".yellow end def lose_message puts "\t\t There are no more ajacent tiles with the same number.".red puts "\t\t The game is over".red end def game_over_message puts "\n\t\t Your final score was #{game_score}." puts "\n\t\t Press 'a' to view your achievements!\n" end def end_game @win ? win_message : lose_message game_over_message @scores << game_score end # The sequences of events for a game def play_cycle play earn_achievements end_game end play_cycle # Starts the game response = '' while response == '' || response == 'y' puts "\t\t HIGH SCORE: #{@scores.max}\n" @board = Array.new(4) { [0, 0, 0, 0] } puts "\n\t\t Would you like to play again?" puts "\t\t Press y for 'Yes' and n for 'No'" response = gets.chomp # A list of the achievements they've earned will show up while response == 'a' puts "\n\t\t ACHIEVEMENTS \n\n" @unlocked.each { |a| puts "\t\t " << a } puts "\n" response = '' end play_cycle if response == 'y' end
true
4a62a2b7a84f9aeb80b141198119873ad8ebedb9
Ruby
CraftAcademy/slow_food_sinatra_august_17
/spec/order_spec.rb
UTF-8
2,146
2.796875
3
[ "MIT" ]
permissive
require './lib/models/order.rb' describe Order do let(:item_1) { Dish.create(name: 'Test 1', price: 50) } let(:item_2) { Dish.create(name: 'Test 2', price: 10) } let!(:buyer) { User.create!(username: 'Buyer', password: 'password', password_confirmation: 'password', phone_number: '123456', email: 'buyer@test.com') } subject do described_class.create!(user: buyer) end it { is_expected.to have_property :id } it { is_expected.to have_many :order_items } it { is_expected.to belong_to :user } it { is_expected.to validate_presence_of :user } it 'adds dish to order as order_item' do subject.add_item(item_1, item_1.price, 2) expect(subject.order_items.count).to eql 1 end it 'it displays total sum of the order with 1 in quantity' do subject.add_item(item_1, item_1.price, 1) expect(subject.total).to eql item_1.price end it 'it displays total sum of the order with 2 in quantity' do subject.add_item(item_1, item_1.price, 2) expect(subject.total).to eql item_1.price * 2 end it 'it displays total sum of the order with 2 items' do subject.add_item(item_1, item_1.price, 1) subject.add_item(item_2, item_2.price, 1) expect(subject.total).to eql item_1.price + item_2.price end it 'it displays estimated pick up time' do expect(subject.set_pick_up_time).to eql Time.now.round + 1800 end it 'removes item from order' do #we add two items to the order. We count unique items, not the total quantity subject.add_item(item_1, item_1.price, 2) subject.add_item(item_2, item_2.price, 2) expect(subject.order_items.count).to eql 2 subject.remove_item(item_1) expect(subject.order_items.count).to eql 1 end it 'cancels order' do subject.add_item(item_1, item_1.price, 2) subject.cancel_order expect(subject.order_items.count).to eql 0 end it '#order_include?' do subject.add_item(item_1, item_1.price, 2) expect(subject.order_include?(item_1)).to eql true end end
true
577756fc7e462007e66b15fd9fa392d3c2bcf020
Ruby
aphero/voting_api
/app/models/voter.rb
UTF-8
628
2.5625
3
[]
no_license
class Voter < ActiveRecord::Base before_create :generate_access_token # Before a voter is created, generate an access token. has_one :vote validates :name, uniqueness: true, presence: true validates :party, presence: true private def generate_access_token begin # Looping! self.access_token = SecureRandom.hex # Generate a random hex token! end while self.class.exists?(access_token: access_token) # Check to make sure that the generated token doesn't already exist. end end # THERE ARE THINGS IN DOUG'S
true
e57f8313b589f0692bb2177f13b2b868cda0b735
Ruby
cmkoller/rescue_mission
/spec/features/user_creates_a_question_spec.rb
UTF-8
2,827
2.625
3
[]
no_license
require "rails_helper" feature "Post a Question", %q( As a user I want to post a question So that I can receive help from others Acceptance Criteria [ ] I must provide a title that is at least 40 characters long [ ] I must provide a description that is at least 150 characters long [ ] I must be presented with errors if I fill out the form incorrectly ) do context "authenticated user" do before(:each) do user = User.create( first_name: "Joe", last_name: "Schmoe", email: "email@email.com", password: "passwordsecret" ) visit new_user_session_path fill_in "Email",with: user.email fill_in "Password", with: user.password click_button "Log in" visit new_question_path end scenario 'user posts a question' do question = FactoryGirl.create(:question) fill_in "Title", with: question.title fill_in "Description", with: question.description click_on "Create Question" expect(page).to have_content("Question created.") expect(page).to have_content(question.title) expect(page).to have_content(question.description) end scenario 'user posts a question with too-short title' do question = FactoryGirl.create(:question) question.title = "Short Title" fill_in "Title", with: question.title fill_in "Description", with: question.description click_on "Create Question" expect(page).to have_content("Title is too short") expect(find_field("Title").value).to eq question.title expect(find_field("Description").value).to eq question.description end scenario 'user posts a question with too-long title' do question = FactoryGirl.create(:question) question.title *= 8 fill_in "Title", with: question.title fill_in "Description", with: question.description click_on "Create Question" expect(page).to have_content("Title is too long") expect(find_field("Title").value).to eq question.title expect(find_field("Description").value).to eq question.description end scenario 'user posts a question with too-short description' do question = FactoryGirl.create(:question) question.description = "Short description" fill_in "Title", with: question.title fill_in "Description", with: question.description click_on "Create Question" expect(page).to have_content("Description is too short") expect(find_field("Title").value).to eq question.title expect(find_field("Description").value).to eq question.description end end context "unauthenticated user" do scenario "can't access question creation form" do visit new_question_path expect(page).to have_content("You need to sign in or sign up before continuing") end end end
true
51535d2a242f55aece980ec8074544d9d83a6053
Ruby
wlodi83/Praca-Magisterska
/app/models/article.rb
UTF-8
2,041
2.578125
3
[]
no_license
class Article < ActiveRecord::Base has_many :comment before_save :update_published_at belongs_to :user has_many :photos, :dependent => :destroy has_and_belongs_to_many :categories, :after_add => :counter_inc, :after_remove => :counter_dec def counter_inc(t) counter_change(t, 1) end def counter_dec(t) counter_change(t, -1) end acts_as_commentable has_and_belongs_to_many :authors has_and_belongs_to_many :photographers define_index do # fields indexes title indexes body indexes synopsis indexes authors.name, :as => :authors_name indexes photographers.name, :as => :photographers_name indexes categories.name, :as => :categories_name # attributes has authors(:id), :as => :author_ids has photographers(:id), :as => :photographer_ids has categories(:id), :as => :category_ids has created_at, updated_at end #walidacje validates_presence_of :title, :synopsis, :body validates_inclusion_of :published, :in => [true, false], :message => "Musisz zaznaczyć opcję czy artykuł ma być opublikowany" validates_presence_of :user_id validates_length_of :title, :within => 3..200 validates_length_of :synopsis, :maximum => 50000 validates_length_of :body, :maximum => 500000 validate :maximum_three_categories validate :minimum_one_category validate :minimum_one_author def minimum_one_category errors.add(:categories, "Musisz zaznaczyć conajmniej jedną kategorię") if (categories.length < 1) end def maximum_three_categories errors.add(:categories, "Możesz zaznaczyć maksimum 3 kategorie") if (categories.length > 3) end def minimum_one_author errors.add(:authors, "Musisz zaznaczyć conajmniej jednego Autora tekstu") if (authors.length < 1) end def update_published_at self.published_at = Time.now if published == true end private def counter_change(object, amount) object.articles_count = object.articles_count+amount; object.save end end
true
12f27d04a43d453043f50e419fd0e46f1255e79b
Ruby
abeidahmed/tic-tac-toe
/bin/main.rb
UTF-8
1,518
3.765625
4
[ "MIT" ]
permissive
#!/usr/bin/env ruby require_relative '../lib/player' require_relative '../lib/game' EXIT_KEY = 'q'.freeze def register_player_for(player_name) puts "✨ Please enter Player #{player_name}'s name ✨" player_name = gets.chomp.to_s.strip while player_name.empty? puts 'Please enter a valid name' player_name = gets.chomp.to_s end player_name end puts '' puts '🙌 Welcome to Tic Tac Toe 🙌' puts '' puts 'Before we begin with the game, register yourself and your partner' puts "Press 'Enter' to continue or press '#{EXIT_KEY}' to exit the game" command = gets.chomp.to_s.strip exit if command == EXIT_KEY puts '' player_x = register_player_for('x') puts '' player_o = register_player_for('o') while player_x.downcase == player_o.downcase puts '' puts "Players should have different names. Enter a different name for 'Player O'" puts '' player_o = register_player_for('o') end player_x = Player.new(player_x, 'x') player_o = Player.new(player_o, 'o') game = Game.new(player_x, player_o) until game.game_over puts game.show_updated_board puts game.current_turn_to_play player_selection = gets.chomp.to_i until game.make_play(player_selection) puts game.show_updated_board puts '' puts 'Choose a valid move, write a non reserved number between 1 to 9' puts '' puts game.current_turn_to_play player_selection = gets.chomp.to_i end end if game.someone_won puts game.show_message else puts '' puts 'The game ended is a Draw' puts '' end
true
92dc512564f29043aa7912f78026dc8220e11f15
Ruby
bula21/mova21-orca
/app/services/activity_linter.rb
UTF-8
871
2.53125
3
[ "MIT" ]
permissive
# frozen_string_literal: true class ActivityLinter CHECKS = { title_translated: ->(activity) { activity.label_in_database.values.count(&:present?) > 3 }, description_translated: ->(activity) { activity.description_in_database.values.count(&:present?) > 3 }, participant_count_min: ->(activity) { activity.participants_count_activity&.>=(12) }, valid: ->(activity) { activity.valid? }, languages_min: ->(activity) { activity.languages.values.count(&:itself) >= 1 }, stufen_min: ->(activity) { (activity.stufe_ids & activity.stufe_recommended_ids).count >= 1 } }.freeze def lint(activities = Activity.all) failed_checks = CHECKS.transform_values { [] } activities.find_each do |activity| CHECKS.each { |check, check_proc| check_proc.call(activity) || (failed_checks[check] << activity.id) } end failed_checks end end
true
0be93e98a8a41a6b326d3138dd86cc163ff4f6ba
Ruby
meh/ruby-protobuffo
/lib/protobuffo/message/fields.rb
UTF-8
1,555
2.84375
3
[]
no_license
#-- # DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE # Version 2, December 2004 # # DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE # TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION # # 0. You just DO WHAT THE FUCK YOU WANT TO. #++ module ProtoBuffo; class Message class Fields include Enumerable attr_reader :message def initialize (message) @message = message @fields = [] @extensions = [] end def add_extensions (what) unless what.is_a?(Integer) || (what.is_a?(Range) && what.begin.is_a?(Integer) && what.end.is_a?(Integer)) raise ArgumentError, "#{what.inspect} is not an Integer or a Range made of Integers" end @extensions << what end def add (rule, type, name, tag, options, extension = false) Field.new(rule, type, name, tag, options, extension).tap {|field| if self[field.tag] raise ArgumentError, "#{field.tag} is already present" end if field.extension? && !extension?(field.tag) raise ArgumentError, "#{field.tag} isn't available as an extension" end if field.type.is_a?(Class) && !field.type.ancestors.member?(Message) raise ArgumentError, "#{field.type} has to be a subclass of Message" end @fields << field @fields.sort_by!(&:tag) } end def each (&block) return enum_for :each unless block @fields.each(&block) self end def [] (what) find { |f| what === f.name || what.to_s == f.name.to_s || what == f.tag } end def extension? (tag) @extensions.any? { |n| n === tag } end end end; end
true
7e54faba4e06027531db3e2235c61fb66913fb24
Ruby
OpenRubyRMK/game-engine
/data/scripts/new_rpg_data/baseitem.rb
UTF-8
906
2.78125
3
[]
no_license
require_relative "baseobject" module RPG class BaseItem < BaseObject attr_accessor :price #translation :name,:description def initialize(name) @price=0 super end end end module Game class BaseItem attr_reader :name def initialize(name) @name = name #get the Game Modules of the curresponding RPG Modules Game.constants.each do |s| if RPG.const_defined?(s) && rpg.is_a?(RPG.const_get(s)) && Game.const_get(s).instance_of?(Module) self.extend(Game.const_get(s)) end end cs_init end def to_sym return @name end def rpg return RPG::BaseItem[@name] end def price return stat(:price,rpg.price) end private def stat(key,default=0,type=nil) temp = cs_stat_sum(key,type).inject(default,:+) temp = cs_stat_multi(key,type).inject(temp,:*) temp = cs_stat_add(key,type).inject(temp,:+) return temp end end end
true
d0690d60501f898275d55fdf249bcfb648e7cd45
Ruby
screencastmint/mhack
/lib/mhack.rb
UTF-8
1,075
2.515625
3
[ "MIT" ]
permissive
class Mhack attr_reader :techno, :action, :params, :helper def initialize @techno = ARGV[0] @action = ARGV[1] @params = Array.new @helper = Helper.new argv_size = ARGV.length 2.upto(argv_size) { |i| @params.push ARGV[i] } end #Instantiates mhackmd designated by @something def router if @techno && @techno == "@aliases" && @action == ":show" @helper.render_message($techno_aliases_list) # @aliases alone render error elsif @techno && @techno == "@aliases" @helper.render_action_error # redirect to @something ... elsif @techno && @techno[0] == "@" param_count = @techno.length - 1 param_name = @techno[1,param_count] launch_techno = "$techno_#{param_name}".constantize techno = launch_techno ? (launch_techno.capitalize) : (param_name.capitalize) "Mhackmd#{techno}::#{techno}".constantize.new.launcher else @helper.render_techno_error end end end
true
9c8a9e9f95eba78c706afa5d2f6351013d34858f
Ruby
IceDragon200/BaconBot
/plugins/weather.rb
UTF-8
355
2.78125
3
[]
no_license
require 'weather-underground' plugin :Weather do def cmds "weather" end match /weather\s+(.+)/ def execute m, loc m.reply get_weather(loc) end def get_weather loc w = WeatherUnderground::Base.new obv = w.CurrentObservations(loc) obv.display_location[0].full + ": " + obv.temperature_string + " " + obv.weather end end
true
02f95704e9502f1abbb29eafbb9c572c9845b99b
Ruby
agiambro/algos
/app/run.rb
UTF-8
185
2.984375
3
[]
no_license
#!/usr/bin/env ruby require_relative 'lib/search' # arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 100, 101, 201, 301, 401, 501] arr = (1..90000000).to_a puts Search.find(9900000, arr)
true
6c90444f7e94e52ab75045301686d515e048fe1a
Ruby
mattknox/jeweler
/bin/jeweler
UTF-8
2,432
2.640625
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require 'rubygems' require 'optparse' $:.unshift File.join(File.dirname(__FILE__), '..', 'lib') require 'jeweler' class JewelerOpts < Hash attr_reader :opts def initialize(args) super() self[:test_style] = :shoulda @opts = OptionParser.new do |o| o.banner = "Usage: #{File.basename($0)} [options] reponame\ne.g. #{File.basename($0)} the-perfect-gem" o.on('--bacon', 'generate bacon specs') do self[:test_style] = :bacon end o.on('--shoulda', 'generate shoulda tests') do self[:test_style] = :shoulda end o.on('--create-repo', 'create the repository on GitHub') do self[:create_repo] = true end o.on('--summary [SUMMARY]', 'specify the summary of the project') do |summary| self[:summary] = summary end o.on_tail('-h', '--help', 'display this help and exit') do puts o exit end end @opts.parse!(args) end end options = JewelerOpts.new(ARGV) unless ARGV.size == 1 puts options.opts exit 1 end github_repo_name = ARGV.first begin generator = Jeweler::Generator.new github_repo_name, options generator.run rescue Jeweler::NoGitUserName $stderr.puts %Q{No user.name found in ~/.gitconfig. Please tell git about yourself (see http://github.com/guides/tell-git-your-user-name-and-email-address for details). For example: git config --global user.name "mad voo"} exit 1 rescue Jeweler::NoGitUserEmail $stderr.puts %Q{No user.email found in ~/.gitconfig. Please tell git about yourself (see http://github.com/guides/tell-git-your-user-name-and-email-address for details). For example: git config --global user.email mad.vooo@gmail.com} exit 1 rescue Jeweler::NoGitHubUser $stderr.puts %Q{No github.user found in ~/.gitconfig. Please tell git about your GitHub account (see http://github.com/blog/180-local-github-config for details). For example: git config --global github.user defunkt} exit 1 rescue Jeweler::NoGitHubToken $stderr.puts %Q{No github.token found in ~/.gitconfig. Please tell git about your GitHub account (see http://github.com/blog/180-local-github-config for details). For example: git config --global github.token 6ef8395fecf207165f1a82178ae1b984} exit 1 rescue Jeweler::FileInTheWay $stderr.puts "The directory #{github_repo_name} already exists. Maybe move it out of the way before continuing?" exit 1 end
true
55d35ac5a15c44a235486e798f5a788f5987cd2a
Ruby
imurchie/checkers
/lib/piece.rb
UTF-8
1,955
3.296875
3
[ "MIT" ]
permissive
module Checkers class Piece attr_reader :color, :row, :col def initialize(color, board, position, directions) @color, @board = color, board @row = position[0] @col = position[1] @directions = directions end def available_moves moves = jump_moves moves += slide_moves if moves.empty? moves end def slide_moves moves = [] directions.each do |dir| next_row = row.send(dir, 1) move_offsets(row, col).each do |offset| if Board.on_board?(next_row, col + offset) && board[next_row, col + offset].nil? moves << [next_row, col + offset] end end end moves end def jump_moves moves = [] directions.each do |dir| move_offsets(row, col).each do |offset| next_row = row.send(dir, 1) next unless Board.on_board?(next_row, col + offset) neighbor = board[next_row, col + offset] next if neighbor.nil? || neighbor.color == color row_n = neighbor.row.send(dir, 1) col_n = neighbor.col + offset if Board.on_board?(row_n, col_n) && board[row_n, col_n].nil? moves << [row_n, col_n] end end end moves end def set_position(row, col) @row = row @col = col end def make_king @directions = [:+, :-] end def king? directions.length == 2 end def to_s "Piece: #{color} @ (#{row}, #{col})" end def inspect to_s end def dup(new_board) Piece.new(color, new_board, [row, col], directions) end private attr_reader :board, :directions def move_offsets(row, col) offsets = [] directions.each do |dir| offsets += [-1, 1].select do |offset| Board.on_board?(row.send(dir, 1), col + offset) end end offsets end end end
true
43ce8fb1b6f3a35a2e730959efedd2e489a95593
Ruby
chinnurtb/rtb_decode
/lib/rtb_decode/ADExchange/gadx.rb
UTF-8
1,010
2.796875
3
[ "MIT" ]
permissive
module Rtbdecode module ADExchange class Gadx < Base def initialize(*args) config = args.shift @encryption_key = config.gadx[:e_key].unpack("m")[0] end def decode_price(final_message) decoded = final_message.tr("-_", "+/").unpack("m")[0] # split message into 3 parts: initialization vector, encrypted price and signature iv, p, sig = split_src decoded # generate padding (use first 8 bytes only) pad = price_padding iv # p XOR pad, then convert to 64-bit integer price = price_xor_pads(p, pad) price end def split_src(src) iv = src[0,16] enc_price = src[16,8] signature = src[24,4] [iv,enc_price,signature] end def price_xor_pads(p1, p2) p1s = p1.unpack("NN") p2s = p2.unpack("NN") (p1s[0] ^ p2s[0]) * 4294967296 + (p1s[1] ^ p2s[1]) end end # class Gadx end #module ADExchange end #module Rtbdecode
true
8d822e5bf04d73ad68ea9d394c4c850eaec0d9c5
Ruby
spatchcock/math-function
/lib/math_function/function.rb
UTF-8
2,855
3.109375
3
[ "MIT" ]
permissive
module Math class Function attr_accessor :place_holders def initialize(options={},&block) if block_given? @function = block @variable = nil @place_holders = [] initialize_place_holders &block else raise ArgumentError, "No block given" end set options unless options.empty? end def variable @variable end def variable=(symbol_or_string) raise ArgumentError, "#{symbol_or_string} is not a valid variable. Must be one of #{@place_holders.join(",")}" unless is_place_holder?(symbol_or_string) @variable = symbol_or_string.to_sym end def parameters @place_holders.reject {|p| p == @variable } end def set(options={}) options.each { |var,value| self.send("#{var}=",value) } return self end def evaluate(options={}) set options unless options.empty? instance_eval(&@function) end def distribution(range=[],options={}) raise ArgumentError, "range is not an Array or Range object" unless range.is_a?(Array) || range.is_a?(Range) set options unless options.empty? Distribution.new do |distribution| distribution.x = range.to_a distribution.y = distribution.x.map do |x| set(variable => x) if @variable evaluate end end end def integrate(from,to,delta,options={}) scale = Distribution.scale(from,to,delta) distribution(scale,options).integrate end def absolute_difference(target,options={}) set options unless options.empty? (evaluate - target).abs end protected UNDEFINED_VARIABLE_REGEX = /undefined local variable or method `(.*)'/ def initialize_place_holders(&block) value = nil until value.is_a?(Numeric) do begin value = instance_eval(&block) rescue => error if UNDEFINED_VARIABLE_REGEX.match(error.inspect) initialize_place_holder($1) else string = "WARNING: This exception may have been generated because the stated function uses " string += "one of the following reserved phrases as a placeholder #{methods.join(",")}.\n\n" string += "Please check the function for invalid placeholders." raise error.exception(error.message + "\n\n" + string) end end end end def initialize_place_holder(string) @place_holders << string.to_sym instance_variable_set("@#{string}", 1) define_singleton_method(string.to_sym) { instance_variable_get("@#{string}") } define_singleton_method("#{string}=") { |val| instance_variable_set("@#{string}",val) } end def is_place_holder?(string_or_symbol) @place_holders.include?(string_or_symbol.to_sym) end end end
true
ab466c7cd58dcb0755dfd399211642fbbab846e7
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/rna-transcription/d1be8065f58a49fab9b4c08d6bf47edc.rb
UTF-8
435
3.3125
3
[]
no_license
class RibonucleicAcid def initialize(string) @string = string end def to_s @string end def ==(object) object.to_s == @string end end class String alias :old_equals :== def ==(that) if that.kind_of?(RibonucleicAcid) that == self else old_equals(that) end end end class DeoxyribonucleicAcid < RibonucleicAcid def to_rna RibonucleicAcid.new(@string.gsub("T","U")) end end
true
35d2d22bb1708182f76bf01fb8e65228537e311b
Ruby
kaz29/candycane
/scripts/gloc2gettext.rb
UTF-8
854
2.953125
3
[]
no_license
#!/usr/bin/ruby master_file = "/Users/kabayaki91/ruby/redmine-0.8.1/lang/en.yml" local_file = "/Users/kabayaki91/ruby/redmine-0.8.1/lang/ca.yml" class Gloc2gettext def Gloc2gettext.parse(fname) tmpmap = Hash.new File.open(fname){|f| i = 0; f.each_line do |line| i += 1 next if i < 1 # skip the header part. values = line.split(/\:\s/) next if values.count < 2 tmpmap.store values[0], values[1].strip.gsub("\"","\\\"") end } return tmpmap end end # extract english file eng_map = Gloc2gettext.parse(master_file) loc_map = Gloc2gettext.parse(local_file) dup = Hash.new eng_map.each do |key, value| next if dup.key? value dup.store value, 1 # based on enlgish message puts "# " + key puts "msgid \"" + value + "\"" puts "msgstr \"" + loc_map[key] + "\"" puts "" end
true
5874f9abeb78c0f096a0042de2f935c145b00f16
Ruby
kriom/ray
/test/scene_test.rb
UTF-8
3,781
2.765625
3
[ "Zlib" ]
permissive
require File.expand_path(File.dirname(__FILE__)) + '/helpers.rb' context "a scene" do setup do always_proc = @always_proc = Proc.new {} @game = a_small_game @game.scene(:test) { always { exit! } } @game.scene(:other) { always { exit! } } @game.scene(:normal) { always { always_proc.call } } @game.registered_scene :test end asserts(:name).equals :test asserts(:event_runner).equals { @game.event_runner } asserts(:animations).kind_of Ray::AnimationList asserts(:frames_per_second).equals 60 context "rendered with a custom rendering block" do hookup do @render_proc = proc { |win| } stub(@render_proc).call topic.render { |win| @render_proc.call(win) } topic.render @game.window end asserts("the proc") { @render_proc }.received(:call) { @game.window } end context "cleaned up with a custom clean_up block" do hookup do @clean_up_proc = proc { } stub(@clean_up_proc).call topic.clean_up { @clean_up_proc.call } topic.clean_up end asserts("the proc") { @clean_up_proc }.received :call end context "after changing framerate" do hookup{ topic.frames_per_second = 250 } asserts(:frames_per_second).equals 250 end context "run once" do hookup do %w[clean_up render].each do |meth| stub(topic).__send__(meth) end stub(topic.animations).update @game.scenes << :test @game.run end asserts(:animations).received :update asserts_topic.received :clean_up asserts_topic.received(:render) { @game.window } end context "run using #run_scene" do setup do @game.scenes << :test scene = @game.registered_scene :other %w[clean_up render].each do |meth| stub(scene).__send__(meth) end topic.run_scene :other, :argument scene end asserts(:scene_arguments).equals [:argument] asserts_topic.received :clean_up asserts_topic.received(:render) { @game.window } asserts("current scene") { @game.scenes.current }.equals { @game.registered_scene :test } end context "run using #run_tick" do setup do scene = @game.registered_scene :normal scene.register_events proxy(scene).clean_up proxy(scene).render proxy(@always_proc).call proxy(scene.animations).update scene.run_tick(false) scene end denies_topic.received :clean_up asserts_topic.received(:render) { @game.window } asserts("always block") { @always_proc }.received(:call) asserts(:animations).received :update end context "after #exit!" do hookup do @game.scenes << :test topic.exit! end asserts("current scene") { @game.scenes.current }.nil end end class MyScene < Ray::Scene scene_name :my_scene end context "an instance of a scene subclass" do setup do @game = a_small_game MyScene.bind(@game) @game.registered_scene :my_scene end asserts_topic.kind_of MyScene asserts(:name).equals :my_scene context "run once" do hookup do %w[setup render clean_up].each do |meth| stub(topic).__send__(meth) end stub(topic).register { topic.always { topic.exit! } } @game.push_scene :my_scene, :argument @game.run end asserts_topic.received :setup, :argument asserts_topic.received :register asserts_topic.received :clean_up asserts_topic.received(:render) { @game.window } end end class RandomScene < Ray::Scene end context "a game with a random scene bound" do setup do game = a_small_game proxy(game).scene RandomScene.bind game game end asserts_topic.received :scene, :random_scene, RandomScene end run_tests if __FILE__ == $0
true
74c375df413dcd6d4c9fc97bd3c4919d516b8106
Ruby
molawson/repeatable
/lib/repeatable/expression/set.rb
UTF-8
950
2.703125
3
[ "MIT" ]
permissive
# typed: strict module Repeatable module Expression class Set < Base abstract! sig { returns(T::Array[Expression::Base]) } attr_reader :elements sig { params(elements: T.any(Expression::Base, T::Array[Expression::Base])).void } def initialize(*elements) @elements = T.let(elements.flatten.uniq, T::Array[Expression::Base]) end sig { params(element: T.untyped).returns(Repeatable::Expression::Set) } def <<(element) elements << element unless elements.include?(element) self end sig { params(other: Object).returns(T::Boolean) } def ==(other) other.is_a?(self.class) && elements.size == other.elements.size && other.elements.all? { |e| elements.include?(e) } end private sig { override.returns(T::Array[Types::SymbolHash]) } def hash_value elements.map(&:to_h) end end end end
true
a46153d780e17e035182de7b7d5d1ba96047ee49
Ruby
mikamai/rxp-hpp-ruby
/lib/rxp_hpp.rb
UTF-8
946
2.59375
3
[]
no_license
# frozen_string_literal: true require 'hpp_request' require 'hpp_response' require 'utils/validator' # RealexHpp class for converting HPP requests and responses to and from JSON. # This class is also responsible for validating inputs, generating defaults # and encoding parameter values. class RealexHpp include Validator def initialize(secret) @secret = secret end def request_to_json(hpp_request) hpp_request .build_hash(@secret) .encode .to_json end def request_from_json(json, encoded = true) hpp_request = HppRequest.new json hpp_request.decode if encoded hpp_request end def response_to_json(hpp_response) hpp_response .build_hash(@secret) .encode .to_json end def response_from_json(json, encoded = true) hpp_response = HppResponse.new json hpp_response.decode if encoded validate_response hpp_response, @secret hpp_response end end
true
b470e3b737ac32535d782343d23441f3305e75f8
Ruby
zerolive/simple_sinatra_rest_api
/spec/app_spec.rb
UTF-8
4,064
2.59375
3
[]
no_license
require 'spec_helper' require 'json' describe 'Simple app' do before do Widgets.reset end context 'GET /' do it 'returns with the list of witgets' do widgets = [{ :id => 1, :name => "First Widget"}, { :id => 2, :name => "Second Widget"}] get '/' expect(last_response.body).to eq(widgets.to_json) expect(last_response.status).to eq 200 end end context 'POST /widget' do describe 'with a name param' do it "adds a new widget" do widget_name = "Third widget" post '/widget', { name: "Third widget" } expect(last_response.status).to eq 201 end end describe 'with missing name param' do it "retrieves bad request" do widget_name = "Third widget" post '/widget' expect(last_response.status).to eq 400 end end describe 'with empty name param' do it "retrieves bad request" do widget_name = "Third widget" post '/widget', { name: "" } expect(last_response.status).to eq 400 end end end context 'GET /widget' do describe 'with right params' do it 'returns a specific widget with an id' do widget = { :id => 1, :name => "First Widget"} get '/widget', { :id => 1 } expect(last_response.body).to eq(widget.to_json) end it 'returns a different widget with another id' do widget = { :id => 2, :name => "Second Widget"} get '/widget', { :id => 2 } expect(last_response.body).to eq(widget.to_json) end end describe 'with missing id param' do it "retrieves bad request" do get '/widget' expect(last_response.status).to eq(400) end end describe 'with empty id param' do it "retrieves bad request" do get '/widget', { id: '' } expect(last_response.status).to eq(400) end end describe 'with non-existent id' do it "responses with a not found request" do get '/widget', { id: :id } expect(last_response.status).to eq(404) end end end context 'PUT /widget' do describe 'with right params' do it "updates the name of widget" do put '/widget', { :id => 1, :name => "new name" } expect(last_response.status).to eq 200 end end describe 'with missing id param' do it 'responses with a bad request' do put 'widget', { name: "new name" } expect(last_response.status).to eq 400 end end describe 'with missing name param' do it 'responses with a bad request' do put 'widget', { id: 1 } expect(last_response.status).to eq 400 end end describe 'with empty id param' do it 'responses with a bad request' do put 'widget', { id: '', name: "new name" } expect(last_response.status).to eq 400 end end describe 'with empty name param' do it 'responses with a bad request' do put 'widget', { id: 1, name: "" } expect(last_response.status).to eq 400 end end describe 'with non-existent id' do it 'responses with a not found request' do put 'widget', { id: :id, name: "new_name" } expect(last_response.status).to eq 404 end end end context 'DELETE /widget' do describe 'with an existent id' do it "deletes a widget" do delete '/widget', { id: 2 } expect(last_response.status).to eq 200 end end describe 'with non-existent id' do it 'responses with a not found request' do delete '/widget', { id: :id } expect(last_response.status).to eq 404 end end describe 'with missing id param' do it 'responses with a bad request' do delete '/widget' expect(last_response.status).to eq 400 end end describe 'with empty id param' do it 'responses with a bad request' do delete '/widget' expect(last_response.status).to eq 400 end end end end
true
38d1b177e0ea65e9379ea212a97e93c6ed87393f
Ruby
winch/osm-projects
/sqlite/test/test_node.rb
UTF-8
3,066
2.828125
3
[]
no_license
#!/usr/bin/env ruby #-- # $Id$ # #Copyright (C) 2007 David Dent # #This program is free software; you can redistribute it and/or #modify it under the terms of the GNU General Public License #as published by the Free Software Foundation; either version 2 #of the License, or (at your option) any later version. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. # #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. require 'test/unit' require File.dirname(__FILE__) + '/../primative.rb' class TestNode < Test::Unit::TestCase #tests == method def test_node_equal a = Node.new(1, 2) a.id = 123 a.tags.push(['k', 'v']) a.tags.push(['v', 'k']) #b has different order tags b = Node.new(1, 2) b.id = 123 b.tags.push(['v', 'k']) b.tags.push(['k', 'v']) #c has different lon c = Node.new(1, 3) c.id = 123 c.tags.push(['k', 'v']) c.tags.push(['v', 'k']) #d has different tags d = Node.new(1, 2) d.id = 123 d.tags.push(['v', 'k']) d.tags.push(['k', 'v']) d.tags.push(['kk', 'vv']) #e has different id e = Node.new(1, 2) e.id = 321 e.tags.push(['k', 'v']) e.tags.push(['v', 'k']) #tests assert_equal(true, a == b) assert_equal(true, b == a) assert_equal(false, a == c) assert_equal(false, c == a) assert_equal(false, a == d) assert_equal(false, d == a) assert_equal(false, a == e) end #tests to_xml method def test_node_to_xml #node with tags a = Node.new(1, 2) a.id = 123 a.tags.push(['key', 'value & value']) a.tags.push(['highway', 'footway']) #node without tags b = Node.new(3, 4) b.id = 456 #tests xml = a.to_xml.split("\n") assert_equal(4, xml.length) assert_equal(' <node id="123" lat="1" lon="2">', xml[0]) assert_equal(' <tag k="key" v="value &amp; value"/>', xml[1]) assert_equal(' <tag k="highway" v="footway"/>', xml[2]) assert_equal(' </node>', xml[3]) xml = b.to_xml.split("\n") assert_equal(1, xml.length) assert_equal(' <node id="456" lat="3" lon="4"/>', xml[0]) #node with action a.action = 'delete' b.action = 'modify' #tests xml = a.to_xml.split("\n") assert_equal(4, xml.length) assert_equal(' <node id="123" action="delete" lat="1" lon="2">', xml[0]) xml = b.to_xml.split("\n") assert_equal(1, xml.length) assert_equal(' <node id="456" action="modify" lat="3" lon="4"/>', xml[0]) end end
true
ea5cc154ffc09e994fd20b0c4fbdae0e7778d724
Ruby
EgleMekaite/ruby-exercises
/ruby1.rb
UTF-8
824
3.671875
4
[]
no_license
puts "What is your full name?" full_name=gets.chomp puts "Hi, #{full_name}!" puts "What is your street address?" street_address = gets.chomp #puts street_address.split(' ') first_name = full_name.split(' ').first last_name = full_name.split(' ').last block_letter = street_address.split(' ').first.split('').last #street_number = street_address.split(' ').first.split('').tap(&:pop).join street_name = street_address.split(' ').first street_number = street_name.chomp(block_letter) block_letters = Hash[ "A" => "A-Block", "B" => "B-Block", "C" => "C-Block", "D" => "D-Block" ] block_letter_value = block_letters[block_letter] puts "Your first name is #{first_name}." puts "Your last name is #{last_name}." puts "Your street number is #{street_number}." puts "Your street letter means: #{block_letter_value}."
true