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
38b75ff68aa21ff5aa3da35441507f7c11931c72
Ruby
Timbinous/practice
/libraries/resque/word_analyzer.rb
UTF-8
218
2.953125
3
[]
no_license
class WordAnalyzer @queue = 'some_queue_name' def self.perform(from_queue) puts "About to do some heavy duty analysis on #{from_queue}" sleep 3 puts "Finished with analysis on #{from_queue}" end end
true
2166bcb0962e702fa0de664ec2d2a7baad54ff17
Ruby
moonfox/2-broke-girls
/app/format_subtitle.rb
UTF-8
2,605
2.625
3
[]
no_license
require 'iconv' class FormatSubtitle class << self def remove_timeline item = ARGV[0] source_file = File.readlines(File.expand_path("../original/broke_girls_#{item}.txt", __FILE__)) find_session_start = source_file.find_index("19\n") if find_session_start.nil? find_session_start = source_file.find_index("19\r\n") end # puts source_file[0..20].inspect # puts "find_session_start:#{find_session_start}" source_file = source_file[find_session_start..-1] source_file = source_file.collect do |line| encode = line.force_encoding("gb2312") if encode.valid_encoding? Iconv.conv("utf-8//IGNORE","gb2312", line) else line end end puts source_file[0..20] source_file.delete_if{|line| line.include?(' --> ')} source_file = source_file.collect{|line|line.gsub(/\{.+\}/,'')} new_file = File.open(File.expand_path("../subtitle/broke_girls_#{item}.txt", __FILE__),"w") new_file.puts source_file end def parse_html path = File.expand_path("../new_file/html.txt", __FILE__) if File.exist?(path) return "File already exist" end url = 'http://www.yyets.com/search/index?keyword=%E6%89%93%E5%B7%A5%E5%A7%90%E5%A6%B9%E8%8A%B1+%E7%AC%AC%E4%B8%80%E5%AD%A3&type=' response = %x[ curl #{url} ].to_s new_file = File.open(path,"w") new_file.puts response end def parse_url path = File.expand_path("../new_file/html.txt", __FILE__) html = File.read(path) download_url = html.scan(/www\.yyets\.com\/subtitle\/\d+/) new_file = File.open(File.expand_path("../new_file/download_url.txt", __FILE__),"w") new_file.puts download_url end def session_url path = File.expand_path("../new_file/download_url.txt", __FILE__) urls = File.readlines(path) session_url = [] urls.each do |line| response = %x[ curl #{line} ].to_s.scan(/www\.yyets\.com\/subtitle\/index\/download\?id\=\d+/) session_url << response.first end new_file = File.open(File.expand_path("../new_file/session_url.txt", __FILE__),"w") new_file.puts session_url end def download_rar path = File.expand_path("../new_file/session_url.txt", __FILE__) urls = File.readlines(path) # urls.each_with_index do |uri, index| # %x[ wget -O #{index}.rar #{uri}] # end %x[mv *.rar #{File.expand_path("../download", __FILE__)}] end end end FormatSubtitle.remove_timeline # FormatSubtitle.download_rar
true
81185fac01001cc4d92723c46adbee38b552cc8e
Ruby
Taishawnk/programming-univbasics-3-labs-with-tdd-online-web-prework
/calculator.rb
UTF-8
885
4.09375
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
puts "Simple Calculator" 25.times{ print "-"} puts puts "first number" num_1 = gets.chomp puts "second number" num_2 = gets.chomp puts "let's multiply both numbers and we get #{num_1.to_i * num_2.to_i}" puts "let's divide both numbers and we get #{num_1.to_i / num_2.to_i}" puts "let's substract both numbers and we get #{num_1.to_i - num_2.to_i}" puts "let's add both numbers and we get #{num_1.to_i + num_2.to_i}" puts "let's find the modulus for both numbers and we get #{num_1.to_i % num_2.to_i}" #- The third test is looking for a local variable named `sum`. The `sum` variable #is the result of adding `first_number` and `second_number` together. This test # is using all three variables. Not only that, the test is using whatever values #_you_ assigned to `first_number` and `second_number`. #`quotient` for dividing the `first_number` and `second_number` variables.
true
e120db1a982df6c5b576a41fe8a3f3d50b8acede
Ruby
sunainashrivastava/Ruby-Assignments
/class.rb
UTF-8
104
3.265625
3
[]
no_license
class FirstClass def hello puts "Hello Ruby!" end end object = FirstClass.new object.hello
true
e5e635e4d605d24e7bffcab15fc3bf8130d15838
Ruby
amckemie/Walking-With-The-Dead-Dungeon-Game
/spec/commands/use_item_spec.rb
UTF-8
11,660
2.703125
3
[]
no_license
require 'spec_helper' describe WWTD::UseItem do let(:db) {WWTD.db} before(:each) do db.clear_tables @room = db.create_room(name: 'Bedroom', description: 'test', quest_id: 1) @player = db.create_player(username: 'Ashley', password: 'eightletters', description: "Test player", room_id: @room.id) @jacket = db.create_item(classification: 'item', name: 'jacket', description: "A comfy UT jacket left over from the good ole days", actions: 'put on, wear, pick up, take', room_id: @room.id ) @quest = db.create_quest(name: 'Quest Test (haha)', data: {answer_phone: true}) db.create_room_item(player_id: @player.id, quest_id: @quest.id, room_id: @room.id, item_id: @jacket.id) WWTD.db.create_quest_progress(quest_id: @quest.id, player_id: @player.id, furthest_room_id: @room.id, data: @quest.data, complete: false) end describe 'preparing input' do it 'parses the array down to the 1st 4 inputted words' do input = WWTD::UseItem.new.prepare_input('jacket', ['put','on', 'two', 'shirt', 'with','my', 'hands']) expect(input).to eq(['put', 'on', 'two', 'shirt']) input2 = WWTD::UseItem.new.prepare_input('jacket', ['wear', 'two', 'shirt']) expect(input2).to eq(['wear', 'two', 'shirt']) end it 'deletes the item' do input = WWTD::UseItem.new.prepare_input('jacket', ['put','on', 'two', 'jacket', 'with','my', 'hands']) expect(input).to eq(['put', 'on','two']) input2 = WWTD::UseItem.new.prepare_input('jacket', ['put','on', 'jacket','too', 'with','my', 'hands']) expect(input2).to eq(['put', 'on','too']) end it 'deletes common articles/conjunctions' do input = WWTD::UseItem.new.prepare_input('jacket', ['put','on', 'the', 'jacket', 'with','my', 'hands']) expect(input).to eq(['put', 'on']) end end describe 'checking items actions' do before(:each) do @result = WWTD::UseItem.new.check_item_actions('jacket', ['wear']) @result2 = WWTD::UseItem.new.check_item_actions('jacket', ['put', 'on',]) end it 'returns success true if the inputted action is a recognized one for the item' do expect(@result.success?).to eq(true) expect(@result2.success?).to eq(true) end it 'returns the recognized action if success is true' do expect(@result.action).to eq('wear') expect(@result2.action).to eq('put on') end it 'returns success false if the inputted action is not recognized for the item' do result3 = WWTD::UseItem.new.check_item_actions('jacket', ['put', 'the', 'on']) expect(result3.success?).to eq(false) expect(result3.error).to eq('Sorry, that is not a known action for that.') end end describe 'jacket' do it "returns 'You are now nice and toasty with the jacket on.' if input is 'put on' or 'wear'" do result = WWTD::UseItem.run(@player, 'jacket', ['put', 'on','the', 'jacket']) expect(result.message).to eq('You are now nice and toasty with the jacket on.') result2 = WWTD::UseItem.run(@player, 'jacket', ['wear','the', 'jacket']) expect(result2.message).to eq('You are now nice and toasty with the jacket on.') end it "returns the failure message if the input is not either put on or wear" do result = WWTD::UseItem.run(@player, 'jacket', ['use','the', 'jacket']) expect(result.message).to eq('Sorry, that is not a known action for that.') end end describe 'TV' do before(:each) do @tv = WWTD.db.create_item(classification: 'item', name: 'tv', description: "A badass 80inch TV that a roommate once left in your lucky lucky possession.", actions: 'turn on, watch', room_id: @room.id ) end it "returns 'You're going to watch the powder puff girls?? Really??' if input is 'put on' or 'wear'" do result = WWTD::UseItem.run(@player, 'tv', ['turn', 'on','the', 'tv']) expect(result.message).to eq("You're going to watch the powder puff girls?? Really??") result2 = WWTD::UseItem.run(@player, 'tv', ['watch','the', 'tv']) expect(result2.message).to eq("You're going to watch the powder puff girls?? Really??") end it "returns the failure message if the input is not either put on or wear" do result = WWTD::UseItem.run(@player, 'tv', ['use','the', 'tv']) expect(result.message).to eq('Sorry, that is not a known action for that.') end end describe 'socks' do before(:each) do @socks = WWTD.db.create_item(classification: 'item', name: 'socks', description: "A pair of grungy white socks that have held up over the years", actions: 'put on, wear, pick up, take', room_id: @room.id ) end it "returns 'You are now wearing the socks, which is kinda gross, but what can you do?' if input is 'put on' or 'wear'" do result = WWTD::UseItem.run(@player, 'socks', ['put', 'on','the', 'socks']) expect(result.message).to eq('You are now wearing the socks, which is kinda gross, but what can you do?') result2 = WWTD::UseItem.run(@player, 'socks', ['wear', 'socks']) expect(result2.message).to eq('You are now wearing the socks, which is kinda gross, but what can you do?') end it "returns the failure message if the input is not either put on or wear" do result = WWTD::UseItem.run(@player, 'socks', ['use','the', 'socks']) expect(result.message).to eq('Sorry, that is not a known action for that.') end end describe 'shower' do before(:each) do @shower = WWTD.db.create_item(classification: 'item', name: 'shower', description: "Just astand up shower in your bathroom.", actions: 'get in, use, take, shower, clean', room_id: @room.id ) end it "returns You're so fresh and so clean clean now.'' if input is 'get in', 'take', or 'shower'" do result = WWTD::UseItem.run(@player, 'shower', ['get', 'in','the', 'shower']) expect(result.message).to eq("You're so fresh and so clean clean now.") result2 = WWTD::UseItem.run(@player, 'shower', ['clean', 'shower']) expect(result2.message).to eq("Well, that's one way to start your day. But the shower is now clean.") end it "returns the failure message if the input is not either put on or wear" do result = WWTD::UseItem.run(@player, 'shower', ['wear','the', 'shower']) expect(result.message).to eq('Sorry, that is not a known action for that.') end end describe 'backpack (else part of statement)' do before(:each) do @backpack = db.create_item(classification: 'item', name: 'backpack', description: "A trusty backpack that can fit a surprising number of medical books", actions: 'put on, take', room_id: @room.id ) db.create_room_item(player_id: @player.id, quest_id: 1, room_id: @room.id, item_id: @backpack.id) end it 'returns success with a message of Good idea. Youll probably need this. if player enters take' do result = WWTD::UseItem.run(@player, 'backpack', ['take']) expect(result.message).to eq("Good idea. You'll probably need this.") end it "returns Good idea. Youll probably need this. if input is 'put on'" do result = WWTD::UseItem.run(@player, 'backpack', ['put', 'on','the', 'backpack']) expect(result.message).to eq("Item picked up!") end it "returns the failure message if the input is not either put on or take" do result = WWTD::UseItem.run(@player, 'backpack', ['wear','the', 'backpack']) expect(result.message).to eq('Sorry, that is not a known action for that.') end it 'is added to a persons inventory' do result = WWTD::UseItem.run(@player, 'backpack', ['take','the', 'backpack']) player_inventory = WWTD.db.get_player_inventory(@player.id) expect(player_inventory[0].name).to eq('backpack') end end describe 'take_item' do before(:each) do @backpack = db.create_item(classification: 'item', name: 'backpack', description: "A trusty backpack that can fit a surprising number of medical books", actions: 'put on, take', room_id: @room.id ) end it "returns a failure message of 'Sorry, you have nothing to take this item in yet.' if the backpack hasn't been picked up." do result = WWTD::UseItem.new.take_item('jacket', @player) expect(result.success?).to eq(false) expect(result.error).to eq("Sorry, you have nothing to take this item in yet.") end it 'returns success with a message of "Item picked up!" if player has backpack' do db.create_room_item(player_id: @player.id, quest_id: 1, room_id: @room.id, item_id: @backpack.id) db.create_inventory(@player.id, @player.room_id, @backpack.id, 1) result = WWTD::UseItem.new.take_item('jacket', @player) expect(result.success?).to eq(true) expect(result.message).to eq('Item picked up!') end it "adds the item to the person's inventory" do db.create_room_item(player_id: @player.id, quest_id: 1, room_id: @room.id, item_id: @backpack.id) db.create_inventory(@player.id, @player.room_id, @backpack.id, 1) result = WWTD::UseItem.run(@player, 'jacket', ['take', 'the', 'jacket']) expect(result.success?).to eq(true) player_inventory = WWTD.db.get_player_inventory(@player.id) expect(player_inventory.count).to eq(2) end # testing take / pick up through whole command it 'returns successfully routes to take_item method if input is take or pick up' do db.create_room_item(player_id: @player.id, quest_id: 1, room_id: @room.id, item_id: @backpack.id) db.create_inventory(@player.id, @player.room_id, @backpack.id, 1) result = WWTD::UseItem.run(@player, 'jacket', ['take', "the", "jacket"]) expect(result.message).to eq("Item picked up!") result2 = WWTD::UseItem.run(@player, 'jacket', ['pick', "up", "the", "jacket"]) expect(result2.message).to eq("Item picked up!") end end # describe 'toothbrush and toothpaste' do # before(:each) do # @toothpaste = WWTD.db.create_item(classification: 'item', # name: 'Toothpaste', # description: "So fresh and so clean, clean. ", # actions: 'take', # room_id: @room.id # ) # @toothbrush = WWTD.db.create_item(classification: 'item', # name: 'Toothbrush', # description: "Don't you think you're a little old for a Spiderman toothbrush? Nah.... ", # actions: 'brush teeth', # room_id: @room.id # ) # end # it "let's you brush your teeth if you have " # end end
true
25e4e532c5c8456cfc2bd02176bddcb9bbaf9455
Ruby
jminterwebs/flatiron-bnb-methods-v-000
/app/models/listing.rb
UTF-8
1,123
2.546875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Listing < ActiveRecord::Base belongs_to :neighborhood belongs_to :host, :class_name => "User" has_many :reservations has_many :reviews, :through => :reservations has_many :guests, :class_name => "User", :through => :reservations validates :address, presence: true validates :listing_type, presence: true validates :title, presence: true validates :price, presence: true validates :description, presence: true validates :neighborhood, presence: true after_create :user_to_host after_destroy :user_to_unhost def average_review_rating avg = 0.0 total = 0 self.reservations.each do |reservation| total += reservation.review.rating end avg = total/self.reservations.count.to_f end def booked booked = [] self.reservations.each do |reservation| booked << [reservation.checkin .. reservation.checkout] end booked.flatten end private def user_to_host # binding.pry self.host.update(host: true) end def user_to_unhost self.host.update(host: false) if self.host.listings.count == 0 end end
true
d2fc62c6d531977105ee64cdb50ba10b05382b9c
Ruby
sulaimancode/bank_tech_test
/spec/account_spec.rb
UTF-8
788
2.703125
3
[]
no_license
require 'account' describe Account do TRANSACTION_AMOUNT = 1000 let(:account) { described_class.new } let(:transaction) { double :transaction, amount: TRANSACTION_AMOUNT } before do allow(transaction).to receive(:account_balance=) allow(transaction).to receive(:type=) end describe '::new' do it 'has an initial balance of £0' do expect(account.balance).to eq 0 end end describe '#deposit' do it 'increments balance by amount given' do expect { account.deposit(transaction) }.to change { account.balance }.by(TRANSACTION_AMOUNT) end end describe '#withdraw' do it 'decrements balance by amount given' do expect { account.withdraw(transaction) }.to change { account.balance }.by(-TRANSACTION_AMOUNT) end end end
true
45dddb9c20787fb25bb5b80d5be2060c5305ceb8
Ruby
bsdave/ruby-parallel-forkmanager
/lib/parallel/forkmanager/serializer.rb
UTF-8
1,503
3.046875
3
[]
no_license
require "yaml" require_relative "error" module Parallel class ForkManager # TODO: Maybe make this into a factory, given the number of case statements # switching on type. This is a "shameless green" if you use Sandi Metz's # terminology. class Serializer ## # Raises a {Parallel::ForkManager::UnknownSerializerError} exception if # +type+ isn't one of +marshal+ or +yaml+ # # @param type [String] The type of serialization to use. def initialize(type) @type = validate_type(type) end ## # @param data_structure [Object] the data to be serialized. # @return [String] the serialized representation of the data. def serialize(data_structure) case type when :marshal Marshal.dump(data_structure) when :yaml YAML.dump(data_structure) end end ## # @param serialized [String] the serialized representation of the data. # @return [Object] the resonstituted data structure. def deserialize(serialized) case type when :marshal Marshal.load(serialized) when :yaml YAML.load(serialized) end end private attr_reader :type def validate_type(t) case t.downcase when "marshal" :marshal when "yaml" :yaml else fail Parallel::ForkManager::UnknownSerializerError end end end end end
true
abca139ab18486e28a22bf5ebf5329e20a224a30
Ruby
sjmog/dnd_engine
/lib/item.rb
UTF-8
181
2.65625
3
[]
no_license
class Item attr_reader :type, :armor_check_penalty def initialize(opts = {}) @type = opts.fetch(:type, :misc) @armor_check_penalty = opts[:armor_check_penalty] end end
true
db47cc614fbfc5cd520ad79c9ee042d8157deecd
Ruby
daneb/codedtrue.com
/column_to_sql.rb
UTF-8
473
3.1875
3
[]
no_license
# Converts a column format file into a SQL string for use in an "IN" # For example: select * from x where y IN ({result}) # if ARGV.empty? puts "Please provide a column spaced file to convert to a SQL string" else sql_string = "" column_file = ARGV.last file = File.open(column_file) file.each do |column_item| sql_string = (sql_string + "'" + column_item.chomp + "',") end sql_string.chop! File.open('result.txt', 'w') { |file| file.write(sql_string) } end
true
3cdd7d8ea8b3ae0bee364e2f97bef7a650784fcf
Ruby
TapasTech/InvestCooker
/lib/concerns/limit_frequency.rb
UTF-8
1,097
2.5625
3
[]
no_license
concern :LimitFrequency do def limit_frequency(key:, time: nil) return if $redis_object.get(key).present? $redis_object.set(key, 'processing') yield ensure if time.present? $redis_object.expire(key, time) else $redis_object.del(key) end end included do def self.limit_frequency(method_name, key:, time: nil) method_with_limit_frequency = Module.new do define_method method_name do |*args| if key.respond_to?(:call) key_str = key.call(*args) else key_str = key.to_s end limit_frequency key: key_str, time: time do super(*args) end end end prepend method_with_limit_frequency end end end
true
d6d951cdd0bd40eb11c7611c9857512c0e814f5e
Ruby
jongillies/barnyard
/barnyard_harvester/lib/barnyard_harvester/generic_queue.rb
UTF-8
1,950
2.84375
3
[ "MIT" ]
permissive
module BarnyardHarvester class GenericQueue def initialize(args) @queueing = args.fetch(:queueing) { raise "You must provide :queueing" } case @queueing when :sqs require "aws-sdk" @sqs_settings = args.fetch(:sqs_settings) { raise "You must provide :sqs_settings" } @sqs = AWS::SQS.new(@sqs_settings) when :rabbitmq require "bunny" @rabbitmq_settings = args.fetch(:rabbitmq_settings) { raise "You must provide :rabbitmq_settings" } @rabbitmq_settings[:logging] = true if @debug @bunny = Bunny.new(@rabbitmq_settings) @bunny.start when :hash @queues = Hash.new else raise "Unknown queueing method. #{@queuing}" end end def push(queue_name, message) case @queueing when :sqs queue = @sqs.queues.create(queue_name) queue.send_message(message) when :rabbitmq @bunny.queue(queue_name).publish(message) when :hash @queues[queue_name] = Array.new unless @queues.has_key?(queue_name) @queues[queue_name] << message File.open("#{queue_name}.yml", "w") { |file| file.puts(@queues[queue_name].to_yaml) } end end def pop(queue_name) case @queueing when :sqs msg = @sqs.queues.create(queue_name).receive_message unless msg.nil? msg.delete msg.body else nil end when :rabbitmq msg = @bunny.queue(queue_name).pop[:payload] if msg == :queue_empty return nil else msg end when :hash msg = @queue.pop File.open("#{queue_name}.yml", "w") { |file| file.puts(@queues[queue_name].to_yaml) } msg end end def empty(queue_name) while pop(queue_name) end end end end
true
aa2294df03a03753420bb80afdc6c6dbb172ea04
Ruby
Jing1107/wdi30-classwork
/wdi30-ruby/05-ruby/class.rb
UTF-8
972
3.53125
4
[]
no_license
require 'pry' class Actor def award_speech "I would like to thank my parents and my agent. We did it baby" end def deny_allagations "I deny that and I was drunk and I don't remember" end end class MarxBrother attr_accessor :name, :instrument, :vice #Macro -writes the getter and setter for you # #Getter # def name # #return # @name # end # # Setter # def name=(n) # @name = n # end # # def instrument # @instrument # end # # def instrument=(i) # @instrument = i # end # # def vice # @vice # end # # def vice=(v) # @vice = v # end def initialize (n='',i='',v='') @name = n @instrument = i @vice = v end def perform "My name is #{name} and I play the #{instrument}" end end class Stooge < Actor def terrible? true end end groucho = MarxBrother.new # Create an instance object binding.pry # groucho.name=("Groucho") # puts groucho.name #=> "Groucho"
true
2cc192393689332532a8804ae6e8c28658f66b87
Ruby
minnonong/Codecademy_Ruby
/01. Introduction to Ruby/01_12.rb
UTF-8
115
3.359375
3
[]
no_license
# 01-12 Naming Conventions # 변수 이름은 소문자로 시작하고 단어는 _로 구분함. name = "Eric"
true
01079e1e30d194bfcbe52fa9b4cf61b077ef0da3
Ruby
spejamchr/code
/first_programs/stuff.rb
UTF-8
166
2.875
3
[]
no_license
number = 1 start_time = Time.new 1000000.times do number = number * 2 end puts number.to_s.length processing_time = Time.new - start_time puts puts processing_time
true
857e11df8f6d81d0812f01da78ffb445a40640b1
Ruby
dnhc/Introduction-to-Regular-Expressions
/Character_Class_Shortcuts/ex3.rb
UTF-8
751
3.84375
4
[]
no_license
# Write a regex that matches any four digit hexadecimal number that is both # preceded and followed by whitespace. Note that 0x1234 is not a hexadecimal # number in this exercise: there is no space before the number 1234. # Hello 4567 bye CDEF - cdef # 0x1234 0x5678 0xABCD # 1F8A done # There should be four matches (2 on Scriptular) def match_in_string?(string, regex) string.match(regex).class == MatchData end def number_of_matches(string, regex) dup_string = string.dup matches = [] while match_in_string?(dup_string, regex) matches.push('match') dup_string.sub!(regex, '') end matches.length end regex = /\s\h\h\h\h\s/ test = 'Hello 4567 bye CDEF - cdef 0x1234 0x5678 0xABCD 1F8A done' p number_of_matches(test, regex)
true
4048d7a621e99f19c65bf0b25f0fe7a12c1fb572
Ruby
AskBid/school-domain-online-web-sp-000
/lib/school.rb
UTF-8
433
3.5625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# code here! class School attr_reader :roster def initialize(name) @name = name @roster = {} end def add_student(stud, grade) @roster[grade] = [] if ! @roster[grade] @roster[grade] << stud end def grade(grade) @roster[grade] end def sort @roster.each {|k, arr| # puts '--------------' # puts @roster[k] @roster[k] = arr.sort # puts '*' # puts @roster[k] # puts '--------------' } end end
true
eec18822a61285b3f4cdb791cd43cb20b672aa4c
Ruby
rootstrap/rs-code-review-metrics
/app/services/builders/review_turnaround.rb
UTF-8
986
2.53125
3
[]
no_license
module Builders class ReviewTurnaround < BaseService def initialize(review_request) @review_request = review_request end def call ::ReviewTurnaround.create!(review_request: @review_request, value: calculate_turnaround, pull_request: @review_request.pull_request) end private def calculate_turnaround weekend_seconds = WeekendSecondsInterval.call( start_date: review_request_created_at, end_date: review_opened_at ) (review_opened_at.to_i - review_request_created_at.to_i) - weekend_seconds end def review_request_created_at @review_request_created_at ||= @review_request.created_at end def review_opened_at @review_opened_at ||= first_review_or_comment end def first_review_or_comment (@review_request.pull_request_comments | @review_request.reviews) .min_by(&:opened_at).opened_at end end end
true
99211d23632ae45bef425c1f77ce0fc94d07e0aa
Ruby
nico24687/open_mic
/lib/joke.rb
UTF-8
331
2.890625
3
[]
no_license
class Joke attr_reader :id, :question, :answer def initialize(attributes) @id = attributes[:id] @question = attributes[:question] @answer = attributes[:answer] end # def id # @id # end # def question # @question # end # def answer # @answer # end end
true
80f2a923338765d8056d73e00c5388db1c0b6421
Ruby
sshaw/itunes_store_transporter
/lib/itunes/store/transporter/output_parser.rb
UTF-8
2,415
2.859375
3
[ "MIT" ]
permissive
require "itunes/store/transporter/errors" module ITunes module Store module Transporter class OutputParser ## # This class extracts error and warning messages output by +iTMSTransporter+. For each message # is creates an instance of ITunes::Store::Transporter::TransporterMessage # attr :errors attr :warnings ERROR_LINE = /<main>\s+ERROR:\s+(.+)/ WARNING_LINE = /<main>\s+WARN:\s+(.+)/ # Generic messages we want to ignore. SKIP_ERRORS = [ /\boperation was not successful/i, /\bunable to verify the package/i, /\bwill NOT be verified/, /^an error has occurred/i, /^an error occurred while/i, /^unknown operation/i, /\bunable to authenticate the package/i ] ## # === Arguments # # [output (Array)] +iTMSTransporter+ output # def initialize(output) @errors = [] @warnings = [] parse_output(output) if Array === output end private def parse_output(output) output.each do |line| if line =~ ERROR_LINE error = $1 next if SKIP_ERRORS.any? { |skip| error =~ skip } errors << create_message(error) elsif line =~ WARNING_LINE warnings << create_message($1) end end # Unique messages only. The block form of uniq() is not available on Ruby < 1.9.2 [errors, warnings].each do |e| next if e.empty? uniq = {} e.replace(e.select { |m| uniq.include?(m.message) ? false : uniq[m.message] = true }) end end def create_message(line) case line when /^(?:ERROR|WARNING)\s+ITMS-(\d+):\s+(.+)/ code = $1 message = $2 when /(.+)\s+\((\d+)\)$/, # Is this correct? /(.+)\s+errorCode\s+=\s+\((\d+)\)$/ message = $1 code = $2 else message = line code = nil end message.gsub! /^"/, "" message.gsub! /"(?: at .+)?$/, "" TransporterMessage.new(message, code ? code.to_i : nil) end end end end end
true
92c64e817773e5cae9ac5a78224c5e172abfa8db
Ruby
daniel-schroeder-dev/tts-ruby
/w1/wk_2_hw1.rb
UTF-8
366
4.78125
5
[]
no_license
# Write a program that takes a string argument and: # outputs the string in reverse # outputs the string in all caps # tells you the length of the string puts "Type any sentence:" sentence = gets.chomp puts "The sentence reversed is #{sentence.reverse}" puts "The sentence in all caps is #{sentence.upcase}" puts "The length of the sentence is #{sentence.length}"
true
b32f719bc1d46ee1fe4aa4ab3289a44123c13a5c
Ruby
aballal/oystercard
/feature_spec/feature9_spec.rb
UTF-8
221
3.203125
3
[]
no_license
# Step 13 # In order to know how far I have travelled # As a customer # I want to know what zone a station is in require_relative '../lib/station.rb' station = Station.new("Kings Cross",1) p station.name p station.zone
true
726cf0ab2f4ec53210241badb2376cdbb3c9f1c8
Ruby
jaynetics/immutable_set
/benchmarks/new.rb
UTF-8
892
2.734375
3
[ "MIT" ]
permissive
require_relative './shared' benchmark( caption: '::new with 5M Range items', cases: { 'stdlib' => ->{ S.new(0...5_000_000) }, 'gem' => ->{ I.new(0...5_000_000) }, 'gem w/o C' => ->{ P.new(0...5_000_000) }, } ) benchmark( caption: '::new with 100k Range items', cases: { 'stdlib' => ->{ S.new(0...100_000) }, 'gem' => ->{ I.new(0...100_000) }, 'gem w/o C' => ->{ P.new(0...100_000) }, } ) prep_ranges = [ 0...1000, 1001...2001, 2002...3002, 3003...4003, 4004...5004, 5005...5006, 6006...6007, 7007...7008, 8008...8009, 9009...9010, 10_010...11_010 ] benchmark( caption: '::new with 10k Range items in 10 non-continuous Ranges', cases: { 'stdlib' => ->{ set = S.new; prep_ranges.each { |r| set.merge(r) } }, 'gem' => ->{ I.from_ranges(*prep_ranges) }, 'gem w/o C' => ->{ P.from_ranges(*prep_ranges) }, } )
true
bf13ae5a8251028cc810ff32e5370f03e762465d
Ruby
cadwallion/em-ruby-irc
/lib/em-ruby-irc/IRC-User.rb
UTF-8
329
2.8125
3
[]
no_license
module IRC class User attr_reader :name attr_accessor :hostmask, :user_data attr_writer :logged_in def initialize(name, hostmask=nil) @name = name @hostmask = String.new @hostmask = hostmask unless hostmask.nil? @logged_in = false @user_data = nil end def logged_in? @logged_in end end end
true
52c112e0e34a438cee35f3711ee011122b82002e
Ruby
Pablo-Merino/mail-parser
/lib/mail_parser/address.rb
UTF-8
280
2.84375
3
[]
no_license
module MailParser class Address attr_accessor :name attr_accessor :address EMAIL_REGEX = /^(.+) <(.+)>$/i def initialize(string) matches = EMAIL_REGEX.match(string) @name = matches[1] @address = matches[2] end end end
true
994f63607c774163578e43aea033b7e178f18365
Ruby
joelmac/number-sensei-rails-4
/db/seeds/gamification.seeds.rb
UTF-8
1,074
3.125
3
[]
no_license
# experience level curve ExperienceLevel.delete_all ExperienceFunction.delete_all levels = 20 xp_for_first_level = 100 xp_for_last_level = 200000 BB = Math.log(1.0 * xp_for_last_level / xp_for_first_level) / (levels - 1) AA = 1.0 * xp_for_first_level / (Math.exp(BB) - 1.0) puts "Coefficients A=#{AA}, B=#{BB}" experience_function = ExperienceFunction.create!(coefficient_a: AA, coefficient_b: BB) #def self.xp_for_level(i) # x = (AA * Math.exp(BB * i)).to_i # y = 10**(Math.log(x) / Math.log(10) - 2.2).to_i # (x / y).to_i * y #end ExperienceLevel.create(level: 0, experience: 0) # starting level is always 0 cumulative_experience = 0 (1..levels).each do |i| experience_to_level = experience_function.calculate_experience_for_level(i) - experience_function.calculate_experience_for_level(i-1) cumulative_experience += experience_to_level lvl = ExperienceLevel.create(level: i, experience: cumulative_experience, delta: experience_to_level) puts "#{lvl} #{lvl.experience} (+#{lvl.delta})" end experience_function.experience_levels << ExperienceLevel.all
true
f5d97bde7638faf44ff80d46d502edfef0eba096
Ruby
macbury/ralyxa
/lib/ralyxa/register_intents.rb
UTF-8
1,322
2.78125
3
[ "MIT" ]
permissive
require_relative './skill' module Ralyxa class RegisterIntents DEFAULT_INTENTS_DIRECTORY = './intents'.freeze def initialize(intents_directory, alexa_skill_class) @intents_directory = intents_directory @alexa_skill_class = alexa_skill_class end def self.run(intents_directory = DEFAULT_INTENTS_DIRECTORY, alexa_skill_class = Ralyxa::Skill) new(intents_directory, alexa_skill_class).run end def run warn NO_INTENT_DECLARATIONS_FOUND if intent_declarations.empty? intent_declarations.each do |intent_declaration| alexa_skill_class.class_eval intent_declaration end end private attr_reader :intents_directory, :alexa_skill_class def intent_declarations @intent_declarations ||= Dir.glob("#{intents_directory}/*.rb") .map { |relative_path| File.expand_path(relative_path) } .map { |intent_declaration_path| File.open(intent_declaration_path).read } end heredoc = <<~HEREDOC \e[33m WARNING: You haven't defined any intent declarations. Please define intent declarations inside a directory called 'intents', on the same directory level as the runfile for your server application. \e[0m HEREDOC NO_INTENT_DECLARATIONS_FOUND = heredoc.freeze end end
true
5411b5567b7f18c3ce502547a92bfc04c88df06c
Ruby
MadBomber/experiments
/ruby_misc/net_ssh_multi_test.rb
UTF-8
2,426
2.625
3
[]
no_license
############################################## ### ## File: net_ssh_multi_test.rb ## Desc: Just testing # require 'net/ssh' Net::SSH.start('10.0.52.139', 'dvanhoozer', :password => ENV["xyzzy"]) do |ssh| # capture all stderr and stdout output from a remote process output = ssh.exec!("hostname") # capture only stdout matching a particular pattern stdout = "" ssh.exec!("ls -l /home/dvanhoozer") do |channel, stream, data| stdout << data if stream == :stdout end puts stdout # run multiple processes in parallel to completion ssh.exec "echo 'one'" ssh.exec "echo 'two'" ssh.exec "echo 'three'" ssh.loop =begin # open a new channel and configure a minimal set of callbacks, then run # the event loop until the channel finishes (closes) channel = ssh.open_channel do |ch| ch.exec "/usr/local/bin/ruby /path/to/file.rb" do |ch, success| raise "could not execute command" unless success # "on_data" is called when the process writes something to stdout ch.on_data do |c, data| $STDOUT.print data end # "on_extended_data" is called when the process writes something to stderr ch.on_extended_data do |c, type, data| $STDERR.print data end ch.on_close { puts "done!" } end end # channel.wait # forward connections on local port 1234 to port 80 of www.capify.org # ssh.forward.local(1234, "www.capify.org", 80) # ssh.loop { true } =end end ################################################################### =begin require 'net/ssh/multi' Net::SSH::Multi.start do |session| # access servers via a gateway # session.via 'gateway', 'gateway-user' # define the servers we want to use # session.use "[email protected]/#{ENV['xyzzy']}" # session.use "[email protected]/#{ENV['xyzzy']}" # define servers in groups for more granular access session.group :ise do session.use "[email protected]/#{ENV['xyzzy']}" session.use "[email protected]/#{ENV['xyzzy']}" end # execute commands on all servers session.exec "uptime" # execute commands on a subset of servers session.with(:ise).exec "hostname" # run the aggregated event loop session.loop end =end
true
ecebbfe3c53d0916d6f76e25b4012d69c56f8334
Ruby
mfoody72/WDI_SYD_7_Work
/w01/d01/michael/roman_numerals.rb
UTF-8
370
3.890625
4
[]
no_license
def to_roman(number) string = "I" * number string.gsub("I" * 1000, "M"). gsub("I" * 900, "CM"). gsub("I" * 500, "D"). gsub("I" * 400, "CD"). gsub("I" * 100, "C"). gsub("I" * 90, "CX"). gsub("I"*50,"L"). gsub("I"*40,"LX"). gsub("I"*10,"X"). gsub("I"*9,"XI"). gsub("I"*5,"V"). gsub("I"*4,"VI") end puts to_roman(1997)
true
d148087488ca86ab344bd6ac32eac68340b179f7
Ruby
cristianrasch/c2010-scrapper
/lib.rb
UTF-8
1,907
2.921875
3
[ "MIT" ]
permissive
### ### Methods ### def usage " Censo 2010 Scrape Tool: Usage ruby scrape.rb [option] * option: Viviendas, Poblacion, Hogares " end def scrape_viviendas scrape(VIVIENDAS_ID) end def scrape_hogares scrape(HOGARES_ID) end def scrape_poblacion scrape(POBLACION_ID) end def scrape_xls(base_path, provincia_id, departamento_id, departamento_name, unidad_id, unidad_desc) puts "Scraping... Provincia: #{provincia_id}. Departamento: #{departamento_name}. Unidad: #{unidad_desc}" xml = Hpricot::XML(HTTParty.get("#{RESULTADOS_DEFINITIVOS_URL}?p=#{provincia_id}&d=#{departamento_id}&t=#{unidad_id}")) (xml/:a).each_with_index do |link, index| uri = link.attributes['href'] if link.innerHTML == "XLS" unless SCRAPED[uri] SCRAPED[uri] = true file_path = "#{base_path}/pcia#{provincia_id}-depto#{departamento_id}-#{unidad_desc}-#{index / 2}.xls" begin puts "Downloading: #{file_path}" if Pathname.new(file_path).exist? puts "Already downloaded: #{file_path}" else AGENT.get("http://www.censo2010.indec.gov.ar/#{uri}").save_as file_path end rescue Exception => e puts "Error downloading: http://www.censo2010.indec.gov.ar/#{uri} to scraped/pcia#{provincia_id}-depto#{departamento_id}-#{unidad_desc}-#{index}.xls" puts e.message end end end end if (xml/:a) puts "Scraped!" end def scrape(unidad_id) unidad_desc = UNIDADES[unidad_id] puts "Scraping #{unidad_desc}... " base_path = "scraped/#{unidad_desc}" FileUtils.mkdir_p base_path CSV.foreach('data/departamentos.csv') do |row| provincia_id = row[0] departamento_id = row[1] departamento_name = row[2] scrape_xls(base_path, provincia_id, departamento_id, departamento_name, unidad_id, unidad_desc) end end
true
f3dc94f87ef110265dd8679b13299c43c01277a8
Ruby
myokoym/bricks_meet_balls
/lib/bricks_meet_balls/bar.rb
UTF-8
737
3.15625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require "gosu" require "bricks_meet_balls/util" require "bricks_meet_balls/z_order" module BricksMeetBalls class Bar include Util def initialize(window) @window = window @width = @window.width * 0.3 @height = @window.height * 0.01 @x1 = @window.width * 0.5 @y1 = @window.height * 0.9 @x2 = @x1 + @width @y2 = @y1 + @height @movement = @width * 0.04 end def draw draw_square(@window, @x1, @y1, @x2, @y2, Gosu::Color::BLACK, ZOrder::Bar) end def move_left @x1 -= @movement @x2 = @x1 + @width end def move_right @x1 += @movement @x2 = @x1 + @width end end end
true
48ea896e11b0f22bdfa6e86c53df68674f0f572b
Ruby
thefotios/uberconfig
/lib/uberconfig.rb
UTF-8
806
2.703125
3
[]
no_license
#!/usr/bin/env ruby require 'logging' module UberConfig class Config include Logging attr_reader :configs, :values def initialize(*configs) logger.debug "Initializing" @values = {} @configs = [] configs.each do |cfg| add_config(cfg) end end def add_config(*objects) [*objects].each do |config| logger.debug "Adding: #{config.name}" @configs << config @values.merge!(config.values) end end def save(config) unless config.kind_of?(UberConfig::File) config = @configs.select{|x| x.name == config}.first end if config.writable? config.save(values) else logger.warn "Config file #{config.path} not writable, cannot save" end end end end
true
cf8caa6d7b04bcd2e6ee58331b7bae2f779f8411
Ruby
kpenn44/Ruby-Programming
/BlackJack_Exercise.rb
UTF-8
7,513
3.59375
4
[]
no_license
#--------------------------------------------------------------------------- # # Script Name: BlackJarck.rb # Version: 1.0 # Author: Kelvin Penn # Date: April 2010 # # Description: This ruby game is a computerized version of the casino card # game in which the player competes against the dealer (i.e., computer) in # an effor to build a hand that comes as close as possible to 21 without # going over # #-------------------------------------------------------------------------- #define a class representin the console window class Screen def cls #define a method that clears the display area puts ("\n" * 25) #scroll the screen 25 times puts "\a" #make a little noise to get the player's attention end def pause #define a method that pauses the display area STDIN.gets #execute the STDIN class's gets method to pause the #script execution until player presses Enter end end #define a class representin the Ruby Blackjack game class Game def get_file(filename) if filename == "Help" then retrieve_files("Help") elsif filename == "Welcome" retrieve_files("Welcome") elsif filename == "Credits" retrieve_files("Credits") end Console_Screen.pause end def retrieve_files(pickfile) if pickfile == "Help" then $help_file = File.read("BJHelp.txt") puts $help_file elsif pickfile == "Welcome" then $welcome_file = File.read("BJWelcome.txt") puts $welcome_file elsif pickfile == "Credits" then $credits_file = File.read("BJCredits.txt") puts $credits_file end end #define a method to be used to display game instructions #define a method to control game play def play_game Console_Screen.cls #clear the display area #give the player and dealer an initial starting card playerHand = get_new_card dealerHand = get_new_card #call the method responsible for dealing new cars to the player playerHand = complete_player_hand(playerHand, dealerHand) #if the player has not busted, call the method if playerHand <= 21 then dealerHand = play_dealer_hand(dealerHand) end #call the method responsible for determining the results determine_winner(playerHand, dealerHand) end def write_log_file(type) if RUBY_PLATFORM =~ /win32/ then outFile = File.new('C:\temp\BJLog.txt', "a") outFile.puts type outFile.close else outFile = File.new('tmp/BJLog.txt', "a") outFile.puts type outfile.close end #define a method responsible for dealing a new card def get_new_card #assign a random number from 1 to 13 as the value of the card #being created card = 1 + rand(13) #a value of 1 is an ace, so reassign the card value of 11 return 11 if card == 1 #a value of 10 or more equals a face card so reassign the card #a value of 10 return 10 if card >= 10 return card #return the value assigned to the new card end #define a method responsible for dealing the rest of the player hand def complete_player_hand(playerHand, dealerHand) loop do #loop forever Console_Screen.cls #clear the display area #show the current state of the player's and dealer's hands puts "Player's hand: " + playerHand.to_s + "\n\n" puts "Dealer's hand: " + dealerHand.to_s + "\n\n\n\n\n" print "Would you like another card (y/n) " reply = STDIN.gets #collect the player's answer reply.chop! #remove any extra characters appended #to the string #see if the player decided to ask for another card if reply =~ /y/i then #call method responsible to the player's hand playerHand = playerHand + get_new_card end #see if the player has decided to stick with the current hand if reply =~ /n/i then break #terminate the execution of the loop end if playerHand > 21 then break #terminate the execution of the loop end end #return the value of the player's hand return playerHand end #defin a method responsible for managing the dealer's hand def play_dealer_hand(dealerHand) loop do #loop forever #if the alue of the dealer's hand is less than 17 #then give the dealer another card if dealerHand < 17 then #call method responsible for getting a new card #and add to dealer's hand dealerHand = dealerHand + get_new_card else break #terminate the execution of the loop end end #return the value of the dealer's hand return dealerHand end #define a method responsible for analying the player's and dealer's #hands and determining who won def determine_winner(playerHand, dealerHand) Console_Screen.cls #clear the display area #show the value of the player's and dealer's hands puts "Player's hand: " + playerHand.to_s + "\n\n" puts "Dealer's hand: " + dealerHand.to_s + "\n\n\n\n\n\n\n" write_log_file("Player's hand: " + playerHand.to_s) write_log_file("Dealer's hand: " + dealerHand.to_s) if playerHand > 21 then #see if the player has busted puts "You have gone bust!\n\n" print "Press Enter to continue." else #see if the player and dealer have tied if playerHand == dealerHand then puts "Tie!\n\n" print "Press Enter to continue" end #see if dealer has busted if dealerHand > 21 then puts "The Dealer has gone bust!\n\n" print "Press Enter to continue." else #see if the player's hand beats the dealer's hand if playerHand > dealerHand then puts "You have won!\n\n" print "Press Enter to continue" end #see if the dealer's hand beats the player's hand if playerHand < dealerHand then puts "The Dealer has won!\n\n" print "Press Enter to continue." end end end Console_Screen.pause #pause the game end end #Main Script Logic-------------------------------------------------------- Console_Screen = Screen.new #instantiate a new Screen object BJ = Game.new #instantiate a new Game object #execute the Game class's display_greeting method BJ.display_greeting answer = "" #initialized variable and assign it an empty string #loop until the player enters y or n and nothing else loop do Console_Screen.cls #clear the display area #prompt the player for permission to start the game print "Are you ready to play Ruby Blackjack? (y/n): " answer = STDIN.gets #collect the player's answer answer.chop! #remove any extra characters appended to string #terminate the loop if valid input was provided break if answer =~ /y|n/i #accept upercase and lowercase input end #analyze the player's answer if answer =~ /n/i #see if player wants to quit Console_Screen.cls #clear display area #invite the player to return and play the game soe other time puts "Okay, perhaps another time.\n\n" else #player wants to play game #execute the Game class's display_instructions method BJ.get_file playAgain = "" #initialized variable and assign it an empty string loop do #loop forever #execute the Game class's play_game method BJ.play_game loop do #loop forever Console_Screen.cls #clear the display area #find out if player wants to play another round print "Would you like to play another hand? (y/n): " playAgain = STDIN.gets #collect the player's respons playAgain.chop! #remove any extra characters appended #terminate loop if valid input was provided break if playAgain =~ /n|y/i #accept uppercase and lowercase end #terminate the loop if valid input was provided break if playAgain =~/n/i end #call upon the Game class's display_credits method BJ.display_credits end
true
381195b9e4ff3071433fb1e0fdd4ddbb2fad49cf
Ruby
IanVaughan/site-stats
/stats.rb
UTF-8
346
2.53125
3
[]
no_license
require 'sinatra' require 'json' stats = { nmt: 4807, mods: 35221, interactions: 211330, sites: 7601, members: 11987246 } counter = Thread.new(stats) do |s| loop do s[:nmt] += 4 s[:mods] += 3 s[:interactions] += 1 s[:sites] += 0 s[:members] += 4 sleep 1 end end get '/' do content_type :json stats.to_json end
true
95f552302b816d8cc21931d52c74d9686ff64165
Ruby
TamerL/searchable_docs
/spec/document_spec.rb
UTF-8
1,191
2.640625
3
[]
no_license
require 'rspec/autorun' require './src/document' RSpec.describe Document do describe '.initialize' do # initialize is a class method before do @document = Document.new('./doc1.txt') end it 'has a name' do expect(@document.name).to eq('doc1.txt') end it 'has a path' do expect(@document.path).to eq('./doc1.txt') end end describe '#content' do # content is instant method context 'given file is read successfully' do before do @document = Document.new('the document path') allow(File).to receive(:read).and_return("the document content") end it "calls File to read the document" do expect(File).to receive(:read).with('the document path') @document.content end it 'returns the content' do expect(@document.content).to eq("the document content") end end context 'when reading the file failed' do it 'raises an error' do @document = Document.new('the document path') allow(File).to receive(:read).and_raise("something wrong") expect do @document.content end.to raise_error("something wrong") end end end end
true
a4a6143d71cd1a5cc0ca94e38e91b4ffc99903bc
Ruby
nhashmi/a-nice-nest
/app/models/ranking.rb
UTF-8
888
2.671875
3
[]
no_license
class Ranking < ActiveRecord::Base belongs_to :user def self.load_rankings(user) if user.rankings.all.length == 0 total_residents = user.other_residents.to_i + 1 total_residents.times do user.rankings.create end @rankings = user.rankings.all return @rankings end end def ever_updated? created_at == updated_at ? false : true end def update_message if ever_updated? return "Last updated at" else return "Incomplete" end end def welcome_message if resident_name == "A resident" return "What are you looking for in a home?" else return "#{resident_name}, what are you looking for in a home?" end end def evaluate(attribute) if attribute == 'nice-to-have' return 3 elsif attribute == 'must-have' return 5 else return 1 end end end
true
5ee0dfbcbad33570a65e0e70cefde60f9ccf4433
Ruby
hopsoft/hero
/test/observer_test.rb
UTF-8
1,044
2.546875
3
[ "MIT" ]
permissive
require File.expand_path("../test_helper", __FILE__) class ObserverTest < PryTest::Test test "should support add_step" do step = lambda {} o = Hero::Observer.new(:example) o.add_step(:one, step) assert o.steps.length == 1 assert o.steps[0].first == :one assert o.steps[0].last == step end test "should support properly handle a double add" do step1 = lambda {} step2 = lambda {} o = Hero::Observer.new(:example) o.add_step(:one, step1) o.add_step(:one, step2) assert o.steps.length == 1 assert o.steps[0].first == :one assert o.steps[0].last == step2 end test "should properly sort steps based on the order they were added" do o = Hero::Observer.new(:example) o.add_step(:one) {} o.add_step(:two) {} o.add_step(:three) {} o.add_step(:four) {} o.add_step(:one) {} assert o.steps.length == 4 assert o.steps[0].first == :two assert o.steps[1].first == :three assert o.steps[2].first == :four assert o.steps[3].first == :one end end
true
576f80dcafdd91ad9a4f7dd740965cff037109d6
Ruby
jfredett/advent2020
/lib/toboggan.rb
UTF-8
271
3.0625
3
[]
no_license
class Toboggan attr_reader :run, :fall, :position attr_accessor :performance def initialize(run, fall) @position = [0,0] @run = run @fall = fall end def slide! @position = [self.position[0] + self.run, self.position[1] + self.fall] end end
true
2b6e2b58b502201f80f83c9e83faaf032a584a84
Ruby
caueguedes/design_patterns_ruby
/behavioral/8_strategy_example.rb
UTF-8
960
3.828125
4
[]
no_license
class Strategy def execute(_a, _b) raise NotImplementedError, "#{self.class} has not implemented method #{__method__}" end end class ConcreteStrategyAdd < Strategy def execute(a, b) a + b end end class ConcreteStrategySubtract < Strategy def execute(a, b) a - b end end class ConcreteStrategyMultiply < Strategy def execute(a, b) a * b end end class Context attr_accessor :strategy def initialize(strategy) @strategy = strategy end def execute(a, b) @strategy.execute(a, b) end end if $PROGRAM_NAME == __FILE__ a, b = 5, 3 context = Context.new(ConcreteStrategyAdd.new) puts 'ConcreteStrategyAdd' puts "5 + 3 = #{context.execute(a, b)}" puts 'ConcreteStrategySubtract' context.strategy = ConcreteStrategySubtract.new puts "5 - 3 = #{context.execute(a, b)}" puts 'ConcreteStrategyMultiply' context.strategy = ConcreteStrategyMultiply.new puts "5 * 3 = #{context.execute(a, b)}" end
true
718bf343ace98486ab71eee8370ad46754026390
Ruby
zencoder/zenflow
/spec/zenflow/helpers/ask_spec.rb
UTF-8
4,691
2.53125
3
[ "MIT" ]
permissive
require 'spec_helper' describe Zenflow do describe "prompt" do before do Zenflow.stub(:LogToFile) $stdin.stub(:gets).and_return("good") end it "displays a prompt" do Zenflow::Query.should_receive(:print).with(">> How are you? ") Zenflow::Ask("How are you?") end it "displays a prompt with options" do Zenflow::Query.should_receive(:print).with(">> How are you? [good/bad] ") Zenflow::Ask("How are you?", options: ["good", "bad"]) end it "displays a prompt with default" do Zenflow::Query.should_receive(:print).with(">> How are you? [good] ") Zenflow::Ask("How are you?", default: "good") end it "displays a prompt with options and default" do Zenflow::Query.should_receive(:print).with(">> How are you? [good/bad] ") Zenflow::Ask("How are you?", options: ["good", "bad"], default: "good") end context "on error" do before(:each) do Zenflow::Query.should_receive(:ask_question).at_least(:once).and_return('foo') Zenflow::Query.should_receive(:handle_response).once.and_raise('something failed') $stdout.should_receive(:puts).once end it{expect{Zenflow::Ask('howdy', response: 'foo', error_message: 'something failed')}.to raise_error(/something failed/)} end context "on interrupt" do before(:each) do Zenflow::Query.should_receive(:ask_question).once.and_return('foo') Zenflow::Query.should_receive(:handle_response).once.and_raise(Interrupt) Zenflow.should_receive(:LogToFile) $stdout.should_receive(:puts).at_least(:once) end it{expect{Zenflow::Ask('howdy')}.to raise_error(SystemExit)} end end describe Zenflow::Query do describe '.get_response' do context 'with a response' do it{expect( Zenflow::Query.ask_question('foo?', response: 'bar')).to eq('bar') } end context 'with a response' do before(:each) do Zenflow::Query.should_receive(:prompt_for_answer).with('foo?',{}).and_return('bar') end it{expect(Zenflow::Query.ask_question('foo?')).to eq('bar')} end end describe '.prompt_for_answer' do before(:each) do Zenflow::Query.should_receive(:print).with(">> Hi? [yes/bye] ") STDIN.should_receive(:gets).and_return("bye") end it{expect( Zenflow::Query.prompt_for_answer('Hi?', options: ['yes','bye']) ).to( eq('bye') ) } end describe '.handle_response' do context 'invalid response' do before(:each){Zenflow::Query.should_receive(:valid_response?).and_return(false)} it{expect{Zenflow::Query.handle_response('foo')}.to raise_error} end context 'valid response' do before(:each){Zenflow::Query.should_receive(:valid_response?).and_return(true)} it{expect(Zenflow::Query.handle_response('foo')).to eq('foo')} it{expect(Zenflow::Query.handle_response('Y')).to eq('y')} it{expect(Zenflow::Query.handle_response('N')).to eq('n')} it{expect(Zenflow::Query.handle_response('', default: 'foo')).to eq('foo')} it{expect(Zenflow::Query.handle_response('', default: 'FOO')).to eq('foo')} end end describe '.valid_response?' do it{expect(Zenflow::Query.valid_response?('foo', options: ['foo'])).to eq(true)} it{expect(Zenflow::Query.valid_response?('foo', options: ['bar'])).to eq(false)} it{expect(Zenflow::Query.valid_response?('foo', validate: /foo/)).to eq(true)} it{expect(Zenflow::Query.valid_response?('foo', validate: /bar/)).to eq(false)} it{expect(Zenflow::Query.valid_response?('', required: true)).to eq(false)} it{expect(Zenflow::Query.valid_response?('foo', required: true)).to eq(true)} it{expect(Zenflow::Query.valid_response?('foo', required: false)).to eq(true)} it{expect(Zenflow::Query.valid_response?('', required: false)).to eq(true)} it{expect(Zenflow::Query.valid_response?('', default: 'MERGE', options: ['merge', 'rebase'])).to eq(true)} it{expect(Zenflow::Query.valid_response?('MERGE', options: ['merge', 'rebase'])).to eq(true)} it{expect(Zenflow::Query.valid_response?('rebase', options: ['MERGE', 'REBASE'])).to eq(true)} end describe '.build_error_message' do it{expect(Zenflow::Query.build_error_message('foo')).to match(/not a valid response/)} it{expect(Zenflow::Query.build_error_message('foo', error_message: 'stupid response.')).to match(/stupid response/)} it{expect(Zenflow::Query.build_error_message('foo', required: true)).to match(/must respond/)} end end end
true
0df5ccb8cf8303cb40b819aa5e59b2ba1bc1ff62
Ruby
manofsteele/W4D2
/ninetyninecats/app/models/cat.rb
UTF-8
372
2.515625
3
[]
no_license
class Cat < ApplicationRecord validates :birth_date, :color, :name, presence: true validates :sex, presence: true, inclusion: {in: ["M", "F"]} COLORS = ["red", "black", "calico", "grey", "white", "blue"] def age birth_year = self.birth_date.year this_year = Date.today.year return this_year - birth_year end end
true
d81fb160f70e72ad5192eef64bbc548c59ddb091
Ruby
lelilia/job-prep
/leetCode/merge-sorted-array.rb
UTF-8
1,779
3.796875
4
[]
no_license
# https://leetcode.com/problems/merge-sorted-array/ # @param {Integer[]} nums1 # @param {Integer} m # @param {Integer[]} nums2 # @param {Integer} n # @return {Void} Do not return anything, modify nums1 in-place instead. def merge(nums1, m, nums2, n) return nums1 if n == 0 k = m + n - 1 i = m - 1 j = n - 1 while k >= 0 if j < 0 nums1[k] = nums1[i] i -= 1 elsif i < 0 nums1[k] = nums2[j] j -= 1 elsif nums1[i] > nums2[j] nums1[k] = nums1[i] i -= 1 else nums1[k] = nums2[j] j -= 1 end k -= 1 end return nums1 end def run_tests desc = "negative numbers" result = merge([-1, 0, 0, 3, 3, 3, 0, 0, 0], 6, [1,2,2], 3) correct = [-1, 0, 0, 1, 2, 2, 3, 3, 3] assert(desc, result, correct) desc = "empty 1" result = merge([0,0,0,0,0], 0, [1,2,3,4,5], 5) correct = [1,2,3,4,5] assert(desc, result, correct) desc ="test" result = merge([2,0],1,[1],1) correct = [1,2] assert(desc, result, correct) desc = "[1,2,3,0,0,0] + [2,5,6]" result = merge([1,2,3,0,0,0],3,[2,5,6],3) correct = [1,2,2,3,5,6] assert(desc, result, correct) desc = "short one" result = merge([1,2,3,0,0,0],3,[1,2,3],3) correct = [1,1,2,2,3,3] assert(desc, result, correct) desc = "longer one" result = merge([1,2,3,4,5,6,7,8,0,0,0,0,0,0,0,0], 8, [1,2,3,4,5,6,7,8], 8) correct = [1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8] assert(desc, result, correct) desc = "one is empty" result = merge([1],1,[], 0) correct = [1] assert(desc, result, correct) desc = "first is empty" result = merge([0],0,[1],1) correct = [1] assert(desc, result, correct) end def assert(desc, result, correct) puts "#{desc} ... #{result == correct ? 'PASS' : "FAIL: #{result} is not #{correct}"}" end run_tests
true
b19e6395901c33fb621118f9cc6ec09ee1418c1c
Ruby
dmaster18/learn-co-sandbox
/ruby_past_practice/bartender.rb
UTF-8
820
3.765625
4
[]
no_license
class Bartender attr_accessor :name BARTENDERS = [] def initialize(name) @name = name BARTENDERS << self end def self.all BARTENDERS end def intro "Hello, my name is #{@name}!" end def make_drink @cocktail_ingredients = [] choose_liquor choose_mixer choose_garnish return "Here is your drink. It contains #{@cocktail_ingredients}." end private def choose_liquor @cocktail_ingredients.push("whiskey") end def choose_mixer @cocktail_ingredients.push("vermouth") end def choose_garnish @cocktail_ingredients.push("olives") end end phil = Bartender.new("Phil") bob = Bartender.new("Bob") joe = Bartender.new("Joe") ellen = Bartender.new("Ellen") alex = Bartender.new("Alex") puts Bartender.all puts phil.make_drink
true
8fef43adc7ee054140160c37a042a34a1dc743bc
Ruby
Bluezzy/101
/101-109first_attempt/easy9.rb
UTF-8
1,748
4
4
[]
no_license
def greetings(name, skill) "Hello #{name.join(' ')} ! We are glad to have a #{skill[:title]} \n #{skill[:occupation]} here !" end def doubled?(number) number = number.to_s number_of_digits = number.size center_index = (number_of_digits / 2) left_part = number[0..center_index-1] right_part = number[center_index..-1] left_part == right_part end def twice(number) return number*2 if number.to_s.size == 1 if doubled?(number) number else number*2 end end def negative(int) return 0 if int == 0 if int.positive? int * -1 else int end end def sequence(number) result = [] while number > 0 result << number number -= 1 end result.sort end def uppercase?(string) string == string.upcase end def words_length(words_string) words = words_string.split(' ') words.each_index do |index| words[index] += " #{words[index].chars.count}" end end def swap_name(full_name) first_name = full_name.split(' ')[0] last_name = full_name.split(' ')[-1] "#{last_name}, #{first_name}" end def sequence(count, first_number) result = [] multiplier = 1 count.times do result << multiplier * first_number multiplier += 1 end result end def get_grade(score1, score2, score3) average_score = (score1 + score2 + score3) / 3 case when average_score >= 90 then 'A' when average_score >= 80 && average_score <= 90 then 'B' when average_score >= 70 && average_score <= 80 then 'C' when average_score >= 60 && average_score <= 70 then 'D' when average_score >= 50 && average_score <= 60 then 'E' else 'F' end end def buy_fruit(list) result = [] list.each do |fruit| fruit[-1].times do result << fruit[0] end end result end
true
5491d106501bb36c8ae076522e31d86917762378
Ruby
AnansiOmega/mod-1-mini-challenge-oo-one-to-many
/models/menu_item.rb
UTF-8
410
3.34375
3
[]
no_license
require 'pry' class MenuItem attr_accessor attr_reader :dish_name, :price, :restaurant @@all = [] def self.all @@all end def initialize(restaurant,dish_name,price) @restaurant = restaurant @dish_name = dish_name @price = price @@all << self end def restaurant_name self.restaurant.name end end # end of MenuItem class
true
4bdedbab0d6af5781fdac5a7de85dafcadde9b7e
Ruby
rsupak/aa-online
/Richard_Supak_Hotel_Project/lib/hotel.rb
UTF-8
847
3.515625
4
[]
no_license
require_relative "room" class Hotel attr_accessor :rooms def initialize(name, rooms) @name = name @rooms = rooms.each { |k, v| rooms[k] = Room.new(v) } end def name @name.split.map(&:capitalize).join(' ') end def room_exists?(room_name) rooms.key?(room_name) end def check_in(person, room_name) if room_exists?(room_name) if rooms[room_name].full? puts 'sorry, room is full' else rooms[room_name].add_occupant(person) unless rooms[room_name].full? puts 'check in successful' end else puts 'sorry, room does not exist' end end def has_vacancy? vacant = false rooms.values.each do |room| vacant = true unless room.full? end vacant end def list_rooms rooms.each { |k, v| puts "#{k} : #{v.available_space}" } end end
true
abb52e99011b8479251f5552076b50f3b0f601b5
Ruby
mpereira/bell
/lib/bell/user_report.rb
UTF-8
2,157
2.921875
3
[ "MIT" ]
permissive
# encoding: utf-8 module Bell class UserReport include Bell::Util::String def initialize(phone_bill, user_name) @phone_bill = phone_bill @user_name = user_name end def user Bell::User.find(:name => @user_name) end def calls @phone_bill.calls.inject([]) do |calls, call| if Bell::UserContact.find(:user_id => user.id, :number => call.number_called) calls << call else calls end end end def total calls.inject(0) { |total, call| total += call.cost.to_f } end def to_s "#{formatted_header}\n#{formatted_contact_calls}\n\n#{formatted_total}" end private def formatted_header "Data".ljust(15) << "Contato".ljust(20) << "Número".ljust(15) << "Horário".ljust(20) << "Custo" end def contact_calls calls.inject([]) do |contact_calls, call| if contact = Bell::UserContact.find(:number => call.number_called) contact_calls << { :contact => contact, :call => call } else contact_calls end end end def formatted_total "Total: R$ #{sprintf("%.2f", total)}" end def formatted_contact_name(contact_name) if contact_name.size > 20 shortened_contact_name = contact_name[0, 15].rstrip.concat('...') else shortened_contact_name = contact_name end multibyte_characters = shortened_contact_name.size - multibyte_length(shortened_contact_name) formatted_contact_name = shortened_contact_name. ljust(20 + multibyte_characters) end def formatted_contact_call(contact_call) contact = contact_call[:contact] call = contact_call[:call] call.date[0, 8].ljust(15) << formatted_contact_name(contact.name) << call.number_called.ljust(15) << call.start_time.ljust(20) << sprintf("%.2f", call.cost) end def formatted_contact_calls contact_calls. map { |contact_call| formatted_contact_call(contact_call) }.join("\n") end end end
true
8845287991b6dce2583efbade5cddf16afc611aa
Ruby
bluepostit/active-record-intro-628
/db/seeds.rb
UTF-8
519
2.921875
3
[]
no_license
# This is where you can create initial data for your app. require 'faker' # Restaurant.destroy_all puts 'Creating restaurants...' tour_d_argent = Restaurant.new(name: "La Tour d'Argent", address: 'Paris') tour_d_argent.save! chez_gladines = Restaurant.new(name: "Chez Gladines", address: 'Marseille') chez_gladines.save! # Create 10 restaurants with data from Faker 10.times do name = Faker::Restaurant.name address = Faker::Address.full_address Restaurant.create!(name: name, address: address) end puts 'Finished!'
true
7896e9c5d10ab83f36f7d52b069742287995a927
Ruby
masterzora/tawny-cdk
/lib/cdk/viewer.rb
UTF-8
23,040
2.609375
3
[ "BSD-3-Clause", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
require_relative 'cdk_objs' module CDK class VIEWER < CDK::CDKOBJS DOWN = 0 UP = 1 def initialize(cdkscreen, xplace, yplace, height, width, buttons, button_count, button_highlight, box, shadow) super() parent_width = cdkscreen.window.getmaxx parent_height = cdkscreen.window.getmaxy box_width = width box_height = height button_width = 0 button_adj = 0 button_pos = 1 bindings = { CDK::BACKCHAR => Ncurses::KEY_PPAGE, 'b' => Ncurses::KEY_PPAGE, 'B' => Ncurses::KEY_PPAGE, CDK::FORCHAR => Ncurses::KEY_NPAGE, ' ' => Ncurses::KEY_NPAGE, 'f' => Ncurses::KEY_NPAGE, 'F' => Ncurses::KEY_NPAGE, '|' => Ncurses::KEY_HOME, '$' => Ncurses::KEY_END, } self.setBox(box) box_height = CDK.setWidgetDimension(parent_height, height, 0) box_width = CDK.setWidgetDimension(parent_width, width, 0) # Rejustify the x and y positions if we need to. xtmp = [xplace] ytmp = [yplace] CDK.alignxy(cdkscreen.window, xtmp, ytmp, box_width, box_height) xpos = xtmp[0] ypos = ytmp[0] # Make the viewer window. @win= Ncurses::WINDOW.new(box_height, box_width, ypos, xpos) if @win.nil? self.destroy return nil end # Turn the keypad on for the viewer. @win.keypad(true) # Create the buttons. @button_count = button_count @button = [] @button_len = [] @button_pos = [] if button_count > 0 (0...button_count).each do |x| button_len = [] @button << CDK.char2Chtype(buttons[x], button_len, []) @button_len << button_len[0] button_width += @button_len[x] + 1 end button_adj = (box_width - button_width) / (button_count + 1) button_pos = 1 + button_adj (0...button_count).each do |x| @button_pos << button_pos button_pos += button_adj + @button_len[x] end end # Set the rest of the variables. @screen = cdkscreen @parent = cdkscreen.window @shadow_win = nil @button_highlight = button_highlight @box_height = box_height @box_width = box_width - 2 @view_size = height - 2 @input_window = @win @shadow = shadow @current_button = 0 @current_top = 0 @length = 0 @left_char = 0 @max_left_char = 0 @max_top_line = 0 @characters = 0 @list_size = -1 @show_line_info = 1 @exit_type = :EARLY_EXIT # Do we need to create a shadow? if shadow @shadow_win = Ncurses::WINDOW.new(box_height, box_width + 1, ypos + 1, xpos + 1) if @shadow_win.nil? self.destroy return nil end end # Setup the key bindings. bindings.each do |from, to| self.bind(:VIEWER, from, :getc, to) end cdkscreen.register(:VIEWER, self) end # This function sets various attributes of the widget. def set(title, list, list_size, button_highlight, attr_interp, show_line_info, box) self.setTitle(title) self.setHighlight(button_highlight) self.setInfoLine(show_line_info) self.setBox(box) return self.setInfo(list, list_size, attr_interp) end # This sets the title of the viewer. (A nil title is allowed. # It just means that the viewer will not have a title when drawn.) def setTitle(title) super(title, -(@box_width + 1)) @title_adj = @title_lines # Need to set @view_size @view_size = @box_height - (@title_lines + 1) - 2 end def getTitle return @title end def setupLine(interpret, list, x) # Did they ask for attribute interpretation? if interpret list_len = [] list_pos = [] @list[x] = CDK.char2Chtype(list, list_len, list_pos) @list_len[x] = list_len[0] @list_pos[x] = CDK.justifyString(@box_width, @list_len[x], list_pos[0]) else # We must convert tabs and other nonprinting characters. The curses # library normally does this, but we are bypassing it by writing # chtypes directly. t = '' len = 0 (0...list.size).each do |y| if list[y] == "\t".ord begin t << ' ' len += 1 end while (len & 7) != 0 elsif CDK.CharOf(list[y].ord).match(/^[[:print:]]$/) t << CDK.CharOf(list[y].ord) len += 1 else t << Ncurses.unctrl(list[y].ord) len += 1 end end @list[x] = t @list_len[x] = t.size @list_pos[x] = 0 end @widest_line = [@widest_line, @list_len[x]].max end def freeLine(x) if x < @list_size @list[x] = '' end end # This function sets the contents of the viewer. def setInfo(list, list_size, interpret) current_line = 0 viewer_size = list_size if list_size < 0 list_size = list.size end # Compute the size of the resulting display viewer_size = list_size if list.size > 0 && interpret (0...list_size).each do |x| filename = '' if CDK.checkForLink(list[x], filename) == 1 file_contents = [] file_len = CDK.readFile(filename, file_contents) if file_len >= 0 viewer_size += (file_len - 1) end end end end # Clean out the old viewer info. (if there is any) @in_progress = true self.clean self.createList(viewer_size) # Keep some semi-permanent info @interpret = interpret # Copy the information given. current_line = 0 x = 0 while x < list_size && current_line < viewer_size if list[x].size == 0 @list[current_line] = '' @list_len[current_line] = 0 @list_pos[current_line] = 0 current_line += 1 else # Check if we have a file link in this line. filename = [] if CDK.checkForLink(list[x], filename) == 1 # We have a link, open the file. file_contents = [] file_len = 0 # Open the file and put it into the viewer file_len = CDK.readFile(filename, file_contents) if file_len == -1 fopen_fmt = if Ncurses.has_colors? then '<C></16>Link Failed: Could not open the file %s' else '<C></K>Link Failed: Could not open the file %s' end temp = fopen_fmt % filename self.setupLine(true, temp, current_line) current_line += 1 else # For each line read, copy it into the viewer. file_len = [file_len, viewer_size - current_line].min (0...file_len).each do |file_line| if current_line >= viewer_size break end self.setupLine(false, file_contents[file_line], current_line) @characters += @list_len[current_line] current_line += 1 end end elsif current_line < viewer_size self.setupLine(@interpret, list[x], current_line) @characters += @list_len[current_line] current_line += 1 end end x+= 1 end # Determine how many characters we can shift to the right before # all the items have been viewer off the screen. if @widest_line > @box_width @max_left_char = (@widest_line - @box_width) + 1 else @max_left_char = 0 end # Set up the needed vars for the viewer list. @in_progress = false @list_size = viewer_size if @list_size <= @view_size @max_top_line = 0 else @max_top_line = @list_size - 1 end return @list_size end def getInfo(size) size << @list_size return @list end # This function sets the highlight type of the buttons. def setHighlight(button_highlight) @button_highlight = button_highlight end def getHighlight return @button_highlight end # This sets whether or not you wnat to set the viewer info line. def setInfoLine(show_line_info) @show_line_info = show_line_info end def getInfoLine return @show_line_info end # This removes all the lines inside the scrolling window. def clean # Clean up the memory used... (0...@list_size).each do |x| self.freeLine(x) end # Reset some variables. @list_size = 0 @max_left_char = 0 @widest_line = 0 @current_top = 0 @max_top_line = 0 # Redraw the window. self.draw(@box) end def PatternNotFound(pattern) temp_info = [ "</U/5>Pattern '%s' not found.<!U!5>" % pattern, ] self.popUpLabel(temp_info) end # This function actually controls the viewer... def activate(actions) refresh = false # Create the information about the file stats. file_info = [ '</5> </U>File Statistics<!U> <!5>', '</5> <!5>', '</5/R>Character Count:<!R> %-4d <!5>' % @characters, '</5/R>Line Count :<!R> %-4d <!5>' % @list_size, '</5> <!5>', '<C></5>Press Any Key To Continue.<!5>' ] temp_info = ['<C></5>Press Any Key To Continue.<!5>'] # Set the current button. @current_button = 0 # Draw the widget list. self.draw(@box) # Do this until KEY_ENTER is hit. while true # Reset the refresh flag. refresh = false input = self.getch([]) if !self.checkBind(:VIEWER, input) case input when CDK::KEY_TAB if @button_count > 1 if @current_button == @button_count - 1 @current_button = 0 else @current_button += 1 end # Redraw the buttons. self.drawButtons end when CDK::PREV if @button_count > 1 if @current_button == 0 @current_button = @button_count - 1 else @current_button -= 1 end # Redraw the buttons. self.drawButtons end when Ncurses::KEY_UP if @current_top > 0 @current_top -= 1 refresh = true else CDK.Beep end when Ncurses::KEY_DOWN if @current_top < @max_top_line @current_top += 1 refresh = true else CDK.Beep end when Ncurses::KEY_RIGHT if @left_char < @max_left_char @left_char += 1 refresh = true else CDK.Beep end when Ncurses::KEY_LEFT if @left_char > 0 @left_char -= 1 refresh = true else CDK.Beep end when Ncurses::KEY_PPAGE if @current_top > 0 if @current_top - (@view_size - 1) > 0 @current_top = @current_top - (@view_size - 1) else @current_top = 0 end refresh = true else CDK.Beep end when Ncurses::KEY_NPAGE if @current_top < @max_top_line if @current_top + @view_size < @max_top_line @current_top = @current_top + (@view_size - 1) else @current_top = @max_top_line end refresh = true else CDK.Beep end when Ncurses::KEY_HOME @left_char = 0 refresh = true when Ncurses::KEY_END @left_char = @max_left_char refresh = true when 'g'.ord, '1'.ord, '<'.ord @current_top = 0 refresh = true when 'G'.ord, '>'.ord @current_top = @max_top_line refresh = true when 'L'.ord x = (@list_size + @current_top) / 2 if x < @max_top_line @current_top = x refresh = true else CDK.Beep end when 'l'.ord x = @current_top / 2 if x >= 0 @current_top = x refresh = true else CDK.Beep end when '?'.ord @search_direction = CDK::VIEWER::UP self.getAndStorePattern(@screen) if !self.searchForWord(@search_pattern, @search_direction) self.PatternNotFound(@search_pattern) end refresh = true when '/'.ord @search_direction = CDK::VIEWER:DOWN self.getAndStorePattern(@screen) if !self.searchForWord(@search_pattern, @search_direction) self.PatternNotFound(@search_pattern) end refresh = true when 'N'.ord, 'n'.ord if @search_pattern == '' temp_info[0] = '</5>There is no pattern in the buffer.<!5>' self.popUpLabel(temp_info) elsif !self.searchForWord(@search_pattern, if input == 'n'.ord then @search_direction else 1 - @search_direction end) self.PatternNotFound(@search_pattern) end refresh = true when ':'.ord @current_top = self.jumpToLine refresh = true when 'i'.ord, 's'.ord, 'S'.ord self.popUpLabel(file_info) refresh = true when CDK::KEY_ESC self.setExitType(input) return -1 when Ncurses::ERR self.setExitType(input) return -1 when Ncurses::KEY_ENTER, CDK::KEY_RETURN self.setExitType(input) return @current_button when CDK::REFRESH @screen.erase @screen.refresh else CDK.Beep end end # Do we need to redraw the screen? if refresh self.drawInfo end end end # This searches the document looking for the given word. def getAndStorePattern(screen) temp = '' # Check the direction. if @search_direction == CDK::VIEWER::UP temp = '</5>Search Up : <!5>' else temp = '</5>Search Down: <!5>' end # Pop up the entry field. get_pattern = CDK::ENTRY.new(screen, CDK::CENTER, CDK::CENTER, '', label, Ncurses.COLOR_PAIR(5) | Ncurses::A_BOLD, '.' | Ncurses.COLOR_PAIR(5) | Ncurses::A_BOLD, :MIXED, 10, 0, 256, true, false) # Is there an old search pattern? if @search_pattern.size != 0 get_pattern.set(@search_pattern, get_pattern.min, get_pattern.max, get_pattern.box) end # Activate this baby. list = get_pattern.activate([]) # Save teh list. if list.size != 0 @search_pattern = list end # Clean up. get_pattern.destroy end # This searches for a line containing the word and realigns the value on # the screen. def searchForWord(pattern, direction) found = false # If the pattern is empty then return. if pattern.size != 0 if direction == CDK::VIEWER::DOWN # Start looking from 'here' down. x = @current_top + 1 while !found && x < @list_size pos = 0 y = 0 while y < @list[x].size plain_char = CDK.CharOf(@list[x][y]) pos += 1 if @CDK.CharOf(pattern[pos-1]) != plain_char y -= (pos - 1) pos = 0 elsif pos == pattern.size @current_top = [x, @max_top_line].min @left_char = if y < @box_width then 0 else @max_left_char end found = true break end y += 1 end x += 1 end else # Start looking from 'here' up. x = @current_top - 1 while ! found && x >= 0 y = 0 pos = 0 while y < @list[x].size plain_char = CDK.CharOf(@list[x][y]) pos += 1 if CDK.CharOf(pattern[pos-1]) != plain_char y -= (pos - 1) pos = 0 elsif pos == pattern.size @current_top = x @left_char = if y < @box_width then 0 else @max_left_char end found = true break end end end end end return found end # This allows us to 'jump' to a given line in the file. def jumpToLine newline = CDK::SCALE.new(@screen, CDK::CENTER, CDK::CENTER, '<C>Jump To Line', '</5>Line :', Ncurses::A_BOLD, @list_size.size + 1, @current_top + 1, 0, @max_top_line + 1, 1, 10, true, true) line = newline.activate([]) newline.destroy return line - 1 end # This pops a little message up on the screen. def popUpLabel(mesg) # Set up variables. label = CDK::LABEL.new(@screen, CDK::CENTER, CDK::CENTER, mesg, mesg.size, true, false) # Draw the label and wait. label.draw(true) label.getch([]) # Clean up. label.destroy end # This moves the viewer field to the given location. # Inherited # def move(xplace, yplace, relative, refresh_flag) # end # This function draws the viewer widget. def draw(box) # Do we need to draw in the shadow? unless @shadow_win.nil? Draw.drawShadow(@shadow_win) end # Box it if it was asked for. if box Draw.drawObjBox(@win, self) @win.wrefresh end # Draw the info in the viewer. self.drawInfo end # This redraws the viewer buttons. def drawButtons # No buttons, no drawing if @button_count == 0 return end # Redraw the buttons. (0...@button_count).each do |x| Draw.writeChtype(@win, @button_pos[x], @box_height - 2, @button[x], CDK::HORIZONTAL, 0, @button_len[x]) end # Highlight the current button. (0...@button_len[@current_button]).each do |x| # Strip the character of any extra attributes. character = CDK.CharOf(@button[@current_button][x]) # Add the character into the window. @win.mvwaddch(@box_height - 2, @button_pos[@current_button] + x, character.ord | @button_highlight) end # Refresh the window. @win.wrefresh end # This sets the background attribute of the widget. def setBKattr(attrib) @win.wbkgd(attrib) end def destroyInfo @list = [] @list_pos = [] @list_len = [] end # This function destroys the viewer widget. def destroy self.destroyInfo self.cleanTitle # Clean up the windows. CDK.deleteCursesWindow(@shadow_win) CDK.deleteCursesWindow(@win) # Clean the key bindings. self.cleanBindings(:VIEWER) # Unregister this object. CDK::SCREEN.unregister(:VIEWER, self) end # This function erases the viewer widget from the screen. def erase if self.validCDKObject CDK.eraseCursesWindow(@win) CDK.eraseCursesWindow(@shadow_win) end end # This draws the viewer info lines. def drawInfo temp = '' line_adjust = false # Clear the window. @win.werase self.drawTitle(@win) # Draw in the current line at the top. if @show_line_info == true # Set up the info line and draw it. if @in_progress temp = 'processing...' elsif @list_size != 0 temp = '%d/%d %2.0f%%' % [@current_top + 1, @list_size, ((1.0 * @current_top + 1) / (@list_size)) * 100] else temp = '%d/%d %2.0f%%' % [0, 0, 0.0] end # The list_adjust variable tells us if we have to shift down one line # because the person asked for the line X of Y line at the top of the # screen. We only want to set this to true if they asked for the info # line and there is no title or if the two items overlap. if @title_lines == '' || @title_pos[0] < temp.size + 2 list_adjust = true end Draw.writeChar(@win, 1, if list_adjust then @title_lines else 0 end + 1, temp, CDK::HORIZONTAL, 0, temp.size) end # Determine the last line to draw. last_line = [@list_size, @view_size].min last_line -= if list_adjust then 1 else 0 end # Redraw the list. (0...last_line).each do |x| if @current_top + x < @list_size screen_pos = @list_pos[@current_top + x] + 1 - @left_char Draw.writeChtype(@win, if screen_pos >= 0 then screen_pos else 1 end, x + @title_lines + if list_adjust then 1 else 0 end + 1, @list[x + @current_top], CDK::HORIZONTAL, if screen_pos >= 0 then 0 else @left_char - @list_pos[@current_top + x] end, @list_len[x + @current_top]) end end # Box it if we have to. if @box Draw.drawObjBox(@win, self) @win.wrefresh end # Draw the separation line. if @button_count > 0 boxattr = @BXAttr (1..@box_width).each do |x| @win.mvwaddch(@box_height - 3, x, @HZChar | boxattr) end @win.mvwaddch(@box_height - 3, 0, Ncurses::ACS_LTEE | boxattr) @win.mvwaddch(@box_height - 3, @win.getmaxx - 1, Ncurses::ACS_RTEE | boxattr) end # Draw the buttons. This will call refresh on the viewer win. self.drawButtons end # The list_size may be negative, to assign no definite limit. def createList(list_size) status = false self.destroyInfo if list_size >= 0 status = true @list = [] @list_pos = [] @list_len = [] end return status end def position super(@win) end def object_type :VIEWER end end end
true
0fc6ded8ddd3f3f9670fdcaad520f9cdcf200f19
Ruby
gipsh/miradetodo-scrapper
/test.rb
UTF-8
284
2.9375
3
[]
no_license
require 'base64' s = "aHR0c!ArEovL29rLnJ1L3ZpZGVvLzE2MTg5O!ArEExNjE1N!ArEUN" puts "original string [#{s}]" t = s.split("!Ar") for i in 1..t.size-1 puts "#{i}. #{t[i]}" t[i][0] = (t[i][0].ord - 1).chr end puts t.join puts "Download link is: #{Base64.decode64(t.join)}"
true
c0a23b036385512ab6b68a93c16dc9749267012f
Ruby
edwardloveall/bestiary
/lib/bestiary/parsers/space.rb
UTF-8
626
2.875
3
[ "LicenseRef-scancode-ogl-1.0a", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class Bestiary::Parsers::Space attr_accessor :creature def self.perform(creature) new(creature).perform end def initialize(creature) @creature = creature end def perform return if parent_element.nil? text = parent_element.text feet(text) end def parent_element @parent ||= begin creature.css('p').find do |stat| text = stat.text break if text.strip.match(/STATISTICS/) text.match(/\ASpace/i) end end end def feet(text) space = text.split(/[;,]/).first space.sub('-1/2', '.5') .sub('Space ', '') .to_f end end
true
fe771b759dbe19773078070f05fd0225501b79b0
Ruby
ChenWeiLee/CWSVM
/pattern.rb
UTF-8
914
3.203125
3
[ "MIT" ]
permissive
require './kernels' class Pattern attr_accessor :features # 數據特徵值 attr_accessor :expectation # 期望輸出值 attr_accessor :alpha def initialize(data_features, expectation_target, alpha_value = 0) @features = data_features.to_a # Why needs to_a ? @expectation = expectation_target.to_f @alpha = alpha_value.to_f @kernel = Kernels.new() end #bais 為目前此SVM的Bais #all_points是一個裝Pattern型態的Array #kernel要傳入Kernel class 來做kernel的計算 def error(bais = 0.0, all_points, kernel_type ) @kernel.kernel_method = kernel_type error_value = 0.0 all_points.each{ |pattern| error_value += (pattern.expectation * pattern.alpha * @kernel.run_with_data(pattern.features, @features)) } error_value += bais - expectation end def update_alpha(new_alpha) @alpha = new_alpha.to_f end end
true
a72074a779f469a4d40930fc6515644e6b488eb1
Ruby
aravindh-browserstack/greed.dice.game
/game.rb
UTF-8
3,877
3.578125
4
[]
no_license
require './player' include Player require './diceset' include DiceSet module Game class GameClass def initialize(num_players) raise ArgumentError unless num_players > 1 @players = [] @player_score = {} @dice = Dice.new count = 1 num_players.times { p = PlayerClass.new(count,@dice) @players << p @player_score[p] = 0 count += 1 } end def score v = @dice.values v.sort! current_score = 0 i = 0 while i < v.length if v[i] == v[i+1] && v[i+1] == v[i+2] if v[i] == 1 current_score += 1000 else current_score += (v[i]*100) end i += 3 else if v[i] == 1 current_score += 100 elsif v[i] == 5 current_score += 50 end i += 1 end end current_score end def take_input_to_play_again(player,cur_num) print "Do you want to roll the non-scoring #{cur_num} dice? (y/n): " choice = gets.chomp.downcase end def get_nonscoring_num count = 0 repeated = [] v = @dice.values.sort i = 0 while i < v.length if v[i] == v[i+1] && v[i+1] == v[i+2] i += 3 elsif (v[i] != 1 && v[i] != 5) i += 1 count += 1 else i += 1 end end count = 5 if count == 0 count end def play_turn(player) player.play(5) sleep 1 # slow down a bit so that user can see what's happening cur_score = score print "#{player.name} rolls: " + @dice.to_s+"\n" print "Score in this round: #{score} \n" print "Total score: #{@player_score[player]}\n" if cur_score != 0 loop do n = get_nonscoring_num choice = take_input_to_play_again(player,n) if choice == 'y' player.play(n) print "#{player.name} rolls: " + @dice.to_s + "\n" new_score = score if new_score == 0 cur_score = 0 print "Score in this round: #{new_score} \n" print "Total score: #{@player_score[player]}\n" break end cur_score += new_score print "Score in this round: #{new_score} \n" print "Total score: #{@player_score[player]}\n" else # Anything else resorts to No if (@player_score[player] >= 300 || cur_score >=300) @player_score[player] += cur_score end break end end end end def final_round? @player_score.each_value { |x| return true if x >= 3000 } return false end def get_winner m = -1 winner = nil @player_score.each { |k,v| if m < v m = v winner = k end } winner end def print_scores print "############################################################\n" @player_score.each { |k,v| puts "#{k.name}'s score at the end of this round is .. #{v}" } print "############################################################\n" end def play turn = 1 loop do print "Turn #{turn}\n" print "------------\n" @players.each { |x| play_turn(x) print "\n" } turn += 1 break if final_round? end # get one more turn for others & compute final score print "Final round\n" print "-----------\n" @players. each { |x| if @player_score[x] < 3000 play_turn(x) end } winner = get_winner print "winner is #{winner.name} .. score is " + @player_score[winner].to_s + "\n" end end end
true
ce02748bdbf411f41653c85d55b2aac26c60f4cd
Ruby
JakeMKelly/phase-0-tracks
/ruby/santa.rb
UTF-8
1,766
3.53125
4
[]
no_license
class Santa attr_reader :ethnicity, :age attr_accessor :gender def initialize(gender, ethnicity) puts "Initializing Santa instance..." @gender = gender @ethnicity = ethnicity end def gender_ethnicity(gender, ethnicity) puts "#{@gender}, #{@ethnicity}" end def speak puts "Ho, ho, ho! Haaaappy holidays!" end def eat_milk_and_cookies(cookie_type) puts "That was a good #{cookie_type}!" end def reindeer_ranker @reindeer_ranking = ["Rudolph", "Dasher", "Dancer", "Prancer", "Vixen", "Comet", "Cupid", "Donner", "Blitzen"] end def current_age(age = 0) @age = age end def celebrate_birthday @age = @age + 1 end def get_mad_at(bad_reindeer) @reindeer_ranking.delete(bad_reindeer) @reindeer_ranking.push(bad_reindeer) end end # kringle = Santa.new # kringle.speak # kringle.eat_milk_and_cookies("brookie") santas = [] example_genders = ["agender", "female", "bigender", "male", "female", "gender fluid", "N/A"] example_ethnicities = ["black", "Latino", "white", "Japanese-African", "prefer not to say", "Mystical Creature (unicorn)", "N/A"] while santas.length <= 5 do example_genders.length.times do |i| santas << Santa.new(example_genders[i], example_ethnicities[i]) end end p santas p santas.length santa = Santa.new("female", "white") p santa.ethnicity p santa p santa.current_age santa.current_age(70) p santa.age santa.celebrate_birthday p santa.age santa.reindeer_ranker p santa.reindeer_ranker p santa.get_mad_at("Dancer") santa.gender = "male" puts "Santa is a #{santa.ethnicity} #{santa.gender} ." 10000.times do p Santa.new(example_genders.sample, example_ethnicities.sample) p santa.current_age(rand(140)) end
true
a653be7e37dd7432844c0ebd04fd46ae4bb57934
Ruby
atsubi/oekakinosato
/cgi-bin/decide_answer.rb
UTF-8
171
2.671875
3
[]
no_license
#!/root/.rbenv/shims/ruby # -*- coding: utf-8 -*- player_mun = [ 1, 2, 3, 4 ] p = player_mun.sample puts p fp = File.open("answer.txt", "w") fp.print "#{p}" fp.close
true
0f463e94314a14c94d687d6d184c70200b69475a
Ruby
tblarel/W3D2
/AA_questions/question_like_orm.rb
UTF-8
1,597
2.828125
3
[]
no_license
require_relative 'users_orm' require_relative 'questions_orm' class QuestionLike attr_accessor :user_id, :question_id def self.all data = QuestionsDatabase.instance.execute ("SELECT * FROM question_likes") data.map { |datum| QuestionLike.new(datum) } end def self.likers_for_question_id(search_question_id) data = QuestionsDatabase.instance.execute <<-SQL, search_question_id SELECT users.* FROM question_likes JOIN users on question_likes.user_id = users.id WHERE question_likes.question_id = ? SQL data.map { |datum| User.new(datum) } end def self.num_likes_for_question_id(search_question_id) data = QuestionsDatabase.instance.execute <<-SQL, search_question_id SELECT questions.*, COUNT(question_likes.user_id) AS num_likes FROM question_likes JOIN questions ON questions.id = question_likes.question_id WHERE question_likes.question_id = ? GROUP BY question_likes.question_id SQL data.map { |datum| [ Question.new(datum), datum["num_likes"] ] } end def self.most_liked_questions(n) data = QuestionsDatabase.instance.execute <<-SQL, n SELECT COUNT(user_id) AS num_likes FROM question_likes GROUP BY question_id ORDER BY count(user_id) DESC LIMIT ? SQL data end def initialize(options) @user_id = options["user_id"] @question_id = options["question_id"] end def self.liked_questions_for_user_id(user_id) end end
true
f50d1f723ad11a5380e7d409806381f1d442acc6
Ruby
Frosty21/w6d1
/math-game/round.rb
UTF-8
1,347
4.09375
4
[]
no_license
# starts the round with Player1 as player to starts # <TODO> set initialize current_player as a puts choice option question class Round def initialize(player1, player2) @player1 = player1 @player2 = player2 @current_player = @player1 end # sets number1 and number2 for each player between 1-20 # random number the uses p to display the text in array # format def question @number1 = rand(1..20) @number2 = rand(1..20) @answer = @number1 + @number2 puts '--------- New Round-----------' p "OK #{@current_player.name}, what is #{@number1} plus #{@number2}?" end # checks to see if answer matches if not take 1 life from # current_player def answer input = gets.chomp.to_i if input == @answer puts 'Correct' else puts "Incorrect, expected #{@answer}" @current_player.lives -= 1 end end # gives the player1 and player2 lives score def score puts '<<<<<<<<<<<SCORE>>>>>>>>>>>' p "Player1 #{@player1.lives}/3 VS Player2 #{@player2.lives}/3" end # switches current_player from either Player1 or Player2 # depending on current_player def switch_players @current_player = @current_player == @player1 ? @player2 : @player1 end # order with the game is executed def order question answer switch_players score end end
true
0d6edd63fffbec9bf2bfcee55c95c2a278ce0f55
Ruby
terra-yucco/ruthenium
/test/controllers/recipe_controller_test.rb
UTF-8
1,864
2.578125
3
[ "MIT" ]
permissive
require 'test_helper' class RecipeControllerTest < ActionController::TestCase # 楽天APIを利用してピックアップレシピが取得できる test "should get pickup via rakuten api" do get :pickup assert_response :success assert_not_nil assigns(:menu) assert_not_nil assigns(:materials) end # カテゴリーを指定してレシピを取得できる test "should get pickup by category" do # サラダカテゴリ get :pickup, :category => '18' assert_response :success assert_not_nil assigns(:menu) assert_not_nil assigns(:materials) end # 野菜登録画面を表示できる test "should show add_vegetables" do get :add_vegetables assert_response :success end # 野菜登録ページでのCookie保存 test "should save veg numbers" do # 登録(にんじん 2個、玉ねぎ 3個) post :regist_vegetables, :carrot => '2', :onion => '3' assert_response :redirect assert_equal '2', response.cookies['veg_carrot'] assert_equal '3', response.cookies['veg_onion'] end # 材料の数量を取得できる # @todo 楽天レシピのページ形式と、掲載先レシピの内容に依存している # http://recipe.rakuten.co.jp/recipe/1490006283/ test "should get material amount" do get :scrape assert_response :success result = assigns(:materials) assert_not_nil result assert (0 < result.length) # 材料がないということはないはず assert_not_nil result.first[0]['materialName'] assert_not_nil result.first[0]['materialAmount'] end # 買ったものの Cookie保存のテスト追加 test "should save cookie" do get :pickup assert_response :success # 1つ目の項目をチェック get :bought, :material0 => 'on' assert_not_nil response.cookies['bought_list'] end end
true
dbe50364dc16d3d35d9c39c1443c3c6a09ce260e
Ruby
haugenc/oo-kickstarter-v-000
/lib/project.rb
UTF-8
311
3.015625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Project attr_accessor :title, :backers def initialize(title) @title = title @backers = [] end #///CLASS METHODS ///# #///INSTANCE METHODS ///# def add_backer(backer) @backers << backer backer.back_project(self) if backer.backed_projects.all? {|test| test != self} end end
true
4c50d688af41b414cc8ecf2f7e74a64b13040ea0
Ruby
LesnyRumcajs/advent-of-ruby-2019
/src/day9.rb
UTF-8
344
2.984375
3
[ "MIT" ]
permissive
require_relative 'components/intcodeparser' intcode = File.read('res/day9.txt').split(',').map(&:to_i) # part 1 computer = IntCodeParser.new(intcode.clone) computer.calculate [1] until computer.finished? p computer.output # part 2 computer = IntCodeParser.new(intcode.clone) computer.calculate [2] until computer.finished? p computer.output
true
165adb22d734a24c02cb33be2b7ec0e628c03436
Ruby
dvguruprasad/movie_rec
/app/models/recommender.rb
UTF-8
1,121
3.0625
3
[]
no_license
class Recommender def self.recommend(user) similar_users = Similarity.similar_to(user) weighted_rating_sums = weighted_rating_sums(similar_users, user) final_movie_ratings = {} weighted_rating_sums.each do |movie_id, weighted_rating| final_movie_ratings[movie_id] = weighted_rating / similarity_score_sum(similar_users, movie_id) end result = final_movie_ratings.sort_by{|movie_id, rating| rating}.reverse result.collect{|m| Movie.find m.first} end private def self.weighted_rating_sums(similar_users, user) weighted_rating_sums = {} similar_users.each do |similar_user| similar_user[:user].ratings.collect do |rating| next if user.has_rated rating.movie_id weighted_rating_sums[rating.movie_id] ||= 0 weighted_rating_sums[rating.movie_id] += rating.value * similar_user[:score] end end weighted_rating_sums end def self.similarity_score_sum(similar_users, movie_id) similar_users.inject(0) do |sum, similar_user| sum += (similar_user[:user].has_rated(movie_id)) ? similar_user[:score] : 0 end end end
true
0c3dd3733734a4c7bd64fe2b63a5afe0cdc39605
Ruby
pimenvibritania/ChatRoom
/alphabet.rb
UTF-8
1,442
3.734375
4
[ "MIT" ]
permissive
#!/usr/bin/env ruby # alphabet.rb # # this module grabs alphabet letters from the alphabet.yml file and allows # you to print them out or builds and returns a hash map of their data. require 'yaml' module Alphabet YAML_FILE = File.dirname(__FILE__) + '/alphabet.yml' DOCUMENT = YAML.load_file(YAML_FILE) def self.print_letter(letter) curr = DOCUMENT[letter] width = curr[0]['width'] height = curr[1]['height'] chars = curr[2]['chars'] (1..height).each do |n| puts chars[(n-1)*width,width] end puts chars end def self.get_letter_chars(letter) curr = DOCUMENT[letter] width = curr[0]['width'] height = curr[1]['height'] chars = curr[2]['chars'] return chars end def self.get_chronological_letter_chars(letter) curr = DOCUMENT[letter] width = curr[0]['width'] height = curr[1]['height'] chars = curr[2]['chars'] chrono_chars = '' width.times do |m| height.times do |n| chrono_chars += chars[(m + (n*7)), 1] end end return chrono_chars end def self.letter_to_hash(letter) curr = DOCUMENT[letter] width = curr[0]['width'] height = curr[1]['height'] chars = curr[2]['chars'] char_map = Hash.new (1..width).each do |n| (1..height).each do |m| pos = (n-1) + (m-1)*width char = chars[pos] char_map[[n-1,m-1]] = char end end return char_map end end
true
6034a8e2d658d40f0417e79e2ebd536032bfc509
Ruby
microformats/microformats-ruby
/lib/microformats/time_property_parser.rb
UTF-8
7,411
2.515625
3
[ "CC0-1.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
module Microformats class TimePropertyParser < ParserCore def parse(element, base: nil, element_type:, format_class_array: [], backcompat: nil) @base = base @duration_value = nil @date_value = nil @time_value = nil @tz_value = nil @property_type = element_type @fmt_classes = format_class_array @mode_backcompat = backcompat parse_value_class_pattern(element) if @duration_value.nil? && @time_value.nil? && @date_value.nil? && @tz_value.nil? value = if %w[time ins del].include?(element.name) && !element.attribute('datetime').nil? element.attribute('datetime').value.strip elsif element.name == 'abbr' && !element.attribute('title').nil? element.attribute('title').value.strip elsif (element.name == 'data' || element.name == 'input') && !element.attribute('value').nil? element.attribute('value').value.strip else element.text.strip end parse_dt(value) end if !@duration_value.nil? @duration_value else result = nil result = result.to_s + @date_value unless @date_value.nil? unless @time_value.nil? result = result.to_s + ' ' unless result.nil? result = result.to_s + @time_value end result = result.to_s + @tz_value unless @tz_value.nil? result end end def parse_value_class_pattern(element) parse_node(element.children) end def parse_element(element) if @duration_value.nil? || (@time_value.nil? && @date_value.nil? && @tz_value.nil?) if value_title_classes(element).length >= 1 value = element.attribute('title').value.strip elsif value_classes(element).length >= 1 value = if element.name == 'img' || element.name == 'area' && !element.attribute('alt').nil? element.attribute('alt').value.strip elsif element.name == 'data' && !element.attribute('value').nil? element.attribute('value').value.strip elsif element.name == 'abbr' && !element.attribute('title').nil? element.attribute('title').value.strip elsif %w[time ins del].include?(element.name) && !element.attribute('datetime').nil? element.attribute('datetime').value.strip else element.text.strip end end parse_dt(value, normalize: true) p_classes = property_classes(element) p_classes = backcompat_property_classes(element) if @mode_backcompat if p_classes.empty? && format_classes(element).empty? parse_node(element.children) end end end def parse_dt(data, normalize: false) # currently the value-class-pattern page lists to normalize and remove :'s but not regular parsing, seems very odd # https://github.com/microformats/tests/issues/29 # # TODO: this still allows a lot of non correct values such as 39th day of the month, etc case data.strip when /^P\d*W$/ @duration_value = data if @duration_value.nil? when /^P(\d+Y)?(\d+M)?(\d+D)?(T(\d+H)?(\d+M)?(\d+S)?)?$/ @duration_value = data if @duration_value.nil? when /^(\d{4}-[01]\d-[0-3]\d)[tT ]([0-2]\d:[0-5]\d(:[0-5]\d)?)?([zZ]|[-+][01]?\d:?[0-5]\d)?$/ @date_value = Regexp.last_match(1) if @date_value.nil? @time_value = Regexp.last_match(2) if @time_value.nil? @tz_value = Regexp.last_match(4).tr('z', 'Z') if @tz_value.nil? when /^(\d{4}-[01]\d-[0-3]\d)[tT ]([0-2]\d:[0-5]\d(:[0-5]\d)?)( ?[-+]\d\d:?(\d\d)?)$/ @date_value = Regexp.last_match(1) if @date_value.nil? @time_value = Regexp.last_match(2) if @time_value.nil? if normalize @tz_value = Regexp.last_match(4).tr('z', 'Z').delete(':') if @tz_value.nil? else @tz_value = Regexp.last_match(4).tr('z', 'Z') if @tz_value.nil? end when /^(\d{4}-[0-3]\d\d)[tT ]([0-2]\d:[0-5]\d(:[0-5]\d)?)?([zZ]|[-+][01]?\d:?[0-5]\d)?$/ @date_value = Regexp.last_match(1) if @date_value.nil? @time_value = Regexp.last_match(2) if @time_value.nil? @tz_value = Regexp.last_match(4).tr('z', 'Z') if @tz_value.nil? when /^(\d{4}-[0-3]\d\d)[tT ]([0-2]\d:[0-5]\d(:[0-5]\d)?)( ?[-+]\d\d:?(\d\d)?)$/ @date_value = Regexp.last_match(1) if @date_value.nil? @time_value = Regexp.last_match(2) if @time_value.nil? if normalize @tz_value = Regexp.last_match(4).tr('z', 'Z').delete(':') if @tz_value.nil? else @tz_value = Regexp.last_match(4).tr('z', 'Z') if @tz_value.nil? end when /^(\d{4})-([01]?\d)-([0-3]?\d)$/ @date_value = DateTime.new(Regexp.last_match(1).to_i, Regexp.last_match(2).to_i, Regexp.last_match(3).to_i).strftime('%F') if @date_value.nil? when /^(\d{4})-([0-3]\d{2})$/ @date_value = data if @date_value.nil? when /^(\d{4})-([01]?\d)$/ @date_value = data if @date_value.nil? when /^([zZ]|[-+][01]?\d:?[0-5]\d)$/ if normalize @tz_value = Regexp.last_match(1).tr('z', 'Z').delete(':') if @tz_value.nil? else @tz_value = Regexp.last_match(1).tr('z', 'Z') if @tz_value.nil? end when /^([0-2]\d:[0-5]\d(:[0-5]\d)?)([zZ]|[-+][01]\d:?\d\d)?$/ @time_value = Regexp.last_match(1) if @time_value.nil? if normalize @tz_value = Regexp.last_match(3).tr('z', 'Z').delete(':') if @tz_value.nil? else @tz_value = Regexp.last_match(3).tr('z', 'Z') if @tz_value.nil? end when /^[0-2]\d:[0-5]\d[zZ]?$/ @time_value = Time.parse(data).strftime('%H:%M') if @time_value.nil? @tz_value = 'Z' when /^([0-2]\d:[0-5]\d:[0-5]\d)([-+][01]\d:?[0-5]\d)$/ Time.parse(data).strftime('%T') # to make sure this time doesn't throw an error @time_value = Regexp.last_match(1) if @time_value.nil? @tz_value = Regexp.last_match(2) if @tz_value.nil? when /^([0-2][0-0]:[0-5]\d)([-+][01]\d:?[0-5]\d)$/ Time.parse(data).strftime('%H:%M') # to make sure this time doesn't throw an error @time_value = Regexp.last_match(1) if @time_value.nil? @tz_value = Regexp.last_match(2) if @tz_value.nil? when /^([01]?\d):?([0-5]\d)?p\.?m\.?$/i @time_value = (Regexp.last_match(1).to_i + 12).to_s + ':' + Regexp.last_match(2).to_s.rjust(2, '0') if @time_value.nil? when /^([01]?\d):?([0-5]\d)?a\.?m\.?$/i @time_value = Regexp.last_match(1).to_s.rjust(2, '0') + ':' + Regexp.last_match(2).to_s.rjust(2, '0') if @time_value.nil? when /^([01]?\d):([0-5]\d):([0-5]\d)?p\.?m\.?$/i @time_value = (Regexp.last_match(1).to_i + 12).to_s + ':' + Regexp.last_match(2).to_s.rjust(2, '0') + ':' + Regexp.last_match(3).to_s.rjust(2, '0') if @time_value.nil? when /^([01]?\d):([0-5]\d):([0-5]\d)?a\.?m\.?$/i @time_value = Regexp.last_match(1).to_s.rjust(2, '0') + ':' + Regexp.last_match(2).to_s.rjust(2, '0') + ':' + Regexp.last_match(3).to_s.rjust(2, '0') if @time_value.nil? else t = Time.parse(data) @time_value = t.strftime('%T') if @time_value.nil? @date_value = t.strftime('%F') if @date_value.nil? end rescue nil end end end
true
85ee7ff22c3df51879cfc30ab7224b708cb21440
Ruby
somenugget/dry-stuff
/app/async_monads.rb
UTF-8
1,110
2.9375
3
[]
no_license
require 'benchmark' require 'dry/monads/task' require './lib/blog/get' class GetPhotoaAndAlbums include Dry::Monads::Task::Mixin def call # Start two tasks running concurrently albums = Task { fetch_albums } photos = Task { fetch_photos } # Combine two tasks albums.bind do |albums_result| photos.fmap do |photos_result| [albums_result, photos_result] end end end def fetch_albums Blog::Get.new.call(endpoint: 'albums') end def fetch_photos Blog::Get.new.call(endpoint: 'photos') end end result = Benchmark.measure do albums = Blog::Get.new.call(endpoint: 'albums').value!.map { |a| [a['id'], a] }.to_h photos = Blog::Get.new.call(endpoint: 'photos') photos.value!.each do |photo| # puts "#{albums[photo['albumId']]['title']}: #{photo['url']}" end end puts result result = Benchmark.measure do albums, photos = GetPhotoaAndAlbums.new.call.value! albums = albums.value!.map { |a| [a['id'], a] }.to_h photos.value!.each do |photo| # puts "#{albums[photo['albumId']]['title']}: #{photo['url']}" end end puts result
true
fd9802ea3be381f2c13bfefbaeb489d44b7acd89
Ruby
javkhaanj7/ruby-challenges
/WordCount.rb
UTF-8
449
4.3125
4
[]
no_license
#Using the Ruby language, have the function WordCount(str) take the str string parameter #being passed and return the number of words the string contains (ie. "Never eat shredded wheat" would return 4). #Words will be separated by single spaces. #Correct Sample Outputs: #Input = "Hello World" Output = 2 #Input = "one 22 three" Output = 3 #http://coderbyte.com/ def WordCount(str) words = str.split(" ") return words.length end
true
da33c287cdddd7f03a1710f3c9d83ff62e96c050
Ruby
josephbhunt/GosuShooter
/grid.rb
UTF-8
1,255
3.703125
4
[]
no_license
# This is not functional yet. # The intent of Grid is to brake the screen into a grid of squares. Then images can be assigned to the grid # to create a background image or level environment like walls, etc. # Each square should have a GridTile attached to it. The GridTile contains an image. # This way the grid tiles can be assigned to different parts of the grid. class Grid include GameConstants attr_accessor :tiles, :map def initialize(ordered_images) @tiles = ordered_images.map{|oi| GridTile.new(oi)} @grid_height = WINDOW_HEIGHT / TILE_SIZE + 2 @map = Array.new(WINDOW_WIDTH / TILE_SIZE) {Array.new(WINDOW_HEIGHT / TILE_SIZE + 2)} @map.each_with_index do |row, x| row.each_with_index do |col, y| if y == 0 elsif y > 0 && y < @grid_height - 2 image_x = x * TILE_SIZE image_y = y * TILE_SIZE y_multiplyer = WINDOW_WIDTH / TILE_SIZE grid_tile = @tiles[(y * y_multiplyer + x)] grid_tile.set_grid_location(x, y - TILE_SIZE) grid_tile.set_image_location(image_x, image_y) @map[x][y] = grid_tile else end end end end def draw map.each {|t_row| t_row.each {|t| t.draw unless t.nil? }} end end
true
9c0b69705494994f30779b0098939351f5ab90fb
Ruby
justonemorecommit/puppet
/lib/puppet/pops/types/p_sensitive_type.rb
UTF-8
1,529
2.859375
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
module Puppet::Pops module Types # A Puppet Language type that wraps sensitive information. The sensitive type is parameterized by # the wrapped value type. # # # @api public class PSensitiveType < PTypeWithContainedType class Sensitive def initialize(value) @value = value end def unwrap @value end def to_s "Sensitive [value redacted]" end def inspect "#<#{self}>" end def hash @value.hash end def ==(other) other.is_a?(Sensitive) && other.hash == hash end alias eql? == end def self.register_ptype(loader, ir) create_ptype(loader, ir, 'AnyType') end def initialize(type = nil) @type = type.nil? ? PAnyType.new : type.generalize end def instance?(o, guard = nil) o.is_a?(Sensitive) && @type.instance?(o.unwrap, guard) end def self.new_function(type) @new_function ||= Puppet::Functions.create_loaded_function(:new_Sensitive, type.loader) do dispatch :from_sensitive do param 'Sensitive', :value end dispatch :from_any do param 'Any', :value end def from_any(value) Sensitive.new(value) end # Since the Sensitive value is immutable we can reuse the existing instance instead of making a copy. def from_sensitive(value) value end end end private def _assignable?(o, guard) self.class == o.class && @type.assignable?(o.type, guard) end DEFAULT = PSensitiveType.new end end end
true
2d6b633a0ef897434d16b642c633a7863d8a0047
Ruby
imperio0001/aula-gama
/challenge/game/game.rb
UTF-8
777
3.828125
4
[]
no_license
class Game def iniciar # Introducao e Regras do jogo puts "Luck Game" puts "===============" puts "Sera sorteado um numero,\n sera que você consegue adivinhar?" # Sorteia o númro numero = sortear puts "Numero sorteado!" # Espera o usuário digitar um número puts "Qual numero sera?" chute = gets.to_i # Retorna o resultado resultado = chutar(numero, chute) puts resultado end def sortear # Sorteando numero random entre 1 e 10 n = rand 1..3 # Retorna o numero n end def chutar(numero, chute) # Condicional comparando # chute e numero para ver # se o jogador acertou resultado = if chute == numero "Acertou!!!!" else "ERRRRRRROOOOUUUU!" end end end
true
9337d0d56dc48c10701ca32125d39775f0e1fbc3
Ruby
luckyfishlab/foundry
/lib/foundry/callback.rb
UTF-8
844
2.75
3
[ "MIT" ]
permissive
require 'redis' require 'uuid' require 'json' module Foundry # Callback provides a mechanism to signal that a job # is done class Callback attr_reader :uuid def initialize generator = UUID.new @uuid = generator.generate end # Called by the producer's worker def self.done(redis,id,val) #puts "Callback Signaling done for ID: #{id} VAL: #{val}" r = Redis.new(redis) r.rpush("foundry:callback:#{id}", [val].to_json) #puts redis.lrange("foundry:callback:#{id}",0,-1) end # Used by the processor to sync on a producer def self.wait_for(redis,id) #puts "Callback Waiting for ID: #{id}" r = Redis.new(redis) ret = r.blpop("foundry:callback:#{id}",0) #puts "Callback received #{ret}" JSON.parse(ret[-1])[0] end end end
true
1769730316731ac2dc9105a3bf372fe0c1a7c0a8
Ruby
abrennec/sose20_mc
/code/ruby_language_nutshell/25_errors.rb
UTF-8
850
4.1875
4
[]
no_license
lucky_nums = [4, 8, 15, 16, 23, 24] #lucky_nums["dogs"] begin lucky_nums["dogs"] num = 10 / 0 rescue => exception puts "Errors" # catches any error that gets thrown end # to specify specific error blocks for specific exceptions begin lucky_nums["dogs"] num = 10 / 0 rescue ZeroDivisionError # this is the error message that gets thrown in the case of 10/0 puts "Division by zero error" # catches any error that gets thrown rescue TypeError puts "wrong type" end # store the error that was thrown in a variable begin lucky_nums["dogs"] num = 10 / 0 rescue ZeroDivisionError # this is the error message that gets thrown in the case of 10/0 puts "Division by zero error" # catches any error that gets thrown rescue TypeError => e # this message contains usually specific info on the error puts e end
true
cb31380b4b2d000ef72b11f2622c707c0b21d71c
Ruby
jerryzlau/algorithms
/hackerrank/ransom_note.rb
UTF-8
288
3.359375
3
[]
no_license
def ransom_note(magazine,ransom) m_hash = Hash.new(0) r_hash = Hash.new(0) magazine.each {|word| m_hash[word] += 1} ransom.each {|word| r_hash[word] += 1} flag = 'Yes' r_hash.each do |word, count| if m_hash[word] < count flag = 'No' end end flag end
true
addcffedc9fb2a7068dfd545383420bf5c99a5b0
Ruby
ajLapid718/HackerRank-30-Days-of-Code
/Day-06-Lets_Review.rb
UTF-8
736
4.09375
4
[]
no_license
# Task # Given a string, S, of length N that is indexed from 0 to N-1, print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line (see the Sample below for more detail). # Sample Input: # 2 # Hacker # Rank # Sample Output: # Hce akr # Rn ak amount_of_test_cases = gets.to_i STRINGS = [] OUTPUT = [] amount_of_test_cases.times do |idx| STRINGS << gets.chomp end STRINGS.each do |word| odd_characters = "" even_characters = "" word.length.times do |str_idx| if str_idx.even? even_characters << word[str_idx] else odd_characters << word[str_idx] end end OUTPUT.push(even_characters + " " + odd_characters) end puts OUTPUT
true
cb6dfe8e45dedf39f1e75026adab574c876f0e3d
Ruby
samesystem/social_security_number
/spec/lib/social_security_number/country/dk_spec.rb
UTF-8
1,696
2.6875
3
[ "MIT" ]
permissive
require 'spec_helper' describe SocialSecurityNumber::Dk do subject(:civil_number) { SocialSecurityNumber::Dk.new(number) } describe '#validate' do let(:number) { '1004932990' } context 'when number is valid' do it { is_expected.to be_valid } end context 'when number is valid with divider -' do let(:number) { '100493-2990' } it { is_expected.to be_valid } end context 'when number contains not digits' do let(:number) { '10010A100177' } it { is_expected.not_to be_valid } end end describe '#error' do subject(:error) { civil_number.tap(&:valid?).error } context 'when number contains not digits' do let(:number) { '10049A32990' } it { is_expected.to eq('bad number format') } end context 'when number contains invalid birth date' do let(:number) { '9004932990' } it { is_expected.to eq('number birth date is invalid') } end context 'when number has bad control number' do let(:number) { '311277-0005' } it { is_expected.to eq('control code invalid') } end end describe '#year' do context 'when receive valid value' do context 'when civil number is from 21st century' do let(:number) { '1004022990' } it { expect(civil_number.send(:year)).to eq(2002) } end context 'when civil number is from 20th century' do let(:number) { '1004402990' } it { expect(civil_number.send(:year)).to eq(1940) } end end end describe '#gender' do context 'when receive odd value' do let(:number) { '1004402990' } it { expect(civil_number.send(:gender)).to eq(:female) } end end end
true
f8df3e7f3a50e77058d96e12e48e4bbe96e9536e
Ruby
timchen777/MEANstack2
/README.rb
UTF-8
2,725
2.609375
3
[ "ISC" ]
permissive
================ MEAN stck NTU class 275===================== 1. Register https://mlab.com/home https://www.getpostman.com/ https://developers.facebook.com/ 2. Install Node.js https://nodejs.org/en/ 3 npm: 下載Node.js module或package來擴充app的功能 如: Mongoose Morgan:輸出HTTP request至console body-parser:解析body Express:幫忙建立website 4. Use 'npm install <pkg> --save', save it as a dependency in package.json. ex: install cat-me package https://www.npmjs.com/package/cat-me > npm init > npm install cat-me >>> create app.js under node_modules folder -------- app.js ----------- var cat = require('cat-me'); console.log(cat()); ---------------------------- > MEANstack\node_modules\cat-me> node app.js >> see Cat picture ========= create and run hellowWord.js ==== $ node helloWorld.js on terminal see --> Hello MEAN stack ........ Hello MEAN stack ============ 1105 video 1: 1:18 Create server =========== created server.js PS C:\NTU\GitHub\MEANstack> node server.js Server is runnning.. browser: http://localhost:3000 ==>I created a Server ============== 1105 video 1:25 Web Framework: Express === http://express.com ---video 1.32.40 create C:\NTU\GitHub\MEANstack\expressApp folder C:\NTU\GitHub\MEANstack\expressApp>npm init name: (expressApp) app version: (1.0.0)description: entry point: (index.js) app.js ... then package.json created under expressApp folder { "name": "app", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC" } PS C:\NTU\GitHub\MEANstack\expressApp> npm install express nodemon --save -> created node_modules PS C:\NTU\GitHub\MEANstack\expressApp> node app.js HW erver running . Browser: http://localhost:3000/ ==> see "Hi, this is HW1" http://localhost:3000/speak/dog ==>This dog says 'Woof woof!' http://localhost:3000/repeat/hi/10 ===>hi hi hi hi hi hi hi hi hi hi ================== Video 1:40 Express:View (Template Engine EJS/Jade)=========== EJS( Embedded Javascript ): http://www.embeddedjs.com/ JADE : https://www.npmjs.com/package/jade ================== Shop ======================= $ npm install (to create node_modules based on package.json's dependency info) $ npm install -- save express (to install express and save it to package.json, so next time "npm install" will install express) server.js: var port = process.env.PORT || 3000; ( process.env.PORT is for Heroku deployment) PS C:\NTU\GitHub\MEANstack\shop> node server.js Server is running on port 3000.......... Browser: http://localhost:3000/index.html --> see button "Click" @2016 Company. Inc
true
68a83c73bd54adb86360b3ce6b4eda61cf00c1b7
Ruby
Varunram/AlgoStuff
/codeforces/384-2/joinarr.rb
UTF-8
207
2.890625
3
[]
no_license
n, k = gets.chomp.split(" ").map(&:to_i) a = Array.new a.insert(a.length, 1) if n>1 for i in 2..n b = a a.insert(a.length, *b) a.insert((a.length+1)/2, i) end puts a[k-1] else puts 1 end
true
8ec147b00762b8e1438e0f0d64a71be958d3cfb6
Ruby
PShoe/warmups
/sept20.rb
UTF-8
734
3.578125
4
[]
no_license
# Lunch Orders # require 'pry' add_another_name = "" orders = {} until add_another_name == "n" do puts "Name for order: " name = gets.chomp orders[name] = {} orders[name][:items] = [] add_another_item = "" until add_another_item == "n" do puts "#{ name } wants to order: " item = gets.chomp orders[name][:items].push(item) puts "Add another item to the order? (y/n)" add_another_item = gets.chomp end one_person_order = orders[name][:items].join(", ") puts "All #{ name } orders: #{ one_person_order }" puts "Add another person? (y/n)" add_another_name = gets.chomp end all_orders = orders.each {|key, value| puts "#{ key } ordered #{ orders[key][:items].join(" & ") }." } binding.pry
true
3864bf1b66492805eeebe7744d851dbed7eb99d8
Ruby
Graciexia/Eight-Queens-problem
/eight_queens.rb
UTF-8
563
3.75
4
[]
no_license
# previous version COL = 0 ROW = 1 def show_queens(queens) (0..7).each do |row| (0..7).each do |col| if queens.include? ([col,row]) print ' Q' else print ' .' end end print "\n" end print "\n" end def in_line?(queens) (0..6).each do |i| ((i+1)..7).each do |j| print "Compare queen #{i} to queen #{j}\n" end end return false end queens = [] (0..7).each do |i| queens[i] = [i,i] end show_queens(queens) print "Are any queens on the same line? " print in_line?(queens) print "\n"
true
1ff668eeb1b6004bc62c4ef2ea3bfac4b3e9505f
Ruby
jisraelsen/orm
/lib/extensions.rb
UTF-8
136
2.96875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
Object.class_eval do def to_boolean return [true, "true", 1, "1"].include?(self.class == String ? self.downcase : self) end end
true
71e8cd06aa2f81f571a1b29eacae3790c314a459
Ruby
bassnode/liner_notes
/Liner Notes.app/lib/string.rb
UTF-8
131
3.03125
3
[ "MIT" ]
permissive
class String def titleize self.split(' '). map{ |part| part[0,1] = part[0,1].upcase; part }. join(' ') end end
true
4372dc4948266aa5c2f4a66b9043f462b7f88941
Ruby
solo123/tv_website
/app/models/type_text.rb
UTF-8
712
3.078125
3
[]
no_license
class TypeText include Singleton def initialize @tts = InputType.all end def get_text(type_name, type_value) return '' unless type_value tt = @tts.detect{|s| s.type_name == type_name.to_s && s.type_value == type_value.to_s} if tt tt.type_text else type_value end end def get_texts(type_name, type_value) return '' unless type_value && type_value.length > 0 tt = [] type_value.each_char do |c| tt << get_text(type_name, c) end tt.join(',') end def get_types(type_name) tt = [] @tts.each do |s| if s.type_name == type_name.to_s tt << s end end tt end end
true
bebba93529c18703c01e8bdd8398052d39981078
Ruby
kariounayoub/batch-439
/01-Ruby/05-Regular-Expressions/Reboot1/calculator/interface.rb
UTF-8
1,188
4.09375
4
[]
no_license
require_relative 'calculator' def do_a_calcul # afficher la phrase :"Enter a first number" (puts) puts "> Enter a first number:" print '> ' # on stock un nombre dans `first_number` (gets.chomp) (attention un nombre c'est un integer :-) first_number = gets.chomp.to_i # afficher la deuxieme phrase puts "> Enter a second one:" print '> ' # stocker le deuxieme nombre second_number = gets.chomp.to_i # afficher "choose operation" (penser à lui dire quel type d'opération il peut faire) puts "> Choose operation [+][-][*][/]" print '> ' # stocker l'operator dans une variable (gets.chomp) operator = gets.chomp # on calcul le résultat # dans une variable `result` result = calculate(first_number, second_number, operator) # on affiche le résultat (interpolation) puts "> Result: #{result}" end def run # on déclare une varaible `choice`, qu'on assign à 'Y' choice = 'Y' # tant que choice == 'Y' while choice == 'Y' do_a_calcul # on demande si il veut en refaire un (puts) puts "> Do you want to calculate again? [Y/N]" print '> ' # on stock dans `choice` 'Y' ou 'N' choice = gets.chomp end end run
true
9440a49c1bc946e803f01219a8c1e5d272c679ce
Ruby
jimm/patchmaster
/test/sorted_song_list_test.rb
UTF-8
517
2.625
3
[]
no_license
require 'test_helper' class SortedSongListTest < Test::Unit::TestCase def test_sorting ssl = PM::SortedSongList.new('') %w(c a b).each { |name| ssl << PM::Song.new(name) } %w(a b c).each_with_index { |name, i| assert_equal name, ssl.songs[i].name } end def test_pm_sorting ssl = PM::SortedSongList.new('') ssl << PM::Song.new("First Song") ssl << PM::Song.new("Second Song") assert_equal "First Song", ssl.songs[0].name assert_equal "Second Song", ssl.songs[1].name end end
true
7c11cc92a3be28c41eb7bf71541f5b16e911796d
Ruby
ZeeCoder/vk-elso-epizod
/game/Scripts/Window_ShopCommand.rb
UTF-8
1,567
3.09375
3
[]
no_license
#============================================================================== # ■ Window_ShopCommand #------------------------------------------------------------------------------ #  ショップ画面で、用件を選択するウィンドウです。 #============================================================================== class Window_ShopCommand < Window_Selectable #-------------------------------------------------------------------------- # ● オブジェクト初期化 #-------------------------------------------------------------------------- def initialize super(0, 64, 480, 64) self.contents = Bitmap.new(width - 32, height - 32) self.contents.font.name = $defaultfonttype # "Shop Commands" window font self.contents.font.size = $defaultfontsize @item_max = 3 @column_max = 3 @commands = ["Vesz", "Elad", "Távoz"] refresh self.index = 0 end #-------------------------------------------------------------------------- # ● リフレッシュ #-------------------------------------------------------------------------- def refresh self.contents.clear for i in 0...@item_max draw_item(i) end end #-------------------------------------------------------------------------- # ● 項目の描画 # index : 項目番号 #-------------------------------------------------------------------------- def draw_item(index) x = 4 + index * 160 self.contents.draw_text(x, 0, 128, 32, @commands[index]) end end
true
2950c04fb928d135a40c39a1cf81edc39899807c
Ruby
Hsiu-YiLin/ironhack
/week04/day19/timetrackerv3/db/seeds.rb
UTF-8
707
2.6875
3
[]
no_license
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) # puts "Creating projects" # 5.times do |i| # p = Project.create(name: "Project #{i}", description: "Hello #{i}") # if i.odd? # p.entries.create(minutes: 10 * i, hours: 1 * i) # else # p.entries.create(minutes: i, hours: i) # end # end p = Project.create(name: "Leo") 10 .times do p.entries.create(hours: 1, minutes: 10, date: 1.month.ago) end
true
3e7eb1bb117661cdd8d2a2e00768d52863285e5d
Ruby
dawnmiceli100/cipher
/cipher.rb
UTF-8
1,826
3.609375
4
[]
no_license
class Cipher attr_reader :key ALPHABET = ("abcdefghijklmnopqrstuvwxyz") def initialize(key=nil) if key.nil? generate_random_key elsif key == "" raise(ArgumentError) else key.each_char do |char| if (char == char.upcase) || (char == " ") || ("0123456789".include? char) raise(ArgumentError) end end @key = key end end def generate_random_key @key = ALPHABET.split("").shuffle.join end def get_indexes_of_characters(text) indexes = [] text.each_char do |char| indexes << ALPHABET.index(char) end return indexes end def calc_indexes_of_cipher_characters @ciphertext_indexes = [] @plaintext_indexes.each.with_index do |value, idx| cipher_index = value + @key_indexes[idx] cipher_index-=26 if cipher_index > 25 @ciphertext_indexes << cipher_index end end def calc_indexes_of_plaintext_characters @plaintext_indexes = [] @ciphertext_indexes.each_with_index do |value, idx| plaintext_index = value - @key_indexes[idx] plaintext_index+=26 if plaintext_index < 0 @plaintext_indexes << plaintext_index end end def encode(plaintext) @key_indexes = get_indexes_of_characters(@key) @plaintext_indexes = get_indexes_of_characters(plaintext) calc_indexes_of_cipher_characters @ciphertext = "" @ciphertext_indexes.each do |ci| @ciphertext << ALPHABET[ci] end return @ciphertext end def decode(ciphertext) @key_indexes = get_indexes_of_characters(@key) @ciphertext_indexes = get_indexes_of_characters(ciphertext) calc_indexes_of_plaintext_characters @plaintext = "" @plaintext_indexes.each do |pi| @plaintext << ALPHABET[pi] end return @plaintext end end
true
d99edc5f89058aaa73a8bc9b125c0c833a203c87
Ruby
cjkula/cipher-lang
/spec/js_helper.rb
UTF-8
714
2.53125
3
[]
no_license
Capybara.javascript_driver = :webkit Capybara.default_driver = Capybara.javascript_driver module JS # used to contain helper classes that wrap JavaScript objects and provide a layer of # abstraction against the language spec. Contained classes defined in helper files. end class JS::Base def var @var ||= 'window.' + self.class.to_s.downcase.gsub(/::/,'_') + rand(1000000).to_s end def to_s var end def assign_to_var(expression) page.execute_script("#{var} = (#{expression});") end def this(expression) page.evaluate_script "#{var}.#{expression}" end def class_name this('className') end public def eval(text) page.evaluate_script("#{var}.#{text}") end end
true
29a2a921501fcb89370c77f08d20b32dc1ddccb1
Ruby
kssajith/monopoly_game
/lib/game.rb
UTF-8
2,278
3.71875
4
[]
no_license
class Game def initialize(board, players) @board = board @players = players end def play loop do @players.each do |player| dice_value = throw_dice print "Player: #{player.id} Dice value: #{dice_value}\n" @board.move(dice_value, player) break if @board.last_cell_occupied? sleep(0.25) end @board.display if @board.last_cell_occupied? print "******************************" print "Player #{@board.player_at_last_cell} won" print "******************************" break end end end private def throw_dice (1..6).to_a.sample end end class Player attr_reader :id attr_reader :current_index def initialize(id, money_in_hand = 1000) @id = id @current_index = 0 @money_in_hand = money_in_hand end def update_position(index) @current_index = index end end class Board def initialize(pattern) @board = create_board(pattern) end def move(dice_value, player) @board[player.current_index].move_out(player) next_position = if (player.current_index + dice_value) > max_index max_index else player.current_index + dice_value end @board[next_position].occupy(player) player.update_position(next_position) end def last_cell_occupied? @board.last.occupied? end def display print @board.map(&:status).join(" ") print "\n" end def player_at_last_cell @board.last.occupied_player_ids end private def max_index @board.length - 1 end def create_board(pattern) pattern.downcase.split('').map do |char| cell_type(char).new end end def cell_type(char) { 'c' => Cell }[char] end end class Cell def initialize @occupied_by = [] end def occupy(player) @occupied_by << player end def move_out(player) @occupied_by.delete(player) end def occupied? !@occupied_by.empty? end def status @occupied_by.map(&:id).inspect end def occupied_player_ids "#{@occupied_by.map(&:id).join(', ')}" end end board = Board.new("ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc") players = [1, 2, 3].map {|id| Player.new(id) } Game.new(board, players).play
true
ba97ff8dd1a6fe08e8822d2a2668a66c1eceab17
Ruby
twlevelup/driver-green-and-lean
/lib/car.rb
UTF-8
1,917
3.609375
4
[]
no_license
require_relative 'OutsideGridException' require_relative 'InvalidCommandException' require_relative 'grid' class Car attr_reader :x, :y, :orientation def initialize(x, y, orientation) if ![:north, :east, :south, :west].include?(orientation) raise ArgumentError, 'Invalid orientation.' end validate_position(x, y, 'Starting position outside grid.') @x = x @y = y @orientation = orientation end def move_forward move_distance(1) end def move_backward move_distance(-1) end def turn_left case @orientation when :north @orientation = :west when :south @orientation = :east when :east @orientation = :north when :west @orientation = :south end end def turn_right case @orientation when :north @orientation = :east when :south @orientation = :west when :east @orientation = :south when :west @orientation = :north end end def position [@x, @y, @orientation] end def perform_commands(commands) commands.each do |e| if not respond_to?(e) raise InvalidCommandException, "Invalid command in list: #{e}" end end moved_through = [position] commands.each do |e| send e moved_through << position end moved_through end private def move_distance(increment) desired_x = @x desired_y = @y case @orientation when :north desired_y += increment when :south desired_y -= increment when :east desired_x += increment when :west desired_x -= increment end validate_position(desired_x, desired_y, 'Taxi is not permitted to move outside the grid.') @x = desired_x @y = desired_y end def validate_position(x, y, error_message) if not Grid.valid_position?(x, y) raise OutsideGridException, error_message end end end
true
73e280d087472d5e4f43b68f0eb69fc8e7d0b0f0
Ruby
DouglasAllen/code-Metaprogramming_Ruby
/raw-code/PART_II_Metaprogramming_in_Rails/gems/builder-2.1.2/test/preload.rb
UTF-8
1,102
2.875
3
[]
no_license
#!/usr/bin/env ruby #--- # Excerpted from "Metaprogramming Ruby: Program Like the Ruby Pros", # published by The Pragmatic Bookshelf. # Copyrights apply to this code. It may not be used to create training material, # courses, books, articles, and the like. Contact us if you are in doubt. # We make no guarantees that this code is fit for any purpose. # Visit http://www.pragmaticprogrammer.com/titles/ppmetr for more book information. #--- # We are defining method_added in Kernel and Object so that when # BlankSlate overrides them later, we can verify that it correctly # calls the older hooks. module Kernel class << self attr_reader :k_added_names alias_method :preload_method_added, :method_added def method_added(name) preload_method_added(name) @k_added_names ||= [] @k_added_names << name end end end class Object class << self attr_reader :o_added_names alias_method :preload_method_added, :method_added def method_added(name) preload_method_added(name) @o_added_names ||= [] @o_added_names << name end end end
true
03ac6019f43f14d7af699812d0d089e008e36b2f
Ruby
antonzaharia/key-for-min-value-onl01-seng-pt-012220
/key_for_min.rb
UTF-8
613
3.765625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# prereqs: iterators, hashes, conditional logic # Given a hash with numeric values, return the key for the smallest value def key_for_min_value(name_hash) if name_hash.empty? return nil else array = [] name_hash.each do |keys, value| array << value end result = [] if array[0] < array[1] && array[0] < array[2] result << array[0] end if array[1] < array[0] && array[1] < array[2] result << array[1] end if array[2] < array[1] && array[2] < array[0] result << array[2] end result name_hash.collect do |keys,value| if value == result[0] return keys end end end end
true
37d7bfb98abceef43d0d84ec716d80566c2b6527
Ruby
JulianNicholls/ParserAndLexer
/spec/parser_spec.rb
UTF-8
8,273
3.390625
3
[]
no_license
require_relative '../parser.rb' require 'spec_helper.rb' # Parser that allow access to its variables class Parser attr_reader :variables end describe Parser do before :all do @parser = Parser.new end describe 'Emptyness' do it 'should not be allowed in .do_program' do expect { @parser.do_program '' }.to raise_error StandardError end it 'should not allow nil in .do_program' do expect { @parser.do_program nil }.to raise_error StandardError end it 'should return 0 for an unused variable' do expect(@parser.variables['A']).to eq 0 end end # Each section checks that the previous variables are still set correctly describe '.do_assignment' do it 'should be able to set an integer' do @parser.line_do "A1=1\n" # No spaces expect(@parser.variables['A1']).to eq 1 end it 'should be able to set a floating point value' do @parser.line_do 'A2 =1.5' # Space before expect(@parser.variables['A2']).to eq 1.5 expect(@parser.variables['A1']).to eq 1 end it 'should be able to set a string' do @parser.line_do "A3= 'a string'" # Space after expect(@parser.variables['A3']).to eq 'a string' expect(@parser.variables['A1']).to eq 1 expect(@parser.variables['A2']).to eq 1.5 end it 'should be able to set the value of another variable' do @parser.line_do 'A4 = A2' # Space both expect(@parser.variables['A4']).to eq 1.5 expect(@parser.variables['A4']).to eq @parser.variables['A2'] expect(@parser.variables['A1']).to eq 1 expect(@parser.variables['A2']).to eq 1.5 expect(@parser.variables['A3']).to eq 'a string' end it 'should be able to set the value of an arithmetic expression' do @parser.line_do 'A6 = A2 * 10 + 5 - 3' expect(@parser.variables['A6']).to eq 17.0 expect(@parser.variables['A1']).to eq 1 expect(@parser.variables['A2']).to eq 1.5 expect(@parser.variables['A3']).to eq 'a string' expect(@parser.variables['A4']).to eq 1.5 end it 'should use LET if it is present' do @parser.line_do 'LET A5=5' # No spaces expect(@parser.variables['A5']).to eq 5 expect(@parser.variables['A1']).to eq 1 expect(@parser.variables['A2']).to eq 1.5 expect(@parser.variables['A3']).to eq 'a string' expect(@parser.variables['A4']).to eq 1.5 expect(@parser.variables['A6']).to eq 17.0 end end it 'should allow optional line numbers' do @parser.line_do '100 LET A7=7' expect(@parser.variables['A7']).to eq 7 end describe '.do_print' do it 'should work on its own to make a blank line' do output = capture_stdout do @parser.line_do 'PRINT' end expect(output).to eq "\n" end it 'should allow printing of strings' do output = capture_stdout do @parser.line_do "PRINT 'hello world'\n" # UGH! end expect(output).to eq "hello world\n" end it 'should allow printing of integers' do output = capture_stdout do @parser.line_do 'PRINT 1234' end expect(output).to eq "1234\n" end it 'should allow printing of floats' do output = capture_stdout do @parser.line_do 'PRINT 123.456' end expect(output).to eq "123.456\n" end it 'should allow printing of variables' do output = capture_stdout do @parser.line_do 'PRINT A2' end expect(output).to eq "1.5\n" end it 'should allow printing of expressions' do output = capture_stdout do @parser.line_do 'PRINT (123 + 456) * 10' end expect(output).to eq "5790\n" end it 'should allow printing of a function' do output = capture_stdout do @parser.line_do 'PRINT SQR(2)' end expect(output).to eq "1.4142135623730951\n" end describe 'Separators' do it 'should use ; to put two items together' do output = capture_stdout do @parser.line_do 'PRINT A2;A1' end expect(output).to eq "1.51\n" # 1.5 immediately followed by 1 end it 'should use , to separate two items with a tab' do output = capture_stdout do @parser.line_do 'PRINT A2,A1' end expect(output).to eq "1.5\t1\n" end it 'should use ; to not end a line with a line ending' do output = capture_stdout do @parser.line_do 'PRINT A2;' end expect(output).to eq '1.5' end it 'should use , to end a line with a tab but no line ending' do output = capture_stdout do @parser.line_do 'PRINT A2,' end expect(output).to eq "1.5\t" end end end # These are only capturing stdout so that it doesn't pollute the results describe '.do_input' do it 'should input a string' do capture_stdout do feed_stdin("word\n") { @parser.line_do 'INPUT A15' } end expect(@parser.variables['A15']).to eq 'word' end it 'should input an integer value' do capture_stdout do feed_stdin("23\n") { @parser.line_do 'INPUT A16' } end expect(@parser.variables['A16']).to eq 23 end it 'should input a floating point value' do capture_stdout do feed_stdin("23.67\n") { @parser.line_do 'INPUT A17' } end expect(@parser.variables['A17']).to eq 23.67 end it 'should allow for a prompt' do capture_stdout do feed_stdin("23\n") { @parser.line_do "INPUT 'Enter A16: ';A16" } end expect(@parser.variables['A16']).to eq 23 end end describe '.do_conditional' do it 'should do the action when the conditional is true' do output = capture_stdout do @parser.line_do "IF A4 == 1.5 THEN PRINT 'it is'\n" end expect(output).to eq "it is\n" end it 'should not do the action when the conditional is false' do @parser.line_do 'IF A4 = 1.4 THEN A4 = 2' expect(@parser.variables['A4']).to eq 1.5 end it 'should accept 2-part AND' do @parser.variables['A_AND'] = 1 @parser.line_do 'IF 1 <= 2 AND 2 <= 3 THEN A_AND = 2' # Both true expect(@parser.variables['A_AND']).to eq 2 @parser.line_do 'IF 1 <= 2 AND 3 <= 2 THEN A_AND = 3' # Right false expect(@parser.variables['A_AND']).to eq 2 @parser.line_do 'IF 1 >= 2 AND 2 <= 3 THEN A_AND = 4' # Left false expect(@parser.variables['A_AND']).to eq 2 @parser.line_do 'IF 1 >= 2 AND 2 >= 3 THEN A_AND = 5' # Both false expect(@parser.variables['A_AND']).to eq 2 end it 'should accept 3-part AND' do @parser.line_do 'IF 1 <= 2 AND 2 <= 3 AND 3 <= 4 THEN A_AND = 6' expect(@parser.variables['A_AND']).to eq 6 end it 'should accept 2-part OR' do @parser.line_do 'IF 1 <= 2 OR 2 <= 3 THEN A_OR = 3' # Both true expect(@parser.variables['A_OR']).to eq 3 @parser.line_do 'IF 1 <= 2 OR 3 <= 2 THEN A_OR = 4' # Right false expect(@parser.variables['A_OR']).to eq 4 @parser.line_do 'IF 1 >= 2 OR 2 <= 3 THEN A_OR = 5' # Left false expect(@parser.variables['A_OR']).to eq 5 @parser.line_do 'IF 1 >= 2 OR 2 >= 3 THEN A_OR = 6' # Both false expect(@parser.variables['A_OR']).to eq 5 end it 'should accept 3-part OR' do @parser.line_do 'IF 1 >= 2 OR 2 >= 3 OR 3 <= 4 THEN A_OR = 9' expect(@parser.variables['A_OR']).to eq 9 end end describe 'Malformed lines' do it 'should raise an error for reserved word used as variable' do expect { @parser.line_do 'LET INPUT = 1' }.to raise_error StandardError end it 'should raise an error for INPUT without a variable' do expect do capture_stdout { @parser.line_do "INPUT 'Prompt';" } end.to raise_error StandardError end it 'should raise an error for GOTO with a bad line number' do expect do @parser.do_program "GOTO 20\n30 REM OOPS\n" end.to raise_error StandardError end it 'should reject STEP 0 (unlikely, but there you go)' do expect do @parser.line_do 'FOR I = 1 TO 10 STEP 0' end.to raise_error StandardError end end end
true
269465c8187fd4227effb81c662120639e0ca784
Ruby
mu0s7afa/english-script
/test/unit/loop_test.rb
UTF-8
2,511
2.828125
3
[]
no_license
#!/usr/bin/env ruby # encoding: utf-8 $use_tree=false # $use_tree=true require_relative '../parser_test_helper' class LoopTest < ParserBaseTest include ParserTestHelper def _test_forever # OK ;{TRUST ME;} init 'beep forever' loops parse 'beep forever' # OK ;{TRUST ME;} end def test_while_return assert_equals parse('c=0;while c<1:c++;beep;done'), "beeped" end # def test_repeat_while #todo # parse 'x=0;repeat while x<4: x++' # assert_equals variables["x"], 4 # parse 'repeat x++ while x<4' # assert_equals variables["x"], 4 # parse 'repeat x++ until x>4' # assert_equals variables["x"], 5 # end def test_while_loop parse 'c=0;while c<3:c++;beep;done' assert variables["c"]==3 end def test_expressions #s "counter=0" #setter parse 'counter=1' #counter=@variables['counter'] #@variables['counter']=1 #parse "counter+1" #r=expression0 assert(@variableValues['counter']==1) parse 'counter++' #r=expression0 assert(@variableValues['counter']==2) #@variables['counter']=2 parse 'counter+=1' #r=plusEqual #r=expression0 assert(@variableValues['counter']==3) parse 'counter=counter+counter' #r=setter #r=algebra #r=expression0 counter=@variableValues['counter'] assert counter==6 end def test_repeat # NEEEEDS blocks!! Parser.new(block) parse "counter =0; repeat three times: increase the counter; okay" assert "counter=3" assert_equals @variableValues['counter'], 3 # assert_equals @variables[:counter],3 #s "counter=counter+1;" #@interpret=false #action #@interpret=true end def test_repeat3 assert_result_is 'counter =0; repeat three times: counter=counter+1; okay',3 # parse 'counter =0; repeat three times: counter=counter+1; okay' # assert 'counter =3' #if $use_tree # counter=counter+1 not repeatable as string assert_result_is 'counter =0; repeat while counter < 3: counter=counter+1; okay',3 end def test_repeat1 # @parser.verbose=true parse 'counter =0; repeat three times: counter+=1; okay' assert 'counter =3' parse 'counter =0; repeat three times: counter++; okay' counter=@variableValues['counter'] assert 'counter =3' assert counter ==3 #parse "counter =0; repeat three times: increase the counter by two; okay" #assert "counter =10" end def _test_forever # OK ;{TRUST ME;} @parser.s 'beep forever' @parser.loops end end
true
d08e4e0c2cff4accf9b6d8b7a33bd9ff96322e1e
Ruby
NickSpangler/school-domain-onl01-seng-ft-072720
/lib/school.rb
UTF-8
497
3.609375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class School def initialize(name) @name= name @roster= {} end def roster @roster end def add_student(name, grade) if @roster[grade] @roster[grade] << name else @roster[grade] = [] @roster[grade] << name end end def grade(grade) @roster[grade] end def sort @roster = @roster.each { |grade, students| @roster[grade].sort! } @roster.to_h end end
true
e7e924ff2679fa6a2bb82e698400e6971da83e6e
Ruby
ardama/LoLCritic
/app/models/flag.rb
UTF-8
991
3.015625
3
[]
no_license
class Flag < ActiveRecord::Base attr_accessible :body, :rawtime, :review_id, :time, :user_id, :minute, :second belongs_to :review belongs_to :user # Converts raw input of time (string) into seconds (integer) def convert_to_seconds() regex = /(\d{1,2}):(\d{2})/ match = regex.match(self.rawtime) minutes = match[1].to_i seconds = match[2].to_i total = 60*minutes + seconds self.time = total self.save end def convert_time() total = 0 if self.minute total += 60 * self.minute else self.minute = 0 self.save end if self.second total += self.second else self.second = 0 self.save end self.time = total self.save end def get_time_string() time = "" if self.minute time += minute.to_s else time += "0" end time += ":" if self.second && self.second != 0 time += self.second.to_s else time += "00" end return time end end
true
179d54af4e59ec4f962c758ef8c77c495a477369
Ruby
sousou11190/tddworkshop
/fizzbuzz/fizzbuzz_test.rb
UTF-8
1,434
3.1875
3
[]
no_license
# coding: utf-8 require 'test/unit' require "./fizzbuzz" class FizzBuzzTest < Test::Unit::TestCase def setup super # 前準備 @fizzbuzz = FizzBuzz.new() end sub_test_case "その他の数の場合は文字列にして返す" do def test_1を渡すと文字列1を返す # 実行 & 検証 assert_equal("1", @fizzbuzz.convert(1)) end def test_2を渡すと文字列2を返す # 実行 & 検証 assert_equal("2", @fizzbuzz.convert(2)) end end sub_test_case "3の倍数のときは数の代わりにFizzと返す" do def test_3を渡すと文字列Fizzを返す assert_equal("Fizz", @fizzbuzz.convert(3)) end def test_6を渡すと文字列Fizzを返す assert_equal("Fizz", @fizzbuzz.convert(6)) end end sub_test_case "5の倍数のときは数の代わりにBuzzと返す" do def test_5を渡すと文字列Buzzを返す assert_equal("Buzz", @fizzbuzz.convert(5)) end def test_10を渡すと文字列Buzzを返す assert_equal("Buzz", @fizzbuzz.convert(10)) end end sub_test_case "15の倍数の場合は数の代わりにFizzBuzzと返す" do def test_15を渡すと文字列FizzBuzzを返す assert_equal("FizzBuzz", @fizzbuzz.convert(15)) end def test_30を渡すと文字列FizzBuzzを返す assert_equal("FizzBuzz", @fizzbuzz.convert(30)) end end end
true
6023e97419b510267460c12c9b4543c97242ee62
Ruby
paolov1928/deli-counter-ruby-apply-000
/deli_counter.rb
UTF-8
1,492
4.46875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Write your code here. def line(input) if input == [] puts "The line is currently empty." else puts "The line is currently: "+input.map.with_index { |person,index| "#{index+1}. #{person} " } .join("") .rstrip end end #. Build a method that a new customer will use when entering the deli. The `take_a_number` method should accept two arguments, the array for the current line of people (`katz_deli`), and a string containing the name of the person joining the end of the line. The method should call out (`puts`) the person's name along with their position in line. **Top-Tip:** *Remember that people like to count from* `1`*, not from* `0` *("zero") like computers.* def take_a_number(katz_deli, new_person) if katz_deli == [] puts "Welcome, #{new_person}. You are number 1 in line." katz_deli << new_person else katz_deli << new_person lengths = katz_deli.length #good because this is the old length but given people like +1 compared to computer notation puts "Welcome, #{new_person}. You are number #{lengths} in line." end end #3. Build the `now_serving` method which should call out (i.e. `puts`) the next person in line and then remove them from the front. If there is nobody in line, it should call out (`puts`) that `"There is nobody waiting to be served!"`. def now_serving(katz_deli) if katz_deli == [] puts "There is nobody waiting to be served!" else puts "Currently serving #{katz_deli[0]}." katz_deli.shift() end end
true
8b56034897416c961104068b6c6204e0aed20bc4
Ruby
jamis/sqlite-ruby
/test/tc_database.rb
UTF-8
9,576
2.6875
3
[ "BSD-3-Clause" ]
permissive
$:.unshift "lib" require 'sqlite' require 'test/unit' class TC_Database < Test::Unit::TestCase def setup @db = SQLite::Database.open( "db/fixtures.db" ) end def teardown @db.close end def test_constants assert_equal "constant", defined?( SQLite::Version::MAJOR ) assert_equal "constant", defined?( SQLite::Version::MINOR ) assert_equal "constant", defined?( SQLite::Version::TINY ) assert_equal "constant", defined?( SQLite::Version::STRING ) expected = [ SQLite::Version::MAJOR, SQLite::Version::MINOR, SQLite::Version::TINY ].join( "." ) assert_equal expected, SQLite::Version::STRING end def test_execute_no_block rows = @db.execute( "select * from A order by name limit 2" ) assert_equal [ [nil, "6"], ["Amber", "5"] ], rows end def test_execute_with_block expect = [ [nil, "6"], ["Amber", "5"] ] @db.execute( "select * from A order by name limit 2" ) do |row| assert_equal expect.shift, row end assert expect.empty? end def test_execute2_no_block columns, *rows = @db.execute2( "select * from A order by name limit 2" ) assert_equal [ "name", "age" ], columns assert_equal [ [nil, "6"], ["Amber", "5"] ], rows end def test_execute2_with_block expect = [ ["name", "age"], [nil, "6"], ["Amber", "5"] ] @db.execute2( "select * from A order by name limit 2" ) do |row| assert_equal expect.shift, row end assert expect.empty? end def test_bind_vars rows = @db.execute( "select * from A where name = ?", "Amber" ) assert_equal [ ["Amber", "5"] ], rows rows = @db.execute( "select * from A where name = ?", 15 ) assert_equal [], rows end def test_result_hash @db.results_as_hash = true rows = @db.execute( "select * from A where name = ?", "Amber" ) assert_equal [ {"name"=>"Amber", 0=>"Amber", "age"=>"5", 1=>"5"} ], rows end def test_result_hash_types @db.results_as_hash = true rows = @db.execute( "select * from A where name = ?", "Amber" ) assert_equal [ "VARCHAR(60)", "INTEGER" ], rows[0].types end def test_query @db.query( "select * from A where name = ?", "Amber" ) do |result| row = result.next assert_equal [ "Amber", "5"], row end end def test_metadata @db.query( "select * from A where name = ?", "Amber" ) do |result| assert_equal [ "name", "age" ], result.columns assert_equal [ "VARCHAR(60)", "INTEGER" ], result.types assert_equal [ "Amber", "5"], result.next end end def test_get_first_row row = @db.get_first_row( "select * from A order by name" ) assert_equal [ nil, "6" ], row end def test_get_first_value age = @db.get_first_value( "select age from A order by name" ) assert_equal "6", age end def test_create_function @db.create_function( "maim", 1 ) do |func, value| if value.nil? func.set_result nil else func.set_result value.split(//).sort.join end end value = @db.get_first_value( "select maim(name) from A where name='Amber'" ) assert_equal "Abemr", value end def test_create_aggregate step = proc do |func, value| func[ :total ] ||= 0 func[ :total ] += ( value ? value.length : 0 ) end finalize = proc do |func| func.set_result( func[ :total ] || 0 ) end @db.create_aggregate( "lengths", 1, step, finalize ) value = @db.get_first_value( "select lengths(name) from A" ) assert_equal "33", value end def test_set_error @db.create_function( "barf", 1 ) do |func, value| func.set_error "oops! I did it again" end assert_raise( SQLite::Exceptions::SQLException ) do @db.get_first_value( "select barf(name) from A where name='Amber'" ) end end def test_context_on_nonaggregate @db.create_function( "barf1", 1 ) do |func, value| assert_raise( SQLite::Exceptions::MisuseException ) do func['hello'] end end @db.create_function( "barf2", 1 ) do |func, value| assert_raise( SQLite::Exceptions::MisuseException ) do func['hello'] = "world" end end @db.create_function( "barf3", 1 ) do |func, value| assert_raise( SQLite::Exceptions::MisuseException ) do func.count end end @db.get_first_value( "select barf1(name) from A where name='Amber'" ) @db.get_first_value( "select barf2(name) from A where name='Amber'" ) @db.get_first_value( "select barf3(name) from A where name='Amber'" ) end class LengthsAggregate def self.function_type :numeric end def self.arity 1 end def self.name "lengths" end def initialize @total = 0 end def step( ctx, name ) @total += ( name ? name.length : 0 ) end def finalize( ctx ) ctx.set_result( @total ) end end def test_create_aggregate_handler @db.create_aggregate_handler LengthsAggregate result = @db.get_first_value( "select lengths(name) from A" ) assert_equal "33", result end def test_prepare stmt = @db.prepare( "select * from A" ) assert_equal "", stmt.remainder assert_equal [ "name", "age" ], stmt.columns assert_equal [ "VARCHAR(60)", "INTEGER" ], stmt.types stmt.execute do |result| row = result.next assert_equal [ "Zephyr", "1" ], row end end def test_prepare_bind_execute stmt = @db.prepare( "select * from A where age = ?" ) stmt.bind_params 1 stmt.execute do |result| row = result.next assert_equal [ "Zephyr", "1" ], row assert_nil result.next end end def test_prepare_bind_execute! stmt = @db.prepare( "select * from A where age = ?" ) stmt.bind_params 1 rows = stmt.execute! assert_equal 1, rows.length assert_equal [ "Zephyr", "1" ], rows.first end def test_prepare_execute stmt = @db.prepare( "select * from A where age = ?" ) stmt.execute( 1 ) do |result| row = result.next assert_equal [ "Zephyr", "1" ], row assert_nil result.next end end def test_prepare_execute! stmt = @db.prepare( "select * from A where age = ?" ) rows = stmt.execute!( 1 ) assert_equal 1, rows.length assert_equal [ "Zephyr", "1" ], rows.first end def test_execute_batch count = @db.get_first_value( "select count(*) from A" ).to_i @db.execute_batch( %q{--- query number one insert into A ( age, name ) values ( 200, 'test' ); /* query number * two */ insert into A ( age, name ) values ( 201, 'test2' ); insert into A ( age, name ) values ( 202, /* comment here */ 'test3' )} ) new_count = @db.get_first_value( "select count(*) from A" ).to_i assert_equal 3, new_count - count @db.execute_batch( %q{--- query number one delete from A where age = 200; /* query number * two */ delete from A where age = 201; delete from /* comment */ A where age = 202;} ) new_count = @db.get_first_value( "select count(*) from A" ).to_i assert_equal new_count, count assert_nothing_raised do @db.execute_batch( "delete from A where age = 200;\n" ) end end def test_transaction_block_errors assert_raise( SQLite::Exceptions::SQLException ) do @db.transaction do @db.commit end end assert_raise( SQLite::Exceptions::SQLException ) do @db.transaction do @db.rollback end end end def test_transaction_errors assert_raise( SQLite::Exceptions::SQLException ) do @db.commit end assert_raise( SQLite::Exceptions::SQLException ) do @db.rollback end end def test_transaction_block_good count = @db.get_first_value( "select count(*) from A" ).to_i begin @db.transaction do |db| assert @db.transaction_active? db.execute( "insert into A values ( 'bogus', 1 )" ) sub_count = db.get_first_value( "select count(*) from A" ).to_i assert_equal count+1, sub_count raise "testing rollback..." end rescue Exception end new_count = @db.get_first_value( "select count(*) from A" ).to_i assert_equal count, new_count @db.transaction do |db| db.execute( "insert into A values ( 'bogus', 1 )" ) sub_count = db.get_first_value( "select count(*) from A" ).to_i assert_equal count+1, sub_count end new_count = @db.get_first_value( "select count(*) from A" ).to_i assert_equal count+1, new_count @db.execute( "delete from A where name = ?", "bogus" ) end def test_transaction_explicit count = @db.get_first_value( "select count(*) from A" ).to_i @db.transaction assert @db.transaction_active? @db.execute( "insert into A values ( 'bogus', 1 )" ) sub_count = @db.get_first_value( "select count(*) from A" ).to_i assert_equal count+1, sub_count @db.rollback sub_count = @db.get_first_value( "select count(*) from A" ).to_i assert_equal count, sub_count @db.transaction @db.execute( "insert into A values ( 'bogus', 1 )" ) sub_count = @db.get_first_value( "select count(*) from A" ).to_i assert_equal count+1, sub_count @db.commit sub_count = @db.get_first_value( "select count(*) from A" ).to_i assert_equal count+1, sub_count @db.execute( "delete from A where name = ?", "bogus" ) end end
true
e38d1e58c408fcea2dc3882bdd544c888a486025
Ruby
Koyirox/s3_desafio_1estructurasDeControl
/2_Ciclos_Iterativos/2.1.rb
UTF-8
177
3.34375
3
[]
no_license
=begin 2.1 En el siguiente código reemplaza la instrucción 'for' por 'times'. for i in 1..10 do puts i end =end 10.times do |i| i+=1 puts i end
true
f77457b10cabb0f37bfe65526ae0124f258e6905
Ruby
Maheshkumar-novice/Hangman
/lib/game.rb
UTF-8
3,948
3.34375
3
[]
no_license
#!/usr/bin/env ruby # frozen_string_literal: true require_relative 'file-handler' require_relative 'user' require_relative 'word' require_relative 'guess' require_relative 'modules/game-output' require_relative 'modules/print-hangman' require 'yaml' # Class Game - Game Driver & Operations class Game include GameOutput include PrintHangman SAVE_DIR = 'saved_games' attr_reader :user, :word, :guess, :file_handler attr_accessor :user_guess def initialize(user, word, guess, file_handler) @user = user @word = word @guess = guess @file_handler = file_handler @user_guess = nil @validation = nil end def intro print_game_intro end def start if user.make_choice == 'y' load_game else new_game end print_go_again_prompt start if gets.chomp.downcase == 'y' end private def new_game word.secret_word = word.generate word.placeholder = ' _ ' * word.secret_word.size create_game_state(5, [], [], word.secret_word, word.placeholder) play_the_game end def load_game return print_no_games_found if file_handler.save_not_available? hash = file_handler.game_data create_game_state(hash[:remaining_incorrect_guesses], hash[:correct_guesses], hash[:incorrect_guesses], hash[:secret_word], hash[:placeholder]) play_the_game end def play_the_game print_game_state loop do process_the_game break print_thank_you if exit? break announce_result if game_end? end end def process_the_game create_user_guess return save_game if save? return if exit? if guess.already_guessed?(user_guess) print_already_guessed else validation = validate_user_guess update_game_state(validation) end print_game_state end def save_game filename = file_handler.file_name file_handler.save_file("#{SAVE_DIR}/#{filename}", YAML.dump(create_game_state_hash)) print_game_saved end def update_game_state(validation) if validation update_correct_guesses update_placeholder return end update_incorrect_guesses decrease_remaining_incorrect_guesses print_hangman(guess.remaining_incorrect_guesses) end def create_user_guess self.user_guess = user.make_guess until user_guess =~ /^[a-z]{1}$/i break if user_guess =~ /^save$|^exit$/i print_user_guess_error self.user_guess = user.make_guess end end def create_game_state(remaining_incorrect_guesses, correct_guesses, incorrect_guesses, secret_word, placeholder) guess.remaining_incorrect_guesses = remaining_incorrect_guesses guess.correct_guesses = correct_guesses guess.incorrect_guesses = incorrect_guesses word.secret_word = secret_word word.placeholder = placeholder end def create_game_state_hash { remaining_incorrect_guesses: guess.remaining_incorrect_guesses, correct_guesses: guess.correct_guesses, incorrect_guesses: guess.incorrect_guesses, secret_word: word.secret_word, placeholder: word.placeholder } end def validate_user_guess guess.validate(user_guess, word.secret_word) end def update_placeholder word.update_placeholder(guess.correct_guesses) end def update_correct_guesses guess.correct_guesses << user_guess unless guess.correct_guesses.include?(user_guess) end def update_incorrect_guesses guess.incorrect_guesses << user_guess unless guess.incorrect_guesses.include?(user_guess) end def decrease_remaining_incorrect_guesses guess.remaining_incorrect_guesses -= 1 end def game_end? return true if guess.remaining_incorrect_guesses.zero? return true if word.placeholder == word.secret_word false end def save? user_guess == 'save' end def exit? user_guess == 'exit' end end
true
c82b2bc68bfb30e49f6a75dafceea8d433b49e87
Ruby
Vidreven/rubitcointools
/lib/transaction.rb
UTF-8
9,435
2.796875
3
[ "MIT" ]
permissive
require_relative 'specials' require_relative 'hashes' require_relative 'ecdsa' require_relative 'scripts' class Transaction def initialize @sp = Specials.new @h = Hashes.new @dsa = ECDSA.new @k = Keys.new @sc = Scripts.new end def deserialize(tx) txcpy = tx.clone obj = {ins: [], outs: []} obj[:version] = @sp.change_endianness(read_and_modify!(4, txcpy)) ins = read_var_int!(txcpy) ins.times{ obj[:ins] << { outpoint: { hash: @sp.change_endianness(read_and_modify!(32, txcpy)), index: @sp.change_endianness(read_and_modify!(4, txcpy)) }, scriptSig: read_var_string!(txcpy), sequence: @sp.change_endianness(read_and_modify!(4, txcpy)) } } outs = read_var_int!(txcpy) outs.times{ obj[:outs] << { value: @sp.change_endianness(read_and_modify!(8, txcpy)), scriptPubKey: read_var_string!(txcpy) } } obj[:locktime] = @sp.change_endianness(read_and_modify!(4, txcpy)) obj end def serialize(txobj) raw = '' raw += @sp.change_endianness(txobj[:version]) #raw += txobj[:ins].length.to_s(16).rjust(2, '0') raw += to_var_int(txobj[:ins].length) txobj[:ins].each do |input| raw += @sp.change_endianness(input[:outpoint][:hash]) raw += @sp.change_endianness(input[:outpoint][:index]) #scriptlen = input[:scriptSig].length / 2 # convert charlen to bytelen #scriptlen = scriptlen.to_s(16) #raw += scriptlen + input[:scriptSig] raw += to_var_str(input[:scriptSig]) raw += @sp.change_endianness(input[:sequence]) end #raw += txobj[:outs].length.to_s(16).rjust(2, '0') raw += to_var_int(txobj[:outs].length) txobj[:outs].each do |output| raw += @sp.change_endianness(output[:value]) raw += to_var_str(output[:scriptPubKey]) end raw += @sp.change_endianness(txobj[:locktime]) raw end # Hashing transactions for signing SIGHASH_ALL = 1 SIGHASH_NONE = 2 SIGHASH_SINGLE = 3 SIGHASH_ANYONECANPAY = 0x80 # Prepares the transaction for hashing. Each input has to be handled separately. # For hasing each scriptSig in has to be first filled with scriptPubKey. def signature_form(tx, i, scriptPubKey, hashcode=SIGHASH_ALL) i, hashcode = i.to_i, hashcode.to_i raise ArgumentError, "i > #inputs" if i > tx[:ins].size # if tx.respond_to? :each_char # return serialize(signature_form(deserialize(tx), i, scriptPubKey, hashcode)) # end newtx = tx.clone newtx[:ins].each do |input| input[:scriptSig] = "" end newtx[:ins][i][:scriptSig] = scriptPubKey if hashcode & 0x1f == SIGHASH_NONE newtx[:outs] = [] elsif hashcode & 0x1f == SIGHASH_SINGLE newtx[:outs].each_index do |index| next if index == i newtx[:outs][index][:value] = 2**64 - 1 newtx[:outs][index][:scriptPubKey] = "" #newtx[:ins][index][:sequence] = '00000000' end end if hashcode & SIGHASH_ANYONECANPAY == SIGHASH_ANYONECANPAY newtx[:ins] = [newtx[:ins][i]] end newtx end # def bin_txhash(tx, hashcode='None') # if hashcode == 'None' # result = @h.bin_dbl_sha256(tx) # else # result = @h.bin_dbl_sha256(tx + hashcode.to_s.rjust(8, '0')) # end # return @sp.change_endianness(result) # end # Accepts transaction in serialized format and appends hashcode before hashing. def bin_txhash(tx, hashcode=SIGHASH_ALL) tx = @sp.changebase(tx, 16, 256) hashcode = @sp.encode(hashcode, 256, 4) #hashcode.to_s.rjust(8, '0') hashcode.reverse! # = @sp.change_endianness(hashcode) result = @h.bin_dbl_sha256(tx + hashcode) result end def txhash(tx, hashcode=SIGHASH_ALL) @sp.changebase(bin_txhash(tx, hashcode), 256, 16) end # Signs the transaction, appends the hashcode and encodes it into DER format. def ecdsa_tx_sign(tx, priv, hashcode=SIGHASH_ALL) rawsig = @dsa.ecdsa_raw_sign(bin_txhash(tx, hashcode), priv) @dsa.encode_sig(*rawsig) + hashcode.to_s.rjust(2, '0') #@sp.encode(hashcode, 16, 2) end def ecdsa_tx_verify(tx, sig, pub, hashcode=SIGHASH_ALL) @dsa.ecdsa_raw_verify(bin_txhash(tx, hashcode), @dsa.decode_sig(sig), pub) end # recovers pubkey # def ecdsa_tx_recover(tx, sig, hashcode=SIGHASH_ALL) # z = bin_txhash(tx, hashcode) # v, r, s = @dsa.decode_sig sig # left, right = @dsa.ecdsa_raw_recover(z, [v, r, s]) # @k.encode_pubkey([left, right], :hex) # end # Signing and verifying # Takes a deserialized transaction as input, generates the public key and address, # signs the input and creates and inserts the proper scriptSig. def sign(tx, i, priv, hashcode=SIGHASH_ALL) i = i.to_i priv = @k.encode_privkey(priv, :hex) pub = @k.privtopub(priv) address = @k.pubtoaddr(pub) txobj = deepcopy(tx) # u scriptSig ide scriptPubKey transakcije koju želimo potrošiti (ali nije nužno) signing_tx = signature_form(tx, i, @sc.mk_pubkey_script(address), hashcode) signing_tx = serialize signing_tx # Samo ako prethodno nije serijalizirana sig = ecdsa_tx_sign(signing_tx, priv, hashcode) txobj[:ins][i][:scriptSig] = (sig.length / 2).to_s(16) + sig + (pub.length / 2).to_s(16) + pub #return serialize(txobj) txobj end # Takes a deserialized transaction as input # and signs every transaction input. def sign_all(tx, priv) tx[:ins].each_index do |i| tx = sign(tx, i, priv) end tx end # Takes a deserialized transaction as input and signs the input # script =? pubKeyhash def multisign(tx, i, script, priv, hashcode=SIGHASH_ALL) modtx = signature_form(tx, i, script, hashcode) modtx = serialize modtx ecdsa_tx_sign(modtx, priv, hashcode) end # Takes a deserialized multisig transaction as input # and appends signatures and script to the input field. # Separate persons can controll different pubkeys/signatures. # Params: # +tx+:: deserialized multisig transaction # +i+:: - input index # +script+:: - PSH reddem script (OP_M pubkeys OP_N OP_CHECKMULTISIG) # +sigs+:: - string list or array of signatures def apply_multisignatures(tx, i, script, *sigs) #txobj = deserialize(tx) scriptSig = "00" # Push byte 0x0 due to bug in multisig pushdata = '' # In case transaction > 150 bytes. # In case sigs is an array * puts it inside another array # so that outter array size is 1. sigs = sigs[0] if sigs.length == 1 sigs.each do |sig| scriptSig += (sig.length / 2).to_s(16) + sig end pushdata = case script.length when 151..255 then '4c' when 256..65535 then '4d' when 65546..0xFFFFFFFF then '4e' end scriptSig += pushdata #'4c' if (script.length / 2) > 150 # OP_PUSHDATA1 scriptSig += (script.length / 2).to_s(16) + script tx[:ins][i][:scriptSig] = scriptSig tx end def mkout(amount=546, scriptPubKey) raise ArgumentError, "Amount must be present" if amount.nil? #raise ArgumentError, "Amount can't be empty" if amount.empty? raise ArgumentError, "Amount must be atleast 546 satoshi" if amount < 546 raise ArgumentError, "Script must be present" if scriptPubKey.nil? raise ArgumentError, "Script can't be empty" if scriptPubKey.empty? #raise ArgumentError, "Invalid script" if scriptPubKey.size < 50 amount = amount.to_s(16).rjust(16, '0') {value: amount, scriptPubKey: scriptPubKey} end def mkin(hash, index, scriptSig, sequence='ffffffff') raise ArgumentError, "Input can't be empty" unless [hash, scriptSig].none? {|x| x.empty?} #raise ArgumentError, "Invalid signature" unless @dsa.bip66? scriptSig outpoint = {outpoint: {hash: hash, index: index.to_s.rjust(8, '0')}} outpoint[:scriptSig] = scriptSig outpoint[:sequence] = sequence outpoint end # Takes a list of input and output hashes # in0, in1, ..., out0, out1, ... def mktx(*args) raise ArgumentError, "Input can't be nil" if args[0].nil? raise ArgumentError, "Input can't be empty" if args[0].length == 0 raise ArgumentError, "Invalid input" if args[0].length < 2 tx = {version: '00000001', locktime: '00000000', ins: [], outs: []} args.each do |arg| input?(arg) ? tx[:ins] << arg : tx[:outs] << arg end tx end #private # accepts length in bytes # modifies the string by slicing off bytes def read_and_modify!(bytes, tx) chars = bytes * 2 #reads hexa chars return tx.slice!(0..chars-1) end # returns variable part of varint and modyfies tx # Longer numbers are encoded in little endian. def read_var_int!(tx) val = tx.slice!(0..1).to_i(16) return val if val < 253 var = read_and_modify!(2**(val-252), tx) return @sp.change_endianness(var).to_i(16) end # varint + char[] # returns the string and modyfies tx def read_var_string!(tx) size = read_var_int!(tx) return read_and_modify!(size, tx) end def to_var_int(val) val = val.to_s(16) return val.rjust(2, '0') if val.to_i(16) < 0xFD return 'fd' + @sp.change_endianness(val.rjust(4, '0')) if val.to_i(16) < 0xFFFF return 'fe' + @sp.change_endianness(val.rjust(8, '0')) if val.to_i(16) < 0xFFFFFFFF return 'ff' + @sp.change_endianness(val.rjust(16, '0')) end def to_var_str(str) return to_var_int(str.length / 2) + str end private def input?(arg) arg.has_key? :outpoint end def deepcopy(obj) return Marshal.load(Marshal.dump(obj)) end end
true