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
20d1d0cb20a2b2d2e588f8bd73d5f2751e93c66c
Ruby
jemmaissroff/ractor-sudoku
/sudoku-3.rb
UTF-8
3,533
3.328125
3
[]
no_license
class Candidate attr_accessor :ractor def initialize @ractor = Ractor.new do value = Ractor.receive loop { Ractor.yield value } end end end class Group attr_reader :candidate_ractors def initialize(candidate_ractors) @candidate_ractors = candidate_ractors Ractor.new candidate_ractors do |candidate_ractors| value = false 8.times do r, value = Ractor.select(*candidate_ractors) candidate_ractors.delete r puts "deleted #{r} #{value}" break if value end puts "22" candidate_ractors.each { puts _1; _1.send !value } Ractor.yield true end end end class Board attr_accessor :board, :groups def initialize @board = 3.times.map do |row| 3.times.map do |col| 3.times.map do |cell_row| 3.times.map do |cell_col| 9.times.map do |value| { row: row, col: col, cell_row: cell_row, cell_col: cell_col, value: value, ractor: Candidate.new.ractor } end end.flatten end.flatten end.flatten end.flatten end def make_groups rows = board.group_by do |candidate| (candidate[:row] * 3 + candidate[:cell_row]) end.values.map do |row| row.group_by do |candidate| candidate[:value] end end.map(&:values).flatten(1) cols = board.group_by do |candidate| (candidate[:col] * 3 + candidate[:cell_col]) end.values.map do |row| row.group_by do |candidate| candidate[:value] end end.map(&:values).flatten(1) cells = board.group_by do |candidate| (candidate[:row] * 3 + candidate[:col]) end.values.map do |row| row.group_by do |candidate| candidate[:value] end end.map(&:values).flatten(1) # Only one not by value squares = board.group_by do |candidate| (candidate[:row] * 3 + candidate[:col]) end.values.map do |row| row.group_by do |candidate| (candidate[:cell_row] * 3 + candidate[:cell_col]) end end.map(&:values).flatten(1) @groups = (rows + cols + cells + squares).map do |group| Group.new(group.map { _1[:ractor] }) end end def send(row, col, cell_row, cell_col, value) find(row, col, cell_row, cell_col, value)[:ractor].send true end def find(row, col, cell_row, cell_col, value) board.select do |square| square[:row] == row && square[:col] == col && square[:cell_row] == cell_row && square[:cell_col] == cell_col && square[:value] == value end.first end end board = Board.new board.send(0,0,0,1,7) board.send(0,0,1,1,6) board.send(0,0,2,0,2) board.send(0,1,0,1,2) board.send(0,1,2,0,8) board.send(0,2,0,1,4) board.send(0,2,0,2,6) board.send(0,2,1,0,8) board.send(0,2,1,1,0) board.send(0,2,2,0,7) board.send(0,2,2,1,1) board.send(0,2,2,2,5) board.send(1,0,0,1,8) board.send(1,0,0,2,4) board.send(1,0,1,0,7) board.send(1,0,1,1,1) board.send(1,1,0,1,0) board.send(1,1,0,2,7) board.send(1,1,2,0,1) board.send(1,1,2,1,3) board.send(1,2,1,1,5) board.send(1,2,1,2,0) board.send(1,2,2,0,4) board.send(1,2,2,1,8) board.send(2,0,0,0,6) board.send(2,0,0,1,0) board.send(2,0,0,2,7) board.send(2,0,1,1,5) board.send(2,0,1,2,8) board.send(2,0,2,0,4) board.send(2,0,2,1,3) board.send(2,1,0,2,2) board.send(2,1,2,1,8) board.send(2,2,0,2,8) board.send(2,2,1,1,6) board.send(2,2,1,2,7) ### # board.send(0,0,0,0,8)
true
d2ef3b6b216f67de46f4fa4f4f23f8cd661dc8a9
Ruby
DialBird/e_anki_dsl
/main_dsl.rb
UTF-8
929
2.578125
3
[]
no_license
# frozen_string_literal: true require 'bundler/setup' require 'active_record' require 'pry' require './schema' Dir.glob('./lib/ext/*.rb').each { |f| require f } lambda { vocabs = [] define_method :remember do |name, &block| v = Vocab.new(name: name) block.call v vocabs << v end define_method :each_vocabs do |&block| vocabs.each do |vocab| block.call vocab end end class CleanObject attr_accessor(*Vocab::ATTRIBUTES) end }.call load './vocab_list.rb' # main if $PROGRAM_NAME == __FILE__ each_vocabs do |vocab| ActiveRecord::Base.transaction do vocab.save! end puts "#{vocab.name.red} is perfectly registered!" rescue ActiveRecord::RecordInvalid => e if e.message.include?('has already been taken') puts "Sorry but #{e.record.name.red} is already registered" else puts "Error with #{e.record.name.red}: #{e.message}" end end end
true
68785e87825a911d9c28e1d301bc4920e5845bcc
Ruby
alphagov/gsd-publish-data
/app/models/year_month.rb
UTF-8
960
3.171875
3
[]
no_license
class YearMonth class Serializer < ActiveRecord::Type::Value def type :year_month end def cast(value) value end def serialize(value) value ? value.date : nil end def deserialize(value) case value when Date YearMonth.new(value.year, value.month) when String date = Date.parse(value) YearMonth.new(date.year, date.month) end end end def initialize(year, month) @year = year.to_i @month = month.to_i @date = Date.new(@year, @month) end attr_reader :year, :month, :date def ==(other) year == other.year && month == other.month end def to_formatted_s(format = :long_day_month_year) if format == :long_day_month_year end_date = date.end_of_month "#{date.to_formatted_s(:day_excluding_leading_zero)} to #{end_date.to_formatted_s(:long_day_month_year)}" else date.to_formatted_s(format) end end end
true
b0ea72a302155954f0462ff8b47b62e41371fd4c
Ruby
J-Y/RubyQuiz
/ruby_quiz/quiz16_sols/solutions/players/ne_stupid.rb
UTF-8
1,565
3.515625
4
[ "MIT" ]
permissive
class NeoneyeStupid < Player QUEUE = [ :scissors, :rock, :paper ] def initialize( opponent ) super @history = [] @count = 0 @lose = [] @draw = [] @win = [] end def qs QUEUE.size end def queue(i) QUEUE[i % QUEUE.size] end def chance(level, a, b) (rand(100) < level) ? a : b end def choose @count += 1 # 1st strategy: try all combinations return queue(@count-1) if @count <= qs # 2nd strategy: play on those where we won if @count <= qs*2 you, them, wld = @history[@count - qs - 1] return case wld when :draw: chance(80, them, queue(@count - 1)) when :lose: them when :win: you end end # 3rd strategy: what happened if @count == (qs*2)+1 #puts "status1: win=#{@win.size} " + # "draw=#{@draw.size} lose=#{@lose.size}" end if @count <= qs*3 you, them, wld = @history[@count - qs*2 - 1] return case wld when :draw: chance(80, them, queue(@count - 1)) when :lose: them when :win: you end end if @count == (qs*3)+1 #puts "status2: win=#{@win.size} " + # "draw=#{@draw.size} lose=#{@lose.size}" end you, them, wld = @history.last choice = case wld when :draw: chance(80, them, queue(@count - 1)) when :lose: them when :win: you end if @lose.size > @win.size return them end return choice end def result( you, them, win_lose_or_draw ) case win_lose_or_draw when :lose: @lose << [you, them] when :draw: @draw << [you, them] when :win: @win << [you, them] end @history << [you, them, win_lose_or_draw] end end
true
082984a9fa980a09fce2499c45e051ab8c3d1910
Ruby
vybirjan/MI-RUB-ukoly
/brainfuck/lib/bf_c_translator.rb
UTF-8
1,208
3.359375
3
[]
no_license
require_relative 'brainfuck_ast.rb' class BrainfuckCTranslator def self.to_c_source(ast) source = "" source << PROLOG element = ast tabcount = 1 while(element != nil) source << tabs(tabcount) case element when IncrementValue source << "memory[pointer]++;\n" when DecrementValue source << "memory[pointer]--;\n" when IncrementPointer source << "pointer++;\n" when DecrementPointer source << "pointer--;\n" when ReadInput source << "memory[pointer] = getchar();\n" when PrintValue source << "putchar(memory[pointer]);\n" when LoopStart source << "while(memory[pointer] != 0) {\n" tabcount = tabcount + 1 when LoopEnd source << "}\n" tabcount = tabcount - 1 end element = element.next end source << EPILOG end private def self.tabs(count) ret = "" 1.upto(count) do ret << "\t" end return ret end PROLOG = "#include <stdio.h>\n\nint main(void)\n{\n\tstatic char memory[30000];\n\tint pointer = 0;\n" EPILOG = "\treturn 0;\n}" end
true
bf39fa9f3f26647e6764de680afa70616f691b40
Ruby
simp/pupmod-simp-simp_rsyslog
/lib/puppet/functions/simp_rsyslog/format_options.rb
UTF-8
2,084
2.84375
3
[ "Apache-2.0" ]
permissive
# Formats a passed log options hash into a form that is appropriate for an # Expression Filter-based Rsyslog 7 rule. # # @see https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/System_Administrators_Guide/s1-basic_configuration_of_rsyslog.html Basic Configuration of Rsyslog # # @author Trevor Vaughan <tvaughan@onyxpoint.com> # Puppet::Functions.create_function(:'simp_rsyslog::format_options') do # @param opts # The options hash. # # * All entries will be combined with a logical ``OR`` # * **NOTE** Only the documented Hash keys will be respected # # @option options [Array[String]] 'programs' logged daemon names # @option options [Array[String]] 'facilities' syslog facilities # @option options [Array[String]] 'priorities' syslog priorities # @option options [Array[String]] 'msg_starts' strings the message starts with # @option options [Array[String]] 'msg_regex' regular exprssion match on the message # # @return [String] # A formatted entry suitable for injecting into an ``if`` statement in # Rsyslog 7 # dispatch :format_options do param 'Hash', :opts end def format_options(opts) valid_options = { 'programs' => { :start => '($programname == ', :end => ')' }, 'facilities' => { :start => 'prifilt(', :end => ')' }, 'msg_starts' => { :start => '($msg startswith ', :end => ')' }, 'msg_regex' => { :start => 're_match($msg, ', :end => ')' } } return_str = [] Array(opts['facilities']).each do |facility| unless facility.include?('.') fail('All facility entries must be of the form "facility.priority"') end end valid_options.keys.each do |opt| Array(opts[opt]).each do |value| return_str << valid_options[opt][:start] + "'" + value + "'" + valid_options[opt][:end] end end if return_str.empty? fail('Did not find any valid content in the passed Options') end return return_str.join(' or ') end end
true
bb61949e0058c335615d74c86b8002d4e80bf7ed
Ruby
NickLindeberg/parkween
/app/services/google_geolocation_service.rb
UTF-8
503
2.5625
3
[]
no_license
class GoogleGeolocationService def get_geolocation_coordinates get_json("/geolocation/v1/geolocate?key=#{ENV['GOOGLE_API_KEY']}")[:location] #this will return the value of location{:lat => x, :lng=>x} end private def conn Faraday.new(url:"https://www.googleapis.com") do |faraday| faraday.params["key"] = ENV['GOOGLE_API_KEY'] faraday.adapter Faraday.default_adapter end end def get_json(url) JSON.parse(conn.post(url).body, symbolize_names: true) end end
true
d2dff1df2c6d1d090c7782197a01b99bffbb6ca2
Ruby
contiguity/playskull
/cinch-playskull/lib/cinch/plugins/skullgame.rb
UTF-8
20,566
2.65625
3
[]
no_license
require 'cinch' require 'set' require_relative 'game' $pm_users = Set.new module Cinch class Message old_reply = instance_method(:reply) define_method(:reply) do |*args| if self.channel.nil? && !$pm_users.include?(self.user.nick) self.user.send(args[0], true) else old_reply.bind(self).(*args) end end end end module Cinch class User old_send = instance_method(:send) define_method(:send) do |*args| old_send.bind(self).(args[0], !$pm_users.include?(self.nick)) end end module Plugins class SkullGame include Cinch::Plugin def initialize(*args) super @active_game = Game.new @channel_name = config[:channel] end match /join/i, :method => :join match /leave/i, :method => :leave match /start/i, :method => :start # match /disks/i, :method => :reply_with_disk_choices match /diskcount (\d)/, :method=> :set_disk_count match /shuffle/, :method => :set_shuffle match /place (\d)/i, :method => :place_disk match /play (\d)/i, :method => :place_disk match /raise$/i, :method => :raise_bid match /raise (\d+)/i, :method => :raise_bid_number match /bid$/i, :method => :raise_bid match /bid (\d+)/i, :method => :raise_bid_number match /pass/i, :method => :pass_bid match /flip (.+)/i, :method => :flip_single match /remove (\d)/i, :method => :remove_chosen_disk match /help/i, :method => :help match /rules/i, :method => :rules match /who/i, :method => :show_players_in_game match /nextround/i, :method => :nextround match /forcereset/i, :method => :forcereset match /reset/i, :method => :forcereset #all players can reset if they're in the game match /infodebug/i, :method => :info match /status/i, :method => :status def help(m) User(m.user).send '--------Basic commands--------' User(m.user).send '!help to see this help screen' User(m.user).send '!join to join a game' User(m.user).send '!leave to leave a game' User(m.user).send '!start to start a game' User(m.user).send '----------------' User(m.user).send '!place [num] to place a disk (see your private message for numbers)' User(m.user).send '!bid [num] to bid' User(m.user).send '!bid to bid the next higher number' User(m.user).send '!pass to pass' User(m.user).send '!flip [name] to flip another players disk (yours are autoflipped' User(m.user).send '!remove [num] to remove a disk if you autoflipped a skull' User(m.user).send '----------------' end def rules(m) User(m.user).send '--------Basic rules--------' User(m.user).send 'Based on skull, players have 4 disks (3 roses and 1 skull)' User(m.user).send 'On a players turn, they choose and place a disk face down' User(m.user).send 'A player may choose to start bidding instead of placing a disk' User(m.user).send 'From then on, players must increase the bid if they want to continue' User(m.user).send 'If a player passes, they are out of the bidding.' User(m.user).send 'The last player in the bidding is the revealer' User(m.user).send '--------Revealing disks--------' User(m.user).send 'A player wants to reveal as many disks as the bid, without flipping a skull' User(m.user).send 'The first disks the player flips must be their own.' User(m.user).send 'If no skull, then one by one, they flip disks of other players.' User(m.user).send 'If they succeed in flipping only flowers, they flip their mat over' User(m.user).send 'If their mat was already flipped, they win instead, and the game is over.' User(m.user).send '--------Losing disks--------' User(m.user).send 'If a player flips over one of their own disks as a skull' User(m.user).send 'then the player may choose which disk of theirs to remove from the game' User(m.user).send 'If a player flips over another players skull, it is randomly chosen' User(m.user).send 'A player with no disks is out of the game.' User(m.user).send '(If only one player remains, that player wins)' User(m.user).send '----------------' end def join(m) if @active_game.started User(m.user).send 'Game already started' elsif @active_game.user_hash.include?(m.user.nick) Channel(@channel_name).send " #{m.user.nick} already joined. Game has #{@active_game.players_joined} player(s)." else @active_game.add_user(m.user) Channel(@channel_name).send " #{m.user.nick} joined. Game now has #{@active_game.players_joined} player(s)." end end def leave(m) if @active_game.started User(m.user).send 'Game already started' else @active_game.remove_user(m.user) Channel(@channel_name).send "#{m.user.nick} left. Game now has #{@active_game.players_joined} player(s)." end end def show_players_in_game() #m Channel(@channel_name).send "Players in game: #{@active_game.user_hash.keys.join(', ')}" end def set_disk_count(m,num_disks_input) if @active_game.started User(m.user).send "Game already started" return end num_disks=num_disks_input.to_i if (num_disks<=0) User(m.user).send "Invalid number of disks chosen" return elsif (num_disks>5) User.(m.user).send "Maximum 5 disks for each player" return end @active_game.disks_for_each_player=num_disks User(m.user).send "Preparing #{num_disks} disks for each player." end def set_shuffle(m) if @active_game.shuffle_names @active_game.shuffle_names=false Channel(@channel_name).send "Shuffling play order is off" else @active_game.shuffle_names=true Channel(@channel_name).send "Shuffling play order is on" end end def start(m) if @active_game.started User(m.user).send 'Game has started already' elsif @active_game.players_joined<2 User(m.user).send 'Need at least 2 players' else @active_game.setup_game @active_game.user_hash.keys.each do |single_name| current_player=Player.new(@active_game.disks_for_each_player) current_player.set_name(single_name) current_player.set_user(@active_game.user_hash[single_name]) @active_game.player_hash[single_name]=current_player end Channel(@channel_name).send "Game has started with #{@active_game.playing_user_names.join(', ')}." Channel(@channel_name).send "Use !place to start placing." @active_game.round_order=@active_game.playing_user_names.dup @active_game.turn_queue=@active_game.round_order.dup self.start_round() end end def nextround(m) self.start_round end def start_round return if !@active_game.started #may try to start round after game has been won round_order_string=@active_game.round_order.join(', ') Channel(@channel_name).send "A new round has started (Turn order is #{round_order_string})." @active_game.turn_queue=@active_game.round_order.dup @active_game.bid=0 @active_game.disks_placed=0 @active_game.user_hash.keys.each do |single_name| single_player=@active_game.player_hash[single_name] single_player.all_disks.shuffle! single_player.table_disks=[] max_disk_num=single_player.all_disks.length-1 puts "Player #{single_player} is has 0 to #{max_disk_num} disks" single_player.remaining_disk_nums=(0..max_disk_num).to_a.map! { |num| num.to_s } puts "Player has disks #{single_player.remaining_disk_nums}" end @active_game.revealer=nil @active_game.revealer_remove=false @active_game.user_hash.values.each { |single_user| puts "Showing disk choices for #{single_user.nick}" } @active_game.user_hash.values.each { |single_user| self.reply_with_disk_choices(single_user) } end def reply_with_disk_choices(input_user) #current_user=@active_game.user_hash[input_name] current_name=input_user.nick current_player=@active_game.player_hash[current_name] total_disks=current_player.all_disks.length-1 #top disk number puts "===Replying with #{total_disks} for #{current_name}" disk_message=(0..total_disks).collect{ |num| if (current_player.remaining_disk_nums.include?(num.to_s) || @active_game.revealer_remove) "#{num} #{current_player.all_disks[num]}" else "#{num}" end }.join(", ") puts "Trying to send message #{disk_message}" input_user.send("===#{disk_message}===") end def place_disk(m, num) #Channel(@channel_name).send "Got place command for #{num} from #{m.user.nick}" return unless @active_game.user_in_started_game(m.user) current_player_name=@active_game.turn_queue[0] if current_player_name!=(m.user.nick) Channel(@channel_name).send "It isn't your turn. Wait for #{current_player_name}" return elsif @active_game.bid >0 Channel(@channel_name).send "Can no longer play disks; use !raise to raise the bid" return else current_player=@active_game.get_player_by_user(m.user) if num.to_i>=current_player.all_disks.length Channel(@channel_name).send "You don't have that many disks." elsif current_player.remaining_disk_nums.include?(num) disk_to_place=current_player.all_disks[num.to_i] current_player.table_disks.push(disk_to_place) current_player.remaining_disk_nums.delete(num) @active_game.disks_placed+=1 puts "Played disk #{num.to_i}" #shows the chosen disk self.make_next_turn() else Channel(@channel_name).send "You already played disk #{num}" puts "Can't place disk #{num}, only have disks #{current_player.remaining_disk_nums}" end end end def raise_bid_number(m, input_bid) return unless @active_game.user_in_started_game(m.user) current_player_name=@active_game.turn_queue[0] new_bid=input_bid.to_i if current_player_name!=(m.user.nick) Channel(@channel_name).send "It isn't your turn. Wait for #{current_player_name}" return elsif @active_game.disks_placed==0 Channel(@channel_name).send "There are no disks out. Use !place [number] to place a disk." return elsif new_bid<=@active_game.bid Channel(@channel_name).send "The current bid is #{@active_game.bid}; you must go higher" return elsif new_bid>@active_game.disks_placed Channel(@channel_name).send "There are only #{@active_game.disks_placed} disks, so you can't bid more than #{@active_game.disks_placed}." return else @active_game.bid=new_bid Channel(@channel_name).send "Player #{m.user.nick} bids #{@active_game.bid}" make_next_turn() end end def raise_bid(m) self.raise_bid_number(m, @active_game.bid+1) #raise_bid is another name for this end def remove_name_and_check_for_win(player_name) @active_game.round_order.delete(player_name) Channel(@channel_name).send "Player #{player_name} is out of the game!" if @active_game.round_order.length==1 Channel(@channel_name).send "Player #{@active_game.round_order.pop} wins!" self.reset_game elsif @active_game.round_order.length<1 Channel(@channel_name).send "No one is playing!" end end def make_next_turn() previous_player_name=@active_game.turn_queue.shift @active_game.turn_queue.push(previous_player_name) new_turn_name=@active_game.turn_queue[0] self.reply_with_disk_choices(@active_game.user_hash[new_turn_name]) Channel(@channel_name).send "Turn: #{new_turn_name}, Bid: #{@active_game.bid}" end def pass_bid(m) ##nick? return unless @active_game.user_in_started_game(m.user) current_player_name=@active_game.turn_queue[0] if current_player_name!=(m.user.nick) Channel(@channel_name).send "It isn't your turn. Wait for #{current_player_name}" return end make_next_turn() @active_game.turn_queue.delete(m.user.nick) if @active_game.turn_queue.length>1 Channel(@channel_name).send "Player #{m.user.nick} passes." #Use !reveal (name) to identify return elsif @active_game.turn_queue.empty? Channel(@channel_name).send "Somehow unsure who is revealing." #Use !reveal (name) to identify return end #Here, revealing begins @active_game.revealer=@active_game.turn_queue.pop revealer_player=@active_game.player_hash[@active_game.revealer] revealer_index=@active_game.round_order.find_index(@active_game.revealer) @active_game.round_order.rotate!(revealer_index) unless revealer_index.nil? #rotate so revealer goes first if @active_game.bid< revealer_player.table_disks.length revealed_disks=revealer_player.table_disks.pop(@active_game.bid) else revealed_disks=revealer_player.table_disks.dup end Channel(@channel_name).send "All other players pass..." sleep(1) Channel(@channel_name).send "Player #{@active_game.revealer} reveals #{revealed_disks.join(', ')}." if revealed_disks.include?(:skull) Channel(@channel_name).send "Player #{@active_game.revealer} removes a disk." revealer_player.all_disks.shuffle! #player shuffles disks before looking and removing one @active_game.revealer_remove=true self.reply_with_disk_choices(@active_game.user_hash[@active_game.revealer]) if revealer_player.all_disks.length<=1 remove_name_and_check_for_win(@active_game.revealer) self.start_round return end Channel(@channel_name).send "(Use !remove (number) to remove a disk from the above choices.)" else Channel(@channel_name).send "No skull revealed." @active_game.bid -= revealed_disks.length check_for_bid_completed end end def remove_chosen_disk(m, input_number) return unless @active_game.user_in_started_game(m.user) if !@active_game.revealer_remove Channel(@channel_name).send "Wait for a skull to be revealed to remove a disk." #return elsif m.user.nick!=@active_game.revealer Channel(@channel_name).send "Only the revealer #{@active_game.revealer} can remove a disk." #return else revealer_player=@active_game.player_hash[@active_game.revealer] num_disks=revealer_player.all_disks.length disk_number=input_number.to_i if disk_number<0 or disk_number>num_disks Channel(@channel_name).send "Choose a number from 0 to #{num_disks-1}" return end revealer_player=@active_game.player_hash[@active_game.revealer] chosen_disk=revealer_player.all_disks.delete_at(disk_number) m.user.send("You removed #{chosen_disk}") @active_game.revealer_remove=false if num_disks==1 remove_name_and_check_for_win(@active_game.revealer) end self.start_round #if game is over, won't start end end def flip_single(m, target_player) return unless @active_game.user_in_started_game(m.user) if @active_game.revealer.nil? Channel(@channel_name).send "Flipping disks happens when one player remains. Use !place, !raise, or !pass." return elsif m.user.nick!=@active_game.revealer Channel(@channel_name).send "Only the current revealer (#{@active_game.revealer}) can flip disks" return elsif @active_game.player_hash[target_player].nil? Channel(@channel_name).send "Player #{target_player} is not in the game." return end disk_flipped=@active_game.player_hash[target_player].table_disks.pop if disk_flipped.nil? Channel(@channel_name).send "Player #{target_player} has no disks remaining." return end Channel(@channel_name).send "Revealer #{@active_game.revealer} flips..." sleep(1) if disk_flipped==:skull Channel(@channel_name).send "...a SKULL from #{target_player}!" revealer_player=@active_game.player_hash[@active_game.revealer] disk_removed=revealer_player.all_disks.shuffle!.pop m.user.send("A disk (#{disk_removed}) was randomly removed.") disks_left=revealer_player.all_disks.length if disks_left>0 Channel(@channel_name).send "Player #{@active_game.revealer} has #{disks_left} disks left." else remove_name_and_check_for_win(@active_game.revealer) end self.start_round() else Channel(@channel_name).send "...a ROSE from #{target_player}." @active_game.bid-=1 check_for_bid_completed() end end def check_for_bid_completed if @active_game.bid>0 Channel(@channel_name).send "Flip #{@active_game.bid} more disks." return end Channel(@channel_name).send "Revealer #{@active_game.revealer} has made the bid!." revealer_player=@active_game.player_hash[@active_game.revealer] if revealer_player.mat_flipped Channel(@channel_name).send "Revealer #{@active_game.revealer} has won!" self.reset_game else Channel(@channel_name).send "Revealer now has a flipped mat." revealer_player.mat_flipped=true self.start_round() end end def forcereset(m) #only users in the game can reset it self.reset_game if @active_game.user_in_started_game?(m.user) end def reset_game @active_game=Game.new Channel(@channel_name).send "The game has been reset." end def status(m) return unless @active_game.user_in_started_game(m.user) Channel(@channel_name).send "Current player #{@active_game.turn_queue[0]}" Channel(@channel_name).send "Player order #{@active_game.turn_queue}" Channel(@channel_name).send "Players are seated as #{@active_game.round_order}" Channel(@channel_name).send "Bid is #{@active_game.bid}" @active_game.playing_user_names.each do |single_name| num_disks_played=@active_game.player_hash[single_name].table_disks.length Channel(@channel_name).send "Player #{single_name} has played #{num_disks_played} disks" end if @active_game.revealer.nil? Channel(@channel_name).send "(No revealer yet)" else Channel(@channel_name).send "Revealer is #{@active_game.revealer}" end if @active_game.revealer_remove Channel(@channel_name).send "Waiting for a disk to be removed." Channel(@channel_name).send "Use !remove [num] to remove a disk." end end def info(m) #this gives spoilers, so use for debugging return unless @active_game.user_in_started_game(m.user) self.status(m) @active_game.playing_user_names.each do |single_name| disks_string=@active_game.player_hash[single_name].table_disks.join(', ') Channel(@channel_name).send "Player #{single_name} has played disks #{disks_string}" disks_left_string=@active_game.player_hash[single_name].remaining_disk_nums.join(', ') Channel(@channel_name).send "Player #{single_name} has disks #{disks_left_string}" end end def show_players_in_game(m) Channel(@channel_name).send "#{players_string=@active_game.user_hash.keys.join(', ')}" end end end end
true
381a5b64f10905808d4c866c8ea232a24717bc88
Ruby
toddzal/odin_exercises
/inheritence.rb
UTF-8
1,563
4.03125
4
[]
no_license
module Towable def tow puts "Tow machine go brrrrrr." end end class Vehicle @@vehicle_counter = 0 def initialize (year, make, color) @year = year @make = make @color = color @speed = 0 @@vehicle_counter += 1 end def calc_MPG (miles, gallons) puts "The vehicles miles per gallon is #{miles/gallons}" end def count_vehicles puts "The number of vehicles is #{@@vehicle_counter}" end def accelerate @speed += 10 puts "Your Speed is now #{@speed}" end def decelearate if @speed>0 @speed -= 10 end puts "Your Speed is now #{@speed}" end end class Car < Vehicle attr_accessor :year, :make, :color def initialize(year, make, color) super(year, make, color) end end class Truck < Vehicle include Towable attr_accessor :year, :make, :color, :dual def initialize(year, make, color, dual) super(year, make, color) @dual = dual end end class Student attr_accessor :name def initialize(name, grade) @name = name @grade = grade end def better_grade_than?(comp) @grade > comp.grade end protected def grade @grade end end ford = Car.new(2016, "Ford", "Gray" ) silverado = Truck.new(2020,"Chevy", "Black", false) puts "The make of my car is #{ford.make}" puts "My #{silverado.make} is #{silverado.dual ? "": " not"} a dualie" ford.count_vehicles silverado.tow ford.accelerate ford.accelerate
true
5edec60cf874a796f08c4aec11010861bc23c197
Ruby
pedropereira/curex
/app/entities/rate_value_entity.rb
UTF-8
543
2.6875
3
[]
no_license
# frozen_string_literal: true class RateValueEntity attr_reader :created_at attr_reader :id attr_reader :rate_id attr_reader :updated_at attr_reader :value def initialize(created_at:, id:, rate_id:, updated_at:, value:) @created_at = created_at @id = id @rate_id = rate_id @updated_at = updated_at @value = value end def ==(other) id == other.id && value == other.value && rate_id == other.rate_id && created_at == other.created_at && updated_at == other.updated_at end end
true
d01ac05226af7e3bad4401f47c02bf3affeaf847
Ruby
julieharrow/ecomm-app
/db/seeds.rb
UTF-8
1,251
2.546875
3
[]
no_license
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) Product.create([ {name: 'Macbook', price: 1000.24, description: "Great buy!", promoted: true, stock: 24}, {name: 'Chromebook', price: 800.99, description: "Amazing value!", promoted: true, stock: 11}, {name: 'Surface', price: 1300.89, description: "So unique!", promoted: true, stock: 9}, {name: 'iPad', price: 649.49, description: "Bring it everywhere!", promoted: true, stock: 18} ]) 100.times do Product.create(name: Faker::Commerce.product_name, price: Faker::Commerce.price, description: Faker::Hipster.sentence, promoted: false, stock: Faker::Number.number(2)) end 10.times do Product.create(name: Faker::Commerce.product_name, price: Faker::Commerce.price, description: Faker::Hipster.sentence, promoted: true, stock: Faker::Number.number(2)) end
true
1235bc9ac512fa99cba8c797d0fb7fc155777e18
Ruby
johnhowardroberts/launch-school-ruby-basics-exercises
/return/breakfast1.rb
UTF-8
196
3.1875
3
[]
no_license
def meal return 'Breakfast' end puts meal # Return ensures it prints # prints Breakfast even if return isn't there because method will always execute the last line within it that is executed.
true
5706f87c97d3586d241cefdd3d6ddfcef016bff4
Ruby
rinayumiho/aA-homeworks
/W4D5/solutions.rb
UTF-8
593
3.6875
4
[]
no_license
def longest_fish(arr) # O(n^2) arr.each do |ele| longest = true arr.each do |ele2| if ele2 > ele longest = false break end end return ele if longest end nil # O(nlgn) arr.sort_by! { |a, b| a.length <=> b.length } arr[-1] # O(n) arr.inject { |acc, ele| acc.length < ele.length ? ele : acc } end def slow_dance(str, arr) (0...arr.length).each { |i| return i if str == arr[i] } nil end def constant_dance(str, hash) hash.key?(str) ? hash[str] : nil end
true
0470072301f125b27778d536db0883748f750103
Ruby
monical75/vcloud-rest
/lib/vcloud-rest/vcloud/catalog.rb
UTF-8
4,082
2.71875
3
[ "Apache-2.0" ]
permissive
module VCloudClient class Connection ## # Fetch details about a given catalog def get_catalog(catalogId) params = { 'method' => :get, 'command' => "/catalog/#{catalogId}" } response, headers = send_request(params) description = response.css("Description").first description = description.text unless description.nil? items = {} response.css("CatalogItem[type='application/vnd.vmware.vcloud.catalogItem+xml']").each do |item| items[item['name']] = item['href'].gsub(/.*\/catalogItem\//, "") end { :id => catalogId, :description => description, :items => items } end ## # Friendly helper method to fetch an catalog id by name # - organization hash (from get_organization/get_organization_by_name) # - catalog name def get_catalog_id_by_name(organization, catalogName) result = nil organization[:catalogs].each do |catalog| if catalog[0].downcase == catalogName.downcase result = catalog[1] end end result end ## # Friendly helper method to fetch an catalog by name # - organization hash (from get_organization/get_organization_by_name) # - catalog name def get_catalog_by_name(organization, catalogName) result = nil organization[:catalogs].each do |catalog| if catalog[0].downcase == catalogName.downcase result = get_catalog(catalog[1]) end end result end ## # Fetch details about a given catalog item: # - description # - vApp templates def get_catalog_item(catalogItemId) params = { 'method' => :get, 'command' => "/catalogItem/#{catalogItemId}" } response, headers = send_request(params) description = response.css("Description").first description = description.text unless description.nil? items = [] # manage two different types of catalog items: vAppTemplate and media if response.css("Entity[type='application/vnd.vmware.vcloud.vAppTemplate+xml']").size > 0 response.css("Entity[type='application/vnd.vmware.vcloud.vAppTemplate+xml']").each do |item| itemId = item['href'].gsub(/.*\/vAppTemplate\/vappTemplate\-/, "") # Fetch the catalogItemId information params = { 'method' => :get, 'command' => "/vAppTemplate/vappTemplate-#{itemId}" } response, headers = send_request(params) # VMs Hash for all the vApp VM entities vms_hash = {} response.css("/VAppTemplate/Children/Vm").each do |vmElem| vmName = vmElem["name"] vmId = vmElem["href"].gsub(/.*\/vAppTemplate\/vm\-/, "") # Add the VM name/id to the VMs Hash vms_hash[vmName] = { :id => vmId } end items << { :id => itemId, :name => item['name'], :vms_hash => vms_hash } end { :id => catalogItemId, :description => description, :items => items, :type => 'vAppTemplate' } elsif response.css("Entity[type='application/vnd.vmware.vcloud.media+xml']").size > 0 name = response.css("Entity[type='application/vnd.vmware.vcloud.media+xml']").first['name'] { :id => catalogItemId, :description => description, :name => name, :type => 'media' } else @logger.warn 'WARNING: either this catalog item is empty or contains something not managed by vcloud-rest' { :id => catalogItemId, :description => description, :type => 'unknown' } end end ## # friendly helper method to fetch an catalogItem by name # - catalogId (use get_catalog_name(org, name)) # - catalagItemName def get_catalog_item_by_name(catalogId, catalogItemName) result = nil catalogElems = get_catalog(catalogId) catalogElems[:items].each do |k, v| if (k.downcase == catalogItemName.downcase) result = get_catalog_item(v) end end result end end end
true
6ae2fef1d5356dbe0deb198ebf6a20ffc47cc855
Ruby
nathanworden/Introduction-to-Programming-with-Ruby
/05. Loops & Iterators/00.perform_again.rb
UTF-8
566
3.96875
4
[]
no_license
# perform_again.rb declining_balance = 0 puts puts "Your current declining balance is $#{declining_balance}" puts puts "Would you like to add $10 to your declining balance? Enter 'Y' or 'N'" answer = gets.chomp.downcase if answer == 'n' p declining_balance elsif loop do declining_balance += 10 puts "new declining balance: $#{declining_balance}" puts "Do you want to do that again? Y/N" again = gets.chomp.downcase if again != 'y' break end end end puts puts puts "Ending Declining Balance: $#{declining_balance}" puts puts
true
2a376379ae18845689e125c5a641d8dc4bd769cc
Ruby
blambeau/veritas
/lib/veritas/attribute/date_time.rb
UTF-8
798
2.640625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# encoding: utf-8 module Veritas class Attribute # Represents a DateTime value in a relation tuple class DateTime < Object include Comparable DEFAULT_RANGE = (::DateTime.new..::DateTime::Infinity.new).freeze # The DateTime primitive # # @example # DateTime.primitive # => ::DateTime # # @return [Class<::DateTime>] # # @api public def self.primitive ::DateTime end # The DateTime range for a valid value # # @example # DateTime.range # => ::DateTime.new(*from)..::DateTime.new(*to) # # @return [Range<::DateTime>] # # @api public def range DEFAULT_RANGE end end # class DateTime end # class Attribute end # module Veritas
true
696c2c26af8069b483760ae350aaf2e93e722698
Ruby
songgz/tumugi
/lib/tumugi/cli.rb
UTF-8
3,728
2.515625
3
[ "Apache-2.0" ]
permissive
require 'thor' require 'tumugi' require 'tumugi/command/new' module Tumugi class CLI < Thor package_name "tumugi" default_command "run_" class << self def common_options option :file, aliases: '-f', desc: 'Workflow file name', required: true option :config, aliases: '-c', desc: 'Configuration file name' option :params, aliases: '-p', type: :hash, desc: 'Task parameters' option :quiet, type: :boolean, desc: 'Suppress log', default: false option :verbose, type: :boolean, desc: 'Show verbose log', default: false option :log_format, type: :string, desc: 'Log format', enum: ['text', 'json'], default: 'text' end def exit_on_failure? true end end desc "version", "Show version" def version puts "tumugi v#{Tumugi::VERSION}" end desc "run TASK", "Run TASK in a workflow" map "run" => "run_" # run is thor's reserved word, so this trick is needed option :workers, aliases: '-w', type: :numeric, desc: 'Number of workers to run task concurrently' option :out, aliases: '-o', desc: 'Output log filename. If not specified, log is write to STDOUT' option :all, aliases: '-a', type: :boolean, desc: 'Run all tasks even if target exists', default: false common_options def run_(task) execute(:run, task, options) end desc "show TASK", "Show DAG of TASK in a workflow" common_options option :out, aliases: '-o', desc: 'Output file name. If not specified, output result to STDOUT' option :format, aliases: '-t', desc: 'Output file format. Only affected --out option is specified.', enum: ['dot', 'png', 'svg'] def show(task) opts = options.dup opts[:quiet] = true if opts[:out].nil? execute(:show, task, opts.freeze) end desc "new type NAME", "Create a new template of type. type is 'plugin' or 'project'" def new(type, name) generate_project(type, name, options) end desc "init", "Create an tumugi project template" def init(path='') generate_project('project', path, force: true) end private def execute(command, task, options) logger.info "tumugi v#{Tumugi::VERSION}" args = { task: task, options: options } logger.info "status: running, command: #{command}, args: #{args}" success = Tumugi.workflow.execute(command, task, options) unless success raise Thor::Error, "execute finished, but failed" end logger.info "status: success, command: #{command}, args: #{args}" rescue => e handle_error(command, e, args) end def generate_project(type, name, options) logger.info "tumugi v#{Tumugi::VERSION}" args = { type: type, name: name, options: options } logger.info "status: running, command: new, args: #{args}" Tumugi::Command::New.new.execute(type, name, options) logger.info "status: success, command: new, args: #{args}" rescue => e handle_error("new", e, args) end private def handle_error(command, e, args) logger.error "#{command} command failed" logger.error e.message reason = e if e.is_a?(Tumugi::TumugiError) && !e.reason.nil? reason = e.reason logger.error reason.message end if options[:verbose] logger.error { reason.backtrace.join("\n") } else logger.error "If you want to know more detail, run with '--verbose' option" end logger.error "status: failed, command: #{command}, args: #{args}" raise Thor::Error.new("tumugi #{command} failed, please check log") end def logger @logger ||= Tumugi::ScopedLogger.new("tumugi-main") end end end
true
4c6918890d33749d5b88e51b17477439f2fb0e19
Ruby
kgoettling/intro_to_programming
/ch2_variables/ex4_name3.rb
UTF-8
320
4.21875
4
[]
no_license
# Modify name.rb again so that it stores the user's first name in a variable # then does the same for the last name and outputs both at once puts 'Hi, what\'s your first name?' first_name = gets.chomp puts 'And your last name?' last_name = gets.chomp puts "So, your full name is #{first_name} #{last_name}. Awesome!"
true
10742ec6bc3384c58093d1b891c49c32bd265a2a
Ruby
timsjoberg/circus
/lib/irc/connection.rb
UTF-8
1,446
2.890625
3
[ "Beerware", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'thread' require 'socket' require 'timeout' current_dir = File.dirname(__FILE__) require File.join(current_dir, 'parser') require File.join(current_dir, 'errors') module Circus class Connection def initialize(event_manager, config) @parser = Parser.new(event_manager) @config = config @queue = Queue.new end def connect @socket = TCPSocket.open(@config[:server], @config[:port]) @send_thread = Thread.new { dispatch } begin loop do line = nil Timeout::timeout(@config[:timeout]) do line = @socket.gets(@config[:eol]) end raise "Socket Closed" unless line parse line.chomp end rescue Timeout::Error raise PingTimeout rescue Interrupt @queue.clear @queue << "QUIT :Circus-IRC out" sleep 1 ensure @send_thread.exit @queue.clear @socket.close unless @socket.nil? || @socket.closed? end end def send(message) @queue << message end protected def dispatch loop do message = @queue.pop puts "sending: \"#{message}\"" if @config[:debug] @socket.write "#{message}#{@config[:eol]}" sleep @config[:send_speed] end end def parse(line) puts line if @config[:debug] @parser.parse line end end end
true
e63b9773dcd45092a7bcd1ffe2ce47defaf0119d
Ruby
angelbotto/logvisual-api
/models/user.rb
UTF-8
1,433
2.609375
3
[]
no_license
## # User model # class User include Mongoid::Document include Mongoid::Timestamps # adds created_at and updated_at fields include BCrypt field :email, type: String field :password_hash, type: String field :verify, type: Boolean, default: false field :token, type: String, default: -> { Digest::SHA1.hexdigest Time.now.to_s } index({ email: 1 }, unique: true, name: 'email_index') validates_presence_of :token, :email validates :email, presence: true, uniqueness: true, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/, on: :create } has_many :tasks ## # Create new user # def self.signup(user = {}) user = User.new( email: user[:email], password: user[:password] ) user.save ? user : false end ## # Signin def self.signin(obj = {}) user = User.where(email: obj[:email]).first user.password == obj[:password] ? user : false end ## # Validate token def self.validate_token(token) user = User.where(token: token, verify: true).first user ? user : false end ## # Return o generate new password def password @password ||= Password.new(password_hash) end ## # Assign password def password=(new_password) @password = Password.create(new_password) self.password_hash = @password end end
true
3d56f5140b3ec925459f07d8b03e0765b00644b4
Ruby
acco/dm-salesforce
/lib/dm-salesforce/property/boolean.rb
UTF-8
391
2.59375
3
[ "MIT" ]
permissive
module DataMapper::Salesforce module Property class Boolean < ::DataMapper::Property::Integer FALSE = 0 TRUE = 1 def self.dump(value, property) case value when nil, false then FALSE else TRUE end end def self.load(value, property) [true, 1, '1', 'true', 'TRUE', TRUE].include?(value) end end end end
true
d09e007259548110f04a8e3942a3ebaf4eb11c9e
Ruby
daniel-lanciana/paxos-challenges
/lib/file_binary_search.rb
UTF-8
2,358
3.421875
3
[]
no_license
# frozen_string_literal: true require './lib/gift_input_parser' # Returns line of sorted file without loading everything into memory class FileBinarySearch NEWLINE_CHARACTER = "\n" MIN_LINE_LENGTH = 4 DELIMITER = ', ' def initialize(args) @file = args[:file] @parser = args[:parser] end def find(exclusions, target, lower = 0, upper = @file.size, closest_match = nil) return closest_match if end_of_file_reached?(lower, upper) @line = get_middle_line!(@file, lower, upper) @line_amount = @parser.parse_line_amount(@line) return @line if @line_amount == target halve_and_find_again target, exclusions, lower, upper, closest_match end private def halve_and_find_again(target, exclusions, lower, upper, closest_match) if @line_amount < target closest_match = @line unless exclusions.include?(@line) # Set lower to the end of the line find exclusions, target, @file.pos + @line.length, upper, closest_match else # Set upper to the start of the line find exclusions, target, lower, @file.pos, closest_match end end def end_of_file_reached?(lower, upper) # number of bits in file may be uneven, so allow buffer of the minimum gift # entry (e.g. "a, 1\n") upper - lower <= MIN_LINE_LENGTH end def get_middle_line!(file, lower, upper) goto_middle_of_file!(file, lower, upper) && get_full_line(file) end def goto_middle_of_file!(file, lower, upper) file.seek((lower + upper) / 2) end def get_full_line(file) original_pos = file.pos rewind_line(file, file.gets) ensure # Return original file position (for accurate binary searching) file.seek original_pos end # If input lines are not equal length, we might land in the middle of a line def rewind_line(file, line) until file_at_starting_position?(file, line) line_rewind_one_char(file, line) do |rewound_line| return line if newline?(rewound_line) line = rewound_line end end line end def file_at_starting_position?(file, line) file.pos == line.length end def line_rewind_one_char(file, line) # File position currently at the end of the line file.seek file.pos - (line.length + 1) yield file.gets end def newline?(line) line == NEWLINE_CHARACTER end end
true
c374dc3a6c59b4864343ef36ba8264f820b58aff
Ruby
miguelrosato/101_programming_foundations
/00 Lesson 2 Small Programs/00 Small Problems Exercises/10 Medium 1/02_rotation2.rb
UTF-8
455
3.515625
4
[]
no_license
def rotate_str(str) str[1..-1] + str[0] end def rotate_rightmost_digits(num, idx) str = num.to_s (str[0..-idx - 1] + rotate_str(str[-idx..-1])).to_i end p rotate_rightmost_digits(735291, 1) # == 735291 p rotate_rightmost_digits(735291, 2) # == 735219 p rotate_rightmost_digits(735291, 3) # == 735912 p rotate_rightmost_digits(735291, 4) # == 732915 p rotate_rightmost_digits(735291, 5) # == 752913 p rotate_rightmost_digits(735291, 6) # == 352917
true
ca11ebd15c03826ef81ffd98d541f836b09a2557
Ruby
jazzygasper/bank_tech_test
/lib/bank_account.rb
UTF-8
421
3.25
3
[]
no_license
require_relative 'statement' class Bank_Account attr_reader :balance, :statement def initialize(statement = Statement.new) @balance = 0 @statement = statement end def deposit(amount) @balance += amount @statement.current_deposit(amount, @balance) end def withdrawal(amount) @balance -= amount @statement.current_withdrawl(amount, @balance) end def print_statement end end
true
07a3eeed586f4b534f49e0bec2cb21c62aefa58f
Ruby
SalarGhotaslo/airport_challenge_own
/lib/airport.rb
UTF-8
532
3.140625
3
[]
no_license
require_relative 'weather_reporter' # frozen_string_literal: true # Creating a class airport class Airport def initialize(capacity) @capacity = capacity @planes = [] end def land(plane) raise 'Cannot land as airport is full' if full? raise 'Cannot land plane: weather is stormy' if stormy? @planes << plane end def take_off(_plane) raise 'Cannot takeoff: weather is stormy' if stormy? end end private def full? @planes.length >= @capacity end def stormy? Weather_reporter.stormy? end
true
b3cb063bf0f791384b89781fe93a334aea93e759
Ruby
BeccaHyland/potluck
/test/potluck_test.rb
UTF-8
1,335
3.015625
3
[]
no_license
require 'minitest/autorun' require 'minitest/pride' require './lib/potluck' require 'pry' class DishTest < Minitest::Test def test_it_has_a_date potluck = Potluck.new("7-13-18") assert_equal "7-13-18", potluck.date end def test_it_starts_with_an_empty_array_of_dishes potluck = Potluck.new("7-13-18") assert_equal [], potluck.dishes end def test_it_stores_dishes potluck = Potluck.new("7-13-18") couscous_salad = Dish.new("Couscous Salad", :appetizer) cocktail_meatballs = Dish.new("Cocktail Meatballs", :entre) potluck.add_dish(couscous_salad) potluck.add_dish(cocktail_meatballs) assert_equal [couscous_salad, cocktail_meatballs], potluck.dishes assert_equal 2, potluck.dishes.length end def test_it_returns_dishes_by_category potluck = Potluck.new("7-13-18") couscous_salad = Dish.new("Couscous Salad", :appetizer) summer_pizza = Dish.new("Summer Pizza", :appetizer) roast_pork = Dish.new("Roast Pork", :entre) potluck.add_dish(couscous_salad) potluck.add_dish(summer_pizza) potluck.add_dish(roast_pork) actual = potluck.get_all_from_category(:entre) expected = [roast_pork] assert_equal expected, actual # potluck.get_all_from_category(:appetizer).first # potluck.get_all_from_category(:appetizer).first.name end end
true
e97f2896230e3289d80583e4dedce45fad9db810
Ruby
oscarcuihang/leetcode
/ruby_solutions/191.NumberOf1Bits.rb
UTF-8
449
4.03125
4
[]
no_license
# Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). # For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. # @param {Integer} n, a positive integer # @return {Integer} def hamming_weight(n) count = 0 while n.nonzero? count += 1 n &= n - 1 end count end
true
29f61926a52c0b6f8a79fcc1bb7e8e1ba44753e6
Ruby
josephine-c/Phone_number
/phone-number/phone_number.rb
UTF-8
498
3.640625
4
[]
no_license
# Get rid of white space and punctuation # Get rid of country code 1 and restrict area code to starts with a number ranging from 2-9 # Restrict length of number to 10 digits and restrict the exchange code with number from 2-9 class PhoneNumber def self.clean(phone) phone_num = phone.scan(/\d/).join while phone_num[0] < "2" do phone_num.gsub!(/^\d/, '') end p phone_num.length != 10 || phone_num[3] < "2"? nil : phone_num end end
true
baaa4636dd72f4be3607ab9d4446386bdd25067b
Ruby
aitorlb/launch_school
/RB109/interview/exercises/easy_7/1_combine_two_lists.rb
UTF-8
1,147
4.53125
5
[ "MIT" ]
permissive
=begin Combine Two Lists Write a method that combines two Arrays passed in as arguments, and returns a new Array that contains all elements from both Array arguments, with the elements taken in alternation. You may assume that both input Arrays are non-empty, and that they have the same number of elements. Example: interleave([1, 2, 3], ['a', 'b', 'c']) == [1, 'a', 2, 'b', 3, 'c'] - Understand the problem - Input - 2 Arrays of any elements - Output - 1 Array containing all elements from both Array arguments - Rules - New Array has elements taken in alternation - both input Arrays are non-empty and have the same number of elements - Examples - Covered - Algorithm 1. Assign empty array to ´result´ 2. Iterate over one array 1. Add current value to ´result´ 2. Add current index value from other array to ´result´ 3. Return ´result´ - Code =end def interleave(array1, array2) result = [] array1.each_with_index do |element, index| result << element result << array2[index] end result end puts interleave([1, 2, 3], ['a', 'b', 'c']) == [1, 'a', 2, 'b', 3, 'c'] # true
true
8c82fa024583ed34ee56bf5e3fb27533630a6bac
Ruby
elimiller783/green_grocer-001-prework-web
/grocer.rb
UTF-8
1,139
3.203125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def consolidate_cart(cart:[]) hash = {} cart.each do |item| item.each do |key, value| value[:count] = cart.count(item) hash[key] = value end end hash end def apply_coupons(cart:[], coupons:[]) coupons.each do |coupon| x = coupon[:item] if cart[x] && cart[x][:count] >= coupon[:num] if cart["#{x} W/COUPON"] cart["#{x} W/COUPON"][:count] += 1 else cart["#{x} W/COUPON"] = {:count => 1, :price => coupon[:cost]} cart["#{x} W/COUPON"][:clearance] = cart[x][:clearance] end cart[x][:count] -= coupon[:num] end end cart end def apply_clearance(cart:[]) cart.each do |item, value| if value[:clearance] value[:price] -= value[:price] * 0.2 end end cart end def checkout(cart: [], coupons: []) combined_cart = consolidate_cart(cart: cart) marked_down_cart = apply_coupons(cart: combined_cart, coupons: coupons) complete_cart = apply_clearance(cart: marked_down_cart) total = 0 complete_cart.each do |name, value| total += value[:price] * value[:count] end if total > 100 total -= total * 0.1 end total end
true
d6d95f4930de965aa246dfb4a298fde686bdee61
Ruby
alisa1649/brainflayer
/db/seeds.rb
UTF-8
1,270
2.625
3
[]
no_license
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) user = User.create!({ email: "erlich@aviato.io", password: "hunter2" }) tags = Tag.create!([ {name: "development"}, {name: "trivia"} ]) deck = Deck.create!({ title: "react", objective: "learn react magic", author_id: user.id, tag_id: tags[0].id, icon_url: "fakeurl" }) deck2 = Deck.create!({ title: "silicon valley", objective: "learn trivia", author_id: user.id, tag_id: tags[1].id, icon_url: "fakeurl2" }) react_cards = Card.create!([ {title: "what is react?", body: "react is a javascript library", deck: deck}, {title: "what is redux?", body: "redux is a state management framework", deck: deck} ]) silicon_valley_trivia = Card.create!([ {title: "who is richard hendricks?", body: "the founder of pied piper", deck: deck2}, {title: "what is pied piper?", body: "a lossless compression algorithm company, duh!", deck: deck2} ])
true
b7de11315c466a76278716c3a2e51e6d525f92a2
Ruby
johnisom/ruby-challenge-problems
/advanced_1/bowling.rb
UTF-8
1,945
3.359375
3
[]
no_license
# frozen_string_literal: true # bowling game class class Game def initialize setup @game_over = false @throws = [] @score = 0 end def roll(pins) validate(pins) @throws << pins if @frame == 10 do_tenth_frame_logic(pins) else @second_throw ^= true unless pins == 10 @frame += 1 unless @second_throw end end def score validate_able_to_score setup @throws.each_with_index do |pins, idx| @score += pins next if @frame == 10 @score += strike_amount(idx, pins) + spare_amount(idx, pins) @second_throw ^= true unless pins == 10 @frame += 1 unless @second_throw end @score end private def strike_amount(idx, pins) pins == 10 ? @throws[idx + 1] + @throws[idx + 2] : 0 end def spare_amount(idx, pins) @throws[idx - 1] + pins == 10 && @second_throw ? @throws[idx + 1] : 0 end def validate(pins) raise('Pins must have a value from 0 to 10') unless (0..10).cover?(pins) raise('Should not be able to roll after game is over') if @game_over raise('Pin count exceeds pins on lane') if pin_count_exceeds(pins) end def validate_able_to_score raise('Game is not yet over, cannot score!') if @fill_ball && !@game_over raise('Score cannot be taken until the end of the game') unless @game_over end def do_tenth_frame_logic(pins) @fill_ball ||= begin (pins == 10 || @throws[-2] == 10 || pins + @throws[-2] == 10) && @second_throw end @second_throw ^= true @game_over = @fill_ball != !@second_throw end def pin_count_exceeds(pins) @frame == 10 && exceeds_frame_10(pins) || @second_throw && @throws.last + pins > 10 && @frame != 10 end def exceeds_frame_10(pins) @throws.last != 10 && @throws.last + pins > 10 && (@second_throw || @fill_ball) end def setup @fill_ball = false @second_throw = false @frame = 1 end end
true
9ed36261c548ae42ce44e7e26762cb2cbd8e41d0
Ruby
ivanacostarubio/vector_with_error
/spec/vector_with_error_spec.rb
UTF-8
669
3.34375
3
[]
no_license
class Vector attr_accessor :data def initialize(data) @data = data end def compare_with_error(y,tolerance) !y.data.each_with_index.map{|number,index| within(number,@data[index],tolerance) }.include? false end private def within(x,y,tolerance) x.between?(y - tolerance, y + tolerance) end end describe Vector do let(:x) { Vector.new([1,2,3]) } it "is the same" do Vector.new([1,2,3]).compare_with_error(x,0).should == true end it "can compare with an error rate" do Vector.new([1.1,1.9,3.1]).compare_with_error(x,0.1).should == true Vector.new([1.1,1.9,3.1]).compare_with_error(x,0.0).should == false end end
true
b61657ee3f92503cb415521afe4b37972b576a5c
Ruby
harryplumer/ruby_calculator
/calculator.rb
UTF-8
2,005
4.375
4
[]
no_license
#all requires go on top require 'pry' def get_input puts "\nPlease enter an equation with space in between each input. Ex: 2 + 2" puts "You may also enter trig functions cos, sin and tan. Ex: cos(180) + sin(32)" puts "You may also type 'quit' to Quit" parse(gets.strip) get_input end def verify_operator(operator) if operator == "+" || operator == "-" || operator == "*" || operator == "/" operator else false end end def get_answer(first_num, operation, second_num) case operation when "+" answer = first_num + second_num when "-" answer = first_num - second_num when "*" answer = first_num * second_num when "/" if second_num == 0 puts "Dividing by 0 is not permitted" get_input else answer = first_num / second_num end end end def verify_number(input) if (!input) puts "ERROR: One or more numbers was left blank! Please try again." get_input end number = Float(input) rescue false if (number) number = number.to_f elsif input.scan(/cos\((.*?)\)/).any? number = Math.cos(input.scan(/cos\((.*?)\)/)[0][0].to_f) elsif input.scan(/sin\((.*?)\)/).any? number = Math.sin(input.scan(/sin\((.*?)\)/)[0][0].to_f) elsif input.scan(/tan\((.*?)\)/).any? number = Math.tan(input.scan(/tan\((.*?)\)/)[0][0].to_f) else puts "ERROR: #{input} could not be read! Please try again." get_input end end def parse(input) if input.downcase == "quit" exit end input_array = input.split(" ") first_num = verify_number(input_array[0]) second_num = verify_number(input_array[2]) operation = verify_operator(input_array[1]) if verify_operator(input_array[1]) operation = input_array[1] else puts "ERROR: Operator could not be read" get_input end puts "The result of #{first_num} #{operation} #{second_num} is #{get_answer(first_num, operation, second_num).round(2)}" end puts "--- WELCOME TO THE RUBY CALCULATOR ---" get_input
true
93458fa24bf2bceaff038d63efb5393892b5a8b6
Ruby
paula-lee/phase-0-tracks
/ruby/guessing_game/word_game_spec.rb
UTF-8
1,490
4.25
4
[]
no_license
# pseudocode # initialize method # create an instance variable called pokemon names and it is equal to # an array of pokemon names. # create an instance variable called guess count that is equal to zero # create an instance variable called game over and have that equal to # false. # create an instance variable called user input that equals to a blank array # define method pick pokemon # player 1 will enter a pokemon name that player 2 has to guess # split it by character so that it becomes an array with each letter # as a value. # Have the split pokemon name chosen to equal to who’s that # pokemon variable name require_relative 'word_game' describe Pokemon do let(:game) { Pokemon.new("pikachu") } it "stores the pokemon name given in initializion" do expect(game.pokemon_name).to eq "pikachu" # puts game end it "gets pokemon name from user and return underscores the length of the pokemon name" do expect(game.convert_pokemon_name).to eq("_ _ _ _ _ _ _") # puts game end it "inserts the users input if correct, to be displayed" do expect(game.check_letter("p")).to eq("p _ _ _ _ _ _") # puts game end it "checks if user's input is equal to the secret word" do game.check_letter("p") game.check_letter("i") game.check_letter("k") game.check_letter("a") game.check_letter("c") game.check_letter("h") game.check_letter("u") expect(game.guess_count_check).to be true end end
true
f51e86c4258aedfa6a296b6391dfe5609049417c
Ruby
jcjohnny/nauts
/vendor/bundle/gems/formtastic-3.1.3/lib/formtastic/inputs/select_input.rb
UTF-8
9,755
2.59375
3
[ "MIT" ]
permissive
module Formtastic module Inputs # A select input is used to render a `<select>` tag with a series of options to choose from. # It works for both single selections (like a `belongs_to` relationship, or "yes/no" boolean), # as well as multiple selections (like a `has_and_belongs_to_many`/`has_many` relationship, # for assigning many genres to a song, for example). # # This is the default input choice when: # # * the database column type is an `:integer` and there is an association (`belongs_to`) # * the database column type is a `:string` and the `:collection` option is used # * there an object with an association, but no database column on the object (`has_many`, etc) # * there is no object and the `:collection` option is used # # The flexibility of the `:collection` option (see examples) makes the :select input viable as # an alternative for many other input types. For example, instead of... # # * a `:string` input (where you want to force the user to choose from a few specific strings rather than entering anything) # * a `:boolean` checkbox input (where the user could choose yes or no, rather than checking a box) # * a `:date_select`, `:time_select` or `:datetime_select` input (where the user could choose from pre-selected dates) # * a `:number` input (where the user could choose from a set of pre-defined numbers) # * a `:time_zone` input (where you want to provide your own set of choices instead of relying on Rails) # * a `:country` input (no need for a plugin really) # # Within the standard `<li>` wrapper, the output is a `<label>` tag followed by a `<select>` # tag containing `<option>` tags. # # For inputs that map to associations on the object model, Formtastic will automatically load # in a collection of objects on the association as options to choose from. This might be an # `Author.all` on a `Post` form with an input for a `belongs_to :user` association, or a # `Tag.all` for a `Post` form with an input for a `has_and_belongs_to_many :tags` association. # You can override or customise this collection and the `<option>` tags it will render through # the `:collection` option (see examples). # # The way on which Formtastic renders the `value` attribute and content of each `<option>` tag # is customisable through the `:member_label` and `:member_value` options. When not provided, # we fall back to a list of methods to try on each object such as `:to_label`, `:name` and # `:to_s`, which are defined in the configurations `collection_label_methods` and # `collection_value_methods` (see examples below). # # @example Basic `belongs_to` example with full form context # # <%= semantic_form_for @post do |f| %> # <%= f.inputs do %> # <%= f.input :author, :as => :select %> # <% end %> # <% end %> # # <form...> # <fieldset> # <ol> # <li class='select'> # <label for="post_author_id">Author</label> # <select id="post_author_id" name="post[post_author_id]"> # <option value=""></option> # <option value="1">Justin</option> # <option value="3">Kate</option> # <option value="2">Amelia</option> # </select> # </li> # </ol> # </fieldset> # </form> # # @example Basic `has_many` or `has_and_belongs_to_many` example with full form context # # <%= semantic_form_for @post do |f| %> # <%= f.inputs do %> # <%= f.input :tags, :as => :select %> # <% end %> # <% end %> # # <form...> # <fieldset> # <ol> # <li class='select'> # <label for="post_tag_ids">Author</label> # <select id="post_tag_ids" name="post[tag_ids]" multiple="true"> # <option value="1">Ruby</option> # <option value="6">Rails</option> # <option value="3">Forms</option> # <option value="4">Awesome</option> # </select> # </li> # </ol> # </fieldset> # </form> # # @example Override Formtastic's assumption on when you need a multi select # <%= f.input :authors, :as => :select, :input_html => { :multiple => true } %> # <%= f.input :authors, :as => :select, :input_html => { :multiple => false } %> # # @example The `:collection` option can be used to customize the choices # <%= f.input :author, :as => :select, :collection => @authors %> # <%= f.input :author, :as => :select, :collection => Author.all %> # <%= f.input :author, :as => :select, :collection => Author.some_named_scope %> # <%= f.input :author, :as => :select, :collection => Author.pluck(:full_name, :id) %> # <%= f.input :author, :as => :select, :collection => Author.pluck(Arel.sql("CONCAT(`first_name`, ' ', `last_name`)"), :id)) %> # <%= f.input :author, :as => :select, :collection => [Author.find_by_login("justin"), Category.find_by_name("kate")] %> # <%= f.input :author, :as => :select, :collection => ["Justin", "Kate"] %> # <%= f.input :author, :as => :select, :collection => [["Justin", "justin"], ["Kate", "kate"]] %> # <%= f.input :author, :as => :select, :collection => [["Justin", "1"], ["Kate", "3"]] %> # <%= f.input :author, :as => :select, :collection => [["Justin", 1], ["Kate", 3]] %> # <%= f.input :author, :as => :select, :collection => 1..5 %> # <%= f.input :author, :as => :select, :collection => "<option>your own options HTML string</option>" %> # <%= f.input :author, :as => :select, :collection => options_for_select(...) %> # <%= f.input :author, :as => :select, :collection => options_from_collection_for_select(...) %> # <%= f.input :author, :as => :select, :collection => grouped_options_for_select(...) %> # <%= f.input :author, :as => :select, :collection => time_zone_options_for_select(...) %> # # @example Set HTML attributes on the `<select>` tag with `:input_html` # <%= f.input :authors, :as => :select, :input_html => { :size => 20, :multiple => true, :class => "special" } %> # # @example Set HTML attributes on the `<li>` wrapper with `:wrapper_html` # <%= f.input :authors, :as => :select, :wrapper_html => { :class => "special" } %> # # @example Exclude, include, or customize the blank option at the top of the select. Always shown, even if the field already has a value. Suitable for optional inputs. # <%= f.input :author, :as => :select, :include_blank => false %> # <%= f.input :author, :as => :select, :include_blank => true %> => <option value=""></option> # <%= f.input :author, :as => :select, :include_blank => "No author" %> # # @example Exclude, include, or customize the prompt at the top of the select. Only shown if the field does not have a value. Suitable for required inputs. # <%= f.input :author, :as => :select, :prompt => false %> # <%= f.input :author, :as => :select, :prompt => true %> => <option value="">Please select</option> # <%= f.input :author, :as => :select, :prompt => "Please select an author" %> # # # @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options. # @see Formtastic::Inputs::CheckBoxesInput CheckBoxesInput as an alternative for `has_many` and `has_and_belongs_to_many` associations # @see Formtastic::Inputs::RadioInput RadioInput as an alternative for `belongs_to` associations # # @todo Do/can we support the per-item HTML options like RadioInput? class SelectInput include Base include Base::Collections def to_html input_wrapping do label_html << select_html end end def select_html builder.select(input_name, collection, input_options, input_html_options) end def include_blank options.key?(:include_blank) ? options[:include_blank] : (single? && builder.include_blank_for_select_by_default) end def prompt? !!options[:prompt] end def label_html_options super.merge(:for => input_html_options[:id]) end def input_options super.merge :include_blank => (include_blank unless prompt?) end def input_html_options extra_input_html_options.merge(super.reject {|k,v| k==:name && v.nil?} ) end def extra_input_html_options { :multiple => multiple?, :name => (multiple? && Rails::VERSION::MAJOR >= 3) ? input_html_options_name_multiple : input_html_options_name } end def input_html_options_name if builder.options.key?(:index) "#{object_name}[#{builder.options[:index]}][#{association_primary_key}]" else "#{object_name}[#{association_primary_key}]" end end def input_html_options_name_multiple input_html_options_name + "[]" end def multiple_by_association? reflection && [ :has_many, :has_and_belongs_to_many ].include?(reflection.macro) end def multiple_by_options? options[:multiple] || (options[:input_html] && options[:input_html][:multiple]) end def multiple? multiple_by_options? || multiple_by_association? end def single? !multiple? end end end end
true
7cc2de62d4df04cead562e6f13c355643bd74136
Ruby
codeclanstudentls/reimagined-goggles
/models/wizard_maker.rb
UTF-8
1,830
3.234375
3
[]
no_license
require('pry-byebug') require_relative('../db/sql_runner') class Wizard attr_reader( :first_name, :last_name, :house_name, :age, :id ) def initialize( options ) @id = nil || options['id'].to_i @first_name = options['first_name'] @last_name = options['last_name'] @house_name = options['house_name'] @age = options['age'].to_i end def house_id_from_name() sql = " SELECT * FROM house WHERE house_name = '#{@house_name}' ;" house = SqlRunner.run(sql) house_id = house[0]['id'] return house_id end def save house_id = house_id_from_name() sql = "INSERT INTO students(first_name, last_name, age, house_id) VALUES ('#{@first_name}', '#{@last_name}', #{@age}, #{house_id}) returning *;" result = SqlRunner.run( sql ).first @id = result['id'].to_i end def self.house(student_first_name) sql = " SELECT s.*, h.house_name FROM students s INNER JOIN house h on s.house_id = h.id WHERE s.first_name = '#{student_first_name}';" house_result = SqlRunner.run(sql).first house = house_result['house_name'] return house end def self.delete( id ) sql = "DELETE FROM students WHERE id=#{id}" SqlRunner.run( sql ) end def self.delete_all() sql = "DELETE FROM students;" SqlRunner.run(sql) end def self.all() sql = " SELECT s.*, h.house_name FROM students s INNER JOIN house h on s.house_id = h.id;" students = SqlRunner.run(sql) result = students.map {|lizard| Wizard.new(lizard)} return result end def self.find(wizard_id) sql = " SELECT s.*, h.house_name FROM students s INNER JOIN house h on s.house_id = h.id WHERE s.id = #{wizard_id};" students = SqlRunner.run(sql).first return Wizard.new(students) end end
true
168ce3ed10e23846043eaa8c30fa5e85874e259a
Ruby
zenspider/seeing_is_believing
/spec/binary/marker_spec.rb
UTF-8
2,060
3.015625
3
[ "WTFPL" ]
permissive
require 'seeing_is_believing/binary/data_structures' RSpec.describe SeeingIsBelieving::Binary::Marker do describe 'to_regex' do def assert_parses(input, regex) expect(described_class.to_regex input).to eq regex end it 'doesn\'t change existing regexes' do assert_parses /^.$/ix, /^.$/ix end it 'converts strings into regexes' do assert_parses '', %r() assert_parses 'a', %r(a) end it 'ignores surrounding slashes' do assert_parses '//', %r() assert_parses '/a/', %r(a) end it 'respects flags after the trailing slash in surrounding slashes' do assert_parses '/a/', %r(a) assert_parses '/a//', %r(a/) assert_parses '//a/', %r(/a) assert_parses '/a/i', %r(a)i assert_parses '/a/im', %r(a)im assert_parses '/a/xim', %r(a)xim assert_parses '/a/mix', %r(a)mix assert_parses '/a/mixi', %r(a)mixi end it 'isn\'t fooled by strings that kinda look regexy' do assert_parses '/a', %r(/a) assert_parses 'a/', %r(a/) assert_parses '/', %r(/) assert_parses '/i', %r(/i) end it 'does not escape the content' do assert_parses 'a\\s+', %r(a\s+) assert_parses '/a\\s+/', %r(a\s+) end end it 'requires prefix and a regex' do described_class.new prefix: '', regex: // expect { described_class.new }.to raise_error ArgumentError expect { described_class.new prefix: '' }.to raise_error ArgumentError expect { described_class.new regex: // }.to raise_error ArgumentError end it 'stores the prefix and a regex' do marker = described_class.new(prefix: 't', regex: /r/) expect(marker.prefix).to eq 't' expect(marker.regex).to eq /r/ end it 'converts strings to rgexes when they are set' do marker = described_class.new prefix: 't', regex: 'r1' expect(marker[:regex]).to eq /r1/ marker.regex = '/r2/i' expect(marker.regex).to eq /r2/i marker[:regex] = 'r3' expect(marker.regex).to eq /r3/ end end
true
b7a086090f96b5c322423029b77861c636a815b2
Ruby
smccarthy/profile-service-presentation
/profile-service-example.rb
UTF-8
1,973
3.125
3
[]
no_license
require 'faraday' require 'json' require 'uri' class ProfileService @@profile_service_url = 'http://localhost:8080' # 1st API request - Add data to profile in the profile service. # This will be done prior to your tests running. def add_to_profile(profile_name:, profile_data:) Faraday.post "#{@@profile_service_url}/profile/#{profile_name}", profile_data rescue StandardError => e puts "Error adding to profile : #{e.message}" end # 2nd API request - Retrieves an object from the profile service. # This will lock that profile so another test can not use it. def profile(profile_name:) claim_url = "#{@@profile_service_url}/profile/#{profile_name}/next" response = Faraday.get claim_url profile = JSON.parse(response.body) raise "No profile available for #{profile_name}" unless profile profile end # 3rd API request - Releases profile lock, so another test can get this profile. def release_profile(profile_id:) Faraday.post "#{@@profile_service_url}/profile/#{profile_id}/release", {} rescue StandardError => e puts "Error releasing profile : #{e.message}" end end profile_service = ProfileService.new profile_name = 'test-profile' profile_data = { username: 'myTestUserName1', password: 'myTestPassword1' } p = profile_service.add_to_profile(profile_name: profile_name, profile_data: profile_data) puts "Response from adding to profile #{p.body}" p = profile_service.profile(profile_name: profile_name) puts "Response from getting a profile #{p}" profile_id = p['_id'] r = profile_service.release_profile(profile_id: profile_id) puts "Response from releasing profile #{r.body}" # Add two more entries p = profile_service.add_to_profile(profile_name: profile_name, profile_data: {username: 'myTestUserName2', password: 'myTestPassword2'}) p = profile_service.add_to_profile(profile_name: profile_name, profile_data: {username: 'myTestUserName3', password: 'myTestPassword3'}) # ruby profile-service-example.rb
true
46f895403db50149ea782adcf9a0153328f2e0df
Ruby
dembasiby/cp_learn_to_program
/02-numbers/hours_in_a_year.rb
UTF-8
113
2.734375
3
[]
no_license
hours_in_a_day = 24 days_in_a_year = 365 hours_in_a_year = days_in_a_year * hours_in_a_day puts hours_in_a_year
true
7411fc7b75f9a295db64bdc674c3b0abb632c07e
Ruby
gaboncio42/badges-and-schedules-dumbo-web-102918
/conference_badges.rb
UTF-8
560
3.71875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def badge_maker(name) return "Hello, my name is #{name}." end def batch_badge_creator(array) new_badge = [] array.each {|name| new_badge.push("Hello, my name is #{name}.")} return new_badge end def assign_rooms(array) rooms = [] array.each_with_index do |name, index| index_plus_one = index + 1 rooms.push("Hello, #{name}! You'll be assigned to room #{index_plus_one}!") end return rooms end def printer(array) batch_badge_creator(array).each {|line| puts line} assign_rooms(array).each {|line| puts line} end
true
7ac146b664a9a988c3709f1aa55c6bd9a177545a
Ruby
mgoodhart5/reunion
/test/activity_test.rb
UTF-8
1,640
3.046875
3
[]
no_license
require 'minitest/autorun' require 'minitest/pride' require './lib/activity' require 'pry' class ActivityTest < Minitest::Test def test_it_exists activity = Activity.new("Brunch") assert_instance_of Activity, activity end def test_that_it_is_initialized_with_a_name activity = Activity.new("Brunch") assert_equal "Brunch", activity.name end def test_that_it_starts_with_an_empty_hash_for_participants activity = Activity.new("Brunch") assert_equal ({}), activity.participants end def test_that_it_can_add_participants activity = Activity.new("Brunch") activity.add_participant("Maria", 20) assert_equal ({"Maria" => 20}), activity.participants activity.add_participant("Luther", 40) assert_equal ({"Maria" => 20, "Luther" => 40}), activity.participants end def test_that_it_can_find_total_cost_of_activity activity = Activity.new("Brunch") activity.add_participant("Maria", 20) assert_equal 20, activity.total_cost activity.add_participant("Luther", 40) assert_equal 60, activity.total_cost end def test_that_they_can_split_total_cost_between_participants activity = Activity.new("Brunch") activity.add_participant("Maria", 20) activity.add_participant("Luther", 40) activity.total_cost assert_equal 30, activity.split end def test_that_it_can_charge_the_participants activity = Activity.new("Brunch") activity.add_participant("Maria", 20) activity.add_participant("Luther", 40) activity.total_cost activity.split assert_equal ({"Maria" => 10, "Luther" => -10}), activity.owed end end
true
6a4e02489cc58cf4a9a77cb4f3ec6c805bef7001
Ruby
wakeless/gallball
/spec/models/player_spec.rb
UTF-8
2,382
2.578125
3
[]
no_license
require 'spec_helper' describe Player do let (:golf) { FactoryGirl.create(:sport, :name => 'Golf') } let (:tennis) { FactoryGirl.create(:sport, :name => 'Tennis') } let (:player) { FactoryGirl.create(:player) } let (:player2) { FactoryGirl.create(:player) } it { should have_many(:games) } #failing it { should have_many(:losses) } it { should have_many(:wins) } it { should have_many(:ranks) } it { should validate_presence_of(:name).with_message("People have names, yo") } describe "#leaderboard" do before { player = FactoryGirl.create(:player) player2 = FactoryGirl.create(:player) FactoryGirl.create(:rank, :player => player, :sport => tennis, :value => 10) FactoryGirl.create(:rank, :player => player, :sport => tennis, :value => 90) FactoryGirl.create(:rank, :player => player2, :sport => tennis, :value => 20) FactoryGirl.create(:rank, :player => player, :sport => golf, :value => 30) FactoryGirl.create(:rank, :player => player2, :sport => golf, :value => 10) FactoryGirl.create(:rank, :player => player2, :sport => golf, :value => 40) } it { leaderboard = Player.leaderboard(tennis) leaderboard.length.should == 2 leaderboard.first.value.should == 90 } it { leaderboard = Player.leaderboard(golf) leaderboard.length.should == 2 leaderboard.first.value.should == 40 } end describe "#rank_for_sport" do before { FactoryGirl.create(:rank, :sport => tennis, :player => player) FactoryGirl.create(:rank, :sport => golf, :player => player) } it { player.ranks == 2 } it { player.rank_for_sport(tennis).should == 1000 } end describe "#update_rank" do before { FactoryGirl.create(:rank, :sport => tennis, :player => player) FactoryGirl.create(:rank, :sport => golf, :player => player) } it { player.ranks == 2 } it { player.rank_for_sport(tennis).should == 1000 } it { player.update_rank(tennis, 1234) player.rank_for_sport(tennis).should == 1234 } end describe "#games_played" do before { FactoryGirl.create(:game, :winner => player) FactoryGirl.create(:game, :loser => player) FactoryGirl.create(:game) } it { player.reload player.games_played.should == 2 } end end
true
9278ff2cd6f5c8db545e9b78a78a7964be24e451
Ruby
sarahdactyl71/Headcount
/test/economic_profile_test.rb
UTF-8
2,891
2.859375
3
[]
no_license
gem 'minitest' require 'minitest/autorun' require 'minitest/pride' require './lib/economic_profile' class EconomicProfileTest < Minitest::Test attr_reader :epr, :ep def setup @epr = EconomicProfileRepository.new epr.load_data({ :economic_profile => { :median_household_income => "./data/Median household income.csv", :children_in_poverty => "./data/School-aged children in poverty.csv", :free_or_reduced_price_lunch => "./data/Students qualifying for free or reduced price lunch.csv", :title_i => "./data/Title I students.csv" } }) @ep = epr.find_by_name("ACADEMY 20") end def test_it_has_a_class assert_equal EconomicProfile, ep.class end def test_can_it_pull_in_a_median_income assert_equal 85060, ep.median_household_income_in_year(2005) assert_equal 87635, ep.median_household_income_in_year(2009) assert_equal 89222, ep.median_household_income_in_year(2011) end def test_median_household_income income = ep.median_household_income_average assert_equal 87635, income assert_equal Fixnum, income.class end def test_percentage_of_students_in_title_i_in_year assert_equal 0.027, ep.title_i_in_year(2014) assert_equal 0.011, ep.title_i_in_year(2011) assert_equal 0.012, ep.title_i_in_year(2013) assert_equal 0.014, ep.title_i_in_year(2009) assert_raises(UnknownDataError) do ep.title_i_in_year(1995) end end def test_children_in_poverty_over_years assert_equal 0.064, ep.children_in_poverty_in_year(2012) assert_equal 0.04404, ep.children_in_poverty_in_year(2008) assert_equal 0.042, ep.children_in_poverty_in_year(2005) assert_equal 0.05754, ep.children_in_poverty_in_year(2010) assert_raises(UnknownDataError) do ep.children_in_poverty_in_year(1895) end end def test_percentage_of_free_or_reduced_lunch assert_equal 0.127, ep.free_or_reduced_price_lunch_percentage_in_year(2014) assert_equal 0.119, ep.free_or_reduced_price_lunch_percentage_in_year(2011) assert_equal 0.08, ep.free_or_reduced_price_lunch_percentage_in_year(2007) assert_equal 0.103, ep.free_or_reduced_price_lunch_percentage_in_year(2009) assert_raises(UnknownDataError) do ep.free_or_reduced_price_lunch_percentage_in_year(1995) end end def test_number_of_students_with_free_or_reduced_lunches assert_equal 3132, ep.free_or_reduced_price_lunch_number_in_year(2014) assert_equal 2834, ep.free_or_reduced_price_lunch_number_in_year(2011) assert_equal 1630, ep.free_or_reduced_price_lunch_number_in_year(2007) assert_equal 2338, ep.free_or_reduced_price_lunch_number_in_year(2009) assert_raises(UnknownDataError) do ep.free_or_reduced_price_lunch_number_in_year(1995) end end def test_relationship assert epr.find_by_name('ACADEMY 20').is_a?(EconomicProfile) end end
true
33ece8527185c28499de0b1edbf526c4ddd964af
Ruby
nagi/fishy
/lib/game_over.rb
UTF-8
82
2.671875
3
[]
no_license
class GameOver attr_reader :why def initialize(why) @why = why end end
true
a69cd4eab6225b3b6b8df794e69fcd362947d650
Ruby
simonovich88/cycles-and-pattern
/patron2.rb
UTF-8
205
3.125
3
[]
no_license
n=ARGV[0].to_i (n/2).times do |i| if i.even? print "**" else print ".." end end if n.even? print " " else if ((n/2)%2!=0) print "." else print "*" end end
true
75ff350fc4178f34d9f2555d1410c612974798e9
Ruby
karthickpdy/CP
/a20j/array.rb
UTF-8
592
3.34375
3
[]
no_license
n = gets.to_i arr = gets.split(" ").map(&:to_i) zero_array = arr.select{|i| i == 0} zero_count = zero_array.length pos_array = arr.select{|i| i > 0} pos_count = pos_array.length neg_count = n - zero_count - pos_count neg_array = arr - pos_array - zero_array if pos_count == 0 pos_array << neg_array.pop pos_array << neg_array.pop neg_count -= 2 pos_count += 2 end if neg_count.even? zero_array << neg_array.pop zero_count += 1 neg_count -= 1 end puts "#{neg_count} #{neg_array.join(' ')}" puts "#{pos_count} #{pos_array.join(' ')}" puts "#{zero_count} #{zero_array.join(' ')}"
true
0f9e5c345c83c368f2b954954cd4b4ff268f63c9
Ruby
TatsuyaIsamu/Arrays
/sample.rb
UTF-8
268
2.828125
3
[]
no_license
File.open("./sample.txt", "w") do |file| file.puts("追加テキスト1") file.puts("追加テキスト2") file.puts("追加テキスト3") end # File.open メソッドは外部リソースを使用するのでブロックを使うことでスコープを作る
true
ab81ba0f3b1ef5905e29a8fd90a93020b1c5c714
Ruby
vlebedeff/exercise
/lib/exercise/lcs.rb
UTF-8
1,269
3.34375
3
[]
no_license
module Exercise # Longest common subsequence of two strings that appears in the same relative order, but not # necessarily contiguous def lcs(s1, s2) table = Array.new(s1.size + 1) { Array.new(s2.size + 1) { 0 } } 1.upto(s1.size) do |i| 1.upto(s2.size) do |j| table[i][j] = if s1[i - 1] == s2[j - 1] table[i - 1][j - 1] + 1 else [table[i][j - 1], table[i - 1][j]].max end end end table[s1.size][s2.size] end # Longest common subsequence of three strings def lcs3(s1, s2, s3) table = Array.new(s1.size + 1) { Array.new(s2.size + 1) { Array.new(s3.size + 1) { 0 } } } 1.upto(s1.size) do |i| 1.upto(s2.size) do |j| 1.upto(s3.size) do |k| table[i][j][k] = if s1[i - 1] == s2[j - 1] && s1[i - 1] == s3[k - 1] table[i - 1][j - 1][k - 1] + 1 else [ table[i][j][k - 1], table[i][j - 1][k], table[i][j - 1][k - 1], table[i - 1][j][k], table[i - 1][j][k - 1], table[i - 1][j - 1][k] ].max end end end end table[s1.size][s2.size][s3.size] end end
true
9f3db14a379b9b28cafe91c793907f52a510946e
Ruby
fireworksinnovation/za-id-validator
/test/test_za-id-validator.rb
UTF-8
2,020
2.859375
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
require 'helper' class TestZaIdValidator < Test::Unit::TestCase include ZaIdValidator context "a valid ID number" do # Test and ID number based on data from # http://en.wikipedia.org/wiki/National_identification_number#South_Africa setup do @valid = "8001015009087" @valid_integer = 8001015009087 end should "be the correct length" do assert length_is_valid?(@valid) # flunk "hey buddy, you should probably rename this file and start testing for real" end should "have the correct A sum" do # 8+0+0+5+0+0 = 13 assert_equal 13, a(@valid) end should "have the correct B concatenation" do assert_equal "011098", b(@valid) end should "have the correct C value" do # (011098 * 2) = 22196 # 2 + 2 + 1 + 9 + 6 = 20 assert_equal 20, c(@valid) end should "have the right Z check digit" do assert_equal 7, z(@valid) end should "be a valid ID number" do result = valid_za_identity_number?(@valid) assert_not_nil(result) assert(result) end should "be a valid ID number (when passed as an int)" do result = valid_za_identity_number?(@valid_integer) assert_not_nil(result) assert(result) end end context "an invalid ID number" do setup do @invalid = "8001015009086" end should "not be a valid ID number" do result = valid_za_identity_number?(@invalid) assert_not_nil(result) assert(!result) end end context "an ID number that is too long" do setup do @too_long = "80010150090871" @too_long_integer = 80010150090871 end should "not be a valid ID number" do result = valid_za_identity_number?(@too_long) assert_not_nil(result) assert(!result) end should "not be a valid ID number (when passed as an int)" do result = valid_za_identity_number?(@too_long_integer) assert_not_nil(result) assert(!result) end end end
true
71765aacfb2ac0cc4cf523fd95d12e36784ea48c
Ruby
mwagner19446/wdi_work
/w01/d04/Isaac/receipt_reader.rb
UTF-8
286
3.390625
3
[]
no_license
# read information from a receipt and print it out to the user f = File.open("receipt.txt", "r") string_version_of_receipt = f.read array = string_version_of_receipt.split("\n") selector = array.select{|line| line.length>0}.select{ |line| line.include?("$")} puts selector f.close
true
920d4a20ad2496096d6985b84ca7e3e3b371cf71
Ruby
kadambarijena/ruby-exercises
/cli/cli_equal.rb
UTF-8
90
2.578125
3
[]
no_license
# Equal two operands reading command line # ["a", "b"] puts ARGV[0].to_i == ARGV[1].to_i
true
284ebe36d10509b9f5e021b8fa673486444146ad
Ruby
nathanstruhs/the_odin_project
/oop/tic_tac_toe/board.rb
UTF-8
2,226
4
4
[]
no_license
class Board def initialize @board = [" ", " ", " ", " ", " ", " ", " ", " ", " ", " "] @current_player = "" end def display puts puts "3|#{@board[0]}|#{@board[1]}|#{@board[2]}|" puts "2|#{@board[3]}|#{@board[4]}|#{@board[5]}|" puts "1|#{@board[6]}|#{@board[7]}|#{@board[8]}|" puts " a b c " puts end def process_move(input) case when input == "a3" || input == "3a" return 0 when input == "b3" || input == "3b" return 1 when input == "c3" || input == "3c" return 2 when input == "a2" || input == "2a" return 3 when input == "b2" || input == "2b" return 4 when input == "c2" || input == "2c" return 5 when input == "a1" || input == "1a" return 6 when input == "b1" || input == "1b" return 7 when input == "c1" || input == "1c" return 8 else puts "Error, please enter move coordinates." return nil end end def already_played?(input) if @board[input] == "X" || @board[input] == "O" puts "Those coordinates have already been played." return true end end def move(player, position) @board[position] = player.type end def win?(current_player) case when @board[0] == current_player.type && @board[1] == current_player.type && @board[2] == current_player.type return true when @board[3] == current_player.type && @board[4] == current_player.type && @board[5] == current_player.type return true when @board[6] == current_player.type && @board[7] == current_player.type && @board[8] == current_player.type return true when @board[0] == current_player.type && @board[3] == current_player.type && @board[6] == current_player.type return true when @board[1] == current_player.type && @board[4] == current_player.type && @board[7] == current_player.type return true when @board[2] == current_player.type && @board[5] == current_player.type && @board[8] == current_player.type return true when @board[0] == current_player.type && @board[4] == current_player.type && @board[8] == current_player.type return true when @board[2] == current_player.type && @board[4] == current_player.type && @board[6] == current_player.type return true else return false end end end
true
f0c2bd4c5f1f44022b14b64332f5d1b04340368f
Ruby
dpaden/salvo2
/app/models/move.rb
UTF-8
314
2.515625
3
[]
no_license
class Move < ActiveRecord::Base belongs_to :game belongs_to :user #must be in format A:N where A is between A-J(Upper Case) and N is an integer between 1 and 10, 2 OR 3 Alpha Numberics only VALID_MOVE_REGEX = /\A[A-J][1-9]0?\z/ validates :location, presence: true, format: { with: VALID_MOVE_REGEX } end
true
97c5476b2a7a6da9298d2036a017fbe875095a1d
Ruby
jdbernardi/assignment_knights_travails
/tree.rb
UTF-8
1,520
3.546875
4
[]
no_license
Move = Struct.new( :x, :y, :depth, :children, :parent ) class Tree attr_reader :coords, :max_depth, :root, :depth def initialize( coords, max_depth ) @root = Move.new( coords[0], coords[1], 0, [], nil ) @max_depth = max_depth @current_node = @root @count = 1 create_moves end def create_moves queue = [] while @current_node.depth < @max_depth get_children( @current_node ) @current_node.children.each do | n | queue << n @count += 1 end @current_node = queue.shift end end def add_parent( parent, new_node ) parent.children << new_node new_node.parent = parent end def get_children( parent ) moves = within_board?( [ parent.x, parent.y ]) moves.each do | coords | new_node = Move.new( coords[ 0 ], coords[ 1 ], parent.depth + 1, [], nil ) add_parent( @current_node, new_node ) end return parent end def within_board?( move ) x = move[ 0 ] y = move[ 1 ] moves = [] arr = [ [ x + 2, y - 1 ], [ x + 2, y + 1 ], [ x + 1, y - 2 ], [ x - 1, y - 2 ], [ x - 2, y + 1 ], [ x - 2, y - 1 ], [ x - 1, y + 2 ], [ x + 1, y + 2 ] ] arr.each do | coords | moves << coords if valid_move?( coords ) end moves end def valid_move?( coord ) return true if ( 0..7 ) === coord[ 0 ] && ( 0..7 ) === coord[ 1 ] end def inspect puts "Tree has #{ @count } Move nodes and a maximun depth of #{@max_depth}" end end
true
48507a6b3f889df18e23533f5c35f9e01dda93af
Ruby
AdamLombard/LS-coursework
/exercises/RubyBasics/UserInput/07-UserNameAndPassword.rb
UTF-8
318
2.953125
3
[]
no_license
USERNAME = 'admin' PASSWORD = 'password' loop do puts ">> Please enter your username:" username_attempt = gets.chomp puts ">> Please enter your password:" password_attempt = gets.chomp break if username_attempt == USERNAME && password_attempt == PASSWORD puts ">> Access denied!" end puts ">> Welcome!"
true
fad7d70081951072f4a380043e59f04acbe1cba7
Ruby
NJichev/blogster
/spec/templates_spec.rb
UTF-8
1,511
2.6875
3
[ "MIT" ]
permissive
require 'spec_helper' describe Blogster::Template do it 'can save path to templates' do path = '/home/terran/scv' name = 'build.md' template = t(path, name) expect(template.path).to eq path expect(template.fullpath).to eq File.join(path, name) end end describe Blogster::Templates do it 'can give us the pages' do expect(templates.pages).to eq %w(about starcraft) end it 'can give us the templates' do expect(templates['starcraft']).to match_array starcraft_templates end it 'can write templates' do posts = [t('/home/me/blog/_posts/', 'vim.md')] templates['posts'] = posts expect(templates['posts']).to match_array posts end it 'can iterate over the templates of a page' do template_names = [] templates['starcraft'].each do |template| template_names << template.name end expect(template_names).to match_array %w(terran zerg protoss) end def templates templates_hash = { 'about' => about_templates, 'starcraft' => starcraft_templates } @templates ||= Blogster::Templates.new(templates_hash) end def about_templates [ t('/home/me/blog/_about/', 'me.md'), t('/home/me/blog/_about/', 'introduction.md') ] end def starcraft_templates [ t('/home/me/blog/_starcraft/', 'terran.md'), t('/home/me/blog/_starcraft/', 'zerg.md'), t('/home/me/blog/_starcraft/', 'protoss.md') ] end end def t(path, name) Blogster::Template.new(path, name) end
true
5f92f6b4aa7a96e7ba15ff50749ee69a03d34526
Ruby
mjschwartz/high_sn_hn
/lib/high_sn_hn/workers/items_worker.rb
UTF-8
770
2.53125
3
[]
no_license
module HighSnHn class ItemsWorker @queue = :high_sn def self.perform(min_item, max_item) return unless min_item.to_i > 0 && max_item.to_i > 0 (min_item..max_item).each do |id| begin #LOGGER.info("ItemsWorker for: #{id}") item = HighSnHn::HnItem.new(id) if item.should_fetch? #LOGGER.info("Fetching HnItem ##{id}") item.fetch end rescue NullItemResult => e # there was no HTTP result for the item fetch - requeue #LOGGER.error("#{e}") HighSnHn::ReEnqueueItem.new(id) end end rescue Exception => e LOGGER.error("there was some other error: #{e}") LOGGER.error("#{e.backtrace.join("\n")}") end end end
true
3f8f860f93ab6a1a2ab55499a64c8cc90b0ba59c
Ruby
Rockster160/Games
/aoc2022/d16.rb
UTF-8
5,004
2.84375
3
[]
no_license
# $test = true $part = 1 # $pryonce || ($pryonce ||= true) && binding.pry require "/Users/rocco/code/games/aoc2022/base" # Draw.cell_width = 1 input = File.read("/Users/rocco/code/games/aoc2022/d16.txt") input = "Valve AA has flow rate=0; tunnels lead to valves DD, II, BB Valve BB has flow rate=13; tunnels lead to valves CC, AA Valve CC has flow rate=2; tunnels lead to valves DD, BB Valve DD has flow rate=20; tunnels lead to valves CC, AA, EE Valve EE has flow rate=3; tunnels lead to valves FF, DD Valve FF has flow rate=0; tunnels lead to valves EE, GG Valve GG has flow rate=0; tunnels lead to valves FF, HH Valve HH has flow rate=22; tunnel leads to valve GG Valve II has flow rate=0; tunnels lead to valves AA, JJ Valve JJ has flow rate=21; tunnel leads to valve II" if $test class Area attr_accessor :name, :rate, :connections, :paths def initialize(name, rate, connections) @name = name @rate = rate.to_i @connections = connections.split(", ") @paths = [] $areas[name] = self end def tunnels @connections.map { |path| $areas[path] } end end # worth = $areas.select { |_name, area| area.rate > 0 } def explore(area, path=[]) path = path + [area.name] start = ($paths[path.first] ||= {}) old_dist = start[path.last]&.length if path.length > 1 && (old_dist.nil? || old_dist > path.length) start[path.last] = path[1..] end area.tunnels.each { |down| explore(down, path) unless path.include?(down.name) } end $paths = {} $areas = {} $pressurized_valves = [] $countdown = 30 input.split("\n").each_with_index { |row, idx| _, name, rate, tunnels = row.match(/Valve (\w+) has flow rate=(\d+); tunnels? leads? to valves? ((?:\w+(, )?)*)/).to_a area = Area.new(name, rate, tunnels) $pressurized_valves.push(area) if area.rate > 0 } Benchmark.time("Find all Paths") do |bm| $areas.each_with_index do |(_name, area), idx| explore(area) end end class Adventure attr_accessor :current, :steps, :pressure, :pressurized_valves, :open_valves def initialize @current = $areas["AA"] @steps = [] @pressure = 0 @open_valves = [] @pressurized_valves = $pressurized_valves.dup end def alternate_reality # Need to deep clone self.dup.tap { |alternate| alternate.current = @current.dup alternate.steps = @steps.dup alternate.pressure = @pressure.dup alternate.pressurized_valves = @pressurized_valves.dup alternate.open_valves = @open_valves.dup } end def debug cpressure = 0 valves_open = {} @steps.each_with_index do |step, idx| puts "== Minute #{idx+1} ==" if valves_open.length == 0 puts "No valves are open." elsif valves_open.length == 1 puts "Valve #{valves_open.keys.first} is open, releasing #{valves_open.values.first} pressure." else names = valves_open.keys.sort.tap { |a| a[-1] = "and #{a[-1]}" } names = names.length == 2 ? names.join(" ") : names.join(", ") puts "Valves #{names} are open, releasing #{valves_open.values.sum} pressure." end cpressure += valves_open.values.sum name = step[/\w+$/] if step.match?(/^move/i) puts "You move to valve #{name}." else puts "You open valve #{name}." $pryonce || ($pryonce ||= true) && binding.pry if $areas[name].nil? valves_open[name] = $areas[name].rate end puts "" end end def open_valve(area) path = $paths[@current.name][area.name] @steps += path.map { |step| "Move to #{step}" } @steps += ["Open valve #{area.name}"] @pressure += ($countdown - @steps.length) * area.rate @current = area @open_valves.push(area) @pressurized_valves.reject! { |valve| valve.name == area.name } end end def continue_journey(adventure=Adventure.new) if adventure.steps.length >= $countdown || adventure.pressurized_valves.length == 0 $completed << adventure # if adventure.steps == ["Move to DD", "Open valve DD"] # $pryonce || ($pryonce ||= true) && binding.pry # end return end available = adventure.pressurized_valves smart = available.select { |valve| path = $paths[adventure.current.name][valve.name] # You would never walk past an on_valve that's higher than the one you're going to next false if path.length + 1 > $countdown - adventure.steps.length true } smart.each do |goal_valve| alternate = adventure.alternate_reality alternate.open_valve(goal_valve) continue_journey(alternate) end end puts "Direct paths: #{$paths.sum { |starts, ends| ends.keys.length }}" $completed = [] Benchmark.time("Journey") do |bm| continue_journey end puts "Possible Adventures: #{$completed.count}" best = nil Benchmark.time("Get best") do |bm| best = $completed.max { |a1, a2| a1.pressure <=> a2.pressure } end puts best.inspect puts "Pressure Released: #{best.pressure}" puts best.debug # $pryonce || ($pryonce ||= true) && binding.pry # TOO LOW -- 1824
true
ebab9cfaec3efc14e8b6101f57c19c2b5eca723e
Ruby
andyss/active_tool
/lib/active_tool/relation_prob.rb
UTF-8
3,419
2.546875
3
[]
no_license
module ActiveTool module RelationProb class RelationModeProb attr_accessor :mode attr_accessor :probs def initialize(mode, &block) @mode = mode @probs = {} self.instance_eval(&block) end def add_prob(name, options={}) @probs[name] = options end end class RelationMode attr_accessor :name attr_accessor :relations def initialize(name, &block) @name = name @relations = {} self.instance_eval(&block) end def add_relation(mode, &block) @relations[mode] = RelationModeProb.new(mode, &block) end def has?(key) keys.index(key) end def keys self.relations.keys end end def self.included(base) base.extend(ClassMethods) end def relation_modes self.class.relation_modes end def relation_mode_attrs self.class.relation_mode_attrs end def get_value(str) self.send(str) end def set_value(str, value) self.send("#{str}=", [[value, 0].max, 100].min) end def incr_value(mode_attr, mode, relation, value) attr_str = "#{mode_attr}_prob_#{mode}_#{relation}" tmp_value = get_value(attr_str) set_value(attr_str, tmp_value + value) end def change_value(mode_attr, mode, relation, value, incr=false) attr_str = "#{mode_attr}_prob_#{mode}_#{relation}" tmp_value = get_value(attr_str) if incr set_value(attr_str, tmp_value + value) else set_value(attr_str, tmp_value - value) end end def decr_relation(mode, relation, type, mode_attr) # p "decr: #{relation_obj.probs[type][:decr]}" mode_obj = self.relation_modes[mode] relation_obj = mode_obj.relations[relation] decr = relation_obj.probs[type][:decr] change_value(mode_attr, mode, relation, decr) end def decr_relations(mode, relations, type, mode_attr) relations.map do |relation| decr_relation(mode, relation, type, mode_attr) end end def incr_relation(mode, relation, type, mode_attr) mode_obj = self.relation_modes[mode] relation_obj = mode_obj.relations[relation] incr = relation_obj.probs[type][:incr] change_value(mode_attr, mode, relation, incr, true) end def incr_relations(mode, relations, type, mode_attr) relations.map do |relation| incr_relation(mode, relation, type, mode_attr) end end def set_relation_prob(mode, relation, type, mode_attr=nil) mode_obj = self.relation_modes[mode] mode_attr = type unless mode_attr if mode_obj.has?(relation) decr_relation(mode, relation, type, mode_attr) end incr_relations(mode, mode_obj.keys - [relation], type, mode_attr) self end module ClassMethods def relation_modes @@relation_modes end def relation_mode_attrs @@relation_mode_attrs end def add_mode_attr(*attrs) @@relation_mode_attrs ||= [] @@relation_mode_attrs += attrs end def add_relation_mode(mode, &block) @@relation_modes ||= {} @@relation_modes[mode] = RelationMode.new(mode, &block) end end end end
true
755785d78c69095811126fc914d3ba0c6a4f81c4
Ruby
frantzmiccoli/Gimuby
/tests/genetic/archipelago/test_connected_measure.rb
UTF-8
1,316
2.921875
3
[ "MIT", "LicenseRef-scancode-other-permissive" ]
permissive
require './abstract_test_case' require './mock/population_mock' require 'gimuby/genetic/archipelago/archipelago' require 'gimuby/genetic/archipelago/measure/connected_measure' class TestConnectedMeasure < AbstractTestCase def test_compute size = 10 archipelago = get_archipelago(size) measure = get_connected_measure message = 'No connection, no connected' assert_equal(size, measure.compute(archipelago), message) archipelago.connect(0, 1) message = 'One connection, one class less' assert_equal(size - 1, measure.compute(archipelago), message) archipelago.connect(2, 1) message = 'Two connections, one class less' assert_equal(size - 2, measure.compute(archipelago), message) archipelago.connect(2, 0) message = 'Three connections, no class less ' assert_equal(size - 2, measure.compute(archipelago), message) archipelago.connect(6, 7) message = 'Four connections, one class less' assert_equal(size - 3, measure.compute(archipelago), message) end def get_archipelago(size) archipelago = Archipelago.new size.times do |_| archipelago.add_population(get_mock_population) end archipelago end def get_connected_measure ConnectedMeasure.new end def get_mock_population PopulationMock.new end end
true
0b36117b32deaf58b1478b4db14f79efbe314c5a
Ruby
pranavnawathe/DesignPatternsNew
/ruby/Memento/.idea/home_theatre.rb
UTF-8
474
3.4375
3
[]
no_license
class HomeTheatre def initialize(ledTv, speaker) @ledTv = ledTv @speaker = speaker @@stateCount +=1 end def getLedTv @ledTv end def setLedTv(ledTv) @ledTv = ledTv end def getSpeaker @speaker end def setSpeaker(speaker) @speaker = speaker end def self.getStateCount() @@stateCount end def toString "HomeTheatre [ledTV = #{@ledTv} Speaker = #{@speaker}]" end end
true
4d4bdcd3c1025cbf318b6ffce6b6a5223c509113
Ruby
apoorvmishra28/whoisproject
/whoisDB.rb
UTF-8
438
2.75
3
[]
no_license
require 'whois-parser' # Arguments to be input by user Domain = ARGV[0] record = Whois.whois(Domain) #whois all-in-one method which fetches complete data at once for given domain parser = Whois::Parser.new(record) # created whois-parser object which is further used for parsing whois informaition puts parser.created_on puts parser.updated_on puts parser.expires_on parser.nameservers.each do |nameserver| puts nameserver end
true
a006d1f8b41feceb96c56804d9b6001f167dd432
Ruby
danelowe/magedetect
/spec/workers/sites_worker_spec.rb
UTF-8
1,243
2.515625
3
[]
no_license
require_relative '../spec_helper' class Indicators::Test def self.run site site.score += 1 true end end # We want to stub out create_csv, but using a mock will stub out other methods we want to test. SitesWorker.instance_eval do private def create_csv name, sites, header CSV.open(File.join(SPEC_PATH, 'fixtures', 'test.csv'), 'wb').path end end describe SitesWorker do describe '#perform' do let(:urls) { ['http://demo.magentocommerce.com/', 'www.goodasgold.co.nz'] } let(:email) { Sinatra::Application.from_email } before do allow(Indicators).to receive(:all).and_return([Indicators::Test]) @mail = double @mail.stub(:deliver) allow(Mailer).to receive(:csv).and_return(@mail) end it 'calls all indicators for each url passed in' do Indicators::Test.should_receive(:run).exactly(2).times SitesWorker.new.perform(urls, email) end it 'creates a results csv and a summary csv' do SitesWorker.any_instance.should_receive(:create_csv).exactly(2).times SitesWorker.new.perform(urls, email) end it 'sends an email to the email passed in' do @mail.should_receive(:deliver) SitesWorker.new.perform(urls, email) end end end
true
7b7a4a38006df33810e424581aea2a0ba2181cd8
Ruby
rene-dev/pqongmaps
/app.rb
UTF-8
2,918
2.65625
3
[]
no_license
#! /usr/bin/env ruby # Import gems for Sinatra, XML-parsing and json stuff require 'rubygems' require 'bundler' Bundler.require class Cache < ActiveRecord::Base def self.in_area(lat1,lon1,lat2,lon2) where("lat > #{lat2} and lat < #{lat1} and lon > #{lon2} and lon < #{lon1}") end end class Pqongmaps < Sinatra::Base # Registering some plugins register SinatraMore::RoutingPlugin register SinatraMore::MarkupPlugin # Defining the routes map(:home).to("/") map(:upload).to("/upload") map(:pins).to("/pins.json") map(:garmin).to("/garmin") def parse_type(type) # Parse the type of the cache for proper image displaying type_no = case type when 'Geocache|Unknown Cache' then 8 when 'Geocache|Traditional Cache' then 2 when 'Geocache|Multi-cache' then 3 when 'Geocache|Virtual Cache' then 4 else 8 end return type_no end #every time the viewport of the map changes, a callback gets the pins #for the new viewport from this json file. get (:pins) do content_type :json #ask the database which caches are in the viewport, and return them as json Cache.select('name,lat,lon,gc_type').in_area(params['lat1'],params['lon1'],params['lat2'],params['lon2']).to_json end # Handle GET-request (Show the upload form) get (:upload) do erb :upload end # Handle POST-request (Receive and save the uploaded file) post (:upload) do #save file to uploads folder File.open('uploads/' + params['myfile'][:filename], "w") do |f| f.write(params['myfile'][:tempfile].read) end gpx = Nokogiri::XML(File.open('uploads/'+params['myfile'][:filename])) # Open the gpx lat = (gpx.css('bounds')[0].values[0].to_f+gpx.css('bounds')[0].values[2].to_f)/2 #parse boundaries of query lon = (gpx.css('bounds')[0].values[1].to_f+gpx.css('bounds')[0].values[3].to_f)/2 old = 0 new = 0 #add ALL the caches to the database gpx.css('wpt').each do |wpt| cache = Cache.find_or_initialize_by_gccode(:name => wpt.css('urlname').inner_text, #add cache to the database :gccode => wpt.css('name').inner_text, :lat => wpt.values[0], :lon => wpt.values[1], :gc_type => parse_type(wpt.css('type').inner_text).to_i, :terrain => wpt.css('groundspeak:cache').css('groundspeak:difficulty').inner_text.to_i, :difficulty => wpt.css('groundspeak:cache').css('groundspeak:terrain').inner_text.to_i) if cache.persisted? #skip if already in db old = old+1 else new = new+1 cache.save #add new caches to db end end return "Imported #{new} caches, ignored #{old} duplicates" end get '/' do @apikey = '' # Define the GMaps Api key erb :index # Call the view end get (:garmin) do erb :garmin # Call the garmin view end end
true
0a707d61db8df31cc941f273154cceb811c7c993
Ruby
liantics/MetisPracticeFiles
/Week1/flash_cards/normal/musicdeck.rb
UTF-8
263
2.9375
3
[]
no_license
require './musiccards' class Deck def initialize(cards) @cards = cards end # def play # @cards.each do |card| # card.play # end # @cards # puts "playing" # end end deck = Deck.new("musiccards.csv") #cards is the filename of the cards file
true
7fc16dcdef7d8bc3f0db1a5e41d7adb36aa752f4
Ruby
CDL-Dryad/dryad-app
/app/helpers/stash_engine/link_generator.rb
UTF-8
5,207
2.90625
3
[ "MIT" ]
permissive
module StashEngine module LinkGenerator def self.create_link(type:, value:) # get [link_text, href] back from the id so we can create normal <a href link> send(type.downcase, value) end # This *should* only be called from #create_link, and if we reach it, # it's because the identifier type is one that we didn't know how to handle, # in which case we just return the identifier as-is. def self.method_missing(_method_name, *arguments) arguments.first end # (see #method_missing) def self.respond_to_missing?(*_args) true end # all these return [link_text, url] def self.doi(value) # example reference: doi:10.5061/DRYAD.VN88Q # example url: http://doi.org/10.5061/DRYAD.VN88Q item = Fixolator.new(id_value: value, target_prefix: 'doi:', resolver_prefix: 'https://doi.org/').text_and_link [item[1], item[1]] end def self.ark(value) # example reference: ark:/13030/m55d9m2t # example url: http://n2t.net/ark:/13030/m55d9m2t Fixolator.new(id_value: value, target_prefix: 'ark:/', resolver_prefix: 'http://n2t.net/ark:/').text_and_link end def self.arxiv(value) # info at https://arxiv.org/help/arxiv_identifier # example reference: arXiv:1212.4795 # example url: https://arxiv.org/abs/1212.4795 Fixolator.new(id_value: value, target_prefix: 'arXiv:', resolver_prefix: 'https://arxiv.org/abs/').text_and_link end def self.handle(value) # handle urls look like http://hdl.handle.net/2027.42/67268 sometimes. Also hdl:1839/00-0000-0000-0009-3C7E-F # it seems like they do not represent them like handle:/2027/67268 or anything that I can find, but as full urls # in the citations I'm seeing Fixolator.new(id_value: value, target_prefix: 'hdl:', resolver_prefix: 'https://hdl.handle.net/').text_and_link end def self.isbn(value) # ISBNs are just numbers with maybe dashes in them (or spaces?) # a url like this seems to return results for isbns from worldcat. http://www.worldcat.org/search?q=bn%3A0142000280 Fixolator.new(id_value: value, target_prefix: 'ISBN: ', resolver_prefix: 'http://www.worldcat.org/search?q=bn%3A').text_and_link end def self.pmid(value) # pubmed id references look like PMID: 19386008 # the urls look like https://www.ncbi.nlm.nih.gov/pubmed/19386008 Fixolator.new(id_value: value, target_prefix: 'PMID: ', resolver_prefix: 'https://www.ncbi.nlm.nih.gov/pubmed/').text_and_link end def self.purl(value) # it seems like PURLs are essentially just URLs that resolve to something else, so something like # http://purl.org/net/ea/cleath/docs/cat/ value = "http://#{value}" unless value.strip.start_with?('http') [value, value] end def self.url(value) # I think people should be able to put them in correctly by copy/pasting, but maybe # people leave off the http(s) sometimes? value = "http://#{value}" unless value.nil? || value.strip.start_with?('http') [value, value] end def self.urn(value) # a urn could be a url or other things that may resolve or not resolve. Just pass it on through. value end # A standard fixing and extracting class to get parts of many identifiers. # The goal is to take link text and identifier values and break the identifier values into parts # so that we can separate something like like doi:10.5061/DRYAD.VN88Q into # 1) identifier prefix and 2) bare identifier itself. In the example above, 1) is doi: , 2) is 10.5061/DRYAD.VN88Q # if the item is really a url for resolution (starting with http) then we need to know that, also. class Fixolator # id_value would be something that the user typed in and may be full of garbage # target_prefix is what we know the generally used prefix should be when it's written # usually as a reference such as doi: or ark:/ def initialize(id_value:, target_prefix:, resolver_prefix:) @id_value = id_value @target_prefix = target_prefix @resolver_prefix = resolver_prefix if id_value.nil? @is_http_url = false @prefix_correct = false else @is_http_url = id_value.strip.downcase.start_with?('http') @prefix_correct = id_value.strip.downcase.start_with?(target_prefix.strip.downcase) end end def http_url? @is_http_url end def prefix_correct? @prefix_correct end def reference_form return @id_value if http_url? "#{@target_prefix}#{bare_id}" end def bare_id if prefix_correct? # remove the prefix and give bare id @id_value[@target_prefix.strip.length..].strip else # they must've given it as a bare id if it didn't have the prefix (and isn't a URL) @id_value&.strip end end # returns text and link for creating a URL def text_and_link return [@id_value, @id_value] if http_url? [reference_form, "#{@resolver_prefix}#{bare_id}"] end end end end
true
64b98b62782af6b425a8ad6968195751635869f1
Ruby
herrklaseen/babysleep
/app/models/sleeptime.rb
UTF-8
1,663
3.09375
3
[]
no_license
class Sleeptime < ActiveRecord::Base attr_accessible :start, :duration belongs_to :baby, :inverse_of => :sleeptimes validates :baby, { :presence => true } validates :start, { :presence => true } validates :duration, { :presence => true, :numericality => { :only_integer => true, :greater_than => 0 } } def self.make_instance (starttime, endtime, baby_object = nil) sleeptime_object = Sleeptime.new sleeptime_object.baby = baby_object begin sleeptime_object.start = self.parse(starttime) endtime = self.parse(endtime) rescue ArgumentError sleeptime_object.start = nil end if (sleeptime_object.start?) if (sleeptime_object.start > endtime) sleeptime_object.start += -24.hours end if (endtime > DateTime.current()) return sleeptime_object end sleeptime_object.duration = self.create_duration(sleeptime_object.start, endtime) end sleeptime_object end def self.seconds_to_human_readable(seconds, locale='en') hours = (seconds / 1.hour.to_i).floor remaining_seconds = seconds - (hours * 1.hour.to_i) minutes = (remaining_seconds / 1.minute.to_i).floor "#{hours} h, #{minutes} min" end def self.seconds_to_percentage_of_24h(seconds) sleep_percentage = ((seconds / 24.hours.to_f) * 100).round wake_percentage = 100 - sleep_percentage [sleep_percentage, wake_percentage] end private def self.parse(date_string) DateTime.strptime(date_string, '%H%M') end def self.create_duration(starttime, endtime) duration = endtime.to_i - starttime.to_i end end
true
d78a9d5c7830c04f9f4c1fa5831323684746f45f
Ruby
jbmenashi/dunder-mifflin-rails-review-nyc-web-102918
/app/models/dog.rb
UTF-8
197
2.515625
3
[]
no_license
class Dog < ApplicationRecord has_many :employees def employee_count self.employees.count end def self.sort_by_employee_count Dog.all.sort_by(&:employee_count).reverse end end
true
43dd6fe42dc2114cac348a3b66262491d3651490
Ruby
jeromeOthot/Puzzle-Quest-Adventure
/Scripts/Puzzle/Window/Window_PuzzleChrono.rb
UTF-8
1,661
2.71875
3
[]
no_license
#D�claration des constantes HERO_WEAPON_POS_X = 16 HERO_WEAPON_POS_Y = 0 HERO_SHIELD_POS_X = 80 HERO_SHIELD_POS_Y = 0 HERO_ARMOR_POS_X = 0 HERO_ARMOR_POS_Y = 32 HERO_HELMET_POS_X = 32 HERO_HELMET_POS_Y = 32 HERO_BOOTS_POS_X = 64 HERO_BOOTS_POS_Y = 32 HERO_ACCESSORIES_POS_X = 96 HERO_ACCESSORIES_POS_Y = 32 HERO_DEFENSE_POS_X = 0 HERO_DEFENSE_POS_Y = 64 HERO_SKULL_POS_X = 48 HERO_SKULL_POS_Y = 64 class Window_PuzzleChrono < Window_Base #-------------------------------------------------------------------------- # Constructeur #-------------------------------------------------------------------------- def initialize() super(0, 0, 196, 113) draw_icon(1505, 2, 2, enabled = true) draw_icon(8687, 2, 30, enabled = true) draw_time() draw_nbMove() @nbMove = 0 end def draw_icon(icon_index, x, y, enabled = true) bit = Cache.system("bigset") rect = Rect.new(icon_index % 16 * 24, icon_index / 16 * 24, 24, 24) self.contents.blt(x, y, bit, rect, enabled ? 255 : 150) end def draw_time() draw_text( 25, -2, 80, 40, "Time: " + $game_chrono.min().to_s + ":" + $game_chrono.sec().to_s + " min" ) end def incrementNbMove() @nbMove += 1 end def decrementNbMove() if( @nbMove > 0 ) @nbMove -= 1 end end def draw_nbMove() draw_text( 25, 25, 80, 40, @nbMove.to_s + " moves" ) end def update() if( ($game_chrono.count % Graphics.frame_rate) == 0 ) contents.clear() draw_icon(1505, 2, 2, enabled = true) #Hourglass draw_icon(8687, 2, 30, enabled = true) #Icon move gems draw_time() draw_nbMove() end end end
true
db35bb45c866733ca31787c0520b18e905b5d181
Ruby
MariusGG/The_Kingdom
/spec/landCreature_spec.rb
UTF-8
480
2.671875
3
[]
no_license
require 'landCreature' describe LandCreature do it { expect(described_class).to be < TheKingdom } it "should have a starting health point of 10" do expect(subject.hp).to eq 10 end it "has a random amount generator" do expect(subject).to receive(:rand).and_return(12345) expect(subject.amount).to eq 12345 end it "can run but will lose a random amount to health point" do expect{subject.run}.to change{subject.hp}.from (10) end end
true
c723405527162ac4f66d15294bee176f9c7ff059
Ruby
bmedici/rbpm
/app/models/step_watchfolder.rb
UTF-8
3,185
2.5625
3
[ "MIT" ]
permissive
class StepWatchfolder < Step def paramdef { :watch => { :description => "Incoming folder to watch", :format => :text, :lines => 2 }, :target => { :description => "Target folder to move the detected file", :format => :text, :lines => 2 }, :delay => { :description => "Delay to wait when watching folder (seconds)", :format => :text, :lines => 1 }, } end def color '#C6B299' end def run(current_job, current_action) # Init watch = self.pval(:watch) target = self.pval(:target) delay = self.pval(:delay).to_f # Delay is default unless specified delay = 0.5 if delay.zero? # Check for run context log "StepWatchfolder starting" return 21, "depends on the run context to gather variables, no valid current_job given" if current_job.nil? # Evaluate source file and targt dir evaluated_watch = current_job.evaluate(watch) log "evaluated watch: #{evaluated_watch}" # Check for directory presence return 21, "watch directory not found (#{evaluated_watch})" unless File.directory? evaluated_watch # Wait for a file in the watchfolder filter_watch = "#{evaluated_watch}/*" log "watching with delay (#{delay}s) and filter (#{filter_watch})" begin # Try to detect a file first_file = Dir[filter_watch].first #first_file = Dir['/Users/bruno/web/rbpm/tmp/incoming'].first # If found, continue outside of this loop break unless first_file.nil? # Otherwise, wait before looping #log " - nothing" sleep delay # Touch job self.touch_beanstalk_job end while true # A file has been detected basename = File.basename(first_file) log "detected (#{basename})" # Compute target directory and filename evaluated_target = current_job.evaluate(target) log "evaluated target: #{evaluated_target}" target_file = "#{evaluated_target}/#{File.basename(first_file)}" # Create the target directory if not found unless File.directory? evaluated_target log "making directory (#{evaluated_target})" begin FileUtils.mkdir_p(evaluated_target, :mode => 0777) rescue Exception => e msg = "uncaught exception: #{e.message}" log msg return 32, msg end end # Move file to target dir log "moving (#{first_file}) to (#{target_file})" begin FileUtils.mv(first_file, target_file) rescue Errno::EACCES msg = "file move: EACCES: access denied" log msg return 31, msg end # Prepare a new run and "fork" a thread to handle it #puts " - setting :detected_file variable to (#{target_file})" #current_job.set_var(:detected_file, target_file, self, current_action) # Add detected filename to "locals" returned log "StepWatchfolder end" return 0, "detected (#{basename}) moved to (#{target_file})", {:detected_file => target_file, :label => basename} end #private def validate_params? return :watch if self.pval(:watch).blank? return :archive if self.pval(:target).blank? return false end end
true
a8baa33ed866d295815e801bfc93c5f8750cf295
Ruby
Dane-Dawson/rspec-notes
/Rspec-Ref-Sheets/Built-in-matchers/yield_matchers.rb
UTF-8
5,800
3.453125
3
[]
no_license
#yield_control => matches if the method-under-test yields, regardless of whether or not arguments are yielded #yield_with_args => matches if the method-under-test yields with arguments. If arguments are provided to this matcher, it will only pass if the actual yielded arguments match the expected ones using === or ==. #yield_with_no_args => matches if the method-under-test yields with no arguments #yield_successive_args => is designed for iterators, matching if the method-under-test yields the same number of times as arguments passed to this matcher, and all actual yielded arguments match the expected ones using === or ==. #NOTE# #your expect block *must* accept an argument that is then passed on to the method-under-test as a block. This acts as a "probe" that allows matcher to detect whether or not your method yields and, if so, how many times and what the yielded arguments are. #Background class to test class MyClass def self.yield_once_with(*args) yield *args end def self.yield_twice_with(*args) 2.times { yield *args } end def self.raw_yield yield end def self.dont_yield end end #Example Scenarios #yield_control matcher require './my_class' RSpec.describe "yield_control matcher" do specify { expect { |b| MyClass.yield_once_with(1, &b) }.to yield_control } specify { expect { |b| MyClass.dont_yield(&b) }.not_to yield_control } specify { expect { |b| MyClass.yield_twice_with(1, &b) }.to yield_control.twice } specify { expect { |b| MyClass.yield_twice_with(1, &b) }.to yield_control.exactly(2).times } specify { expect { |b| MyClass.yield_twice_with(1, &b) }.to yield_control.at_least(1) } specify { expect { |b| MyClass.yield_twice_with(1, &b) }.to yield_control.at_most(3).times } # deliberate failures specify { expect { |b| MyClass.yield_once_with(1, &b) }.not_to yield_control } specify { expect { |b| MyClass.dont_yield(&b) }.to yield_control } specify { expect { |b| MyClass.yield_once_with(1, &b) }.to yield_control.at_least(2).times } specify { expect { |b| MyClass.yield_twice_with(1, &b) }.not_to yield_control.twice } specify { expect { |b| MyClass.yield_twice_with(1, &b) }.not_to yield_control.at_least(2).times } specify { expect { |b| MyClass.yield_twice_with(1, &b) }.not_to yield_control.at_least(1) } specify { expect { |b| MyClass.yield_twice_with(1, &b) }.not_to yield_control.at_most(3).times } end #yield_with_args matcher require './my_class' RSpec.describe "yield_with_args matcher" do specify { expect { |b| MyClass.yield_once_with("foo", &b) }.to yield_with_args } specify { expect { |b| MyClass.yield_once_with("foo", &b) }.to yield_with_args("foo") } specify { expect { |b| MyClass.yield_once_with("foo", &b) }.to yield_with_args(String) } specify { expect { |b| MyClass.yield_once_with("foo", &b) }.to yield_with_args(/oo/) } specify { expect { |b| MyClass.yield_once_with("foo", "bar", &b) }.to yield_with_args("foo", "bar") } specify { expect { |b| MyClass.yield_once_with("foo", "bar", &b) }.to yield_with_args(String, String) } specify { expect { |b| MyClass.yield_once_with("foo", "bar", &b) }.to yield_with_args(/fo/, /ar/) } specify { expect { |b| MyClass.yield_once_with("foo", "bar", &b) }.not_to yield_with_args(17, "baz") } # deliberate failures specify { expect { |b| MyClass.yield_once_with("foo", &b) }.not_to yield_with_args } specify { expect { |b| MyClass.yield_once_with("foo", &b) }.not_to yield_with_args("foo") } specify { expect { |b| MyClass.yield_once_with("foo", &b) }.not_to yield_with_args(String) } specify { expect { |b| MyClass.yield_once_with("foo", &b) }.not_to yield_with_args(/oo/) } specify { expect { |b| MyClass.yield_once_with("foo", "bar", &b) }.not_to yield_with_args("foo", "bar") } specify { expect { |b| MyClass.yield_once_with("foo", "bar", &b) }.to yield_with_args(17, "baz") } end #yield_with_no_args matcher require './my_class' RSpec.describe "yield_with_no_args matcher" do specify { expect { |b| MyClass.raw_yield(&b) }.to yield_with_no_args } specify { expect { |b| MyClass.dont_yield(&b) }.not_to yield_with_no_args } specify { expect { |b| MyClass.yield_once_with("a", &b) }.not_to yield_with_no_args } # deliberate failures specify { expect { |b| MyClass.raw_yield(&b) }.not_to yield_with_no_args } specify { expect { |b| MyClass.dont_yield(&b) }.to yield_with_no_args } specify { expect { |b| MyClass.yield_once_with("a", &b) }.to yield_with_no_args } end #yield_successive_args matcher def array [1, 2, 3] end def array_of_tuples [[:a, :b], [:c, :d]] end RSpec.describe "yield_successive_args matcher" do specify { expect { |b| array.each(&b) }.to yield_successive_args(1, 2, 3) } specify { expect { |b| array_of_tuples.each(&b) }.to yield_successive_args([:a, :b], [:c, :d]) } specify { expect { |b| array.each(&b) }.to yield_successive_args(Integer, Integer, Integer) } specify { expect { |b| array.each(&b) }.not_to yield_successive_args(1, 2) } # deliberate failures specify { expect { |b| array.each(&b) }.not_to yield_successive_args(1, 2, 3) } specify { expect { |b| array_of_tuples.each(&b) }.not_to yield_successive_args([:a, :b], [:c, :d]) } specify { expect { |b| array.each(&b) }.not_to yield_successive_args(Integer, Integer, Integer) } specify { expect { |b| array.each(&b) }.to yield_successive_args(1, 2) } end
true
4c7aa3415e9672b77a13ba46cc5f4cbc5e42e1da
Ruby
nurrutia/clase23
/ejercicio5.rb
UTF-8
1,871
3.890625
4
[]
no_license
hash = [{ :firstname => "Diego", :country => "Chile", :continent => "south america", :gender => "M" }, { :firstname => "Juan", :country => "Peru", :continent => "south america", :gender => "M" }, { :firstname => "Pedro", :country => "Colombia", :continent => "south america", :gender => "F" }, { :firstname => "Federico", :country => "EEUU", :continent => "north america", :gender => "M" }, { :firstname => "Marcelo", :country => "Rusia", :continent => "Europe", :gender => "F" }, { :firstname => "Pepito", :country => "Italia", :continent => "Europe", :gender => "M" }, { :firstname => "Joel", :country => "Bolivia", :continent => "South america", :gender => "F" }, { :firstname => "Dario", :country => "Brasil", :continent => "south america", :gender => "M" }] #Crear el array de hashes y pobarlo con al menos 8 personas: puts hash.length # Generar un array con cada continente, eliminar repeticiones, considerar que pueden haber nombres escritos con mayúscula y minúscula. continentes = [] hash.each do |key, value| continentes << key[:continent].capitalize end puts continentes.uniq #Generar una lista con todas las personas llamadas pedro hash.each do |key| if key[:firstname].to_s == "Pedro" puts "si hay #{key[:firstname]}" end end #Hacer dos listas de personas, una por cada género masculino = [] femenino = [] hash.each do |key| if key[:gender].to_s == "M" masculino << key elsif key[:gender].to_s == "F" femenino << key end end puts femenino puts masculino #6. Armar un hash, donde cada clave sea un continente y el value un array con los países de cada continente =begin=endcontinentes = [{:paises => "Chile", :continentes => "south america"}] paises = [] hash.each do |key, value| if key[:continent].to_s continentes << key end if key[:country].to_s paises << value end end
true
85bfee631e0c8beed1d42b65984beafeb3d0d113
Ruby
ChrisGoodson/bug-free-octo-garbanzo
/lib/weapon.rb
UTF-8
482
3.375
3
[]
no_license
class Weapon attr_reader :name, :damage attr_accessor :bot def initialize(name, damage = 0) raise ArgumentError if !name.instance_of? String raise ArgumentError if !damage.instance_of? Fixnum @name = name @damage = damage @bot = nil @picked_up = false end def bot=(some_bot) raise ArgumentError unless some_bot.nil? || some_bot.instance_of?(BattleBot) @bot = some_bot @picked_up = true end def picked_up? @picked_up end end
true
b5fde6d8fa0ce67c224f0c227b26577582b39680
Ruby
Torres-x86-64/x86_64-linux-cheatsheats
/scrape-syscalls.rb
UTF-8
642
2.609375
3
[]
no_license
require "open-uri" require "nokogiri" require "pry" page = Nokogiri::HTML(open("https://filippo.io/linux-syscall-table/")) syscall_rows = page.css(".tbls-table > tr.tbls-entry-collapsed").map do |row| row.css("td").map(&:text).join("\t") end args_rows = page.css(".tbls-table > tr.tbls-arguments-collapsed").map do |row| sub_rows = row.css("tbody tr") row_text = [] sub_rows[0].css("td").each_with_index do |register, i| row_text << "#{register.text.gsub(/%/, "")}: #{sub_rows[1].css("td")[i].text}" end row_text.join(" ") end syscall_rows.each_with_index do |syscall, i| puts "#{syscall}\n\t\t#{args_rows[i]}\n\n" end
true
7410a5a61471ecb813bbc78c24c26fa45554c1db
Ruby
jbr/breakglass
/vendor/plugins/freighthopper/test/array_test.rb
UTF-8
1,269
2.75
3
[ "MIT" ]
permissive
require File.instance_eval { expand_path join(dirname(__FILE__), 'test_helper') } require 'freighthopper' class ArrayTest < Test::Unit::TestCase context 'singular' do should 'return the singular object if there is indeed only one' do assert_singular 5, [5] end should 'return nil if the array is empty' do assert_singular nil, [] end should 'return nil if the array has > 1 item' do assert_singular nil, [1, 2] end end context 'singular questionmark' do should 'return true if the array has only one member' do assert_singular [5] end should 'return false if the array is empty' do assert_not_singular [] end should 'return false if the array has more than one member' do assert_not_singular [1, 2] end end context 'singular bang' do should 'return the item if there is just one' do assert_equal 5, [5].singular! end should 'raise if there are no items' do e = assert_raise(RuntimeError){ [].singular! } assert_message 'not singular', e end should 'raise if there are more than one item' do e = assert_raise(RuntimeError){ [1, 2].singular! } assert_message 'not singular', e end end end
true
742873aa471de7801384ec5754f9bf9475005fd1
Ruby
niquola/kung_figure
/test/kung_figure_test.rb
UTF-8
2,327
2.53125
3
[ "MIT" ]
permissive
require File.dirname(__FILE__) + '/test_helper.rb' module MyModule include KungFigure class Config < KungFigure::Base define_prop :prop1,'default1' define_prop :prop2, 2 define_prop :bool,true class NestedConfig < KungFigure::Base define_prop :prop3,'prop3' class NestedNestedConfig < KungFigure::Base define_prop :prop4,'prop4' end end end end module Another include KungFigure class Config < KungFigure::Base define_prop :prop,'default' end end module MyModule class WorkHorse include KungFigure class Config < KungFigure::Base define_prop :my_config,'default' end end end class TestKungFigure < Test::Unit::TestCase def test_configuration assert_equal('default1',MyModule.config.prop1) assert_equal(2,MyModule.config.prop2) assert_equal('prop3',MyModule.config.nested_config.prop3) assert_equal('prop4',MyModule.config.nested_config.nested_nested_config.prop4) MyModule.config.nested_config.nested_nested_config.prop4 'new value' assert_equal('new value',MyModule.config.nested_config.nested_nested_config.prop4) MyModule.configure do nested_config do prop3 'value3' end end assert_equal('value3',MyModule.config.nested_config.prop3) end def test_bug_with_boolean MyModule.configure do bool false end assert_equal(false,MyModule.config.bool) end def test_nested_config_declaration MyModule.clear_config! assert_equal('default',MyModule.config.work_horse.my_config) assert_equal('default',MyModule::WorkHorse.config.my_config) MyModule.configure do work_horse do my_config 'new value' end end assert_equal('new value',MyModule.config.work_horse.my_config) assert_equal('new value',MyModule::WorkHorse.config.my_config) assert_equal(MyModule::WorkHorse.config,MyModule::WorkHorse.new.config) end def test_clear_configuration MyModule.config.work_horse.my_config 'some config' MyModule.config.prop1 'some config' Another.config.prop 'some config' MyModule.clear_config! assert_equal('default',MyModule.config.work_horse.my_config) assert_equal('default1',MyModule.config.prop1) assert_equal('some config',Another.config.prop,'This branch not cleared') end end
true
c562c7e1fdc4c07c16e31549f1b4e7ead94b42ae
Ruby
Cileos/shiftplan
/lib/time_component.rb
UTF-8
1,529
2.875
3
[]
no_license
class TimeComponent < Struct.new(:record, :start_or_end) FullTimeExp = /\A (?<hour> \d{1,2}) : (?<minute> \d{1,2}) \z/x ShortTimeExp = /\A (?<hour> \d{1,2}) /x # interpret the first 2 digits as hour, discard the rest MinuteInterval = 15 def hour=(hour) @hour = hour.present?? hour.to_i : nil end def attr_name :"#{start_or_end}s_at" end def hour @hour || (from_record.present? && from_record.hour) || 0 end def hour_present? @hour.present? end def metric_hour hour + (0.25 * minute / 15) end def time=(time) if m = FullTimeExp.match(time) self.hour = m[:hour] self.minute = m[:minute] elsif m = ShortTimeExp.match(time) self.hour = m[:hour] self.minute = 0 end end def time '%02d:%02d' % [hour, minute] end def minute @minute || (from_record.present? && from_record.min) || 0 end def day @day || (from_record.present? && from_record.day) || 0 end def minute=(minute) @minute = if minute.present? minute = minute.to_i rounded = round_minute minute if minute - rounded > MinuteInterval # overflow self.hour = hour + 1 # must be assigned first, obviously end rounded else nil end end def round_minute(minute, int=MinuteInterval) ( ( ( minute + int / 2 # rounding up ) / int ) * int ) % 60 end private def from_record record.public_send(attr_name) end end
true
accb1472a9213a369ae3531b1f3a80b9f4961c3b
Ruby
hrigu/planik_parser
/examples/test_date.rb
UTF-8
160
2.921875
3
[]
no_license
require 'date' puts Date.today d = Date.parse("2013-01-07") #puts d.next_day #puts d.next_day 3 puts d.wday wt = ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"]
true
49d1900531b35d0f30a43a6ce597a8befeb0482a
Ruby
huijunyam/minesweeper
/board.rb
UTF-8
1,001
3.546875
4
[]
no_license
require_relative 'tile' require_relative 'game' class Board attr_reader :grid, :bomb_positions def initialize @grid = Array.new(9) { Array.new(9) } @bomb_positions = [] @bomb_neighbors = [] end def [](pos) row, col = pos @grid[row][col] end def []=(pos, mark) row, col = pos @grid[row][col] = mark end def populate_board 10.times { @bomb_positions << [rand(10), rand(10)] } @grid = @grid.map.with_index do |row, idx| row.map.with_index do |_, i| bomb_positions.include?([idx, i]) ? Tile.new(true) : Tile.new(false) end end end def display_grid print " " puts (0..8).to_a.join(" ") @grid.each_with_index do |row, idx| print "#{idx} " puts row.map { |el| el.symbol }.join(' ') end end def flag(pos) @grid[pos].is_flagged = !@grid[pos].is_flagged end def reveal(pos) if @grid[pos].is_bomb game.game_over else @grid[pos].revealed = true end end end
true
d5f2b74096dd5032585b0072a1d9da8accefb143
Ruby
SmoothTrane/Greed
/client.rb
UTF-8
2,768
3.78125
4
[]
no_license
class Grid def initialize @array = [ [1,2,2,1,1], [1,1,2,2,2,1], [1,1,1,1,1,1] ] rand = Random.new firstIndex = rand.rand(0..@array.length - 1) secondIndex = rand.rand(0..@array[firstIndex].length - 1) @array[firstIndex][secondIndex] = "@" display_grid # for the first val, 0 to @array.length # second val is 0 to @array[val].length end def display_grid p "Here is your grid, you must move the @ symbol across the map in order to make it the last element" p @array end def move(dir) dir = dir.downcase if dir == "n" || dir == "north" @array.each_index do |i| j = @array[i].index '@'; if j @val = i @secondVal = j end end if @val >= 0 num = @array[@val - 1][@secondVal] num.times do |i| p @val @array[@val].delete_at(@secondVal) @val -= 1 if i == num - 1 @array[@val][@secondVal] = "@" end end p @array end elsif dir == "e" || dir == "east" @array.each_index do |i| j = @array[i].index '@'; if j @val = i @secondVal = j end end if @secondVal < @array[@val].length - 1 num = @array[@val][@secondVal + 1] num.times do |i| @array[@val].delete_at(@secondVal) if i == num - 1 @array[@val][@secondVal] = "@" end if @secondVal == @array[@val].length puts 't' break; end end p @array end elsif dir == "s" || dir == "south" @array.each_index do |i| j = @array[i].index '@'; if j @val = i @secondVal = j end end num = @array[@val + 1][@secondVal] num.times do |i| p @val @array[@val].delete_at(@secondVal) @val += 1 if i == num - 1 @array[@val][@secondVal] = "@" end if i == @array.length + 1 puts 'done' break end p @array end elsif dir == "w" || dir == "west" @array.each_index do |i| j = @array[i].index '@'; if j @val = i @secondVal = j end end if @secondVal < 0 num = @array[@val][@secondVal - 1] num.times do |i| @secondVal -= 1 p @secondVal @array[@val].delete_at(@secondVal) if i == num - 1 @array[@val][@secondVal] = "@" end end p @array end else puts 'Please enter North South East or West' end end end
true
d62d62ca0e8f7a9752a896f15617692cfc568ad7
Ruby
zjciris/Foodies
/db/seeds/production.rb
UTF-8
6,739
2.703125
3
[]
no_license
###################################### # config ###################################### # allow_image_upload = true && total_num_of_users = 20 -- 3 min # allow_image_upload = true && total_num_of_users = 50 -- 7 min # allow_image_upload = false && total_num_of_users = 50 -- 1 min # allow_image_upload = false && total_num_of_users = 500 -- 5 min require 'faker' allow_randomness = false allow_image_upload = false total_num_of_users = 500 total_num_of_recipes = 0 # total_num_of_recipes is calculated later total_num_of_masterpieces = 0 # total_num_of_masterpieces is calculated later total_num_of_tags = 100 total_num_of_ingredients = 50 avg_num_of_recipes_per_user = 2 avg_num_of_masterpieces_per_user = 4 avg_num_of_liked_recipes_per_user = 20 avg_num_of_bookmarked_recipes_per_user = 10 avg_num_of_liked_masterpieces_per_user = 20 avg_num_of_tags_per_recipe = 3 avg_num_of_ingredients_per_recipe = 3 avg_num_of_steps_per_recipe = 2 tags_array = (1..total_num_of_tags).to_a tags_array.map! { |x| "tag" + x.to_s } ingredients_array = (1..total_num_of_ingredients).to_a ingredients_array.map! { |x| "ingredient" + x.to_s } sample_avatar_file = File.new("#{Rails.root}/load_tests/sample_avatar.png") sample_recipe_img_file = File.new("#{Rails.root}/load_tests/sample_recipe_img.jpg") sample_step_img_file = File.new("#{Rails.root}/load_tests/sample_step_img.png") sample_masterpiece_img_file = File.new("#{Rails.root}/load_tests/sample_masterpiece_img.jpg") ###################################### # util functions ###################################### def user_like_recipe(user_id, recipe_id) UserLikeRecipe.create( user_id: user_id, recipe_id: recipe_id ) end def user_bookmark_recipe(user_id, recipe_id) UserBookmarkRecipe.create( user_id: user_id, recipe_id: recipe_id ) end def user_like_masterpiece(user_id, masterpiece_id) UserLikeMasterpiece.create( user_id: user_id, masterpiece_id: masterpiece_id ) end ###################################### # create users ###################################### total_num_of_users.times do |n_user| puts 'Creating user: user_' + (n_user + 1).to_s user = User.create( username: "user_" + (n_user + 1).to_s, email: "user_" + (n_user + 1).to_s + "@example.com", password: "88888888", password_confirmation: "88888888", avatar: allow_image_upload ? sample_avatar_file : nil ) end ###################################### # user create recipes ###################################### total_num_of_users.times do |n_user| user_id = n_user + 1 puts 'User ' + user_id.to_s + ' creates recipes' num_of_recipes = allow_randomness ? rand(avg_num_of_recipes_per_user * 2 + 1) : avg_num_of_recipes_per_user num_of_recipes.times do ###################################### # create recipe ###################################### num_of_tags = allow_randomness ? rand(avg_num_of_tags_per_recipe * 2 + 1) : avg_num_of_tags_per_recipe recipe = Recipe.create( user_id: user_id, title: Faker::Lorem.sentence, description: Faker::Lorem.sentence, cook_time: (rand(6) + 1) * 10, recipe_img: allow_image_upload ? sample_recipe_img_file : nil, tag_list: tags_array.sample(num_of_tags) ) recipe_id = recipe.id puts 'Created recipe:' + recipe_id.to_s ###################################### # add ingredients to each recipe ###################################### puts '- Adding ingredients' num_of_ingredients = allow_randomness ? rand(avg_num_of_ingredients_per_recipe * 2 + 1) : avg_num_of_ingredients_per_recipe ingredients_array.sample(num_of_ingredients).each do |ingredient_name| ingredient = Ingredient.create( recipe_id: recipe_id, name: ingredient_name, quantity: ((rand(50) + 1) * 10).to_s + 'g' ) end ###################################### # add steps to each recipe ###################################### puts '- Adding steps' num_of_steps = allow_randomness ? rand(avg_num_of_steps_per_recipe * 2 + 1) : avg_num_of_steps_per_recipe num_of_steps.times do |n_step| step = Step.create( recipe_id: recipe_id, step_number: n_step + 1, description: Faker::Lorem.sentence, step_img: allow_image_upload ? sample_step_img_file : nil ) end total_num_of_recipes += 1 end end recipe_ids_array = (1..total_num_of_recipes).to_a ###################################### # user create masterpieces ###################################### total_num_of_users.times do |n_user| user_id = n_user + 1 puts 'User ' + user_id.to_s + ' creates masterpieces' num_of_masterpieces = allow_randomness ? rand(avg_num_of_masterpieces_per_user * 2 + 1) : avg_num_of_masterpieces_per_user recipe_ids_array.sample(num_of_masterpieces).each do |recipe_id| puts '- adding masterpiece to recipe:' + recipe_id.to_s masterpiece = Masterpiece.create( recipe_id: recipe_id, user_id: user_id, description: Faker::Lorem.sentence, masterpiece_img: allow_image_upload ? sample_masterpiece_img_file : nil ) total_num_of_masterpieces += 1 end end masterpiece_ids_array = (1..total_num_of_masterpieces).to_a total_num_of_users.times do |n_user| user_id = n_user + 1 puts 'User' + user_id.to_s ###################################### # user like recipes ###################################### puts '- likes recipes' user_like_recipe_count = allow_randomness ? rand(avg_num_of_liked_recipes_per_user * 2 + 1) : avg_num_of_liked_recipes_per_user recipe_ids_array.sample(user_like_recipe_count).each do |recipe_id| user_like_recipe(user_id, recipe_id) end ###################################### # user bookmark recipes ###################################### puts '- bookmarks recipes' user_bookmark_recipe_count = allow_randomness ? rand(avg_num_of_bookmarked_recipes_per_user * 2 + 1) : avg_num_of_bookmarked_recipes_per_user recipe_ids_array.sample(user_bookmark_recipe_count).each do |recipe_id| user_bookmark_recipe(user_id, recipe_id) end ###################################### # user like masterpieces ###################################### puts '- likes masterpieces' user_like_masterpiece_count = allow_randomness ? rand(avg_num_of_liked_masterpieces_per_user * 2 + 1) : avg_num_of_liked_masterpieces_per_user masterpiece_ids_array.sample(user_like_masterpiece_count).each do |masterpiece_id| user_like_masterpiece(user_id, masterpiece_id) end end puts '====' puts 'Total number of recipes: ' + total_num_of_recipes.to_s puts 'Total number of masterpieces: ' + total_num_of_masterpieces.to_s
true
3ab13cb24d998cc22d1430c8aa26d98d22fe0f48
Ruby
Vitoko-Arriagada/ruby-module
/proyecto.rb
UTF-8
423
3.21875
3
[]
no_license
class Proyecto attr_reader :nombre, :descripcion def initialize nombre, descripcion @nombre = nombre @descripcion = descripcion end def presentacion puts "#{@nombre}, #{@descripcion}" end end proyecto1 = Proyecto.new("Proyecto 1", "Descripción 1") puts proyecto1.nombre proyecto1.presentacion proyecto2 = Proyecto.new("Proyecto 2", "Descripción 2") puts proyecto2.nombre proyecto2.presentacion
true
df3f27a37fa4553fa48a77b214943ffe131dd431
Ruby
mattbehan/project-euler-exercises
/euler_14/euler_14.rb
UTF-8
280
3.46875
3
[]
no_license
hash = {2 => 1} [*3..1000000].each do |number| count = 0 x = number while x > 1 if x.even? x = x/2 else count += 1 x = ( x * 3 ) + 1 end end if count > hash.values[0] hash = {number => count} puts "updating: #{hash}" end end puts "final answer: #{hash}"
true
8ad76526a3bc5507568b60f5979888d23ba8acb6
Ruby
jackslinger/Advent-of-code-2020
/day5/day5.rb
UTF-8
1,831
3.890625
4
[ "MIT" ]
permissive
#!/usr/bin/env ruby example = File.open("day5/example.txt").read input = File.open("day5/input.txt").read.split("\n").map(&:chomp) class Seat attr_reader :number_of_rows, :row_code attr_reader :number_of_cols, :col_code def initialize(input) @row_code = input.slice(0..6).split('') @number_of_rows = 127 @col_code = input.slice(7..-1).split('') @number_of_cols = 7 end def row min = 0 max = number_of_rows row_code.each do |front_or_back| case front_or_back when 'F' max = mid_point(min, max) - 1 when 'B' min = mid_point(min, max) end end min end def col min = 0 max = number_of_cols col_code.each do |left_or_right| case left_or_right when 'L' max = mid_point(min, max) - 1 when 'R' min = mid_point(min, max) end end min end def seat_id (row * 8) + col end private def mid_point(min, max) min + ((max + 1 - min) / 2) end end booked_seats = input.map{ |code| Seat.new(code) } # puts booked_seats.map(&:seat_id).max # Part 2 booked_seats = input.map{ |code| Seat.new(code) } booked_seats_hash = booked_seats.map { |seat| [seat.seat_id, seat] }.to_h # (0..127).each do |row| # row_text = "" # (0..7).each do |col| # seat_id = (row * 8) + col # if booked_seats_hash[seat_id].nil? # row_text << "." # else # row_text << "*" # end # end # puts row_text # end # First 10 rows don't exist # Last 20 rows don't exist my_seat_id = nil (10..106).each do |row| row_text = "" (0..7).each do |col| seat_id = (row * 8) + col if booked_seats_hash[seat_id].nil? row_text << "." my_seat_id = seat_id else row_text << "*" end end puts row_text end puts "My Seat: #{my_seat_id}"
true
07e5a5f11bdc9c408d813be72ab149164ec04ea4
Ruby
chaitali-khangar/data_structure
/SingularCircularLinkedList.rb
UTF-8
136
3.03125
3
[]
no_license
class Node attr_accessor :value, :node_next def initialize(value, node_next) @value = value @node_next = node_next end end
true
2a996c59fbd277c20550597f4b20cfb9b456f68c
Ruby
dyba/cracking_the_ruby_coding_interview
/lib/ctci/linked_lists/palindrome.rb
UTF-8
697
2.8125
3
[]
no_license
require 'ctci/data_structures/stack' module CTCI module LinkedLists def palindrome? list return false unless list runner = list reversed = nil while runner do if reversed front = ::CTCI::DataStructures::SinglyLinkedNode.new(runner.value) front.next = reversed reversed = front else reversed = ::CTCI::DataStructures::SinglyLinkedNode.new(runner.value) end runner = runner.next end runner = list while reversed do return false if reversed.value != runner.value reversed = reversed.next runner = runner.next end true end end end
true
25b5ddd0d8b749d18ecf51d8ef437a41be3fa14b
Ruby
McNeill2019/SEI-Exercises-35
/Week4/WarmUps/Raindrops /raindrops.rb
UTF-8
1,381
5.03125
5
[]
no_license
#Warmup - Raindrops #Write a program using Ruby that will take a number (eg 28 or 1755 or 9, etc) and output the following: #If the number contains 3 as a factor, output 'Pling'. #If the number contains 5 as a factor, output 'Plang'. #If the number contains 7 as a factor, output 'Plong'. #If the number does not contain 3, 5, or 7 as a factor, output the number as a string. print "Enter number to test:" guess = gets.chomp.to_i def number (guess) if guess % 3 == 0 && guess % 5 == 0 && guess % 7 == 0 puts "PlingPlangPlong" elsif guess % 3 == 0 && guess % 5 == 0 puts "PlingPlang" elsif guess % 3 == 0 && guess % 7 == 0 puts "PlingPlong" elsif guess % 7 == 0 puts "Plong" elsif guess % 5 == 0 puts "Plang" elsif guess % 3 == 0 puts "Pling" else puts "#{guess}" end end number (guess) #josh solution: def raindrops number string = "" if number % 3 == 0 string += "Pling" end if number % 5 == 0 string += "Plang" end if number % 5 == 0 string += "Plong" end if string.length == 0 string = number.to_s end puts "input is #{number} the word is #{string}" end def raindrops number string = "" string += "Pling" if number % 3 == 0 string += "Plang" if number % 5 == 0 string += "Plong" if number % 7 == 0 string.empty? ? number.to_s : string end puts "input 28: #{raindrops 28}"
true
f37ea12f874ae31adef66942814a9f6847b43bad
Ruby
birbl/birbl-ruby
/lib/birbl/user.rb
UTF-8
960
2.546875
3
[]
no_license
require 'cgi' module Birbl class User < Birbl::Resource def self.attribute_names super + [ :username, :email, :active, :options, :reservations ] end define_attributes validates_presence_of :username validates_presence_of :email validates_presence_of :active def initialize(attributes = {}, parent = nil) @reservations = [] @partners = [] super attributes, parent end def active? @active end def reservations children('reservations') end def partners children('partners') end def writable_attributes attributes.select { |k,v| ['username', 'active', 'email', 'options'].include?(k.to_s) } end def self.find_by_email(email) attributes = client.get("users/show_by_email/#{ CGI.escape(email.sub('.', '+')) }") attributes.empty? ? nil : new(attributes) end end end
true
a5e8ccf84678ec6745bf721acf40088772a3b4f8
Ruby
swathi-0901/ruby-joy
/reverse_string.rb
UTF-8
249
4.03125
4
[]
no_license
#Ruby program which accept the user's first and last name and print them in reverse order with a space between them. puts "Input your first name: " fname = gets.chomp puts "Input your last name: " lname = gets.chomp puts "Hello #{lname} #{fname}"
true
547da777b5575b14247f4415d59650ea11997e84
Ruby
piotrmurach/benchmark-perf
/spec/unit/ips_result_spec.rb
UTF-8
1,028
2.578125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# frozen_string_literal: true RSpec.describe Benchmark::Perf::IPSResult do it "defaults all calculations to zero" do result = described_class.new expect(result.avg).to eq(0) expect(result.stdev).to eq(0) expect(result.iter).to eq(0) expect(result.dt).to eq(0) end it "adds measurements correctly" do result = described_class.new result.add 1, 50_000 result.add 2, 100_000 result.add 0.5, 25_000 expect(result.avg).to eq(50_000) expect(result.stdev).to eq(0) expect(result.iter).to eq(175_000) expect(result.dt).to eq(3.5) result.add 0.5, 25_000 expect(result.avg).to eq(50_000) expect(result.stdev).to eq(0) expect(result.iter).to eq(200_000) expect(result.dt).to eq(4) end it "inpsects content" do result = described_class.new result.add 1, 50_000 result.add 2, 100_000 expect(result.inspect).to eq("#<Benchmark::Perf::IPSResult @avg=50000 " \ "@stdev=0 @iter=150000 @dt=3>") end end
true
e79764beb9a1dc569086a0c7cdcb5901180a9090
Ruby
Pau1fitz/Fizz_buzz
/spec/fizzbuzz_spec.rb
UTF-8
1,026
3.359375
3
[]
no_license
require 'fizzbuzz' describe FizzBuzz do let(:fizzbuzz) { FizzBuzz.new } it 'knows 1 is not divsible by 3' do expect(fizzbuzz.divided_by_three?(1)).to eq false end it 'knows 3 is divisible by 3' do expect(fizzbuzz.divided_by_three?(3)).to eq true end it 'knows 1 is not divisible by 5' do expect(fizzbuzz.divided_by_five?(1)).to eq false end it 'knows 5 is divsible by 5' do expect(fizzbuzz.divided_by_five?(5)).to eq true end it 'knows that 1 is not divisible by 15' do expect(fizzbuzz.divided_by_fifteen?(1)).to eq false end it 'knows 15 is divisible by 15' do expect(fizzbuzz.divided_by_fifteen?(15)).to eq true end it 'returns 1 when given 1' do expect(fizzbuzz.play(1)).to eq 1 end it 'returns fizz when given 3' do expect(fizzbuzz.play(3)).to eq 'fizz' end it 'returns buzz when given 5' do expect(fizzbuzz.play(5)).to eq 'buzz' end it 'returns fizzbuzz when given 15' do expect(fizzbuzz.play(15)).to eq 'fizzbuzz' end end
true
4717b38d9a07d629c8694e0afcaf0f30b91986fe
Ruby
pablo31/asistefe
/main.rb
UTF-8
1,622
2.640625
3
[]
no_license
# bundle exec ruby main.rb worksets/201803 15 # see FileManager for directory structure working_directory_path = ARGV[0] practices_interval = ARGV[1].to_i offset_start = ARGV[2]&.to_i offset_end = ARGV[3]&.to_i # entry_ids = ARGV[2].split(',').map(&:to_i) require 'json' require'pry' require './lib/asistefe' include Asistefe # helpers serializator = EntrySerializer.new file_manager = FileManager.new(working_directory_path) # writer output_interface = LinuxInterface.new speed_control = SpeedControls.slow # ui_layout = UiLayouts::UnicaDesktopPc.new ui_layout = UiLayouts::UnicaNotebookPc.new system_manager = SystemManager.new(output_interface, ui_layout, speed_control) writer = Writer.new(system_manager) # source calendar_data = JSON.parse(file_manager.read_calendar) # TODO send to another file calendar_parser = Calendar::Parser.new(calendar_data) # TODO send to another file calendar = calendar_parser.build_with_interval(practices_interval) reader = Reader.new(file_manager) generator = Sources::Generator.new(reader, calendar) recovery = Sources::Recovery.new(file_manager, serializator) mixed = Sources::Mixed.new(generator, recovery) source = LimitedSource.new(mixed, offset_start, offset_end) # source = ScopedSource.new(mixed, entry_ids) # iterator # progress_control = ProgressControls::Manual.new(writer) progress_control = ProgressControls::Screenshots.new(file_manager) iterator = Iterator.new(source, writer, progress_control) puts "Time available: #{calendar.max_practices_qty} practices" puts "Real practices count: #{source.entries.count}" iterator.start! puts "Thats all folks!"
true
6a2085b43c951d799a8e00db951ae02871f5f3fa
Ruby
yoggy/mqtt_rain_checker
/mqtt_rain_checker.rb
UTF-8
1,975
2.53125
3
[ "MIT" ]
permissive
#!/usr/bin/ruby # vim: ts=2 sw=2 et si ai : require 'pp' require 'mqtt' require 'logger' require 'yaml' require 'ostruct' require 'json' require 'date' def usage $stderr.puts "usage : #{File.basename($0)} config.yaml" exit(1) end $stdout.sync = true Dir.chdir(File.dirname($0)) $current_dir = Dir.pwd $log = Logger.new(STDOUT) $log.level = Logger::DEBUG $last_is_rainy = false usage if ARGV.size == 0 $conf = OpenStruct.new(YAML.load_file(ARGV[0])) $conn_opts = { remote_host: $conf.mqtt_host, client_id: $conf.mqtt_client_id } if !$conf.mqtt_port.nil? $conn_opts["remote_port"] = $conf.mqtt_port end if $conf.mqtt_use_auth == true $conn_opts["username"] = $conf.mqtt_username $conn_opts["password"] = $conf.mqtt_password end def main_loop $log.info "connecting..." MQTT::Client.connect($conn_opts) do |c| $log.info "connected!" c.subscribe($conf.subscribe_topic) c.get do |topic, message| $log.info "recv: topic=#{topic}, message=#{message}" $last_received_time = Time.now json = JSON.parse(message) now_count = json["rainy_pixel_count"] is_rainy = false if now_count >= $conf.rainy_pixel_threshold is_rainy = true end if $last_is_rainy != is_rainy && is_rainy == true $log.info "rainy_pixel count is greater than #{$conf.rainy_pixel_threshold}" h = Time.now.hour h += 24 if h < 5 # 5-29 if $conf.start_time <= h && h <= $conf.end_time $log.info "publish : topic=#{$conf.publish_topic}, payload=#{$conf.rainy_alert_message}" c.publish($conf.publish_topic, $conf.rainy_alert_message) end end $last_is_rainy = is_rainy end end end loop do begin main_loop rescue Exception => e $log.debug(e.to_s) end begin Thread.kill($watchdog_thread) if $watchdog_thread.nil? == false $watchdog_thread = nil rescue end $log.info "waiting 5 seconds..." sleep 5 end
true
5aa98643546d7b113763f93a0131e7c9764ab6b6
Ruby
codemilan/old_stuff
/sbs2/rad_core/lib/rad/router/object_router.rb
UTF-8
4,560
2.640625
3
[ "MIT" ]
permissive
class Rad::Router::ObjectRouter include Rad::Router::RouterHelper def initialize self.class_to_resource = -> klass {raise ':class_to_resource not specified!'} self.resource_to_class = -> resource {raise ':resource_to_class not specified!'} self.id_to_class = -> id, params {raise ':id_to_class not specified!'} self.default_class_method = :all self.default_method = :read @cached_class_to_resource, @cached_resource_to_class = {}, {} end def configure options = {} raise "can't configure ObjectRouter twice!" if configured? self.configured = true # parsing options options.validate_options! :default_class_name, :class_to_resource, :resource_to_class, :id_to_class, :prefix self.default_class_name = options[:default_class_name] || raise(':default_class_name not provided!') self.class_to_resource = options[:class_to_resource] if options.include? :class_to_resource self.resource_to_class = options[:resource_to_class] if options.include? :resource_to_class self.id_to_class = options[:id_to_class] if options.include? :id_to_class self.prefix = parse_prefix options end def encode! klass, method, params return nil unless configured? id = params[:id] # id and resource path = if id raise ":id can be used with :default_class only (#{klass}, '#{id}')!" if klass != default_class params.delete :id raise ":id must not start from capital letter ('#{id}')!" if id =~ /^[A-Z]/ path = if !method or method == default_method "/#{id}" else "/#{id}/#{method}" end else resource = cached_class_to_resource klass raise "no resource for #{klass}!" unless resource raise "resource must start from capital letter (class: #{klass}, resource: '#{resource}')!" unless resource =~ /^[A-Z]/ path = if !method or method == default_class_method "/#{resource}" else "/#{resource}/#{method}" end end # prefix path, params = encode_prefix_params! path, params, prefix if prefix [path, params] end def decode! path, params return nil unless configured? parts = path[1..-1].split('/') # checking 'size' of path extra_size = (prefix ? prefix.size : 0) valid_range = (1 + extra_size)..(2 + extra_size) raise "invalid 'size' of path, must be in #{valid_range}!" unless valid_range.include? parts.size # prefix path, params = decode_prefix_params! path, parts, params, prefix if prefix # id, resource and method if parts.first =~ /^[A-Z]/ resource, method = parts method ||= default_class_method method = method.to_sym # raise "resource must be in plural form ('#{resource}')!" unless resource.pluralize == resource klass = cached_resource_to_class resource raise "no class for '#{resource}' resource!" unless klass else id, method = parts method ||= default_method method = method.to_sym # sometimes we need params inside of :id_to_class block, # for example to find out Space before finding Item klass = id_to_class.call id, params raise "no class for '#{id}' id!" unless klass params[:id] = id end klass.must.be_a Class return klass, method, path, params end protected attr_accessor :class_to_resource, :resource_to_class, :id_to_class, :default_class_method, :default_method, :prefix, :configured, :default_class_name def default_class @default_class ||= default_class_name.constantize end def configured?; !!@configured end def cached_class_to_resource klass unless @cached_class_to_resource.include? klass resource = class_to_resource.call klass resource.must_not =~ /\// # raise 'resource name must be in plural form' unless resource.pluralize == resource @cached_class_to_resource[klass] = resource end @cached_class_to_resource[klass] end def cached_resource_to_class resource unless @cached_resource_to_class.include? resource klass = resource_to_class.call resource @cached_resource_to_class[resource] = klass end @cached_resource_to_class[resource] end end Rad::Router::Configurator.class_eval do def objects *args, &block router = @router.routers.find{|router| router.is_a? Rad::Router::ObjectRouter} raise "There's no ObjectRouter (use config to add it)!" unless router router.configure *args, &block end end
true
99e784a5cd32a0612555dbf43e5dc80ebc4e2639
Ruby
devmicka/Mardi-Week2-THP-Exo-Ruby
/exo_15.rb
UTF-8
324
3.59375
4
[]
no_license
puts "Salut, bienvenue dans ma super pyramide ! Combien d'étages veux-tu (entre 1 et 25) ?" print "> " height_pyramid = gets.chomp.to_i if (1..25).include? height_pyramid height_pyramid.times do |i| x = i+1 x.times do print "#" end puts end else puts "Donne moi un nombre entre 1 et 25 !" end
true
597745678eb1b9f7676dd1e4fbd3b2de67788d78
Ruby
vittalgit/lynda-ruby-course
/lynda_ruby_exercise_files/Chapter03/03_03_loops.rb
UTF-8
869
3.53125
4
[ "MIT" ]
permissive
# This file is a transcript of the IRB session shown in the movie. # You should be able to cut and paste it into IRB to get # the same results shown in the comments. #loop do # ...(code block) #end #break #next #redo #retry # irb --simple-prompt x = 0 # => 0 loop do x += 2 break if x >= 20 puts x end # 2 # 4 # 6 # 8 # 10 # 12 # 14 # 16 # 18 # => nil x = 0 # => 0 loop do x += 2 break if x >= 20 next if x == 6 puts x end # 2 # 4 # 8 # 10 # 12 # 14 # 16 # 18 # => nil #while boolean #... #end #until boolean (while something is not true) #... #end # for while & until there is no do included, although it is implied #matters what is happening at the start of the loop x = 0 # => 0 while x < 20 x += 2 puts x end # 2 # 4 # 6 # 8 # 10 # 12 # 14 # 16 # 18 # 20 # => nil quit #x = 0 #puts x +=2 while x < 100 #y = 3245 #puts y /=2 until y <= 1
true
df942fb6eee9883bee01516993b9cbe288a44fd5
Ruby
ShigeruIchinoki/gem_mini_test
/test/gem_mini_test_test.rb
UTF-8
1,098
3.1875
3
[ "MIT" ]
permissive
require 'test_helper' class GemMiniTestTest < Minitest::Test def setup @num = GemMiniTest::Main.new @num2 = GemMiniTest::Main.new end def test_that_it_has_a_version_number refute_nil ::GemMiniTest::VERSION end def test_odd? assert @num.odd?(1)==true, '1 is odd' refute @num.odd?(2), '2 is not odd' end def test_check_number? assert @num2.check_number?("4444") == true, "even 4" refute @num2.check_number?("0444"), "even 3" refute @num2.check_number?("1111"), "not even 4" end def test_enough_length? assert @num2.enough_length?("12345678") == true, "3-8ji" refute @num2.enough_length?("12"), "not 3-8ji" refute @num2.enough_length?("123456789"), "not 3-8ji" end def test_fizz_buzz assert @num.fizz_buzz(15)=="FizzBuzz", "FizzBuzz" assert @num.fizz_buzz(5)=="Buzz" , "Buzz" assert @num.fizz_buzz(3)=="Fizz" , "Fizz" end def test_divide refute @num.divide(1, 0), "divided by 0" assert @num.divide(1, 1), "OK" end def test_putshello refute @num.putshello == "", "No puts Hello" end end
true
acda902255113b019ca5eed818357422719641af
Ruby
stjeeves/week2_day3_pub_class_lab
/specs/drink_class_spec.rb
UTF-8
573
2.96875
3
[]
no_license
require("minitest/autorun") require("minitest/reporters") MiniTest::Reporters.use! Minitest::Reporters::SpecReporter.new require_relative("../drink_class") class TestDrink < MiniTest::Test def setup() @drink1 = Drink.new("beer", 400, 5) @drink2 = Drink.new("whisky", 500, 40) @drink3 = Drink.new("wine", 600, 15) end def test_name_of_drink() assert_equal("beer", @drink1.name) end def test_price_of_drink() assert_equal(400, @drink1.price) end def test_alcohol_level_of_drink() assert_equal(40, @drink2.alcohol_level) end end
true