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
5b1f372f7f5ea17f67d62780db384072398ad30d
Ruby
Intetaget/Homework
/OO-tic-tac-toe/Player_tic_tac.rb
UTF-8
284
3.859375
4
[]
no_license
#require 'pry' class Player def initialize(letter) @name = get_name @letter = letter end def name @name end def letter @letter end def get_move gets.chomp.to_i end private def get_name puts "What is your name? Human player" gets.chomp end end
true
a183a86411116b34a35187403159cbf1a0eac628
Ruby
silcam/cmbpayroll
/test/models/loan_payment_test.rb
UTF-8
2,084
2.515625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require "test_helper" class LoanPaymentTest < ActiveSupport::TestCase def setup @luke = employees :Luke @loan_one = loans :one end test "Validate Presence of Required Attributes" do model_validation_hack_test LoanPayment, some_valid_params end test "Get all payments for period" do anakin = employees :Anakin # pay off this loan in july julyloan = loans :twokjuly julypay = LoanPayment.new julypay.amount = 2000 julypay.date = "2017-07-02" julyloan.loan_payments << julypay # this loan's payments should appear in the call augloan = loans :sixkaug augpay = LoanPayment.new augpay.amount = 3000 augpay.date = "2017-08-02" augloan.loan_payments << augpay # get August payments augpayments = LoanPayment.get_all_payments(anakin, Period.new(2017,8)) assert_equal(1, augpayments.size()) end test "can't add or edit during posted period" do # Can't add loan during posted pay period pay = LoanPayment.new pay.amount = 8 pay.date = '2017-07-30' pay.loan = loans :julloan refute pay.valid?, "should not be able to create during posted period" # Can't add loan during posted pay period pay = LoanPayment.new pay.amount = 10 pay.date = '2017-08-03' pay.loan = loans :augloan assert pay.valid?, "should be valid outside of posted period" end test "can't delete during posted period" do LastPostedPeriod.post_current augpay = loan_payments :augpay augpay.destroy assert_includes LoanPayment.all(), augpay end test "can delete during posted period" do septpay = loan_payments :septpay septpay.destroy refute_includes LoanPayment.all(), septpay end test "loan payment can be cash" do septpay = loan_payments :septpay septpay.cash_payment = true assert(septpay.cash?, "should be a cash payment") septpay.cash_payment = false refute(septpay.cash?, "should now not be a cash payment") end def some_valid_params { loan: @loan_one, date: '2017-10-02', amount: 90 } end end
true
605e4f2cdf7b4dcb32cf0e9064fc8246e2537af1
Ruby
seanmsmith23/matasano-crypto
/lib/set-1/03-single-byte-xor-cypher.rb
UTF-8
1,102
3.546875
4
[]
no_license
require 'awesome_print' require 'byebug' # http://cryptopals.com/sets/1/challenges/3/ class DecryptSingleXOR def initialize(hex_string, test_array) @hex = hex_decode(hex_string) @test_array = test_array end def ranked_solutions scored_solutions.sort_by { |solution| solution[:score] }.reverse end def scored_solutions potential_solutions.map do |solution| {key: solution[:key], score: score(solution), result: solution[:result]} end end def potential_solutions @test_array.map do |letter| {key: letter, result: fixed_xor(@hex, letter)} end end private def fixed_xor(given_string, xor) empty = "" given_string.each_byte do |byte| empty << xor_against(byte, xor) end empty end def hex_decode(hex_string) [hex_string].pack("H*") end def xor_against(byte, char_to_xor) byte ^ char_to_xor.to_s.bytes.pop end def score(solution) (solution[:result].scan(/[a-z]/).count + solution[:result].scan(/[ ]/).count - solution[:result].scan(/\W/).count - solution[:result].scan(/\d/).count) end end
true
f52eb065416993909de7d5113c679d66f016698c
Ruby
handwerger/launch-school-repo
/chapter_3/3_5.rb
UTF-8
102
2.890625
3
[]
no_license
def scream(words) words = words + "!!!!" puts words end scream ("Yipeeee") #prints "Yipeeee!!!!"
true
9f2118c3ddc691798bcd16978814aa5b04e021aa
Ruby
benfurber/bank_ruby
/spec/unit/account_spec.rb
UTF-8
964
2.828125
3
[ "MIT" ]
permissive
require 'account' describe Account do subject { Account.new(transaction_class_double, statement_class_double) } let(:transaction_class_double) { double 'Transaction', new: transaction } let(:transaction) { double 'transaction_instance' } let(:statement_class_double) { double 'Statement', new: statement } let(:statement) { double 'statement_instance', print: statement_print } let(:statement_print) { 'Statement printed' } describe '#initalize' do it 'log is empty' do expect(subject.log).to be_empty end end describe 'Transactions' do it '#deposit adds to the log' do subject.deposit(50) expect(subject.log).to include(transaction) end it '#withdraw adds to the log' do subject.withdraw(50) expect(subject.log).to include(transaction) end end describe '#statement' do it 'prints the statement' do expect(subject.statement).to include statement_print end end end
true
79206d415ae0acc6837e593d6cad017fb5fef266
Ruby
JK8283/BEWD
/secret_number.rb
UTF-8
2,069
4.5
4
[]
no_license
def intro puts "Welcome to the secret number game! Created by John Kim. Type q to quit." puts "What is your name?" name = gets.chomp if name != "q" puts "Hi #{name}!" game1 else response = name end end ## First guess method. def game1 secret_number = 5 puts "Guess a number between 1 and 10. You only have 3 tries to guess correctly or you lose!" user_guess1 = gets.chomp.to_i if user_guess1 == secret_number puts "Congratulations! You've guessed correctly and win the game!" elsif user_guess1 < secret_number puts "Oops! Looks like your guess is too low!" game2 elsif user_guess1 > secret_number puts "Oops! Looks like your guess is too high!" game2 else puts "Make sure you enter a number between 1 and 10." game1 end end ## Second guess method. def game2 secret_number = 5 puts "Guess a number between 1 and 10. You only have 2 tries to guess correctly or you lose!" user_guess2 = gets.chomp.to_i if user_guess2 == secret_number puts "Congratulations! You've guessed correctly and win the game!" elsif user_guess2 < secret_number puts "Oops! Looks like your guess is too low!" game3 elsif user_guess2 > secret_number puts "Oops! Looks like your guess is too high!" game3 else puts "Make sure you enter a number between 1 and 10." game2 end end ## Third guess method. def game3 secret_number = 5 puts "Guess a number between 1 and 10. You only have 1 more try to guess correctly or you lose!" user_guess3 = gets.chomp.to_i if user_guess3 == secret_number puts "Congratulations! You've guessed correctly and win the game!" elsif user_guess3 < secret_number puts "Oops! Looks like your guess is too low! You've run out of tries - the correct answer was #{secret_number}." elsif user_guess3 > secret_number puts "Oops! Looks like your guess is too high! You've run out of tries - the correct answer was #{secret_number}." else puts "Make sure you enter a number between 1 and 10." game3 end end ## Methods always go on top! response = intro while response != "q" response = intro end
true
395af3bb5d36393417fc6381d072b0d1b5f227cb
Ruby
sge/beefcake
/lib/beefcake/delayed.rb
UTF-8
895
2.90625
3
[ "MIT" ]
permissive
module Beefcake class Delayed attr_accessor :klass, :bytes, :object def initialize(klss, byts) @klass, @bytes = klss, byts end def decode __object__ end def encode (@object) ? @object.encode : @bytes end def class_from_string(str) str.split('::').inject(Object) do |mod, class_name| mod.const_get(class_name) end end def __object__ @object = class_from_string(@klass).decode(@bytes.dup) unless @object @object end alias :_inspect :inspect def inspect if @object @object.inspect else _inspect end end def respond_to?(message) message = message.to_sym [:__object__, :inspect].include?(message) || __object__.respond_to?(message) end def method_missing(*a, &b) __object__.__send__(*a, &b) end end end
true
1eb3224e9022683c5596d24ce4e6feb356fdec54
Ruby
fx-kirin/ruby_backtest
/test/test_backtest_order_list.rb
UTF-8
3,714
2.609375
3
[ "Apache-2.0" ]
permissive
require_relative "test_master" require_relative "../lib/backtest_order_manager/backtest_order_list" class TestBacktestOrderList < TestMaster def setup @list = BacktestOrderList.new end def test_insert_get_update_order order = @list.new_order assert_raise(BacktestOrderList::NoDataFoundException, "Must raise error when order_number is not found."){ result = @list.get_position(order.order_number) } order = set_open_data(order) result = nil assert_nothing_raised("insert_order failed."){ result = @list.insert_order(order) } assert_raise(BacktestOrderList::OrderNumberIsNotNilException, "Must raise error when insert order with order_number not nil."){ result = @list.insert_order(order) } assert_nothing_raised("insert_order failed."){ result = @list.get_position(order.order_number) } assert_equal("USDJPY", order.symbol, "Data mismatch error.") order = set_close_data(order) assert_nothing_raised("save failed."){ result = @list.save(order) } end def test_get_all_positions @list.delete_all_positions 100.times{ order = @list.new_order order = set_open_data(order) @list.insert_order(order) } positions = @list.get_all_positions assert_equal(positions.length, 100, "Positions must be 100.") end def test_get_positions_by_status @list.delete_all_positions 100.times{ order = @list.new_order order = set_open_data(order) @list.insert_order(order) } assert_equal(@list.get_open_positions.length, 100, "Open Positions must be 100.") assert_equal(@list.get_close_positions.length, 0, "Close Positions must be 0.") positions = @list.get_all_positions positions.each{|pos| set_close_data(pos) @list.save(pos) } assert_equal(@list.get_open_positions.length, 0, "Open Positions must be 100.") assert_equal(@list.get_close_positions.length, 100, "Close Positions must be 0.") end def test_get_position_by_magic_number @list.delete_all_positions 100.times{ order = @list.new_order order = set_open_data(order) @list.insert_order(order) } assert_equal(@list.get_positions_by_magic_number(1234).length, 100, "Positions must be 100.") assert_equal(@list.get_open_positions_by_magic_number(1234).length, 100, "Open Positions must be 100.") assert_equal(@list.get_close_positions_by_magic_number(1234).length, 0, "Close Positions must be 0.") positions = @list.get_positions_by_magic_number(1234) positions.each{|pos| set_close_data(pos) @list.save(pos) } assert_equal(@list.get_positions_by_magic_number(1234).length, 100, "Positions must be 100.") assert_equal(@list.get_open_positions_by_magic_number(1234).length, 0, "Open Positions must be 0.") assert_equal(@list.get_close_positions_by_magic_number(1234).length, 100, "Close Positions must be 100.") end def test_delete_all_positions order = @list.new_order order = set_open_data(order) @list.insert_order(order) @list.delete_all_positions assert_equal(@list.get_all_positions.length, 0, "Positions have not been deleted.") end private def set_open_data(order) order.symbol = "USDJPY" order.order_type = 1 order.lots = 10 order.status = 1 order.open_price = 100.10 order.stop_loss = 99.00 order.take_profit = 101.90 order.open_time = Time.parse("2007.01.02 07:00") order.magic_number = 1234 order end def set_close_data(order) order.status = 2 order.close_price = 100.00 order.close_time = Time.parse("2007.01.02 07:00") order end end
true
a11afc036a72dfd8f58913764f92db831dbb874c
Ruby
rebeccanewborn/oxford-comma-prework
/lib/oxford_comma.rb
UTF-8
565
3.5625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def oxford_comma(array) # if array.size == 1 # return array[0] # elsif array.size == 2 # return "#{array[0]} and #{array[1]}" # else # output = "" # counter = 0 # while counter < array.size - 1 # output << "#{array[counter]}, " # counter += 1 # end # output << "and #{array[-1]}" # return output # end if array.size == 1 return array[0] elsif array.size == 2 return "#{array[0]} and #{array[1]}" else last_elt = array[-1] array[-1] = "and #{last_elt}" return array.join(", ") end end
true
3d0914618e40a01a53600ca2700de10413b25258
Ruby
Jablooo/ATM
/atm_v1.rb
UTF-8
3,624
4.03125
4
[]
no_license
=begin ****BRIEF**** Use Ruby to create a terminal app that behaves like an ATM in real life. structure: - intro to customer and displaying the options. - use case when for your code - running each option individually (withdraw, check balance, greeting, deposit) - use loops - sign off TRY ADDING A PIN TO THE SYSTEM =end # Introduction of user interface puts puts puts puts puts puts puts " Welcome to Jon Bank" puts " Please insert your card" puts " press enter to continue" puts puts puts puts gets.chomp def intro #Establish the account balance $balance = 0 $runner = 1 puts puts puts " Thank you for banking with us today." while $runner == 1 puts " Here are your available options" puts puts "[1] Withdraw [3] Check Balance" puts "[2] Deposit [4] Remove Card" puts puts optionsAnswer = gets.chomp.to_i if optionsAnswer == 1 withdraw_function elsif optionsAnswer == 2 deposit_function elsif optionsAnswer == 3 check_balance elsif optionsAnswer == 4 puts puts puts "We hope you have enjoyed your Jon Bank" puts " experience and hope to see you soon" puts puts $runner = 2 return $runner else puts "Please select valid option" end end while $runner ==2 puts puts puts puts puts "We hope you have enjoyed your Jon Bank" puts " experience and hope to see you soon" puts puts puts puts $runner = 3 end end def deposit_function puts "How much would you like to deposit today?" depositAnswer = gets.chomp.to_i if depositAnswer <= 0 puts "Please write a positive number" elsif depositAnswer > 0 $balance = $balance + depositAnswer puts puts puts puts puts puts puts "Your balance is now $#{$balance}" puts puts puts puts puts puts puts "Would you like to do anything else?" puts " [Y]/[N]" puts puts puts puts option = gets.chomp.downcase if option == "y" $runner = 1 return $runner elsif option == "n" $runner = 2 return $runner else puts "Please select valid option" end return $balance else puts puts puts puts puts "Please enter number" puts puts puts puts end end def withdraw_function puts "How much would you like to withdraw today?" withdrawAnswer = gets.chomp.to_i if withdrawAnswer <= 0 puts "Please write a positive number" elsif withdrawAnswer > 0 && withdrawAnswer < $balance $balance = $balance - withdrawAnswer puts puts puts puts puts puts puts "Your balance is now $#{$balance}" puts puts puts puts puts puts puts "Would you like to do anything else?" puts " [Y]/[N]" puts puts puts puts option = gets.chomp.downcase if option == "y" $runner = 1 return $runner elsif option == "n" $runner = 2 return $runner else puts "Please select valid option" end return $balance else puts puts puts puts puts "You have insufficient funds" puts puts puts puts end end def check_balance puts puts puts puts puts "Your balance is $#{$balance}" puts puts puts puts "Would you like to do anything else?" puts " [Y]/[N]" puts puts puts puts option = gets.chomp.downcase if option == "y" $runner = 1 return $runner elsif option == "n" $runner = 2 return $runner else puts "Please select valid option" end end intro
true
af5353cbd8d275921b8b4620cd8f7e22460758bb
Ruby
bleakwood/web-crawler
/selenium.rb
UTF-8
1,468
2.546875
3
[]
no_license
require "selenium-webdriver" require "pry-byebug" require 'timers' def collect_data driver = Selenium::WebDriver.for :firefox driver.navigate.to "https://mp.weixin.qq.com" element = driver.find_element(:name, 'account') element.send_keys "danna@beamalliance.com" element = driver.find_element(:name, 'password') element.send_keys "" driver.find_element(:id, 'loginBt').click wait = Selenium::WebDriver::Wait.new(:timeout => 5) wait.until { driver.find_element(:id => "menuBar").displayed? } link = driver.find_element(:link_text, '图文分析') link.click wait.until { driver.find_element(:id => "js_articles_items").displayed? } fname = "sample.txt" somefile = File.open(fname, "a") begin somefile.puts Time.now.strftime("%m-%d %H:%M") items = driver.find_elements(:css, '.appmsg_chart_abstract') items.each do |item| title = item.find_element(:class, 'sub_title').text somefile.puts title view_counts_array = item.find_elements(:css, '.td2 em') description_array = ["送达人数", "图文页阅读人数", "原文页阅读人数", "转发+收藏人数"] (0..3).each do |i| somefile.puts description_array[i] somefile.puts view_counts_array[i].text end end rescue Exception => e puts "#{e.class} with message: #{e.message}" puts e.backtrace.join("\n") ensure somefile.close driver.quit end end collect_data timers = Timers::Group.new five_second_timer = timers.every(3600) { collect_data } loop { timers.wait }
true
d29b9705d104b3357d5278f3fb132da1011e044a
Ruby
TakuLibraries/DuplicateFile
/lib/duplicate_file.rb
UTF-8
739
2.796875
3
[ "MIT" ]
permissive
require "duplicate_file/command" require "duplicate_file/version" module DuplicateFile def self.group_by_checksum(root_path) all_files = Dir.glob(root_path + "**/*").select{|path| File.file?(path) } all_files.group_by{|path| Digest::MD5.file(path).to_s } end def self.unique!(root_path) stay_pathes = [] deleted_pathes = [] checksum_filepath_group = group_by_checksum(root_path) checksum_filepath_group.each do |checksum, filepathes| dupricate_pathes = filepathes[1..(filepathes.size - 1)] || [] stay_pathes << filepathes.first dupricate_pathes.each do |path| deleted_pathes << path File.delete(path) end end return stay_pathes.uniq, deleted_pathes end end
true
a6d381e1f4aebe55848671390d7e53c8302b1a84
Ruby
david-azevedo/advent-of-code-2019
/src/day24.rb
UTF-8
1,069
2.796875
3
[ "MIT" ]
permissive
lines = File.readlines("../data/#{__FILE__.split('.')[0]}.txt").map(&:strip) def cal_bio(layout) bin_layout = layout.join.reverse.gsub('#', '1').gsub('.', '0') bin_layout.to_i(2) end starting_layout = lines previous_layouts = { starting_layout.join => 1 } stop = false until stop next_layout = Array.new(5) { '.....' } 25.times do |i| r = i / 5 c = i % 5 adjacent = [[r - 1, c], [r + 1, c], [r, c + 1], [r, c - 1]] n_bugs = 0 adjacent.each do |adj| if adj[0] < 5 && adj[0] >= 0 && adj[1] < 5 && adj[1] >= 0 n_bugs += 1 if starting_layout[adj[0]][adj[1]] == '#' end end next_layout[r][c] = starting_layout[r][c] if starting_layout[r][c] == '#' next_layout[r][c] = '.' unless n_bugs == 1 end if starting_layout[r][c] == '.' next_layout[r][c] = '#' if [1, 2].include?(n_bugs) end end starting_layout = next_layout if previous_layouts[starting_layout.join] == 1 stop = true next end previous_layouts[starting_layout.join] = 1 end puts cal_bio(starting_layout)
true
018004db6be64a540494e31045a77ae98cda37d1
Ruby
tsuruhaya/freemarket_sample_64b
/spec/models/user_spec.rb
UTF-8
5,292
2.921875
3
[]
no_license
require 'rails_helper' describe User do describe '#create' do it "is valid with a nickname, email, password, first_name, last_name" do user = build(:user) expect(user).to be_valid end # ニックネームが空では登録できない it "it invalid without a nickname" do user = build(:user, nickname: nil) user.valid? expect(user.errors[:nickname]).to include("can't be blank") end # メールが空では登録できない it "it invalid without a email" do user = build(:user, email: nil) user.valid? expect(user.errors[:email]).to include("can't be blank") end # パスワードが空では登録できない it "it invalid without a password" do user = build(:user, password: nil) user.valid? expect(user.errors[:password]).to include("can't be blank") end # パスワードが登録されてもpassword_confirmationが空では登録できない it "it invalid without a password_confirmation although with a password" do user = build(:user, password_confirmation: "") user.valid? expect(user.errors[:password_confirmation]).to include("doesn't match Password") end # パスワードが7文字以上で登録ができる it "is vaild with a password that has more than 7 characters" do user = build(:user, password: "1k2o334", password_confirmation: "1k2o334") user.valid? expect(user).to be_valid end # パスワードがが6文字以下なら登録ができない it "is invaild with a password that has less than 6 characters" do user = build(:user, password: "10ako", password_confirmation: "10ako") user.valid? expect(user.errors[:password]).to include("is too short (minimum is 6 characters)", "is too short (minimum is 7 characters)") end # 名字が空では登録ができない it "is invalid without a first_name" do user = build(:user, first_name: nil) user.valid? expect(user.errors[:first_name]).to include("can't be blank") end # 名前が空では登録ができない it "is invalid without a last_name" do user = build(:user, last_name: nil) user.valid? expect(user.errors[:last_name]).to include("can't be blank") end # 名字(カナ)が空では登録ができない it "is invalid without a first_name_kana" do user = build(:user, first_name_kana: nil) user.valid? expect(user.errors[:first_name_kana]).to include("can't be blank") end # 名前(カナ)が空では登録ができない it "is invalid without a last_name_kana" do user = build(:user, last_name_kana: nil) user.valid? expect(user.errors[:last_name_kana]).to include("can't be blank") end # 誕生日が空では登録ができない it "is invalid without a birthday" do user = build(:user, birthday: nil) user.valid? expect(user.errors[:birthday]).to include("can't be blank") end # が空では登録ができない it "is invalid without a money" do user = build(:user, money: nil) user.valid? expect(user.errors[:money]).to include("can't be blank") end # が空では登録ができない it "is invalid without a point" do user = build(:user, point: nil) user.valid? expect(user.errors[:point]).to include("can't be blank") end # パスワードに英字、数字が含まれているか it "is valid with a password that contains letters and numbers" do user = build(:user, password: "1t0okaa", password_confirmation: "1t0okaa") user.valid? expect(user).to be_valid end # 氏名は全角で入力でしているか it "is valid with a first_name entered full-width" do user = build(:user, first_name: "ぁ-んァ-ン一-龥") user.valid? expect(user).to be_valid end # 名前は全角で入力でしているか it "is valid with a last_name entered full-width" do user = build(:user, last_name: "ぁ-んァ-ン一-龥") user.valid? expect(user).to be_valid end # 氏名(カナ)は全角で入力でしているか it "is valid with a first_name_kana entered full-width" do user = build(:user, first_name_kana: "サカエ") user.valid? expect(user).to be_valid end # 名前(カナ)は全角で入力でしているか it "is valid with a last_name_kana entered full-width" do user = build(:user, last_name_kana: "タロウ") user.valid? expect(user).to be_valid end # @を含んで使用しているか it "is valid with a email that includes @" do user = build(:user, email: "aaa@aaa.jp") user.valid? expect(user).to be_valid end # ドメインを含んで使用しているか it "is valid with a email that includes ne.jp" do user = build(:user, email: "aaa@aaa.ne.jp") user.valid? expect(user).to be_valid end # ドメインを含んで使用しているか it "is valid with a email that includes com" do user = build(:user, email: "aaa@aaa.com") user.valid? expect(user).to be_valid end end end
true
470e4554711fb218ee67ae39d7a71677cde65ac8
Ruby
timm3/regnow
/mock/main.rb
UTF-8
22,584
2.734375
3
[]
no_license
require 'sinatra' require_relative '../requirements' FILE_CONFIG = File.dirname(__FILE__) + "/classes.csv" FILE_USERS = File.dirname(__FILE__) + "/users.csv" FOLDER = 'views/mock/' FILE_LOGIN = FOLDER + 'login.html' FILE_LOGOUT = FOLDER + 'banner_logout.html' FILE_LOGOUTDO = FOLDER + 'banner_logoutdo.html' FILE_WELCOME = FOLDER + 'banner_welcome.html' FILE_LOGIN_FAILED = FOLDER + 'login_failed.html' FILE_REG_AND_RECORDS = FOLDER + 'banner_reg_and_records.html' FILE_REGISTRATION = FOLDER + 'banner_registration.html' FILE_REG_AGREEMENT = FOLDER + 'banner_reg_agreement.html' FILE_SELECT_TERM = FOLDER + 'banner_select_term.html' FILE_LOOKUP_CLASSES = FOLDER + 'banner_lookup_classes.html' FILE_CLASS_LIST = FOLDER + 'banner_class_list.html' FILE_ADVANCED_SEARCH = FOLDER + 'banner_advanced_search.html' FILE_CLASS_RESULTS = FOLDER + 'banner_class_results.html' FILE_ADD_DROP_CLASSES = FOLDER + 'banner_add_drop_classes.html' FILE_DETAILED = FOLDER + 'banner_detailed.html' FILE_CLASS_NOT_FOUND = FOLDER + 'banner_class_not_found.html' class Section attr_reader :course_reg_number attr_reader :subject attr_reader :course attr_accessor :num_enrolled attr_reader :capacity attr_reader :name def initialize(crn,subj,crs,enrol,cap,nm) @course_reg_number = crn @subject = subj @course = crs @num_enrolled = enrol @capacity = cap @name = nm end #users can register for classes only if number of students enrolled in less than capacity def canRegister if(num_enrolled.to_i<capacity.to_i) return true else return false end end end class Subject attr_reader :subject attr_reader :name def initialize(subj,nm) @subject = subj @name = nm end end class MockUser attr_reader :netid attr_reader :password attr_reader :crns def initialize(id,pass) @netid = id @password = pass @crns = Array.new end def add_class(crn) @crns.push(crn) end def clear_classes() @crns = Array.new end def canRegister(crn,classes) sec = getSection(crn,classes) if( sec != nil ) #check number of spots if !sec.canRegister return false end #check to make sure student isn't in this section already for sec in @crns if(sec==crn) return false end end return true end return false end end classes = Array.new subjects = Array.new users = Array.new current_user = nil #load all classes and subjects from config file File.open( FILE_CONFIG, 'r') do |f1| while line = f1.gets line.delete! "\n" parsed_values = line.split(",") #if there are two values it is a new subject if(parsed_values.size == 2) subject = parsed_values[0] name = parsed_values[1] new_subject = Subject.new( subject, name) subjects.push( new_subject ) #if there are more than two values it is a course else course_number = parsed_values[0] subject = parsed_values[1] course = parsed_values[2] num_enrolled = parsed_values[3] capacity = parsed_values[4] name = parsed_values[5] new_section = Section.new( course_number, subject, course, num_enrolled, capacity, name ) classes.push( new_section ) end end end #add all valid courses from DB Course.find_each() do |course| for crn in course[:crns] crn = crn.to_s course_number = crn subject = "XY" course = "123" num_enrolled = "0" capacity = "100" name = "no name" new_section = Section.new( course_number, subject, course, num_enrolled, capacity, name ) puts 'added class with crn: '+crn classes.push( new_section ) end end def classExists(crn,classes) for section in classes if(section.course_reg_number==crn) return true end end return false end def getSection(crn,classes) for section in classes if(section.course_reg_number==crn) return section end end return nil end #load all users with their passwords and what CRNs they're registered for File.open( FILE_USERS, 'r') do |f1| while line = f1.gets line.delete! "\n" parsed_values = line.split(",") id = parsed_values[0] pass = parsed_values[1] new_user = MockUser.new( id, pass) #if there are more than two values, the third+ values are CRNs if(parsed_values.size > 2) for i in 2..(parsed_values.size-1) new_user.add_class(parsed_values[i]) end end users.push( new_user ) end end get '/enterprise' do html_output = "" File.open( FILE_LOGIN, 'r') do |f1| while line = f1.gets html_output += line end end html_output end get '/twbkwbis.P_Logout' do html_output = "" File.open( FILE_LOGOUT, 'r') do |f1| while line = f1.gets html_output += line end end html_output end post '/logout.do' do if( params[:BTN_YES] == 'Yes') html_output = "" File.open( FILE_LOGOUTDO, 'r') do |f1| while line = f1.gets html_output += line end end if(current_user==nil) html_output = "failed to find current user" else puts "LOGGED OUT: "+current_user.netid current_user = nil end html_output end end post '/login.do' do authenticated = false for user in users if ( user.netid == params[:inputEnterpriseId] and user.password == params[:password] ) current_user = user puts "LOGGED IN: "+current_user.netid authenticated = true break end end if authenticated html_output = "" File.open( FILE_WELCOME, 'r') do |f1| while line = f1.gets html_output += line end end html_output else html_output = "" File.open( FILE_LOGIN_FAILED, 'r') do |f1| while line = f1.gets html_output += line end end html_output end end get '/reg_and_records' do html_output = "" File.open( FILE_REG_AND_RECORDS, 'r') do |f1| while line = f1.gets html_output += line end end html_output end get '/registration' do html_output = "" File.open( FILE_REGISTRATION, 'r') do |f1| while line = f1.gets html_output += line end end html_output end get '/registration_agreement' do html_output = "" File.open( FILE_REG_AGREEMENT, 'r') do |f1| while line = f1.gets html_output += line end end html_output end get '/select_term' do html_output = "" File.open( FILE_SELECT_TERM , 'r') do |f1| while line = f1.gets html_output += line end end html_output end post '/select_classes' do html_output = "" File.open( FILE_LOOKUP_CLASSES, 'r') do |f1| while line = f1.gets html_output += line end end index = html_output.index("<!--OPTIONS-->") insertedOptions = "" for sub in subjects insertedOptions += "<OPTION VALUE=\""+sub.subject+"\">"+sub.name end html_output.insert(index,insertedOptions) html_output end post '/get_courses' do if params[:SUB_BTN] == "Course Search" html_output = "" File.open( FILE_CLASS_LIST, 'r') do |f1| while line = f1.gets html_output += line end end index = html_output.index("<!--SUBJECT-->") subName = "ERROR_NO_SUBJECT" for sub in subjects if(sub.subject== params[:sel_subj]) subName = sub.name end end html_output.insert(index,"<TR><TH CLASS=\"ddheader\" scope=\"col\" colspan=\"4\" style=\"font-size:16px;\">"+subName+"</TH></TR>") rows = "" coursesListed = Array.new for course in classes if( (course.subject == params[:sel_subj]) && (!coursesListed.include?(course.course))) coursesListed.push(course.course) rows += "<TD CLASS=\"dddefault\"width=\"10%\">"+course.course+"</TD> <TD CLASS=\"dddefault\"width=\"35%\" text-align=\"left\">"+course.name+"</TD> <td> <FORM ACTION=\"/search_results\" METHOD=\"POST\" onSubmit=\"return checkSubmit()\"> <input type=\"hidden\" name=\"term_in\" value=\"120141\" > <INPUT TYPE=\"hidden\" NAME=\"sel_subj\" VALUE=\"dummy\"> <input type=\"hidden\" name=\"sel_subj\" value=\""+course.subject+"\" > <input type=\"hidden\" name=\"sel_crse\" value=\""+course.course+"\" > <input type=\"hidden\" name=\"SEL_TITLE\" value=\"\"> <input type=\"hidden\" name=\"BEGIN_HH\" value=\"0\"> <input type=\"hidden\" name=\"BEGIN_MI\" value=\"0\"> <input type=\"hidden\" name=\"BEGIN_AP\" value=\"a\"> <input type=\"hidden\" name=\"SEL_DAY\" value=\"dummy\"> <input type=\"hidden\" name=\"SEL_PTRM\" value=\"dummy\"> <input type=\"hidden\" name=\"END_HH\" value=\"0\"> <input type=\"hidden\" name=\"END_MI\" value=\"0\"> <input type=\"hidden\" name=\"END_AP\" value=\"a\"> <input type=\"hidden\" name=\"SEL_CAMP\" value=\"dummy\"> <input type=\"hidden\" name=\"SEL_SCHD\" value=\"dummy\"> <input type=\"hidden\" name=\"SEL_SESS\" value=\"dummy\"> <input type=\"hidden\" name=\"SEL_INSTR\" value=\"dummy\"> <input type=\"hidden\" name=\"SEL_INSTR\" value=\"%\"> <input type=\"hidden\" name=\"SEL_ATTR\" value=\"dummy\"> <input type=\"hidden\" name=\"SEL_ATTR\" value=\"%\"> <input type=\"hidden\" name=\"SEL_LEVL\" value=\"dummy\"> <input type=\"hidden\" name=\"SEL_LEVL\" value=\"%\"> <input type=\"hidden\" name=\"SEL_INSM\" value=\"dummy\"> <input type=\"hidden\" name=\"sel_dunt_code\" value=\"\"> <input type=\"hidden\" name=\"sel_dunt_unit\" value=\"\"> <input type=\"hidden\" name=\"call_value_in\" value=\"\"> <INPUT TYPE=\"hidden\" NAME=\"rsts\" VALUE=\"dummy\"> <INPUT TYPE=\"hidden\" NAME=\"crn\" VALUE=\"dummy\"> <input type=\"hidden\" name=\"path\" value=\"1\" > <INPUT TYPE=\"submit\" NAME=\"SUB_BTN\" VALUE=\"View Sections\" > </FORM> <BR> </td> </TR>" end end index = html_output.index("<!--COURSES-->") html_output.insert(index,rows) html_output else html_output = "" File.open( FILE_ADVANCED_SEARCH, 'r') do |f1| while line = f1.gets html_output += line end end index = html_output.index("<!--OPTIONS-->") insertedOptions = "" for sub in subjects insertedOptions += "<OPTION VALUE=\""+sub.subject+"\">"+sub.name end html_output.insert(index,insertedOptions) html_output end end post '/search_results' do output = "" File.open( FILE_CLASS_RESULTS, 'r') do |f1| while line = f1.gets output += line end end index = output.index("<!--SUBJECT-->") subName = "ERROR_NO_SUBJECT" for sub in subjects if(sub.subject == params[:sel_subj]) subName = sub.name end end output.insert(index,"<TR><TH COLSPAN=\"26\" CLASS=\"ddtitle\" scope=\"colgroup\" >"+subName+"</TH></TR>") results ="" for course in classes if( (course.subject == params[:sel_subj]) && (params[:sel_crse]=="" || params[:sel_crse]==course.course) && (params[:crn]=="dummy" || params[:sel_crn]==course.course_reg_number)) if(course.canRegister) results += '<TR> <TD CLASS="dddefault"><ABBR title = "Available for registration">A</ABBR></TD>' else results += '<TR> <TD CLASS="dddefault"><ABBR title = Closed>C</ABBR></TD>' end results += '<TD CLASS="dddefault"><A HREF="/BANPROD1/bwckschd.p_disp_listcrse?term_in=120141&amp;subj_in=CS&amp;crse_in=125&amp;crn_in=31152" onMouseOver="window.status=\'Detail\'; return true" onFocus="window.status=\'Detail\'; return true" onMouseOut="window.status=''; return true"onBlur="window.status=''; return true">'+course.course_reg_number+'</A></TD> <TD CLASS="dddefault">'+course.subject+'</TD> <TD CLASS="dddefault">'+course.course+'</TD> <TD CLASS="dddefault">AL1</TD> <TD CLASS="dddefault">100</TD> <TD CLASS="dddefault">4.000</TD> <TD CLASS="dddefault">Intro to Computer Science</TD> <TD CLASS="dddefault">MWF</TD> <TD CLASS="dddefault">02:00 pm-02:50 pm</TD> <TD CLASS="dddefault">'+course.capacity+'</TD> <TD CLASS="dddefault">'+course.num_enrolled+'</TD> <TD CLASS="dddefault">'+(course.capacity.to_i-course.num_enrolled.to_i).to_s+'</TD> <TD CLASS="dddefault">0</TD> <TD CLASS="dddefault">0</TD> <TD CLASS="dddefault">0</TD> <TD CLASS="dddefault">0</TD> <TD CLASS="dddefault">0</TD> <TD CLASS="dddefault">0</TD> <TD CLASS="dddefault">Lawrence Christopher Angrave (<ABBR title= "Primary">P</ABBR>)</TD> <TD CLASS="dddefault">01/21-05/07</TD> <TD CLASS="dddefault">1SIEBL 1404</TD> <TD CLASS="dddefault">UIUC: Quant Reasoning I</TD> </TR>' end end index = output.index("<!--SECTIONS-->") output.insert(index,results) output end get '/add_drop_classes' do html_output = "" File.open( FILE_ADD_DROP_CLASSES, 'r') do |f1| while line = f1.gets html_output += line end end if( current_user != nil && current_user.crns.size > 0 ) table_start = '<h3>Current Schedule</h3> <table class="datadisplaytable" summary="Current Schedule"> <tbody><tr> <th class="ddheader" scope="col">Status</th> <th class="ddheader" scope="col">Action</th> <th class="ddheader" scope="col"><acronym title="Course Reference Number">CRN</acronym></th> <th class="ddheader" scope="col"><abbr title="Subject">Subj</abbr></th> <th class="ddheader" scope="col"><abbr title="Course">Crse</abbr></th> <th class="ddheader" scope="col"><abbr title="Section">Sec</abbr></th> <th class="ddheader" scope="col">Level</th> <th class="ddheader" scope="col"><abbr title="Credit Hours">Cred</abbr></th> <th class="ddheader" scope="col">Grade Mode</th> <th class="ddheader" scope="col">Title</th> </tr>' table_end = '</tbody></table><br>' table_schedule = '<table class="plaintable" summary="Schedule Summary"> <tbody><tr> <td class="pldefault">Total Credit Hours: </td> <td class="pldefault"> 3.000</td> </tr> <tr> <td class="pldefault">Billing Hours:</td> <td class="pldefault"> 3.000</td> </tr> <tr> <td class="pldefault">Minimum Hours:</td> <td class="pldefault"> 12.000</td> </tr> <tr> <td class="pldefault">Maximum Hours:</td> <td class="pldefault"> 18.000</td> </tr> <tr> <td class="pldefault">Date:</td> <td class="pldefault">Apr 08, 2014 09:18 am</td> </tr> </tbody></table> <br>' index = html_output.index("<!--CURRENT_SCHEDULE-->") inserted = "" inserted += table_start for crn in current_user.crns inserted += '<tr> <td class="dddefault"><input type="hidden" name="MESG" value="DUMMY">**Web Registered** on Apr 08, 2014</td> <td class="dddefault"> <label for="action_id1"><span class="fieldlabeltextinvisible">Action</span></label> <select name="RSTS_IN" size="1" id="action_id1"> <option value="" selected="">None </option><option value="DW">Web Drop Course </option></select> </td> <td class="dddefault"><input type="hidden" name="assoc_term_in" value="120148"><input type="hidden" name="CRN_IN" value="'+crn+'">'+crn+'<input type="hidden" name="start_date_in" value="08/25/2014"><input type="hidden" name="end_date_in" value="12/10/2014"></td> <td class="dddefault"><input type="hidden" name="SUBJ" value="SUBJ">SUBJ</td> <td class="dddefault"><input type="hidden" name="CRSE" value="101">101</td> <td class="dddefault"><input type="hidden" name="SEC" value="Q3">Q3</td> <td class="dddefault"><input type="hidden" name="LEVL" value="Undergrad - Urbana-Champaign">Undergrad - Urbana-Champaign</td> <td class="dddefault"><input type="hidden" name="CRED" value=" 3.000"> 3.000</td> <td class="dddefault"><input type="hidden" name="GMOD" value="Standard Letter">Standard Letter</td> <td class="dddefault"><input type="hidden" name="TITLE" value="CLASS NAME">CLASS NAME</td> </tr>' end inserted += table_end inserted += table_schedule html_output.insert(index,inserted) end html_output end post '/add_drop_classes' do if current_user == nil puts "error no user logged in" end html_output = "" error_crns = Array.new add_crns = Array.new for crn in [ params[:CRN_IN1], params[:CRN_IN2], params[:CRN_IN3], params[:CRN_IN4], params[:CRN_IN5] , params[:CRN_IN6] , params[:CRN_IN7] , params[:CRN_IN8], params[:CRN_IN9] , params[:CRN_IN10] ] if(crn!="") if(current_user.canRegister(crn,classes)) add_crns.push(crn) puts "REGISTERED FOR CRN '" + crn + "' (netid: '" + current_user.netid + "')" else error_crns.push(crn) puts "FAILED TO REGISTER FOR CRN '" + crn + "' (netid: '" + current_user.netid + "')" end end end if(error_crns.size == 0) for crn in add_crns current_user.add_class(crn) end end File.open( FILE_ADD_DROP_CLASSES, 'r') do |f1| while line = f1.gets html_output += line end end if( error_crns.size > 0) error_start= '<table class="plaintable" summary="This layout table holds message information"> <tbody><tr> <td class="pldefault"> </td> <td class="pldefault"> <span class="errortext">Registration Add Errors</span> <br> </td> </tr> </tbody></table> <table class="datadisplaytable" summary="This layout table is used to present Registration Errors."> <tbody><tr> <th class="ddheader" scope="col">Status</th> <th class="ddheader" scope="col"><acronym title="Course Reference Number">CRN</acronym></th> <th class="ddheader" scope="col"><abbr title="Subject">Subj</abbr></th> <th class="ddheader" scope="col"><abbr title="Course">Crse</abbr></th> <th class="ddheader" scope="col"><abbr title="Section">Sec</abbr></th> <th class="ddheader" scope="col">Level</th> <th class="ddheader" scope="col"><abbr title="Credit Hours">Cred</abbr></th> <th class="ddheader" scope="col">Grade Mode</th> <th class="ddheader" scope="col">Title</th> </tr>' error_end = '<tbody></table><br>' index = html_output.index("<!--REGISTRATION_ERRORS-->") inserted = "" inserted += error_start for crn in error_crns inserted += ' <tr> <td class="dddefault">ERROR MESSAGE</td> <td class="dddefault">'+crn+'</td> <td class="dddefault">SUBJ</td> <td class="dddefault">101</td> <td class="dddefault">A</td> <td class="dddefault">Undergrad - Urbana-Champaign</td> <td class="dddefault"> 0.000</td> <td class="dddefault">Standard Letter DFR - UIUC</td> <td class="dddefault">NAME</td> </tr>' end inserted += error_end html_output.insert(index,inserted) end if( current_user != nil && current_user.crns.size > 0 ) table_start = '<h3>Current Schedule</h3> <table class="datadisplaytable" summary="Current Schedule"> <tbody><tr> <th class="ddheader" scope="col">Status</th> <th class="ddheader" scope="col">Action</th> <th class="ddheader" scope="col"><acronym title="Course Reference Number">CRN</acronym></th> <th class="ddheader" scope="col"><abbr title="Subject">Subj</abbr></th> <th class="ddheader" scope="col"><abbr title="Course">Crse</abbr></th> <th class="ddheader" scope="col"><abbr title="Section">Sec</abbr></th> <th class="ddheader" scope="col">Level</th> <th class="ddheader" scope="col"><abbr title="Credit Hours">Cred</abbr></th> <th class="ddheader" scope="col">Grade Mode</th> <th class="ddheader" scope="col">Title</th> </tr>' table_end = '</tbody></table><br>' table_schedule = '<table class="plaintable" summary="Schedule Summary"> <tbody><tr> <td class="pldefault">Total Credit Hours: </td> <td class="pldefault"> 3.000</td> </tr> <tr> <td class="pldefault">Billing Hours:</td> <td class="pldefault"> 3.000</td> </tr> <tr> <td class="pldefault">Minimum Hours:</td> <td class="pldefault"> 12.000</td> </tr> <tr> <td class="pldefault">Maximum Hours:</td> <td class="pldefault"> 18.000</td> </tr> <tr> <td class="pldefault">Date:</td> <td class="pldefault">Apr 08, 2014 09:18 am</td> </tr> </tbody></table> <br>' index = html_output.index("<!--CURRENT_SCHEDULE-->") inserted = "" inserted += table_start for crn in current_user.crns inserted += '<tr> <td class="dddefault"><input type="hidden" name="MESG" value="DUMMY">**Web Registered** on Apr 08, 2014</td> <td class="dddefault"> <label for="action_id1"><span class="fieldlabeltextinvisible">Action</span></label> <select name="RSTS_IN" size="1" id="action_id1"> <option value="" selected="">None </option><option value="DW">Web Drop Course </option></select> </td> <td class="dddefault"><input type="hidden" name="assoc_term_in" value="120148"><input type="hidden" name="CRN_IN" value="'+crn+'">'+crn+'<input type="hidden" name="start_date_in" value="08/25/2014"><input type="hidden" name="end_date_in" value="12/10/2014"></td> <td class="dddefault"><input type="hidden" name="SUBJ" value="SUBJ">SUBJ</td> <td class="dddefault"><input type="hidden" name="CRSE" value="101">101</td> <td class="dddefault"><input type="hidden" name="SEC" value="Q3">Q3</td> <td class="dddefault"><input type="hidden" name="LEVL" value="Undergrad - Urbana-Champaign">Undergrad - Urbana-Champaign</td> <td class="dddefault"><input type="hidden" name="CRED" value=" 3.000"> 3.000</td> <td class="dddefault"><input type="hidden" name="GMOD" value="Standard Letter">Standard Letter</td> <td class="dddefault"><input type="hidden" name="TITLE" value="CLASS NAME">CLASS NAME</td> </tr>' end inserted += table_end inserted += table_schedule html_output.insert(index,inserted) end html_output end get '/detailed' do html_output = "" crn = params[:crn_in] if(classExists(crn,classes)) section = getSection(crn,classes) File.open( FILE_DETAILED, 'r') do |f1| while line = f1.gets html_output += line end end index = html_output.index("<!--CRN-->") html_output.insert(index,section.course_reg_number) index = html_output.index("<!--SUBJ-->") html_output.insert(index,section.subject) index = html_output.index("<!--COURSE-->") html_output.insert(index,section.course) index = html_output.index("<!--CAPACITY-->") html_output.insert(index,section.capacity) index = html_output.index("<!--ACTUAL-->") html_output.insert(index,section.num_enrolled) index = html_output.index("<!--REMAINING-->") html_output.insert(index,(section.capacity.to_i-section.num_enrolled.to_i).to_s) else File.open( FILE_CLASS_NOT_FOUND, 'r') do |f1| while line = f1.gets html_output += line end end end html_output end get '/open_spot' do crn = params[:crn] if(classExists(crn,classes)) section = getSection(crn,classes) section.num_enrolled = "0" end end get '/clear_classes' do html_output = "" for user in users if ( user.netid == params[:netid]) user.clear_classes() puts "Cleared Classes for: "+user.netid html_output +="Cleared Classes for: "+user.netid break end end html_output end
true
5013bf20af134fc258cd1b16f8a957492fc44072
Ruby
winterle/cryptopal
/set5/dh_mitm_injection.rb
UTF-8
1,684
2.671875
3
[]
no_license
require_relative 'dh' g = 2 p = "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024 e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd 3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec 6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f 24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361 c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552 bb9ed529077096966d670c354e4abc9804f1746c08ca237327fff fffffffffffff".to_i(16) #initialize the client dh_cli = DH.new(p,g) dh_cli.gen_priv dh_cli.gen_pub #send params to echo bot, init bot cli_pub = dh_cli.get_pub dh_echo = DH.new(p,g) dh_echo.set_pub_other(cli_pub) dh_echo.gen_priv dh_echo.gen_pub #send bot's public key to client dh_cli.set_pub_other(dh_echo.get_pub) #both parties calculate the session key dh_echo.gen_s dh_cli.gen_s #client sends message to echo, echo sends it back and client can decrypt it cipher = dh_cli.aes_cbc("echo me") dh_echo.echo_msg(cipher) puts dh_cli.aes_cbc_dec(cipher) #now to the MITM with parameter injection: by swapping out the public keys with p, calculation of @session key is doomed: @session = p^priv%p = 0 #initialize the client dh_cli = DH.new(p,g) dh_cli.gen_priv dh_cli.gen_pub #send params to echo bot, init bot dh_echo = DH.new(p,g) dh_mitm = DH.new(p,g) dh_mitm.set_pub_other(p) dh_mitm.gen_priv # inject dh_echo.set_pub_other(p) dh_echo.gen_priv dh_echo.gen_pub # inject dh_cli.set_pub_other(p) #all parties calculate the session key (which is now 0) and derive the aes-cbc key dh_echo.gen_s dh_cli.gen_s dh_mitm.gen_s #now, mitm can read all messages cipher = dh_cli.aes_cbc("very secret") print "mitm read:\n" puts dh_mitm.aes_cbc_dec(cipher)
true
c32504607da9fb9f590ce06f33811b548ab0ec79
Ruby
zohrehj/timestamp_state_fields
/lib/timestamp_state_fields.rb
UTF-8
1,608
2.703125
3
[ "MIT" ]
permissive
module TimestampStateFields extend ActiveSupport::Concern module ClassMethods # Implements ActiveRecord state fields based on timestamp columns. # # Requires a column in the model to have :`state`_at # # Example: # # class User < ActiveRecord::Base # include TimestampStateFields # timestamp_state_fields :subscribed_at, :verified_at # end # # u = User.new # u.mark_as_subscribed # u.subscribed_at # => "2015-11-15 22:51:13 -0800" # u.subscribed? # => true # # User.subscribed.count # Number of subscribed users # User.subscribed.not_verified.count # Number of unsubscribed users that are not verified # def timestamp_state_fields(*timestamps) timestamps.map(&:to_s).each do |timestamp| Raise ArgumentError.new("Timestamp name should end with '_at'") unless timestamp.end_with?("_at") state = timestamp.sub(/_at$/, '') define_singleton_method(:"#{state}") do where.not(timestamp => nil) end define_singleton_method(:"not_#{state}") do where(timestamp => nil) end define_method(:"#{state}?") do read_attribute(timestamp).present? end define_method(:"not_#{state}?") do read_attribute(timestamp).blank? end define_method(:"mark_as_#{state}") do write_attribute(timestamp, Time.current) end define_method(:"mark_as_not_#{state}") do write_attribute(timestamp, nil) end end end end end
true
0708cac7ba520e42464ca1c420d31d94118c353a
Ruby
patcarrasco/collections_practice_vol_2-dumbo-web-111918
/collections_practice.rb
UTF-8
2,234
3.609375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# your code goes here def begins_with_r(array) match_array = [] match_array = array.select {|word| word.start_with?('r')} if array.size == match_array.size true else false end end def contain_a(array) new = [] array.each do |word| eval = word.include?('a') if eval == true new.push(word) end end new end def first_wa(array) array.find do |val| val.to_s.start_with?('wa') ## use .to_s to convert values to STRINGS, then use .start_with?() to check for 'wa' end end def remove_non_strings(array) array.select do |word| word.is_a? String # check if String end end def count_elements(array) a = array.group_by(&:itself) # will group all identical components, put them into a hash under same key a.collect {|key, val| key.merge(count: val.size)} # use merge to combine two hashes into one hash! end =begin def merge_data(keys, data) new = [] keys.each do |i| # iterate through keys array data.first.collect do |key, val| # grab the first if i.values[0] == key new << i.merge(val) end end end new end =end def merge_data(keys, data) merged = [] # create empty array keys.each do |entry| # iterate through keys, grab each entry from hash name_key = entry[:first_name] # assign the name value to match below data.each do |hash| # iterate through data list hash.each do |name, info| # iterate through each hash, assign name, info if name_key == name # if name key in key_entry is == to name in hash merged_hash = {entry.key(name_key) => name_key} # create a hash, where we merge with this assigned order... # .key(value) returns the key for the value entered merged << merged_hash.merge(info) # merge the values from data into this hash end end end end merged end def find_cool(array) new = [] array.each do |hash| temp = hash[:temperature] if temp == 'cool' new << hash end end new end def organize_schools(school_dict) new = {} school_dict.collect do |k, v| new[v[:location]] = [] end new.each do |k, v| school_dict.each do |skl, data| if k == data[:location] v << skl end end end end
true
e940cc83caef2f8348ab682a8a4f0bfbfe5b63b9
Ruby
craigh44/Boris_Bikes
/lib/van.rb
UTF-8
739
2.859375
3
[]
no_license
require_relative 'bike_container' class Van include BikeContainer def initialize(options = {}) self.capacity = options.fetch(:capacity, capacity) end def pick_up_bikes(station) station.unavailable_bikes.each { |broken_bike| station.release(broken_bike) dock(broken_bike)} end def full_error_message 'Van is full' end def deliver_to(garage) unavailable_bikes.each { |broken_bike| garage.dock(broken_bike) release(broken_bike)} end def deliver_to_station(station) available_bikes.each { |fixed_bike| station.dock(fixed_bike) release(fixed_bike)} end def pick_up_from_garage(garage) garage.available_bikes.each { |fixed_bikes| garage.release(fixed_bikes) dock(fixed_bikes) } end end
true
aa78917dfeb59ab282c5b2e9cc17e278a99b9f72
Ruby
Zheka1988/ruby_replay
/lesson_1/ideal_mass.rb
UTF-8
285
3.203125
3
[]
no_license
puts 'Kak vas zovut?' name = gets.chomp # puts "Kakoy u vas ves?" # ves = gets.chomp.to_i puts 'Kakoy u vas rost?' height = gets.chomp.to_i ideal_ves = (height - 110) * 1.15 if ideal_ves < 0 puts 'Vash ves optimalniy!' else puts "#{name}, vash idealniy ves = #{ideal_ves}!!!" end
true
a70110c4b2c933e60505ce861db9abfb90f539a9
Ruby
rwestgeest/dialoogtafels
/spec/lib/csv/person_export_spec.rb
UTF-8
2,076
2.734375
3
[ "MIT" ]
permissive
require 'spec_helper' require 'csv/person_export' module Csv describe Csv do let(:people_repository) { mock(PeopleRepository) } let(:first_person) { Person.new :name => "Piet", :telephone => "123123123", :email => "e@mail.com" } let(:second_person) { Person.new :name => "Henk", :telephone => "234234234", :email => "other@mail.com" } let(:people_to_export) { [ first_person ] } let(:exported_data) { export.run(people_to_export) } let(:export) { Csv::PersonExport.create people_repository } before do people_repository.stub(:profile_field_names) { [] } end describe PersonExport do subject { exported_data } describe "with one person" do it { should have(2).lines } describe "data" do subject { first_data_row_of exported_data } it { should == '"Piet";"123123123";"e@mail.com"' } end end describe "with profile fields" do before{ define_profile_field('bedrijf') } it { should include '"jansen"' } end describe "with more persons" do let(:people_to_export) { [first_person, second_person ] } it { should have(3).lines } describe "data" do subject { second_data_row_of exported_data } it { should == '"Henk";"234234234";"other@mail.com"' } end end describe "header" do subject { header_row_of exported_data } it { should == '"naam";"telefoon";"email"' } describe "with profile fields" do before{ define_profile_field('bedrijf') } it { should include '"bedrijf"' } end end def define_profile_field(field_name) first_person.stub(:"profile_#{field_name}" => "jansen") people_repository.stub(:profile_field_names) { [ field_name ] } end end def header_row_of(data) rows(data).first end def first_data_row_of(data) rows(data)[1] end def second_data_row_of(data) rows(data)[2] end def rows(data) data.split $/ end end end
true
484e0eca560cfad758443b33607c3d11b336c9a7
Ruby
ryuchan00/Miscellaneous
/option_paser/sample.rb
UTF-8
171
2.796875
3
[]
no_license
require 'optparse' opt = OptionParser.new opt.on('-a', '--add', 'add an item') { puts 'Added' } opt.on('-d', '--del', 'delete an item') { puts 'Deleted' } opt.parse(ARGV)
true
d2e01a99c35ebd1b42f16c48dbe3fd04bb1f7600
Ruby
graphiti-api/graphiti_spec_helpers
/lib/graphiti_spec_helpers/errors_proxy.rb
UTF-8
1,133
2.5625
3
[ "MIT" ]
permissive
module GraphitiSpecHelpers class ErrorsProxy class Error attr_reader :json def initialize(json) @json = json end def attribute @json[:meta][:attribute] end # TODO: move to top-level code in errorable def code @json[:meta][:code] end def message @json[:meta][:message] end def title @json[:title] end def detail @json[:detail] end def status @json[:status] end end include Enumerable def initialize(array) @errors = array.map { |e| Error.new(e) } end def [](key) @errors[key] end def each(&blk) @errors.each(&blk) end def length count end def to_h {}.tap do |hash| @errors.each do |e| hash[e.attribute] = e.message end end end def method_missing(id, *args, &blk) if error = @errors.select { |e| e.attribute.to_sym == id } error = error[0] if error.length == 1 return error else super end end end end
true
071cfc4ec8a37c1a6d9a727f75efa7478cf579ad
Ruby
dagpan/ruby-oo-relationships-practice-auto-shop-exercise-nyc04-seng-ft-012720
/app/models/car.rb
UTF-8
717
3.203125
3
[]
no_license
class Car attr_reader :make, :model, :classification @@all = [] def initialize(make, model, classification) @make = make @model = model @classification = classification @@all << self end def self.all @@all # - Get a list of all cars end def self.cars_classifications # - Get a list of all car classifications result= [] all.map do |car| result << car.classification end result.uniq end def mechanics_by_classification #- Get a list of mechanics that have an expertise that matches the car classification Mechanic.all.select do |mechanic| mechanic.specialty == self.classification end end end
true
5a2f86f8384c25a45754e061888889917008b6dd
Ruby
btwelch/gluestick
/lib/gluestick/onboarding.rb
UTF-8
585
2.578125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'json' module Gluestick class OnboardingCustomer attr_accessor :customer_email, :customer_name, :customer_phone, :customer_website def initialize(params = {}) params.each do |k, v| instance_variable_set("@#{k}", v) unless v.nil? end yield self if block_given? end def to_h payload = { :customer_email => @customer_email, :customer_name => @customer_name, :customer_phone => @customer_phone, :customer_website => @customer_website }.reject {|k,v| v.nil?} payload end end end
true
2724ae141b33cb7d9511a9b8bfa14ada5cfb8207
Ruby
annehoogerbrugge/attensi-ec-game
/app/services/weekly_summary.rb
UTF-8
1,195
2.984375
3
[]
no_license
# frozen_string_literal: true class WeeklySummary def initialize(week_number, stat_option) @week_number = week_number.to_i @stat_option = stat_option @scores = {} end def find_top_scores # I forgot to ask; the top players on score, # is that the total score of the week, or the highest score of a single entry # Here are both options # I actually googled this, to get 'commercial', because it was getting ugly... :~ beginning_of_week = Date.commercial(2021, @week_number, 1).beginning_of_day end_of_week = Date.commercial(2021, @week_number, 7).end_of_day scores_of_the_week = Score.where(:start_time => beginning_of_week..end_of_week) case @stat_option when 'single points' scores_of_the_week.ordered_on_points.limit(10) when 'total points' scores_of_the_week.group(:player_id).select("player_id, sum(points) AS points_sum").order('points_sum DESC').limit(10) when 'single playing_time' scores_of_the_week.ordered_on_playing_time.limit(10) else scores_of_the_week.group(:player_id).select("player_id, sum(playing_time) AS playing_time_sum").order('playing_time_sum DESC').limit(10) end end end
true
232f44449651a98a7908afb5b5aa1d88259a9fb9
Ruby
MattRice12/wk2day-01-assignments
/bob2.rb
UTF-8
1,560
3.421875
3
[]
no_license
class Bob attr_accessor :remark def initialize @remark = remark end def feedback(remark) puts "Bob hears #{text.inspect}, and.." end def shouting remark.to_s != remark.upcase end def shouting_gibberish remark =~ /^[A-Z]*$/ end def asking_a_question remark =~ /^[A-Z]([a-z]*\s)*[a-z]*(\?)$/ # remark.to_s == remark.include?("?") end def asking_a_numeric_question /^[A-Z]([a-z]*\s)*([a-z]*\,\s)*([a-z]*\s)*\d*\?$/ end def asking_gibberish /^[a-z]*\?$/ end def hey(remark) if remark.include?("\n") 'Whatever.' elsif remark =~ /^\s/ 'Fine. Be that way!' elsif remark.to_s == '' 'Fine. Be that way!' elsif remark.include?("!") && remark.include?("?") 'Sure.' elsif remark =~ /\?./ 'Whatever.' elsif remark =~ /\W(\!)/ 'Whoa, chill out!' elsif remark =~ /\d(\?)/ 'Sure.' elsif remark =~ /[a-z](!)/ 'Whatever.' elsif remark =~ /^(\d*(\,)(\s))*(\d)(\s)[A-Z]*(\!)/ 'Whoa, chill out!' elsif remark =~ /^([A-Z]*(\s))*[A-Z]*(\?)$/ 'Whoa, chill out!' elsif remark =~ /^([A-Z]*(\s))*[A-Z]*(\!)$/ 'Whoa, chill out!' elsif remark =~ /\d(,)/ 'Whatever.' elsif remark =~ /^([A-Z]*(\s))*[A-Z]*$/ 'Whoa, chill out!' elsif @asking_gibberish 'Sure.' elsif @asking_a_numeric_question 'Sure.' elsif @shouting_gibberish 'Sure.' elsif @asking_a_question 'Sure.' elsif @shouting "Whatever." else "Whatever." end end end
true
8fe5ed926428cceafe5fa9bc924dbe9d36cc1566
Ruby
afrolambo/ruby-oo-relationships-practice-art-gallery-exercise-nyc01-seng-ft-060120
/tools/console.rb
UTF-8
765
2.984375
3
[]
no_license
require_relative '../config/environment.rb' met = Gallery.new("Metropolitan Art Gallery", "New York") charles = Doner.new("Charles", 1000) arty = Artist.new("Arthur", 15, charles) sam = Artist.new("Sam", 25, charles) x = Painting.new("X", 200, arty, met) y = Painting.new("Y", 35, arty, met) w = Painting.new("W", 700, arty, met) a = Painting.new("A", 310, sam, met) b = Painting.new("B", 88, sam, met) binding.pry puts "Bob Ross rules." # What are your models? # Painting, Gallery, Artist # What does your schema look like? # What are the relationships between your models? # Gallery has many artists and many paintings through artists # Artists has many paintings, and has many galleries # A Painting belongs to an Artist, and blongs to a gallery
true
a59cc1d20aed84f2938956f0a32bdc74097448f5
Ruby
japanrock/TwitterTools
/shorten_url.rb
UTF-8
1,297
2.859375
3
[]
no_license
require 'rubygems' require 'net/http' Net::HTTP.version_1_2 require 'json' require 'yaml' # Thanks!! http://d.hatena.ne.jp/m-kawato/20090603/1244041369 # Usage: # shorten_url = ShortenURL.new # shorten_url.get_short_url("http://yahoo.co.jp") # puts shorten_url.short_url # => http://bit.ly/dnBGwo class ShortenURL attr_reader :short_url def initialize @api_key = YAML.load_file(File.dirname(__FILE__) + '/bit_ly_api_key.yml') @long_url = '' @short_url = '' @api_result = '' @query = '' end # このメソッドはイケテないのであとで修正・・・ def get_short_url(long_url) set_long_url(long_url) make_query api_call make_short_url end private def set_long_url(long_url) @long_url = [long_url] end # bit.ly Web APIに渡すquery stringの生成 def make_query @query = 'version=2.0.1&' + @long_url.map {|url| "longUrl=#{url}"}.join('&') + '&login=' + "#{@api_key['USERNAME']}" + '&apiKey=' + "#{@api_key['API_KEY']}" end # bit.ly APIの呼び出し def api_call @api_result = JSON.parse(Net::HTTP.get("api.bit.ly", "/shorten?#{@query}")) end def make_short_url @api_result['results'].each_pair {|long_url, value| @short_url = value['shortUrl'] } end end
true
d34db33faf07e7144bb981a8d88f16c96fdf12d8
Ruby
brenoperucchi/tdlib-ruby
/lib/tdlib/types/validated_order_info.rb
UTF-8
511
2.546875
3
[ "MIT" ]
permissive
module TD::Types # Contains a temporary identifier of validated order information, which is stored for one hour. # Also contains the available shipping options. # # @attr order_info_id [String] Temporary identifier of the order information. # @attr shipping_options [Array<TD::Types::ShippingOption>] Available shipping options. class ValidatedOrderInfo < Base attribute :order_info_id, TD::Types::String attribute :shipping_options, TD::Types::Array.of(TD::Types::ShippingOption) end end
true
a3166d6ec8c9313b4c45e991c2efdca6911dc1e8
Ruby
norskbrek/ruby-foundations
/small_problems/02_easy1/06.rb
UTF-8
276
3.703125
4
[]
no_license
def reverse_words(string) words = [] string.split.each do |word| word.reverse! if word.length >= 5 words.push(word) end words.join(' ') end puts reverse_words('Professional') puts reverse_words('Walk around the block') puts reverse_words('Launch School')
true
39e7d96d6f46a939f2745decf4b5511a2c449a53
Ruby
postageapp/configature
/spec/unit/configature_data_spec.rb
UTF-8
1,118
2.640625
3
[ "MIT" ]
permissive
RSpec.describe Configature::Data do context 'can be initialized with' do it 'defaults' do data = Configature::Data.new expect(data.test).to eq(nil) expect(data.to_h).to eq({ }) end it 'a Hash' do data = Configature::Data.new(test: 'value') expect(data.test).to eq('value') expect(data.to_h).to eq(test: 'value') end end context 'can be converted to a regular Hash' do it 'at one level' do data = Configature::Data.new(test: 'value') expect(data.to_h).to eq(test: 'value') end it 'with nested Data structures' do data = Configature::Data.new( top: Configature::Data.new( level: 1 ), array: [ Configature::Data.new(index: 0), Configature::Data.new(index: 1), [ Configature::Data.new(index: 2), ] ] ) expect(data.to_h).to eq( top: { level: 1 }, array: [ { index: 0 }, { index: 1 }, [ { index: 2 } ] ] ) end end end
true
89315964cdae0b5c4b88bf36fe31d570c1233dde
Ruby
nulogy/Gorgon
/spec/host_state_spec.rb
UTF-8
2,261
2.796875
3
[]
no_license
require 'gorgon/host_state' describe Gorgon::HostState do it { should respond_to(:file_started).with(2).arguments } it { should respond_to(:file_finished).with(2).arguments } it { should respond_to(:each_running_file).with(0).argument } it { should respond_to(:total_running_workers).with(0).argument } before do @host_state = Gorgon::HostState.new end describe "#total_workers_running" do it "returns 0 if there are no worker running files" do expect(@host_state.total_running_workers).to eq(0) end it "returns 1 if #file_started was called, but #file_finished has not been called with such a worker id" do @host_state.file_started "worker1", "path/to/file.rb" expect(@host_state.total_running_workers).to eq(1) end it "returns 0 if #file_started and #file_finished were called for the same worker_id" do @host_state.file_started "worker1", "path/to/file.rb" @host_state.file_finished "worker1", "path/to/file.rb" expect(@host_state.total_running_workers).to eq(0) end it "returns 1 if #file_started and #file_finished were called for different worker id (worker1)" do @host_state.file_started "worker1", "path/to/file.rb" @host_state.file_started "worker2", "path/to/file2.rb" @host_state.file_finished "worker2", "path/to/file2.rb" expect(@host_state.total_running_workers).to eq(1) end end describe "#each_running_file" do before do @host_state.file_started "worker1", "path/to/file1.rb" @host_state.file_started "worker2", "path/to/file2.rb" end context "when no #file_finished has been called" do it "yields each currently running file" do files = [] @host_state.each_running_file do |file| files << file end expect(files).to eq(["path/to/file1.rb", "path/to/file2.rb"]) end end context "when #file_finished has been called for one of the workers" do it "yields each currently running file" do @host_state.file_finished "worker2", "path/to/file2.rb" files = [] @host_state.each_running_file do |file| files << file end expect(files).to eq(["path/to/file1.rb"]) end end end end
true
7082322c997a01e381a2469d31e4cc92c2c10d5c
Ruby
nicrou/hotel_management_system
/app/helpers/currency_helper.rb
UTF-8
171
2.546875
3
[]
no_license
module CurrencyHelper def number_to_euro(number) number_to_currency(number, :unit => '€', precision: 2, separator: ",", delimiter: ".", format: "%n %u") end end
true
98ea49c762d84195c1560257ae12ff3655f082e6
Ruby
sdonohue0918/rails-create-action-readme-nyc01-seng-ft-082420
/app/controllers/posts_controller.rb
UTF-8
728
2.734375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class PostsController < ApplicationController def index @posts = Post.all end def show @post = Post.find(params[:id]) end def new @post = Post.new end def create @post = Post.new @post.title = params[:title] @post.description = params[:description] @post.save redirect_to post_path(@post) end # add create method here end # When a user submits a form, it is the params hash that contains all the input data. As long as the form is routed to the create method we've written (in config/routes.rb), we'll be able to initialize a new instance of Post, grab those input values from params, assign them the post instance attributes and save the instance to our database.
true
2ca0799276ff0a9d416ac4615a07a9ca48cacff1
Ruby
alphagov/smart-answers
/test/unit/calculators/marriage_abroad_data_query_test.rb
UTF-8
13,229
2.515625
3
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
require_relative "../../test_helper" module SmartAnswer module Calculators class MarriageAbroadDataQueryTest < ActiveSupport::TestCase context MarriageAbroadDataQuery do setup do @data_query = MarriageAbroadDataQuery.new end context "#marriage_data" do should "load data from yaml file only once" do YAML.stubs(:load_file).returns({}) YAML.expects(:load_file).once.returns({}) @data_query.marriage_data @data_query.marriage_data end should "load data from correct path leading to marriage_abroad_data.yml" do path = Rails.root.join("config/smart_answers/marriage_abroad_data.yml") YAML.stubs(:load_file).returns({}) YAML.expects(:load_file).with(path).returns({}) @data_query.marriage_data end should "only contain pre-defined data keys" do keys = %w[countries_with_18_outcomes countries_with_19_outcomes countries_with_2_outcomes countries_with_3_outcomes countries_with_2_outcomes_marriage_or_pacs countries_with_6_outcomes countries_with_ceremony_location_outcomes countries_with_9_outcomes countries_with_1_outcome] data = @data_query.marriage_data assert_equal keys, data.keys end end context "#countries_with_18_outcomes" do should "returns countries that are listed to have 18 outcomes" do YAML.stubs(:load_file).returns(countries_with_18_outcomes: %w[anguilla bermuda]) assert_equal %w[anguilla bermuda], @data_query.countries_with_18_outcomes end should "return empty array if no country is found" do YAML.stubs(:load_file).returns(countries_with_18_outcomes: nil) assert_equal [], @data_query.countries_with_18_outcomes end should "throw RuntimeError if data structure isn't an array of strings" do YAML.stubs(:load_file).returns(countries_with_18_outcomes: [{ sample: "value" }]) exception = assert_raises RuntimeError do @data_query.countries_with_18_outcomes end assert_equal exception.message, "Country list must be an array of strings" end should "throw RuntimeError if data structure is a Hash" do YAML.stubs(:load_file).returns(countries_with_18_outcomes: {}) exception = assert_raises RuntimeError do @data_query.countries_with_18_outcomes end assert_equal exception.message, "Country list must be an array of strings" end should "throw KeyError if countries_with_18_outcomes is missing" do YAML.stubs(:load_file).returns({}) exception = assert_raises KeyError do @data_query.countries_with_18_outcomes end assert_equal exception.message, "key not found: \"countries_with_18_outcomes\"" end end context "#countries_with_2_outcomes" do should "returns countries that are listed to have 2 outcomes" do YAML.stubs(:load_file).returns(countries_with_2_outcomes: %w[aruba bonaire-st-eustatius-saba]) assert_equal %w[aruba bonaire-st-eustatius-saba], @data_query.countries_with_2_outcomes end should "return empty array if no country is found" do YAML.stubs(:load_file).returns(countries_with_2_outcomes: nil) assert_equal [], @data_query.countries_with_2_outcomes end should "throw RuntimeError if data structure isn't an array of strings" do YAML.stubs(:load_file).returns(countries_with_2_outcomes: [{ sample: "value" }]) exception = assert_raises RuntimeError do @data_query.countries_with_2_outcomes end assert_equal exception.message, "Country list must be an array of strings" end should "throw RuntimeError if data structure is a Hash" do YAML.stubs(:load_file).returns(countries_with_2_outcomes: {}) exception = assert_raises RuntimeError do @data_query.countries_with_2_outcomes end assert_equal exception.message, "Country list must be an array of strings" end should "throw KeyError if countries_with_2_outcomes is missing" do YAML.stubs(:load_file).returns({}) exception = assert_raises KeyError do @data_query.countries_with_2_outcomes end assert_equal exception.message, "key not found: \"countries_with_2_outcomes\"" end end context "#countries_with_2_outcomes_marriage_or_pacs" do should "returns countries that are listed to have 2 marriage or pacs outcomes" do YAML.stubs(:load_file).returns(countries_with_2_outcomes_marriage_or_pacs: %w[monaco wallis-and-futuna new-caledonia]) assert_equal %w[monaco wallis-and-futuna new-caledonia], @data_query.countries_with_2_outcomes_marriage_or_pacs end should "return empty array if no country is found" do YAML.stubs(:load_file).returns(countries_with_2_outcomes_marriage_or_pacs: nil) assert_equal [], @data_query.countries_with_2_outcomes_marriage_or_pacs end should "throw RuntimeError if data structure isn't an array of strings" do YAML.stubs(:load_file).returns(countries_with_2_outcomes_marriage_or_pacs: [{ sample: "value" }]) exception = assert_raises RuntimeError do @data_query.countries_with_2_outcomes_marriage_or_pacs end assert_equal exception.message, "Country list must be an array of strings" end should "throw RuntimeError if data structure is a Hash" do YAML.stubs(:load_file).returns(countries_with_2_outcomes_marriage_or_pacs: {}) exception = assert_raises RuntimeError do @data_query.countries_with_2_outcomes_marriage_or_pacs end assert_equal exception.message, "Country list must be an array of strings" end should "throw KeyError if countries_with_2_outcomes_marriage_or_pacs is missing" do YAML.stubs(:load_file).returns({}) exception = assert_raises KeyError do @data_query.countries_with_2_outcomes_marriage_or_pacs end assert_equal exception.message, "key not found: \"countries_with_2_outcomes_marriage_or_pacs\"" end end context "#countries_with_6_outcomes" do should "returns countries that are listed to have 6 outcomes" do YAML.stubs(:load_file).returns(countries_with_6_outcomes: %w[argentina brazil]) assert_equal %w[argentina brazil], @data_query.countries_with_6_outcomes end should "return empty array if no country is found" do YAML.stubs(:load_file).returns(countries_with_6_outcomes: nil) assert_equal [], @data_query.countries_with_6_outcomes end should "throw RuntimeError if data structure isn't an array of strings" do YAML.stubs(:load_file).returns(countries_with_6_outcomes: [{ sample: "value" }]) exception = assert_raises RuntimeError do @data_query.countries_with_6_outcomes end assert_equal exception.message, "Country list must be an array of strings" end should "throw RuntimeError if data structure is a Hash" do YAML.stubs(:load_file).returns(countries_with_6_outcomes: {}) exception = assert_raises RuntimeError do @data_query.countries_with_6_outcomes end assert_equal exception.message, "Country list must be an array of strings" end should "throw KeyError if countries_with_6_outcomes is missing" do YAML.stubs(:load_file).returns({}) exception = assert_raises KeyError do @data_query.countries_with_6_outcomes end assert_equal exception.message, "key not found: \"countries_with_6_outcomes\"" end end context "#countries_with_ceremony_location_outcomes" do should "returns countries that are listed to have ceremony location outcomes" do YAML.stubs(:load_file).returns(countries_with_ceremony_location_outcomes: %w[finland]) assert_equal %w[finland], @data_query.countries_with_ceremony_location_outcomes end should "return empty array if no country is found" do YAML.stubs(:load_file).returns(countries_with_ceremony_location_outcomes: nil) assert_equal [], @data_query.countries_with_ceremony_location_outcomes end should "throw RuntimeError if data structure isn't an array of strings" do YAML.stubs(:load_file).returns(countries_with_ceremony_location_outcomes: [{ sample: "value" }]) exception = assert_raises RuntimeError do @data_query.countries_with_ceremony_location_outcomes end assert_equal exception.message, "Country list must be an array of strings" end should "throw RuntimeError if data structure is a Hash" do YAML.stubs(:load_file).returns(countries_with_ceremony_location_outcomes: {}) exception = assert_raises RuntimeError do @data_query.countries_with_ceremony_location_outcomes end assert_equal exception.message, "Country list must be an array of strings" end should "throw KeyError if countries_with_ceremony_location_outcomes is missing" do YAML.stubs(:load_file).returns({}) exception = assert_raises KeyError do @data_query.countries_with_ceremony_location_outcomes end assert_equal exception.message, "key not found: \"countries_with_ceremony_location_outcomes\"" end end context "#countries_with_1_outcome" do should "returns countries that are listed to have 1 outcomes" do YAML.stubs(:load_file).returns(countries_with_1_outcome: %w[monaco new-caledonia]) assert_equal %w[monaco new-caledonia], @data_query.countries_with_1_outcome end should "return empty array if no country is found" do YAML.stubs(:load_file).returns(countries_with_1_outcome: nil) assert_equal [], @data_query.countries_with_1_outcome end should "throw RuntimeError if data structure isn't an array of strings" do YAML.stubs(:load_file).returns(countries_with_1_outcome: [{ sample: "value" }]) exception = assert_raises RuntimeError do @data_query.countries_with_1_outcome end assert_equal exception.message, "Country list must be an array of strings" end should "throw RuntimeError if data structure is a Hash" do YAML.stubs(:load_file).returns(countries_with_1_outcome: {}) exception = assert_raises RuntimeError do @data_query.countries_with_1_outcome end assert_equal exception.message, "Country list must be an array of strings" end should "throw KeyError if countries_with_1_outcome is missing" do YAML.stubs(:load_file).returns({}) exception = assert_raises KeyError do @data_query.countries_with_1_outcome end assert_equal exception.message, "key not found: \"countries_with_1_outcome\"" end end context "#outcome_per_path_countries" do should "return an alphabetical list of countries under all outcome groups" do YAML.stubs(:load_file).returns( countries_with_18_outcomes: %w[anguilla], countries_with_19_outcomes: %w[panama], countries_with_6_outcomes: %w[bermuda], countries_with_2_outcomes: %w[cayman-islands], countries_with_3_outcomes: %w[japan], countries_with_2_outcomes_marriage_or_pacs: %w[monaco], countries_with_ceremony_location_outcomes: %w[finland], countries_with_9_outcomes: %w[chile], countries_with_1_outcome: %w[french-guiana], ) assert_equal @data_query.outcome_per_path_countries, %w[anguilla bermuda cayman-islands chile finland french-guiana japan monaco panama] end end end end end end
true
cd3eaf0de9bf9bb7acd0d1a4751a1194f0bfaa27
Ruby
hidehiro98/some_codes
/atcoder_abc001_4.rb
UTF-8
893
3.25
3
[]
no_license
# this programme only pass the tests partial a = [] result = [] n = gets.chomp.to_i n.times do b = gets.chomp temp_array = [] temp_array2 = [] temp_array = b.split("-").map(&:to_i) temp_array.each_with_index do |num, index| if (num % 5).zero? temp_array2 << num else if index.zero? temp_array2 << (num / 5) * 5 else if 55 < (num % 100) && (num % 100) < 60 temp_array2 << (num / 100 + 1) * 100 else temp_array2 << ((num + 4) / 5) * 5 end end end end a << temp_array2 end a.sort! a.each_with_index do |arr, index| if index.zero? result << arr elsif result[-1][1] >= arr[0] result[-1][1] = arr[1] if result[-1][1] < arr[1] else result << arr end end result.each do |arr| arr2 = arr.map do |e| sprintf("%04d", e) end puts arr2.join("-") $stdout.flush end
true
6354e2088d9e82a8d8c046a8087d049c2d5043fa
Ruby
agrberg/benchmarks
/string_shovel_join_or_interp.rb
UTF-8
970
3
3
[]
no_license
#!/usr/bin/env ruby require 'benchmark' # Make sure you `gem install benchmark-ips` require 'benchmark/ips' TIMES = [5, 20, 100] ALPHA = ('a'..'z').to_a benchmark_lambda = lambda do |x| TIMES.each do |i| base_string = Array.new(i) { ALPHA.sample }.join TIMES.each do |j| string_to_append = Array.new(j) { ALPHA.sample }.join x.report("interpolation - #{i} + #{j} = #{i + j}") do # this is the fastest in almost all cases at all sizes "#{base_string}/#{string_to_append}" end x.report("join - #{i} + #{j} = #{i + j}") do [base_string, string_to_append].join('/') end x.report("<< - #{i} + #{j} = #{i + j}") do base_string.dup << string_to_append end x.report("interp + << - #{i} + #{j} = #{i + j}") do "#{base_string}/" << string_to_append end end end x.compare! # uncomment if you want comparisons between them all end Benchmark.ips(&benchmark_lambda); nil
true
6ddfbcd5c38c3a4664a43b992dcb16345af759fc
Ruby
arvida/cf-invalidator
/cf-invalidator.rb
UTF-8
2,221
2.796875
3
[]
no_license
#!/usr/bin/env ruby puts " * Please install the fog gem\n $ gem install fog" and exit if !defined?("Fog") == 'constant' && Fog.class == Module require 'rubygems' require 'optparse' require 'fog' options = {} opt_parser = OptionParser.new do |opt| opt.banner = "Usage: cf-invalidator.rb -a ACCESS_KEY_ID -s SECRET_ACCESS_KEY -i DISTRIBUTION_ID [PATH1 PATH2]" opt.on('-i','--distribution_id DISTRIBUTION_ID', '') do |distribution_id| options[:distribution_id] = distribution_id end opt.on('-a','--access_key_id ACCESS_KEY_ID', '') do |access_key_id| options[:access_key_id] = access_key_id end opt.on('-s','--secret_access_key SECRET_ACCESS_KEY', '') do |secret_access_key| options[:secret_access_key] = secret_access_key end end opt_parser.parse! options[:paths] = ARGV class CloudFrontInvalidator def initialize(arguments) @options = arguments end def connection @connection ||= Fog::CDN.new( :provider => 'AWS', :aws_access_key_id => @options[:access_key_id], :aws_secret_access_key => @options[:secret_access_key] ) end def has_paths? @options[:paths].any? end def has_distribution_id? @options[:distribution_id] end def invalidate_paths connection.get_distribution(@options[:distribution_id]) puts "== Invalidating\n#{@options[:paths].join("\n")}" connection.post_invalidation(@options[:distribution_id], @options[:paths]).tap do |response| puts " * InvalidationId: #{response.body['Id']}\n" end end def list_invalidations connection.get_invalidation_list(@options[:distribution_id]).tap do |response| if response.body['InvalidationSummary'].any? puts "== Invalidation list" response.body['InvalidationSummary'].each do |invalidation| puts "#{invalidation['Id']} - #{invalidation['Status']}" end end end end def self.perform_with(arguments) CloudFrontInvalidator.new(arguments).tap do |invalidator| invalidator.invalidate_paths if invalidator.has_distribution_id? and invalidator.has_paths? invalidator.list_invalidations if invalidator.has_distribution_id? end end end CloudFrontInvalidator.perform_with options
true
093186d14391f7f57017b62a0aaafffd9fd2c620
Ruby
vinay-ankola/pickaxe
/stock_stats.rb
UTF-8
286
2.9375
3
[]
no_license
require_relative 'csv_reader' reader = CsvReader.new ARGV.each do |csv_file_name| STDERR.puts "Processing #{csv_file_name}" reader.read_in_csv_data(csv_file_name) end puts "Total value = #{reader.total_value_in_stock}" #b1 = BookInStock.new("isbn1", 3) #puts b1 #p b1
true
319042bb10d34129c6069d87357a19b58168208b
Ruby
cojenco/binary-and-decimal
/test/binary_to_decimal_test.rb
UTF-8
1,661
2.984375
3
[]
no_license
require 'minitest/autorun' require 'minitest/reporters' require_relative '../lib/binary_to_decimal' Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new describe "binary to decimal" do it "From 10011001 to 153" do binary_array = [1, 0, 0, 1, 1, 0, 0, 1] expected_decimal = 153 binary_to_decimal(binary_array).must_equal expected_decimal end it "From 00001101 to 13" do binary_array = [0, 0, 0, 0, 1, 1, 0, 1] expected_decimal = 13 binary_to_decimal(binary_array).must_equal expected_decimal end it "From 10000000 to 128" do binary_array = [1, 0, 0, 0, 0, 0, 0, 0] expected_decimal = 128 binary_to_decimal(binary_array).must_equal expected_decimal end it "From random binary to decimal" do binary_array = Array.new(8) { rand(0..1) } expected_decimal = binary_array.join.to_s.to_i(2) binary_to_decimal(binary_array).must_equal expected_decimal end end # Optional: Testing for decimal_to_binary method describe "decimal to binary" do it "From 13 to 1101" do decimal_input = 13 expected_binary = [1, 1, 0, 1] decimal_to_binary(decimal_input).must_equal expected_binary end it "From 153 to 10011001" do decimal_input = 153 expected_binary = [1, 0, 0, 1, 1, 0, 0, 1] decimal_to_binary(decimal_input).must_equal expected_binary end it "From 0 to 0" do decimal_input = 0 expected_binary = [0] decimal_to_binary(decimal_input).must_equal expected_binary end it "Raises ArgumentError if a negative value is passed in" do decimal_input = (-128) expect{decimal_to_binary(decimal_input)}.must_raise ArgumentError end end
true
d9e9d8a4fe95bda4f77c360193d8c9b516ef13ab
Ruby
nergzd723/osdev
/script/user_program_dump
UTF-8
194
2.515625
3
[]
no_license
#!/usr/bin/env ruby raw = `xxd user_program.bin` lines = raw.split("\n") formatted_lines = lines.map do |line| line[9,41].tr(' ', '') end puts formatted_lines.join("").gsub(/(.{2})/, '\1 ')
true
e048ea1fd88bef866efa224309c0a94c0437cb6e
Ruby
metade/rena
/spec/literal_spec.rb
UTF-8
4,504
2.59375
3
[ "MIT" ]
permissive
require 'lib/rena' describe "Literals" do it "accept a language tag" do f = Literal.untyped("tom", "en") f.lang.should == "en" end it "accepts an encoding" do f = Literal.typed("tom", "http://www.w3.org/2001/XMLSchema#string") f.encoding.to_s.should == "http://www.w3.org/2001/XMLSchema#string" end it "should be equal if they have the same contents" do f = Literal.untyped("tom") g = Literal.untyped("tom") f.should == g end it "should not be equal if they do not have the same contents" do f = Literal.untyped("tom") g = Literal.untyped("tim") f.should_not == g end it "should be equal if they have the same contents and language" do f = Literal.untyped("tom", "en") g = Literal.untyped("tom", "en") f.should == g end it "should return a string using to_s" do f = Literal.untyped("tom") f.to_s.should == "tom" end it "should not be equal if they do not have the same contents and language" do f = Literal.untyped("tom", "en") g = Literal.untyped("tim", "en") f.should_not == g lf = Literal.untyped("tom", "en") lg = Literal.untyped("tom", "fr") lf.should_not == lg end it "should be equal if they have the same contents and datatype" do f = Literal.typed("tom", "http://www.w3.org/2001/XMLSchema#string") g = Literal.typed("tom", "http://www.w3.org/2001/XMLSchema#string") f.should == g end it "should not be equal if they do not have the same contents and datatype" do f = Literal.typed("tom", "http://www.w3.org/2001/XMLSchema#string") g = Literal.typed("tim", "http://www.w3.org/2001/XMLSchema#string") f.should_not == g dtf = Literal.typed("tom", "http://www.w3.org/2001/XMLSchema#string") dtg = Literal.typed("tom", "http://www.w3.org/2001/XMLSchema#token") dtf.should_not == dtg end it "should return valid N3/NTriples format strings" do f = Literal.untyped("tom") f.to_n3.should == "\"tom\"" f.to_ntriples.should == f.to_n3 g = Literal.untyped("tom", "en") g.to_n3.should == "\"tom\"@en" f.to_ntriples.should == f.to_n3 typed_int = Literal.typed(5, "http://www.w3.org/2001/XMLSchema#int") typed_int.to_n3.should == "5^^<http://www.w3.org/2001/XMLSchema#int>" typed_int.to_ntriples.should == typed_int.to_n3 typed_string = Literal.typed("foo", "http://www.w3.org/2001/XMLSchema#string") typed_string.to_n3.should == "\"foo\"^^<http://www.w3.org/2001/XMLSchema#string>" typed_string.to_ntriples.should == typed_string.to_n3 end it "should normalize language tags to lower case" do f = Literal.untyped("tom", "EN") f.lang.should == "en" end it "should support TriX encoding" do e = Literal.untyped("tom") e.to_trix.should == "<plainLiteral>tom</plainLiteral>" f = Literal.untyped("tom", "en") f.to_trix.should == "<plainLiteral xml:lang=\"en\">tom</plainLiteral>" g = Literal.typed("tom", "http://www.w3.org/2001/XMLSchema#string") g.to_trix.should == "<typedLiteral datatype=\"http://www.w3.org/2001/XMLSchema#string\">tom</typedLiteral>" end it "should handle XML litearls" do # first we should detect XML literals and mark them as such in the class f = Literal.typed("foo <sup>bar</sup> baz!", "http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral") f.xmlliteral?.should == true # pending "TODO: the thought of XML literals makes me want to wretch" end it "build_from should infer the type" do int = Literal.build_from(15) int.encoding.should == "http://www.w3.org/2001/XMLSchema#int" float = Literal.build_from(15.4) float.encoding.should == "http://www.w3.org/2001/XMLSchema#float" other = Literal.build_from("foo") other.encoding.should == "http://www.w3.org/2001/XMLSchema#string" end it "build_from_language" do english = Literal.build_from_language("Have a nice day") english.encoding.should == "en" french = Literal.build_from_language("Bonjour, madame. Parlez vous francais?") french.encoding.should == "fr" german = Literal.build_from_language("Achtung") german.encoding.should == "de" end # TODO: refactor based on new interface # describe "Languages" do # it "should be inspectable" do # literal = Rena::Literal.new("foo", "en") # lang = literal.lang # lang.to_s == "en" # lang.hash.class.should == Fixnum # end # end end
true
5ea3445595809cba524139350cc04f8d9296126c
Ruby
shhavel/training_tasks
/spec/07_stacks_and_queues/02_brackets_spec.rb
UTF-8
569
3.15625
3
[]
no_license
# frozen_string_literal: true describe 'solution' do def solution(s) len = s.length return 1 if len == 0 return 0 if len.odd? open_b = (o1, o2, o3 = %w<( [ {>) c1, c2, c3 = %w<) ] }> opened = [] s.each_char do |b| if open_b.include?(b) opened << b else o = opened.pop return 0 unless (o == o1 && b == c1) || (o == o2 && b == c2) || (o == o3 && b == c3) end end opened.empty? ? 1 : 0 end it { expect(solution('{[()()]}')).to eql(1) } it { expect(solution('([)()]')).to eql(0) } end
true
08df1d967750a2e99841f3b0b7eff7fdf428ee8a
Ruby
agrmv/SoftwareOptimization
/degree_conversion/lib/input_checker/input_check.rb
UTF-8
277
3.359375
3
[]
no_license
class InputCheck def is_number?(string) string if Float(string) rescue abort("Value not a numeric") end def unit_is_true?(string) if string == 'C' or string == 'K' or string == 'F' string else abort("Unit is not true(C, K, F)") end end end
true
d872e48363bd337f59b5d0339bfc4b9604115036
Ruby
antonzaharia/algorithms
/Ruby/last_digit.rb
UTF-8
142
3.40625
3
[]
no_license
class LastDigit def last_digit(n1, n2) square = n1**n2 square.infinite? ? 0 : square.to_s.split("").last.to_i end end
true
4701d83ee9be252e681f9177f3456b96ec8c70ff
Ruby
fursich/pry-stack_explorer
/test/commands_test.rb
UTF-8
11,608
2.921875
3
[ "MIT" ]
permissive
require_relative 'test_helper' class Top attr_accessor :method_list, :middle def initialize method_list @method_list = method_list end def bing @middle = Middle.new method_list @middle.bong end end class Middle attr_accessor :method_list, :bottom def initialize method_list @method_list = method_list end def bong @bottom = Bottom.new method_list @bottom.bang end end class Bottom attr_accessor :method_list def initialize method_list @method_list = method_list end def bang Pry.start(binding) end end describe "Commands" do let(:bingbong){ BingBong.new } include ResetHelper before do method_list = [] @top = Top.new method_list end describe "stack" do it "outputs the call stack" do output = issue_pry_commands("stack"){ bingbong.bing } expect(output).to match(/bang.*?bong.*?bing/m) end it "supports 'show-stack' as an alias" do output = issue_pry_commands("show-stack"){ bingbong.bing } expect(output).to match(/bang.*?bong.*?bing/m) end end describe "up" do it 'should move up the call stack one frame at a time' do redirect_pry_io(InputTester.new("@methods << __method__", "up", "@methods << __method__", "up", "@methods << __method__", "exit-all"), out=StringIO.new) do bingbong.bing end expect(bingbong.methods).to eq [:bang, :bong, :bing] end it 'should move up the call stack two frames at a time' do redirect_pry_io(InputTester.new("@methods << __method__", "up 2", "@methods << __method__", "exit-all"), out=StringIO.new) do bingbong.bing end expect(bingbong.methods).to eq [:bang, :bing] end describe "by method name regex" do it 'should move to the method name that matches the regex' do redirect_pry_io(InputTester.new("@methods << __method__", "up bi", "@methods << __method__", "exit-all"), out=StringIO.new) do bingbong.bing end expect(bingbong.methods).to eq [:bang, :bing] end it 'should move through all methods that match regex in order' do redirect_pry_io(InputTester.new("@methods << __method__", "up b", "@methods << __method__", "up b", "@methods << __method__", "exit-all"), out=StringIO.new) do bingbong.bing end expect(bingbong.methods).to eq [:bang, :bong, :bing] end it 'should error if it cant find frame to match regex' do redirect_pry_io(InputTester.new("up conrad_irwin", "exit-all"), out=StringIO.new) do bingbong.bing end expect(out.string).to match(/Error: No frame that matches/) end end describe 'by Class#method name regex' do it 'should move to the method and class that matches the regex' do redirect_pry_io(InputTester.new("@method_list << self.class.to_s + '#' + __method__.to_s", 'up Middle#bong', "@method_list << self.class.to_s + '#' + __method__.to_s", "exit-all"), out=StringIO.new) do @top.bing end expect(@top.method_list).to eq(['Bottom#bang', 'Middle#bong']) end ### ????? ### # it 'should be case sensitive' do # end ### ????? ### it 'should allow partial class names' do redirect_pry_io(InputTester.new("@method_list << self.class.to_s + '#' + __method__.to_s", 'up Mid#bong', "@method_list << self.class.to_s + '#' + __method__.to_s", "exit-all"), out=StringIO.new) do @top.bing end expect(@top.method_list).to eq(['Bottom#bang', 'Middle#bong']) end it 'should allow partial method names' do redirect_pry_io(InputTester.new("@method_list << self.class.to_s + '#' + __method__.to_s", 'up Middle#bo', "@method_list << self.class.to_s + '#' + __method__.to_s", "exit-all"), out=StringIO.new) do @top.bing end expect(@top.method_list).to eq(['Bottom#bang', 'Middle#bong']) end it 'should error if it cant find frame to match regex' do redirect_pry_io(InputTester.new('up Conrad#irwin', "exit-all"), out=StringIO.new) do @top.bing end expect(out.string).to match(/Error: No frame that matches/) end end end describe "down" do it 'should move down the call stack one frame at a time' do def bingbong.bang() Pry.start(binding, :initial_frame => 1) end redirect_pry_io(InputTester.new("@methods << __method__", "down", "@methods << __method__", "exit-all"), out=StringIO.new) do bingbong.bing end expect(bingbong.methods).to eq [:bong, :bang] end it 'should move down the call stack two frames at a time' do def bingbong.bang() Pry.start(binding, :initial_frame => 2) end redirect_pry_io(InputTester.new("@methods << __method__", "down 2", "@methods << __method__", "exit-all"), out=StringIO.new) do bingbong.bing end expect(bingbong.methods).to eq [:bing, :bang] end describe "by method name regex" do it 'should move to the method name that matches the regex' do redirect_pry_io(InputTester.new("frame -1", "down bo", "@methods << __method__", "exit-all"), out=StringIO.new) do bingbong.bing end expect(bingbong.methods[0]).to eq(:bong) end it 'should move through all methods that match regex in order' do redirect_pry_io(InputTester.new("frame bing", "@methods << __method__", "down b", "@methods << __method__", "down b", "@methods << __method__", "exit-all"), out=StringIO.new) do bingbong.bing end expect(bingbong.methods).to eq [:bing, :bong, :bang] end it 'should error if it cant find frame to match regex' do redirect_pry_io(InputTester.new("frame -1", "down conrad_irwin", "exit-all"), out=StringIO.new) do bingbong.bing end expect(out.string).to match(/Error: No frame that matches/) end end describe 'by Class#method name regex' do it 'should move to the method and class that matches the regex' do redirect_pry_io(InputTester.new('frame Top#bing', "@method_list << self.class.to_s + '#' + __method__.to_s", 'down Middle#bong', "@method_list << self.class.to_s + '#' + __method__.to_s", "exit-all"), out=StringIO.new) do @top.bing end expect(@top.method_list).to eq(['Top#bing', 'Middle#bong']) end ### ????? ### # it 'should be case sensitive' do # end ### ????? ### it 'should error if it cant find frame to match regex' do redirect_pry_io(InputTester.new('down Conrad#irwin', "exit-all"), out=StringIO.new) do @top.bing end expect(out.string).to match(/Error: No frame that matches/) end end end describe "frame" do describe "by method name regex" do it 'should jump to correct stack frame when given method name' do redirect_pry_io(InputTester.new("frame bi", "@methods << __method__", "exit-all"), out=StringIO.new) do bingbong.bing end expect(bingbong.methods[0]).to eq(:bing) end it 'should NOT jump to frames lower down stack when given method name' do redirect_pry_io(InputTester.new("frame -1", "frame bang", "exit-all"), out=StringIO.new) do bingbong.bing end expect(out.string).to match(/Error: No frame that matches/) end end it 'should move to the given frame in the call stack' do redirect_pry_io(InputTester.new("frame 2", "@methods << __method__", "exit-all"), out=StringIO.new) do bingbong.bing end expect(bingbong.methods[0]).to eq(:bing) end it 'should return info on current frame when given no parameters' do redirect_pry_io(InputTester.new("frame", "exit-all"), out=StringIO.new) do bingbong.bing end expect(out.string).to match(/\#0.*?bang/) expect(out.string).not_to match(/\#1/) end describe "negative indices" do class AlphaBetaGamma attr_accessor :frame, :frame_number def alpha; binding; end def beta; binding; end def gamma; binding; end end let(:alphabetagamma){ AlphaBetaGamma.new } it 'should work with negative frame numbers' do o = AlphaBetaGamma.new call_stack = [o.alpha, o.beta, o.gamma] method_names = call_stack.map { |v| v.eval('__method__') }.reverse (1..3).each_with_index do |v, idx| redirect_pry_io(InputTester.new("frame -#{v}", "@frame = __method__", "exit-all"), out=StringIO.new) do Pry.start(o, :call_stack => call_stack) end expect(o.frame).to eq(method_names[idx]) end end it 'should convert negative indices to their positive counterparts' do o = AlphaBetaGamma.new call_stack = [o.alpha, o.beta, o.gamma] (1..3).each_with_index do |v, idx| issue_pry_commands( "frame -#{v}", "@frame_number = PryStackExplorer.frame_manager(pry_instance).binding_index", "exit-all" ){ Pry.start(o, call_stack: call_stack) } expect(o.frame_number).to eq(call_stack.size - v) end end end end end
true
acc41dabbaece7651a88df1754f6cfa864f6b0fe
Ruby
UnglazedPottery/jsdir
/AlgorithmswithFernando/chessSquareMatch.rb
UTF-8
687
3.828125
4
[]
no_license
#Fernando's soln def chessboard_cell_color(cell1, cell2) letters = ('A'..'H').to_a colors = ['Black', 'White','Black', 'White','Black', 'White','Black', 'White'] arr_cells = [] arr_colors = [] hash = {} for i in 1..8 for x in letters arr_cells << x + i.to_s end for x in 0..7 arr_colors << colors[x] end colors = colors.reverse end hash = Hash[arr_cells.zip arr_colors] if hash[cell1] == hash[cell2] return true else return false end end p chessboard_cell_color("A1","C3") #true p chessboard_cell_color("A1","H3") #false p chessboard_cell_color("A1","A2") #false
true
2305967cc8823959af0b28ecf161236f0edf47b4
Ruby
dpreli/ttt-7-valid-move-q-000
/lib/valid_move.rb
UTF-8
462
3.296875
3
[]
no_license
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "] def valid_move?(board, position) if (position.to_i-1).between?(0, 8) == true && position_taken?(board, position) == false true else false end end def position_taken?(board, position) if board[position.to_i - 1] == " " || board[position.to_i - 1] == "" || board[position.to_i - 1] == nil false elsif board[position.to_i - 1] == "X" || board[position.to_i - 1] == "O" true end end
true
aba9a06626981feb8dc401e6b5c615e90d2fc4b9
Ruby
hpi-epic/workshop-portal-analysis
/app/models/event.rb
UTF-8
925
2.609375
3
[ "MIT" ]
permissive
# == Schema Information # # Table name: events # # id :integer not null, primary key # name :string # description :string # max_participants :integer # active :boolean # created_at :datetime not null # updated_at :datetime not null # class Event < ActiveRecord::Base has_many :application_letters validates :max_participants, numericality: { only_integer: true, greater_than: 0 } # Returns the number of free places of the event, this value may be negative # # @param none # @return [Int] for number of free places available def compute_free_places max_participants - compute_occupied_places end # Returns the number of already occupied places of the event # # @param none # @return [Int] for number of occupied places def compute_occupied_places application_letters.where(status: true).count end end
true
49444cf9b321c1ca290c341901fa2b1e274c728d
Ruby
gregwebs/module-import
/lib/module-import.rb
UTF-8
2,266
2.890625
3
[ "MIT" ]
permissive
class ImportError < Exception; end module Kernel # abstraction:: only include the methods given by _meths_ # implementation:: includes a duplicate of _mod_ with only the specified instance methods included. By default, all private methods will be included unless the option :import_private is set to false. If no methods are given, def import(mod, *methods_or_options) mod_dup = mod.dup unless methods_or_options.empty? # get list of methods to remove module ims = mod.instance_methods meths = [] modifiers = [] methods_or_options.each do |m_o| case m_o when Hash bool = m_o.delete(:import_private) if bool.nil? modifiers.push m_o else if meths.empty? and methods_or_options.size == 1 and m_o.empty? fail ArgumentError, "methods arguments required with :import_private flag" end if bool == false ims += mod.private_instance_methods end end else meths.push m_o end end ims.map! {|m| m.to_sym} removes = ims - meths if removes.size != (ims.size - meths.size) raise ImportError, "##{(meths - ims).join(' and #')} not found in #{mod}" end mod_dup.module_eval do keeps = [] modifiers.each do |hash| hash.each_pair do |meths, modifier| meths = meths.is_a?(Array) ? meths : [meths] case modifier when :as_public public *meths keeps.concat meths when :as_private private *meths keeps.concat meths else # don't keep renamed methods unless meths.size == 1 fail ArgumentError, "cannot alias multiple methods to the same alias" end m = modifier.to_s unless m[0..2] == 'as_' && m[3] raise ArgumentError, "expected as_ modifier" end alias_method :"#{m[3..-1]}", meths.first end end end (removes - keeps).each { |meth| remove_method meth } end end include mod_dup end end
true
4892f179126984299e2fd8cdff1d1694e147ff43
Ruby
TonishevAlexey/black_jack
/game.rb
UTF-8
2,684
3.40625
3
[]
no_license
require_relative 'deck' require_relative 'user' class Game attr_reader :user, :dealer, :deck attr_accessor :stop, :state def initialize @user = nil @dealer = User.new @deck = Deck.new @stop = false @state = nil end def start_game @stop = false if user.nil? print "Введите свое имя: " name = gets.chomp @user = User.new(name) end user.cards = [] dealer.cards = [] start_carts end def round text c = gets.chomp.to_i case c when 1 dealer_add_card when 2 user.cards << deck.hand_deck dealer_add_card when 3 finish end if (dealer.cards.size == 3 || points(dealer.cards) >= 17) && user.cards.size == 3 finish end end def bank puts "Ваш банк:#{user.bank}" puts "Банк дилера:#{dealer.bank}" end def bank? true if user.bank == 0 || dealer.bank == 0 end private def text puts "Ваши карты:#{user.cards}" puts "Ваши очки:#{points(user.cards)}" puts "Пропустить введите 1" if dealer.cards.size < 3 puts "Добавить карту введите 2" if user.cards.size < 3 puts "Открыть карты введите 3" end def dealer_add_card dealer.cards << deck.hand_deck if points(dealer.cards) < 17 && dealer.cards.size < 3 end def finish puts "Ваши очки:#{points(user.cards)}" puts "Карты диллера :#{dealer.cards}" puts "Очки диллера:#{points(dealer.cards)}" stop_round state_game end def state_game if (points(dealer.cards) > points(user.cards) && points(dealer.cards) < 22) || (points(dealer.cards) < 22 && points(user.cards) > 21) user.bank = user.bank - 10 dealer.bank = dealer.bank + 10 self.state = "поражение" elsif (points(dealer.cards) < points(user.cards) && points(user.cards) < 22) || (points(dealer.cards) > 21 && points(user.cards) < 22) user.bank = user.bank + 10 dealer.bank = dealer.bank - 10 self.state = "победа" elsif (points(dealer.cards) == points(user.cards) && points(dealer.cards) < 22) || (points(dealer.cards) > 21 && points(user.cards) > 21) self.state = "ничья" end end def stop_round self.stop = true end def start_carts user.cards = deck.start dealer.cards = deck.start end def points(p) sum = p.inject(0) do |sum, x| if Deck::SYMBOL_CARD.include?(x[0]) x = Deck::SYMBOL_CARD[x[0]] x = 1 if Deck::SYMBOL_CARD[x[0]] == 'Т' && sum + x > 21 end sum + x.to_i end sum end end
true
677baa21bf4895d312e26c5eacc8f757927800a8
Ruby
AliSchlereth/job-tracker
/app/models/company.rb
UTF-8
646
2.59375
3
[]
no_license
class Company < ActiveRecord::Base validates :name, :city, presence: true validates :name, uniqueness: true has_many :jobs, dependent: :destroy has_many :contacts def self.top_three_companies_by_interest top_3 = joins(:jobs).group(:id).order("AVG(jobs.level_of_interest) DESC").limit(3).pluck(:name, "AVG(jobs.level_of_interest)") top_3.map {|company| [company[0], company[1].to_f]} end def self.sort_by_location order(:city) end def self.count_by_location cities = Company.pluck(:city).uniq thing = cities.map do |city| [city, Job.joins(:company).where("city = ?", city).count] end end end
true
7436ca271796f23941dfc7940667d26d77246581
Ruby
hanmoonkyo/tt-lib
/modules/command.rb
UTF-8
2,018
2.734375
3
[ "MIT" ]
permissive
# frozen_string_literal: true Sketchup.require 'modules/resource' module SkippyLib # A wrapper on top of `UI::Command` which will automatically pick the # appropriate vector file format alternative for icon resources. # # @since 3.0.0 module Command # Allows for an error handler to be configured for when commands raises an # error. Useful for providing general feedback to the user or error loggers. # # @since 3.0.0 def self.set_error_handler(&block) @error_handler = block end # @param [String] title # @since 3.0.0 def self.new(title, &block) # SketchUp allocate the object by implementing `new` - probably part of # older legacy implementation when that was the norm. Because of that the # class cannot be sub-classed directly. This module simulates the # interface for how UI::Command is created. `new` will create an instance # of UI::Command but mix itself into the instance - effectively # subclassing it. (yuck!) command = UI::Command.new(title) { begin block.call rescue Exception => e # rubocop:disable Lint/RescueException if @error_handler.nil? raise else @error_handler.call(e) end end } command.extend(self) command.instance_variable_set(:@proc, block) command end # @return [Proc] # @since 3.0.0 def proc @proc end # @since 3.0.0 def invoke @proc.call end # Sets the large icon for the command. Provide the full path to the raster # image and the method will look for a vector variant in the same folder # with the same basename. # # @param [String] path # @since 3.0.0 def large_icon=(path) super(Resource.icon_path(path)) end # @see #large_icon # # @param [String] path # @since 3.0.0 def small_icon=(path) super(Resource.icon_path(path)) end end # module end # module
true
11ec4f45e5b4f795bd67ef7329541073ea1950a2
Ruby
hoarf/farm-control-system
/app/models/fact.rb
UTF-8
1,243
2.640625
3
[]
no_license
# coding: utf-8 # This class represents any accounting relevant thing that happens. class Fact < ActiveRecord::Base MOVES_COUNT_MIN = 2 # Relationships has_many :moves, dependent: :destroy, inverse_of: :fact has_many :credits, dependent: :destroy has_many :debits, dependent: :destroy has_one :entry, dependent: :destroy belongs_to :partner # Saving accepts_nested_attributes_for :moves, allow_destroy: true accepts_nested_attributes_for :entry, allow_destroy: true # Validation validate :at_least_two_moves, :credits_and_debits_must_be_equal def credits_and_debits_must_be_equal unless moves.reject(&:marked_for_destruction?) .select { |m| m.valid? } .map { |m| m.type == "Debit" ? m.amount : - m.amount }.reduce(:+) == 0 errors.add(:moves, "A soma dos créditos e débitos deve ser igual") end end def at_least_two_moves unless moves.reject(&:marked_for_destruction?).count >= MOVES_COUNT_MIN errors.add(:moves, "No mínimo duas movimentações financeiras são necessárias") end end def credits_of_cts_account_of(date) credits.of_account(date, :cts) end def debits_of_cts_account_of(date) debits.of_account(date, :cts) end end
true
e7c908ca600c28292a31f828dafca30318cd5221
Ruby
armaultasch/important_program
/lib/blog.rb
UTF-8
432
3.390625
3
[]
no_license
#lib/blog.rb class Blog def initialize @posts = [] end def add_post (post) @posts.push(post) end def show_post @posts.sort! {|a,b| b.date <=> a.date} @posts.each do |x| x.print_post end end starts = 0 stops = 3 def show_paginated(num) puts page_amount = (@posts.length / 3.0).ceil @posts[starts] # while num < @posts.length # @posts.take(num).each do |page| # page.print_post # end end end
true
9ed775695c6aa2fa35b85c5b981c96b3042222ab
Ruby
borkabrak/binfiles
/iphmotj
UTF-8
1,820
4.125
4
[]
no_license
#!/usr/bin/env ruby # # Obfuscate text by shifting each consonant and vowel one consonant or # vowel to the right (e.g., 'english' becomes 'iphmotj'). # # Example: # a -> e # next vowel # b -> c # c -> d # d -> f # next consonant # # In other words, it's a rotation cipher but where consonants and vowels stay # that way. The idea is that it sort of preserves pronounceability. # # Handles text as arguments or from STDIN. Non-letters are ignored. # # NOTE: This is NOT any kind of secure crypto. This is for fun. # # TODO: # * characters without an encoding are unchanged, (not skipped) class String def iphmotj(offset) encodings = [ 'bcdfghjklmnpqrstvwxz', 'aeiouy', 'BCDFGHJKLMNPQRSTVWXZ', 'AEIOUY', '0123456789' ] self.split(//).map do |char| encodings.map do |list| index = list.index(char) list[( index + offset ) % list.length] if index end end.join("") end end # Convert command line to a single string because it's actually easier to parse # options this way (eat that, perl) arguments = ARGV.join(' ') # Option: # -o <val>, --offset=<val>' - move each character <val> positions down # # This particular way of parsing the option seems hacky, but it does work at # both catching the option's value and removing the entire option specification # from the argument list. offset = arguments.sub!(/(-o|--offset)[\s=]?(-?\d+)/,"") ? $2.to_i : 1 # The text to be encoded is either passed in as an argument or read from STDIN # (if the argument list has no non-whitespace content) plain = (arguments[/\S/] ? arguments : STDIN.gets ) # Finally, do what we came here to do. puts plain.iphmotj offset
true
5383051a4f46913f7d2c1eec894557e99d877caf
Ruby
ljsking/PatternSearch
/src/ptxt.rb
UTF-8
275
3.109375
3
[]
no_license
class PTxt attr_accessor :filename, :sentences def initialize @sentences = [] end def verify return true end def size return @sentences.size end def add(sentence) @sentences << sentence end def get(idx) return @sentences[idx] end end
true
bca4d0243dcaaf065eed145f0caa272e349831bc
Ruby
DanOlson/evergreen-menus
/app/services/availability_range.rb
UTF-8
454
2.828125
3
[]
no_license
module AvailabilityRange FORMAT = '%l:%M %P' class << self def call(menu) start_time = menu.availability_start_time && menu.availability_start_time.strftime(FORMAT) end_time = menu.availability_end_time && menu.availability_end_time.strftime(FORMAT) if start_time [start_time, end_time].compact.map(&:strip).join(' - ') elsif end_time "until #{end_time}" else '' end end end end
true
01d5ccff81443e5a9e2dbe7c35eb03b71381d5ea
Ruby
globalxolutions/cond
/spec/calc_spec.rb
UTF-8
1,697
3.0625
3
[ "MIT" ]
permissive
require File.dirname(__FILE__) + '/cond_spec_base' require 'cond/dsl' class DivergedError < StandardError attr_reader :epsilon def initialize(epsilon) super() @epsilon = epsilon end def message "Failed to converge with epsilon #{@epsilon}" end end def calc(x, y, epsilon) restartable do restart :change_epsilon do |new_epsilon| epsilon = new_epsilon again end restart :give_up do leave end # ... # ... some calculation # ... if epsilon < 0.01 raise DivergedError.new(epsilon) end 42 end end describe "A calculation which can raise a divergent error," do describe "with a handler which increases epsilon" do before :all do handling do @memo = [] @result = nil epsilon = 0.0005 handle DivergedError do epsilon += 0.001 @memo.push :increase invoke_restart :change_epsilon, epsilon end @result = calc(3, 4, epsilon) end end it "should converge after repeated epsilon increases" do @memo.should == (1..10).map { :increase } end it "should obtain a result" do @result.should == 42 end end describe "with a give-up handler and a too-small epsilon" do before :all do handling do @result = 9999 @memo = [] epsilon = 1e-10 handle DivergedError do @memo.push :give_up invoke_restart :give_up end @result = calc(3, 4, epsilon) end end it "should give up" do @memo.should == [:give_up] end it "should obtain a nil result" do @result.should == nil end end end
true
9413d74ab76b732804a29c442f85804171fe3dde
Ruby
RollingStone90/Brainbuster-ruby-2
/loopspractice.rb
UTF-8
867
4.03125
4
[]
no_license
# 5.times do # puts"I think i can" # end # count=0 # 10.times do # puts count*count # count += 1 # end #until loops #double users number through 10 # puts"Give a number from 1 to 10" # num = gets.chomp.to_i # until num == 11 # puts num * 2 # num +=1 # end # puts"Give a number from 1 to 10" # num= gets.chomp.to_i # until num == 0 # puts num * 2 # num -=1 # end # until loops # dad= "no" # until dad == "yes" # puts "Can we go to Itchy and Scratchy land" # dad = gets.chomp.downcase # if dad == "no" # puts "No, now stop asking" # end # end # puts"yay!" # # while loops # name = " " # while name != "jacob" # puts"Whats your name" # name= gets.chomp.downcase # end # puts "Thank you Jacob for Signing in!" #random number generator num = 0 while num != 7 puts num num = rand(1...10) end animal=["pig", "horse","cat","dog"] animal.each do |a| end
true
777d6f5ec8d5e721af431bf4ba5f535fac03a86f
Ruby
chellberg/advent
/3/solution_part_2.rb
UTF-8
3,409
3.90625
4
[]
no_license
# --- Day 3: Perfectly Spherical Houses in a Vacuum --- # Santa is delivering presents to an infinite two-dimensional grid of houses. # He begins by delivering a present to the house at his starting location, and # then an elf at the North Pole calls him via radio and tells him where to move # next. Moves are always exactly one house to the north (^), south (v), east # (>), or west (<). After each move, he delivers another present to the house # at his new location. # However, the elf back at the north pole has had a little too much eggnog, and # so his directions are a little off, and Santa ends up visiting some houses # more than once. How many houses receive at least one present? # For example: # > delivers presents to 2 houses: one at the starting location, and one to the east. # ^>v< delivers presents to 4 houses in a square, including twice to the house at his starting/ending location. # ^v^v^v^v^v delivers a bunch of presents to some very lucky children at only 2 houses. # # --- Part Two --- # The next year, to speed up the process, Santa creates a robot version of # himself, Robo-Santa, to deliver presents with him. # Santa and Robo-Santa start at the same location (delivering two presents to # the same starting house), then take turns moving based on instructions from # the elf, who is eggnoggedly reading from the same script as the previous # year. # This year, how many houses receive at least one present? # For example: # ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa goes south. # ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa end up back where they started. # ^v^v^v^v^v now delivers presents to 11 houses, with Santa going one direction and Robo-Santa going the other. DRUNKEN_ELF_DIRECTIONS = File.open('input.txt').read.chars NORTH, SOUTH, EAST, WEST = %w(^ v > <) # maps coordinate pairs representing houses to present counts # default present counts to 0 initial_map = Hash.new 0 initial_map[[0, 0]] = 2 # Santa and Robo-Santa start at the same location # (delivering two presents to the same starting house) INITIAL_STATE = { index: 0, positions: { santa: [0, 0], robo_santa: [0, 0] }, map: initial_map } def get_next_state current_state, direction current_santa = get_current_santa current_state[:index] next_index = current_state[:index] += 1 next_position = get_next_position current_state[:positions][current_santa], direction next_map = get_next_map current_state[:map], next_position next_positions = current_state[:positions].tap { |pos| pos[current_santa] = next_position } { index: next_index, positions: next_positions, map: next_map } end def get_current_santa index if index.even? :santa else :robo_santa end end def get_next_position current_position, direction x, y = current_position case direction when NORTH y += 1 when SOUTH y -= 1 when EAST x += 1 when WEST x -= 1 end [x, y] end def get_next_map current_map, next_position current_map[next_position] += 1 current_map end FINAL_STATE = DRUNKEN_ELF_DIRECTIONS.inject INITIAL_STATE do |current_state, direction| get_next_state current_state, direction end HOUSES_WITH_PRESENTS_COUNT = FINAL_STATE[:map].size puts "#{HOUSES_WITH_PRESENTS_COUNT} houses received at least one present on Drunken Christmas"
true
a54f30aaacd85b78e4bc5e3bc4d4fc6e050f2794
Ruby
delambo/gettit
/example/Rakefile
UTF-8
909
2.59375
3
[ "MIT" ]
permissive
require 'rubygems' require 'jammit' # Usage: # rake build # Think before you change - this directory is removed!!! BUILDDIR = "build" desc "minify source with jammit" task :build do puts "Building to #{BUILDDIR}/" FileUtils.rm_rf BUILDDIR, :verbose => true Jammit.package!({ :config_path => "assets.yml", :output_folder => BUILDDIR }) fix_css_paths end # Jammit will hardcode css image file urls that are document relative (../img/test.jpg) # with the server's working directory. This function will find all of the css files # and replace the working directory path with the root relative web location (/img/..). # def fix_css_paths Dir.foreach(BUILDDIR) do |file| if /\.css$/.match(file) File.open(BUILDDIR + '/' + file, 'r+') do |f| css = f.read css.gsub!(/url\((.*?)\/img\//, 'url(/img/') f.rewind f.write(css) f.truncate(css.length) end end end end
true
01dd7d363aa100dbc6b41749e431895203ba349e
Ruby
PerfectoCode/reporting-ruby-sdk
/lib/perfecto-reporting/test/TestContext.rb
UTF-8
1,519
2.859375
3
[ "Apache-2.0" ]
permissive
require_relative '../model/CustomField.rb' # TestContext # # TestExecutionTags will be presented in reporting ui. # This tags attached to each test execution. # # Custom Fields defined for the TestContext are presented in report UI # These custom fields override the values in the PerfectoExecutionContext class TestContext attr_accessor :testExecutionTags, :customFields # Create TestContext instance def initialize(contextBuilder ) @testExecutionTags = contextBuilder.testExecutionTags @customFields = contextBuilder.customFields end # TestContextBuilder # # This class used to create TestContext instance # # example: # cf1 = CustomField.new(key1, val1) # cf2 = CustomField.new(key2, val2) # TestContext::TestContextBuilder # .withContextTags("tag1" , "tag2" ) # .withCustomFields(cf1, cf2) # .build() class TestContextBuilder @@customFields = Hash.new @@testExecutionTags = nil # define contextTags def self.withTestExecutionTags *args @@testExecutionTags = args return self end # define the custom fields, overriding any existing definition def self.withCustomFields *args unless args.nil? args.each do |cf| @@customFields[cf.key] = cf.value end end return self end # building a new builder instance def self.build return self.new end def testExecutionTags @@testExecutionTags end def customFields @@customFields end end # end TestContextBuilder end
true
f9bef9e88a02e189574970b260aa8bf19c8a477a
Ruby
fcontreras18/intro_to_programming
/back_end_prep/intro_exercises/exercise7.rb
UTF-8
125
2.546875
3
[]
no_license
What's the major difference between an Array and a Hash? Arrays store data in an index, hashes store data in key value pairs
true
aacc2b28babb8c7a973f80a9cb9d6adc2aa105fe
Ruby
craftdata/locations_ng
/lib/locations_ng/state.rb
UTF-8
1,012
2.78125
3
[ "MIT" ]
permissive
module LocationsNg class State @all_states = LocationsNg::LoadFile.read('states') class << self def all @all_states.map{ |s| {name: s['name'], capital: s['capital']} } end def details(state) state_index = @all_states.index{ |s| s['alias'] == format_query(state) } if state_index.nil? {message: "No state found for '#{state}'", status: 404} else res = @all_states[state_index] res['cities'] = LocationsNg::City.cities(state) res['lgas'] = LocationsNg::Lga.lgas(state) res end end def capital(state) state_index = @all_states.index{ |s| s['alias'] == format_query(state) } unless state_index.nil? return @all_states[state_index]['capital'] end {message: "No state found for '#{state}'", status: 404} end private def format_query(query) query ? query.downcase.tr(' ', '_') : query end end end end
true
3aa47bfe5eacddfeb70882149a3bd0e5608c637f
Ruby
adammcfadden/anagrams
/spec/anagrams_spec.rb
UTF-8
315
2.734375
3
[]
no_license
require 'rspec' require 'anagrams' describe('String#anagrams') do it('return true if a word is an anagram to the given word') do expect('dog'.anagrams('god')).to(eq(true)) end it('return false if a word is an anagram to the given word') do expect('pool'.anagrams('elephant')).to(eq(false)) end end
true
d32f7e6b4a19178f0c672c4cd7f78da976a2b5ad
Ruby
benrconway/Cinema-modelling-homework
/db/console.rb
UTF-8
2,198
2.84375
3
[]
no_license
require("pry") require_relative("../models/customer.rb") require_relative("../models/film.rb") require_relative("../models/ticket.rb") require_relative("../models/screening.rb") Customer.delete_all() Film.delete_all() Ticket.delete_all() Screening.delete_all() customer1 = Customer.new({"name" => "Dr Worm", "funds" => 1_000}) customer2 = Customer.new({"name" => "Leon the Lion", "funds" => 100}) customer3 = Customer.new({"name" => "Gerry Giraffe", "funds" => 800}) customer4 = Customer.new({"name" => "Harry Hopopotamus", "funds" => 5}) film1 = Film.new({"title" => "Atomic Blonde"}) film2 = Film.new({"title" => "Dunkirk"}) film3 = Film.new({"title" => "The Dark Tower"}) film4 = Film.new({"title" => "The Hitman's Bodyguard"}) customer1.save() customer2.save() customer3.save() customer4.save() film1.save() film2.save() film3.save() film4.save() screening1 = Screening.new({"film_id"=>film1.id, "price" => 15, "start_time" => "15:50", "attendance"=> 0}) screening2 = Screening.new({"film_id"=>film2.id, "price" => 15, "start_time" => "09:50", "attendance"=> 0}) screening3 = Screening.new({"film_id"=>film3.id, "price" => 15, "start_time" => "12:50", "attendance"=> 0}) screening4 = Screening.new({"film_id"=>film4.id, "price" => 15, "start_time" => "18:50", "attendance"=> 0}) screening1.save() screening2.save() screening3.save() screening4.save() ticket1 = customer1.buy_ticket(screening1) ticket2 = customer2.buy_ticket(screening2) ticket3 = customer3.buy_ticket(screening1) ticket1.save ticket2.save ticket3.save binding.pry nil # ticket1 = Ticket.new({"customer_id" => customer3.id, "film_id" => film4.id}) # ticket2 = Ticket.new({"customer_id" => customer1.id, "film_id" => film1.id}) # ticket3 = Ticket.new({"customer_id" => customer2.id, "film_id" => film3.id}) # ticket4 = Ticket.new({"customer_id" => customer3.id, "film_id" => film3.id}) # ticket5 = Ticket.new({"customer_id" => customer1.id, "film_id" => film3.id}) # ticket6 = Ticket.new({"customer_id" => customer1.id, "film_id" => film2.id}) # ticket7 = Ticket.new({"customer_id" => customer1.id, "film_id" => film4.id}) # ticket1.save() # ticket2.save() # ticket3.save() # ticket4.save() # ticket5.save() # ticket6.save() # ticket7.save()
true
40797270003b0992bc9feb766acb12ee30b7eb47
Ruby
mwlang/ramaze-protos
/erubis_sequel_bacon_railsy/lib/enforce_ssl.rb
UTF-8
2,021
2.71875
3
[ "MIT" ]
permissive
if Ramaze.options.mode == :bogus require 'rack/utils' module Rack # # EnforceSSL is a Rack middleware app that enforces that users visit # specific paths via HTTPS. If a sensitive path is requested over # plain-text HTTP, a 307 Redirect will be issued leading to the HTTPS # version of the Requested URI. # # MIT License - Hal Brodigan (postmodern.mod3 at gmail.com) # class EnforceSSL include Rack::Utils # # Initializes the SSL enforcement rules. # # @param [#call] app # The app to apply SSL enforcement rules on. # # @param [Array<String, Regexp>] rules # URI paths and patterns to enforce SSL upon. # # @example # use Rack::EnforceSSL, ['/login', /\.xml$/] # def initialize(app,rules) @app = app patterns = [] paths = [] rules.each do |pattern| if pattern.kind_of?(Regexp) patterns << pattern else paths << pattern end end @rules = patterns + paths.sort.reverse end def call(env) uri = env['REQUEST_URI'] unless uri[0,6] == 'https:' path = env['PATH_INFO'] enforce = @rules.any? do |pattern| if pattern.kind_of?(Regexp) path =~ pattern else path[0,pattern.length] == pattern end end if enforce return [ 307, { 'Content-Type' => 'text/html', 'Location' => uri.gsub(/^http:/,'https:') }, [%{<html> <head> <title>SSL Redirect</title> </head> <body> <h1>SSL Redirect</h1> <p>The requested path (#{escape_html(path)}) must be requested via SSL. You are now being redirected to the SSL encrypted path.</p> </body> </html>}] ] end end @app.call(env) end end end end # if mode
true
24d2d6f30df35d574e828e97f094ee4edac864dc
Ruby
KalMegati/anagram-detector-online-web-pt-090919
/lib/anagram.rb
UTF-8
298
3.46875
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'pry' # Your code goes here! class Anagram attr_accessor :word def initialize(word) @word = word end def matching yield.split(//).sort == word.split(//).sort end def match(phrase) phrase.map{ |piece| piece if matching{piece} }.compact end end
true
c4c9302d594e20d10cd6bf378179f68811977edd
Ruby
kondorkiewicz/climbing-judge-terminal
/lib/list_manager.rb
UTF-8
1,326
3.078125
3
[]
no_license
module ListManager extend self def add_score(comp, score) comp[:score] = score.to_i end def print_list(list) columns_names = list.first.keys.map { |key| key.to_s.upcase } puts "\n\n" columns_names.each { |name| print name.center(12) }; puts list.each do |comp| comp.values.each { |v| print v.to_s.center(12) }; puts end puts "\n\n" end def set_places(scores) scores.sort_by! {|score| score[:score]}.reverse! count = 1; place = 1 scores.each_cons(2) do |a, b| if a[:score] == b[:score] a[:place] = place; b[:place] = place count += 1 else a[:place] = place; b[:place] = place + count place += count; count = 1 end end scores end def set_ex_aequo_points(list) ex_aequo_places = list.group_by {|comp| comp[:place]} ex_aequo_places.map do |place, comps| if comps.size > 1 add_ex_aequo_points(place, comps) else comps.each {|comp| comp[:points] = comp[:place]} end end list end def add_ex_aequo_points(place, comps) limit = place + comps.size - 1 range = place < limit ? place..limit : limit..place points = [*range].inject(:+) / comps.size.to_f comps.each do |comp| comp[:points] = points end end end
true
e772c1482f71c4f756c6823c895bd1f403e24bd9
Ruby
bazzel/coursera-algorithms-part-1.rb
/lib/percolation/percolation_randomizer.rb
UTF-8
693
3.484375
3
[]
no_license
class PercolationRandomizer attr_reader :n, :positions # Create an array representing an n*n plane # with [x,y] coordinates as its elemens # # @example # PercolationRandomizer.new(4) # # => [[1,1], [1,2], [1,3], [1,4], # [2,1], [2,2], [2,3], [2,4], # [3,1], [3,2], [3,3], [3,4], # [4,1], [4,2], [4,3], [4,4]] def initialize(n) @n = n init_positions end # @return [Array<FixNum, FixNum] a random element from the array def position positions.delete(positions.sample) end private def init_positions @positions = [] 1.upto(n) do |r| 1.upto(n) do |c| positions << [r,c] end end end end
true
a4abce8779e7ce0e7f2d1d3c20775921fa2706c4
Ruby
mloreti/learning
/odin-project/ruby-basics-project/cypher.rb
UTF-8
503
4.1875
4
[]
no_license
puts "What message do you want to encrypt?" word = gets.chomp.downcase puts "How many letters do you want to shift?" number = gets.chomp.to_i def cipher input, key alphabet = ('a'..'z').to_a new_alphabet = alphabet.rotate(key) word = input.split("") new_word = "" word.each do |letter| if !(alphabet.include? letter) new_word += letter else new_word += new_alphabet[alphabet.index(letter)] end end puts "Output: " + new_word.capitalize end cipher word, number
true
83dee3c0e1737fff19b25e5b331ab4bc6e1db2af
Ruby
angelalonso/cal_eyo_rb
/old/test.rb
UTF-8
3,410
3.65625
4
[]
no_license
#!/usr/bin/ruby # usage: ruby SortCsvFile.rb InputFilename > OutputFilename # define a "Person" class to represent the three expected columns class Calendar < # a Person has a first name, last name, and city Struct.new(:day, :sintrom_amount, :blood_test, :shift, :birthdays, :task1, :task2, :task3, :task4) # a method to print out a csv record for the current Person. # note that you can easily re-arrange columns here, if desired. # also note that this method compensates for blank fields. def print_csv_record day.length==0 ? printf(",") : printf("\"%s\",", day) sintrom_amount.length==0 ? printf(",") : printf("\"%s\",", sintrom_amount) blood_test.length==0 ? printf(",") : printf("\"%s\",", blood_test) shift.length==0 ? printf(",") : printf("\"%s\",", shift) birthdays.length==0 ? printf(",") : printf("\"%s\",", birthdays) task1.length==0 ? printf(",") : printf("\"%s\",", task1) task2.length==0 ? printf(",") : printf("\"%s\",", task2) task3.length==0 ? printf(",") : printf("\"%s\",", task3) task4.length==0 ? printf(",") : printf("\"%s\",", task4) printf("\n") end end #------# # MAIN # #------# # bail out unless we get the right number of command line arguments unless ARGV.length == 2 puts "ERROR: Not the right number of arguments." puts "Usage: ruby SortCsvFile.rb [InputFile.csv] [title|notitle]\n" exit end # get the input filename from the command line input_file = ARGV[0] title = ARGV[1] # define an array to hold the Person records arr = Array.new # loop through each record in the csv file, adding # each record to our array. f = File.open(input_file, "r") linenr = 0 f.each_line { |line| words = line.split(',') c1 = Calendar.new # do a little work here to get rid of double-quotes and blanks if ( title == "title" ) if linenr == 0 @titleline = line else c1.day = words[0].tr_s('"', '').strip c1.sintrom_amount = words[1].tr_s('"', '').strip c1.blood_test = words[2].tr_s('"', '').strip c1.shift = words[3].tr_s('"', '').strip c1.birthdays = words[4].tr_s('"', '').strip c1.task1 = words[5].tr_s('"', '').strip c1.task2 = words[6].tr_s('"', '').strip c1.task3 = words[7].tr_s('"', '').strip c1.task4 = words[8].tr_s('"', '').strip arr.push(c1) end elsif ( title == "notitle" ) c1.day = words[0].tr_s('"', '').strip c1.sintrom_amount = words[1].tr_s('"', '').strip c1.blood_test = words[2].tr_s('"', '').strip c1.shift = words[3].tr_s('"', '').strip c1.birthdays = words[4].tr_s('"', '').strip c1.task1 = words[5].tr_s('"', '').strip c1.task2 = words[6].tr_s('"', '').strip c1.task3 = words[7].tr_s('"', '').strip c1.task4 = words[8].tr_s('"', '').strip arr.push(c1) else puts "Error : Second value invalid (MUST BE either title or notitle)" end linenr += 1 } # sort the data by the last_name field arr.sort! { |a,b| a.day.downcase <=> b.day.downcase } # print out all the sorted records (just print to stdout) puts @titleline arr.each { |c1| c1.print_csv_record }
true
39e3aaef2543f59e70ce390e3b14d0f317bab0c6
Ruby
dball1126/Coding_problems
/ruby/inorder_traversal.rb
UTF-8
497
3.453125
3
[]
no_license
# Definition for a binary tree node. class TreeNode attr_accessor :val, :left, :right def initialize(val) @val = val @left, @right = nil, nil end end def inorder_traversal(root) return [] if !root inorder = [] stack = [root] end node1 = TreeNode.new(1) node2 = TreeNode.new(2) node3 = TreeNode.new(3) node4 = TreeNode.new(4) node5 = TreeNode.new(5) node1.left = node2 node1.right = node3 node2.left = node4 node2.right = node5 p inorder_traversal(node1)
true
cbd9ec9e5f10a3391616cb91e2223354c3de8b48
Ruby
Shelvak/nebula-game
/lib/flyers/lib/keygen.rb
UTF-8
593
2.921875
3
[ "LicenseRef-scancode-other-permissive" ]
permissive
#!/usr/bin/env ruby require 'rubygems' require 'yaml' class Keygen STEP = 4 TIME_MULT = 100000 def self.part_string(string, step, separator="-") parts = [] 0.step(string.length - 1, step) do |start_index| parts.push string[start_index...start_index + step] end parts.join(separator) end def self.get_key(id, event_name) ("%s-%04d-%s-%s" % [ part_string((Time.now.to_f * TIME_MULT).to_i.to_s(16), STEP), id, event_name, (4096 + rand(61439)).to_s(16) ]).upcase end end 90.times do |i| puts Keygen.get_key(i, "ITCITY") end
true
76f0e6fdcd04b7f171574278f8d8163579ba4b5d
Ruby
thagomizer/Euler
/015s/paths.rb
UTF-8
1,079
3.890625
4
[]
no_license
require 'rubygems' require 'pp' # Starting in the top left corner of a 22 grid, there are 6 routes # (without backtracking) to the bottom right corner. # Each route is a combination of rights and downs. The number of rights and # downs is equal to the the manhattan distance from corner to corner. And # half of them must be downs and half must be rights. side = ARGV.shift.to_i path = [] side.times do |n| path << "D" path << "R" end def permute(ary) results = [] if ary.length == 1 results << ary else ary.length.times do |n| wierdo = ary[n] rest = ary[0...n] + ary[(n+1)...(ary.length)] sub = permute(rest) results += sub.collect{|x| [wierdo] + x} end end results.uniq end def permute_count(ary) result = 0 if ary.length == 1 return 1 else ary.length.times do |n| wierdo = ary[n] rest = ary[0...n] + ary[(n+1)...(ary.length)] sub = permute_count(rest) result += sub end end result end paths2 = permute(path).sort # paths2 puts paths2.length #puts permute_count(path)
true
6151f53a5150052e705946b3c79195c84541e19e
Ruby
jamesponeal/phase-0
/week-5/die-class/my_solution.rb
UTF-8
3,051
4.3125
4
[ "MIT" ]
permissive
# Die Class 1: Numeric # I worked on this challenge by myself. # I spent [1.5] hours on this challenge. # 0. Pseudocode # Input: # The input is an integer which represents the number of sides of a die. # Output: # If .sides is called: # The output will be an integer corresponding to the number of sides the die has. # If .roll is called: # The output should be a random number from 1 upto and including the number that was passed in. # Steps: # Create instance variable @sides. # .sides # This method will return the value of the instance variable @sides. # .roll # This method will return a random number from 1 to @sides. # 1. Initial Solution # class Die # def initialize(sides) # if sides <=0 # raise ArgumentError.new("Number of sides must be greater than 0!!") # else # @sides = sides # end # end # def sides # p @sides # end # def roll # p 1 + rand(@sides) # end # end # die1 = Die.new(6) # die1.sides # die1.roll # 3. Refactored Solution # I spent some time going through my code and researching some methods to help me simplify but I could not come up with anything, so my refactored code is the same as my initial solution. class Die def initialize(sides) if sides <=0 raise ArgumentError.new("Number of sides must be greater than 0!!") else @sides = sides end end def sides @sides end def roll 1 + rand(@sides) end end # 4. REFLECTION # For this reflection, we were asked to answer the following questions: # 1) What is an ArgumentError and why would you use one? # An ArgumentError is an error that is given when there is a problem with the argument(s) that were passed into a class or method, such as the wrong number or type of argument. You can create your own type of ArgumentError for classes and methods that you create to give a user a custom notification about the error. # 2) What new Ruby methods did you implement? What challenges and successes did you have in implementing them? # I have actually not done much with classes leading up to phase 0, I just did a little bit here and there. So using the instance variable when the class was initialized was fairly new. As far as challenges, I thought this exercise was fairly straight-forward, so it wasn't very challenging for me. # 3) What is a Ruby class? # A class is a set of rules, methods, and plans for how an object behaves. An object is always part of a class. # 4) Why would you use a Ruby class? # Classes are useful if you want to create several objects that will all follow the same set of rules, have the same methods available to them, and behave in similar ways. # 5) What is the difference between a local variable and an instance variable? # A local variable is only usable inside the method where it was created. An instance variable is available for a given instance anywhere inside a class. # 6) Where can an instance variable be used? # An instance variable can only be used inside a method.
true
e016c4b1187965f51193abecfcac48c0eccb4cf3
Ruby
rugl-at/www
/_plugins/storyblok_page.rb
UTF-8
1,242
2.59375
3
[]
no_license
require "storyblok" module Jekyll class StoryblokPage < Page def initialize(site, base, dir, story, links) @site = site @base = base @dir = dir @name = 'index.html' # We will use the page component (which acts as content-type here) as layout layout = story['content']['component'] self.process(@name) self.read_yaml(File.join(base, '_layouts'), layout + '.html') # Assign the received data from the Storyblok API as variables self.data['story'] = story self.data['title'] = story['name'] self.data['links'] = links end end class StoryblokPageGenerator < Generator safe true def generate(site) # change this to your preview token client = ::Storyblok::Client.new(token: 'wp7qdJrYewGupG6UP8eFfAtt', version: 'draft') res = client.stories stories = res['data']['stories'] res_links = client.links links = res_links['data']['links'] stories.each do |story| site.pages << StoryblokPage.new(site, site.source, story['full_slug'], story, links) if story['full_slug'] == 'home' site.pages << StoryblokPage.new(site, site.source, '', story, links) end end end end end
true
bb4a83448d76d9e672811fa58c8f390b48fda30d
Ruby
Noelryn/fizzbuzz-october2019
/spec/fizz_buzz_spec.rb
UTF-8
461
3.546875
4
[]
no_license
require './lib/fizzbuzz.rb' describe 'fizzbuzz' do it 'returns 1 if number is 1' do expect(fizzbuzz(1)).to eq 1 end it 'returns Fizz! if number is divisable by 3' do expect(fizzbuzz(3)).to eq 'Fizz!' end it 'returns Buzz! if number is divisable by 5' do expect(fizzbuzz(5)).to eq 'Buzz!' end it 'returns fizzbuzz! if number is divisable by 15' do expect(fizzbuzz(15)).to eq 'fizzbuzz!' end end
true
3f7eb30bbc663dd9a46209fd605693cdac8cbd53
Ruby
zachholcomb/black_thursday_lite
/test/merchant_collection_test.rb
UTF-8
1,645
2.921875
3
[]
no_license
require 'minitest/autorun' require 'minitest/pride' require './lib/merchant' require './lib/merchant_collection' class MerchantCollectionTest < Minitest::Test def setup @merchant = Merchant.new({:id => 5, :name => "Turing School"}) @merchant2 = Merchant.new({:id => 6, :name => "Starbucks"}) @merchant3 = Merchant.new({:id => 1, :name => "Pizza Hut"}) @merchant4 = Merchant.new({:id => 9, :name => "KFC"}) @merchants_list = [@merchant, @merchant2, @merchant3, @merchant4] @merchant_collection = MerchantCollection.new(@merchants_list) end def test_it_exists assert_instance_of Merchant, @merchant end def test_it_can_find_all_merchants assert_equal @merchants_list, @merchant_collection.all end def test_it_can_find_merchants_by_id assert_equal @merchant, @merchant_collection.find(5) assert_equal @merchant2, @merchant_collection.find(6) assert_equal @merchant3, @merchant_collection.find(1) assert_equal @merchant4, @merchant_collection.find(9) assert_nil @merchant_collection.find(11) end def test_it_can_create_new_merchants assert_equal 4, @merchant_collection.all.length @merchant_collection.create({:id => 4, :name => "Little Owl"}) assert_equal 5, @merchant_collection.all.length assert_equal "Little Owl", @merchant_collection.find(4).name end def test_it_can_update_name_of_merchant @merchant_collection.update({:id => 1, :name => "Little Caesar's"}) assert_equal "Little Caesar's", @merchant_collection.find(1).name end def test_it_can_destroy_the_merchant @merchant_collection.destroy(1) assert_nil @merchant_collection.find(1) end end
true
e7468cbae233ebc1159c9f268b9a349621b4851c
Ruby
moufidjaber/moufidjaber
/reboot/horse_race/race.rb
UTF-8
368
3.5625
4
[]
no_license
def display_horses(horses) horses.each_with_index do |horse, index| puts "#{index + 1} - #{horse}" end end def run_race(horses) shuffled = [] 4.times do |lap| # Each lap, shuffle the array shuffled = horses.shuffle puts "Here is the ranking at lap #{lap + 1}:" display_horses(shuffled) sleep 2 puts '' end return shuffled end
true
28e45d4955ba58920e8da38c71d32417ae730af8
Ruby
timrogers/alexa_bank_details_lookup
/lib/validate_uk_bank_details_handler.rb
UTF-8
1,693
2.546875
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'alexa_skills_ruby' require_relative 'bank_details_lookup_service' class ValidateUkBankDetailsHandler < AlexaSkillsRuby::Handler on_intent('ValidateUkBankDetails') { look_up_bank_details } private def look_up_bank_details bank_details_lookup = bank_details_lookups.create(account_number: account_number, sort_code: sort_code) valid_bank_details_message(bank_details_lookup.bank_name) rescue GoCardlessPro::ValidationError => exception invalid_bank_details_message(exception) rescue GoCardlessPro::GoCardlessError => exception generic_error_message(exception) end def account_number request.intent.slots['AccountNumber'] end def sort_code request.intent.slots['SortCode'] end def bank_details_lookups BankDetailsLookupService.new(access_token: Prius.get(:gocardless_access_token)) end def valid_bank_details_message(bank_name) logger.info 'Successfully looked up bank details belonging to #{bank_name}' response.set_output_speech_text('Those bank details are valid, and belong to ' \ "#{bank_name}.") end def invalid_bank_details_message(exception) logger.error "Validation failure when looking up bank details: #{exception}" response.set_output_speech_text('Those bank details are invalid.') end def generic_error_message(exception) logger.error "Unknown GoCardless error when looking up bank details: #{exception}" response.set_output_speech_text('Sorry, something went wrong while looking up ' \ 'those bank details.') end end
true
2c55f90d9b951c263b08236f4f218c24e7818721
Ruby
horisakis/pro_ruby_intro
/02/2.05/2.5.2/logical_operator.rb
UTF-8
138
2.609375
3
[]
no_license
t1 = true t2 = true f1 = false f2 = false t1 && t2 t1 && f1 t1 || f1 f1 || f2 t1 && t2 || f1 && f2 t1 && (t2 || f1) && f2 !(t1 && f1)
true
bc3743e89b3220cc2c5ce558a830c9e6041c857f
Ruby
filipeamoreira/rstat.us
/test/models/update_test.rb
UTF-8
9,168
2.609375
3
[ "WTFPL" ]
permissive
require_relative '../test_helper' describe Update do include TestHelper describe "text length" do it "is not valid without any text" do u = Factory.build(:update, :text => "") refute u.save, "I made an empty update, it's very zen." end it "is valid with one character" do u = Factory.build(:update, :text => "?") assert u.save end it "is not valid with > 140 characters" do u = Factory.build(:update, :text => "This is a long update. This is a long update. This is a long update. This is a long update. This is a long update. This is a long update. jklol") refute u.save, "I made an update with over 140 characters" end end describe "@ replies" do describe "non existing user" do it "does not make links (before create)" do u = Factory.build(:update, :text => "This is a message mentioning @steveklabnik.") assert_match "This is a message mentioning @steveklabnik.", u.to_html end it "does not make links (after create)" do u = Factory(:update, :text => "This is a message mentioning @steveklabnik.") assert_match "This is a message mentioning @steveklabnik.", u.to_html end end describe "existing user" do before do Factory(:user, :username => "steveklabnik") end it "makes a link (before create)" do u = Factory.build(:update, :text => "This is a message mentioning @SteveKlabnik.") assert_match /\/users\/steveklabnik'>@SteveKlabnik<\/a>/, u.to_html end it "makes a link (after create)" do u = Factory(:update, :text => "This is a message mentioning @SteveKlabnik.") assert_match /\/users\/steveklabnik'>@SteveKlabnik<\/a>/, u.to_html end end describe "existing user with domain" do it "makes a link (before create)" do @author = Factory(:author, :username => "steveklabnik", :domain => "identi.ca", :remote_url => 'http://identi.ca/steveklabnik') u = Factory.build(:update, :text => "This is a message mentioning @SteveKlabnik@identi.ca.") assert_match /<a href='#{@author.url}'>@SteveKlabnik@identi.ca<\/a>/, u.to_html end it "makes a link (after create)" do @author = Factory(:author, :username => "steveklabnik", :domain => "identi.ca", :remote_url => 'http://identi.ca/steveklabnik') u = Factory(:update, :text => "This is a message mentioning @SteveKlabnik@identi.ca.") assert_match /<a href='#{@author.url}'>@SteveKlabnik@identi.ca<\/a>/, u.to_html end end describe "existing user mentioned in the middle of the word" do before do Factory(:user, :username => "steveklabnik") Factory(:user, :username => "bar") end it "does not make a link (before create)" do u = Factory.build(:update, :text => "@SteveKlabnik @nobody foo@bar.wadus @SteveKlabnik") assert_match "\/users\/steveklabnik'>@SteveKlabnik<\/a> @nobody foo@bar.wadus <a href='http:\/\/#{u.author.domain}\/users\/steveklabnik'>@SteveKlabnik<\/a>", u.to_html end it "does not make a link (after create)" do u = Factory(:update, :text => "@SteveKlabnik @nobody foo@bar.wadus @SteveKlabnik") assert_match "\/users\/steveklabnik'>@SteveKlabnik<\/a> @nobody foo@bar.wadus <a href='http:\/\/#{u.author.domain}\/users\/steveklabnik'>@SteveKlabnik<\/a>", u.to_html end end end describe "links" do it "makes URLs into links (before create)" do u = Factory.build(:update, :text => "This is a message mentioning http://rstat.us/.") assert_match /<a href='http:\/\/rstat.us\/'>http:\/\/rstat.us\/<\/a>/, u.to_html u = Factory.build(:update, :text => "https://github.com/hotsh/rstat.us/issues#issue/11") assert_equal "<a href='https://github.com/hotsh/rstat.us/issues#issue/11'>https://github.com/hotsh/rstat.us/issues#issue/11</a>", u.to_html end it "makes URLs into links (after create)" do u = Factory(:update, :text => "This is a message mentioning http://rstat.us/.") assert_match /<a href='http:\/\/rstat.us\/'>http:\/\/rstat.us\/<\/a>/, u.to_html u = Factory(:update, :text => "https://github.com/hotsh/rstat.us/issues#issue/11") assert_equal "<a href='https://github.com/hotsh/rstat.us/issues#issue/11'>https://github.com/hotsh/rstat.us/issues#issue/11</a>", u.to_html end it "makes URLs in this edgecase into links" do edgecase = <<-EDGECASE Not perfect, but until there's an API, you can quick add text to your status using links like this: http://rstat.us/?status={status} EDGECASE u = Factory.build(:update, :text => edgecase) assert_match "<a href='http://rstat.us/?status={status}'>http://rstat.us/?status={status}</a>", u.to_html end end describe "hashtags" do it "makes links if hash starts a word (before create)" do u = Factory.build(:update, :text => "This is a message with a #hashtag.") assert_match /<a href='\/search\?q=%23hashtag'>#hashtag<\/a>/, u.to_html u = Factory.build(:update, :text => "This is a message with a#hashtag.") assert_equal "This is a message with a#hashtag.", u.to_html end it "makes links if hash starts a word (after create)" do u = Factory(:update, :text => "This is a message with a #hashtag.") assert_match /<a href='\/search\?q=%23hashtag'>#hashtag<\/a>/, u.to_html u = Factory(:update, :text => "This is a message with a#hashtag.") assert_equal "This is a message with a#hashtag.", u.to_html end it "makes links for both a hashtag and a URL (after create)" do u = Factory(:update, :text => "This is a message with a #hashtag and mentions http://rstat.us/.") assert_match /<a href='\/search\?q=%23hashtag'>#hashtag<\/a>/, u.to_html assert_match /<a href='http:\/\/rstat.us\/'>http:\/\/rstat.us\/<\/a>/, u.to_html end it "extracts hashtags" do u = Factory(:update, :text => "#lots #of #hash #tags") assert_equal ["lots", "of", "hash", "tags"], u.tags end end describe "twitter" do describe "twitter => true" do it "sets the tweeted flag" do u = Factory.build(:update, :text => "This is a message", :twitter => true) assert_equal true, u.twitter? end it "sends the update to twitter" do f = Factory(:feed) at = Factory(:author, :feed => f) u = Factory(:user, :author => at) a = Factory(:authorization, :user => u) Twitter.expects(:update) u.feed.updates << Factory.build(:update, :text => "This is a message", :twitter => true, :author => at) assert_equal u.twitter?, true end it "does not send to twitter if there's no twitter auth" do f = Factory(:feed) at = Factory(:author, :feed => f) u = Factory(:user, :author => at) Twitter.expects(:update).never u.feed.updates << Factory.build(:update, :text => "This is a message", :twitter => true, :author => at) end end describe "twitter => false (default)" do it "does not set the tweeted flag" do u = Factory.build(:update, :text => "This is a message.") assert_equal false, u.twitter? end it "does not send the update to twitter" do f = Factory(:feed) at = Factory(:author, :feed => f) u = Factory(:user, :author => at) a = Factory(:authorization, :user => u) Twitter.expects(:update).never u.feed.updates << Factory.build(:update, :text => "This is a message", :twitter => false, :author => at) end end end describe "same update twice in a row" do it "will not save if both are from the same user" do feed = Factory(:feed) author = Factory(:author, :feed => feed) user = Factory(:user, :author => author) update = Factory.build(:update, :text => "This is a message", :feed => author.feed, :author => author, :twitter => false) user.feed.updates << update user.feed.save user.save assert_equal 1, user.feed.updates.size update = Factory.build(:update, :text => "This is a message", :feed => author.feed, :author => author, :twitter => false) user.feed.updates << update refute update.valid? end it "will save if each are from different users" do feed1 = Factory(:feed) author1 = Factory(:author, :feed => feed1) user1 = Factory(:user, :author => author1) feed2 = Factory(:feed) author2 = Factory(:author, :feed => feed2) user2 = Factory(:user, :author => author2) update = Factory.build(:update, :text => "This is a message", :feed => author1.feed, :author => author1, :twitter => false) user1.feed.updates << update user1.feed.save user1.save assert_equal 1, user1.feed.updates.size update = Factory.build(:update, :text => "This is a message", :feed => author2.feed, :author => author2, :twitter => false) user1.feed.updates << update assert update.valid? end end end
true
0facc922de024115ddd844091934b88638347866
Ruby
yangzpag/SecureStreams-DEBS17
/remote/lib/settings.rb
UTF-8
2,051
2.671875
3
[]
no_license
require 'yaml' module DeepMergeHash refine Hash do def deep_merge(second) merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 } self.merge(second, &merger) end end end using DeepMergeHash class Settings DEFAULT_OPTS = { 'cluster' => { 'manager_docker_port' => '2381', 'node_docker_port' => '2375', 'consul_port' => '8500', 'network_name' => 'default_network' }, 'swarm' => { 'image' => 'swarm:1.2.5', 'strategy' => 'spread' } } def self.create_section(name, settings) self.class.instance_eval do define_method(name) do settings end settings.each do |key, value| next unless key.is_a? String self.send(name).define_singleton_method(key) do value.freeze end end end end begin @@settings = DEFAULT_OPTS.deep_merge(YAML::load_file('config.yml')) rescue Exception => e raise "Something is wrong with your config.yml file: #{e.message}" end @@settings.each do |key, value| create_section(key, value || []) end # add methods for nodes self.cluster.nodes.each do |node| [:ip, :name, :role, :roles, :network_if, :type].each do |attribute| node.define_singleton_method(attribute) { node[attribute.to_s] } end end self.define_singleton_method(:manager) { self.cluster.manager } self.define_singleton_method(:manager_docker_port) { self.cluster.manager_docker_port } self.define_singleton_method(:node_docker_port) { self.cluster.node_docker_port } self.define_singleton_method(:manager_localhost) { "localhost:#{manager_docker_port}" } self.define_singleton_method(:node_localhost) { "localhost:#{node_docker_port}" } self.define_singleton_method(:consul_ip) { self.cluster.consul_ip } self.define_singleton_method(:consul_port) { self.cluster.consul_port } self.define_singleton_method(:network_name) { self.cluster.network_name } self.define_singleton_method(:nodes) { self.cluster.nodes } end
true
343efff894141b9a2215586243312514b9a72853
Ruby
Quackers71/automation-sre
/yikes2.rb
UTF-8
100
2.703125
3
[]
no_license
# using the system method output = system("lazy") puts output puts "continuing on our merry way..."
true
748b7e5d244c1aa8324e6509c9118ceddba5ce98
Ruby
hugocorbucci/github-contest-2009
/lib/heuristics/popular_projects.rb
UTF-8
673
3.03125
3
[ "MIT" ]
permissive
require 'lib/project' require 'lib/user' class PopularProjects def initialize(projects, users) followers = count_followers(users) @populars = sort(followers).slice(0..10) end def select_projects_for(user) @populars end private def count_followers(users) follower_counter = {} users.values.each do |user| user.projects.each do |project| if follower_counter[project.id].nil? follower_counter[project.id]=0 else follower_counter[project.id]+=1 end end end follower_counter end def sort(followers) followers.sort{|a,b| b[1]<=>a[1]}.map{|tuple| tuple[0]} end end
true
acb0621e3701fc4759283a1e2d0ba83e75c35763
Ruby
MRudolph/battlebays
/app/helpers/users_helper.rb
UTF-8
813
2.515625
3
[ "MIT" ]
permissive
module UsersHelper def user_text_link (user) if user link_to h(user.displayed_name), user else t('users.missing') end end def user_photo_link(user,size=nil) if user link_to image_tag(user.photo.url(size),:title=>user.displayed_name),user else "" end end def create_groups_from_sorted_users(users,n=3) return [] if users.empty? result=[] current_users=[] current_score=nil users.each do |user| current_score=user.points if current_score.nil? if current_score == user.points current_users << user else result << current_users return result if result.length==n current_users=[user] current_score=user.points end end result << current_users result end end
true
36c3fb1b953ad0bd077ab4358464a47d5e539fd1
Ruby
yendai-vo/nyc-pigeon-organizer-prework
/nyc_pigeon_organizer.rb
UTF-8
490
3.03125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def nyc_pigeon_organizer(data) # write your code here! organizedData = Hash.new data.each do |attributeType, attributeValues | attributeValues.each do |attributeValue, birdNames| birdNames.each do |bird| organizedData[bird] = {} unless organizedData[bird] organizedData[bird][attributeType] = [] unless organizedData[bird][attributeType] organizedData[bird][attributeType].push(attributeValue.to_s) end end end return organizedData end
true
0694b09494b15a85ceb280cf552b130d95cb084f
Ruby
svslight/ruby-basics
/lesson1/perfect_weight.rb
UTF-8
353
3.59375
4
[]
no_license
print 'Введите Ваше имя: ' name = gets.chomp.capitalize print "#{name}, введите Ваш рост: " height = gets.to_i perfect_weight = ((height - 110) * 1.15).round(2) if perfect_weight > 0 puts "#{name}, Ваш идеальный вес: #{perfect_weight} кг." else puts 'Ваш вес уже оптимальный' end
true
03782070e21bbfcd9f78c276c04d5f7aff6fd7df
Ruby
Zensaburou/slack_cli
/lib/message_poster_service.rb
UTF-8
416
3.0625
3
[ "MIT" ]
permissive
class MessagePosterService def initialize user_input = nil until user_input == 'exit' user_input = gets.chomp post_message(user_input) end end private def post_message(user_input) channel_name, message = parse_input(user_input) WebInterface.new.post_message_to_channel_by_name(channel_name, message) end def parse_input(user_input) user_input.split('|') end end
true
262be022e39f861d46045e5d574eb8372a8c97e6
Ruby
ArjunAranetaCodes/MoreCodes-Ruby
/Loops/problem4.rb
UTF-8
125
3.109375
3
[]
no_license
#Problem 4: Write a program that outputs an asterisk #pyramid. for y in 0..5 for x in 0..y print "*" end puts end
true
b16eadb845b3c56fb6844470582e0fc67b12c638
Ruby
crossmann/ruby-example
/CsvReader.rb
UTF-8
469
3.640625
4
[]
no_license
require 'csv' require_relative 'book_in_stock.rb' # read data from CSV file (book.csv) class CsvReader def initialize @books_in_stock =[] end def read_csv_book(csv_filename) CSV.foreach(csv_filename, headers: true) do |row| @books_in_stock << BookInStock.new(row['ISBN'], row['Price']) end end def total_cost sum = 0.0 @books_in_stock.each do |book| sum += book.price end sum puts "Total cost: #{sum}" end end
true
e191a7f6a9aafbe66289e050f5ce9d34b4a0892c
Ruby
wyhaines/ridgepole-executor
/lib/ridgepole/executor/config.rb
UTF-8
1,057
2.65625
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'json' module Ridgepole class Executor # Parse and encapsulate the configuration that may be provided. class Config attr_reader :config def initialize(json = '{}') @config = {} parse(json) end def parse(json = '{}') json = '{}' if json.to_s.empty? @config = @config.merge(JSON.parse(json)) end def [](val) @config[val.to_sym] || @config[val.to_s] end def []=(key, val) @config[key] = val end def merge(other) @config.merge(other) end def merge!(other) @config.merge!(other) end def to_hash @config end def method_missing(meth, *args, &block) if @config.key?(meth) || @config.key?(meth.to_s) @config[meth] || @config[meth.to_s] else super end end def respond_to_missing?(meth, *args) @config.key?(meth) || @config.key?(meth.to_s) || super end end end end
true
115120cbbc97c7628d314a8b8f28128826f66ac2
Ruby
trashcanmonster8/Tic-Tac-Toe
/lib/Board.rb
UTF-8
1,642
3.90625
4
[]
no_license
class Board #initialize the class by creating the board def initialize() $board = [[ 0, 0, 0 ], [ 0, 0, 0 ], [ 0, 0, 0 ]] @boardtomarkerhash = { -1 => ' o', 1 => ' x', 0 => ' _' } $markertoboardhash = { 'x' => 1, 'o' => -1 } system('cls') puts "Welcome to Tic-Tac-Toe!" end def EndGame() #Check rows for i in 0..2 gameover = false sum = 0 for j in 0..2 sum += $board[i][j] end if sum == -3 puts "o wins!" gameover = true break end if sum == 3 puts "x wins!" gameover = true break end end #Check columns for j in 0..2 sum = 0 for i in 0..2 sum += $board[i][j] end if sum == -3 puts "o wins!" gameover = true break end if sum == 3 puts "x win!" gameover = true break end end #Check diagonal sum = 0 for i in 0..2 sum += $board[i][i] end if sum == -3 puts "o wins!" gameover = true end if sum == 3 puts "x win!" gameover = true end #Check other diagonal sum = 0 for i in 0..2 sum += $board[2-i][i] end if sum == -3 puts "o wins!" gameover = true end if sum == 3 puts "x win!" gameover = true end return gameover end def PrintBoard system('cls') puts " 1 2 3" for i in 0..2 print i + 1 for j in 0..2 print @boardtomarkerhash[$board[j][i]] end puts "" end end end
true
1722a408ca373de5de275bf25394d117e4426073
Ruby
MyriamBoran/Myriam_Boran_PDA
/PDA_Static_and_Dynamic_Task_A/specs/testing_task_2_specs.rb
UTF-8
739
3.078125
3
[]
no_license
require 'minitest/autorun' require 'minitest/rg' require_relative('../testing_task_2.rb') require_relative('../card.rb') class TestCardGame < Minitest::Test def setup @card1 = Card.new("ace", 1) @card2 = Card.new("two", 2) @card_game = CardGame.new() end def test_check_for_ace assert_equal(true, @card_game.check_for_ace(@card1)) end def test_check_for_ace_not_ace assert_equal(false, @card_game.check_for_ace(@card2)) end def test_highest_card assert_equal(@card2, @card_game.highest_card(@card1, @card2)) assert_equal(@card2, @card_game.highest_card(@card2, @card1)) end def test_cards_total assert_equal("You have a total of 3", CardGame.cards_total([@card1, @card2])) end end
true
cf330d7145996c15bf181b1eec7f89eabe8c98bb
Ruby
polymar/pages
/lib/twitter_client.rb
UTF-8
2,913
2.859375
3
[]
no_license
require 'net/http' require 'json' require 'lib/short_url' require 'logger' module Twitter class Client def initialize( auth ) @auth = auth end # public method for updating twitter status def update_status( status ) # status = { :message => 'new post on ruby', :url => 'http://www.ruby-lang.com' } message = status[:message] short_url = ::ShortUrl::Client.new.short_url( status[:url] ) if message.nil? or message.empty? posted = shorted unless ( short_url.nil? or short_url.empty? ) else posted = message posted = posted + ': ' + short_url unless ( short_url.nil? or short_url.empty? ) end if posted.nil? { :error => 'Invalid status.'} else call( 'statuses/update', { :status => posted } , :post ) end end # public method for getting public timelines def public_timeline call( 'statuses/public_timeline.json' ) end private def call( path, params = {}, method = :get ) if method == :get logger.info "Calling #{get_url( path, params ) } ..." request = Net::HTTP::Get.new( get_url( path, params ) ) else logger.info "Calling #{post_url( path ) } ..." request = Net::HTTP::Post.new( post_url( path ) ) request.set_form_data( params ) end request.basic_auth( login, password ) response = Net::HTTP.start( 'twitter.com' ) do |h| h.request( request ) end logger.info "tweet: " + response.code response.value # triggers error if not 2xx logger.info "Success!" JSON.parse( response.body ) end def get_url( path, params ) "http://twitter.com/#{path}.json#{query(params)}" end def post_url( path ) "http://twitter.com/#{path}.json" end def query( params ) return '' if params.nil? or params.empty? params.inject('?') { |q,p| q << "#{p[0]}=#{p[1]}&" } end def login @auth[:user] end def password @auth[:password] end def logger @logger ||= Logger.new( $stderr ) end end end # client = Twitter::Client.new( :user => 'duckonice', :password => 'bolognasalvati' ) # begin # resp = client.update_status( { :message => 'testing from' } ) # p resp # rescue Object => e # puts "Log to logger message: #{e.message}" # end # begin # resp = client.update_status( { :url => 'http://www.gazzetta.it' } ) # p resp # rescue Object => e # puts "Log to logger message: #{e.message}" # end # begin # resp = client.update_status( { :message => 'testing from' , :url => 'http://www.google.com' } ) # p resp # rescue Object => e # puts "Log to logger message: #{e.message}" # end # begin # resp = client.update_status( { :ciao => 'testing from' } ) # p resp # rescue Object => e # puts "Log to logger message: #{e.message}" # end
true
c28534f7ab50751d5c302f3e2b82f4ee4ba5bbde
Ruby
woundedfrog/Ruby-prep-exercises
/ch10_more/ex3.rb
UTF-8
337
3.015625
3
[]
no_license
#Exception handling is a piece of code that handles errors, if they occur. # If an erorr occurs, then the specified 'exception handling' rules will allow the program to signal that an error occured, but still continue executing the remaining code. # # Without an exception handling rule stated, the program will stop executing.
true
64b7167c5389bdc12748a72c2d775852ea28b366
Ruby
faezeh-ashtiani/betsy
/test/models/category_test.rb
UTF-8
1,536
2.78125
3
[]
no_license
require "test_helper" describe Category do let (:category) { Category.new( name: "Weird Name" ) } describe "relations" do it "can access the products related to the category throug join table" do products = [products(:product1), products(:product2), products(:product3)] products.each do |product| category.products << product end category.save expect(category).must_respond_to :products expect(category.products.count).must_equal 3 category.products.each do |product| expect(product).must_be_instance_of Product end end it "can have zero products" do expect(categories(:category8).products.count).must_equal 0 end end describe "validations" do it "is valid for a category with all required fields" do expect(category.valid?).must_equal true end it "has the required fields" do category.save new_category = Category.last [:name].each do |field| expect(new_category).must_respond_to field end end it "is invalid without a name" do category.name = nil expect(category.valid?).must_equal false expect(category.errors.messages).must_include :name end it "cannot creat a new category with the same name" do category.save category_2 = Category.new(name: "Weird Name") expect(category_2.valid?).must_equal false expect(category_2.errors.messages).must_include :name end end end
true