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
e3fad9ac0481bbc406268a6db45cbbd10196abb5
Ruby
rdo9313/aa
/exercises/rspec_exercise_4/lib/part_2.rb
UTF-8
352
3.71875
4
[]
no_license
def proper_factors(num) (1...num).select { |n| num % n == 0 } end def aliquot_sum(num) proper_factors(num).reduce(:+) end def perfect_number?(num) aliquot_sum(num) == num end def ideal_numbers(n) array = [] count = 0 i = 1 while count < n if perfect_number?(i) count += 1 array << i end i += 1 end array end
true
7592fdefa3ac5b236c8f8defba25865c9a009e5f
Ruby
rpalo/ruby-cs-algorithms
/algorithms/dfs.rb
UTF-8
1,802
3.703125
4
[ "MIT" ]
permissive
require 'minitest/autorun' require_relative '../data-structures/undirected_graph' # Note that DFS is essentially the same as BFS, but uses a stack # where BFS uses a queue def depth_first_search(graph, start_node, target) processed_nodes = [] pending_nodes = [start_node] # Set up the hash table of nodes to neighbors # Not really necessarily, but possibly a lot more performant # for bigger graphs neighbors = Hash.new { |h, k| h[k] = [] } graph.edges.each do |edge| a, b = edge.to_a neighbors[a] << b neighbors[b] << a end # Run the search until pending_nodes.empty? current = pending_nodes.pop return current if current == target neighbors[current].each do |neighbor| unless processed_nodes.include?(neighbor) or pending_nodes.include?(neighbor) pending_nodes << neighbor end end processed_nodes << current end # We've searched everything. # If we haven't found the target by now, it's not in here return false end class DfsTest < Minitest::Test # 3 # | # 1 - 2 - 4 9 # | | # 5 - 6 - 7 - 8 def setup @graph = UndirectedGraph.new @graph << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 @graph.connect(1, 2) @graph.connect(2, 3) @graph.connect(2, 5) @graph.connect(2, 4) @graph.connect(5, 6) @graph.connect(6, 7) @graph.connect(7, 8) @graph.connect(7, 9) end def test_can_find_node_in_graph result = depth_first_search(@graph, 1, 9) assert_equal 9, result end def test_doesnt_find_node_not_in_graph result = depth_first_search(@graph, 1, 25) refute result end def test_can_still_find_node_in_graph_with_different_start_point result = depth_first_search(@graph, 7, 9) assert_equal 9, result end end
true
b5e3254962a0c1d5cb6e30c192632e8aef7b672f
Ruby
princesadie/phase-0
/week-6/guessing-game/my_solution.rb
UTF-8
3,261
4.4375
4
[ "MIT" ]
permissive
# Build a simple guessing game # I worked on this challenge [by myself]. # I spent [1.5] hours on this challenge. # Pseudocode =begin DEFINE 'initialize' method, takes 1 argument, 'answer' (integer) SET 'answer' instance var equal to 'answer' argument DEFINE 'guess' method, takes 1 argument, 'guess' (integer) CREATE 'status' instance var, SET to 0 IF 'guess' is an integer COMPARE 'guess' with 'answer' instance var IF 'guess' is equal to 'answer' SET status equal to 1 CALL 'solved' method ELSE IF 'guess' is lower than 'answer' SET status equal to 0 RETURN low ELSE IF 'guess' is high than 'answer' SET status equal to 0 RETURN high ELSE raise ArgumentError DEFINE 'solved' method, takes 1 argument, 'status' (boolean) IF status is equal to 1 RETURN true ELSE RETURN false =end # Input: # Output: # Steps: # Initial Solution =begin class GuessingGame def initialize(answer) @answer = answer end def guess(guess) @status = :symbol if guess.is_a?(Integer) if guess == @answer @status = :correct elsif guess > @answer @status = :high elsif guess < @answer @status = :low end else raise ArgumentError.new("Please enter an integer") end end def solved? if @status == :correct return true else return false end end end =end # Refactored Solution class GuessingGame def initialize(answer) @answer = answer @status = :symbol end def guess(guess) if guess.is_a?(Integer) if guess == @answer @status = :correct elsif guess > @answer @status = :high elsif guess < @answer @status = :low end else raise ArgumentError.new("Please enter an integer") end end def solved? if @status == :correct then true else false end end end # Reflection =begin Q: How do instance variables and methods represent the characteristics and behaviors (actions) of a real-world object? A: I view it like this, if you take a look at a lamp in the real world I would consider this lamp's state (on or off) as an instance variable and the action of turning this lamp on and off as a method. I think it would look something like this class lamp def initialize(state) if state.is_a?(Integer) && (state = 1 || state = 0) @state = state else raise ArgumentError.new("It's either on (1) or off (o)") end end def power @state != @state end end Q: When should you use instance variables? What do they do for you? A: Whenever you need a variable to be accessible from anywhere within the class. They allow for easy accessing of a var. Q: Explain how to use flow control. Did you have any trouble using it in this challenge? If so, what did you struggle with? A: Flow control is being able to select an outcome based upon a set of criterias or results. Q: Why do you think this code requires you to return symbols? What are the benefits of using symbols? A: Symbols are stored only once and retain their "id" throughout the life of the code. They also act much like strings, but unlike strings are immutable, meaning they cannot be changed. From my understanding, this saves a lot of memory especially when programs start getting larger in scope. =end
true
ec07e2dd63432e9e50d0554d795b12c62b804559
Ruby
stantoncbradley/exercism_ruby
/series/series.rb
UTF-8
245
3.40625
3
[]
no_license
class Series def initialize(string) @string = string end def slices(length) raise ArgumentError.new("length can't be longer than string") if length > @string.length @string.chars.map(&:to_i).each_cons(length).to_a end end
true
cd6f146d7698fda1991c9271832ae53bcbb8cc22
Ruby
mac718/Launch_School
/ruby_basics/methods.rb
UTF-8
1,082
4.53125
5
[]
no_license
#Greeting Through Methods (Part 1) def hello 'Hello' end def world "world" end puts "#{hello} #{world}" #Greeting Through Methods (Part 2) def hello 'Hello' end def world "world" end def greet "#{hello} #{world}" end puts greet #Make and Model def car(make, model) puts "#{make} #{model}" end car('Toyota', 'Corolla') #Naming Animals def dog(name) return name end def cat(name) return name end puts "The dog's name is #{dog('Spot')}." puts "The cat's name is #{cat('Ginger')}." #Name Not Found def assign_name(name = "Bob") name end #Multiply the Sum def add(num1, num2) num1 + num2 end def multiply(num1, num2) num1 * num2 end #Random Sentence names = ['Dave', 'Sally', 'George', 'Jessica'] activities = ['walking', 'running', 'cycling'] def name(names) names.sample end def activity(activities) activities.sample end def sentence(name, activity) "#{name} went #{activity} today!" end #Print Me (Part 1) def print_me puts "I'm printing withing the method!" end #Print Me (Part 2) def print_me "I'm printing withing the method!" end
true
d176b16955e9b4e39826b6ddb2765df6961dc377
Ruby
sunny-b/Ruby_Practice
/arithmetic_integer.rb
UTF-8
430
3.90625
4
[]
no_license
def calculate(num1, num2, op) puts "Can't perform calculation" if (op == '/' || op == '%') && num2.zero? "#{num1} #{op} #{num2} = #{num1.send(op, num2)}" end def prompt(msg) puts "=> #{msg}" end ops = %w(+ - * / % **) prompt('Enter the first number:') first_number = gets.chomp.to_i prompt('Enter the second number') second_number = gets.chomp.to_i ops.each do |op| puts calculate(first_number, second_number, op) end
true
e7fb2724506b2416cd41a2ca987b6f3f627b19ca
Ruby
LucasDerhore/Lexuruby.github.io
/exo_11.rb
UTF-8
116
3.125
3
[]
no_license
puts "Choisi un nombre :" nombre = gets.chomp.to_i compteur = 0 nombre.times { puts "Salut, ca farte ?" }
true
8753abcc7b6303335c1ff62017c137bac484e5f4
Ruby
Bourg/matrix-verify
/matrix.rb
UTF-8
2,845
2.78125
3
[]
no_license
require 'rdl' require 'types/core' type Enumerable, :inject, "(%integer) { (%integer, t) -> %integer } -> %integer" class Matrix private_class_method :new var_type :@rows, 'Array<Array<%integer>>' var_type :@column_count, '%integer' type '() -> Array<Array<%integer>>' def rows @rows end type '() -> %integer x {{x == @rows.size}}' def row_count @rows.size end type '() -> %integer x {{x == 0 && @rows.size == 0 || x == @rows[0].size}}' def column_count @column_count end type '(Array<Array<%integer>>, %integer) -> self' def initialize(rows, column_count) @rows = rows @column_count = column_count end type '() -> %bool' def valid_matrix? var_type :each_row_valid, '%bool' each_row_valid = true @rows.each{|row| each_row_valid = each_row_valid && (row.size == column_count) } column_count >= 0 && each_row_valid end type '(%integer, %integer) -> %bool' def of_size?(num_rows, num_cols) row_count == num_rows && column_count == num_cols end type '(%integer, %integer) -> %bool' def valid_matrix_of_size?(num_rows, num_cols) valid_matrix? && of_size?(num_rows, num_cols) end type '() -> Matrix' def self.empty a = [] a.instantiate! 'Array<%integer>' Matrix.new a, 0 end type '(Array<%integer>) -> Matrix' def self.diagonal(values) var_type :size, 'Fixnum' size = values.size return empty if size == 0 rows = Array.new(size) {|j| row = Array.new(size, 0) row[j] = values[j] row } rows.instantiate! 'Array<%integer>' Matrix.new rows, rows.size end type '(%integer n {{ n > 0 }}, %integer) -> Matrix m {{ m.valid_matrix_of_size?(n, n) }}' def self.scalar(n, value) a = Array.new(n, value) a.instantiate! '%integer' diagonal(a) end type '(%integer, %integer) -> %integer' def ref(i, j) @rows[i][j] end type '(Matrix l {{ l.valid_matrix? }}, Matrix r {{ r.valid_matrix? }}) -> Matrix res {{ res.valid_matrix_of_size?(l.row_count, r.column_count) }}', verify: :later def self.*(l, r) rows = Array.new(l.row_count) {|i| Array.new(r.column_count) {|j| range = Array.new(l.column_count){|x| x} range.instantiate! '%integer' var_type :start, '%integer' start = 0 range.inject(start){|vij, k| vij + l.ref(i, k) * r.ref(k, j) } } } rows.instantiate! "Array<%integer>" return Matrix.new(rows, r.column_count) end end rdl_do_verify :later, 11
true
9fbed999e0b0d72d50661055234f73a5405f4a3c
Ruby
GitHubAdmin/MDS3Builder
/app/models/fields/j0400.rb
UTF-8
701
2.734375
3
[]
no_license
class J0400 attr_reader :title, :options, :name, :field_type, :node def initialize @title = "Health Conditions" @name = "Pain Frequency: Ask resident: 'How much of the time have you experienced pain or hurting over the last 5 days?' (J0400)" @field_type = DROPDOWN @node = "J0400" @options = [] @options << FieldOption.new("^", "NA") @options << FieldOption.new("1", "Almost constantly") @options << FieldOption.new("2", "Frequently") @options << FieldOption.new("3", "Occasionally") @options << FieldOption.new("4", "Rarely") @options << FieldOption.new("9", "Unable to answer") end def set_values_for_type(klass) return "^" end end
true
1b4bcf54d623e71d3cd0d650694a867fe41ea374
Ruby
nihilismus/exercism
/ruby/series/series.rb
UTF-8
362
3.4375
3
[ "WTFPL" ]
permissive
# frozen_string_literal: true class String def enough_length?(size) size.positive? && size <= length end def slices(size) raise ArgumentError, '' unless enough_length? size chars.each_cons(size).map(&:join) end end class Series def initialize(string) @string = string end def slices(length) @string.slices length end end
true
e7f1c3e0896aea76a14ba686ea91618cd7c1ee18
Ruby
maekawatoshiki/lit-x86
/examples/game.rb
UTF-8
395
3.96875
4
[ "Unlicense" ]
permissive
def solve min max mid = min + (max - min) / 2 puts("Is the number smaller than " mid "? or is the " mid " answer? (yes/no/answer)") ans = gets() if ans[0] == 'y' solve(min mid-1) elsif ans[0] == 'n' solve(mid+1 max) elsif ans[0] == 'a' puts("you choose " mid "!!") end end min = 1 max = 100 puts("Imagine a number between " min " and " max ", and answer questions") solve(min max)
true
04006774b1c7423f49ee54e428b491215073a775
Ruby
daneb/assessment
/question2/custom_errors.rb
UTF-8
348
2.53125
3
[]
no_license
module FlattenIntegerArray module CustomErrors class InputValidationError < StandardError def initialize(message) super(message) end end def self.raise_validation_exception notification = "This is not an arbitrarily nested array of integers" raise InputValidationError, notification end end end
true
424e32680bca1ea7f9f62716d7ab86f61df1dbf2
Ruby
zhivou/playground
/algorithms/array_shift_left.rb
UTF-8
1,056
4.65625
5
[]
no_license
# Shifting whole array on a time left 123 -> 231 -> 312 etc.. # Remember: # array.shift is take left item and deleting it at the same time it returns its value # array.push(n) is adding a value at the end of the array and n - what value it should be! # .join is adding string seportor to the intiger items #.first returns first item from array # Make sure when you create array you don't have [] or .new otherwise it will create 1 sized arrray with # 1..n in one item! #1.0 # Input: a = 12 b = 4 array = Array(1..a) shift_array = Array(1..b) # # Body: # #1 # shift_array.each do |index| # moving_part = array.shift # array = array.push(moving_part) # end # #2 # shift_array.each do |index| # length = array.length # moving_part = array.first # array.delete_at(0) # array << moving_part # raise "Length incorrect!" if array.length != length # end #3 Indexes only shift_array.each do |index| move_item = array[0] array.delete_at(0) array << move_item end # Output: puts "Shift times: #{b}" puts array.join(' ')
true
31373192fb69a03b51ef5eb4147b3a85ba98589c
Ruby
thomasbrus/predicting-scrabble-game-outcomes
/2-extracting-features/lib/internet_scrabble_club/feature_constructors/first_player_average_score.rb
UTF-8
464
2.546875
3
[]
no_license
require_relative 'base' module InternetScrabbleClub module FeatureConstructors class FirstPlayerAverageScore < Base def construct current_score / number_of_turns.to_f end private def number_of_turns FeatureConstructors::FirstPlayerNumberOfTurns.new(turns, game).construct end def current_score FeatureConstructors::FirstPlayerCurrentScore.new(turns, game).construct end end end end
true
0969f22b3933817684f2dfc95187fa2e3cbe197c
Ruby
eiriklied/xlsx_parser
/spec/workbook_spec.rb
UTF-8
3,054
2.703125
3
[ "MIT" ]
permissive
require 'spec_helper' describe XlsxParser::Workbook do before :each do @workbook = XlsxParser::Workbook.new('data/regular_workbook.xlsx') end context 'sheets' do it 'should give the names of the sheets in a workbook' do expect(@workbook.sheets).to eq ['Sheet number one', 'Number two'] end it 'should throw an error if trying to get a sheet that does not exist' do expect { @workbook.sheet('not a real sheet name') }.to raise_error(XlsxParser::Workbook::SheetNotFoundException) end end context 'single sheet' do it 'should return a sheet by its name' do @sheet = @workbook.sheet('Sheet number one') expect(@sheet).to be_an_instance_of(XlsxParser::Sheet) expect(@sheet.name).to eq 'Sheet number one' end end context 'default_sheet' do it 'should default to first sheet if no default sheet has been set' do expect(@workbook.default_sheet.name).to eq('Sheet number one') end it 'should be able to set default sheet sending in a sheet' do @workbook.default_sheet = @workbook.sheet(@workbook.sheets.last) expect(@workbook.default_sheet.name).to eq('Number two') end it 'should be able to set default sheet sending in just sheet name' do @workbook.default_sheet = 'Number two' expect(@workbook.default_sheet.name).to eq('Number two') end it 'should be able to set default sheet sending in an integer' do @workbook.default_sheet = 2 expect(@workbook.default_sheet.name).to eq('Number two') @workbook.default_sheet = 1 expect(@workbook.default_sheet.name).to eq('Sheet number one') end it 'should raise an error if trying to default to a sheet name that does not exist' do expect { @workbook.default_sheet = 'bogus' }.to raise_error(XlsxParser::Workbook::SheetNotFoundException) end it 'should raise an error if trying to default to a sheet number that does not exist' do expect { @workbook.default_sheet = 123 }.to raise_error(XlsxParser::Workbook::SheetNotFoundException) end it 'should raise an error if a bogus param was sent in' do expect { @workbook.default_sheet = 0.3 }.to raise_error(TypeError) end end context '*_row and *_column methods' do it 'should respond to *_row methods' do expect(@workbook.first_row).to eq 1 expect(@workbook.last_row).to eq 4 end it 'should respond to *_column methods' do expect(@workbook.first_column).to eq 1 expect(@workbook.last_column).to eq 3 end end context 'cell' do it 'should proxy cell calls to sheet' do expect(@workbook.cell(1, 'A')).to eq('Cell 1 A') @workbook.default_sheet = 2 expect(@workbook.cell(2, 'B')).to eq('Sheet 2, cell 2 B') end end it 'should not crash on documents with no sharedStrings.xml' do @workbook = XlsxParser::Workbook.new('data/no_shared_strings.xlsx') expect(@workbook.cell(1, 'B')).to eq('Name') expect(@workbook.cell(2, 'B')).to eq('Milton Friedman') end end
true
93b7d01e8bf4a37fce9ed3bdd792974fcf8d7ba6
Ruby
johnantoni/ruby.json
/solutions/steve/json_parser.rb
UTF-8
2,185
2.796875
3
[]
no_license
require 'treetop' File.open("json.treetop", "w") {|f| f.write GRAMMAR } Treetop.load "json" parser = JsonParser.new pp parser.parse(STDIN.read).value if $0 == __FILE__ BEGIN { GRAMMAR = %q{ grammar Json rule json space json_value space { def value; json_value.value; end } end rule json_value string / numeric / keyword / object / array end rule string '"' chars:char* '"' { def value chars.elements.map {|e| e.value }.join end } end rule char !'"' ('\\\\' ( ( [nbfrt"] / '\\\\' / '/' ) / 'u' hex hex hex hex ) / !'\\\\' .) { def value if text_value[0..0] == '\\\\' case c = text_value[1..1] when /[nbfrt]/ {'n' => "\n", 'b' => "\b", 'f' => "\f", 'r' => "\r", 't' => "\t"}[c] when 'u' [text_value[2,4].to_i(16)].pack("L").gsub(/\0*$/,'') else c end else text_value end end } end rule hex [0-9a-fA-F] end rule numeric exp / float / integer end rule exp (float / integer) ('e' / 'E') ('+' / '-')? integer { def value; text_value.to_f; end } end rule float integer '.' [0-9]+ { def value; text_value.to_f; end } end rule integer '-'? ('0' / [1-9] [0-9]*) { def value; text_value.to_i; end } end rule keyword ('true' / 'false' / 'null') { def value { 'true' => true, 'false' => false, 'null' => nil }[text_value] end } end rule object '{' space pairs:pair* space '}' { def value pairs.elements.map {|p| p.value }.inject({}) {|h,p| h.merge p } end } end rule pair space string space ':' space json_value space (',' &pair / !pair) { def value { string.value => json_value.value } end } end rule array '[' space array_values:array_value* space ']' { def value array_values.elements.map {|e| e.value } end } end rule array_value space json_value space (',' &array_value / !array_value) { def value json_value.value end } end rule space [ \t\r\n]* end end } }
true
1f16188b95dd97ce2dab72236e914dba9a35b37e
Ruby
Yoshyn/coding_game_spring-challenge-2020
/tests/path_finder_test.rb
UTF-8
13,490
2.953125
3
[]
no_license
require "minitest/autorun" require "pry-byebug" require_relative "../core_ext/hash" require_relative "./helper" require_relative "../path_finder" require_relative "../scoring_path_finder" require_relative "../cell" require 'benchmark' class TestCell < Cell def accessible_for?(_ = nil ); data != '#'; end end class ScoringPathFinder def move_profit(current, neighbor) current.profit + @grid[neighbor.to].data.to_i end end class PathFinderTest < Minitest::Test IS_VISITABLE = -> (cell) { cell && cell.accessible_for?(nil) } def assert_hash_includes(hash1, hash2) if hash1.include?(hash2) assert_equal true, hash1.include?(hash2) else assert_equal hash1, hash2 end end def test_shortest_path_finder data ||= [ ['.', '.', '.', '.', '.', '.', '#', '.'], ['.', '#', '.', '#', '#', '.', '#', '.'], ['.', '#', '#', '#', '.', '.', '#', '.'], ['.', '#', '.', '.', '.', '.', '#', '.'], ['.', '#', '#', '#', '#', '.', '#', '.'], ['.', '.', '.', '.', '.', '.', '#', '.'], ] grid = init_grid(data, TestCell); assert_equal({ next: Position.new(0,1), # dir: :north, depth: 1, profit: 0, cost: 1, path: [Position.new(0,1)]}, PathFinder.new(grid, Position.new(0,2), is_visitable: IS_VISITABLE).shortest_path( Position.new(0,1))) assert_equal({ next: Position.new(1,0), # dir: :west, profit: 0, cost: 7, depth: 7, path: [ Position.new(1,0), Position.new(0,0), Position.new(0,1), Position.new(0,2), Position.new(0,3), Position.new(0,4), Position.new(0,5)]}, PathFinder.new(grid, Position.new(2,0), is_visitable: IS_VISITABLE).shortest_path( Position.new(0,5))) assert_equal({ next: Position.new(2,0), # dir: :north, profit: 0, cost: 10, depth: 10, path: [ Position.new(2,0), Position.new(3,0), Position.new(4,0), Position.new(5,0), Position.new(5,1), Position.new(5,2), Position.new(5,3), Position.new(4,3), Position.new(3,3), Position.new(2,3) ]}, PathFinder.new(grid, Position.new(2,1), is_visitable: IS_VISITABLE).shortest_path( Position.new(2,3))) assert_equal({ next: Position.new(3,0), # dir: :east, profit: 0, cost: 9, depth: 9, path: [ Position.new(3,0), Position.new(4,0), Position.new(5,0), Position.new(5,1), Position.new(5,2), Position.new(5,3), Position.new(4,3), Position.new(3,3), Position.new(2,3) ]}, PathFinder.new(grid, Position.new(2,0), is_visitable: IS_VISITABLE).shortest_path( Position.new(2,3))) assert_equal(PathFinder.no_result, PathFinder.new(grid, Position.new(2,0), is_visitable: IS_VISITABLE).shortest_path(Position.new(10,10))) assert_equal(PathFinder.no_result, PathFinder.new(grid, Position.new(2,0), is_visitable: IS_VISITABLE).shortest_path( Position.new(1,1))) assert_equal(PathFinder.no_result, PathFinder.new(grid, Position.new(0,0), is_visitable: IS_VISITABLE).shortest_path( Position.new(7,0))) end def test_shortest_path_finder_move_value data ||= [ ['.', '.', '.', '.', '.', '.', '#', '.'], ['.', '#', '.', '#', '#', '.', '#', '.'], ['.', '#', '#', '#', '.', '.', '#', '.'], ['.', '#', '.', '.', '.', '.', '#', '.'], ['.', '#', '#', '#', '#', '.', '#', '.'], ['.', '.', '.', '.', '.', '.', '#', '.'], ] grid = init_grid(data, TestCell); assert_equal({ next: Position.new(0,1), # dir: :north, profit: 0, cost: 1, depth: 1, path: [Position.new(0,1)] }, PathFinder.new(grid, Position.new(0,2), is_visitable: IS_VISITABLE, move_size: 2).shortest_path( Position.new(0,1) ) ) assert_equal({ next: Position.new(0,0), # dir: :north, profit: 0, cost: 1, depth: 2, path: [Position.new(0,1), Position.new(0,0)]}, PathFinder.new(grid, Position.new(0,2), is_visitable: IS_VISITABLE, move_size: 2).shortest_path( Position.new(0,0) ) ) assert_equal({ next: Position.new(0,1), # dir: :north, profit: 0, cost: 2, depth: 3, path: [Position.new(0,2), Position.new(0,1), Position.new(0,0)]}, PathFinder.new(grid, Position.new(0,3), is_visitable: IS_VISITABLE, move_size: 2).shortest_path( Position.new(0,0)) ) assert_equal({ next: Position.new(0,0), # dir: :north, profit: 0, cost: 1, depth: 3, path: [Position.new(0,2), Position.new(0,1), Position.new(0,0)]}, PathFinder.new(grid, Position.new(0,3), is_visitable: IS_VISITABLE, move_size: 3).shortest_path( Position.new(0,0)) ) end def test_tor_shortest_path_finder data ||= [ ['#', '#', '.', '.', '#', '#'], ['.', '.', '.', '.', '.', '.'], ['#', '#', '.', '#', '#', '#'], ] grid = init_tor_grid(data, TestCell); assert_equal({ next: Position.new(0,1), # dir: :west, profit: 0, cost: 2, depth: 2, path: [Position.new(0,1), Position.new(5,1)] }, PathFinder.new(grid, Position.new(1,1), is_visitable: IS_VISITABLE).shortest_path( Position.new(5,1))) grid[Position.new(0,1)].data = '#' assert_equal({ next: Position.new(2,1), # dir: :east, profit: 0, cost: 4, depth: 4, path: [ Position.new(2,1), Position.new(3,1), Position.new(4,1), Position.new(5,1) ]}, PathFinder.new(grid, Position.new(1,1), is_visitable: IS_VISITABLE).shortest_path( Position.new(5,1))) end def test_longest_path_finder data ||= [ ['.', '#', '.', '.', '.', '.', '#', '.' ], ['.', '#', '.', '#', '#', '.', '#', '.' ], ['.', '#', '#', '#', '.', '.', '#', '.' ], ['.', '#', '#', '.', '.', '.', '#', '#' ], ['.', '#', '#', '#', '#', '.', '#', '#' ], ['.', '#', '.', '.', '#', '.', '#', '.' ], ] grid = init_grid(data, TestCell); assert_equal(PathFinder.no_result, PathFinder.new(grid, Position.new(7,5), is_visitable: IS_VISITABLE).longest_path) assert_equal({ next: Position.new(3,5), # dir: :south, profit: 1, depth: 1, cost: 1, path: [Position.new(3,5)]}, PathFinder.new(grid, Position.new(2,5), is_visitable: IS_VISITABLE).longest_path) assert_equal({ next: Position.new(0,2), # dir: :south, profit: 4, depth: 4, cost: 4, path: [ Position.new(0,2), Position.new(0,3), Position.new(0,4), Position.new(0,5) ]}, PathFinder.new(grid, Position.new(0,1), is_visitable: IS_VISITABLE).longest_path) grid[Position.new(1,0)].data = '.' ## skip thisSee test_longest_path_finder_loop # assert_hash_includes( # PathFinder.new(grid, Position.new(0,1), is_visitable: IS_VISITABLE).longest_path, # { next: Position.new(0,0), depth: 13, cost: 13 } #dir: :north # ) grid[Position.new(1,0)].data = '#' grid[Position.new(0,0)].set_neighbor(Position.new(7,0), 0, :west) assert_hash_includes( PathFinder.new(grid, Position.new(0,1), is_visitable: IS_VISITABLE).longest_path, { next: Position.new(0,2), depth: 4 } #dir: :south ) grid[Position.new(0,0)].get_neighbor(Position.new(7,0)).cost = 2 assert_hash_includes( PathFinder.new(grid, Position.new(0,1), is_visitable: IS_VISITABLE, move_size: 1).longest_path, { next: Position.new(0,0) } #dir: :north ) assert_hash_includes( PathFinder.new(grid, Position.new(0,1), is_visitable: IS_VISITABLE, move_size: 3).longest_path, { next: Position.new(7,0) } #dir: :north ) end # TODO : solve this two horrible problem # One solution can be to make a crow fly # def test_longest_path_finder_loop # data ||= [ # ['.', '.', '.', '#' ], # ['.', '#', '.', '#' ], # ['#', '.', '.', '#' ], # ['#', '.', '.', '#' ], # ['#', '#', '.', '#' ] # ] # grid = init_grid(data, TestCell); # assert_hash_includes( # PathFinder.new(grid, Position.new(0,0), is_visitable: IS_VISITABLE).longest_path, # { next: Position.new(1,0), depth: 8, cost: 8 } # ) # data ||= [ # ['#', '.', '.', '.',], # ['#', '.', '#', '.',], # ['#', '.', '.', '#',], # ['#', '.', '.', '#',], # ['#', '.', '#', '#',] # ] # grid = init_grid(data, TestCell); # assert_hash_includes( # PathFinder.new(grid, Position.new(3,0), is_visitable: IS_VISITABLE).longest_path, # { next: Position.new(1,0), depth: 8, cost: 8 } # ) # end def test_longest_path_finder_max_depth data ||= [ ['.', '#'], ['.', '#'], ['.', '#'], ['.', '#'], ['.', '#'], ['.', '.'], ] grid = init_grid(data, TestCell); assert_equal({ next: Position.new(0,0), # dir: :north, profit: 1, depth: 1, cost: 1, path: [ Position.new(0,0) ]}, PathFinder.new(grid, Position.new(0,1), is_visitable: IS_VISITABLE).longest_path(max_depth: 1)) assert_equal({ next: Position.new(0,2), # dir: :north, profit: 2, depth: 2, cost: 2, path: [ Position.new(0,2), Position.new(0,3) ]}, PathFinder.new(grid, Position.new(0,1), is_visitable: IS_VISITABLE).longest_path(max_depth: 2)) end # # # Max cost is only to reduce the possibility count. # # # Like max_depth but max_depth is included in SPF def scoring_path_finder(grid, from, move_size: 1, max_cost: Float::INFINITY, max_depth: Float::INFINITY) break_if = -> (current, to) { (current.cost > max_cost || current.depth >= max_depth) } is_visitable = -> (cell) { cell.accessible_for? } move_profit = -> (current, neighbor) { current.profit + grid[neighbor.to].data.to_i } move_cost = -> (current, neighbor) { ((current.depth + neighbor.cost).to_f / move_size).round } pf = PathFinder.new(grid, from, break_if: break_if, is_visitable: IS_VISITABLE, move_profit: move_profit, move_cost: move_cost, move_size: move_size ) pf.longest_path(max_depth: max_depth) end def test_scoring_path_finder data ||= [ ['#', '#', '2', '2', '2', '#'], ['5', '@', '1', '1', '1', '1'], ['#', '#', '1', '1', '#', '#'], ] grid = init_grid(data, TestCell); assert_equal({ next: Position.new(0,1), profit: 5, depth: 1, cost: 1, path: [ Position.new(0,1) ]}, scoring_path_finder(grid, Position.new(1,1))) assert_equal({ next: Position.new(0,1), profit: 5, depth: 1, cost: 1, path: [ Position.new(0,1) ]}, scoring_path_finder(grid, Position.new(1,1), move_size: 2)) grid[Position.new(3,1)].data = "8" assert_equal({ next: Position.new(0,1), profit: 5, depth: 1, cost: 1, path: [ Position.new(0,1) ]}, scoring_path_finder(grid, Position.new(1,1))) assert_equal({ next: Position.new(3,1), profit: 9, cost: 1, depth: 2, path: [ Position.new(2,1), Position.new(3,1)]}, scoring_path_finder(grid, Position.new(1,1), move_size: 2)) end def test_scoring_path_finder_for_pac_man data ||= [ ['#', '#', '2', '2', '2', '#'], ['5', '@', '1', '1', '1', '1'], ['#', '#', '1', '1', '#', '#'], ] grid = init_grid(data, GameCell) pacman = OpenStruct.new(position: Position.new(1,1), current_speed: 1) pf = ScoringPathFinder.new(grid, pacman) assert_equal({ next: Position.new(0,1), profit: 5, depth: 1, cost: 1, path: [ Position.new(0,1) ]}, pf.path_finder) end def test_performance_shortest_path data ||= [ ['.', '#', '.', '.', '.', '.', '#', '.' ]*4, ['.', '.', '.', '#', '#', '.', '#', '.' ]*4, ['.', '#', '#', '#', '.', '.', '.', '.' ]*4, ['.', '#', '#', '.', '.', '.', '#', '#' ]*4, ['.', '#', '#', '#', '#', '.', '.', '#' ]*4, ['.', '.', '.', '.', '.', '.', '#', '.' ]*4, ]*5 grid = init_grid(data, GameCell); Game.instance.grid_turn = grid player = Player.new(1) pacman = player.get_pac_man(1) pacman.update(Position.new(0,0), "ROCK", 0, 8) is_visitable = -> (cell) { cell && cell.accessible_for?(pacman) } res = nil max_value = 3 #ms running_time = Benchmark.realtime { pf = PathFinder.new(grid, Position.new(0,0), is_visitable: is_visitable) res = pf.shortest_path(Position.new(20,20)) } * 1000 assert_equal(42, res[:path].count) refute_operator running_time, :>, max_value end def test_performance_scoring_path data ||= [ ['.', '#', '.', '1', '5', '1', '#', '1' ]*4, ['.', '.', '.', '#', '#', '1', '#', '1' ]*4, ['.', '#', '.', '#', '1', '1', '5', '1' ]*4, ['.', '#', '.', '1', '0', '1', '#', '#' ]*4, ['.', '.', '.', '#', '#', '1', '1', '#' ]*4, ['1', '5', '1', '1', '1', '1', '#', '1' ]*4, ]*5 grid = init_grid(data, GameCell); Game.instance.grid_turn = grid player = Player.new(1) pacman = player.get_pac_man(1) pacman.update(Position.new(0,0), "ROCK", 0, 8) puts "Max coord : (#{grid.width}, #{grid.height})" res = nil max_value = 3 #ms running_time = Benchmark.realtime { pf = ScoringPathFinder.new(grid, pacman) #, max_depth: 20) res = pf.path_finder } * 1000 assert_equal(195, res[:path].count) #Infinity # assert_equal(20, res[:path].count) refute_operator running_time, :>, max_value end end
true
ce88eb83c944b5ace7922458c6e665e85b69ef60
Ruby
Azzerty23/THP
/THP-jour12/lib/caesar_cipher.rb
UTF-8
742
3.5625
4
[]
no_license
def caesar_cipher(message, key=5) unless message.is_a?(String) && key.is_a?(Integer) return "The message must be a String and the key an Integer" end encoded_message = [] letters = message.split("") letters.each do |letter| letter_ascii = letter.downcase.ord encoded_letter = letter_ascii + key if letter.match?(/\s/) encoded_letter = letter elsif encoded_letter > ("z".ord - key) encoded_letter -= 26 end if letter.match?(/[[:upper:]]/) encoded_message << encoded_letter.chr.upcase else encoded_message << encoded_letter.chr end end return encoded_message.join("") end print caesar_cipher("helLo you") print caesar_cipher("Z", 1)
true
0da0c77cb11ffe6532adb379dbf8c089a5a27f56
Ruby
ababup1192/Rating_aizu_v2
/src/view/rating_dir.rb
UTF-8
1,032
2.578125
3
[]
no_license
# -*- coding: utf-8 -*- require 'observer' require 'tk' module View class RatingDir include Observable def initialize(dialog, rating_dir) add_observer(rating_dir) @label = TkLabel.new(dialog){ text '"採点対象ディレクトリ"の場所:' } @frame = TkFrame.new(dialog) @entry = TkEntry.new(@frame){ width 40 state 'readonly' } TkUtils.set_entry_value(@entry, rating_dir.value) @button = TkButton.new(@frame){ text '変更' } @button.command(self.method(:save_value)) end def pack() @label.pack({side: 'top', anchor: 'w', padx: 10, pady: 10}) @frame.pack({side: 'top'}) @entry.pack({side: 'left'}) @button.pack({side: 'left', padx: 15}) end def save_value() value = Tk.chooseDirectory if !value.empty? then TkUtils.set_entry_value(@entry, value) else @value = nil end changed notify_observers(value) end end end
true
174789f00e2f7fd4a5bb24f493b7169d5825256f
Ruby
flipstone/codiphi
/engine/examples/functional/parser/formula_spec.rb
UTF-8
2,002
2.796875
3
[]
no_license
require_relative 'spec_helper.rb' describe Codiphi::Formula::Parser do it "parses an integer" do Codiphi::Formula::Parser.should parse "1" end it "parses basic arithmetic operations" do Codiphi::Formula::Parser.should parse "1 + 2" Codiphi::Formula::Parser.should parse "1 - 2" Codiphi::Formula::Parser.should parse "1 * 2" Codiphi::Formula::Parser.should parse "1 / 2" Codiphi::Formula::Parser.should parse "1+2" Codiphi::Formula::Parser.should parse "1-2" Codiphi::Formula::Parser.should parse "1*2" Codiphi::Formula::Parser.should parse "1/2" end it "parses multiple arithmetic operations with parentheticals" do Codiphi::Formula::Parser.should parse "1 + 2 + 3" Codiphi::Formula::Parser.should parse "1 * 2 + 3" Codiphi::Formula::Parser.should parse "1 + 2 * 3" Codiphi::Formula::Parser.should parse "1 / 2 - 3" Codiphi::Formula::Parser.should parse "1 - 2 / 3" Codiphi::Formula::Parser.should parse "1 - 2 / 3 + 4 * 5" end it "parses parentheticals" do Codiphi::Formula::Parser.should parse "(1)" Codiphi::Formula::Parser.should parse "(1 + 2)" Codiphi::Formula::Parser.should parse "1 + (2)" Codiphi::Formula::Parser.should parse "1 * (2 + 3)" Codiphi::Formula::Parser.should parse "(1 * 2) + 3" end it "doesn't parse unmatch parentheses" do Codiphi::Formula::Parser.should_not parse "(" Codiphi::Formula::Parser.should_not parse ")" Codiphi::Formula::Parser.should_not parse "1)" Codiphi::Formula::Parser.should_not parse "(1" Codiphi::Formula::Parser.should_not parse "((1 + 2)" Codiphi::Formula::Parser.should_not parse "(1 + 2))" Codiphi::Formula::Parser.should_not parse "(1) + 2)" end it "parses function references" do Codiphi::Formula::Parser.should parse "foo(:bar)" Codiphi::Formula::Parser.should parse "baz(:bat)" Codiphi::Formula::Parser.should parse "3 * baz(:bat)" Codiphi::Formula::Parser.should parse "baz(:bat) - 3" end end
true
d8673b057e9ae585385086455794f6116243c1be
Ruby
Mycobee/koroibos_api
/spec/requests/api/v1/olympians_request_spec.rb
UTF-8
1,866
2.640625
3
[]
no_license
require 'rails_helper' describe "olympians api" do before :each do olympian_1_attrs = { name: "Bob Ross", sex: "M", age: 42, height: 190, weight: 140, team: 'USA' } sport_1 = Sport.create!(name: 'competitive painting') @olympian_1 = sport_1.olympians.create!(olympian_1_attrs) olympian_2_attrs = { name: "Prince", sex: "M", age: 22, height: 160, weight: 110, team: 'USA' } sport_2 = Sport.create!(name: 'competitive dancing') @olympian_2 = sport_2.olympians.create!(olympian_2_attrs) olympian_3_attrs = { name: "Garth Brooks", sex: "F", age: 12, height: 120, weight: 190, team: 'Russia' } sport_3 = Sport.create!(name: 'competitive yodling') @olympian_3 = sport_3.olympians.create!(olympian_3_attrs) end it "sends a list of olympians" do get '/api/v1/olympians' expect(response).to be_successful olympian_data = JSON.parse(response.body) expect(olympian_data["olympians"][0]["name"]).to eq(@olympian_1.name) expect(olympian_data["olympians"][2]["sport"]).to eq(@olympian_3.sport.name) end it "filters by youngest age param" do get '/api/v1/olympians?age=youngest' expect(response).to be_successful olympian_data = JSON.parse(response.body) expect(olympian_data["olympian"]["name"]).to eq(@olympian_3.name) end it "filters by oldest age param" do get '/api/v1/olympians?age=oldest' expect(response).to be_successful olympian_data = JSON.parse(response.body) expect(olympian_data["olympian"]["name"]).to eq(@olympian_1.name) end it "returns 400 for an invalid age param" do get '/api/v1/olympians?age=chicken_dinner' expect(response).to have_http_status(400) end end
true
9036ccc7cd841a537544eda3f58fb592c66465c5
Ruby
DenialAdams/mumblecop
/plugins/music_websites.rb
UTF-8
2,862
2.640625
3
[ "MIT" ]
permissive
require 'open3' # Feed youtube streams into mpd class Youtube < Plugin def initialize super @needs_sanitization = true @commands = %w(youtube yt) @help_text = 'Play a youtube video - youtube [url] (starting time in seconds)' @min_args = 1 @quality = :normal end def go(source, _command, args, bot) result = nil error = 'No youtube-dl error' format = '-f140' format = '-f141' if @quality == :high || args.include?('high') format = '-f140' if args.include?('normal') # We use popen3 to avoid any injection vulnerabilities Open3.popen3('youtube-dl', '--no-cache-dir', '-i', format, '-q', '--no-warnings', '-ge', (args[0]).to_s) do |_stdin, stdout, stderr| result = stdout.read.chomp error = stderr.read.chomp end # Split the result into the title (0) and the stream (1) result = result.split("\n") if CONFIG['debug'] bot.say(self, source, result[0]) bot.say(self, source, result[1]) end bot.mpd.add(result[1]) # MPD doesn't like quotes in the track for send_command so as a hack we change them to single quotes result[0].tr!('"', "'") bot.mpd.send_command('addtagid', bot.mpd.queue.last.id, 'title', result[0]) bot.mpd.send_command('addtagid', bot.mpd.queue.last.id, 'albumartist', bot.get_username_from_source(source)) bot.mpd.play if bot.mpd.stopped? bot.say(self, source, "Request successful. Loading #{result[0]}...") bot.mpd.seek(args[1].to_i) if args[1] && args[1].to_i != 0 rescue => e bot.say(self, source, 'Failed to load video. Check given url, quality, and seek parameter.') bot.say(self, source, error) bot.say(self, source, e.message) end end # Feed soundcloud streams into mpd class Soundcloud < Plugin def initialize super @needs_sanitization = true @commands = %w(soundcloud sc) @help_text = 'Play a soundcloud song - soundcloud [url] (starting time in seconds)' @min_args = 1 end def go(source, _command, args, bot) result = nil error = 'No youtube-dl error' # We use popen3 to avoid any injection vulnerabilities Open3.popen3('youtube-dl', '--prefer-insecure', '-i', '-g', '-q', '--no-warnings', (args[0]).to_s, '-f', 'mp3') do |_stdin, stdout, stderr| result = stdout.read.chomp error = stderr.read.chomp end bot.mpd.say(self, source, result) if CONFIG['debug'] bot.mpd.add(result) bot.mpd.send_command('addtagid', bot.mpd.queue.last.id, 'albumartist', bot.get_username_from_source(source)) bot.mpd.play if bot.mpd.stopped? bot.say(self, source, 'Request successful. Loading...') bot.mpd.seek(args[1].to_i) if args[1] rescue => e bot.say(self, source, 'Failed to stream song. Check given url and seek parameter (if given.)') bot.say(self, source, error) bot.say(self, source, e.message) end end
true
473ffa569468fd856c6d6cb01bc733d6e9924e63
Ruby
tsmall/advent-of-code
/2021/07/ruby/solution.rb
UTF-8
1,649
3.5625
4
[]
no_license
# Advent of Code 2021 # Day 7: The Treachery of Whales require 'immutable' module Day07 module_function def run puts "Part 1: #{part_one}" puts "Part 2: #{part_two}" end def part_one(text=nil) text ||= input.read positions = parse(text) most_efficient_dest(positions, method(:naive_fuel_cost)) end def part_two(text=nil) text ||= input.read positions = parse(text) most_efficient_dest(positions, method(:actual_fuel_cost)) end def most_efficient_dest(positions, fuel_proc) costs = {} start = median(positions) 1000.times do |diff| dest = start + diff costs[dest] = total_fuel_cost(positions, dest, fuel_proc) dest = start - diff if dest > 0 costs[dest] = total_fuel_cost(positions, dest, fuel_proc) end end costs.values.min end def total_fuel_cost(positions, dest, fuel_proc) costs = fuel_costs(positions, dest, fuel_proc) costs.sum end def fuel_costs(positions, dest, fuel_proc) positions.collect do |src| fuel_proc.call(src, dest) end end def naive_fuel_cost(src, dest) distance(src, dest) end def actual_fuel_cost(src, dest) n = distance(src, dest) sum_up_to(n) end def distance(src, dest) (src - dest).abs end def sum_up_to(n) (n * (n + 1)) / 2 end def median(positions) positions .group_by { |pos| pos } .values .max_by(&:size) .first end def parse(text) Immutable::Vector.new(text.split(',').collect(&:to_i)) end def input File.open("../input.txt") end end if $PROGRAM_NAME == __FILE__ Day07.run end
true
bc5a3848b5d92641db448b6274584377ee1a2589
Ruby
pa-childs/Udemy_Courses
/learn_to_code-ruby/Section_13/convert_hash_to_array.rb
UTF-8
510
3.34375
3
[]
no_license
spice_girls = {scary: "Melanie Brown", sporty: "Menanie Chisholm", baby: "Emma Bunton", ginger: "Geri Halliwell", posh: "Victoria Beckham"} # Displays each key-value as an array within an array p spice_girls.to_a # Can make one non-nested array if desired p spice_girls.to_a.flatten puts avengers = [[:iron_man, "Tony Stark"], [:captain_america,"Steve Rogers"], [:black_widow,"Natasha Romanoff"], [:hulk,"Bruce Banner"], [:scarlet_witch,"Wanda"] ] p avengers.to_h
true
d9ba5b82d9631c29c95566423a716b4e4af25615
Ruby
sweetyBThareja/rubyCode
/RubymineProjects/ruby_project/accessor.rb
UTF-8
729
3.921875
4
[]
no_license
class TestClass def initialize id, name @id = id @name = name end def id @id end def name @name end def name= s @name = s end end #Test it works properly tc = TestClass.new 12, 'Boris' p tc.id p tc.name tc.name = 'Alfie' p tc.name #Ruby offers a short cut for getters and setters. The above class can be re-written like this: class TestClass def initialize id, name @id = id @name = name end attr_reader :id attr_accessor :name end obj = TestClass.new 1, "sweety" p obj.id p obj.name #Ruby offers a short cut for getters and setters. i.e accessor methods class TestClassA attr_accessor :name, :id end obj1 = TestClassA.new obj1.name = "Rajat" obj1.id = 2 puts obj1.name puts obj1.id
true
c5c9d7273cbd4a0e5321814cb8e40c711b264ccd
Ruby
wntmddus/Intro-to-Algorithms
/improving_complexity_version_one.rb
UTF-8
753
2.59375
3
[]
no_license
<<<<<<< HEAD def poorly_written_ruby(*arrays) combined_array = [] (0..arrays.length-1).each do |i| (0..arrays[i].length-1).each do |j| combined_array << arrays[i][j] end end sorted_array = [combined_array.delete_at(combined_array.length-1)] for j in (0..combined_array.length-1) i = 0 current = combined_array[j] sorted_array_length = sorted_array.length while current < sorted_array_length if current <= sorted_array[i] sorted_array.insert(i, current) break elsif i == sorted_array_length-1 sorted_array << current break end i+=1 end end # Return the sorted array sorted_array end ======= >>>>>>> 1779c7001d42e60293990037e1258c1221c38c2a
true
ba0cf74b337284def25220761f2c8df19db332b6
Ruby
BenGoldstein88/phase-0-tracks
/something_awesome/song_storage.rb
UTF-8
2,962
3.90625
4
[]
no_license
# Program that stores songs and related information # song_name (str), artist_name (str), album_name (str), original_key (str), year (str) # User should be able to view all songs, an individual song, and input new songs # require gems require 'sqlite3' # create empty SQLite3 database db = SQLite3::Database.new("songs.db") db.results_as_hash = true create_table_cmd = <<-SQL CREATE TABLE IF NOT EXISTS songs( id INTEGER PRIMARY KEY, song_name VARCHAR(255), artist_name VARCHAR(255), album_name VARCHAR(255), original_key VARCHAR(255), year VARCHAR(255) ) SQL # create songs table if not EXISTS db.execute(create_table_cmd) # method to add a new song to the table def create_song(db, name, artist, album, key, year) db.execute("INSERT INTO songs (song_name, artist_name, album_name, original_key, year) VALUES (?, ?, ?, ?, ?)", [name, artist, album, key, year]) end # method to list all songs def list_all_songs(db) db.execute("SELECT * FROM songs") end # method to list a single song def list_song(db, song) db.execute("SELECT * FROM songs WHERE song_name=#{song}") end # sample song addition # create_song(db, 'Drive My Car', 'The Beatles', 'Rubber Soul', 'D', 1965) # Driver code/UI puts "Welcome to song storage! What would you like to do?" puts "1: List all songs" puts "2: Add a song" puts "3: Get info on a song" puts "4: Exit" done = false error_count = 0 while done == false input = gets.chomp if input == '1' # list all songs puts "Here you go!" puts list_all_songs(db) puts "Anything else? (1: List all songs, 2: Add a song, 3: Get info on a song, 4: Exit)" elsif input == '2' # add a song puts "What's the song name?" name = gets.chomp puts "Who's the artist?" artist = gets.chomp puts "What album was the song released on?" album = gets.chomp puts "What's the original key?" key = gets.chomp puts "What year was the song released?" year = gets.chomp puts "Thanks! Anything else? (1: List all songs, 2: Add a song, 3: Get info on a song, 4: Exit)" create_song(db, name, artist, album, key, year) elsif input == '3' # get info on a song puts "What song would you like information on?" search = gets.chomp search = "'" + search + "'" puts "Here you go!" puts list_song(db, search) puts "Anything else? (1: List all songs, 2: Add a song, 3: Get info on a song, 4: Exit)" elsif input == '4' # exit puts "Thanks!" done = true else if error_count >= 3 puts "You're pretty bad at this. Shutting down." done = true else puts "I don't understand what you're getting at. Maybe try again?" error_count += 1 end end end # There are plenty more semi-useless features that could be implemented, like searching by year or album. # Maybe albums should be its own table w/ foreign key # The driver code could be cleaned-up with sub-methods and maybe a case statement.
true
d93c87869245d70dffe9821dd87f6502b649ce74
Ruby
cassiebeisheim/kwk-l1-ruby-2-meal-choice-lab-kwk-students-l1-stl-061818
/meal_choice.rb
UTF-8
1,147
4.5
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Here's an example of a 'snacks' method that returns the meal choice passed in to it and defaults to "cheetos" if nothing is passed in. def snacks(food="Cheetos") "Any time, is the right time for #{food}!" end # Define breakfast, lunch and dinner methods that return the meal choice passed into them. If nothing is passed in, it shoud default to the foods on the readme (frosted flake, grilled cheese, salmon) def breakfast(breakfast="frosted flakes") puts "mmm have some #{breakfast} this fine morning" end def lunch(lunch="grilled cheese") puts "lunch time kiddo! eat some #{lunch}" end def dinner(dinner="salmon") puts "eat some #{dinner} for dinner buddy!" end # Call the methods with puts and your own arguments here. Like this: ## This returns "Any time, is the right time for Sweedish fish!" # call your methods here breakfast("pancakes") lunch("peanut butter") dinner("broccoli") # Call your methods without any arguments here breakfast lunch dinner ## In our snacks method, the default choice is "Cheetos" Calling snacks like this without specifying a choice will return "Any time, is the right time for Cheetos!"
true
1bb7af320c37c4039291897556e05c9a0ef77e29
Ruby
jjsanchezrodriguez/game_of_rooms
/spaces.rb
UTF-8
1,102
3.640625
4
[]
no_license
class Spaces def initialize(message, objects = [], triggers = []) @message = message @objects = objects @triggers = triggers @directions = [] end def add_direction(direction) @directions.push(direction) end def print_message print "Your are in a #{@message}. " @objects.each{|object| print "There is a #{object}"} puts end def trigger?(word) trigger_names = @triggers.map{|trigger| trigger.name} trigger_names.include?(word) end def direction?(word) direction_names = @directions.map{|direction| direction[:direction]} direction_names.include?(word) # binding.pry end def new_direction(coordinate) @directions.find {|space| space[:direction] == coordinate.downcase} end def handle_trigger(position) current_trigger = @triggers.find {|trigger| trigger.name == position.downcase} puts current_trigger.consequence end # def handle_move(position) # binding.pry # if position.size > 1 # @triggers.find {|trigger| trigger == position.downcase} # else # @directions.find {|space| space[:direction] == position.downcase} # end # end end
true
1fe22d2c426f08a9902ee4cd337248ced5b80f26
Ruby
littlegustv/redemption
/commands/commands_u.rb
UTF-8
552
2.859375
3
[]
no_license
require_relative 'command.rb' class CommandUnlock < Command def initialize super( name: "unlock", keywords: ["unlock"], lag: 0.25, position: :standing ) end def attempt( actor, cmd, args, input ) if ( target = actor.target( argument: args[0], list: actor.room.exits ).first ) return target.unlock( actor ) else actor.output "There is no exit in that direction." return false end end end
true
bf88f3d8078bcaed192d81456911c1be1a8373e8
Ruby
SimonGarber/ar-exercises
/exercises/exercise_1.rb
UTF-8
427
2.828125
3
[]
no_license
require_relative '../setup' puts "Exercise 1" puts "----------" t = Store.new t.name = "Burnaby" t.annual_revenue = 3000000 t.womens_apparel = true t.mens_apparel = true t.save t = Store.new t.name = "Richmond" t.annual_revenue = 1260000 t.womens_apparel = true t.mens_apparel = false t.save t = Store.new t.name = "Gastown" t.annual_revenue = 190000 t.womens_apparel = false t.mens_apparel = true t.save puts Store.count
true
b70c8b8493f833488fb54607300a966c7b949632
Ruby
annayerofeyeva/noughts-and-crosses
/spec/board_spec.rb
UTF-8
1,232
2.953125
3
[]
no_license
require './models/board' describe Board do let(:board) {Board.new} let(:cross) {double :choice, :name => "cross"} it 'should contains nine cells' do expect(board.grid.length).to eq(9) end it 'can access every cell' do expect(board.find_cell(2)).to eq(nil) end it 'can add choiced to a specific cell' do board.add_choice(2, cross) expect(board.find_cell(2)).to eq(cross) end it 'knows if there is no vertical match' do expect(board.vertical_match?).to be false end it 'knows if there is a vertical match' do board.add_choice(1, cross) board.add_choice(4, cross) board.add_choice(7, cross) expect(board.vertical_match?).to be true end it 'knows if there is no horisontal match' do expect(board.horisontal_match?).to be false end it 'knows if there is a hoisontal match' do board.add_choice(1, cross) board.add_choice(2, cross) board.add_choice(3, cross) expect(board.horisontal_match?).to be true end it 'knows if there is no diagonal match' do expect(board.diagonal_match?).to be false end it 'knows if there is a diagonal match' do board.add_choice(1, cross) board.add_choice(5, cross) board.add_choice(9, cross) expect(board.diagonal_match?).to be true end end
true
981a023bf0cc978b35c94e0b53bc02f896ddf2bf
Ruby
cogcmd/aws-cfn
/lib/cog_cmd/cfn/definition/create.rb
UTF-8
2,493
2.578125
3
[]
no_license
require 'cog_cmd/cfn/definition' require 'cfn/command' require 'cfn/branch_option' require 'cfn/definition' module CogCmd::Cfn::Definition class Create < Cfn::Command include Cfn::BranchOption DEFINITION_NAME_FORMAT = /\A[\w-]*\z/ TEMPLATE_NAME_FORMAT = /\A[-\w\/]*\z/ def run_command require_git_client! require_s3_client! require_name! require_name_format! require_branch_exists! require_template! require_template_format! require_template_exists! require_defaults_exist! definition = Cfn::Definition.create(git_client, s3_client, cfn_client, { name: name, template: template, defaults: defaults, params: params, tags: tags, branch: branch }) response.template = 'definition_show' response.content = [definition] end def require_name! unless name raise(Cog::Abort, 'Name not provided. Provide a name as the first argument.') end end def require_name_format! unless DEFINITION_NAME_FORMAT.match(name) raise(Cog::Abort, 'Name must only include word characters [a-zA-Z0-9_-].') end end def require_template! unless template raise(Cog::Abort, 'Template not provided. Provide a template as the second argument.') end end def require_template_format! unless TEMPLATE_NAME_FORMAT.match(template) raise(Cog::Abort, 'Name must only include word characters [a-zA-Z0-9_-/].') end end def require_template_exists! unless git_client.template_exists?(template, { branch: branch }) raise(Cog::Abort, "Template does not exist. Check that the template exists in the #{branch} branch and has been pushed to your repository's origin.") end end def require_defaults_exist! return if defaults.nil? defaults.each do |defaults_name| unless git_client.defaults_exists?(defaults_name, { branch: branch }) raise(Cog::Abort, "Defaults file #{defaults_name} does not exist. Check that the defaults file exists in the #{branch} branch and has been pushed to your repository's origin.") end end end def name request.args[0] end def template request.args[1] end def defaults request.options['defaults'] end def params request.options['params'] end def tags request.options['tags'] end end end
true
c72dcdf134af4485b0aee7b73ef4a75516501f3d
Ruby
francesmx/learn_to_program
/ch11-reading-and-writing/safer_picture_downloading.rb
UTF-8
1,051
3.421875
3
[]
no_license
pic_names = Dir["../*.{JPG,jpg}"] # Search in the parent directory puts "What would you like to call this batch?" batch_name = gets.chomp puts print "Downloading #{pic_names.length} files: " pic_number = 1 pic_names.each do |name| print "." new_name = if pic_number < 10 "#{batch_name}0#{pic_number}.jpg" else "#{batch_name}#{pic_number}.jpg" end if File.exist? new_name overwrite = gets.chomp "A file already exists with the name " + new_name + ". Do you want to overwrite? Type \"Yes\" or \"No\"." if overwrite.downcase == "yes" File.rename name, new_name pic_number += 1 elsif overwrite.downcase == "no" puts "Skipping " + new_name + " because it already exists." end end end puts puts "Done, cutie!" # TO DO # Add safety features to sure you never overwrite a file # File.exist? (pass it a filename and it will return true or false) # exit - kills your program right where it stands - good for spitting out an error message and then quitting # ßSolve this in English first Frances!
true
e3cdcf6f28b421dafbbde0085c79d1565f3471a9
Ruby
rb512/algorithms
/project_euler/problem6.rb
UTF-8
110
2.875
3
[]
no_license
def sum_difference(n) sum = (n*(n+1)/2) sum_of_squares = n*(n+1)*(2*n +1)/6 (sum*sum)-sum_of_squares end
true
b3c716d182492e0d1a4d69f930eaa071988b9fb1
Ruby
ozzman84/funny_2107
/lib/open_mic.rb
UTF-8
462
3.265625
3
[]
no_license
class OpenMic attr_reader :location, :date, :performers def initialize(hash) @location = hash[:location] @date = hash[:date] @performers = [] end def welcome(user) @performers << user end def repeated_jokes? all_jokes = [] @performers.each { |performer| performer.jokes.each { |joke| all_jokes << joke }} all_jokes.any? do |joke| all_jokes.count(joke) > 1 end end end
true
5e6192e9fad77254f8b57c30e0749df785c8827b
Ruby
Nejuf/Poker
/lib/Poker.rb
UTF-8
2,794
3.5625
4
[]
no_license
require_relative "Player" require_relative "Deck" require_relative "Hand" class Poker BETTING_COMMANDS = %w(fold raise call withdraw) attr_accessor :players, :deck, :pot def initialize @players = [Player.new("Sleepy", 100), Player.new("Snooky", 100), Player.new("Darwin", 100), Player.new("Snoop Lion", 100)] @deck = Deck.new @hands = {} deal_start_hands @pot = 0 @bet_amount = 0 @remaining_players = @players end def deal @players.each do |player| until player.hand.length >= 5 player.hand << @deck.draw_card end end end def play until @players.length == 1 @remaining_players = @players deal betting # choose to discard cards # deal again # betting again (keeps going until everyone checks or folds) # show down (if remaining players.length > 1) # winner, winner gets the pot # remove existing hands/discard hands, reshuffle deck end end def betting player_has_raised = true @bet_amount = 0 @remaining_players.each {|p|p.bet = 0} until !player_has_raised num_calls = 0 player_has_raised = false @remaining_players.each do |player| bet_response = player.get_bet_response if bet_response == "fold" @pot += player.bet player.take_bet @remaining_players.delete(player) elsif bet_response == "raise" smallest_wallet = @remaining_players.sort_by(&:wallet).first.wallet if player.wallet == smallest_wallet && smallest_wallet == @bet_amount puts "You cannot raise. Instead, you will call. You have bet #{@bet_amount}." player.bet = @bet_amount else begin player_has_raised = true potential_raise_amount = player.get_raise_amount(@bet_amount) if potential_raise_amount > smallest_wallet raise ArgumentError.new "You cannot bet higher than the poorest player." end @bet_amount = potential_raise_amount num_calls = 0 rescue ArgumentError => e puts "Error: #{e.message}" retry end end player.bet = @bet_amount elsif bet_response == "call" num_calls += 1 if num_calls >= @remaining_players.length-1 break end player.bet = @bet_amount elsif bet_response == "withdraw" @remaining_players.delete(player) @players.delete(player) end end end end private def deal_start_hands @players.each do |player| cards = [] 5.times {cards << @deck.draw_card} player.hand = Hand.new(cards) end end end
true
26a3c55971e6020e7609cce9b919483ac0428693
Ruby
kevinpark07/ruby-project-guidelines-nyc01-seng-ft-080320
/app/models/get_character.rb
UTF-8
292
2.703125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'net/http' require 'open-uri' require 'json' class GetCharacter URL = "https://www.potterapi.com/v1/characters?key=$2a$10$9cotrn8hm2vhEzS8mtY.dO3NJ9uobAe9MuERDSy9iR1K10b8kqvvy" def get_characters uri = URI.parse(URL) response = Net::HTTP.get_response(uri) JSON.parse(response.body) end end
true
956c81a5768f46a980fcc7caa8ae58926d4fce78
Ruby
j1wilmot/Challenges
/ProgramThis/3_circle/circle.rb
UTF-8
211
3.078125
3
[]
no_license
radius = Integer(ARGV[0]) if radius.nil? || radius < 1 abort("Need to provide a radius greater than 0") end CHAR = "#" 0.upto(radius) do |i| puts " " * (radius - i) + CHAR end radius.downto(0) do |i| end
true
f5c6d992c597a004133c8b39bca039242d8c4784
Ruby
panozzaj/conf
/common/bin/cp_with_mkdir_p
UTF-8
497
2.96875
3
[]
no_license
#!/usr/bin/ruby require 'fileutils' src, target=ARGV if target =~ /\/$/ # create the directory if it doesn't exist unless File.directory?(target) puts "Creating directory #{target}" FileUtils.mkdir_p target end else # assuming we want to copy the file to that name dirname = File.dirname(target) unless File.directory?(dirname) puts "Creating directory #{dirname}" FileUtils.mkdir_p File.dirname end end FileUtils.cp src, target, :verbose => true
true
3417e58efd3fab24d6484651c89ed66ae4910a0b
Ruby
wudip/need-not-to-speed
/lib/model/game/map/objects/stop_sign.rb
UTF-8
4,545
3.3125
3
[ "MIT" ]
permissive
require 'model/game/crashable' module NeedNotToSpeed module Game # Stop sign - object in map. Player has to stop at least # square root of "#{SQR_STOPPING_AREA_LENGTH}" from it. class StopSign # Length of area before the stop sign where car has to stop (squared to # make computation easier) SQR_STOPPING_AREA_LENGTH = 10_000 # Length from stop sign's line where car is considered 'crossing the line' # (squared to make computation easier) SQR_MIN_DIST_FROM_LINE = 2500 attr_reader :pos_x, :pos_y, :rotation # Creates new stop sign. The sign is encoded by two points and an angle. # If car is crossing the line between two specified point in the # direction opposite to car's movement direction and if it didn't stop # in close area before the sign then it's considered as collision # @param start_x [Integer] x coordinate of the first point of the line # @param start_y [Integer] y coordinate of the first point of the line # @param end_x [Integer] x coordinate of the second point of the line # @param end_y [Integer] y coordinate of the second point of the line # @param rotation [Float] facing of the sign (in radians), it should be # opposite of expected car's direction def initialize(start_x, start_y, end_x, end_y, rotation) @center_x = (start_x + end_x) / 2 @center_y = (start_y + end_y) / 2 @rotation = rotation init_line(start_x, start_y, end_x, end_y) end # Updates the stop sign (it's immutable so the method remains blank) def update; end # Checks for collision with specified object # @param object [Object] and object (probably car) to compute collision # with def collision(object) if near?(object) && passing_right_direction(object) && didnt_stop(object) x = object.pos_x.to_i y = object.pos_y.to_i @line.each do |point| dist = sql_euclidean_distance_points(x, y, point[:x], point[:y]) return { x: x, y: y } if dist < SQR_MIN_DIST_FROM_LINE end end nil end # Square euclidean distance between specified points and center of this # stop sign's line # @param x [Integer] horizontal position of specified point # @param y [Integer] vertical position of specified point def sqr_euclidean_distance(x, y) sql_euclidean_distance_points(x, y, @center_x, @center_y) end private def init_line(start_x, start_y, end_x, end_y) @line = [] repeats, step_x, step_y = get_step(start_x, start_y, end_x, end_y) x = start_x y = start_y repeats.times do @line.push(x: x.to_i, y: y.to_i) x += step_x y += step_y end end def get_step(start_x, start_y, end_x, end_y) diff_x = (start_x - end_x).abs diff_y = (start_y - end_y).abs repeats = [diff_x, diff_y].max step_x = (diff_x.to_f / repeats).to_i step_y = (diff_x.to_f / repeats).to_i [repeats, step_x, step_y] end def near?(object) dist = sqr_euclidean_distance(object.pos_x, object.pos_y) dist < SQR_STOPPING_AREA_LENGTH end # @return [Boolean] true if object is passing the stop sign's direction, # false if not def passing_right_direction(object) rotation = object.rotation rotation += Math::PI if object.speed < 0 min_boundary = @rotation - Math::PI / 2 max_boundary = @rotation + Math::PI / 2 angle_in_boundary?(rotation, min_boundary, max_boundary) end def didnt_stop(object) x, y = object.last_stop dist = sqr_euclidean_distance(x, y) dist > SQR_STOPPING_AREA_LENGTH end def normalize_angle(angle) angle -= Math::PI while angle >= 2 * Math::PI angle += Math::PI while angle < 0 angle end def angle_in_boundary?(rotation, min_boundary, max_boundary) rotation -= 2 * Math::PI while rotation > 2 * Math::PI min_boundary -= 2 * Math::PI while min_boundary > rotation max_boundary -= 2 * Math::PI while max_boundary >= min_boundary max_boundary += 2 * Math::PI max_boundary >= rotation end def sql_euclidean_distance_points(x1, y1, x2, y2) dist_x = x1 - x2 dist_y = y1 - y2 dist_x * dist_x + dist_y * dist_y end end end end
true
0185ba392d3e2dbd7ec6344522d9af4c663410f6
Ruby
ngsmrk/euler
/problem_5.rb
UTF-8
368
3.4375
3
[]
no_license
# naive slow solution!! start_time = Time.now i = 0 upper_number = 20 def divisible(number, range) range.each do | num | return false unless number % num == 0 end end while true i += upper_number puts i break if divisible(i, (1..upper_number)) end elapsed_time = Time.now - start_time puts "Elapsed time : #{elapsed_time}" puts "answer : #{i}"
true
b0931d5cee0839b59f3bddedee5da260aa5dc08e
Ruby
AkiraBrand/sorting_cards
/lib/Deck.rb
UTF-8
844
3.359375
3
[]
no_license
require 'Pry' require_relative './Card' require_relative './Guess' class Deck attr_reader :cards, :value, :suit, :deck def initialize(cards) @cards = cards @empty_array = [] end def count @cards.count end def sort values = {"4 of Hearts" => 1, "5 of Diamonds" => 2, "Jack of Clubs" => 3, "Ace of Diamonds" => 4, "Ace of Spades" => 5 } deck_length = @cards.length loop do switched = false (deck_length-1).times do |card| if values["#{@cards[card].value} of #{@cards[card].suit}"] > values["#{@cards[card +1].value} of #{@cards[card +1].suit}"] @cards[card], @cards[card +1] = @cards[card +1], @cards[card] switched = true end end break if not switched end @cards end end
true
415022404eef7ac4c870de340f8838e4c0f76208
Ruby
tamu222i/ruby01
/tech-book/5/5-9.rb
UTF-8
132
3.453125
3
[]
no_license
# 未定義メソッドの呼び出し class Bar def method_missing(name, *args) puts name end end b = Bar.new b.hoge hoge
true
10154a12a8e1ac3d2b8e52dec99f0af4aa7cf6a7
Ruby
kayeon/sea-c21-ruby
/lib/class7/exercise4.rb
UTF-8
1,701
4.6875
5
[ "MIT" ]
permissive
#!/usr/bin/env ruby # # 5 points # # Copy the previous OrangeTree class and replace the following method: # # OrangeTree#initialize(fruit = 50) # # Sets it's `@fruit` instance variable to the `fruit` parameter, which # defaults to 50. # # orange_tree = OrangeTree.new # orange_tree.fruit #=> 50 # # orange_tree = OrangeTree.new(20) # orange_tree.fruit #=> 20 # # And extend the OrangeTree class with the following method: # # OrangeTree#==(other) #=> true or false # # Given another object, returns `true` if both objects have the same amount # of `fruit`. Otherwise, returns `false`. # # OrangeTree.new(20) == OrangeTree.new(20) # OrangeTree.new(20) != OrangeTree.new(10) # rubocop:disable TrivialAccessors class OrangeTree def initialize(fruit = 50) @fruit = fruit end def pick!(amount = 1) if amount > @fruit nil else puts 'amount = ' + amount.to_s # this is for debugging puts @fruit -= amount end end def ==(other) if @fruit == other.fruit true else false end end def fruit @fruit end end orange_tree = OrangeTree.new(75) puts "quantity of fruits on the tree #{orange_tree.fruit}" orange_tree_1 = OrangeTree.new puts "quantity of fruits on the tree #{orange_tree_1.fruit}" if orange_tree == orange_tree_1 # if orange_tree.==(orange_tree_1) <-- same thing as above puts "they're equal" else puts "they're not equal" end # puts "#{OrangeTree.new(20) == OrangeTree.new(20)}" # puts "#{OrangeTree.new(20) != OrangeTree.new(10)}" # orange_tree.==(another_orange_tree) # x = 3 # y = 4 # if x == y # puts "they're equal" # else # puts "they're not equal" # end
true
fbc603d9ad2d8606b7f07854f180d509f05cffc9
Ruby
ekosz/spacedice
/spec/cup_spec.rb
UTF-8
1,072
3.328125
3
[]
no_license
require 'spec_helper' require_relative '../lib/cup' class MockDie; end describe Cup do it "can give a random dice inside it" do die = MockDie.new cup = Cup.new([die]) cup.take(1).should == [die] end it "can give all the dice inside it" do die1 = MockDie.new die2 = MockDie.new die3 = MockDie.new cup = Cup.new([die1, die2, die3]) cup.take(3).should =~ [die1, die2, die3] end it "can give a subsection of the dice inside it" do die1 = MockDie.new die2 = MockDie.new die3 = MockDie.new cup = Cup.new([die1, die2, die3], proc { |dice| dice }) cup.take(2).should == [die1, die2] end it "removes the dice from the cup" do die = MockDie.new cup = Cup.new([die]) cup.take(1) cup.should be_empty end it "is not empty in the begining" do die = MockDie.new cup = Cup.new([die]) cup.should_not be_empty end it "can have dice added to the cup" do die = MockDie.new cup = Cup.new([]) cup.should be_empty cup.add(die) cup.should_not be_empty end end
true
22b0731052c444da015f487050b2b646ac7513a2
Ruby
blogmitnik/CheckMe
/lib/tasks/import_data.rake
UTF-8
2,519
2.65625
3
[ "MIT" ]
permissive
require 'csv' require 'fileutils' desc "This task is for importing data from csv file into database" task :import_data, [:filename] => :environment do puts "Fetching csv files from local folder..." imported_files = [] imported_main_files = [] imported_mini_files = [] duplicated_files = [] filtered_csvs_from_today = [] no_row_files = [] filtered_csvs = [] check_filename_date = [] target_folder = Dir.home + '/data_csv' # Define the folder of CSV files d = Dir.new(target_folder) #Dir.chdir(d) # This will recursively find all csv files in a given directory #csvs = d.entries.select {|csv| /^.+\.csv$/.match(csv)} filtered_csvs = Dir[ File.join(d, '**', '*.csv') ].reject { |p| File.directory? p } start_time = Time.now puts "Start importing data at #{start_time}" puts '-' * 50 #Only import today's CSV files date_today = DateTime.parse(Date.today.to_s).strftime('%Y%m%d') date_yesterday = DateTime.parse((Date.today-1).to_s).strftime('%Y%m%d') filtered_csvs.select do |file| filename = File.basename(file).gsub('_', '-') # line_count = `wc -l "#{file}"`.strip.split(' ')[0].to_i - 1 # Check if csv file already existed (imported) in database if SourceFile.exists?(file_name: filename) duplicated_files << file puts filename.to_s + ' [Duplicated and ignored]' next else # Process the CSV files that we actually need BinReport.import_data(file, filename) # Check total imported row counts if file = SourceFile.find_by_file_name(filename) count = BinReport.where(source_file_id: file).count # Check if CSV row numbers equal to record numbers that imported to database if count + 1 == file.total_row imported_files << file puts filename.to_s + ' [successfully imported]' else # If row counts are not equal, rollback all the imported rows file.destroy puts 'Data lost while importing data from ' + filename.to_s end end end end puts '-' * 50 puts filtered_csvs.count.to_s + ' CSV file(s) processed, ' + duplicated_files.count.to_s + ' duplicated, ' + no_row_files.count.to_s + ' no-row file(s), and ' + (imported_files.count + imported_main_files.count + imported_mini_files.count).to_s + ' file(s) imported!' puts 'Data importing process completed at ' + Time.now.to_s end_time = Time.now puts "Total time: #{(end_time - start_time)} seconds" end
true
0dff3e93ebc6720d0d25563953250cc51db8fa55
Ruby
techtronics/monster_manual
/app/models/creature.rb
UTF-8
430
2.796875
3
[]
no_license
require "dice" class Creature < ActiveRecord::Base belongs_to :monster def bloodied? hit_points <= monster.bloodied end def take_damage!(amount) self.hit_points -= amount self.hit_points = 0 if hit_points < 0 end def incapacitated? hit_points == 0 end def get_defaults_from_monster return unless monster self.hit_points = monster.hit_points self.initiative = D20.roll(monster.initiative) end end
true
cb4300332815c812edcfe4cb8a2a5d9fb1e154a2
Ruby
geekgrl1965/Wyncode-homework
/classes2.rb
UTF-8
1,273
3.921875
4
[]
no_license
class Table @@next_table_id = 1 attr_reader :id def initialize #applied to every instance of the class @id = @@next_table_id #instance variable using class variable @@next_table_id +=1 end def change_next_id(next_id) @@next_table_id = next_id end def self.next_table_id @@next_table_id #makes variable accessible (to class only) end def self.has_legs? true #declares that all new tables will have legs end def preview_next_id #instance method @@next_table_id #class variable end end #self creates a class method. Affects the class, rather than an #instance of the class puts Table.has_legs? #capital T indicates object is a class, not an instance #therefore, we are calling a class method p Table.next_table_id # p t.next_table_id #raises an "undefined method" error because we are #calling a class method on an instance t = Table.new p t.id #returns id of 1 t2 = Table.new p t2.id #returns id of 2, because of @@next_table_id +=1 puts "The next id back at the factory is #{t2.preview_next_id}" puts t2.change_next_id 99 puts "We changed the @@next_table_id and it is now #{t2.preview_next_id}" #output: We changed the @@next_table_id and it is now 99
true
b472255a7b1cb495db45e7f96805b3ea9617c67f
Ruby
douglaskurotaki/rails-tdd
/exemplo_ruby_rspec/spec/matchers/change/chage_spec.rb
UTF-8
485
2.765625
3
[]
no_license
require 'contador' # Verifica se houve mudanca no valor describe 'Matcher change' do # Verifica se houve mudanca qualuqer it { expect{ Contador.incrementa }.to change { Contador.qtd } } # Verifica se a mudanca foi alterada para 1 valor a mais it { expect{ Contador.incrementa }.to change { Contador.qtd }.by(1) } # Verifica se a mudanca foi alterada de x valor para y valor from(x) to(y) it { expect{ Contador.incrementa }.to change { Contador.qtd }.from(2).to(3) } end
true
fbade188cedc6c6034689186239e592d9735c343
Ruby
DrFriendless/rmud
/wizards/lib/bodyutil.rb
UTF-8
2,694
3.296875
3
[]
no_license
# FIXME: items can't claim two spots of the same type, e.g. you can't have an item which is two rings. module Wearing def initialize_wearing @wear_slots = {'necklace' => [nil], 'hat' => [nil], 'ring' => [nil, nil], 'amulet' => [nil], 'righthand' => [nil], 'lefthand' => [nil], 'shoes' => [nil]} end def unwear_all @wear_slots.each_pair { |k,v| v.each_index { |i| @wear_slots[k][i] = nil if @wear_slots[k][i] } } end # can we put it on now? def space_to_wear?(slots) slots.all? { |s| @wear_slots[s]&.include?(nil) } end # can we put it on now? def wearing_in_slots(slots) result = [] slots.each { |s| if @wear_slots[s] @wear_slots[s].each { |x| if x && !result.include?(x); result.push(x) end } end } result end # do we even have the slots for this def could_wear?(slots) slots.all? { |s| @wear_slots[s] && @wear_slots[s].size > 0 } end # put it on def wear(item) slots = item.slots slots.each { |s| i = @wear_slots[s].find_index(nil); @wear_slots[s][i] = item } end # take it off def remove(item) slots = item.slots slots.each { |s| i = @wear_slots[s].find_index(item); @wear_slots[s][i] = nil } end def wearing?(obj) return false unless obj.slots obj.slots.any? { |slot| @wear_slots[slot]&.include?(obj) } end def persist_wearing(data) # TODO end def wielded_weapon @wear_slots.each_value { |items| items.each { |x| if x.is_a?(Weapon) && wearing?(x); return x; end } } nil end end module HitPoints attr_accessor :hp attr_accessor :maxhp def initialize_hp @hp = 0 @maxhp = 0 end def after_properties_set_hp if !@maxhp || @maxhp <= 0 @maxhp = 1 end if !@hp || @hp <= 0 @hp = @maxhp end end def injured? @hp < @maxhp end def damage(n) alive = @hp > 0 @hp -= n # return whether we were just killed alive && @hp <= 0 end def heal(n) if @ghost; return end if @hp < @maxhp @hp += n if @hp > @maxhp; @hp = @maxhp end if @hp == @maxhp tell("You feel better now.") end end end def persist_hit_points(data) data[:maxhp] = @maxhp data[:hp] = @hp end def restore_hit_points(data, by_persistence_key) @maxhp = data[:maxhp] @hp = data[:hp] end def dead? @hp <= 0 end def health_status if @ghost "You are a ghost. Other than that you feel OK. You should get to a holy place to get that fixed." else s = "You have #{@hp} hit points out of a maximum of #{@maxhp}." if @poison > 0 s += " You are poisoned." end s end end end
true
cda6a220b727135f068ea1bdc7cafeed874627bb
Ruby
mythographer/fuel_app
/test/models/fuel_type_test.rb
UTF-8
1,946
2.53125
3
[]
no_license
require 'test_helper' class FuelTypeTest < ActiveSupport::TestCase def setup @petrol = fuel_types :petrol end test 'responds to name_en, name_ua, abbr_name' do %i(name_en name_ua abbr_name).each do |attr| assert_respond_to @petrol, attr end end test 'should be valid' do assert @petrol.valid? end test ':name_en should be present' do @petrol.name_en = nil assert_not @petrol.valid? assert @petrol.errors.added? :name_en, :blank end test ':name_en should not be too long' do @petrol.name_en = 'a' * 11 assert_not @petrol.valid? assert @petrol.errors.added? :name_en, :too_long, count: 10 end test 'should reject duplicate :name_en' do petrol_dup = @petrol.dup petrol_dup.name_en.upcase! assert_not petrol_dup.valid? assert petrol_dup.errors.added? :name_en, :taken end test ':name_ua should be present' do @petrol.name_ua = nil assert_not @petrol.valid? assert @petrol.errors.added? :name_ua, :blank end test ':name_ua should not be too long' do @petrol.name_ua = 'a' * 11 assert_not @petrol.valid? assert @petrol.errors.added? :name_ua, :too_long, count: 10 end test 'should reject duplicate :name_ua' do petrol_dup = @petrol.dup petrol_dup.name_ua.mb_chars.upcase! assert_not petrol_dup.valid? assert petrol_dup.errors.added? :name_ua, :taken end test ':abbr_name should be present' do @petrol.abbr_name = nil assert_not @petrol.valid? assert @petrol.errors.added? :abbr_name, :blank end test ':abbr_name should not be too long' do @petrol.abbr_name = 'a' * 2 assert_not @petrol.valid? assert @petrol.errors.added? :abbr_name, :wrong_length, count: 1 end test 'should reject duplicate :abbr_name' do petrol_dup = @petrol.dup petrol_dup.abbr_name.upcase! assert_not petrol_dup.valid? assert petrol_dup.errors.added? :abbr_name, :taken end end
true
e94bacf72ec69cd38e449f19bcfd8d5a01d3a64d
Ruby
saganawski/Project-Euler
/sum_squares.rb
UTF-8
693
4.03125
4
[ "MIT" ]
permissive
# The sum of the squares of the first ten natural numbers is, # 12 + 22 + ... + 102 = 385 # The square of the sum of the first ten natural numbers is, # (1 + 2 + ... + 10)2 = 552 = 3025 # Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. # Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. def find_diff_sum_of_squares num_arry = (1..100).to_a sum_of_square = num_arry.map {|int| int * int}.reduce(:+) square_of_sum = num_arry.reduce(:+) * num_arry.reduce(:+) return square_of_sum - sum_of_square end p find_diff_sum_of_squares
true
ad204e5b0c2c91bfe39ab1a39407aa5253110cf0
Ruby
crishoj/dep_feat
/lib/conll/corpus.rb
UTF-8
1,890
3.0625
3
[]
no_license
module Conll class Corpus attr_reader :sentences, :filename def self.parse(file) Corpus.new(file) do |corpus| File.new(file).each("\n\n") do |part| lines = part.split(/\n/) corpus << Conll::Sentence.parse(lines) end end end def <<(sentence) sentence.corpus = self sentence.index = @sentences.size @sentences << sentence end def [](*args) sentences[*args] end def initialize(filename = '') @filename = filename @sentences = [] yield self if block_given? self end def evaluate(gold, categories = {}) @counts = {} for sent in @sentences gold_sent = gold.sentences[sent.index] count_sentence(:total) for tok in sent.tokens eval_token(:total, tok, gold_sent.tokens[tok.index]) end end categories.each_pair do |category, options| grep(options) do |sent| count_sentence(category) gold_sent = gold.sentences[sent.index] for tok in sent.tokens eval_token(category, tok, gold_sent.tokens[tok.index]) end end end @counts end def count_sentence(category) @counts[category] ||= Hash.new(0) @counts[category][:sentences] += 1 end def eval_token(category, token, gold_token) @counts[category] ||= Hash.new(0) @counts[category][:tokens] += 1 if token.head_correct? gold_token @counts[category][:head_correct] += 1 @counts[category][:both_correct] += 1 if token.label_correct? gold_token end end def to_s @sentences.join("\n\n") + "\n" end def grep(options = {}) for sentence in @sentences sentence.grep(options) do |tok| yield sentence break end end end end end
true
66b8fc1fc4b2933a01aa52fb7d5e3f22d43073cc
Ruby
kaineer/phonelib
/test/dummy/test/unit/phone_test.rb
UTF-8
992
2.5625
3
[ "MIT" ]
permissive
require 'test_helper' class PhoneTest < ActiveSupport::TestCase test "saves with valid phone" do phone = Phone.new(number: '972541234567') assert phone.save assert phone.errors.empty? end test "can't save with invalid phone" do phone = Phone.new(number: 'wrong') assert !phone.save assert phone.errors.any? end test "valid passes" do phone = phones(:valid_and_possible) assert phone.save assert phone.errors.empty? end test "wrong fails" do phone = phones(:wrong) assert !phone.save assert phone.errors.any? end test "allow blank passes" do phone = phones(:only_valid) assert phone.save assert phone.errors.empty? end test "without allow blank fails" do phone = phones(:only_possible) assert !phone.save assert phone.errors.any? end test "wrong possible and not blank fails" do phone = phones(:valid_with_bad_possible) assert !phone.save assert phone.errors.any? end end
true
9f3c525c7f0ef21f1a9ef6a9c842269f0bcfe5a7
Ruby
austinoso/ruby-oo-object-relationships-collaborating-objects-lab-sfo-web-012720
/lib/artist.rb
UTF-8
705
3.421875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Artist attr_accessor :name @@all = [] def initialize(name) @name = name @songs = [] @@all << self end def songs Song.all.filter { |song| song.artist == self } end def add_song(song) song.artist_name = self.name end def self.find_or_create_by_name(x) if @@all.find {|artist| artist.name == x} return @@all.find {|artist| artist.name == x} else Artist.new(x) end end def print_songs Song.all.filter do |song| if song.artist == self puts song.name end end end def self.all @@all end end
true
79c9b6f118ae011ba8c4abf6c64d21927fae1672
Ruby
CouteauFourchette/rubychess
/display.rb
UTF-8
1,125
3.328125
3
[]
no_license
require 'colorize' require_relative 'cursor' require_relative 'history' require 'byebug' class Display def initialize(board = Board.create_new_board, cursor) @board = board @cursor = cursor @history = History.instance end def render row_notation = [8,7,6,5,4,3,2,1] column_notation = ['a','b','c','d','e','f','g','h'] system('clear') print " " (0..7).each { |i| print "#{column_notation[i]} " } print " Moves" puts (0..7).each do |i| print "#{row_notation[i]} " (0..7).each do |j| e = @board[[i,j]] if @cursor.cursor_pos == [i,j] sym = !e.empty? ? "#{e.to_s.colorize(:red)} ".blink : '♢ '.colorize(:red) else sym = !e.empty? ? "#{e.to_s} " : ' ' end if @cursor.selected == [i,j] sym = !e.empty? ? "#{e.to_s.colorize(:green)} " : '♢ '.colorize(:green) end if (i % 2 == 0 && j % 2 == 0) || (i % 2 != 0 && j % 2 != 0) print sym.on_light_blue else print sym end end print " #{@history[i]}" puts end end end
true
8ba647c08d04ecd55e722d644787fbd91072a759
Ruby
SureshDamodaran/MyStuff
/Exercise_6_To_10/ex7_WithAddedComments.rb
UTF-8
737
4.4375
4
[]
no_license
puts "Mary had a little lamb." # In the below line snow is a string not a variable. puts "Its fleece was white as #{'snow'}." puts "And everywhere that Mary went." puts "." * 10 # What'd that do? It prints dot 10 times. end1 = "C" end2 = "h" end3 = "e" end4 = "e" end5 = "s" end6 = "e" end7 = "B" end8 = "u" end9 = "r" end10 = "g" end11 = "e" end12 = "r" # watch that print vs. puts on this line what's it do? print end1 + end2 + end3 + end4 + end5 + end6 # print statement will not add a new line at the end puts end7 + end8 + end9 + end10 + end11 + end12 # Double quotes will replace the variables inside it. puts " Hi #{end1}" # Single quotes will not replace the variables inside it. puts 'Hi #{end1}'
true
ab0033df55f5363d748d9885a6dd8d4262c1713b
Ruby
conceptric/stock-data-recorder
/spec/stock-data-recorder/stock_data_recorder_spec.rb
UTF-8
3,391
2.65625
3
[ "MIT" ]
permissive
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') require 'csv' describe Stock::Data::Recorder do let(:tickers) { %w(BP.L GSK.L) } use_vcr_cassette "yahoo-api-query", :record => :new_episodes describe ".new" do it "with an array of ticker symbols returns a new instance" do Stock::Data::Recorder.new(tickers).should be_instance_of Stock::Data::Recorder end it "with an empty array returns a new instance" do Stock::Data::Recorder.new([]).should be_instance_of Stock::Data::Recorder end it "without any arguments raises an Error" do expect { Stock::Data::Recorder.new() }.to raise_error ArgumentError end end describe ".get" do context "with tickers defined" do subject { Stock::Data::Recorder.new(tickers).get } it "returns a collection with an entry for each ticker" do subject.size.should eql tickers.size end it "the first entry for the first ticker" do subject.first['symbol'].should eql tickers.first end it "the last entry for the last ticker" do subject.last['symbol'].should eql tickers.last end end context "with no tickers defined" do it "returns an empty collection" do Stock::Data::Recorder.new([]).get.should be_empty end end end describe ".write_to_csv" do let(:output) { StringIO.new } before(:each) do CSV.should_receive(:open).once.and_return(output) output.should_receive(:close).once end context "with tickers defined" do let(:symbol_regex) { '([A-Za-z]+\.[A-Za-z]+)' } let(:price_regex) { '([0-9]+\.[0-9]{2})' } let(:date_regex) { '(\d{4}(-{1}\d{2}){2})' } let(:time_regex) { 'T((\d{2}:{1}){2}(\d{2}){1})Z' } let(:output_regex) { symbol_regex + "," + price_regex + "," + price_regex + "," + date_regex + time_regex } before(:each) do Stock::Data::Recorder.new(tickers).write_to_csv end it "writes output with a symbol value" do output.string.should =~ Regexp.new(symbol_regex) end it "writes output with a price value" do output.string.should =~ Regexp.new(price_regex) end it "writes output with a datetime value" do output.string.should =~ Regexp.new(date_regex) output.string.should =~ Regexp.new(time_regex) end it "writes output as comma-delimited" do output.string.should =~ Regexp.new(output_regex) end it "writes output with a single line for each ticker" do output.rewind output.readlines.size.should eql tickers.size end end context "with no tickers defined" do it "returns an writes nothing" do Stock::Data::Recorder.new([]).write_to_csv output.string.should eql "" end end end end
true
1f8ea3e4acd01db280a7f189e450cc5d6b002d83
Ruby
aramoe/exercism
/ruby/resistor-color-duo/resistor_color_duo.rb
UTF-8
226
2.875
3
[]
no_license
class ResistorColorDuo COLORS = %w( black brown red orange yellow green blue violet grey white ) def self.value(names) = names.take(2) # duo .map{|name| COLORS.index(name).to_s } .join('') .to_i end
true
1dd73a6cf8cdeeba9bf8fedf41a54df1dda6f147
Ruby
ac1714/mx_record
/lib/mx_record.rb
UTF-8
1,514
2.828125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
require 'resolv' module MXRecord # Obtain the mail exchange record for a particular domain. # # Returns an array of Resolv::DNS::Resource::IN::MX records e.g. for Google: # # [ #<Resolv::DNS::Resource::IN::MX:0x007faaac870da8 @preference=50, @exchange=#<Resolv::DNS::Name: alt4.aspmx.l.google.com.>, @ttl=347>, # #<Resolv::DNS::Resource::IN::MX:0x007faaac8769b0 @preference=20, @exchange=#<Resolv::DNS::Name: alt1.aspmx.l.google.com.>, @ttl=347>, # #<Resolv::DNS::Resource::IN::MX:0x007faaac874db8 @preference=40, @exchange=#<Resolv::DNS::Name: alt3.aspmx.l.google.com.>, @ttl=347>, # #<Resolv::DNS::Resource::IN::MX:0x007faaac87abf0 @preference=30, @exchange=#<Resolv::DNS::Name: alt2.aspmx.l.google.com.>, @ttl=347>, # #<Resolv::DNS::Resource::IN::MX:0x007faaac87f830 @preference=10, @exchange=#<Resolv::DNS::Name: aspmx.l.google.com.>, @ttl=347> ] def self.mail_servers(domain) Resolv::DNS.open do |dns| dns.getresources(domain, Resolv::DNS::Resource::IN::MX) end end # Obtain the preferred mail server based on the MX record's preference. # # Returns a String containing the mail server name e.g. aspmx.l.google.com; # returns nil if no servers are found. def self.primary_server(domain) servers = mail_servers(domain) return nil if servers.empty? primary_server = servers.first servers.each do |server| primary_server = server if server.preference < primary_server.preference end primary_server.exchange.to_s end end
true
18dcdb035a98775c2708be4a23604af4a546537d
Ruby
kargo-k/prime-ruby-seattle-web-060319
/prime.rb
UTF-8
241
3.109375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Add code here! def prime?(num) if num < 4 && num > 1 return true elsif num <= 1 return false else arr = Array(2...num) arr.each do |i| if i ** (num-1) % num == 1 return true else return false end end end end
true
2c952e731b72c5149150068bd3f46c812d1eaad3
Ruby
eliasjpr/poker_time
/lib/card.rb
UTF-8
494
3.53125
4
[]
no_license
class Card # The order of rankings and suits is VERY IMPORTANT (low to high) for ranking RANKINGS = %w(2 3 4 5 6 7 8 9 T J Q K A).freeze SUITS = %w(C D H S).freeze def self.build_deck RANKINGS.compact.inject([]) do |deck, rank| deck << SUITS.map { |s| "#{rank}#{s}" } end.flatten end attr_reader :num, :suit def initialize(num, suit) @num = num @suit = suit end def suit_rank SUITS.index(suit) end def rank RANKINGS.index(num) end end
true
9eb568f5213caaad37f448a49594029c63e3d46c
Ruby
buty4649/atcoder
/abc307/c/main.rb
UTF-8
1,118
3.3125
3
[]
no_license
# frozen_string_literal: true def parse(h) # 左上から0,0とし、最初と最後の0を削除しておく result = h.times.map { gets.chomp.reverse } # 左に詰めつつ2進数にする shift = result.map { |r| r.index('#') || h }.min result.map { |r| r[shift..].gsub('#', '1').gsub('.', '0').to_i(2) } .drop_while(&:zero?) # 縦列の最初の0を削除 .reverse.drop_while(&:zero?).reverse # 縦列の最後の0を削除 end ha, _wa = gets.split.map(&:to_i) a = parse(ha) hb, _wb = gets.split.map(&:to_i) b = parse(hb) hx, wx = gets.split.map(&:to_i) x = parse(hx) def match?(a, b, x, ia, ja, ib, jb) x.each_with_index do |xr, i| aa = (a[ia + i] || 0) << ja bb = (b[ib + i] || 0) << jb return false unless (xr ^ (aa | bb)).zero? end true end # aを縦に移動 (hx + 1).times do |ia| # bを縦に移動 (hx + 1).times do |ib| # aを横に移動 (wx + 1).times do |ja| # bを横に移動 (wx + 1).times do |jb| next unless match?(a, b, x, ia, ja, ib, jb) puts 'Yes' exit end end end end puts 'No'
true
c2c6d26738fa4ab8c5c3cdb57075ee4f4d873055
Ruby
muskarab/GenerasiGigih
/Modul_4/Session_2/integer_array_incrementer.rb
UTF-8
260
3.171875
3
[]
no_license
class IntegerArrayIncrementer def increment(input) if input == [9] return [1, 0] if input.first == 9 [input.first + 1] end else return [input.first + 1] end end end
true
059db4b38e51ec8c3bfd601b49a115bd9cedaf84
Ruby
Arithmetics/auction
/test/models/draft_test.rb
UTF-8
1,959
2.59375
3
[]
no_license
require 'test_helper' class DraftTest < ActiveSupport::TestCase setup do @draft2018 = drafts(:six) @draft2016 = drafts(:four) @player1 = players(:one) @player2 = players(:two) @user1 = users(:one) @bid1 = bids(:one) @bid2 = bids(:two) @bid3 = bids(:three) @user1 = users(:one) @user2 = users(:two) @user3 = users(:three) @auctioneer = users(:auctioneer) end test "draft needs year" do @new_draft = Draft.new( format: "OP_standard", open: false, nominated_player_id: nil ) assert_not @new_draft.valid? end test "draft needs format" do @new_draft = Draft.new( year: 2012, open: false, nominated_player_id: nil ) assert_not @new_draft.valid? end test "draft is valid" do @new_draft = Draft.new( year: 2012, format: "OP_standard", open: false, nominated_player_id: nil ) assert @new_draft.valid? end test "nominated_player returns correct player" do assert @draft2018.nominated_player == @player1 end test "nom player nil returns nil" do assert @draft2016.nominated_player == nil end test "highest bid amount is correct bid" do assert @draft2018.bids.where(:player == @player1).count == 3 assert_equal @draft2018.bids.first.amount, 3 assert_equal @draft2018.bids.second.amount, 2 assert_equal @draft2018.bids.third.amount, 1 assert_equal @draft2018.bids.where(:player == @player1).maximum('amount'), 3 end test "nominating_user is returned" do assert_equal @draft2018.nominating_user, @user1 end test "set_next_nominating_user returns a new user each time and never the auctioneer" do 5.times do last_nominated_user = @draft2018.nominating_user @draft2018.set_next_nominating_user assert_not @draft2018.nominating_user == last_nominated_user assert_not @draft2018.nominating_user == @auctioneer end end end
true
396f6cabde2228340c518a704cf1161e3a5ee2e4
Ruby
unboxed/gdata
/lib/gdata/auth/authsub.rb
UTF-8
5,847
2.546875
3
[ "Apache-2.0" ]
permissive
# Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'cgi' require 'openssl' require 'base64' module GData module Auth # This class implements AuthSub signatures for Data API requests. # It can be used with a GData::Client::GData object. class AuthSub # The URL of AuthSubRequest. REQUEST_HANDLER = 'https://www.google.com/accounts/AuthSubRequest' # The URL of AuthSubSessionToken. SESSION_HANDLER = 'https://www.google.com/accounts/AuthSubSessionToken' # The URL of AuthSubRevokeToken. REVOKE_HANDLER = 'https://www.google.com/accounts/AuthSubRevokeToken' # The URL of AuthSubInfo. INFO_HANDLER = 'https://www.google.com/accounts/AuthSubTokenInfo' # 2 ** 64, the largest 64 bit unsigned integer BIG_INT_MAX = 18446744073709551616 # AuthSub access token. attr_accessor :token # Private RSA key used to sign secure requests. attr_reader :private_key # Initialize the class with a new token. Optionally pass a private # key or custom URLs. def initialize(token, options = {}) if token.nil? raise ArgumentError, "Token cannot be nil." elsif token.class != String raise ArgumentError, "Token must be a String." end @token = token options.each do |key, value| self.send("#{key}=", value) end end # Set the private key to use with this AuthSub token. # The key can be an OpenSSL::PKey::RSA object, a string containing a # private key in PEM format, or a string specifying a path to a PEM # file that contains the private key. def private_key=(key) begin if key.nil? or key.class == OpenSSL::PKey::RSA @private_key = key elsif File.exists?(key) key_from_file = File.read(key) @private_key = OpenSSL::PKey::RSA.new(key_from_file) else @private_key = OpenSSL::PKey::RSA.new(key) end rescue raise ArgumentError, "Not a valid private key." end end # Sign a GData::Http::Request object with a valid AuthSub Authorization # header. def sign_request!(request) header = "AuthSub token=\"#{@token}\"" if @private_key time = Time.now.to_i nonce = OpenSSL::BN.rand_range(BIG_INT_MAX) method = request.method.to_s.upcase data = "#{method} #{request.url} #{time} #{nonce}" sig = @private_key.sign(OpenSSL::Digest::SHA1.new, data) sig = Base64.encode64(sig).gsub(/\n/, '') header = "#{header} sigalg=\"rsa-sha1\" data=\"#{data}\"" header = "#{header} sig=\"#{sig}\"" end request.headers['Authorization'] = header end # Upgrade the current token into a session token. def upgrade request = GData::HTTP::Request.new(SESSION_HANDLER) sign_request!(request) service = GData::HTTP::DefaultService.new response = service.make_request(request) if response.status_code != 200 raise GData::Client::AuthorizationError, "#{response.status_code} : #{response.body}" end @token = response.body[/Token=(.*)/,1] return @token end # Return some information about the current token. If the current token # is a one-time use token, this operation will use it up! def info request = GData::HTTP::Request.new(INFO_HANDLER) sign_request!(request) service = GData::HTTP::DefaultService.new response = service.make_request(request) if response.status_code != 200 raise GData::Client::AuthorizationError, "#{response.status_code} : #{response.body}" end result = {} result[:target] = response.body[/Target=(.*)/,1] result[:scope] = response.body[/Scope=(.*)/,1] result[:secure] = response.body[/Secure=(.*)/,1] return result end # Revoke the token. def revoke request = GData::HTTP::Request.new(REVOKE_HANDLER) sign_request!(request) service = GData::HTTP::DefaultService.new response = service.make_request(request) if response.status_code != 200 raise GData::Client::AuthorizationError, "#{response.status_code} : #{response.body}" end end # Return the proper URL for an AuthSub approval page with the requested # scope. next_url should be a URL that points back to your code that # will receive the token. domain is optionally a Google Apps domain. def self.get_url(next_url, scope, secure = false, session = true, domain = nil) next_url = CGI.escape(next_url) scope = CGI.escape(scope) secure = secure ? 1 : 0 session = session ? 1 : 0 body = "next=#{next_url}&scope=#{scope}&session=#{session}" + "&secure=#{secure}" if domain domain = CGI.escape(domain) body = "#{body}&hd=#{domain}" end return "#{REQUEST_HANDLER}?#{body}" end end end end
true
a1c90abdaefee627ddba6b12f5a374c489b3ecda
Ruby
Hyan18/boris-bikes-2
/lib/docking_station.rb
UTF-8
602
3.203125
3
[]
no_license
class DockingStation docking_station = DockingStation.new attr_reader :bikes DEFAULT_CAPACITY = 20 def initialize(capacity = DEFAULT_CAPACITY) @capacity = capacity @bikes = [] end def release_bike fail "no bikes available" if empty? fail "no working bikes available" if working_bikes.empty? @bikes.pop end def dock(bike) fail "no space available" if full? @bikes << bike end private def full? @bikes.size >= @capacity end def empty? @bikes.empty? end def working_bikes @bikes.select { |bike| bike.working? } end end
true
aa909542b0544b3ad8d43e79a60851bfe9411a2d
Ruby
Directrix777/yield-and-return-values-onl01-seng-ft-070620
/lib/practicing_returns.rb
UTF-8
361
3.96875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' def hello(array) i = 0 collection = [] while i < array.length collection << yield(array[i]) i += 1 end collection end #Collecting the return values of the puts statement would just give you nil, #but I'll code your broken method, since that's what the lab says to do. hello(["Tim", "Tom", "Jim"]) { |name| puts "Hi, #{name}" }
true
833baf959a08644b3b09c47e83c3fe7a2edf2e6d
Ruby
uvlad7/summer-2019
/211/1/gem_scorer.rb
UTF-8
1,017
3
3
[]
no_license
require 'yaml' require 'table_print' require_relative './gem_info.rb' class GemScorer def call(options) list = load_gemlist(options[:file]) gem_names = filter_by_name(list, options[:name]) gems_array = get_gems_info(gem_names) gems_array.sort_by!(&:popularity).reverse! gems_array = take_top(gems_array, options[:top]) tp gems_array, :name, { used_by: { display_name: 'used by' } }, { watch: { display_name: 'Watched By' } }, :star, :fork, { contrib: { display_name: 'Contributors' } }, :issues end def load_gemlist(file) YAML.load_file(file) rescue Errno::ENOENT puts 'file must exist' exit end def filter_by_name(list, name) list['gems'].find_all { |g| g.match(name) } end def take_top(arr, top = nil) top ||= arr.size begin arr.take(top) rescue ArgumentError puts 'top must be positive' exit end end def get_gems_info(names) names.map do |gem| GemInfo.new(gem).call end end end
true
3faeb8cb9e6ea3578b4765e6908dfbc92a5633e8
Ruby
stevenproctor/lsrc_bbd_training
/lib/restaurant.rb
UTF-8
550
3.515625
4
[]
no_license
class Restaurant MAXPRICE = 5 MINPRICE = 0 attr_accessor :ratings, :price, :location def initialize @ratings = [] @price = 0 end def score return 0 if ratings.empty? return ratings.inject(:+) / ratings.count end def add_rating(new_rating) ratings << new_rating end def set_location(location) @location = location end def get_location @location end def set_price(price) return if price < MINPRICE || price > MAXPRICE @price = price end def price return @price end end
true
87a82d545f6c6614753817b06b899eb4818384b7
Ruby
CerrilloMedia/mememe
/app/helpers/posts_helper.rb
UTF-8
1,111
2.53125
3
[]
no_license
module PostsHelper def randomDeletionConfirmationMessage prepost = "Post Deleted," confirmations = [ "#{prepost} your secret is safe with me.", "#{prepost} I guess you really didn't want anyone to know about this thing that happened you know when", "#{prepost} perhaps next time we should stick to posting cat photos" ] return confirmations.sample end def likers_of(post,max=3) votes = post.votes_for.up.by_type(User) user_names = [] unless votes.blank? votes.voters.each do |voter| user_names << (link_to voter.username, profile_path(voter.username), class: 'user-name') end if votes.size > max votes.size.to_s + " likes" else user_names.first(max).to_sentence(:last_word_connector => ' and ').html_safe + like_plural(votes) end end end def like_plural(votes) return ' like this' if votes.count > 1 ' likes this' end def likes_post(post) post.votes_for.up.by_type(User).voters.include?(current_user) end end
true
9c4d4a9477a8d43a8e3db12ad27ed8fa3e3c49ba
Ruby
cpsexton/ruby-enumerables-hash-practice-emoticon-translator-lab-denver-web-82619
/lib/translator.rb
UTF-8
928
3.3125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# require modules here require "yaml" require "pry" def load_library(file_path) emoticon_lib = YAML.load_file(file_path) new_hash = {} emoticon_lib.each do |emotion, symbol_array| new_hash["get_meaning"] ||= {} new_hash["get_emoticon"] ||= {} new_hash["get_meaning"][symbol_array.last] ||= emotion new_hash["get_emoticon"][symbol_array.first] ||= symbol_array.last end new_hash end def get_japanese_emoticon(file_path, emoticon) library_hash = load_library(file_path) english = emoticon if library_hash["get_emoticon"][english] != nil library_hash["get_emoticon"][english] else "Sorry, that emoticon was not found" end end def get_english_meaning(file_path, emoticon) emo_hash = load_library(file_path) japanese = emoticon if emo_hash["get_meaning"][japanese] != nil emo_hash["get_meaning"][japanese] else "Sorry, that emoticon was not found" end end
true
fdbe79554a36ac18226517e0c9b93321ee933bd4
Ruby
albertbahia/wdi_june_2014
/w03/d02/peter_pak/homework/homework_in_class/pokemon/poke_battle.rb
UTF-8
340
2.875
3
[]
no_license
require 'pry' require_relative 'lib/pokemon.rb' require_relative 'lib/trainer.rb' def fight_night(fighter1, fighter2) # map? end trainer1 = Trainer.order(random()).limit(1) trainer2 = Trainer.order(random()).limit(1) trainer1.choose_pokemon(Pokemon.get_pokemon) trainer2.choose_pokemon(Pokemon.get_pokemon) fight_night binding.pry
true
737f205981e8367f6a40e3052fd39c449b971cb7
Ruby
gitter-badger/spectro
/lib/spectro/compiler.rb
UTF-8
1,884
2.796875
3
[ "MIT" ]
permissive
require 'spectro' require 'spectro/spec/parser' require 'yaml/store' module Spectro # Spectro::Compiler is in charge of scan the projects and parse its files, # updating the Spectroi's index and dumping information about the missing # implementations (specs without an associated lambda) class Compiler include Singleton class << self extend Forwardable def_delegators :instance, :compile end # Filters the project files keeping those that make use of Spectro. # It then parses them, check for missing implementations # and creates an .spectro/undefined.yml with their specs. # # @return [Spectro::Compiler] self def compile undefined_yaml = YAML::Store.new(".spectro/undefined.yml") undefined_yaml.transaction do targets().map do |path| missing_specs = missing_specs_from_file(path) next if missing_specs.empty? undefined_yaml[path] = missing_specs end end return self end private # Parse the specs on the given file path and return those # that have not been fulfilled or need to be updated. # # @param [String] path target file path # @return [<Spectro::Spec>] collection of specs not fulfilled or out of date def missing_specs_from_file(path) Spectro::Spec::Parser.parse(path).select do |spec| index_spec = Spectro::Database.index[path] && Spectro::Database.index[path][spec.signature.name] index_spec.nil? || index_spec['spec_md5'] != spec.md5 end end # Filter project's rb files returning an Array of files # containinig specs to be parsed. # # @return [<String>] array of files to be parsed def targets return %x[ grep -Pzrl --include="*.rb" "^__END__.*\\n.*spec_for" . ].split("\n").collect do |path| path[2..-1] end end end end
true
c070ef4915a48b36981578eec5e290f070d17b67
Ruby
Suyog242/mc-lease-specials
/lib/extracters/subaru/extractor.rb
UTF-8
6,567
2.671875
3
[]
no_license
require_relative "../../../lib/extracters/base/base_extractor" require_relative "../../../lib/utils/http_get" require "pry" require "awesome_print" require 'logging' require 'logger' require 'nokogiri' require_relative "op_format.rb" class Extractor < BaseExtractor def initialize(make, zip) super(make, zip) @http_get = HttpGet.new(%w[shader shader shader squid squid shader], nil, {shuffle_prefs: true}, @logger) end def load_target_page() @target_url = @config["target_page"].gsub(/##ZIPCODE##/, "#{@zipcode}") @response = @http_get.get(@target_url, {json_res: true, curl_opts: [get_standard_headers]}) end def set_zip_code() end def extract_lease_data() lease_output_data = [] if(@response.nil? || @response.empty?) output = OpFormat.new output.zip = @zipcode #Populating instance with scraped data output.brand = "SUBARU" @logger.info "No lease data found for #{@zipcode}" lease_output_data << output return OpFormat.convert_to_json(lease_output_data,"lease_data") end @response.each_with_index{|dealer, index| next if index !=0 # taking only the first dealer dealer_id = dealer["dealer"]["id"] dealer_url = "https://www.subaru.com/services/specialoffers/models?dealerCode=" + "#{dealer_id}" @dealer_response = @http_get.get(dealer_url, {json_res: true, curl_opts: [get_standard_headers]}) @dealer_response["incentives"].each{|types| types[1].each{ |year| year[1].each{|details| next if details["type"] != "Lease" output = OpFormat.new #creating instance of OpFormat output.zip = @zipcode output.brand = "SUBARU" output.emi = details["payment"].to_s output.emi_months = details["term"].to_s output.down_payment = details["downPayment"].to_s output.offer_start_date = details["startDate"]["fullDate"].split("T").first output.offer_end_date = details["endDate"]["fullDate"].split("T").first output.security_deposit = details["securityDeposit"].to_s output.msrp = details["msrp"].to_s output.due_at_signing = details["dueAtSigning"].to_s output.title1 = "Lease Offer" output.title2 = details["title"].match(/(201.*) for/)[1] rescue nil output.offer1 = details["title"] output.offer2 = details["details"].match(/(Now.*?2018)/)[1] rescue nil output.offer3 = details["details"] output.disclaimer1 = details["disclaimer"] output.mileage_charge = output.disclaimer1.scan(/\d+\scents\/mile.*miles\/year/)[0] rescue nil output.disposition_fee = output.disclaimer1.scan(/(\$\d+)\sdisposition fee/).flatten[0] rescue nil (output.disclaimer1.include? "excludes tax")? (output.tax_registration_exclusion = "Y") : (output.tax_registration_exclusion = "N") rescue nil output.offer_type = "Lease" output.dealer_zip = @dealer_response["zipcode"] output.dealer_url = @response[0]["dealer"]["siteUrl"] output.dealer_name = @response[0]["dealer"]["name"] lease_output_data << output } } } } @logger.info "Total #{lease_output_data.size} records found for #{@zipcode}" OpFormat.convert_to_json(lease_output_data, "lease_data") #Converting array of output objects in to json format end def extract_finance_data() finance_output_data = [] if(@response.nil? || @response.empty?) output = OpFormat.new output.zip = @zipcode #Populating instance with scraped data output.brand = "SUBARU" @logger.info "No finance data found for #{@zipcode}" finance_output_data << output return OpFormat.convert_to_json(finance_output_data,"finance_data") end @dealer_response["incentives"].each{|types| types[1].each{ |year| year[1].each{|details| next if details["type"] == "Lease" output = OpFormat.new #creating instance of OpFormat output.zip = @zipcode output.brand = "SUBARU" output.emi_months = details["details"].scan(/Financing for \d+ months/)[0].gsub(/Financing for | months/,'') rescue nil output.offer_start_date = details["startDate"]["fullDate"].split("T").first output.offer_end_date = details["endDate"]["fullDate"].split("T").first details["type"] == "LowRate"? output.offer_type="Finance" : output.offer_type="Other" output.title1 = output.offer_type + " Offer" output.title2 = details["title"].scan(/201.*/)[0].gsub(" Models",'') rescue nil output.offer1 = details["title"] output.offer2 = details["details"].match(/(Now.*?2018)/)[1] rescue nil output.offer3 = details["details"] output.disclaimer1 = details["disclaimer"] output.apr_rate = output.offer1.scan(/\d+%\sAPR|\d+.\d+%\sAPR/)[0].sub(" APR","") rescue nil output.dealer_zip = @dealer_response["zipcode"] output.dealer_url = @response[0]["dealer"]["siteUrl"] output.dealer_name = @response[0]["dealer"]["name"] finance_output_data << output } } } other_offers_url = "https://www.subaru.com/special-offers/index.html" other_offers_response = @http_get.get(other_offers_url, {json_res: false, curl_opts: [other_offer_headers]}) other_response = Nokogiri::HTML(other_offers_response) other_offers = other_response.xpath("//div[@class='specialprograms parsys']/div[@class='specialprograms parbase section']") other_offers.each{|offer| output = OpFormat.new #creating instance of OpFormat output.zip = @zipcode output.brand = "SUBARU" output.offer_type = "Other" output.title1 = offer.xpath(".//div[@class='offer_details']/p[@class='full_title']").text output.disclaimer1 = offer.xpath(".//div[@class='offer_details']/p[@class='full_title']/following-sibling::p").text finance_output_data << output } @logger.info "Total #{finance_output_data.size} records found for #{@zipcode}" OpFormat.convert_to_json(finance_output_data, "finance_data") #Converting array of output objects in to json format end def get_standard_headers @config["headers"].join(" ") end def other_offer_headers @config["other_offers"].join(" ") end end
true
f92627c6b20203e3876523abfe50b944732aafbb
Ruby
jacobswartzentruber/project_euler
/problem_30.rb
UTF-8
939
4.34375
4
[]
no_license
#Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: #1634 = 14 + 64 + 34 + 44 #8208 = 84 + 24 + 04 + 84 #9474 = 94 + 44 + 74 + 44 #As 1 = 14 is not a sum it is not included. #The sum of these numbers is 1634 + 8208 + 9474 = 19316. #Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. def digit_pow # Need x digits where x*9^5 has same number of digits # 6*9^5 = 354294 has six digits so we should be good with 6 sum = 0 (2..355000).each do |n| sum_powers = 0 number = n # Sum each digit in number raised to the power of 5 until number == 0 number%10 == number ? sum_powers += number**5 : sum_powers += (number%10)**5 number /= 10 end # If sum of the powers is equal to the number, add to the final tally sum += sum_powers if sum_powers == n end puts sum end digit_pow # Returns 443839
true
00159143282e744fc32686b5c87060e29a42d6f6
Ruby
hby910830/Full-Stack
/Ruby面向对象/include.rb
UTF-8
396
3.21875
3
[]
no_license
module Module1 def my_method 'M1#my_method()' end end class Class1 include Module1 # 相当于 C1 < M1,但是不能继承一个模块,只能继承一个类 end class Class2 < Class1; end # [Class2, Class1, Module1, Object, Kernel, BasicObject] p Class2.ancestors # 出现 Kernel 是因为 Object include 了 Kernel,比如 print 就定义在 Kernel 里 # 接下来看 prepend.rb
true
00e9f15a9b005ad67172cde33c7b8fdb04352496
Ruby
strayllama/music_library__SQL_LAB_14thFeb
/models/album.rb
UTF-8
1,452
3.265625
3
[]
no_license
require_relative('../db/sql_runner.rb') class Album attr_accessor :genre, :title attr_reader :id, :artist_id def initialize(options) @genre = options['genre'] @title = options['title'] @id = options['id'].to_i if options['id'] @artist_id = options['artist_id'].to_i end def save() sql = "INSERT INTO albums( genre, title, artist_id) VALUES( $1, $2, $3) RETURNING *;" values = [@genre, @title, @artist_id] result = SqlRunner.run(sql, values) @id = result[0]['id'].to_i end # end SAVE def artist() sql = "SELECT * FROM artists WHERE id = $1;" result = SqlRunner.run(sql, [@artist_id]) return Artist.new(result[0]) end def update() sql = "UPDATE albums SET (genre, title) = ($1, $2) WHERE id = $3 ;" values = [@genre, @title, @id] SqlRunner.run(sql, values) end def delete() sql = "DELETE FROM albums WHERE id = $1" SqlRunner.run(sql, [@id]) end # CLASS METHODS def Album.find(an_id) sql = "SELECT * FROM albums WHERE id = $1;" result = SqlRunner.run(sql, [an_id]) found_album = Album.new(result[0]) return found_album end def Album.list_all sql = "SELECT * FROM albums;" albums = SqlRunner.run(sql) return albums.map { |album_hash| Album.new(album_hash)} end def Album.delete_all() sql = "DELETE FROM albums" SqlRunner.run(sql) end # end DELETE_ALL end # end CLASS ALBUM
true
1619c78bbee50ab7207d4148038378388ecbbc89
Ruby
Engoh4/rubyWork
/loop_iterators/conditional_loop.rb
UTF-8
62
2.8125
3
[]
no_license
i=0 loop do puts i if i==10 break end i+=1 end
true
79348d125176e0bc27f5f8344a95240e5f220f62
Ruby
kamnnm/todobot
/lib/todobot/commands.rb
UTF-8
1,704
2.546875
3
[ "MIT" ]
permissive
require 'todobot/services/commands/help_command_service' require 'todobot/services/commands/start_command_service' require 'todobot/services/tasks/create_task_service' require 'todobot/services/lists/create_list_service' require 'todobot/services/lists/show_list_service' require 'todobot/services/lists/show_lists_service' module TodoBot module Commands COMMANDS = { ['/start'] => { class: TodoBot::Commands::StartCommandService, args: ->(args, text) { args }, options: ->(args, text) { {} } }, ['/help'] => { class: TodoBot::Commands::HelpCommandService, args: ->(args, text) { args }, options: ->(args, text) { {} } }, ['/create', '/newlist'] => { class: TodoBot::Lists::CreateListService, args: ->(args, text) { args.merge!(name: text) }, options: ->(args, text) { {force_reply: text.nil? && args.fetch(:chat).type != 'private'} } }, ['/todo', '/task', '/t'] => { class: TodoBot::Tasks::CreateTaskService, args: ->(args, text) { args.merge!(name: text) }, options: ->(args, text) { {force_reply: text.nil? && args.fetch(:chat).type != 'private'} } }, ['/list', '/l'] => { class: TodoBot::Lists::ShowListService, args: ->(args, text) { args }, options: ->(args, text) { {} } }, ['/lists', '/ls'] => { class: TodoBot::Lists::ShowListsService, args: ->(args, text) { args }, options: ->(args, text) { {} } } }.freeze private_constant :COMMANDS private def defined_command?(command) COMMANDS.keys.any? { |key| key.include?(command) } end end end
true
35b5609645d1a01cc2f138ce64ae5cd15aa10778
Ruby
GL2-G4/SlitherLink
/Noyau/GestionTechniques/Techniques/2Cases/TroisAvecTroisDiag.rb
UTF-8
4,724
2.734375
3
[]
no_license
## # File: TroisAvecTroisDiag.rb # Project: 2Cases # File Created: Wednesday, 18th March 2020 1:48:16 pm # Author: <CPietJa>Galbrun T. # ----- # Last Modified: Thursday, 26th March 2020 4:05:01 pm # Modified By: <CPietJa>Galbrun T. # path = File.expand_path(File.dirname(__FILE__)) require path + "/../../Technique" require path + "/../../../Case" require path + "/../../Zone" =begin Technique qui lorsqu'un 3 à un 3 diagonale en tire des conséquences. Voir à https://www.conceptispuzzles.com/index.aspx?uri=puzzle/slitherlink/techniques : -> Starting Techniques - 5. Two diagonal 3's Ex: . . . . . . . . . . x . . . . . . . . = . x . 3 3 = . . . . . => . . . . . 3 = 3 . . . . . . x . = . . . x . . . . . . . . . . =end class TroisAvecTroisDiag < Technique def initialize () super("T3A3D") end def chercher(plateau) super() tl, tc = getTailleLigne(plateau), getTailleColonne(plateau) 0.upto(tl-1) do |j| 0.upto(tc-1) do |i| c = plateau[i][j] if (c.nbLigneDevantEtrePleine == 3) dir = checkTrois(plateau,i,j) check = false case dir when :HAUTGAUCHE check = checkCase(plateau,i,j,dir) when :HAUTDROITE check = checkCase(plateau,i,j,dir) when :BASDROITE check = checkCase(plateau,i+1,j+1,:HAUTGAUCHE) when :BASGAUCHE check = checkCase(plateau,i-1,j+1,:HAUTDROITE) end if(dir != nil && check) return true end @zone = nil end end end return false end # Renvoie la 1ère case voisine(HAUTGAUCHE | BASGAUCHE | HAUTDROITE # | BASDROITE) contenant un 3. def checkTrois(plateau,x,y) c = getCase(plateau,x,y,:HAUTGAUCHE) if(c != nil && c.nbLigneDevantEtrePleine == 3) return :HAUTGAUCHE end c = getCase(plateau,x,y,:BASGAUCHE) if(c != nil && c.nbLigneDevantEtrePleine == 3) return :BASGAUCHE end c = getCase(plateau,x,y,:HAUTDROITE) if(c != nil && c.nbLigneDevantEtrePleine == 3) return :HAUTDROITE end c = getCase(plateau,x,y,:BASDROITE) if(c != nil && c.nbLigneDevantEtrePleine == 3) return :BASDROITE end return nil end # Récupère les lignes s'il y en a à prendre, et renvoie # vrai si on en a récupèré. def checkCase(plateau,x,y,direction) #print x, ",", y, " : ", direction, "\n" c = plateau[x][y] case direction when :HAUTGAUCHE verifAddLigne(c.getLigne(:DROITE),:PLEINE) verifAddLigne(c.getLigne(:BAS),:PLEINE) cV = getCase(plateau,x,y,:HAUTGAUCHE) if(cV != nil) verifAddLigne(cV.getLigne(:HAUT),:PLEINE) verifAddLigne(cV.getLigne(:GAUCHE),:PLEINE) end cV = getCase(plateau,x,y,:BASDROITE) if(cV != nil) verifAddLigne(cV.getLigne(:HAUT),:BLOQUE) verifAddLigne(cV.getLigne(:GAUCHE),:BLOQUE) end cV = getCase(plateau,x-2,y-1,:HAUT) if(cV != nil) verifAddLigne(cV.getLigne(:BAS),:BLOQUE) verifAddLigne(cV.getLigne(:DROITE),:BLOQUE) end @zone = Zone.new(x-2,y-2,x+1,y+1) when :HAUTDROITE verifAddLigne(c.getLigne(:GAUCHE),:PLEINE) verifAddLigne(c.getLigne(:BAS),:PLEINE) cV = getCase(plateau,x,y,:HAUTDROITE) if(cV != nil) verifAddLigne(cV.getLigne(:HAUT),:PLEINE) verifAddLigne(cV.getLigne(:DROITE),:PLEINE) end cV = getCase(plateau,x,y,:BASGAUCHE) if(cV != nil) verifAddLigne(cV.getLigne(:HAUT),:BLOQUE) verifAddLigne(cV.getLigne(:DROITE),:BLOQUE) end cV = getCase(plateau,x+2,y-1,:HAUT) if(cV != nil) verifAddLigne(cV.getLigne(:BAS),:BLOQUE) verifAddLigne(cV.getLigne(:GAUCHE),:BLOQUE) end @zone = Zone.new(x-1,y-2,x+2,y+1) end return !@lignesAModif.empty?() end end
true
f55ff561e87bf7a8030909845016f610eda80ecf
Ruby
ScottyP90/Homework_week_1_day_5
/pet_shop.rb
UTF-8
1,489
3.375
3
[]
no_license
def pet_shop_name (name) return name [:name] end def total_cash (sum) return sum [:admin][:total_cash] end def add_or_remove_cash (shop, cash) return shop [:admin][:total_cash] += cash end def pets_sold (sold) return sold [:admin][:pets_sold] end def increase_pets_sold (sold, amount) return sold [:admin][:pets_sold] += amount end def stock_count (count) return count [:pets].count end def pets_by_breed (shop, breed) breed_of_pet = [] for pets in shop[:pets] if pets[:breed] == breed breed_of_pet.push(pets) end end return breed_of_pet end def find_pet_by_name(pet_type,name) for pet in pet_type[:pets] if pet[:name] == name return pet end end return nil end def remove_pet_by_name(pet_shop,names) for pet in pet_shop[:pets] if pet[:name] == names pet_shop[:pets].delete(pet) end end end def add_pet_to_stock(pet_shop, new_pet) pet_shop[:pets] << new_pet return pet_shop.count end def customer_cash (customer) return customer[:cash] end def remove_customer_cash (customer, amount) return customer[:cash] -= amount end def customer_pet_count (customer) return customer[:pets].count end def add_pet_to_customer (customer, pet) return customer[:pets] << pet end def customer_can_afford_pet(customer_money,price_pet) while (customer_money != price_pet) if (customer_money[:cash].to_i >= price_pet[:price].to_i) return true else return false end end end
true
fe0c98f0e3be658a54cb0f5678dc5a4dd1c4e97d
Ruby
MarceloWis/Algoritmos-e-Estruturas-de-Dados
/Ruby/ExponenciacaoRecursiva.rb
UTF-8
198
3.65625
4
[ "MIT" ]
permissive
def exponenciacao(base, expoente) if expoente == 0 return 1 else return base * exponenciacao(base, expoente-1) end end puts exponenciacao(5, 2) puts exponenciacao(5, 5)
true
0c000908a5eb358ede73d8001e86acd876d2003d
Ruby
simonista/ruby_synth
/bin/freq
UTF-8
713
3.25
3
[]
no_license
#!/usr/bin/env ruby require 'ruby_synth' require 'io/console' puts "starting" stream = RubySynth::AudioStream.new s1 = RubySynth::Sine.new stream.load(s1) FREQ_INC = 1.05946309 # ~ 12th root of two counter = 0 start = Time.now.to_i STDIN.raw do |i| loop do begin c = i.read_nonblock(1) s1.frequency *= FREQ_INC if c == 'u' s1.frequency /= FREQ_INC if c == 'd' exit(0) if c == 'q' exit(1) if c == "\u0003" rescue Errno::EINTR rescue Errno::EAGAIN rescue EOFError exit(0) end if counter % 100 == 0 print "\r\033[Kiterations / second: #{(counter.to_f / (Time.now.to_i - start)).round(1)}" end counter += 1 sleep 0.001 end end
true
a4c8fd4d906bbe450e977374fb7bd90e8e043982
Ruby
Lukatastic/ics_bc_w18
/week4/recursion_practice/factorial.rb
UTF-8
316
3.96875
4
[]
no_license
# For this exercise we will not provide any skeleton code (other than the method declaration). # See if you can figure out how to write the method! def factorial(n) if n == 0 || n == 1 return 1 else return n*factorial(n-1) end end #puts(factorial(3)) # expected: 6 #puts(factorial(10)) # expected: 3628800
true
c0a0ff8afbf0d7298362d0659bf36b158c6c7edc
Ruby
mflm30/moodle-tcc
/app/services/sync_tcc.rb
UTF-8
3,473
2.671875
3
[ "MIT" ]
permissive
# app/services/sync_tcc.rb class SyncTcc def initialize(context) @tcc_definition = context @errors = {} @remote_service = MoodleAPI::MoodleUser.new end def call students = get_students unless students.nil? students.with_progress "Sincronizando #{students.size} TCCs para #{@tcc_definition.internal_name}" do |student| synchronize_tcc(student) end end end def display_errors! unless @errors.empty? rows = [] rows << %w(type, attributes, errors) @errors.each do |type, (error_data)| rows << [type, error_data[:context], error_data[:message]] end puts Terminal::Table.new rows: rows end end def find_or_create_person(moodle_id) raise ArgumentError, 'É necessário passar um moodle_id' if moodle_id.nil? person = Person.find_or_initialize_by(moodle_id: moodle_id) # sempre atualiza os dados da pessoa attributes = @remote_service.find_users_by_field('id', moodle_id) if !@remote_service.success? register_error(:person, moodle_id, @remote_service.error_message) return nil elsif attributes.nil? # pessoa não encontrada no Moodle register_error(:person, moodle_id, 'pessoa não encontrada no Moodle') return nil end person.attributes = {moodle_username: attributes.username, email: attributes.email, name: attributes.name} unless person.valid? && person.save register_error(:person, person.attributes, person.error.messages) return nil end person end private def synchronize_tcc(student) tcc = Tcc.find_or_initialize_by(student: student) tcc.tcc_definition = @tcc_definition tutor = get_tutor(student.moodle_id) tcc.tutor = tutor orientador = get_orientador(student.moodle_id) tcc.orientador = orientador tcc.save! if tcc.changed? || !tcc.persisted? end def get_students students = @remote_service.get_students_by_course(@tcc_definition.course_id) unless @remote_service.success? register_error(:course, @tcc_definition.course_id, @remote_service.error_message) return nil end students.with_progress("Sincronizando #{students.size} estudantes do curso '#{@tcc_definition.course_id}'").collect do |student_id| find_or_create_person(student_id) end end def get_tutor(student) tutor_id = @remote_service.find_tutor_by_studentid(student, @tcc_definition.course_id) if !@remote_service.success? register_error(:tutor, student, @remote_service.error_message) return nil elsif tutor_id.nil? # estudante sem tutor atribuído register_error(:tutor, student, 'tutor não definido para este estudante') return nil end find_or_create_person(tutor_id) end def get_orientador(student) orientador_id = @remote_service.find_orientador_responsavel(student, @tcc_definition.course_id) if !@remote_service.success? register_error(:orientador, student, @remote_service.error_message) return nil elsif orientador_id.nil? # estudante sem orientador atribuído register_error(:orientador, student, 'orientador não definido para este estudante') return nil end find_or_create_person(orientador_id) end def register_error(type, context, error_message=nil) type = type.to_sym @errors[type] = [] unless @errors.has_key? type @errors[type] << {context: context, message: error_message} end end
true
a8a81d7217252db09879cef3048916d9ee6e7804
Ruby
paulfioravanti/three_little_pigs
/test/lib/chapters/chapter_14_wolf_attacks_straw_house_test.rb
UTF-8
1,151
2.890625
3
[ "CC-BY-4.0", "MIT" ]
permissive
# frozen_string_literal: true require "test_helper" module ThreeLittlePigs module Chapters class Chapter14WolfAttacksStrawHouseTest < Minitest::Test attr_reader :story, :wolf, :first_pig, :second_pig def setup suppress_output do @story = Story.until_chapter(Chapter14WolfAttacksStrawHouse) @first_pig = story.first_pig @second_pig = story.second_pig Chapter14WolfAttacksStrawHouse.tell(story) end end def test_wolf_huffed_and_puffed_and_blew_the_straw_house_down # NOTE: Couldn't figure out how to do the mocking in Minitest # for huff and puff due to getting `nil` values for the straw house. # There doesn't seem to be a way of doing a `.and_call_original` # where the value that gets mocked has a chance of becoming `nil`. assert_nil(first_pig.house) end def test_the_first_little_pig_ran_to_his_brothers_house_of_sticks stick_house = second_pig.house assert_includes(stick_house.occupants, first_pig) assert_includes(stick_house.occupants, second_pig) end end end end
true
b146c39647833607c715b3926e381a2c3e0baf42
Ruby
vasileios-samarinas/week02_sports_team_student_classes_homework
/sports_team.rb
UTF-8
632
3.5625
4
[]
no_license
class Team attr_accessor :team,:players,:coach,:points def initialize(team,players,coach,points) @team=team @players=players @coach=coach @points=points end def team return @team end def players return @players end def coach return @coach end def add_new_player(footballer) return players.push(footballer) end def check_player_in_array(name) for player in players if player == name return true end end end def check_points(score) if score == "win" @points += 3 end if score == "loss" @points = 0 end end end
true
29a311981118096226389a7ab04591a5f47a6cd2
Ruby
prashu47/Euler_project
/largest_prime_factor.rb
UTF-8
756
3.84375
4
[]
no_license
# frozen_string_literal: true # The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143 ? #--------------------------------------------------------------------------------# def largest_prime_factor(num) primefactor = 2 while primefactor < num if num % primefactor == 0 num = num/primefactor primefactor = 2 else primefactor = primefactor + 1 end end primefactor end puts largest_prime_factor(600_851_475_143) ########################## # def largest_prime_factor(num): # i = 2 # while i * i < num: # while num % i == 0: # num = num / i # i = i + 1 # return num # end # # puts largest_prime_factor(600_851_475_143)
true
007b7cd91cc6c7ac391479fc21e3af5ec2d6cd6d
Ruby
navi-mann/Programming-Fundamentals-Collections-and-Iteration
/excercise.rb
UTF-8
3,753
2.734375
3
[]
no_license
fav_colours = ["pink","purple","yellow","orange"] age = [29,27,36,28] coin_flip = ["tails","tails","tails","heads","heads"] performing_artists = ["Beyonce", "Kanye", "Adele"] fav_colours2 = [:pink,:purple,:yellow,:orange] dictonary = {cunt:"a woman's genitals.",fleek: "To shit on ones education and pull shit out of their ass and call them words.",side_bitch:"A woman that is one level above a jump off but always a step below the wife" } movie_info = { pulp_fiction:"1994",aladdin:"1992",mission_impossible:"1996"} population = {London:8.7, Toronto:2.8, Bombay: 20.7} family = {aman:36,kavita:24,preeti:28,omeet:21} # # puts coin_flip # puts # puts fav_colours[0] # puts # puts "#{age.sort}" # puts # age << "0" # puts age # puts # puts "#{movie_info[:aladdin]}" # # puts fav_colours[-1] # # population[:new_york] = 8.5 # puts population # # puts coin_flip.reverse # # performing_artists.each do |performing_artists| # puts "I think #{performing_artists} is great!" # end # puts performing_artists[0..1] # # movie_info.each do |movie_info, date| # puts "#{movie_info} came out in #{date}" # end # # family_reverse = p family.sort_by {|name, age| age } # # p family_reverse.reverse # # movie_info[:Beauty_and_the_Beast] = ["1991", "2017"] # # puts movie_info # family.each do |name,age| # p "#{name if age < 30}" # end # # family.each { |name,age| # puts name if age == family.values.max # } # # puts coin_flip.count("heads") # # performing_artists.delete("Adele") # # puts performing_artists # # population[:Toronto] = 50 # # puts population # puts population.values.reduce(:+) # # family.each { |name,age| # puts "#{name} is old" if age == family.values.max # puts "#{name} is young" if age == family.values.min # } # # puts fav_colours[-2..-1] # # family.each { |name,age| # family[name] += 1 # } # p family # # fav_colours.insert(4, "black","red") # # p fav_colours # # movie_list = { # 1999 => ["The Matrix","Star Wars:Episode 1","The Mummy"], # 2009 => ["Avatar","Star Trek","District 9"], # 2019 => ["How to Train Your Dragon 3","Toy Story 4","Star Wars:Episode 9"] # } # phone = [ # [1,2,3], # [4,5,6], # [7,8,9], # ["*",0,"#"] # ] # # countries = [ # { # name: "New Zealand", # continent: "Australia", # is_island: true # }, # { # name: "Canada", # continent: "North America", # is_island: false # }, # { # name: "India", # continent: "Asia", # is_island: false # } # ] # # # 20.times do # puts "I will not skateboard in the halls." # end # # str = "I will not skateboard in the halls" # a = [] # # 20.times { a << str} # puts a # # new_list=*(1..50) # p new_list # # new_list.each { |num| # num += 1 # puts num # } # # new_list3=*(1..50) # new_list3 = new_list3 * 3 # p new_list3.sort # # countries_not_island = ["India", "Canada"] # p countries_not_island # # countries_not_island_og = countries.select do |country| # # country[:is_island] == false # # end # puts countries_not_island_og # list_exp = [250, 7.95, 30.95, 16.50] # list_exp1 = [2, 3.5, 2.6, 5 , 6.8 ] # # def list_expenses(expenses) # sum = 0 # expenses.each {|num| # sum += num # } # return sum # end # # puts list_expenses(list_exp) # puts list_expenses(list_exp1) grocery_list = ["carrots","toilet paper", "apples", "salmon"] def print_list(food_list) food_list.each do |name| puts "*" + name end end grocery_list << "rice" print_list(grocery_list) puts grocery_list.length puts grocery_list.include?("bananas") if grocery_list.include?("bananas") puts "You don't need to pick up bananas" else puts "you need to pick up bananas." end puts grocery_list[1] print_list(grocery_list.sort) p "-------" grocery_list.delete "salmon" print_list(grocery_list)
true
6f9dece0e512d5e542e091a0e827e86c9c166a07
Ruby
MaleehaBhuiyan/Rails-Practice-Code-Challenge-Travelatr-nyc01-seng-ft-060120
/app/models/blogger.rb
UTF-8
558
2.78125
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class Blogger < ApplicationRecord has_many :posts has_many :destinations, through: :posts validates :name, :presence => true validates :name, :uniqueness => true validates :age, numericality: { greater_than: 0 } validates :bio, :length => { :minimum => 31} # total likes def total_likes numbers_arr = self.posts.map do |post| post.likes end numbers_arr.inject(0) {|sum,x| sum + x} end def most_liked self.posts.max_by do |post| post.likes end end end
true
0ec8606162caa8803bbe245ec9502e3825d05739
Ruby
Marissab13/phase-0-tracks
/ruby/secret_agents.rb
UTF-8
683
4.0625
4
[]
no_license
puts "Would you like to encrypt or decrypt a password today?" crypt = gets.chomp puts "Enter a password" password = gets.chomp def encryption(str) index = 0 while index < str.length str[index] = str[index].next! index += 1 return str end end def decryption(str) index = 0 decode = "&" reference = "abcdefghijklmnopqrstuvwxyz" while index < str.length pw = str[index] ref = reference.index(pw) ref -= 1 val = reference[ref] decode = decode + val index += 1 end decode.delete! "&" return decode end if crypt == "encrypt" puts encryption(password) elsif crypt == "decrypt" puts decryption(password) else puts "I'm sorry, try again" end
true
f5ce8d66daade2d9c38f4aed4ea3a821a2b0b733
Ruby
BedfordWest/megdumarra
/systems/physics/collisions/collisions.rb
UTF-8
231
2.6875
3
[ "Apache-2.0" ]
permissive
module Collisions def check_collisions(world) world.bodies.combination(2).each { |body1, body2| if (body1.collides body2) world.add_contact(body1, body2) end } end end
true
c1c927ca299e3185e3082c5d0486bb6ba9b1a112
Ruby
MJWangler/RB101-109
/RB 101 Small Programs/lesson_3/practice_medium_1/one.rb
UTF-8
204
3.03125
3
[]
no_license
#Write a one-line program that creates "The Flintstones Rock!" output 10 times, with each subsequence indented 1 space to the right 10.times { |number| puts (" " * number)} + "The Flintstones Rock!" }
true
61d0f49dff222880a3d059b2e769606b5d8aa20f
Ruby
anmolk18/ruby-oo-relationships-practice-gym-membership-exercise-yale-web-yss-052520
/lib/gym.rb
UTF-8
466
3.15625
3
[]
no_license
class Gym attr_reader :name @@all = [] def initialize(name) @name = name @@all << self end def self.all @@all end def memberships Membership.all.select{|membership| membership.gym == self} end def lifters memberships.map{|membership| membership.lifter}.uniq end def lifters_names lifters.map{|lifter| lifter.name} end def lift_total_all lifters.collect{|lifter| lifter.lift_total}.sum end end
true
cbc3f4d6240c51b8729788fa213c9eb1c43246b4
Ruby
agraniero/crud-with-validations-lab-online-web-ft-112618
/app/models/song.rb
UTF-8
1,008
2.859375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Song < ActiveRecord::Base validates :title, presence: true validates :artist_name, presence: true validate :invalid_release_year_if_released_true validate :release_year_included? validate :invalid_if_artist_releases_song_same_year def invalid_release_year_if_released_true if released == true && release_year.blank? errors.add(:release_year, "release year must be present if Song is released") end end def release_year_included? if Array(1..Time.new.year.to_i).include?(release_year) true elsif release_year.nil? true else errors.add(:release_year, "release year can't be in the future") end end def invalid_if_artist_releases_song_same_year Song.all.each { |song| if song.title == title && song.release_year == release_year errors.add(:title, "title of song already released this year") end } end end
true
16e2a7b97864f2aa7fa41708eea03403b25a7262
Ruby
Big-Theta/EulerProblems
/cameron/p082/p82.rb
UTF-8
726
2.953125
3
[]
no_license
require "faceted.rb" def problem82 m, m_dim = gimme_matrix prev_col = [] (0..m_dim[1]).each do |y| prev_col[y] = m[[0, y]] end (1..m_dim[0]).each do |x| curr_col = [] (0..m_dim[1]).each do |y| curr_col.push(m[[x, y]]) end prev_col = min_vertical(prev_col, curr_col) end prev_col.min end def min_vertical(prev_col, curr_col) dim = prev_col.size - 1 down = [] answer = [] down[0] = prev_col[0] + curr_col[0] (1..dim).each do |y| down[y] = curr_col[y] + [prev_col[y], down[y - 1]].min end answer[dim] = prev_col[dim] + curr_col[dim] (1..dim).each do |y| y = dim - y answer[y] = [curr_col[y] + [prev_col[y], answer[y + 1]].min, down[y]].min end answer end
true
cb00e7a7b628d7793e0b7bf60e86f86430a3d238
Ruby
jss530/my-collect-v-000
/lib/my_collect.rb
UTF-8
213
3.09375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def my_collect(collection) if collection.length > 0 i = 0 any_collection = [] while i < collection.length any_collection << yield(collection[i]) i = i + 1 end any_collection end end
true
3cdc29553b953c7fde533a5bf3426fad91c5adfc
Ruby
varindersingh/wiziq-instructure-canvas-plugin
/lib/wiziq/crypto_helper.rb
UTF-8
329
2.703125
3
[ "MIT" ]
permissive
module Wiziq class CryptoHelper attr_reader :signature_base def initialize @signature_base = "" end def add_param(key,value) @signature_base += "&" if !@signature_base.empty? @signature_base << key << "=" << value.to_s if !key.nil? && !value.nil? @signature_base end end end
true