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
c4784558ccd70281ec1670aa460a472a36741f85
Ruby
fursich/hack_assembler
/lib/driver.rb
UTF-8
2,845
2.625
3
[]
no_license
# usage # load 'assembler.rb' # assembler = Assembler::Driver.new('add/Add.asm') # assembler.run require 'forwardable' require_relative 'parser/strategy.rb' require_relative 'utils/fileio.rb' require_relative 'linker/linker.rb' require_relative 'assembler/code.rb' require_relative 'assembler/visitors.rb' require_relative 'parser/commands.rb' require_relative 'parser/command.rb' require_relative 'parser/symbol.rb' require_relative 'parser/expression.rb' module Assembler class Driver attr_reader :source, :commands, :symbols def initialize(filename) @filename = Pathname.new(filename) raise FileError, 'illegal file type' if @filename.extname != '.asm' @output_filename = @filename.sub_ext('.hack') @source = read_file @commands = CommandCollection.new @symbols = Linker::SymbolTable.new reset_line_counter! end def run parse_all! print resolve print @hack = convert write_file end def read_file FileIO.new(@filename).read end def write_file FileIO.new(@output_filename).write(@hack) end def parse_all! @source.each do |source_location, text| parser = ParseTree::ParseStrategy::Mapper.new(text, source_location: source_location).parser parser.parse! expression = parser.build! # expressionは単独のExpressionインスタンス(配列ではないことを仮定) next if expression.blank? if expression.l_command? @symbols.register(expression.name, as: line_counter) else @commands.register(expression, lineno: line_counter, source_location: source_location) increment_line_counter! end end add_parent! add_depth! @commands end def resolve visitor = Linker::SymbolResolver.new(@symbols) @commands.each do |command| command.accept(visitor) end end def convert Code::MLConverter.new(*structurize_commands).convert end def print Visitor::PrintCommand.new(*structurize_commands).perform end def structurize_commands visitor = Visitor::CommandVisitor.new @commands.each.with_object([]) do |command, result| result << command.accept(visitor) end end private def add_parent! visitor = Visitor::ParentLinkVisitor.new @commands.each do |command| command.accept visitor end end def add_depth! visitor = Visitor::MeasureDepthVisitor.new @commands.each do |command| command.accept visitor end end def line_counter @line_counter ||= 0 end def increment_line_counter! @line_counter = line_counter + 1 end def reset_line_counter! @line_counter = 0 end end end
true
a109c68e165b20581dd099fb3d579771dc00b520
Ruby
nickhoffman/eat-the-alphabet
/spec/models/animal_spec.rb
UTF-8
2,770
2.609375
3
[]
no_license
require 'spec_helper' describe Animal do it 'includes Mongoid::Document' do Animal.should include Mongoid::Document end it 'includes Mongoid::Timestamps' do Animal.should include Mongoid::Timestamps end it 'stores valid "type" values in @@valid_types' do Animal.class_variable_get(:@@valid_types).should == [ 'land', 'water', 'air', ] end it { should have_field(:name).of_type String } it { should have_field(:letter).of_type String } it { should have_field(:types).of_type(Array).with_default_value_of [] } it { should have_field(:times_eaten).of_type(Integer).with_default_value_of 0 } it { should have_field(:approved).of_type(Boolean).with_default_value_of false } describe 'field mass-assignment' do # {{{ it 'allows "name" to be set' do Animal.new(:name => 'asdf').name.should == 'asdf' end it %q(doesn't allow "letter" to be set) do Animal.new(:letter => 'x').letter.should_not == 'x' end it 'allows "types" to be set' do Animal.new(:types => [:land]).types.should == [:land] end it %q(doesn't allow "times_eaten" to be set) do Animal.new(:times_eaten => 123).times_eaten.should_not be 123 end it %q(doesn't allow "approved" to be set) do Animal.new(:approved => true).approved.should_not be true end end # }}} describe '"name" validations' do # {{{ describe 'with 1 character' do # {{{ it 'is invalid' do Animal.new(:name => 'x').should have(1).error_on :name end end # }}} describe 'with 2 characters' do # {{{ it 'is invalid' do Animal.new(:name => 'xx').should have(0).errors_on :name end end # }}} describe 'with 100 characters' do # {{{ it 'is invalid' do Animal.new(:name => 'x' * 100).should have(0).errors_on :name end end # }}} describe 'with 101 character' do # {{{ it 'is invalid' do Animal.new(:name => 'x' * 101).should have(1).error_on :name end end # }}} end # }}} describe '"types" validations' do # {{{ describe 'with no types' do it 'is invalid' do Animal.new(:types => []).should have_at_least(1).error_on :types end end describe 'with an invalid value' do # {{{ it 'is invalid' do Animal.new(:types => [:invalid]).should have_at_least(1).error_on :types end end # }}} it 'accepts values in @@valid_types' do Animal.valid_types.each do |type| Animal.new(:types => [type]).should have(0).errors_on :types end end end # }}} describe '.valid_types' do # {{{ it 'returns @@valid_types' do Animal.valid_types.should == Animal.class_variable_get(:@@valid_types) end end # }}} end
true
9c5dd0acc36b014e6f3c54cf0b0a303eb80581f9
Ruby
snsavage/oo-tic-tac-toe-q-000
/lib/tic_tac_toe.rb
UTF-8
1,797
4.125
4
[]
no_license
class TicTacToe WIN_COMBINATIONS = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [6, 4, 2]] def initialize @board = Array.new(9, " ") end def display_board puts " #{@board[0]} | #{@board[1]} | #{@board[2]} " puts "-----------" puts " #{@board[3]} | #{@board[4]} | #{@board[5]} " puts "-----------" puts " #{@board[6]} | #{@board[7]} | #{@board[8]} " end def move(position, player = "X") @board[position - 1] = player end def position_taken?(position) space = @board[position] space == "X" || space == "O" end def valid_move?(position) position = position.to_i position.between?(1, 9) && !position_taken?(position - 1) end def turn puts "Player #{current_player}, please enter a position between 1 and 9:" position = gets.strip if valid_move?(position) move(position.to_i, current_player) else turn end display_board end def turn_count @board.count {|space| space == "X" || space =="O" } end def current_player turn_count.even? ? "X" : "O" end def won? result = WIN_COMBINATIONS.select do |combo| ["X", "O"].any? do |player| combo.all? do |space| @board[space] == player end end end result != [] ? result[0] : false end def full? @board.all? do |space| space == "X" or space == "O" end end def draw? full? && !won? end def over? won? || draw? || full? end def winner winning_combo = won? winning_combo ? @board[winning_combo[0]] : nil end def play until over? turn end if won? puts "Congratulations #{winner}!" else puts "Cats Game!" end end end
true
b2be6b53bca2570e68811f2add7e923abc5c8bc9
Ruby
aadilzbhatti/The-Odin-Project
/RubyProjects/SimpleServer/simple_browser.rb
UTF-8
773
2.921875
3
[]
no_license
require 'socket' require 'json' host = 'localhost' port = 2000 puts 'What type of request would you like to send? [GET, POST]' input = gets.chomp.upcase if input == 'POST' path = "/thanks.html" puts 'What is the name of your viking?' name = gets.chomp puts 'What is the email of your viking?' email = gets.chomp hash = {:viking => {:name=>name, :email=>email}}.to_json request = "POST #{path} HTTP/1.0\r\nFrom: #{email}\r\nUser-Agent: SimpleBrowser\r\nContent-type: application/json\r\nContent-Length: #{hash.to_s.length}\r\n\r\n#{hash}" else path = "/index.html" request = "GET #{path} HTTP/1.0\r\n\r\n" end socket = TCPSocket.open(host, port) socket.print(request) response = socket.read headers, body = response.split("\r\n\r\n", 2) print headers print body
true
f10591c65410529c1d66730dea4037bda1b680c4
Ruby
mainmatter/excellent
/spec/unit/checks/cyclomatic_complexity_method_check_spec.rb
UTF-8
4,605
2.703125
3
[ "MIT" ]
permissive
require 'spec_helper' describe Simplabs::Excellent::Checks::CyclomaticComplexityMethodCheck do before do @excellent = Simplabs::Excellent::Runner.new([:CyclomaticComplexityMethodCheck => { :threshold => 0 }]) end describe '#evaluate' do it 'should find an if block' do code = <<-END def method_name call_foo if some_condition end END verify_code_complexity(code, 2) end it 'should find an unless block' do code = <<-END def method_name call_foo unless some_condition end END verify_code_complexity(code, 2) end it 'should find an elsif block' do code = <<-END def method_name if first_condition then call_foo elsif second_condition then call_bar else call_bam end end END verify_code_complexity(code, 3) end it 'should find a ternary operator' do code = <<-END def method_name value = some_condition ? 1 : 2 end END verify_code_complexity(code, 2) end it 'should find a while loop' do code = <<-END def method_name while some_condition do call_foo end end END verify_code_complexity(code, 2) end it 'should find an until loop' do code = <<-END def method_name until some_condition do call_foo end end END verify_code_complexity(code, 2) end it 'should find a for loop' do code = <<-END def method_name for i in 1..2 do call_method end end END verify_code_complexity(code, 2) end it 'should find a rescue block' do code = <<-END def method_name begin call_foo rescue Exception call_bar end end END verify_code_complexity(code, 2) end it 'should find a case and when block' do code = <<-END def method_name case value when 1 call_foo when 2 call_bar end end END verify_code_complexity(code, 4) end describe 'when processing operators' do ['&&', 'and', '||', 'or'].each do |operator| it "should find #{operator}" do code = <<-END def method_name call_foo #{operator} call_bar end END verify_code_complexity(code, 2) end end end it 'should deal with nested if blocks containing && and ||' do code = <<-END def method_name if first_condition then call_foo if second_condition && third_condition call_bar if fourth_condition || fifth_condition end end END verify_code_complexity(code, 6) end it 'should count stupid nested if and else blocks' do code = <<-END def method_name if first_condition then call_foo else if second_condition then call_bar else call_bam if third_condition end call_baz if fourth_condition end end END verify_code_complexity(code, 5) end it 'should also work on singleton methods' do code = <<-END class Class def self.method_name if first_condition then call_foo else if second_condition then call_bar else call_bam if third_condition end call_baz if fourth_condition end end end END @excellent.check_code(code) warnings = @excellent.warnings warnings.should_not be_empty warnings[0].info.should == { :method => 'Class.method_name', :score => 5 } warnings[0].line_number.should == 2 warnings[0].message.should == "Class.method_name has cyclomatic complexity of 5." end end def verify_code_complexity(code, score) @excellent.check_code(code) warnings = @excellent.warnings warnings.should_not be_empty warnings[0].info.should == { :method => 'method_name', :score => score } warnings[0].line_number.should == 1 warnings[0].message.should == "method_name has cyclomatic complexity of #{score}." end end
true
7d3d35139909be3308cbdc67333f7af218e7403a
Ruby
katou02/baseball-app
/spec/models/tweet_spec.rb
UTF-8
6,209
2.546875
3
[]
no_license
require 'rails_helper' RSpec.describe Tweet, type: :model do let(:tweet){build(:tweet)} describe 'バリデーションのテスト' do subject { tweet.valid? } it '全て入力していれば保存できる' do expect(tweet).to be_valid end context 'titleカラム' do it '未入力だと保存できない' do tweet.title = '' is_expected.to eq false end it 'タイトルが未入力であればエラー' do tweet.title = nil tweet.valid? expect(tweet.errors[:title]).to include('を入力してください') end it '31文字以上だと保存できない' do tweet.title = 'a' * 31 tweet.valid? expect(tweet.errors).to be_added(:title, :too_long, count: 30) end it '30文字以下なら保存できる' do tweet.title = 'a' * 30 expect(tweet).to be_valid end end context 'textカラム' do it '未入力だと保存できない' do tweet.text = '' is_expected.to eq false end it 'テキストが未入力であればエラー' do tweet.text = '' tweet.valid? expect(tweet.errors[:text]).to include('を入力してください') end it '2001文字以上なら保存できない' do tweet.text = 'a' * 2001 tweet.valid? expect(tweet.errors).to be_added(:text, :too_long, count: 2000) end it '2000文字以下なら保存できる' do tweet.text = 'a' * 2000 expect(tweet).to be_valid end end context 'roundカラム' do it '未入力だと保存できない' do tweet.round = '' is_expected.to eq false end it 'ラウンドが未入力であればエラー' do tweet.round = '' tweet.valid? expect(tweet.errors[:round]).to include('を入力してください') end it '入力されていれば保存できる' do tweet.round = '2回戦' expect(tweet).to be_valid end end context 'school_aカラム' do it '未入力だと保存できない' do tweet.school_a_id = '' is_expected.to eq false end it '学校Aが未入力だとエラー' do tweet.school_a_id = '' tweet.valid? expect(tweet.errors[:school_a]).to include('を入力してください') end it '存在しない外部キーなら保存できない' do tweet.school_a_id = 6 is_expected.to eq false end it '外部キーが存在するなら保存できる' do tweet.school_a_id = 1 expect(tweet).to be_valid end end context 'school_bカラム' do it '未入力だと保存できない' do tweet.school_b_id = '' is_expected.to eq false end it '学校Bが未入力だとエラー' do tweet.school_b_id = '' tweet.valid? expect(tweet.errors[:school_b]).to include('を入力してください') end it '存在しない外部キーなら保存できない' do tweet.school_b_id = 4 is_expected.to eq false end it '外部キーが存在するなら保存できる' do tweet.school_b_id = 2 expect(tweet).to be_valid end end context 'school_a_scoreカラム' do it '未入力だと保存できない' do tweet.school_a_score = '' is_expected.to eq false end it '学校Aのスコアが未入力ならエラー' do tweet.school_a_score = '' tweet.valid? expect(tweet.errors[:school_a_score]).to include('を入力してください') end end context 'school_b_scoreカラム' do it '未入力だと保存できない' do tweet.school_b_score = '' is_expected.to eq false end it '学校Bのスコアが未入力ならエラー' do tweet.school_b_score = '' tweet.valid? expect(tweet.errors[:school_b_score]).to include('を入力してください') end end context 'tournamentカラム' do it '未入力なら保存できない' do tweet.tournament_id = '' is_expected.to eq false end it '大会が未入力ならエラー' do tweet.tournament_id = '' tweet.valid? expect(tweet.errors[:tournament]).to include('を入力してください') end it '存在しない外部キーなら保存できない' do tweet.tournament_id = 2 is_expected.to eq false end it '外部キーが存在するなら保存できる' do tweet.tournament_id = 3 expect(tweet).to be_valid end end context 'userカラム' do it '空なら保存できない' do tweet.user_id = '' is_expected.to eq false end it 'ユーザーが空ならエラー' do tweet.user_id = '' tweet.valid? expect(tweet.errors[:user]).to include('を入力してください') end end end describe 'アソシエーションテスト' do context 'Commentテーブルとの関係' do it '1:Nとなっている' do t = Tweet.reflect_on_association(:comments) expect(t.macro).to eq(:has_many) end end context 'Categoryテーブルとの関係' do it '1:Nとなっている' do t = Tweet.reflect_on_association(:categories) expect(t.macro).to eq(:has_many) end end context 'Likeテーブルとの関係' do it '1:Nとなっている' do t = Tweet.reflect_on_association(:likes) expect(t.macro).to eq(:has_many) end end context 'Notificationテーブルとの関係' do it '1:Nとなっている' do t = Tweet.reflect_on_association(:notifications) expect(t.macro).to eq(:has_many) end end context 'Userモデルとの関係' do it 'belongs_toになっている' do t = Tweet.reflect_on_association(:user) expect(t.macro).to eq(:belongs_to) end end end end
true
141d1c69fd68b0bb95f089d734a66012a217a89f
Ruby
kevinday/project-euler
/19.rb
UTF-8
186
3.453125
3
[]
no_license
require 'date' date = Date.new(1901,1,1) end_date = Date.new(2000, 12, 1) sundays = 0 while date < end_date do sundays += 1 if date.sunday? date = date.next_month end puts sundays
true
81b63b31bfcb05b3d3e8975e67a5a6b9a606198f
Ruby
vienbk91/Ruby
/Advance/procs_lambda.rb
UTF-8
2,243
4.1875
4
[]
no_license
# Proc và Lambda trong Ruby ####################################################### ## Block ####################################################### m = [1,2,3,4,5] n = [10,20,30,40,50] # Xây dựng 1 hàm có sử dụng block def double_block(x) if block_given? yield x*2 else puts "Khong co block" end end puts "Mang m_block" puts m.map { |arr| # Đưa từng phần tử của mảng m vào arr #Gọi tới hàm double_block double_block(arr){ # Cho arr trở thành tham số của block |x| # Gán giấ trị tham số truyền vào trong yield vào biến x, ở đây x = arr*2 "#{x}" # Thực thi in ra x } } puts "Mang n_block" puts n.map{ |arr| double_block(arr){|x| "#{x}"}} ####################################################### ## Proc ####################################################### # Ta nhận thấy 2 đoạn code có nội dung hoàn toàn giống nhau # Vì vậy ta sử dụng proc để ghép nó lại double_proc = Proc.new do |t| t*2 end #Bây giờ thay vì viết đoạn code dài như trên ta chỉ cần gọi proc đã tạo # Chú ý proc được đặt trong () thay vì {} như trong block puts "Mang m_proc" puts m.map(&double_proc) puts "Mang n_proc" puts n.map(&double_proc) ####################################################### ## Lambda ####################################################### double_lambda = lambda do |k| k*2 end puts "Mang m_lambda" puts m.map(&double_lambda) puts "Mang n_lambda" puts n.map(&double_lambda) ####################################################### ## Phân biệt Proc và Lambda ####################################################### =begin Ta có thể truyền nhiều tham số vào trong proc mà ko sử dụng thì khi run chương trình cũng sẽ không có thông báo lỗi double_proc = Proc.new do |t,k,x,y| # 4 tham số truyền vào t*2 end puts m.map(&double_proc) # Không phát sinh lỗi Tuy nhiên Lambda thì có bao nhiêu tham số được khai báo thì cần sử dụng toàn bộ, nếu không sẽ có lỗi double_lambda = lambda do |k,m| # Truyền vào lambda 2 tham số k*2 end puts m.map(&double_lambda) # Thông báo lỗi do thiếu argument =end =begin =end
true
3c63765523603d6a5302d011988c41c044cde254
Ruby
Dob212/CADProject
/lib/order_decorator.rb
UTF-8
1,050
3.046875
3
[]
no_license
class BasicOrder def initialize(name, description, time, cost) @oname = name @odescription = description @otime = time @ocost = cost end def ocost return @ocost end def details return @odescription end end class OrderDecorator def initialize(base_order) @base_order = base_order @extra_cost = 0 @extra = "No extras" end def ocost return @extra_cost + @base_order.ocost end def details return @extra + ": #{@extra_cost} + " + @base_order.details end end class FoodDecorator < OrderDecorator def initialize(base_order) super(base_order) @description = "food supplied" @extra_cost = 25 end def details return @description + ": #{@extra_cost} + " + @base_order.details end end #travel decorator class TravelDecorator < OrderDecorator def initialize(base_order) super(base_order) @description = "travel supplied" @extra_cost = 30 end def details return @description + ": #{@extra_cost} + " +@base_order.details end end
true
be8b347b955ecfc7180346b41b9691f4cfa4745f
Ruby
RStankov/SearchObject
/lib/search_object/helper.rb
UTF-8
1,970
2.671875
3
[ "MIT" ]
permissive
# frozen_string_literal: true module SearchObject # :api: private module Helper module_function def stringify_keys(hash) # Note(rstankov): From Rails 5+ ActionController::Parameters aren't Hash # In a lot of cases `stringify_keys` is used on action params hash = hash.to_unsafe_h if hash.respond_to? :to_unsafe_h Hash[(hash || {}).map { |k, v| [k.to_s, v] }] end def slice_keys(hash, keys) keys.inject({}) do |memo, key| memo[key] = hash[key] if hash.key? key memo end end def camelize(text) text.to_s.gsub(/(?:^|_)(.)/) { Regexp.last_match[1].upcase } end def underscore(text) text.to_s .tr('::', '_') .gsub(/([A-Z]+)([A-Z][a-z])/) { "#{Regexp.last_match[1]}_#{Regexp.last_match[2]}" } .gsub(/([a-z\d])([A-Z])/) { "#{Regexp.last_match[1]}_#{Regexp.last_match[2]}" } .tr('-', '_') .downcase end def ensure_included(item, collection) if collection.include? item item else collection.first end end def define_module(&block) Module.new do define_singleton_method :included do |base| base.class_eval(&block) end end end def normalize_search_handler(handler, name) case handler when Symbol then ->(scope, value) { method(handler).call scope, value } when Proc then handler else ->(scope, value) { scope.where name => value unless value.blank? } end end def deep_copy(object) # rubocop:disable Metrics/MethodLength case object when Array object.map { |element| deep_copy(element) } when Hash object.inject({}) do |result, (key, value)| result[key] = deep_copy(value) result end when NilClass, FalseClass, TrueClass, Symbol, Method, Numeric object else object.dup end end end end
true
751c4d1f9690c30df2dde0097ff20f3d01d3f07f
Ruby
MarkLauer/languages
/sysadmins.rb
UTF-8
690
2.65625
3
[]
no_license
if File.exist?("access.log") input = File.new("access.log", "r") regexp_ip = /(?:25[0-5]|2[0-4]\d|[0-1]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[0-1]?\d{1,2})){3}\b/ regexp_sub = /[1-2]?[0-9]?[0-9]\.[1-2]?[0-9]?[0-9]\.[1-2]?[0-9]?[0-9]\./ ip_array = input.read.scan(regexp_ip) input.close ip_hash = Hash.new(0) for ip in ip_array ip_hash[ip] += 1 end output = File.new("output.txt", "w") sub_array = ip_array.uniq.to_s.scan(regexp_sub) for sub in sub_array for ip in ip_array.uniq if (ip.start_with?(sub)) output.print(ip + " " + ip_hash[ip].to_s + "\n") end end output.print("\n") end output.close print "output.txt created" else print "access.log not found" end
true
168ebca2f4325aa5761b9c88879675e8e29f877a
Ruby
tdooner/advent-code
/2016/15/process.rb
UTF-8
498
3.125
3
[]
no_license
def process_line(line, index) num_positions = line.scan(/(\d+) positions/).first.first.to_i initial_position = line.scan(/position (\d+)/).first.first.to_i # puts "0 == (#{initial_position} + #{index} + tick) % #{num_positions}" ->(tick) { 0 == (initial_position + tick + index) % num_positions } end rules = [] ARGF.each_line.each_with_index do |line, index| rules << process_line(line.strip, index + 1) end i = 0 loop do break if rules.all? { |r| r.call(i) } i += 1 end puts i
true
de32f919fae61895e9ff75377ddc3665ff92c050
Ruby
zpeller/aoc-2016
/13_maze_of_cubicles.rb
UTF-8
1,956
3.484375
3
[]
no_license
#!/usr/bin/ruby require 'set' input = 1358 $dest_coords = [31, 39] #input = 10 #$dest_coords = [7, 4] $start_pos = [1, 1] $map_width, $map_height = 55, 55 def is_wall(x, y, favnum) num_d = x*x + 3*x + 2*x*y + y + y*y + favnum num_b = "%b" % num_d one_bits = num_b.chars.select{ |x| x=='1' }.length return ((one_bits % 2) == 1) end def init_maze(width, height, favnum) maze = [] (0..height).each { |y| maze_line = [] (0..width).each { |x| maze_line += [(is_wall(x, y, favnum)? "#":".")] } maze += [maze_line] print maze_line.join(''), "\n" } return maze end def adjacent_field_coords(x, y, w, h) field_coords = [] if x < w-1 field_coords << [x+1, y] end if y < h-1 field_coords << [x, y+1] end if x>0 field_coords << [x-1, y] end if y>0 field_coords << [x, y-1] end return field_coords end def find_num_steps(building_map) # building_map = Marshal.load(Marshal.dump(building_map)) move_level = 1 building_map[$start_pos[1]][$start_pos[0]] = 0 prev_step_list = Set.new prev_step_list.add([1, 1]) while not prev_step_list.empty? next_step_list = Set.new prev_step_list.each {|c_x, c_y| adjacent_field_coords(c_x, c_y, $map_width, $map_height).each { |x, y| if building_map[y][x]=='.' building_map[y][x] = move_level next_step_list.add?([x, y]) if x == $dest_coords[0] and y == $dest_coords[1] return move_level end end } } prev_step_list = next_step_list move_level += 1 end end def count_max_50_steps(building_map) count_50 = 0 (0..$map_height-2).each { |y| (0..$map_width-2).each { |x| if building_map[y][x].class == Fixnum and building_map[y][x]<=50 count_50 += 1 end } } return count_50 end maze = init_maze($map_width, $map_height, input) #print maze, "\n" print("P1 num steps: #{find_num_steps(maze)}\n") print("P2 max 50 steps: #{count_max_50_steps(maze)}\n") __END__
true
0fd2a130c93fbef24b50186947fbd39678ba3107
Ruby
SciRuby/iruby
/lib/iruby/event_manager.rb
UTF-8
989
3
3
[ "MIT" ]
permissive
module IRuby class EventManager def initialize(available_events) @available_events = available_events.dup.freeze @callbacks = available_events.map {|n| [n, []] }.to_h end attr_reader :available_events def register(event, &block) check_available_event(event) @callbacks[event] << block unless block.nil? block end def unregister(event, callback) check_available_event(event) val = @callbacks[event].delete(callback) unless val raise ArgumentError, "Given callable object #{callback} is not registered as a #{event} callback" end val end def trigger(event, *args, **kwargs) check_available_event(event) @callbacks[event].each do |fn| fn.call(*args, **kwargs) end end private def check_available_event(event) return if @callbacks.key?(event) raise ArgumentError, "Unknown event name: #{event}", caller end end end
true
529d41e10e9eb8db275c0e5c2da40ec447fff204
Ruby
samesystem/social_security_number
/lib/social_security_number/validator.rb
UTF-8
1,454
2.90625
3
[ "MIT" ]
permissive
module SocialSecurityNumber # SocialSecurityNumber::Validator class Validator SUPPORTED_COUNTRY_CODES = %w[BE CA CH CN CZ DE DK EE ES FI FR GB IE IS IT LT LV MX NL NO PK SE US].freeze attr_accessor :civil_number, :country_code, :error def initialize(params = {}) @civil_number = params[:number].to_s.strip.gsub(/\s+/, '').upcase @country_code = params[:country_code].to_s.strip.gsub(/\s+/, '').upcase @birth_date = params[:birth_date] ? params[:birth_date] : nil @gender = params[:gender] ? params[:gender] : nil unless self.class::SUPPORTED_COUNTRY_CODES.include?(@country_code) raise "Unexpected country code '#{country_code}' that is not yet supported" end end def valid? civil_number = SocialSecurityNumber.const_get(@country_code.capitalize).new(@civil_number) if civil_number.valid? if !@birth_date.nil? && !civil_number.birth_date.nil? && civil_number.birth_date.to_s != @birth_date.to_s @error = "birth date #{@birth_date} dont match #{civil_number.birth_date}" return false end if !@gender.nil? && !civil_number.gender.nil? && civil_number.gender.to_s.strip != @gender.to_s.strip @error = "gender #{@gender} dont match #{civil_number.gender}" return false end return true end @error = civil_number.error false end end end
true
a5b73de6c3bc1968fe8645aa759ca2653b8b8c4a
Ruby
dallinder/programming_basics
/lesson_5/practice10.rb
UTF-8
153
3.171875
3
[]
no_license
hsh = [{a: 1}, {b: 2, c: 3}, {d: 4, e: 5, f: 6}] hsh.map do |x| new_hsh = {} x.map do |key, value| new_hsh[key] = value + 1 end new_hsh end
true
aab42dd191750003f1a24807b0f557e88265d1a4
Ruby
ably-forks/cloudyscripts
/lib/audit/lib/benchmark/rule_severity.rb
UTF-8
255
3.328125
3
[ "MIT" ]
permissive
class RuleSeverity UNKNOWN = "unknown" INFO = "info" LOW = "low" MEDIUM = "medium" HIGH = "high" SEVERITIES = [UNKNOWN, INFO, LOW, MEDIUM, HIGH] def self.parse(str) return ((SEVERITIES.include? str.downcase) ? str.downcase : UNKNOWN) end end
true
899d1c51cbe1703c67ee416c053c5cf27410ba96
Ruby
toolsforteachers/Assess-Student-Needs
/features/step_definitions/group_steps.rb
UTF-8
1,720
2.640625
3
[]
no_license
Given(/^I add a group named "(.*?)" with a student named "(.*?)"$/) do |group_name, student_name| visit new_group_path fill_in 'Class name', with: group_name click_link 'Add a student' fill_in 'Student', with: 'Ann' click_button "Save" end When(/^I navigate to the "(.*?)" group page$/) do |group_name| click_link "Classes" click_link group_name end When /^the "(.*)" group should have (\d+) students$/ do |group_name, count| Group.find_by_name(group_name).students.length.should eql(count.to_i) end Then(/^I should see "(.*?)" in the list of students$/) do |list_of_student_names| within('.students') do list_of_student_names.split(',').each do |student_name| page.should have_text(student_name) end end end When(/^I the follow the add lesson link$/) do click_link('Add a new lesson', match: :first) end Then(/^I should be the teacher of "(.*?)"$/) do |group_name| within(:css, 'h1') do page.should have_text(group_name) end end When(/^I change the group "(.*?)" to "(.*?)"$/) do |old_name, new_name| visit group_path(Group.find_by_name(old_name)) click_link 'Edit this class' fill_in 'Class name', with: new_name click_button 'Save' end When(/^I remove the student named "(.*?)"$/) do |student_name| click_link "Manage students" click_link "Remove #{ student_name }" click_button 'Save' end When(/^I try to add a duplicate group "(.*?)"$/) do |group_name| visit new_group_path fill_in 'Class name', with: group_name click_button "Save" end Then(/^I should get a group validation error$/) do page.should have_text 'name has already been taken' end Then(/^I should see the new class prompt$/) do page.should have_link 'Add a new class' end
true
fbd1d60599a706aa680d1c6821bfaeb62d274d8b
Ruby
Joelle5/goongit
/duck.rb
UTF-8
102
2.84375
3
[]
no_license
def duck_duck_goose (players, goose) rounds = goose % players.length players(rounds - 1).name end
true
537f7d77313fa7f5a84964227d6d4f44b7ddb530
Ruby
bitprophet/redmine2github
/github.rb
UTF-8
1,957
2.53125
3
[]
no_license
require 'rubygems' require 'json' POST_OK = true REPO_PATH = ENV['REPO'] || "fabric/issuetest2" #ENV['RESTCLIENT_LOG'] = 'stdout' require 'rest_client' class GithubAPI def initialize(section="") @api = RestClient::Resource.new( "https://api.github.com/#{section}", ENV['GITHUB_USERNAME'], ENV['GITHUB_PASSWORD'] ) end def issues @api["/issues"].get end def issue(id) @api["/issues/#{id}"].get end def method_missing(sym, *args, &block) @api.send(sym, *args, &block) end end class ItemCache def initialize(api, urlpart, key) @api = api @urlpart = urlpart @key = key @items = {} end def fetch(params={}) items = {} JSON.parse(@api[@urlpart].get(:params => params)).each do |item| items[item[@key]] = item end items end def list @items = fetch if @items.empty? @items end def create(value) @items[value] = if POST_OK JSON.parse(@api[@urlpart].post( {@key => value}.to_json, :content_type => 'text/json' )) else {@key => value, :number => 1} end end def get(value) list.fetch(value) do create(value) end end end class MilestoneCache < ItemCache def list if @items.empty? @items.merge! fetch(:state => "open") @items.merge! fetch(:state => "closed") end @items end end class NoSuchUser end class UserCache def initialize(api) @api = api @users = {} end def get(username) begin @users[username] ||= begin JSON.parse @api["users/#{username}"].get rescue RestClient::ResourceNotFound NoSuchUser.new end rescue => e pp e pp JSON.parse(e.response) raise end end end REPO = GithubAPI.new "repos/#{REPO_PATH}" GITHUB = GithubAPI.new MILESTONES = MilestoneCache.new REPO, '/milestones', 'title' USERS = UserCache.new GITHUB LABELS = ItemCache.new REPO, '/labels', 'name'
true
b57bc80e73b1e75547a3359a5812aa22d6dbc75f
Ruby
mikethorpe/ruby_codeclan_course
/cchw_wk2_day1/library.rb
UTF-8
1,135
3.421875
3
[]
no_license
class Library def initialize() @books = [ { title: "lord_of_the_rings", rental_details: { student_name: "Jeff", date: "01/12/16" } }, { title: "lord_of_the_flies", rental_details: { student_name: "Barry", date: "01/11/16" } }, { title: "do_androids_dream_of_electric_sheep", rental_details: { student_name: "Kate", date: "01/04/16" } } ] end def books() return @books end def get_book_info(book_title) for book in @books return book if book[:title] == book_title end end def get_book_rental_info(book_title) for book in @books return book[:rental_details] if book[:title] == book_title end end def add_book(new_book) @books.push(new_book) end def update_rental_details(book_title, student, due_date) for book in @books if (book[:title] == book_title) book[:rental_details][:student_name] = student book[:rental_details][:date] = due_date end end end end
true
1a2a5d8bbc06a90c08c810910d96e8101ec25782
Ruby
orangethunder/axlsx
/examples/data_validation.rb
UTF-8
1,397
2.65625
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby -w -s # -*- coding: utf-8 -*- $LOAD_PATH.unshift "#{File.dirname(__FILE__)}/../lib" require 'axlsx' p = Axlsx::Package.new p.workbook.add_worksheet do |ws| ws.add_data_validation("A10", { :type => :whole, :operator => :between, :formula1 => '5', :formula2 => '10', :showErrorMessage => true, :errorTitle => 'Wrong input', :error => 'Only values between 5 and 10', :errorStyle => :information, :showInputMessage => true, :promptTitle => 'Be carful!', :prompt => 'Only values between 5 and 10'}) ws.add_data_validation("B10", { :type => :textLength, :operator => :greaterThan, :formula1 => '10', :showErrorMessage => true, :errorTitle => 'Text is too long', :error => 'Max text length is 10 characters', :errorStyle => :stop, :showInputMessage => true, :promptTitle => 'Text length', :prompt => 'Max text length is 10 characters'}) 8.times do |i| ws.add_row [nil, nil, i*2] end ws.add_data_validation("C10", { :type => :list, :formula1 => 'C1:C8', :showDropDown => false, :showErrorMessage => true, :errorTitle => '', :error => 'Only values from C1:C8', :errorStyle => :stop, :showInputMessage => true, :promptTitle => '', :prompt => 'Only values from C1:C8'}) end p.serialize 'data_validation.xlsx'
true
94bc3ab91b58ba924343c530f340ed92fb7cd567
Ruby
thebravoman/software_engineering_2013
/class8_homework/Petur_Pelovski_1.rb
UTF-8
826
2.8125
3
[]
no_license
require "csv" i = 0 a = "" umri = 'test' string = "" names = [] broqch = 0 broqch2 = 0 File.open("sub_expected.txt", "r") do |file| while line = file.gets string = string + line end file.close end Dir["/home/petur/software_engineering_2013/class7_homework/*.rb"].each {|file| a = file.scan(/test/) a = a.to_s if a != umri result = `ruby #{file} sub.srt` result = result.to_s name = file.split("/").last name = name.split("_")[0..1] name[1] = name[1].split(".").first names[broqch] = name[0] + " " + name[1] if result == string names[broqch] = names[broqch] + "," + "1" else names[broqch] = names[broqch] + "," + result + "," + "0" end broqch += 1 end } File.open("results1.csv", "w") do |file| while broqch2 <= broqch file.write(names[broqch2] + "\n") broqch2 += 1 end file.close end
true
9c119b41f27cdc573caf2d6cfdd2bd0300eaa8d9
Ruby
giddynaj/dedup
/dedup.rb
UTF-8
7,707
3.671875
4
[]
no_license
require 'csv' require 'text' require 'json' require 'sinatra' require 'sinatra/json' # # Utility Methods # clean - Clean a row from file # gen_key - generate a key based on columns you want to combine # add_to - generate a key and use it to insert a hash into the master hash # load_file - open csv file, parse, and build data structure # def clean(hline) #Clean First and Last Name for key in ['first_name','last_name'] hline[key] = hline[key].downcase.strip end end def gen_key(keys, line_to_insert) full_key = [] # Take the initialization arr keys and build the key from it for key in keys full_key << line_to_insert[key] end full_key.join('_') end def add_to(master, keys, line_to_insert) #generate hash key full_key = gen_key(keys, line_to_insert) #initialize hash slot with an empty array master[full_key] = [] if master[full_key].nil? #append the hash master[full_key] << line_to_insert master end def load_file(filename, master, key_arr) #initialize variables hash_line = {} clean_hash_line = {} #Set headers so line can be converted into hash CSV.foreach(filename, headers: true) do |line| hash_line = line.to_h #clean hash line clean_hash_line = clean(hash_line) #add hash_line to master master = add_to(master, key_arr, hash_line) end master end # # Categorize # # First sort out the entries into unique candidates # and duplicates based on keys # # Secondary filtering of unique candidates # def categorize(master, key_arr, duplicates, unique) unique_candidates = [] to_remove = [] # # Sort out entries in master into unique # and duplicates categories # for key in master.keys if master[key].count > 1 # Because there is more than one entry # Append specific reason for tagging this data as a duplicate duplicates << {'reason'=> "Duplicate key #{key}", 'data' => master[key] } else # Since there is only one entry we will add to the candidates unique_candidates << master[key][0] end end # Expensive here n-prime^2 # It seems necessary in order to compare with # all other elements in the unique candidates list. # uc = unique_candidates for idx1 in (0...uc.count).to_a for idx2 in ((idx1+1)...uc.count).to_a #Generate the index keys for the elements #to be compared key1 = gen_key(key_arr, uc[idx1]) key2 = gen_key(key_arr, uc[idx2]) #Doing straight up computation, but we can #chain it. Example: if meta_sim > 0.95 then run #levenshtein. If levenshtein is <= 2 then run #WhiteSimilarity. You would want the less accurate #algorithms to run first, this I'm not sure of ls = Text::Levenshtein.distance(key1, key2) white = Text::WhiteSimilarity.new meta1 = Text::Metaphone.metaphone(key1) meta2 = Text::Metaphone.metaphone(key2) meta_sim = white.similarity(meta1, meta2) sim = white.similarity(key1, key2) #TODO #puts Text::Metaphone.metaphone(uc[key2]) #puts Text::Soundex.soundex(uc[key1]) #puts Text::PorterStemming.stem(can['last_name']) # These are thresholds that were set by looking at the test data # This can be set dynamically based on whoever is manually checking these duplicate candidates if ls < 5 || sim > 0.85 || meta_sim > 0.85 duplicates << {'reason'=> "Levenshtein: #{ls}, Sim: #{sim}, Sim on Metaphone: #{meta_sim}", 'data'=>[uc[idx1], uc[idx2]]} # Remove these entries later to_remove << key1 to_remove << key2 end end end # Remove people that were candidates but were disqualified based on # further text algorithms for key in to_remove unique_candidates.delete_if{ |uc| gen_key(key_arr, uc) == key } end # Assign unique people to list unique = unique_candidates #Optional sort on last name unique = unique.sort {|s1, s2| s1['last_name']<=>s2['last_name']} [duplicates, unique] end # # Print out # def display(unique, duplicates) puts 'Unique' for item in unique item = item puts item['first_name'] + ' ' + item['last_name'] + ' ' + item['email'] end puts 'Multiple' for items in duplicates for item in items #puts item['first_name'] + ' ' + item['last_name'] puts item end puts '----------------------------' end end get '/results' do # Setup variables filename = 'advanced.csv' master = {} common_first_names = {'bill'=>'william'} duplicates = [] unique = [] key_arr = ['last_name', 'first_name', 'email'] # Load master = load_file(filename, master, key_arr) # Categorize duplicates, unique = categorize(master, key_arr, duplicates, unique) results = {"uniques"=> unique, "duplicates"=> duplicates} json results end get '/' do # Setting up some styles and async js call function on the home page # This will call the results page when the dom is loaded. <<-EOS <style> .unique { display: block; } .duplicate { display: block; } </style> <script> function create_td(tn){ td = document.createElement('td'); td.appendChild(document.createTextNode(tn)); return td } function display(elm){ text = elm['first_name'] + ',' +\ elm['last_name'] + ',' +\ elm['email'] + ',' +\ elm['phone'] + ',' +\ elm['company'] + ',' +\ elm['address1'] + ',' +\ elm['address2'] + ',' +\ elm['zip'] + ',' +\ elm['city'] + ',' +\ elm['state'] return document.createTextNode(text); } function display_duplicate_reason(elm){ tn = document.createTextNode('Reason: ' + elm.reason); return tn; } function display_duplicate(ul, elm){ elm.data.forEach(item =>{ li = document.createElement('li'); li.appendChild(display(item)); ul.appendChild(li); }); } function display_uniques(elm){ return display(elm); } function getRequest(url, callback, params, response_type, callback_params) { var request = new XMLHttpRequest(); var method = 'GET'; if(url.charAt(0) != '/'){ url = '/' + url; } request.onload = function() { if(request.status === 200) { let checkType = request.getResponseHeader('content-type'); if (checkType == 'application/json') { raw = JSON.parse(request.responseText); d = document.querySelector('.duplicates'); ul = document.createElement('ul'); for (var i = 0; i < raw.duplicates.length; i++) { li = document.createElement('li'); li.appendChild(display_duplicate_reason(raw.duplicates[i])); ul.appendChild(li); display_duplicate(ul, raw.duplicates[i]); li = document.createElement('li'); li.appendChild(document.createTextNode('')); ul.appendChild(li); } d.appendChild(ul); u = document.querySelector('.uniques'); ul = document.createElement('ul'); for (var i = 0; i < raw.uniques.length; i++) { li = document.createElement('li'); li.appendChild(display_uniques(raw.uniques[i])); ul.appendChild(li) } u.appendChild(ul); } } } request.open(method, url); request.send(null); } document.addEventListener('DOMContentLoaded', function(){ getRequest('/results') }); </script> <body> <h1>Find Duplicates Challenge</h1> <h3>Unique Entries</h3> <div class="uniques"> </div> <h3>Duplicate Entries</h3> <div class="duplicates"> </div> </body> EOS end
true
7e3b303f5f59f19a5489288adf269b850c720a38
Ruby
benders/blarg
/vendor/gems/data_objects-0.9.12/lib/data_objects/uri.rb
UTF-8
2,010
2.828125
3
[ "MIT" ]
permissive
gem 'addressable', '~>2.0' require 'addressable/uri' module DataObjects # A DataObjects URI is of the form scheme://user:password@host:port/path#fragment # # The elements are all optional except scheme and path: # scheme:: The name of a DBMS for which you have a do_\&lt;scheme\&gt; adapter gem installed. If scheme is *jdbc*, the actual DBMS is in the _path_ followed by a colon. # user:: The name of the user to authenticate to the database # password:: The password to use in authentication # host:: The domain name (defaulting to localhost) where the database is available # port:: The TCP/IP port number to use for the connection # path:: The name or path to the database # query:: Parameters for the connection, for example encoding=utf8 # fragment:: Not currently known to be in use, but available to the adapters class URI < Struct.new(:scheme, :user, :password, :host, :port, :path, :query, :fragment) # Make a DataObjects::URI object by parsing a string. Simply delegates to Addressable::URI::parse. def self.parse(uri) return uri if uri.kind_of?(self) uri = Addressable::URI::parse(uri) unless uri.kind_of?(Addressable::URI) self.new(uri.scheme, uri.user, uri.password, uri.host, uri.port, uri.path, uri.query_values, uri.fragment) end # Display this URI object as a string def to_s string = "" string << "#{scheme}://" if scheme if user string << "#{user}" string << ":#{password}" if password string << "@" end string << "#{host}" if host string << ":#{port}" if port string << path.to_s if query string << "?" << query.map do |key, value| "#{key}=#{value}" end.join("&") end string << "##{fragment}" if fragment string end # Compare this URI to another for hashing def eql?(other) to_s.eql?(other.to_s) end # Hash this URI def hash to_s.hash end end end
true
3b07b63e0224c03ba3768687b6c9a50b31a1e901
Ruby
susan-wz/math-game
/questions.rb
UTF-8
560
3.9375
4
[]
no_license
class Question attr_reader :numbers, :ask_question attr_accessor :player def initialize(current_player) @current_player = current_player @number_1 = rand(21) @number_2 = rand(21) end def ask_question puts "#{@current_player.name}: What does #{@number_1} plus #{@number_2} equal?" end def check_answer answer = @number_1 + @number_2 user_response = gets.chomp.to_i if answer == user_response puts "Yes, you're correct!" return true else puts "No, wrong!" return false end end end
true
550d5352b139b6c63012229e28ac625ebd8649fc
Ruby
mmcgirr19/RB101_pgrm_fnds
/lesson_3/pp_easy2/q2.rb
UTF-8
224
3.15625
3
[]
no_license
munsters_description = "The Munsters are creepy in a good way." p munsters_description.upcase!.sub(/T/, 't').sub(/M/, 'm') p munsters_description.capitalize p munsters_description.downcase! p munsters_description.upcase!
true
16a458d1e59d47bc6795c428a1fa613e347b76d7
Ruby
izumariu/hsanhalt-tools
/tools/ims2sched/RUN.rb
UTF-8
1,180
2.71875
3
[]
no_license
#!/usr/bin/env ruby require "time" require "yaml" require "#{File.dirname(__FILE__)}/libuniics.rb" HOUR = 60*60 CLASSES = %w(FSL1 FSL3 FSL5 FSL7 IMS1Ü1 IMS1Ü2 IMS3Ü1 IMS3Ü2 IMS5 IMS7 MIM2 MS L2 MIAM2) PROFS = YAML.load open("#{File.dirname(__FILE__)}/lecturers.yaml", &:read) SUMMARY_REGEX = Regexp.new("(#{CLASSES.join(?|)})(\\s+#{CLASSES.join("|\\s+")})*\s+(#{PROFS.keys.join(?|)})") DAYS = %w(Sunday Monday Tuesday Wednesday Thursday Friday Saturday) if ARGV.length != 2 abort "USAGE: #{__FILE__.split(?/)[-1]} <ICS FILE> <P_GROUP_NUM>" end file, pgroup = ARGV pgroup = pgroup.to_i unless [1,2].include?(pgroup) abort "E: P_GROUP_NUM must be either 1 or 2\n(Tip: If you're in Ü2, group 3 becomes 1 and group 4 becomes 2)" end cal = HSAnhaltICS.from(file, PROFS) cal.schedule.each do |group| if group.length == 1 lec = group.first else lec = group[pgroup - 1] end puts "#{lec.title||"<unknown>"}" puts "- by #{lec.lecturer||"<unknown>"}" puts "- starts #{DAYS[Time.at(lec.start).wday]}, #{Time.at(lec.start)}" puts "- ends #{DAYS[Time.at(lec.start).wday]}, #{Time.at(lec.end)}" puts "- in room #{lec.location||"<unknown>"}" puts end
true
0186a49773f50fa6b90609ea0f1cdb4dbc298094
Ruby
edwardloveall/portfolio
/lib/tasks/tumblr.rake
UTF-8
1,765
2.6875
3
[]
no_license
namespace :tumblr do desc 'Import all posts from tumblr into database (indempotent)' task import_posts: 'db:migrate' do api_key = ENV.fetch('TUMBLR_API_KEY') fetcher = TumblrFetcher.new(api_key: api_key) post_data = fetcher.posts creator = PostCreator.new(json: post_data) creator.perform end class TumblrFetcher TUMBLR_POSTS_URL = 'https://api.tumblr.com/v2/blog' attr_reader :api_key, :blog_id, :post_type def initialize(api_key:) @api_key = api_key @blog_id = 'edwardloveall' @post_type = 'text' end def posts url = URI("#{TUMBLR_POSTS_URL}/#{blog_id}/posts/#{post_type}?api_key=#{api_key}&filter=raw") response = Net::HTTP.get(url) JSON.parse(response) end end class PostCreator attr_reader :json def initialize(json:) @json = json end def perform post_attributes.each do |attributes| post = Post.create(attributes) if post.errors.present? puts post.errors.full_messages else puts "Imported #{post.title}" end end end def post_attributes post_array = json['response']['posts'] attributes = post_array.map do |post| body = body_sanitizer(post['body']) created_at = Time.at(post['timestamp']) { created_at: created_at, updated_at: created_at, title: post['title'], body: body, slug: post['slug'], tumblr_guid: post['id'] } end end def body_sanitizer(body) body.gsub('&lt;', '<') .gsub('&gt;', '>') .gsub(/<pre class="highlight \b(.+)\b"><code>/) { "```#{$1}\n" } .gsub(/<\/code><\/pre>/, '```') end end end
true
e932ce7a8794bdd5eb49dad65452abd0a19a1e09
Ruby
gbellini90/activerecord-validations-lab-nyc-web-102918
/app/models/post.rb
UTF-8
739
3.03125
3
[]
no_license
class Post < ActiveRecord::Base validates :title, presence: true validates :content, length: { minimum: 250 } validates :summary, length: { maximum: 250 } validates :category, inclusion: { in: %w(Fiction Non-Fiction)} validates :title, format: {with: /Won't Believe|Secret|Top \d|Guess/} end # If the title does not contain "Won't Believe", "Secret", # "Top [number]", or "Guess", the validator should return false. #format # This helper validates the attributes' values # by testing whether they match a given regular expression, # which is specified using the :with option. #example: #class Product < ApplicationRecord #validates :legacy_code, format: { with: /\A[a-zA-Z]+\z/, # message: "only allows letters" } #end
true
a1672b80fa201815567f49751970792a16bf01a9
Ruby
mhar-andal/phase-0-tracks
/ruby/secret_agents.rb
UTF-8
1,918
4.3125
4
[]
no_license
=begin ENCRYPT METHOD - advance each letter one letter forward - run .next on each index - use ! to change index in place - spaces remain as spaces DECRYPT METHOD - reverse encrypt - go backward one letter - =end def encrypt(password) index = 0 while index < password.length if password[index] == "z" password[index] = "a" elsif password[index] == " " else password[index] = password[index].next! end index += 1 end puts "#{password}" return password end def decrypt(password) index = 0 alphabet = "abcdefghijklmnopqrstuvwxyz" while index < password.length if password[index] == " " else temp = alphabet.index(password[index]) temp -= 1 password[index] = alphabet[temp] end index += 1 end puts "#{password}" end # MAIN - driver code quit = false while quit != true puts "What would you like to do?" puts "1. Encrypt a password (must do before option 2)" puts "2. Decrypt a password" puts "3. Exit the program" choice = gets.chomp.to_i case choice when 1 puts "-Enter password:" password = gets.chomp.downcase password = encrypt(password) when 2 if password.nil? == true puts "-Please run option 1 first!" else decrypt(password) end when 3 quit = true else puts "-Please enter valid option!" end end encrypt("abc") encrypt("zed") decrypt("bcd") decrypt("afe") encrypt(password) decrypt(password) decrypt(encrypt("swordfish")) # This nested method call works because the encrypt method is returning # the password and decrypt is accepting the returned value as an argument =begin 1. use a menu to ask user what they would like to do - menu as while loop 2. options of menu: -Asks a secret agent (the user) whether they would like to decrypt or encrypt a password -Asks them for the password -Conducts the requested operation, prints the result to the screen -Quit program =end
true
433f621bca42074d2a9415c19cf8886e07cfb4cf
Ruby
CynthiaBin/Programacion-Paralela
/practica_7/models/user.rb
UTF-8
337
2.609375
3
[]
no_license
# Model user class User < AbstractBase attr_reader :id def initialize(name = nil, user_name = nil, email = nil) @name = name @user_name = user_name @email = email super(:users) end def register data_set = DB[@table_name] @id = data_set.insert(name: @name, userName: @user_name, email: @email) end end
true
61854777c807d3a331fcfca7981a3fc5ac514270
Ruby
rn0rno/kyopro
/aoj/ruby/02_Volume0/0001.rb
UTF-8
173
3.5
4
[]
no_license
#!/usr/bin/env ruby # Input mountains = [] while line = gets mountains << line.chomp!.to_i # delete \n end # Sort & Output mountains.sort! 3.times{ puts mountains.pop }
true
d208ba1be4086180ca2378a47f23d879115426d1
Ruby
VDmitryO/pushkin-contest-bot
/app/services/tasks_service.rb
UTF-8
2,392
3.390625
3
[]
no_license
class TasksService attr_accessor :question, :level def initialize(question, level) @question = question @level = level end def get_answer case level when '1' POEMS_1[question] when '2', '3', '4' level_234(POEMS_234) when '5' level_5(question.include?(',') ? POEMS_5_COMMA : POEMS_5) when '6', '7' level_67(POEMS_67) when '8' level_8(POEMS_8) end end def level_234(poems) check_str = question.gsub(/[\n[:punct:]]/, '.') regexp = Regexp.new(check_str.gsub('.WORD.', '[[:word:]]+')) result = regexp.match(poems).to_s.scan(/[[:alpha:]]+/) answer = [] check_str.scan(/[[:alpha:]]+/).each_with_index do |word, index| answer << result[index] if word == 'WORD' end answer.join(',') end def level_5(poems) answer = nil words = question.scan(/[[:alpha:]]+/) poems[words.size].each do |str| errors = 0 str.each_with_index do |word, index| unless word == words[index] answer = words[index] + ',' + word errors += 1 end break if errors == 2 end return answer if errors == 1 end end def level_67(poems) poems[question.scan(/[[:alpha:]]/).sort] end def level_8(poems) letters = question.scan(/[[:alpha:]]/).sort amount_words = question.scan(/[[:alpha:]]+/).size amount_letters = letters.size poems[amount_words][amount_letters].each do |key, value| first_error = 0 last_error = key.size key.each_with_index do |char, index| unless char == letters[index] first_error = index break end end key.reverse_each do |char| last_error -= 1 break unless char == letters[last_error] end range1 = (first_error + 1)..last_error range2 = first_error...last_error return value if key.values_at(range1) == letters.values_at(range2) || key.values_at(range2) == letters.values_at(range1) end nil end # def level_8(poems) # letters = question.scan(/[[:alpha:]]/) # amount_words = question.scan(/[[:alpha:]]+/).size # amount_letters = letters.size # poems[amount_words][amount_letters].each do |key, value| # return value if (key - letters).size < 2 && (letters - key).size < 2 # end # nil # end end
true
81b16f1755516abdd5f63e83b2d82d0d9f97ddf4
Ruby
MrJons/boris_bikes
/lib/van.rb
UTF-8
332
2.515625
3
[]
no_license
require_relative "docking_station" require_relative "garage" class Van def initialize @broken_bikes = [] @good_bikes = [] end def collect(bikes) until bikes.empty? @broken_bikes << bikes.pop end @broken_bikes end def collect_fixed(bikes) until bikes.empty? @good_bikes << bikes.pop end @good_bikes end end
true
756257d3ef6bb8b26a5783334f4c4331a8a684a1
Ruby
Warrenoo/qy_wechat_proxy
/wechat.rb
UTF-8
530
2.5625
3
[]
no_license
require "qy_wechat_api" require "forwardable" QyWechatApi.configure do |config| config.logger = Logger.new(STDOUT) end class Wechat attr_accessor :wc, :appid #wechat_client extend Forwardable def_delegators :wc, :is_valid? def initialize(corpid, corpsecret, appid) @wc = QyWechatApi::Client.new(corpid, corpsecret) @appid = appid raise "cannot connect wechat server with your message" unless is_valid? end def send_text(msg) wc.message.send_text("@all", "@all", "@all", appid, msg) end end
true
c56ba75eca36a3fb35fd386fd5553d438d068af7
Ruby
Tcom242242/t_learn
/lib/t_learn/k_means.rb
UTF-8
2,620
2.875
3
[ "MIT" ]
permissive
#!/usr/bin/ruby # -*- encoding: utf-8 -*- module TLearn class K_Means attr_accessor :data_list, :k, :c_list def init(data_list, k=2) @data_list = data_list sliced_data_list = @data_list.each_slice(k).to_a @dim = data_list[0].size @k = k @cluster_list = @k.times.map {|n| Cluster.new(n, nil,sliced_data_list[n] , @dim)} end def fit(data_list, k) init(data_list, k) history = [] loop { @cluster_list.each{|c| c.reset_v_list()} @data_list.each {|d| min_dist = 100000 min_cluster_id = -1 @cluster_list.each {|c| dist = calc_dist(d, c) if dist < min_dist min_cluster_id = c.id min_dist = dist end } @cluster_list[min_cluster_id].add_v(d) } history.push(format_for_log()) @cluster_list.each{|c| c.calc_center()} break if !change_clusters_center? } return {:result => format_for_log(), :history => history} end def format_for_log() result = @cluster_list.map {|c| c.format_hash()} end def calc_dist(v, cluster) dist_sum = 0.0 v.each_with_index { |v_x, i| dist_sum += (cluster.vec[i] - v_x).abs } return dist_sum/v.size end def change_clusters_center?() @cluster_list.each {|c| return true if(c.change_center?) } return false end # # cluster # cluster has id, vec, and v_list # class Cluster attr_accessor :id, :vec, :v_list, :last_vec def initialize(id, vec=nil, v_list=nil, dim=1) @id = id @v_list= v_list @vec = dim.times.map{0.0} if vec == nil @dim = dim calc_center() end def calc_center() @last_vec = Marshal.load(Marshal.dump(@vec)) vec_sum = Array.new @v_list.each { |v| v.each_with_index { |v_x, i| vec_sum[i] ||= 0.0 vec_sum[i] += v_x } } vec_sum.each_with_index { |new_vec, i| @vec[i] = new_vec/@v_list.size.to_f } end def add_v(v) @v_list.push(v) end def reset_v_list() @v_list = [] end def change_center? @dim.times { |i| return true if @vec[i] != @last_vec[i] } return false end def format_hash() cluster_hash = {} cluster_hash[:id] = @id cluster_hash[:vec] = @vec cluster_hash[:v_list] = @v_list return cluster_hash end end end end
true
b7f09e3ec4f0d291bed8ffe8cab7a93fb8ddd863
Ruby
paulba71/DesignPatternsTermPaperCode
/Object Pool/Without Pattern/main.rb
UTF-8
3,186
3.234375
3
[]
no_license
require 'ruby-prof' require_relative 'proofer' @english_text=['hello', 'the', 'purpose', 'of', 'this', 'sample', 'is', 'to', 'test', 'some', 'spelling', 'mistakes', 'using', 'the', 'object pool', 'design', 'pattern', 'au reviour'] @french_text=['bonjour', 'le', 'but', 'de', 'cet', 'exemple', 'est', 'de', 'tester', 'quelques', 'dorthographe', 'fautes', 'le', 'motif', 'de', 'conception', 'de', 'pool', 'dobjets'] @german_text=['Hallo', 'der', 'Zweck', 'dieses', 'Beispiel', 'ist', 'es', 'einige', 'Rechtschreibfehler', 'mit', 'dem', 'Objekt', 'Pool', 'Design-Muster', 'testen', 'zu' 'testen'] @spanish_text=['Hola', 'el', 'propósito', 'de', 'esta', 'muestra', 'es', 'probar', 'algunos', 'errores', 'ortográficos', 'usando', 'el', 'patrón', 'de', 'diseño', 'de', 'la', 'piscina', 'de', 'objetos', 'adiós'] @proofer=Proofer.new def test_full_language (language) found_count=0 not_found_count=0 total_count=0 case language when :english then data=@english_text when :french then data=@french_text when :german then data=@german_text when :spanish then data=@spanish_text else data=nil end data.each do |str| total_count+=1 result=@proofer.check? language, str.downcase if result puts "Word #{str} was found in the #{language} dictionary" found_count+=1 else puts "Word #{str} was not found in the #{language} dictionary" not_found_count+=1 end end puts '-------------------------------------------' puts "Of #{total_count} words: #{found_count} were found, #{not_found_count} were not" puts '-------------------------------------------' end def test_randomly (iterations) iterations.times do lang_index=rand(4) case lang_index when 0 then #English language='English' word_index=rand(@english_text.count) str = @english_text[word_index].downcase result=@proofer.check? :english, str when 1 then #French language='French' word_index=rand(@french_text.count) str = @french_text[word_index].downcase result=@proofer.check? :french, str when 2 then #German language='German' word_index=rand(@german_text.count) str = @german_text[word_index].downcase result=@proofer.check? :german, str when 3 then #French language='Spanish' word_index=rand(@spanish_text.count) str = @spanish_text[word_index].downcase result=@proofer.check? :spanish, str else result=nil str='' language='' end if result!=nil && language!='' puts "Word #{str} was found in the #{language} dictionary" #found_count+=1 else if language!='' puts "Word #{str} was not found in the #{language} dictionary" #not_found_count+=1 end end end end RubyProf.measure_mode = RubyProf::CPU_TIME RubyProf.start test_full_language(:english) test_full_language(:french) test_full_language(:german) test_full_language(:spanish) test_randomly 10000 result=RubyProf.stop # print a flat profile to text printer = RubyProf::FlatPrinter.new(result) printer.print(STDOUT)
true
3d0cca1836d9f97c353db8a2d23248b1969c33f1
Ruby
jamesboyd2008/phase-0
/week-6/gps2_3.rb
UTF-8
2,148
4.125
4
[ "MIT" ]
permissive
# Your Names # 1) Peter Stratoudakis # 2) James Boyd # We spent [1.5] hours on this challenge. # Bakery Serving Size portion calculator. def serving_size_calc(item_to_make, num_of_ingredients) cook_book = {"cookie" => 1, "cake" => 5, "pie" => 7} if !cook_book.include?(item_to_make) raise ArgumentError.new("#{item_to_make} is not a valid input") end ingredients_needed = cook_book[item_to_make] remaining_ingredients = num_of_ingredients % ingredients_needed suggested_item = "#{remaining_ingredients} cookies" cook_book.each do |item, ingredients| suggested_item = item if remaining_ingredients == ingredients end if remaining_ingredients == 0 return "Calculations complete: Make #{num_of_ingredients / ingredients_needed} of #{item_to_make}" end "Calculations complete: Make #{num_of_ingredients / ingredients_needed} of #{item_to_make}, you have" + " #{remaining_ingredients} leftover ingredients. " + "Suggested baking items: #{suggested_item}" end # DRIVER CODE: p serving_size_calc("pie", 7) p serving_size_calc("pie", 8) p serving_size_calc("cake", 5) p serving_size_calc("cake", 7) p serving_size_calc("cookie", 1) p serving_size_calc("cookie", 10) p serving_size_calc("cake", 12) p serving_size_calc("THIS IS AN ERROR", 5) # Reflection # What did you learn about making code readable by working on this challenge? # It saves a lot of times for other developers if your code is readable. # It's important to take the time to make your code readable. # # Did you learn any new methods? What did you learn about them? # We used hash's .values. We raised an ArgumentError. We used both p and puts. # We used an implicit return. # # What did you learn about accessing data in hashes? # We learned that if you call .each on a hash, and only supply one temporary # variable in the pipes, like this: hash.each do |var| , that variable is # referring to the hash's key/value pairs like this: [key, value]. # # What concepts were solidified when working through this challenge? # Write code that other people can read easily. Sometimes the shortest answer # isn't the best or most readable answer.
true
51cd44d133993e5cd52d89ff681a8e98e96401f9
Ruby
rhosyn/tldr
/lib/services/smmry.rb
UTF-8
712
2.609375
3
[]
no_license
require 'open-uri' require 'json' class Smmry def summarize articles = AylienArticle.where(summary_sentences: nil) articles.each do |a| news_url = a.article_url url = "http://api.smmry.com/&SM_API_KEY=#{ENV['Smmry_API_Key']}&SM_WITH_BREAK&SM_WITH_ENCODE&SM_QUOTE_AVOID&SM_QUESTION_AVOID&SM_EXCLAMATION_AVOID&SM_KEYWORD_COUNT=10&SM_LENGTH=5&SM_URL=#{news_url}" smmry = JSON.parse(open(url).read) a.summary_sentences = smmry["sm_api_content"].strip.gsub(/\&#039;/, "'").split("[BREAK]").each {|s| s.strip } if smmry["sm_api_content"] a.save! puts "WARNING ############## error with summary" if a.summary_sentences.nil? sleep(11) end end end
true
79c1392cc866a9c8396835ad322a53e259ed5481
Ruby
Bschlin/ruby-javascript-converter
/practice.rb
UTF-8
2,414
4.65625
5
[]
no_license
# Write a method that prints out every number from 1 to 100. def one_to_hunnit numba = 1 100.times do p numba numba += 1 end end one_to_hunnit # Write a method that prints out every other number from 1 to 100. (That is, 1, 3, 5, 7 ... 99). def every_other_number number = 0 while number < 100 if number % 2 != 0 puts number end number += 1 end end every_other_number # Write a method that accepts an array of numbers as a parameter, and counts how many 55's there are in the array. def method(arr) count = 0 arr.each do |number| if number == 55 count +=1 end end count end puts method([1,22,55,3,4,6,55,55]) # Write a method that accepts an array of strings and returns a new array that has the string "awesomesauce" inserted between every string. # For example, if the initial array is ["a", "b", "c", "d", "e"], then the returned array should be ["a", "awesomesauce", "b", "awesomesauce", "c", "awesomesauce", "d", "awesomesauce", "e"]. def method(string) new_array = [] length = string.length index = 0 length.times do new_array << string[index] if index != length - 1 new_array << "awesomesauce" end index += 1 end return new_array end p method([1,5,6,8,9,10]) # Start with the hash: item_amounts = {chair: 5, table: 2} # Someone just bought two chairs. Change the hash such that the chair amount is 3. # The final result should be: {chair: 3, table: 2} item_amounts = {chair: 5, table: 2} item_amounts[:chair] = 3 p item_amounts # Start with the hash: item_amounts = {chair: 5, table: 2} # You received 7 desks to sell. Change the hash to include desks. # The final result should be: {chair: 5, table: 2, desk: 7} item_amounts = {chair: 5, table: 2} item_amounts[:desk] = 7 p item_amounts # Write a method that accepts a number and returns its factorial. # For example, the factorial of 5 is 5 * 4 * 3 * 2 * 1 = 120. def factorial(num) num.downto(1).reduce(:*) end p factorial(5) ################### def factorial(num) product = 1 num.times do if num > 0 product *= num num -= 1 # num += 1 (this would end up in an endless loop) end end return product end p factorial(5) ################## # def factorial(num) # product = 1 # while num > 0 # product *= num # num -= 1 # end # return product # end # puts factorial(5)
true
f714c0c2a874b834d01e007eea56ed865811d451
Ruby
lchandra1/nandomoreira-jekyll-theme
/source/_posts/clase.rb
UTF-8
1,115
3.34375
3
[ "MIT" ]
permissive
class lchandra def initialize(name, gender, age, location, email, password) @name = name @gender = gender @age = age @location = location @email = email @password = password end def name=(name) @name = name end def name return @name end def gender=(gender) @gender = gender end def gender return @gender end def age=(age) return @age = age end def age return @age end def location=(location) @location = location end def location return @location end def email=(email) @email = email end def email return @email end def password=(password) @password = password end def password return @password end end lchandra = User_1.new("name", "gender", "age", "location", "email", "password") lchandra.age(17) puts lchandra.age lchandra.name("Luke") puts lchandra.name lchandra.gender("Male") puts lchandra.gender lchandra.email("lchandra@lsoc.org") puts lchandra.email lchandra.password("gobears") puts lchandra.password lchandra.location("Chicago") puts lchandra.location
true
68dabd6a0c2c1b86f11fe5e8a7998bbd9ba46ca9
Ruby
niiccolas/aao
/03_ruby/02_enumerables_and_debugging/projects/02_ghost/spec/game_spec.rb
UTF-8
1,474
3.09375
3
[]
no_license
require 'game' describe "Game class" do players = [Player.new('Slimer'), Player.new('Casper')] ghost_game = Game.new(players) describe "#initialize" do it "should set @dictionary to a hash with keys being words of the dictionary" do expect(ghost_game.dictionary.keys).to_not include(nil) end it "should set @players to an array" do expect(ghost_game.players.is_a? Array).to eq(true) end it "should set @fragment to a string" do expect(ghost_game.fragment.is_a? String).to eq(true) end invalid_players = Game.new([Player.new(123), Player.new(true)]) it "should only accept string for player names" do expect(ghost_game.players.all? { |player| player.name.is_a? String }).to eq(true) expect(invalid_players.players.all? { |player| player.name.is_a? String }).to eq(false) end end describe "#current_player" do it "should return the first element of the @players array" do expect(ghost_game.current_player).to eq(ghost_game.players.first) end end describe "#previous_player" do it "should return the last element of the @players array" do expect(ghost_game.previous_player).to eq(ghost_game.players.last) end end describe "#next_player!" do it "should modify the @players array" do untouched_players_array = ghost_game.players.clone ghost_game.next_player! expect(ghost_game.players).to_not eq(untouched_players_array) end end end
true
8de9546f7fd4266671c0e30f7a48ffbf705a57b5
Ruby
samanthi22/app-academy-ruby
/Enumerables/lib/enumerables.rb
UTF-8
4,650
4.03125
4
[]
no_license
class Array def my_each(&prc) i = 0 while i < length yield self[i] i += 1 end return self end end return_value = [1,2,3].my_each do |num| puts num end #=> 1,2,3 p return_value class Array def my_select(&prc) result = [] each do |ele| result << ele unless prc.call(ele) == false end return result end end a = [1, 2, 3] p a.my_select { |num| num > 1 } # => [2, 3] p a.my_select { |num| num == 4 } # => [] class Array def my_reject(&prc) result = [] each do |ele| result << ele unless prc.call(ele) == true end return result end end a = [1, 2, 3] p a.my_reject { |num| num > 1 } # => [1] p a.my_reject { |num| num == 4 } # => [1, 2, 3] class Array def my_any?(&prc) each do |ele| if prc.call(ele) == true return true end end return false end def my_all?(&prc) each do |ele| if prc.call(ele) == false return false end end return true end end a = [1, 2, 3] p a.my_any? { |num| num > 1 } # => true p a.my_any? { |num| num == 4 } # => false p a.my_all? { |num| num > 1 } # => false p a.my_all? { |num| num < 4 } # => true class Array def my_flatten(&prc) recursive_flatten(self) end def recursive_flatten(array, results = []) array.each do |ele| if ele.class == Array recursive_flatten(ele, results) else results << ele end end return results end end p [1, 2, 3, [4, [5, 6]], [[[7]], 8]].my_flatten # => [1, 2, 3, 4, 5, 6, 7, 8] class Array def my_zip(a, b, *rest) arr = [] i = 0 while i < length array = [] array << self[i] unless nil array << a[i] unless nil array << b[i] unless nil rest.each do |c_d| array << c_d[i] end arr << array i += 1 end return arr end end a = [ 4, 5, 6 ] b = [ 7, 8, 9 ] p [1, 2, 3].my_zip(a, b) # => [[1, 4, 7], [2, 5, 8], [3, 6, 9]] p a.my_zip([1,2], [8]) # => [[4, 1, 8], [5, 2, nil], [6, nil, nil]] p [1, 2].my_zip(a, b) # => [[1, 4, 7], [2, 5, 8]] c = [10, 11, 12] d = [13, 14, 15] p [1, 2].my_zip(a, b, c, d) # => [[1, 4, 7, 10, 13], [2, 5, 8, 11, 14]] class Array def my_rotate(n=1) return self.drop(n%self.length) + self.take(n%self.length) end end a = [ "a", "b", "c", "d" ] p a.my_rotate #=> ["b", "c", "d", "a"] p a.my_rotate(2) #=> ["c", "d", "a", "b"] p a.my_rotate(-3) #=> ["b", "c", "d", "a"] p a.my_rotate(15) #=> ["d", "a", "b", "c"] class Array def my_join(char= "") arr = [] i = 0 while i < self.length - 1 arr << self[i] arr << char i +=1 end arr << self[length-1] return arr.join("") end end a = [ "a", "b", "c", "d" ] p a.my_join # => "abcd" p a.my_join("$") # => "a$b$c$d" class Array def my_reverse arr = [] i = self.length - 1 while i >= 0 arr << self[i] i -= 1 end return arr end end [ "a", "b", "c" ].my_reverse #=> ["c", "b", "a"] [ 1 ].my_reverse #=> [1] def factors(num) arr = [] (1..num).each do |factor| if (num % factor == 0) arr << factor end end return arr end class Array def bubble_sort(&prc) self.dup.bubble_sort!(&prc) end def bubble_sort!(&prc) bool = true while bool bool = false (0..self.size-2).each do |i| if block_given? if prc.call(self[i], self[i+1]) == 1 self[i], self[i+1] = self[i+1], self[i] bool = true end else # block not given if (self[i] > self[i+1]) self[i], self[i+1] = self[i+1], self[i] bool = true end end end end # end while return self end # end bubble_sort! end ascending = Proc.new { |num1, num2| num1 <=> num2 } #sort ascending descending = Proc.new { |num1, num2| num2 <=> num1 } #sort descending def substrings(string) substr = [] string.chars length = string.length length.times do |start_pos| (0..(length+1-start_pos)).each do |len| #byebug substr << string[start_pos..len] end end return substr.uniq end def subwords(word, dictionary) new_arr = [] substr_arr = substrings(word) dictionary.each do |word| if substr_arr.include?(word) then new_arr << word end end return new_arr end
true
b3e129d00088ff375ac73509636c2a19e787ceef
Ruby
AliannyPerez1/array-CRUD-lab-ruby-apply-000
/lib/array_crud.rb
UTF-8
1,148
4
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def create_an_empty_array [] end def create_an_array [1,2,3,4] end def add_element_to_end_of_array(array, element) array = ["wow", "I", "am", "really", "learning"] element = "arrays!" array.push("arrays!") end def add_element_to_start_of_array(array, element) array = ["I", "am", "really", "learning"] element = "wow" array.unshift("wow") end def remove_element_from_end_of_array(array) array = ["I", "am", "really", "learning", "arrays!"] array.pop end ##this one only takes in one argument, dont need to write out element for it to take out (the array on which we want to operate on) def remove_element_from_start_of_array(array) array.shift end def retrieve_element_from_index(array, index_number) array = ["wow", "I", "am", "really", "learning", "arrays!"] index_number = (2) return "am" end def retrieve_first_element_from_array(array) array = ["wow", "I", "am", "really", "learning", "arrays!"] index_number = (0) return "wow" end def retrieve_last_element_from_array(array) array =["wow", "I", "am", "really", "learning", "arrays!"] index_number = (-1) return "arrays!" end
true
84089f2fbb8db85eabf69483eaac33c8ea175402
Ruby
molingyu/dnd
/lib/dnd_log/dnd_log_creator.rb
UTF-8
435
2.796875
3
[]
no_license
require 'qmessage' class DND::DndLogCreator attr_reader :info attr_reader :logs def initialize(log, players) @qm = QMsg.run(log) @players = players @info = OpenStruct.new @logs = [] create end def create @qm.each do |qm| player_infos(qm) end end def player_infos(qm) u_code = qm.u_code @players.each do |player| if player._ucode == u_code end end end end
true
5fe4ed3493bf349ca6bb668cc4ae81a16dc9522f
Ruby
seryl/backdat
/lib/backdat/storage/local.rb
UTF-8
2,656
3
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
require 'set' require 'fileutils' # The backdat Local storage object. class Backdat::Storage::Local < Backdat::Storage::Base attr_reader :excluded # Creates a new Local storage object. # # @param [ Hash ] params The parameters to initialize the Local object with. # # @option params [ String ] :path The path to the Local object. # @option params [ String ] :folder The optional (remote) folder to use. # @option params [ String ] :method The method for target transfers. def initialize(params={}) super @path = link_config :path @excluded = ['.', '..', '.backdat'] exclude_item(link_config :exclude) @method = link_config(:method) || :cp @data = Backdat::Data::File.new(file_list) end # Yields a Backdat::Data enumerator for the next link to consume/backup. # # @note The iterator typing is based on the `@format` given. # # @yield [ Backdat::Data ] A Backdat::Data enumerator. def backup end # Yields a Backdat::Data enumerator for the next link to consume/restore. # # @note The iterator typing is based on the `@format` given. # # @yield [ Backdat::Data ] A Backdat::Data enumerator. def restore end # Returns the list of files at the given path. # # @return [ Array ] The list of files at the given path. def file_list Array(@path).inject(Set.new) do |list, _path| next list unless File.exists?(_path) if File.directory?(_path) list = list | sanitized_directory(_path) else list << _path if keep_file?(_path) end list end.to_a end # Add an item or list of items to the excluded list. # # @note Takes any string or splat to match. # # @param [ Array ] items The list of string to match against. def exclude_item(items) exclude = @excluded.to_set Array(items).each { |_item| exclude << _item } @excluded = exclude.to_a end # The symbolized version of the transfer method. # # @return [ Symbol ] The symbolized version of the transfer method. def method @method.to_sym end private # Checks whether or not the file will be excluded. # # @return [ Boolean ] Whether or not to keep a given file. def keep_file?(path) @excluded.each { |_exclude| return false if path.match(/^#{_exclude}$/) } return true end # The list of files that are not to be excluded in the given path list. # # @return [ Array ] The list of files that are not excluded. def sanitized_directory(path) sane_files = Dir.entries(path).select { |_file| keep_file?(_file) } sane_files.map { |_file| File.expand_path(File.join(path, _file)) } end end
true
223dc3684d5338be50eb8a24262af1c10eda06c1
Ruby
kenchan/competitive_programming
/atcoder/abc276/E.rb
UTF-8
150
2.90625
3
[]
no_license
# https://atcoder.jp/contests/abc276/tasks/abc276_e H, W = gets.split.map(&:to_i) Css = Array.new(H) { gets.chomp.split } puts cond ? 'Yes' : 'No'
true
f9d6f8089f92a42973ca6376d362be1ec23dd986
Ruby
ShashKing/Training
/Ruby Training/ArrayTest25.rb
UTF-8
102
2.734375
3
[]
no_license
arr=[22,55,65,78,12,55,50] num=arr.sort num.each { |e| puts e } puts mutate(arr) puts not_mutate(arr)
true
944a6c995508465a9f51937ee6c1864dc8657d03
Ruby
marswong/prime-ruby-cb-gh-000
/prime.rb
UTF-8
274
3.4375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def prime?(n) if n <= 1 false elsif n <= 3 true elsif n % 2 == 0 || n % 3 == 0 false else i = 5 result = true while i ** 2 < n if n % i == 0 || n % (i + 2) == 0 result = false end i += 6 end result end end
true
4ced150ba82c8714b93aed07fa421a02a20b89af
Ruby
vijayakumarsuraj/automation
/automation/core/task.rb
UTF-8
2,631
2.546875
3
[]
no_license
# # Suraj Vijayakumar # 04 Dec 2012 # require 'automation/core/component' require 'automation/enums/result' require 'automation/enums/status' require 'automation/support/runnable' module Automation # A task represents the most basic unit of work the framework can carry out. class Task < Component # Makes this task a runnable. include Automation::Runnable # If true, this task will persist its results to the results database. attr_accessor :persist # New task. def initialize super @result = Automation::Result::Pass @component_name = @component_name.snakecase @component_type = Automation::Component::TaskType @raise_exceptions = true @persist = true @databases = runtime.databases @results_database = @databases.results_database end # Get the process ID of this task. # # @return [String, Integer] the PID. def pid @config_manager['task.pid'] end # Updates the process ID of this task. # # @param [String, Integer] pid the PID. def update_pid(pid) @config_manager.add_override_property('task.pid', pid, overwrite: true) end private # Executed after the shutdown method, even if there are exceptions. def cleanup if defined? @task_result @task_result.result = @result @task_result.status = Status::Complete @task_result.end_date_time = DateTime.now @task_result.save end end # Executed if there are exceptions. # By default, logs the error and re-raises it. # # @param [Exception] ex the exception. def exception(ex) update_result(Automation::Result::Exception) raise if @raise_exceptions @logger.error(format_exception(ex)) end # Executed before the task runs. # By default, all configured observers are loaded. def setup # Persist this task's results only if the persist flag is set. if @persist @run_result = @results_database.get_run_result @run_config = @run_result.run_config @task_entity = @results_database.get_task!(@run_config, @component_name) @task_result = @results_database.create_task_result(@run_result, @task_entity) end load_observers('task', []) end # Executed after the task runs (if there were no exceptions). def shutdown end # Get a task specific config entry value. # # @param [String] key # @param [Hash] options # @return [String] def task_config(key, options = {}) @config_manager["task.#{@component_name}.#{key}", options] end end end
true
f524ddc1c8265c59f8c30f3271beaf190e708611
Ruby
eichelbw/Conway
/gol_array.rb
UTF-8
5,067
3.640625
4
[]
no_license
require 'rspec' require "pry" class World < Array def initialize(x_dim, y_dim, seed_probabily, steps) @x_dim, @y_dim, @steps = x_dim, y_dim, steps @cells = Array.new(@y_dim) { Array.new(@x_dim) { Cell.new(seed_probabily) } } end def cells @cells end def alive_neighbors(y, x) [[-1,-1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]].inject(0) do |sum, position| sum + @cells[(y + position[0]) % @y_dim][(x + position[1]) % @x_dim].to_i end end def step! @cells.each_with_index do |row, y| row.each_with_index do |cell, x| cell.neighbors = alive_neighbors(y, x) end end @cells.each do |row| row.each do |cell| # binding.pry cell.rules! end end end def display_world newrow = Array.new(0) newarray = Array.new(0) @cells.each do |row| row.each do |cell| newrow << cell.to_s end newarray << newrow newrow = [] end newarray end def play! (1...@steps).each do self.display_world.each do |row| row.each do |cell| print cell end puts end sleep(0.5) system('clear') step! end end end class Cell attr_writer :neighbors attr_writer :alive def initialize(seed_probabily) @alive = seed_probabily < rand end def to_i @alive ? 1 : 0 end def to_s @alive ? 'O' : '-' end def rules! @alive = @alive ? (2..3) === @neighbors : 3 == @neighbors end end world = World.new(10,10,0.5,100) world.play! describe 'the game of life' do describe 'class initialization' do it 'world initialization should take dimensions, seed probability, steps and return an array' do world = World.new(10, 10, 0.5, 1) world.should be_an_instance_of(World) end it 'cell initialization should take seed probability' do cell = Cell.new(0.5) cell.should be_an_instance_of(Cell) end end describe 'world methods' do it '#alive_neighbors(coordinates) should return number of live neighbors to cell at coordinates' do world = World.new(5, 5, 1, 1) world.cells[1][1] = 1 world.alive_neighbors(1, 1).should eq 0 world.cells[1][0] = 1 world.alive_neighbors(1, 1).should eq 1 world.cells[0][1] = 1 world.alive_neighbors(1, 1).should eq 2 end it '#cells should return an array of the cells in the world' do world = World.new(5, 5, 1, 1) world.cells.should be_an_instance_of(Array) world.cells[1][1] = 1 world.cells.should be_an_instance_of(Array) end it '#display_world should print the current world state to the console' do world = World.new(5, 5, 1, 1) array = Array.new(5) { Array.new(5) { '-' } } world.display_world.should eq array world.cells[1][1].alive = true array[1][1] = 'O' world.display_world.should eq array end describe '#step! method' do it 'should apply rule 1 of the game' do world = World.new(5, 5, 1, 1) world.cells[1][1].alive = true world.step! world.cells[1][1].to_i.should eq 0 world.cells[1][1].alive = true world.cells[0][1].alive = true world.step! world.cells[1][1].to_i.should eq 0 end it 'should apply rule 2 of the game' do world_1 = World.new(5, 5, 1, 1) world_2 = World.new(5, 5, 1, 1) world_1.cells[1][1].alive = true world_1.cells[0][1].alive = true world_1.cells[1][0].alive = true world_1.step! world_1.cells[1][1].to_i.should eq 1 world_2.cells[1][1].alive = true world_2.cells[0][1].alive = true world_2.cells[1][0].alive = true world_2.cells[1][2].alive = true # binding.pry world_2.step! world_2.cells[1][1].to_i.should eq 1 end it 'should apply rule 3 of the game' do world = World.new(5, 5, 1, 1) world.cells[1][1].alive = true world.cells[0][1].alive = true world.cells[1][0].alive = true world.step! world.cells[0][0].to_i.should eq 1 end it 'should apply rule 4 of the game' do world = World.new(5, 5, 1, 1) world.cells[1][1].alive = true world.cells[0][1].alive = true world.cells[1][0].alive = true world.cells[2][1].alive = true world.cells[1][2].alive = true world.step! world.cells[1][1].to_i.should eq 0 end end end describe 'cell methods' do it '#to_i should return 1 or 0 depending on life status of the cell' do cell_1 = Cell.new(0) cell_2 = Cell.new(1) cell_1.to_i.should eq 1 cell_2.to_i.should eq 0 end it '#to_s should return "O" or " " depending on the life status of the cell' do cell_1 = Cell.new(0) cell_2 = Cell.new(1) cell_1.to_s.should eq "O" cell_2.to_s.should eq "-" end end end
true
466db6038ab5e2fc6050036303cf9d4aafb8b565
Ruby
zbadiru/ruby-oo-relationships-practice-blood-oath-exercise-lon01-seng-ft-042020
/app/models/follower.rb
UTF-8
649
3.109375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Follower attr_reader :name attr_accessor :age, :life_motto @@all = [] def initialize(name, age, life_motto) @name = name @ago = age @life_motto = "life motto" @@all << self end def bloodoaths_f Bloodoath.all.select {|b| b.follower == self} end def cults self.bloodoaths_f.map {|c| c.cult } end def join_cult(cult) Bloodoath.new(initiation_date, cult, self) end def self.of_a_certain_age(f_age) bloodoaths_f.select {|bloodoaths_f| bloodoaths_f.age >= f_age} end def self.all @@all end end
true
c015aff4665fe5987743e5826517edd2c54e64ea
Ruby
rails-girls-summer-of-code/rgsoc-teams
/spec/lib/selection/distance_spec.rb
UTF-8
1,062
2.953125
3
[ "MIT" ]
permissive
require 'rails_helper' require 'selection/distance' RSpec.describe Selection::Distance do let(:from) { ['30.1279442', '31.3300184'] } let(:to) { ['30.0444196', '31.2357116000001'] } # Validate via geocoder gem or web service # see here: http://boulter.com/gps/distance/?from=30.1279442+31.3300184&to=30.0444196+31.2357116000001&units=k#more subject { described_class.new(from, to) } context 'when passing valid strings as input data' do it 'calcuates the distance between two lat-lng coords in meters' do expect(subject.to_m).to eq 12984 end it 'calculates the distance between two lat-lng coords in km' do expect(subject.to_km).to eq 12 end end context 'when passing nil as input data' do let(:to) { [nil, nil] } it 'raises a no method error' do expect { subject }.to raise_error NoMethodError end end context 'when passing blank strings as input data' do let(:to) { ['', ''] } it 'calculates the distance to zero' do expect(subject.to_km).to eq 4711 end end end
true
2e9c3cabd965b7d8a38dfe384018f7f9c2e9a529
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/triangle/b2441e1073c64cd2957529fa2525c54e.rb
UTF-8
767
3.46875
3
[]
no_license
class TriangleError < Exception end class Triangle def initialize(*sides) @sides = sides end def kind validate return :equilateral if equilateral? return :isosceles if isosceles? return :scalene if scalene? end def validate raise TriangleError if negative_or_zero_sides? || triangle_inequality? end def equilateral? @sides.combination(2).all? {|side1, side2| side1 == side2} end def isosceles? @sides.combination(2).any? {|side1, side2| side1 == side2} end def scalene? @sides.combination(2).none? {|side1, side2| side1 == side2} end def negative_or_zero_sides? @sides.any? {|side| side <= 0} end def triangle_inequality? @sides.permutation.any? {|a, b, c| a + b <= c} end end
true
0bfbb7a7d35147949bc94b3a4a5fb256c0c73294
Ruby
BookBub/ruby-freshbooks
/spec/freshbooks_spec.rb
UTF-8
2,554
2.828125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'lib/ruby-freshbooks' def build_xml(data) FreshBooks::Client.build_xml data, Builder::XmlMarkup.new(:indent => 2) end describe "XML generation:" do describe "simple hash" do it "should serialize correctly" do data = {"foo" => "bar"} build_xml(data).should == "<foo>bar</foo>\n" end end describe "simple hash with Fixnum value" do it "should serialize correctly, coercing to string" do data = {"foo" => 1} build_xml(data).should == "<foo>1</foo>\n" end end describe "simple hash value containing entity" do it "should serialize correctly, escaping entity" do data = {"foo" => "b&r"} build_xml(data).should == "<foo>b&amp;r</foo>\n" end end describe "nested hash" do it "should serialize correctly" do data = {"foo" => {"bar" => "baz"}} build_xml(data).should == "<foo>\n <bar>baz</bar>\n</foo>\n" end end describe "deeply nested hash" do it "should serialize correctly" do data = {"foo" => {"bar" => {"baz" => "bat"}}} build_xml(data).should == "<foo>\n <bar>\n <baz>bat</baz>\n </bar>\n</foo>\n" end end describe "array" do it "should serialize correctly" do data = [{"bar" => "baz"}, {"bar" => "baz"}] build_xml(data).should == "<bar>baz</bar>\n<bar>baz</bar>\n" end end describe "hash with array" do it "should serialize correctly" do data = {"foo" => [{"bar" => "baz"}, {"bar" => "baz"}]} build_xml(data).should == "<foo>\n <bar>baz</bar>\n <bar>baz</bar>\n</foo>\n" end end end describe "FreshBooks Client" do describe "instantiation" do it "should create a TokenClient instance when Connection.new is called" do c = FreshBooks::Connection.new('foo.freshbooks.com', 'abcdefghijklm') c.should be_a(FreshBooks::TokenClient) end end describe "proxies" do before(:each) do @c = FreshBooks::Connection.new('foo.freshbooks.com', 'abcdefghijklm') end it "should not hit API for single method send" do @c.should_not_receive(:post) @c.invoice end it "should hit API for normal double method send" do @c.should_receive(:post, "invoice.list").once @c.invoice.list end it "should not hit API for subordinate resource double method send" do @c.should_not_receive(:post) @c.invoice.lines end it "should hit API for subordinate resource triple method send" do @c.should_receive(:post, "invoice.items.add").once @c.invoice.lines.add end end end
true
c9b4abfcdec3f5f728e8a5acd40cc357c574d79e
Ruby
BaptisteIg/Ruby_start
/exo_07_c.rb
UTF-8
405
3.25
3
[]
no_license
user_name = gets.chomp puts user_name # gets.chomp permet la saisie pour l'utilisateur de la valeur à enregistrer dans la variable user_name. # La différence entre les 3 codes est l'interface utilisateur, le code b est le plus agréable à utiliser pour une interface homme-machine agréable. # L'autre différence est que la taille du code est plus conséquente a = 3lignes b= 4lignes et c = 2lignes
true
b16456073579c564b696caf8f21cebc2ee0de28c
Ruby
coolhead/chef-git
/hello.rb
UTF-8
601
3.296875
3
[]
no_license
puts "Hello World\n" bacon_type = 'crispy' 2.times do puts bacon_type temperature = 300 end x = "hello" puts "#{x} world" puts '#{x} world' <<METHOD_DESCRIPTION I Raghavendra learning Ruby for Chef. Currently I have the liability of home loan and personal loans, which I need to clear ASAP. METHOD_DESCRIPTION types = ['apple', 'mango', 'grapes'] puts types.length puts types.size types.push 'orange' puts types puts types[0] puts types[-1] puts types.first puts types.last #Hashes grades = { raghu: 99, rekha: 99.99, ravi: 99.9999 } puts grades[:raghu] puts grades[:rekha] puts grades[:ravi]
true
6f570e09981c1afe2bcffb604e9ec4ddb0b0ee6c
Ruby
SplitTime/OpenSplitTime
/spec/support/concerns/locatable.rb
UTF-8
2,618
2.625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# frozen_string_literal: true RSpec.shared_examples_for "locatable" do describe "#distance_from" do subject { described_class.new(latitude: 40, longitude: -105) } context "when subject and other have latitude and longitude" do let(:other) { described_class.new(latitude: 40.1, longitude: -105.1) } it "returns distance from other in meters" do expected = 14_003.34 expect(subject.distance_from(other)).to be_within(0.01).of(expected) end end context "when subject or other does not have latitude or longitude" do let(:other) { described_class.new(latitude: nil, longitude: nil) } it "returns nil" do expect(subject.distance_from(other)).to be_nil end end end describe "#different_location?" do subject { described_class.new(latitude: 40, longitude: -105) } context "when subject and other have latitude and longitude and distance is above the threshold" do let(:other) { described_class.new(latitude: 40.1, longitude: -105.1) } it "returns true" do expect(subject.different_location?(other)).to eq(true) end end context "when subject and other have latitude and longitude and distance is below the threshold" do let(:other) { described_class.new(latitude: 40.000001, longitude: -105.000001) } it "returns false" do expect(subject.different_location?(other)).to eq(false) end end context "when other has no latitude or longitude" do let(:other) { described_class.new(latitude: nil, longitude: nil) } it "returns nil" do expect(subject.different_location?(other)).to eq(nil) end end end describe "#same_location?" do subject { described_class.new(latitude: 40, longitude: -105) } context "when subject and other have latitude and longitude and distance is above the threshold" do let(:other) { described_class.new(latitude: 40.1, longitude: -105.1) } it "returns false" do expect(subject.same_location?(other)).to eq(false) end end context "when subject and other have latitude and longitude and distance is below the threshold" do let(:other) { described_class.new(latitude: 40.000001, longitude: -105.000001) } it "returns true" do expect(subject.same_location?(other)).to eq(true) end end context "when other has no latitude or longitude" do let(:other) { described_class.new(latitude: nil, longitude: nil) } it "returns nil" do expect(subject.same_location?(other)).to eq(nil) end end end end
true
0616dec571ccc4cb4b62988f2b927b63521c8155
Ruby
brenoperucchi/tdlib-ruby
/lib/tdlib/types/chat.rb
UTF-8
3,186
2.5625
3
[ "MIT" ]
permissive
module TD::Types # A chat. # (Can be a private chat, basic group, supergroup, or secret chat). # # @attr id [Integer] Chat unique identifier. # @attr type [TD::Types::ChatType] Type of the chat. # @attr title [String] Chat title. # @attr photo [TD::Types::ChatPhoto, nil] Chat photo; may be null. # @attr last_message [TD::Types::Message, nil] Last message in the chat; may be null. # @attr order [Integer] Descending parameter by which chats are sorted in the main chat list. # If the order number of two chats is the same, they must be sorted in descending order by ID. # If 0, the position of the chat in the list is undetermined. # @attr is_pinned [Boolean] True, if the chat is pinned. # @attr is_marked_as_unread [Boolean] True, if the chat is marked as unread. # @attr is_sponsored [Boolean] True, if the chat is sponsored by the user's MTProxy server. # @attr can_be_reported [Boolean] True, if the chat can be reported to Telegram moderators through reportChat. # @attr default_disable_notification [Boolean] Default value of the disable_notification parameter, used when a # message is sent to the chat. # @attr unread_count [Integer] Number of unread messages in the chat. # @attr last_read_inbox_message_id [Integer] Identifier of the last read incoming message. # @attr last_read_outbox_message_id [Integer] Identifier of the last read outgoing message. # @attr unread_mention_count [Integer] Number of unread messages with a mention/reply in the chat. # @attr notification_settings [TD::Types::ChatNotificationSettings] Notification settings for this chat. # @attr reply_markup_message_id [Integer] Identifier of the message from which reply markup needs to be used; 0 if # there is no default custom reply markup in the chat. # @attr draft_message [TD::Types::DraftMessage, nil] A draft of a message in the chat; may be null. # @attr client_data [String] Contains client-specific data associated with the chat. # (For example, the chat position or local chat notification settings can be stored here.) Persistent if a message # database is used. class Chat < Base attribute :id, TD::Types::Integer attribute :type, TD::Types::ChatType attribute :title, TD::Types::String attribute :photo, TD::Types::ChatPhoto.optional.default(nil) attribute :last_message, TD::Types::Message.optional.default(nil) attribute :order, TD::Types::Integer attribute :is_pinned, TD::Types::Bool attribute :is_marked_as_unread, TD::Types::Bool attribute :is_sponsored, TD::Types::Bool attribute :can_be_reported, TD::Types::Bool attribute :default_disable_notification, TD::Types::Bool attribute :unread_count, TD::Types::Integer attribute :last_read_inbox_message_id, TD::Types::Integer attribute :last_read_outbox_message_id, TD::Types::Integer attribute :unread_mention_count, TD::Types::Integer attribute :notification_settings, TD::Types::ChatNotificationSettings attribute :reply_markup_message_id, TD::Types::Integer attribute :draft_message, TD::Types::DraftMessage.optional.default(nil) attribute :client_data, TD::Types::String end end
true
60bf4bdeef7b1681225cccd079ac3209fc22793b
Ruby
LouisaBarrett/String-Calculator
/string_calculator.rb
UTF-8
324
3.375
3
[]
no_license
class StringCalculator def self.add(input) if input.include?("-") negs = input.scan(/-\d+/) raise "negatives not allowed, negatives passed: #{negs.join(', ')}" else numbers = input.split(/\n|,|\D/) numbers.inject(0) do |sum, number| sum + number.to_i end end end end
true
e875d74f5d4dfa50c5cc618faf87c214ee713eab
Ruby
pelf/euler
/p19.rb
UTF-8
1,014
3.828125
4
[]
no_license
# avoided using ruby's builtin date functions @@ldom = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] @@dom = 1 @@year = 1900 @@dow = 0 @@month = 0 @@count = 0 def next_day # day of week @@dow = (@@dow+1)%7 # day of month @@dom += 1 @@dom = 1 if end_of_month? # month @@month = (@@month+1)%12 if @@dom == 1 # year @@year += 1 if @@month == 0 and @@dom == 1 # How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? @@count += 1 if @@year >= 1901 and @@year <= 2000 and @@dom == 1 and @@dow == 6 end def end_of_month? return true if @@month != 1 and @@dom > @@ldom[@@month] return false if @@month != 1 # february return @@dom > 29 if @@year%4==0 and (@@year%100!=0 or @@year%400==0) # leap return @@dom > 28 end months = %w(jan feb mar apr may jun jul aug sep oct nov dec) daysow = %w(mon tue wed thu fri sat sun) loop do # puts "#{daysow[@@dow]} #{@@dom} #{months[@@month]} #{@@year}" next_day break if @@year == 2001 end puts @@count
true
3d54f71a3311ddb86271e7369bf0fafcdff6e80f
Ruby
paulghaddad/think_like_a_programmer_problems
/thinking_like_a_programmer/cheating_at_hangman_version_2/lib/cheater.rb
UTF-8
2,013
3.84375
4
[]
no_license
class Cheater attr_reader :word_set, :winning_word def initialize(word_set:, winning_word:) @word_set = word_set @winning_word = winning_word end def match?(letter) most_frequent_letter_count = patterns_by_count(letter).values.max words_without_letter_count = words_without_letter(letter).size most_frequent_letter_count > words_without_letter_count end def remove_words_matching_most_frequent_pattern(letter) most_frequent_pattern = most_frequent_pattern_by_letter(letter) word_set.inject(Set.new) do |updated_word_set, word| if matches_pattern?(most_frequent_pattern, word, letter) updated_word_set << word else updated_word_set end end end private def words_without_letter(letter) word_set.reject { |word| word.match(letter) } end def patterns_by_count(letter) word_length = word_set.first.length patterns = ["t", "f"].repeated_permutation(word_length).to_a.select { |pattern| pattern.include?("t") } pattern_count = patterns.inject({}) do |count, permutation| count[permutation.join.to_sym] = 0 count end pattern_count.each do |pattern, count| pattern_count[pattern] = word_count_matching_pattern(pattern, letter) end pattern_count end def word_count_matching_pattern(pattern, letter) count = 0 word_set.each do |word| if matches_pattern?(pattern, word, letter) count += 1 else count end end count end def matches_pattern?(pattern, word, letter) match = true pattern.to_s.each_char.with_index do |char, index| if char == "t" match = word[index] == letter else match = word[index] != letter end break unless match end match end def most_frequent_pattern_by_letter(letter) patterns_by_count(letter).max_by { |_pattern, count| count }.first end end
true
b1a7d19e811e4630dfa84dbdb196011ca7745af7
Ruby
Chekushkin/threeofnine
/lib/script.rb
UTF-8
7,175
2.640625
3
[]
no_license
require 'pry' require 'mail' require 'redis' require 'base64' require 'nokogiri' require 'open-uri' require 'digest/md5' require 'unicode_utils' require 'active_support' require 'active_support/core_ext' ARR_MOTH = [ 'января Январь', 'февраля Февраль', 'марта Март', 'апреля Апрель', 'мая Май', 'июня Июнь', 'июля Июль', 'августа Август', 'сентября Сентябрь', 'октября Октябрь', 'ноября Ноябрь', 'декабря Декабрь' ].freeze EMAIL = YAML.load_file(__dir__ + '/../config/secrets.yml')['email'] PASSWORD = YAML.load_file(__dir__ + '/../config/secrets.yml')['password'] NBSP = Nokogiri::HTML('&nbsp;').text # NOTE: ads should be in short description view html = Nokogiri::HTML(open(ARGV[0])) redis = Redis.new data = {} def self.get_index(string) string = UnicodeUtils.downcase(string) ARR_MOTH.each_with_index do |element, index| return index if UnicodeUtils.downcase(element).split.any? { |month| month[/#{string}/] } end ARR_MOTH.each_with_index do |element, index| return index if UnicodeUtils.downcase(element)[/#{string}/] end nil end def convert(string) date = string[/[a-z]+|[а-я]+/i] month_int = format('%02d', (get_index(date) + 1)) string.gsub(date, month_int) end def normalize_string(string) return '' if string.nil? string.gsub(NBSP, ' ').gsub(/[−–]/, '-').squeeze(' ').strip end def parse_description(string) normalize_string(string.gsub(/[\s]/, ' ')).split('.').map(&:capitalize).map(&:strip).join('. ') end counter = 0 html.css('table.ads-list-table tr').select do |tr| tr.css('.ads-list-table-price').present? && !tr.css('.ads-list-table-price').text.blank? end.each_with_index do |item, index| index = "item_#{index}".to_sym data[index] = {} data[index][:name] = parse_description(item.css('a').text) data[index][:price] = item.css('td.ads-list-table-price').text hash = Digest::MD5.hexdigest(Marshal.dump(data[index][:name] + data[index][:name])) next if redis.get(hash) redis.set(hash, '1') next if item.at_css('a')['href'][/booster/] html = Nokogiri::HTML(Net::HTTP.get(URI("https://999.md#{item.at_css('a')['href']}"))) # puts html.css('dd').detect { |dd| dd.text.match(/^\d{1,2}/) }.text.split(',').first date = Date.strptime(convert(html.css('dd').detect { |dd| dd.text.match(/^\d{1,2}\s/) }.text.split(',').first.delete('.')), '%d %m %Y') data[index][:price] = parse_description(html.at_css('ul.adPage__content__price-feature__prices').text) next if data[index][:price][/договорная/i] # NOTE: updating price to get convertion rates counter += 1 break if counter > 3 next if date < 1.week.ago.to_date # puts "https://999.md#{item.at_css('a')['href']}" # puts date.to_s data[index][:url] = "https://999.md#{item.at_css('a')['href']}" body = html.css('div.adPage__content__description.grid_18').text body = body.split('TAGS:').first if body.include?('TAGS:') data[index][:body] = parse_description(body) data[index][:pictures] = [] html.css('div.adPage__content__photos__item').each do |photo_src| data[index][:pictures] << photo_src.css('img').attr('src').value.gsub('160x120', '900x900') end lis = html.css('div.adPage__content__features__col.grid_9.suffix_1 li') data[index][:extra] = lis.each_with_object({}) do |li, hash| hash[parse_description(li.at_css('span').text)] = parse_description(li.css('span').last.text) end if html.css('dl.adPage__content__region.grid_18').present? data[index][:adress] = parse_description(html.css('dl.adPage__content__region.grid_18').text.gsub(/Регион:/, '')).gsub(' ,', ',') end unless html.css('div.adPage__content__features__col.grid_7.suffix_1 li').blank? data[index][:additional] = [] html.css('div.adPage__content__features__col.grid_7.suffix_1 li').each do |li| data[index][:additional] << parse_description(li.text) end end options = { address: 'smtp.gmail.com', port: 587, domain: 'your.host.name', user_name: EMAIL, password: PASSWORD, authentication: 'plain', enable_starttls_auto: true } Mail.defaults do delivery_method :smtp, options end b = binding mail = Mail.new do to(EMAIL) from(EMAIL) subject(data[index][:name] + ' 999 ads') end html_part = Mail::Part.new do content_type('text/html; charset=UTF-8') body(ERB.new(" <style> .header-big { font-family:'HelveticaNeue-UltraLight', 'HelveticaNeue-Light', 'Helvetica Neue Light', 'Helvetica Neue', Helvetica, Arial, 'Lucida Grande', sans-serif; font-size: 30px; color: #005284; } body { background-color: #e6e6e6; } .price-style { font-family: 'HelveticaNeue-Light', Arial; font-size: 35px; color: #ff0000; } .uri-style { font-family: 'HelveticaNeue-Light', Arial; font-size: 15px; color: #005284; } .adress-style { font-family: 'HelveticaNeue-Light', 'Open Sans', Arial; font-size: 20px; color: black; } .body-style { font-family: 'HelveticaNeue-Light', 'Open Sans', Arial; font-size: 15px; color: black; } </style> <div class='header-big' align='center'><%= data[index][:name] %></div> <div class='price-style' align='center'><%= data[index][:price] %></div> <div class='adress-style' align='center'><%= data[index][:url] %></div> <div class='uri-style' align='center'><%= data[index][:adress] %></div> <div class='body-style'><%= data[index][:body] %></div> <p></p> <table class='body-style' align='left'> <% unless data[index][:extra].blank? %> <% data[index][:extra].each do |key, value| %> <tr> <td> <%= key %> ... <%= value %> </td> <tr> <% end %> <% end %> </table> <table class='body-style' align='right'> <% unless data[index][:additional].blank? %> <% data[index][:additional].each do |item| %> <tr> <td><%= item %></td> <tr> <% end %> <% end %> </table> ", 0, '', 'abc').result(b)) end mail.part content_type: 'multipart/alternative' do |p| p.html_part = html_part end unless data[index][:pictures].blank? data[index][:pictures].each_with_index do |img_url, index| mail.attachments["#{index}.jpg"] = { mime_type: 'image/jpeg', content: open(img_url).read } end end mail.content_type = mail.content_type.gsub('alternative', 'mixed') mail.charset = 'UTF-8' mail.content_transfer_encoding = 'quoted-printable' mail.deliver! end
true
935d993b0171c3f2cfe496a2607cc3abcb8db0b0
Ruby
NikitaYaskin/RubyScreencasts
/7/conditions.rb
UTF-8
289
3.546875
4
[]
no_license
i = 1 if i >= 1 puts "number is greater than or equals 1" elsif i <= 1 puts "number is less than or equals 1" else puts "number equals 1" end puts "-" * 15 if i >= 1 puts "number is greater than or equals 1" end if i <= 1 puts "number is less than or equals 1" end
true
c44b6a17662cc9318829439ad1bc341182862c03
Ruby
yifeiwu/json_searcher
/lib/tokenizer.rb
UTF-8
526
3.15625
3
[ "MIT" ]
permissive
# takes an array of json and creates a dictionary set for each term consisting of the values from each entry module Tokenizer # creates a inverted index using the unparsed string value def self.simple_parse(entries) dictionary_set = {} entries.each_with_index do |entry, entry_index| entry.each do |field, value| dictionary_set[field.to_s] ||= {} # initialize the field dictionary (dictionary_set[field.to_s][value.to_s] ||= []) << entry_index end end dictionary_set end end
true
0fd1fa46aa89640e0cad1a843d54e84a7fb17e27
Ruby
mjester93/ruby-oo-practice-relationships-domains-wdc01-seng-ft-060120
/app/models/actors.rb
UTF-8
559
3.5
4
[]
no_license
class Actor attr_accessor :name @@all = [] def initialize(name) @name = name self.class.all << self end def self.all return @@all end def self.most_characters max_appearances = -1 max_name = nil self.all.each do |actor| curr_actor_count = Character.all.count(actor) if curr_actor_count > max_appearances max_appearances = curr_actor_count max_name = actor end end return max_name end end
true
0b62ade3732392a59b5aa3d6b8514adf5970c02e
Ruby
yonjinkoh/assignment5
/testmatrix.rb
UTF-8
535
3.25
3
[]
no_license
#this is to test symmetry. require 'Matrix' our_matrix = Matrix[[0, 1, 1, 1, 0, 0], [1, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 0], [0, 1, 0, 0, 1, 1], [0, 0, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0]] m_array = our_matrix.to_a our_matrix.each_with_index do |e, row, col| # puts "#{e} at #{row}, #{col}" # puts our_matrix[col, row] unless e == our_matrix[col, row] if e == 0 # puts row, col # puts our_matrix[col,row] m_array[col][row] = 0 elsif e == 1 m_array[row][col] = 0 end end end new_matrix = Matrix.row(m_array)
true
64d9199b1fd289035022264624087498c068f9f3
Ruby
osdakira/bitwise_enum
/lib/bitwise_enum.rb
UTF-8
4,659
3.171875
3
[ "MIT" ]
permissive
require 'active_record/base' require "bitwise_enum/version" # Clone from `ActiveRecord::Enum`. # # Declare an bitwise enum attribute where the values map to integers in the database, but can be queried by name. Example: # # class User < ActiveRecord::Base # bitwise_enum role: [ :admin, :worker ] # end # # # user.update! role: "admin" # user.admin! # user.admin? # => true # user.role # => "['admin']" # # # user.update! role: "worker" # user.worker! # user.worker? # => true # user.role # => "['worker']" # # user.admin! # user.admin? # => true # user.worker! # user.worker? # => true # user.role # => "['admin', 'worker']" # # user.admin! # user.admin? # => true # user.not_admin! # user.admin? # => false # # # user.update! role: 1 # user.role = :admin # user.role # => ['admin'] # # user.admin! # => ['admin'] # user.reset_role # => nil # user.role = [] # # Finally, it's also possible to explicitly map the relation between attribute and # database integer with a +Hash+: # # class User < ActiveRecord::Base # enum role: { admin: 1 << 0, worker: 1 << 1 } # end # # Note that when an +Array+ is used, the implicit mapping from the values to database # integers is derived from the order the values appear in the array. In the example, # <tt>:admin</tt> is mapped to +0b1+ as it's the first element, and <tt>:worker</tt> # is mapped to +0b10+. In general, the +i+-th element is mapped to <tt>1 << i-1</tt> in the # database. # # Therefore, once a value is added to the enum array, its position in the array must # be maintained, and new values should only be added to the end of the array. To # remove unused values, the explicit +Hash+ syntax should be used. # # In rare circumstances you might need to access the mapping directly. # The mappings are exposed through a constant with the attributes name: # # User::ROLE # => { "admin" => 1, "worker" => 2 } # # Use that constant when you need to know the ordinal value of an enum: # # User.where("role <> ?", User::ROLE[:worker]) # # A scope call bitwise 'SELECT' sql # module BitwiseEnum def bitwise_enum(definitions) klass = self definitions.each do |name, values| # DIRECTION = { } bitwise_enum_values = _bitwise_enum_methods_module.const_set name.to_s.upcase, ActiveSupport::HashWithIndifferentAccess.new name = name.to_sym _bitwise_enum_methods_module.module_eval do # def role=(value) self[:role] = ROLE[value] end define_method("#{name}=") { |value| if bitwise_enum_values.has_key?(value) bit = bitwise_enum_values[value] self[name] = self[name].nil? ? bit : (self[name] |= bit) elsif value.is_a?(Integer) && value <= bitwise_enum_values.values.inject(:+) self[name] = value else raise ArgumentError, "'#{value}' is not a valid #{name}" end } # def role() ROLE.select{|_, bit| !(self[:role] & bit).zero?}.keys end define_method(name) { return [] if self[name].nil? bitwise_enum_values.select{|k, bit| !(self[name] & bit).zero?}.keys } # def reset_role(); self[:role] = nil; end define_method("reset_#{name}"){ self[name] = nil } # bitwise index pairs = values.respond_to?(:each_pair) ? values.each_pair : values.map.with_index{|value, index| [value, 1 << index]} pairs.each do |value, bit| bitwise_enum_values[value] = bit # scope :admin, -> { where("role & 1 = 0") } # FIXME use arel klass.scope value, -> { klass.where("#{name} & #{bit} = #{bit}") } klass.scope "not_#{value}", -> { klass.where("#{name} IS NULL OR #{name} & #{bit} = 0") } # def admin?() role == 1 end define_method("#{value}?") do self[name].nil? ? false : !(self[name] & bit).zero? end define_method("not_#{value}?") do self[name].nil? ? true : (self[name] & bit).zero? end # def admin! update! role: :admin end define_method("#{value}!") do update! name => self[name].nil? ? bit : (self[name] |= bit) end define_method("not_#{value}!") do update! name => self[name] &= ~bit if self[name] end end end end end private def _bitwise_enum_methods_module @_bitwise_enum_methods_module ||= begin mod = Module.new include mod mod end end end # Extend ActiveRecord's functionality ActiveRecord::Base.send :extend, BitwiseEnum
true
1cfec2373bc4f7b7d94e71d12ac05af9760924a9
Ruby
Bigproblems55/sms_carrier
/lib/sms_carrier/test_case.rb
UTF-8
2,425
2.5625
3
[ "MIT" ]
permissive
require 'active_support/test_case' module SmsCarrier class NonInferrableCarrierError < ::StandardError def initialize(name) super "Unable to determine the carrier to test from #{name}. " + "You'll need to specify it using tests YourCarrier in your " + "test case definition" end end class TestCase < ActiveSupport::TestCase module Behavior extend ActiveSupport::Concern include ActiveSupport::Testing::ConstantLookup include TestHelper included do class_attribute :_carrier_class setup :initialize_test_deliveries setup :set_expected_sms teardown :restore_test_deliveries end module ClassMethods def tests(carrier) case carrier when String, Symbol self._carrier_class = carrier.to_s.camelize.constantize when Module self._carrier_class = carrier else raise NonInferrableCarrierError.new(carrier) end end def carrier_class if carrier = self._carrier_class carrier else tests determine_default_carrier(name) end end def determine_default_carrier(name) carrier = determine_constant_from_test_name(name) do |constant| Class === constant && constant < SmsCarrier::Base end raise NonInferrableCarrierError.new(name) if carrier.nil? carrier end end protected def initialize_test_deliveries # :nodoc: set_delivery_method :test @old_perform_deliveries = SmsCarrier::Base.perform_deliveries SmsCarrier::Base.perform_deliveries = true end def restore_test_deliveries # :nodoc: restore_delivery_method SmsCarrier::Base.perform_deliveries = @old_perform_deliveries SmsCarrier::Base.deliveries.clear end def set_delivery_method(method) # :nodoc: @old_delivery_method = SmsCarrier::Base.delivery_method SmsCarrier::Base.delivery_method = method end def restore_delivery_method # :nodoc: SmsCarrier::Base.delivery_method = @old_delivery_method end def set_expected_sms # :nodoc: @expected = Sms.new end end include Behavior end end
true
5ea8e9e8c6cc0c84d24e6fc7e42178b727d065d0
Ruby
sitrox/inquery
/lib/inquery/query.rb
UTF-8
1,392
2.515625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
module Inquery class Query include Mixins::SchemaValidation include Mixins::RawSqlUtils attr_reader :params # Instantiates the query class using the given arguments # and runs `call` and `process` on it. def self.run(*args) new(*args).run end # Instantiates the query class using the given arguments # and runs `call` on it. def self.call(*args) new(*args).call end # Instantiates the query class and validates the given params hash (if there # was a validation schema specified). def initialize(params = {}) @params = params if _schema @params = _schema.validate!(@params) end end # Runs both `call` and `process`. def run process(call) end # Override this method to perform the actual query. def call fail NotImplementedError end # Override this method to perform an optional result postprocessing. def process(results) results end # Returns a copy of the query's params, wrapped in an OpenStruct object for # easyer access. def osparams @osparams ||= OpenStruct.new(params) end # Provides a connection to the database. May be overridden if a different # connection is desired. Defaults to `ActiveRecord::Base.connection`. def connection ActiveRecord::Base.connection end end end
true
c6ee8f9eb67a1ee5426fba8bd4c1f05af111e612
Ruby
Sahana27/Ruby-Learning
/Ruby_assignment/page_two.rb
UTF-8
2,601
2.90625
3
[]
no_license
#!/usr/bin/ruby $LOAD_PATH.unshift("/usr/local/rvm/gems/ruby-1.9.3-p547/gems/ruby-mysql-2.9.12/lib") require 'mysql' require 'cgi' cgi = CGI.new puts cgi.header #create connection to Mysql def create_connection() con = Mysql.new 'localhost', 'cloudera','', 'chartsearch' #opening a connection with Mysql return con end #Drop table if table exist def drop_table(con) con.query("DROP TABLE IF EXISTS \ Reports") end #create table def create_table(con) con.query("CREATE TABLE IF NOT EXISTS \ Reports(CLIENT_NAME varchar(50), RAW int, RAW_INPROCESS int, RAW_COMPLETED int, PROCESSED int, PROCESSED_UPLOADING int, PROCESSED_COMPLETED int)") end #inserts values to the table def insert_values(con,fields) con.query("INSERT INTO Reports(CLIENT_NAME, RAW, RAW_INPROCESS, RAW_COMPLETED, PROCESSED, PROCESSED_UPLOADING, PROCESSED_COMPLETED) VALUES('#{fields[0]}', '#{fields[1]}', '#{fields[2]}', '#{fields[3]}', '#{fields[4]}', '#{fields[5]}', '#{fields[6]}')") end #close the connection def close_conn(con) con.close end #Retrieves client name def get_clientname(con) con.query("select CLIENT_NAME from Reports") end begin con=create_connection() drop_table(con) create_table(con) value = cgi['year'] puts "<html>" puts "<head>" puts "<div style=\"width: 100%; font-size: 20px; font-weight: italic; text-align: center;\">\n" puts "<center> <b><h2>DATA PROCESSING ANALYSIS OF CHARTSHEET</b> </center>" puts "</head>" puts "<body>" if(value == '2013') csv = File.open("report1.csv","r") else csv = File.open("report2.csv","r") end #Read from csv file and store into table flag = true if(csv) #if the file exists csv.each_line do |line| fields = line.split(',') if flag == true flag = false next end insert_values(con,fields) end end con=create_connection() rs =get_clientname(con) puts "<form method='get' action=\'analysis.rb?clients=value\'>" puts "<b>Client Name</b>" puts "<select name=\"clients\">" #adds to the dropdownbox rs.each do |x| puts "<option value=#{x}>#{x}</option>" #adding the client names to the dropdown end puts "</select>" puts "<input type=\"submit\" value=\"Display the Analysis\"/>" puts "</form>" puts "<div align=\"right\"><a href=\"page_one.rb\">Go Back,To Select another Year</a></div>" puts "</div>" puts "</body>" puts "</html>" rescue Mysql::Error => e #To handle MySQL exceptions puts e.errno puts e.error ensure close_conn(con) if con #close the Mysql connection end
true
7bb539b67478ad8e1478b84b03a37810dbe92fe1
Ruby
christiebelle/Snowman-of-doom
/game.rb
UTF-8
616
3.5625
4
[]
no_license
class Game def initialize(players, word) @playas = players @word = word @guessed_letters = [] end def player_details return "#{@name} has #{@lives} lives" end end # MVP # # A Game will have properties for a Player object, # a HiddenWord object, and an array of guessed_letters # A Player will have a name and number of lives # A HiddenWord will be initialised with a word string, # but will only display letters which have been correctly # guessed, replacing the rest with the * character # The HiddenWord should also be able to report true or # false if a letter appears in the word
true
af5f89bf6d2c6cbdcad0617002d980c58bcebde4
Ruby
T-monius/ruby_small_problems
/easy_9/name_swapping.rb
UTF-8
369
4.125
4
[]
no_license
# name_swapping.rb # Write a method that takes a first name, a space, and a last name passed # as a single String argument, and returns a string that contains the last # name, a comma, a space, and the first name. def swap_name(str) arr = str.split "#{arr[1]}, #{arr[0]}" end # Examples puts swap_name('Joe Roberts') == 'Roberts, Joe' puts swap_name('Torrel Moseley') == 'Moseley, Torrel'
true
c6158f95b8b5bf9b556e57e0aaa9b89c4bfd1296
Ruby
mega0319/key-for-min-value-web-031317
/key_for_min.rb
UTF-8
401
3.671875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# prereqs: iterators, hashes, conditional logic # Given a hash with numeric values, return the key for the smallest value def key_for_min_value(name_hash) smallest_number = "" new_value = 10000000000000 key_house = nil name_hash.each do |key, value| if new_value > value smallest_number = value new_value = smallest_number key_house = key end end key_house end
true
d96fab0643e767167fc5ac8b49b5e51aec788445
Ruby
sunaynab/AppAcademyProjects
/W2D1/class_inheritance.rb
UTF-8
1,101
3.609375
4
[]
no_license
class Employee attr_reader :salary def initialize(name, title, salary, boss) @name = name @title = title @salary = salary @boss = boss end def bonus(multiplier) salary * multiplier end end class Manager < Employee def initialize(name, title, salary, boss, employees) super(name, title, salary, boss) @employees = employees end def bonus(multiplier) total_salary_of_employees * multiplier end def total_salary_of_employees sub_salaries = [] @employees.each do |employee| if employee.class == Manager sub_salaries << employee.salary sub_salaries << employee.total_salary_of_employees else sub_salaries << employee.salary end end sub_salaries.reduce(:+) end end david = Employee.new("David","TA",10000,"darren") shawna = Employee.new("Shawna","TA",12000,"darren") darren = Manager.new("Darren","TA manager",78000,"Ned",[shawna, david]) ned = Manager.new("Ned","Founder",100000,nil,[darren]) p ned.bonus(5) # => 500_000 p darren.bonus(4) # => 88_000 p david.bonus(3) # => 30_000
true
519e813e3f102f8f931f050c8693c9c0058308a3
Ruby
wwilco/week9
/d01/hogwarts/server.rb
UTF-8
692
2.859375
3
[]
no_license
require 'sinatra' students = { 0 => { id: 0, name: "Harry Potter", age: 26, spell: "Pow!" } } counter = 1 get '/students' do erb :index, locals:{students: students} end post '/student' do newstudent = { id: counter, name: params["name"], age: params["age"], spell: params["spell"] } students[counter] = newstudent counter += 1 redirect '/students' end get '/students/:id' do thiswiz = students[params[:id].to_i] erb :next, locals: {thiswiz: thiswiz} end delete '/students/:id' do students.delete(params[:id].to_i) redirect '/students' end get '/search' do name_search = students[params[:name] (erb :search, {locals: name_search}) end
true
436aba3f4f8143ea650067677ed90e71c0f1ff06
Ruby
novarac23/ror-techfleet-class
/week-1/day-2-non-exercise/comparables.rb
UTF-8
1,531
4.28125
4
[]
no_license
a = "something" b = 1 c = nil d = false e = 5 f = true # && operator only works if BOTH values are true puts "&& operator --------" if a && b puts "I AM TRUE" else puts "I AM false" end if a && d puts "I AM TRUE" else puts "I AM false" end puts "----------------" # || operator allows the code to be executed as soon as one value is true puts "|| operator --------" if a || c puts "I AM TRUE" else puts "I AM false" end if a || b puts "I AM TRUE" else puts "I AM false" end if c || d puts "I AM TRUE" else puts "I AM false" end puts "----------------" # > < operators compare if two values are greater or less then puts "> < operator --------" if e > b puts "I AM TRUE" else puts "I AM false" end if e < b puts "I AM TRUE" else puts "I AM false" end puts "----------------" # >= <= operators do the same thing as operators above except they also compare if it's the same value (equal) puts ">= <= operator --------" if e >= b puts "I AM TRUE" else puts "I AM false" end if e >= e puts "I AM TRUE" else puts "I AM false" end if b <= e puts "I AM TRUE" else puts "I AM false" end puts "----------------" # == operators is true if both sides are equal puts "== operator --------" if e == b puts "I AM TRUE" else puts "I AM false" end if e == e puts "I AM TRUE" else puts "I AM false" end puts "----------------" # ! operator reverse the value puts !f puts !d #OR # 1 = true # 0 = false # # 1 || 1 = true # 1 || 0 = true # 0 || 1 = true # 0 || 0 = false
true
92b4d3c2213791516752bbf7d087261da57bdf3f
Ruby
gdistasi/omf-tools
/graphs/calc.rb
UTF-8
1,719
3.28125
3
[]
no_license
#!/usr/bin/env ruby # The script merges two dat files produced by ITGDec by summing up the Aggregate-flow columns of the two files require 'getoptlong' values = Array.new times = Array.new def usage() puts "sum.rb --sum|--average [--skipline] file0.dat file1.dat [file2.dat, ...]" end if ARGV.size<2 usage() exit 1 end if ARGV[0]=="--sum" dosum=true elsif ARGV[0]=="--average" doaverage=true else usage() exit(1) end ARGV.delete_at(0) if ARGV[0]=="--skipline" skipline=true ARGV.delete_at(0) # $stderr.write "Skipping first line\n" else skipline=false end files=Array.new #open all the files ARGV.each do |filename| files << File.open(filename) end numFiles=files.size #read the first line for all the files if (skipline) files.each do |file| file.gets end end #merge the files files[0].each_line do |line| #start writing the time lineEl=line.split(" ") time=lineEl[0] sum=Float(lineEl[-1].chomp) #then write the samples from the files files[1,files.size-1].each do |file| lineTemp=file.gets if (lineTemp==nil) $stderr.write("Warning: reached the end file #{ARGV[files.index(file)]} \n") file.close() files.delete(file) next end lineEl=lineTemp.split(" ") timeN=lineEl[0] if (timeN!=time) $stderr.write "Error: time samples do not coincide\n" end sum=sum+Float(lineEl[-1]) end times << time values << sum end files.each do |file| file.close() end #Writing result on the stdout #puts "Time Aggregate-Flows" i=0 times.each do |time| if (dosum) puts "#{time} #{values[i]}" else puts "#{time} #{values[i]/numFiles}" end i=i+1 end
true
293014d5ffab563429c56310da9cf6403d4a24d6
Ruby
verg/dinner_dash
/spec/models/cart_spec.rb
UTF-8
2,012
2.59375
3
[]
no_license
require 'spec_helper' describe Cart do it { should have_many(:line_items) } it { should belong_to(:user) } describe ".add_product" do it "adds a line item to the cart for the product" do cart = Cart.create product = create(:product) cart.add_product(product) expect(cart.line_items.first.product_id).to eq product.id end end describe "#total_price" do it "sums the total prices for each of its line items" do cart = Cart.create food = create(:product, price_cents: 350) drink = create(:product, price_cents: 150) cart.add_product(food) cart.add_product(drink) expect(cart.total_price).to eq Money.new(350+150, "USD") expect(cart.total_price_cents).to eq 500 end end describe "#count" do it "returns the number of line_items in the cart" do cart = Cart.create food = create(:product, price_cents: 350) drink = create(:product, price_cents: 150) cart.add_product(food) cart.add_product(drink) cart.add_product(drink) expect(cart.count).to eq 3 end end describe "#increment_quantity_or_create_line_item_by_product_id" do let(:product_id) { 1 } context "a line item exists for that cart and product" do it "increments a line item's quantity" do cart = Cart.create cart.line_items << create(:line_item, product_id: 1, quantity: 1) item = cart.increment_quantity_or_create_line_item_by_product_id(product_id, 2) expect(item.quantity).to eq 1 + 2 end end context "a line item doesn't exist" do it "creates a new line item with the specified quantity and product id" do cart = Cart.create item = nil # initialize var so we can access outside of expect block expect { item = cart.increment_quantity_or_create_line_item_by_product_id(product_id, 2) }.to change(LineItem, :count).by(1) expect(item.quantity).to eq 2 end end end end
true
6eb8a4111949b790da7b4e0bf21815bba8da877b
Ruby
LagoLunatic/DSVEdit
/dsvedit/clickable_graphics_scene.rb
UTF-8
860
2.65625
3
[ "MIT" ]
permissive
class ClickableGraphicsScene < Qt::GraphicsScene BACKGROUND_BRUSH = Qt::Brush.new(Qt::Color.new(240, 240, 240, 255)) signals "clicked(int, int, const Qt::MouseButton&)" signals "moved(int, int, const Qt::MouseButton&)" signals "released(int, int, const Qt::MouseButton&)" def initialize super self.setBackgroundBrush(BACKGROUND_BRUSH) end def mousePressEvent(event) x = event.scenePos().x.to_i y = event.scenePos().y.to_i emit clicked(x, y, event.buttons) super(event) end def mouseMoveEvent(event) x = event.scenePos().x.to_i y = event.scenePos().y.to_i emit moved(x, y, event.buttons) super(event) end def mouseReleaseEvent(event) x = event.scenePos().x.to_i y = event.scenePos().y.to_i emit released(x, y, event.button) super(event) end end
true
2c31ebe20840469c9cbdfa9503dd0a83af245395
Ruby
lisaychuang/ruby-collaborating-objects-lab-v-000
/lib/song.rb
UTF-8
510
3.21875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Song attr_accessor :name, :artist def initialize(song) @name = song end def artist= (artist) @artist = artist end def artist @artist end def self.new_by_filename(filename) #=> filename = "Thundercat - For Love I Come - dance.mp3" song_file = filename.split(" - ") new_song = self.new(song_file[1]) new_artist = Artist.find_or_create_by_name(song_file[0]) new_song.artist = new_artist new_song.artist.songs << new_song new_song end end
true
73939aaf211e05dc553cdead86537c80a998064d
Ruby
scotthuston82/object_oriented_programming
/exercise2.rb
UTF-8
134
3.359375
3
[]
no_license
require './cat.rb' one = Cat.new("izzy", "pate", 8) two = Cat.new("bob", "kibble", 19) puts one.eats_at puts one.meow puts two.meow
true
83b079c70365842d8abbdea827fd886d7b56434d
Ruby
jywei/ruby-toys
/OOP_file/file_operator.rb
UTF-8
614
3.03125
3
[]
no_license
require_relative 'file_reader' require_relative 'csv_reader' require_relative 'yml_reader' require_relative 'json_reader' # x = FileReader.new('sample.txt') # x = FileReader.new(ARGV[0]) # puts x.read # FileReader.new(ARGV[0]).read # CsvReader.new(ARGV[0]).read # YmlReader.new(ARGV[0]).read # JsonReader.new(ARGV[0]).read FILENAME = ARGV[0] def file_extension(filename) filename.split('.').last end def reader_class ext = file_extension(FILENAME) return CsvReader if ext == 'csv' return YmlReader if ext == 'yml' return JsonReader if ext == 'json' FileReader end reader_class.new(FILENAME).read
true
0b02e8bd4b99481bc4ff69c4530e7fbb127b7e8d
Ruby
javomorales/BiciMadAnalysis
/Code/FalloBicis.rb
UTF-8
1,998
3.03125
3
[]
no_license
# --------------------- # Saber cuántas veces se deja una bici en la misma estación # Es decir, la bici funciona mal # Recoge datos de los fichero .json de opendata de EMT que se le pasen # # EJECUTAR: # ruby FalloBici.rb FICHERO_W FICHEROs_R # # EJEMPLOs: # ruby FalloBici.rb DejarBiciMismaEstacion.csv 201806_Usage_Bicimad.json # ruby DejarBiciMismaEstacion.rb DejarBiciMismaEstacion.csv 201704_Usage_Bicimad.json 201705_Usage_Bicimad.json 201706_Usage_Bicimad.json 201706_Usage_Bicimad.json 201707_Usage_Bicimad.json 201708_Usage_Bicimad.json 201709_Usage_Bicimad.json 201710_Usage_Bicimad.json 201711_Usage_Bicimad.json 201712_Usage_Bicimad.json 201801_Usage_Bicimad.json 201802_Usage_Bicimad.json # # --------------------- require 'json' if ARGV.length == 0 puts "**************************" puts "Need to type json file to read data from and a file to write the data as an argument" puts "**************************" exit end file_w = File.open(ARGV[0], "a") cont = 1 while (cont < ARGV.length) puts "***********************************************" puts "------ Veces que alguien deja la bici en la misma estación al mes -------" puts "--------- #{ARGV[cont]} -----------------" puts "***********************************************" # Veces que alguien deja la bici en la misma estación -> se entiende que porque está mal contador = 0 fecha_ini = "" File.open(ARGV[cont], "r").each do |line| data = JSON.parse(line) if data["unplug_hourTime"]["$date"][0..9] != fecha_ini if fecha_ini != "" puts "#{fecha_ini} #{contador}" file_w.write("#{fecha_ini} #{contador} \n") end fecha_ini = data["unplug_hourTime"]["$date"][0..9] contador = 0 else if data["idunplug_station"] == data["idplug_station"] contador = contador + 1 end end end puts "#{fecha_ini} #{contador}" file_w.write("#{fecha_ini} #{contador} \n") # en junio -> 10.114 cont = cont+1 end
true
75a8e16a949743fc5b5aa7cefe81b92578317818
Ruby
CristianAbrante/NutritionalCalculator
/lib/nutritional_calculator/food.rb
UTF-8
3,823
3.5
4
[ "MIT" ]
permissive
module NutritionalCalculator # Esta clase representa a un alimento de manera abstracta. # Contiene su nombre y su información nutricional. # Se ha incluido el módulo Comparable. class Food # valor nutricional de las proteinas: <b>4.0</b> PROTEINS_VALUE = 4.0 # Valor nutricional de los glúcidos: <b>4.0</b> CARBOHYDRATE_VALUE = 4.0 # Valor nutricional de los lípidos: <b>9.0</b> LIPIDS_VALUE = 9.0 attr_reader :name, :proteins, :carbohydrates, :lipids, :glucose_concentration include Comparable # Constructor. # @param name [String] Nombre del alimento que queremos representar. # @param proteins [float] Gramos de proteína que contiene el alimanto. # @param carbohydrates [float] Gramos de glúcidos que contiene el alimanto. # @param lipids [float] Gramos de lípidos que contiene el alimanto. # @param glucose_concentration[Array[Array[float]]] listas de concentraciones de glucosa tras la ingesta del alimento para varios individuos. # @param glucose[Food] objeto glucosa de la clase Food, necesario para hacer los cálculos. Si el valor es nulo entonces es el objeto glucosa. def initialize(name, proteins, carbohydrates, lipids, glucose_concentration = nil, glucose = nil) @name = name @proteins = proteins @carbohydrates = carbohydrates @lipids = lipids @glucose_concentration = glucose_concentration @glucose = glucose end # Método que transforma el objeto en un String. # De esta forma será formateado por pantalla. # @return [String] String con el objeto formateado. def to_s "#{@name} -> proteínas(#{@proteins}) glúcidos(#{@carbohydrates}) lípidos(#{@lipids})" end # Método que devuelve el valor nutricional del alimento. # El valor nutricional se calcula como la suma del producto # de los valores nutricionales de los macronutrientes por los gramos # de dicho macronutriente presente en el alimento. # @return [float] Valor nutricional del alimento def get_nutritional_value @proteins * PROTEINS_VALUE + @carbohydrates * CARBOHYDRATE_VALUE + @lipids * LIPIDS_VALUE end # Método que permite hacer al alimento Comparable. # En mi caso el criterio de comparación ha sido el valor # nutricional del alimento. # @param other [NutritionalCalculator::Food] alimento con el cual queremos comparar el alimento. def <=> (other) get_nutritional_value <=> other.get_nutritional_value end # Método que permite calcular el área incremental bajo la curva de las mediciones de glucosa de un alimento. # Se ha realizado mediante programación funcional. # @param individual [int] Individuo para el cual queremos calcular el AIBC del alimento. def aibc(individual) (1..24).lazy.map { |i| s_value(individual, i) }.map { |j| (5.0 / 2.0) * j }.reduce('+') end # Método que calcula el índice glucémico del alimento para un individuo concreto. # Se ha realizado mediante programación funcional. # @param individual [int] Individuo para el cual queremos calcular el índice glucémico del alimento. def individual_glycemic_index(individual) 100.0 * (aibc(individual) / @glucose.aibc(individual)) end # Método que calcula el índice glucémico del alimento, haciendo la media del índice glucémico para los individuos. def glycemic_index (0...@glucose_concentration.size).map { |i| individual_glycemic_index(i) }.instance_eval { reduce('+') / size.to_f} end def weight @proteins + @carbohydrates + @lipids end private def s_value(individual, i) @glucose_concentration[individual][i] + @glucose_concentration[individual][i - 1] - 2 * @glucose_concentration[individual][0] end end end
true
f73aa828bd5c210513ad7fa6857f1f2c8e6c3dc5
Ruby
gerdadecio/bitmap_editor
/spec/commands/colour_spec.rb
UTF-8
1,655
2.953125
3
[]
no_license
require 'bitmap' require 'commands/create' require 'commands/colour' describe Commands::Colour do let(:bitmap) { Bitmap.new } let(:x) { 2 } let(:y) { 3 } let(:colour) { 'N' } subject { described_class.new(bitmap, x, y, colour) } before do Commands::Create.new(bitmap, 5, 6).execute end describe '.initialize' do context 'when passing a valid argument' do it { expect(subject.bitmap).to eq(bitmap) } end context 'when passing an invalid argument' do it { expect{described_class.new}.to raise_error(ArgumentError) } end end describe '#execute' do context 'when valid arguments' do let(:expected_array) { [ ['O','O','O','O','O'], ['O','O','O','O','O'], ['O','N','O','O','O'], ['O','O','O','O','O'], ['O','O','O','O','O'], ['O','O','O','O','O'] ] } before { subject.execute } it 'fills the bitmap image on the specified coordinates' do expect(subject.bitmap.image).to eq expected_array end end end describe '#valid?' do context 'when @bitmap is not a Bitmap object' do it 'raises Errors::InvalidObject' do expect(described_class.new('StringSample', x, y, colour).valid?).to eq false end end context 'when x coordinate is invalid' do it 'returns false' do expect(described_class.new(bitmap, 'a', y, colour).valid?).to eq false end end context 'when y coordinate is invalid' do it 'returns false' do expect(described_class.new(bitmap, x, 'b', colour).valid?).to eq false end end end end
true
20c3600317ff6408fb9ba7d8b32dc05c1aa32345
Ruby
recyclery/vtracklery
/test/models/worker_test.rb
UTF-8
2,947
2.640625
3
[]
no_license
require 'test_helper' class WorkerTest < ActiveSupport::TestCase test "sum_time_in_seconds" do w = Worker.create(name: "test worker", status_id: 1, work_status_id: 1) start_at = DateTime.new(2008, 10, 11, 1, 0) end_at = DateTime.new(2008, 10, 11, 1, 30) # 30 minutes later wt = w.work_times.create(start_at: start_at, end_at: end_at) assert_equal 1, wt.status_id, 'Should inherit status from worker' assert_equal 1, wt.work_status_id, 'Should inherit work_status from worker' # Only 30 minutes (1800 s) of work was done in that day since only 1 entry assert_equal 1800, w.sum_time_in_seconds(start_at, end_at) end test "phone methods" do w = Worker.create(name: "test worker", status_id: 1, work_status_id: 1, phone: "312.555.1212") assert_equal "(312) 555-1212", w.shoehorn_phone assert_equal ["312", "555", "1212"], w.normalize_phone("(312) 555-1212") assert_equal ["312", "555", "1212"], w.normalize_phone("1-312-555-1212") assert_equal ["312", "555", "1212"], w.normalize_phone(" 1-312-555-1212") assert_equal ["312", "555", "1212"], w.normalize_phone("312-555-1212") assert_equal ["312", "555", "1212"], w.normalize_phone("312/555-1212") assert_equal ["312", "555", "1212"], w.normalize_phone("3125551212") assert_equal ["312", "555", "1212"], w.normalize_phone("(312)555-1212") assert_nil w.normalize_phone("5551212") end test "youth_points" do youth_work_status = WorkStatus.create(name: WorkStatus::YOUTHPOINTS) paid_work_status = WorkStatus.create(name: WorkStatus::PAID) youth = Worker.create(name: "youth worker", status_id: 1, work_status: youth_work_status) paid_worker = Worker.create(name: "youth worker", status_id: 1, work_status: paid_work_status) youth_points_time = WorkTime.create(work_status: youth_work_status, worker: youth, status_id: 1, start_at: Time.now - 5.hours, end_at: Time.now - 1.hours) youth_paid_time = WorkTime.create(work_status: paid_work_status, worker: youth, status_id: 1, start_at: Time.now - 6.hours, end_at: Time.now - 4.hours) paid_worker_paid_time = WorkTime.create(work_status: paid_work_status, worker: paid_worker, status_id: 1, start_at: Time.now - 4.hours, end_at: Time.now - 2.hours) assert_equal youth.youth_points, 4, "should only count youth points worktimes" assert_equal paid_worker.youth_points, 0, "should be zero for non-youth" YouthPointPurchase.create(worker: youth, points: 1) YouthPointPurchase.create(worker: youth, points: 2) assert_equal youth.youth_points, 1, "should deduct youth point purchases" end test "youth?" do youth_status = Status.create(name: "Youth") youth = Worker.create(name: "youth worker", status: youth_status, work_status_id: 1) paid_worker = Worker.create(name: "youth worker", status_id: 1, work_status_id: 1) assert youth.youth? assert !paid_worker.youth? end end
true
5e278b714f00279c8848f6584d1f048717068e97
Ruby
pdg137/hangman
/lib/move.rb
UTF-8
433
3.375
3
[]
no_license
class Move attr_reader :guess, :pattern def self.guess(guess) Move.new(nil, guess) end def self.pattern(pattern) Move.new(pattern, nil) end def to_s if @pattern "respond with #{@pattern}" else "guess #{@guess}" end end private def initialize(pattern, guess) raise 'only one of pattern, guess allowed' if @pattern && @guess @pattern = pattern @guess = guess end end
true
067a7819b0797c08c5a63c6ee2b43bc3fb2a8cf3
Ruby
kyatul/ExercismRuby
/simple-linked-list/simple_linked_list.rb
UTF-8
1,268
3.375
3
[]
no_license
# Exercism Ruby - Simple Linked List class SimpleLinkedList attr_accessor :head def initialize @size = 0 @nodes = [] @head = nil end def size @size end def peek if @head.nil? nil else @head.datum end end def empty? @size.zero? end def pop @size -= 1 node = @head @head = @head.next node.datum end def push(datum) @size += 1 if @head.nil? @head = Element.new(datum) else @head = Element.new(datum, @head) end end def to_a datums = [] head_a = @head until head_a.nil? datums.push(head_a.datum) head_a = head_a.next end datums end def reverse list_r = Marshal.load(Marshal.dump(self)) one = nil two = list_r.head until two.nil? three = two.next two.next = one one = two two = three end list_r.head = one list_r end def self.from_a(datums) list = new unless datums.nil? datums.reverse.each do |datum| list.push(datum) end end list end end class Element attr_accessor :datum, :next def initialize(datum, next_node = nil) @datum = datum @next = next_node end def tail? @next.nil? end end
true
28a9d763660acedadc5e140f3e7a52696fcc5028
Ruby
nebanche/AdventOfCode2019
/day1/puzzle1-1.rb
UTF-8
432
3.78125
4
[]
no_license
# ### # First poll, every elf is Go # mass/3, round down, subtract 2 # sum of all inputs by (mass/3) - 2 # ## def fuel_calcuation(mass) (mass/3) - 2 end def calculate_total_fuel(masses) fuel_calcs = masses.map(&method(:fuel_calcuation)) fuel_calcs.reduce(:+) end def run_program file = File.open("input.txt") file_data = file.readlines.map(&:chomp) masses = file_data.map(&:to_i) calculate_total_fuel(masses) end
true
80e6796085142813d5c62fedebb0cb2b750ad872
Ruby
tench-o/release-crawler
/run.rb
UTF-8
369
2.640625
3
[]
no_license
require './lib/crawler' require 'csv' results = Crawler.all_execute puts %w(サイト名 記事タイトル 公開日 記事URL).to_csv results.each do |crawler, articles| next if articles.nil? klass = Crawler.get_executor(crawler) articles.each do |article| puts [klass.name, article[:title], article[:publish_date], article[:content_url]].to_csv end end
true
ee82ac91d1504e8697a55c75a9629d7aca9d052c
Ruby
zacwillmington/playlister-sinatra-v-000
/app/models/song.rb
UTF-8
593
2.734375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Song < ActiveRecord::Base belongs_to :artist has_many :song_genres has_many :genres, through: :song_genres #extend Concerns::Slugifiable def slug self.name.downcase.gsub(" ", "-") end def self.find_by_slug(slug) song = slug.split("-").collect do |name| if name == "with" || name == "the" || name == "a" || name == "and" name.downcase else name.capitalize end end.join(" ") # binding.pry @song = self.find_by(:name => song) end end
true
3490aa9a6b192fdb34568c0733b18c84e0c36d71
Ruby
brianhempel/base_x
/test/test_base_x.rb
UTF-8
8,457
2.84375
3
[ "LicenseRef-scancode-warranty-disclaimer", "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
require 'bundler/setup' Bundler.require(:test) require 'base_x' require 'minitest/autorun' require 'minitest/reporters' MiniTest::Reporters.use! Minitest::Reporters::DefaultReporter.new class TestBaseX < Minitest::Test def setup @base_x = BaseX.new("012") end attr_reader :base_x ### Instance Methods ### def test_complains_if_numerals_has_duplicate_chars BaseX.new("∫©¶çΩ≈") # no error assert_raises(ArgumentError) { BaseX.new("∫©¶çΩ≈Ω") } end def test_complains_if_only_one_numeral BaseX.new("∫©") # no error assert_raises(ArgumentError) { BaseX.new("") } assert_raises(ArgumentError) { BaseX.new("∫") } end def test_string_to_integer assert_equal 48, base_x.string_to_integer("01210") end def test_string_to_integer_errors_with_invalid_chars assert_raises(BaseX::InvalidNumeral) do base_x.string_to_integer("asdf") end end def test_string_to_integer_errors_with_empty_string assert_raises(BaseX::EmptyString) do base_x.string_to_integer("") end end def test_integer_to_string assert_equal "1210", base_x.integer_to_string(48) end def test_0_to_string assert_equal "0", base_x.integer_to_string(0) end def test_encode_decode_empty_string assert_equal "", base_x.decode(base_x.encode("")) end def test_encode_decode_zeros assert_equal "\x00\x00\x00\x00", base_x.decode(base_x.encode("\x00\x00\x00\x00")) end def test_encode_decode_stuff assert_equal "stuff", base_x.decode(base_x.encode("stuff")) end def test_a_bunch_of_zero_strings_in_a_bunch_of_bases (2..10).each do |base| base_x = BaseX.new(('a'..'z').take(base).join) (1..257).to_a.sample(20).each do |size| assert_equal "\x00"*size, base_x.decode(base_x.encode("\x00"*size)), "problem with #{size} length zero string in base #{base}" end end end def test_a_bunch_of_random_strings_in_a_bunch_of_bases (2..10).each do |base| base_x = BaseX.new(('a'..'z').take(base).join) (1..257).to_a.sample(20).each do |size| string = SecureRandom.random_bytes(size) assert_equal string.dup, base_x.decode(base_x.encode(string)), "problem encoding/decoding #{string.inspect} in base #{base}" end end end ### Class Methods ### def test_integer_to_string_class_method assert_equal "1210", BaseX.integer_to_string(48, numerals: "012") end def test_integer_to_string_claass_methods_complains_if_no_numerals_provided assert_raises(ArgumentError) { BaseX.integer_to_string(48, numerals: Object.new) } end def test_string_to_integer_class_method assert_equal 48, BaseX.string_to_integer("01210", numerals: "012") end def test_string_to_integer_claass_methods_complains_if_no_numerals_provided assert_raises(ArgumentError) { BaseX.string_to_integer("01210", numerals: Object.new) } end def test_encode_decode_class_methods assert_equal "stuff", BaseX.decode(BaseX.encode("stuff", numerals: "012"), numerals: "012") end def test_encode_class_method_complains_if_no_numerals_provided assert_raises(ArgumentError) { BaseX.encode("stuff", numerals: Object.new) } end def test_decode_class_method_complains_if_no_numerals_provided assert_raises(ArgumentError) { BaseX.decode("stuff", numerals: Object.new) } end def test_base_class_method assert_equal "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZab", BaseX.base(38).numerals end def test_base_class_method_errors BaseX.base(2) # no error BaseX.base(62) # no error assert_raises(ArgumentError) { BaseX.base(1) } assert_raises(ArgumentError) { BaseX.base(63) } end def test_bases_class_method assert_equal ["Binary", 2, "1111110010001110001111001001000101111101010110000011011010001011", "01"], BaseX.bases.first expected_order = %w[ Binary Base16 Base16L Base16U Hex Hexadecimal Base30L Base30U Base31L Base31U CrockfordBase32 RFC4648Base32 Base58 BitcoinBase58 FlickrBase58 GMPBase58 NewBase60 Base62 Base62DLU Base62DUL Base62LDU Base62LUD Base62UDL Base62ULD URLBase64 Z85 Base256 ] assert_equal expected_order, BaseX.bases.map(&:first) end def test_bases_table_class_method assert_equal String, BaseX.bases_table.class # it doesn't blow up end ### Base Constants ### def test_binary assert_equal "111010110111100110100010101", BaseX::Binary.integer_to_string(123456789) assert_equal "111010110111100110100010110001", BaseX::Binary.integer_to_string(987654321) end def test_base16L assert_equal "75bcd15", BaseX::Base16L.integer_to_string(123456789) assert_equal "3ade68b1", BaseX::Base16L.integer_to_string(987654321) end def test_base16U assert_equal "75BCD15", BaseX::Base16U.integer_to_string(123456789) assert_equal "3ADE68B1", BaseX::Base16U.integer_to_string(987654321) end def test_base30L assert_equal "74eg8b", BaseX::Base30L.integer_to_string(123456789) assert_equal "3cnbspq", BaseX::Base30L.integer_to_string(987654321) end def test_base30U assert_equal "74EG8B", BaseX::Base30U.integer_to_string(123456789) assert_equal "3CNBSPQ", BaseX::Base30U.integer_to_string(987654321) end def test_base31L assert_equal "6bq524", BaseX::Base31L.integer_to_string(123456789) assert_equal "35hft2u", BaseX::Base31L.integer_to_string(987654321) end def test_base31U assert_equal "6BQ524", BaseX::Base31U.integer_to_string(123456789) assert_equal "35HFT2U", BaseX::Base31U.integer_to_string(987654321) end def test_rfc4648_base32 assert_equal "DVXTIV", BaseX::RFC4648Base32.integer_to_string(123456789) assert_equal "5N42FR", BaseX::RFC4648Base32.integer_to_string(987654321) end def test_crockford_base32 assert_equal "3NQK8N", BaseX::CrockfordBase32.integer_to_string(123456789) assert_equal "XDWT5H", BaseX::CrockfordBase32.integer_to_string(987654321) end def test_bitcoin_base58 assert_equal "BukQL", BaseX::BitcoinBase58.integer_to_string(123456789) assert_equal "2WGzDn", BaseX::BitcoinBase58.integer_to_string(987654321) end def test_flickr_base58 assert_equal "bUKpk", BaseX::FlickrBase58.integer_to_string(123456789) assert_equal "2vgZdM", BaseX::FlickrBase58.integer_to_string(987654321) end def test_gmp_base58 assert_equal "AqhNJ", BaseX::GMPBase58.integer_to_string(123456789) assert_equal "1TFvCj", BaseX::GMPBase58.integer_to_string(987654321) end def test_new_base60 assert_equal "9XZZ9", BaseX::NewBase60.integer_to_string(123456789) assert_equal "1GCURM", BaseX::NewBase60.integer_to_string(987654321) end def test_base62_dul assert_equal "8M0kX", BaseX::Base62DUL.integer_to_string(123456789) assert_equal "14q60P", BaseX::Base62DUL.integer_to_string(987654321) end def test_base62_dlu assert_equal "8m0Kx", BaseX::Base62DLU.integer_to_string(123456789) assert_equal "14Q60p", BaseX::Base62DLU.integer_to_string(987654321) end def test_base62_ldu assert_equal "iwaK7", BaseX::Base62LDU.integer_to_string(123456789) assert_equal "beQgaz", BaseX::Base62LDU.integer_to_string(987654321) end def test_base62_lud assert_equal "iwaUH", BaseX::Base62LUD.integer_to_string(123456789) assert_equal "be0gaz", BaseX::Base62LUD.integer_to_string(987654321) end def test_base62_udl assert_equal "IWAk7", BaseX::Base62UDL.integer_to_string(123456789) assert_equal "BEqGAZ", BaseX::Base62UDL.integer_to_string(987654321) end def test_base62_uld assert_equal "IWAuh", BaseX::Base62ULD.integer_to_string(123456789) assert_equal "BE0GAZ", BaseX::Base62ULD.integer_to_string(987654321) end def test_url_base64 assert_equal "HW80V", BaseX::URLBase64.integer_to_string(123456789) assert_equal "63mix", BaseX::URLBase64.integer_to_string(987654321) end def test_z85 assert_equal "2v2B/", BaseX::Z85.integer_to_string(123456789) assert_equal "i]jLP", BaseX::Z85.integer_to_string(987654321) end def test_base256 assert_equal "\x07\x5B\xCD\x15".force_encoding("ASCII-8BIT"), BaseX::Base256.integer_to_string(123456789) assert_equal "\x3A\xDE\x68\xB1".force_encoding("ASCII-8BIT"), BaseX::Base256.integer_to_string(987654321) end end
true
a27b2181a5161540fa99f4e890b5d3ac76d845a4
Ruby
taganaka/link_thumbnailer
/lib/link_thumbnailer/graders/link_density.rb
UTF-8
497
2.59375
3
[ "MIT" ]
permissive
module LinkThumbnailer module Graders class LinkDensity < ::LinkThumbnailer::Graders::Base def call(current_score) return 0 if density_ratio == 0 current_score *= density_ratio end private def density return 0 if text.length == 0 links.length / text.length.to_f end def density_ratio 1 - density end def links node.css('a').map(&:text).compact.reject(&:empty?) end end end end
true
4f3e20840bfd8f16d08135973112d530deb5fbc4
Ruby
drhinehart/data-engineering
/data_engineering/app/services/data_importer.rb
UTF-8
793
3.125
3
[]
no_license
require 'csv' class DataImporter attr_reader :file, :gross_revenue, :purchases def initialize(file) @file = file @purchases = [] end def import csv_options = { headers: :first_row, header_converters: :symbol, converters: :all, col_sep: "\t" } CSV.foreach(file, csv_options).each do |row| purchaser = PurchaserImporter.new(row).import merchant = MerchantImporter.new(row).import item = ItemImporter.new(row, merchant).import purchase = PurchaseImporter.new(row, purchaser, item).import purchases << purchase end end def gross_revenue gross_revenue ||= purchases.reduce(0) { |c,p| c += (p.quantity * p.item.price )} end end
true
97b565f62b354e3de56b649b502ad4838d9ac9c4
Ruby
Mani082/RubyFiles
/aborting.rb
UTF-8
203
3.46875
3
[]
no_license
fruits = ['banana', 'apple', 'Mangoe'] fruits.each do |fruit| if fruit=='apple' #exit abort("I hate apple") end puts fruit.capitalize end puts "Total fruits: #{fruits.count}"
true
6a7081dda3b35acb6d49558af6db20b91664cf64
Ruby
DavisC0801/jungle_beats
/lib/node.rb
UTF-8
166
3.078125
3
[]
no_license
class Node attr_reader :next_node, :data def initialize(data) @data = data @next_node = nil end def set_next(node) @next_node = node end end
true
c352daa3ee1d8ac7da7de18d56d9860134725d4b
Ruby
mandareis/programming-univbasics-4-crud-lab-sfo01-seng-ft-100520
/lib/array_crud.rb
UTF-8
673
3.890625
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def create_an_empty_array [] end def create_an_array an_array = ["Chocolate", "Wine", "Babe", "Money"] end def add_element_to_end_of_array(array, element) array.push(element) end def add_element_to_start_of_array(array, element) array.unshift(element) end def remove_element_from_end_of_array(array) array.pop end def remove_element_from_start_of_array(array) array.shift end def retrieve_element_from_index(array, index_number) array[index_number] end def retrieve_first_element_from_array(array) array[0] end def retrieve_last_element_from_array(array) array[-1] end def update_element_from_index(array, index_number, element) array[index_number] = element end
true
c67ac66508e7e0fdbaed386549e36a5d5df92f72
Ruby
NewbiZ/sandbox
/gmail_lister/gmail_lister.rb
UTF-8
1,141
2.78125
3
[]
no_license
#!/usr/bin/env ruby # You need to define your login and password in JSON format in ~/.gmail : # { # "login": "user.name", # "password": "your_password" # } require 'gmail' require 'json' require 'yaml' require 'date' require 'tmail' gmail_config = JSON.parse( IO.read("/Users/newbiz/.gmail") ) gmail = Gmail.new gmail_config["login"], gmail_config["password"] # Get some useful informations unread_list = gmail.inbox.emails(:unread, {:on => Date.today}) unread_count = unread_list.length read_list = gmail.inbox.emails(:read, {:on => Date.today}) read_count = read_list.length puts "Unread (#{unread_count}):" unread_list.each do |message| puts "#{TMail::Unquoter.unquote_and_convert_to(message.from[0].name,'utf-8')} (#{message.from[0].mailbox}@#{message.from[0].host}) - #{TMail::Unquoter.unquote_and_convert_to(message.subject,'utf-8')}" end puts "" puts "Read (today):" read_list.each do |message| puts "#{TMail::Unquoter.unquote_and_convert_to(message.from[0].name,'utf-8')} (#{message.from[0].mailbox}@#{message.from[0].host}) - #{TMail::Unquoter.unquote_and_convert_to(message.subject,'utf-8')}" end gmail.logout
true