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
8a2b3be5625fd5091959ced9f043297801a524dd
Ruby
MrMarvin/rattlcache
/lib/backends/filesystem.rb
UTF-8
1,937
2.765625
3
[ "MIT" ]
permissive
require 'json' require 'base64' module Rattlecache module Backend class Filesystem < Cache def initialize(prefix = "/tmp/rattlecache/") @prefix = prefix end def get(objectKey) #puts "Filesystem gets you: #{objectKey}" # get the file from the filesystem ret = {:status => 404, :lastModified => nil, :object => nil} begin f = open_file(objectKey) firstline = f.first object = f.read mtime = f.mtime f.close ret = {:status => 200, :object => object, :lastModified => mtime, :header => Base64.strict_decode64(firstline.chomp) } rescue Errno::ENOENT end return ret end def post(object) # put the file to the filesysten firstline = Base64.strict_encode64(object[:header].to_json) #puts "Debug: putting headers as firstline: #{firstline}" f = open_file(object[:key],"w") f.puts(firstline) f.puts(object[:data]) f.close #puts "Debug: filesystem posted #{object[:key]}" end def delete(object_key) begin File.delete(@prefix+object_key) rescue Errno::ENOENT end end def open_file(objectKey,how="r") begin make_sure_dir_exists() File.open(@prefix+objectKey,how) rescue # raise this to the caller raise end end def make_sure_dir_exists() Dir.mkdir(@prefix) unless File.directory?(@prefix) end def flush() make_sure_dir_exists() Dir.foreach(@prefix) do |file| File.delete(@prefix+file) unless File.directory?(file) end end # returns the number of entries in this cache def entries() Dir.entries(@prefix).size - 2 end end end end
true
3da78e8b832e274b417bb1105a7a434f6676f3c0
Ruby
forksaber/ec2
/lib/ec2/subnet.rb
UTF-8
2,402
2.65625
3
[ "MIT" ]
permissive
require 'ec2/helper' require 'ec2/logger' module Ec2 class Subnet include Helper include Logger def initialize(name, vpc_id: nil) error "vpc_id not specified for subnet" if not vpc_id @vpc_id = vpc_id.to_s @name = name.to_s end def id! load_id if not @id error "specified subnet #{@name} doesn't exist in vpc #{@vpc_id}" if not exists? @id end def created(&block) instance_eval &block load_id using_cidr: true if exists? tag if not tagged? verify else create tag end end private def subnet @subnet ||= ::Aws::EC2::Subnet.new(@id) end def create resp = ec2.create_subnet( vpc_id: @vpc_id, cidr_block: @cidr, availability_zone: @availability_zone ) @id = resp.subnet.subnet_id logger.info "(#{@name}) created subnet: #{@cidr}" rescue Aws::Errors::ServiceError, ArgumentError error "while creating subnet #{@name}" end def tag subnet.create_tags( tags: [ { key: "Name", value: @name } ] ) subnet.load end def tagged? subnet.tags.any? { |tag| tag.key == "Name"} end def verify name_tag = subnet.tags.find { |tag| tag.key == "Name" }.value error "availability zone mismatch for subnet #{@name}" if subnet.availability_zone != @availability_zone error "subnet #{@name} already tagged with another name #{name_tag}" if @name != name_tag end def cidr(cidr) @cidr = cidr end def availability_zone(availability_zone) @availability_zone = availability_zone end alias_method :az, :availability_zone def load_id(using_cidr: false) filters = [] if using_cidr filters << { name: "cidr", values: [@cidr.to_s] } else filters << { name: "tag:Name", values: [@name.to_s] } end filters << { name: "vpc-id", values: [@vpc_id.to_s] } result = ec2.describe_subnets(filters: filters) error "mulitple subnets found with name #{@name}" if result.subnets.size > 1 @id = result.subnets.first.subnet_id if result.subnets.size == 1 end def exists? @id end def ec2 @ec2 ||= begin @region ? Aws::EC2::Client.new(region: @region) : Aws::EC2::Client.new end end end end
true
7fab66b8d0e406ffe193fee0d1a97c78816c44e9
Ruby
seielit/figaro
/lib/figaro/settings.rb
UTF-8
2,456
2.921875
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'bigdecimal' module Figaro # # This class should be extended in your own application to provide a higher # level API for use in your application. # # Your app shouldn't use ENV, Figaro.env not Settings#[]. It also shouldn't # fiddle with data conversion in settings. # # class Settings < Figaro::Settings # requires :per_page # makes it fail on startup # requires :port, # :int # # def per_page # self[:per_page].int # end # end # class Settings attr_reader :namespace NAMESPACE_SEPARATOR = '__'.freeze module ClassMethods def [](key) new(key) end def requires(key, type = nil) setting = self[key] if type setting.as type, raises: true else setting.value || raise(MissingKey, key) end end end extend ClassMethods def initialize(namespace) @namespace = [namespace] end def [](key) self.class.new(namespace + [key]) end def key ns = namespace || [] ns.join NAMESPACE_SEPARATOR end def value env.send key end def to_str value end def to_s value end def inspect "Setting: #{key} => #{value.inspect}" end module DataTypes FALSY_VALUES = %w[no off false disabled].freeze NULLABLE_TYPES = { int: method(:Integer), float: method(:Float), decimal: method(:BigDecimal), string: ->(itself) { itself || raise(ArgumentError) } }.freeze class InvalidKey < Error def initialize(setting, type) super("Invalid configuration key: can't convert #{setting.inspect} to #{type}") end end def as(type, raises: false) case type when :bool bool else conversion = NULLABLE_TYPES[type] conversion.call value end rescue ArgumentError, TypeError raise InvalidKey.new(self, type) if raises end def bool !FALSY_VALUES.include? value&.downcase end NULLABLE_TYPES.each do |method, _conversion| define_method method do as method end define_method "#{method}!" do as method, raises: true end end end include DataTypes private def env Figaro.env end end end
true
a64861b348164d71786144df37b574c96b7d6b8d
Ruby
zychmichal/smartflix
/app/adapters/movies/omdb/requests/search_movie_request.rb
UTF-8
590
2.578125
3
[]
no_license
# frozen_string_literal: true require_relative 'uri_omdb_builder' module Movies module Omdb module Requests class SearchMovieRequest include UriOmdbBuilder def search_movies_by_title_and_year(title, year = nil) request_uri = build_uri_by_search(title, year) res = Net::HTTP.get_response(request_uri) res if res.is_a?(Net::HTTPSuccess) end private def build_uri_by_search(title, year = nil) year.nil? ? build_uri(s: title) : build_uri(s: title, y: year) end end end end end
true
0e69bd7e383be765ca104141e3b43713e363f98c
Ruby
jklbj/hw_3-credit_card_crypto
/substitution_cipher.rb
UTF-8
1,573
3.234375
3
[]
no_license
module SubstitutionCipher module Caesar # Encrypts document using key # Arguments: # document: String # key: Fixnum (integer) # Returns: String def self.encrypt(document, key) # TODO: encrypt string using caesar cipher x = document.to_s.each_char.map{|a| a.ord + key } x.map{|a| a.chr}.join("") end # Decrypts String document using integer key # Arguments: # document: String # key: Fixnum (integer) # Returns: String def self.decrypt(document, key) # TODO: decrypt string using caesar cipher x = document.to_s.each_char.map{|a| a.ord - key} x.map{|a| a.chr}.join("") end end module Permutation # Encrypts document using key # Arguments: # document: String # key: Fixnum (integer) # Returns: String def self.encrypt(document, key) # TODO: encrypt string using a permutation cipher def self.hashfun(number, key) number.to_i * 2 + key end document.to_s.each_char.map{|a| hashfun(a.ord, key).chr}.join("") end # Decrypts String document using integer key # Arguments: # document: String # key: Fixnum (integer) # Returns: String def self.decrypt(document, key) # TODO: decrypt string using a permutation cipher def self.hashfun(number, key) (number - key) / 2 end document.to_s.each_char.map{|a| hashfun(a.ord, key).chr}.join("") end end end
true
53880a34dfdd393832a76cf6ae6d7b454d418dda
Ruby
MarkFChavez/maokai
/app/models/user.rb
UTF-8
642
2.625
3
[]
no_license
class User < ActiveRecord::Base attr_accessible :email, :name, :image, :provider, :uid validates :email, :name, :image, :provider, :uid, presence: true #looks on the db for a matching provider & uid, if nothing si found, will create new record def self.from_omniauth(auth_hash) where(auth_hash.slice("provider", "uid")).first || create_from_omniauth(auth_hash) end def self.create_from_omniauth(auth_hash) create! do |user| user.name = auth_hash.info.name user.email = auth_hash.info.email user.image = auth_hash.info.image user.provider = auth_hash.provider user.uid = auth_hash.uid end end end
true
e09142af0577d33fc34bae6233cd345c42cc7c7b
Ruby
banurekha/poker_hands
/lib/hand.rb
UTF-8
4,792
3.515625
4
[]
no_license
# Parser to decode hand and find the rank. It can also compare one hand with other # frozen_string_literal: true class Hand include Comparable attr_reader :cards def initialize(array_of_cards) raise ArgumentError, 'There must be 5 cards' unless array_of_cards.count == 5 card_hashes = array_of_cards.map do |card_string| CardParser.new.parse(card_string) end @cards = card_hashes.map do |card_hash| Card.new(card_hash.fetch(:value), card_hash.fetch(:suit)) end end def <=>(other_hand) rank_type = POKER_RANKS.index(rank.fetch(:type)) other_hand_rank_type = POKER_RANKS.index(other_hand.rank.fetch(:type)) if rank_type == other_hand_rank_type compare_value(:value, rank, other_hand.rank) || compare_value(:full_of, rank, other_hand.rank) || compare_card_arrays(:pairs, rank, other_hand.rank) || compare_card_arrays(:cards, rank, other_hand.rank) || 0 else rank_type <=> other_hand_rank_type end end POKER_RANKS = [ :highest, :pair, :two_pair, :three_of_a_kind, :straight, :flush, :full_house, :four_of_a_kind, :straight_flush ].freeze def rank straight_flush || four_of_a_kind || full_house || flush || straight || three_of_a_kind || two_pair || pair || highest end private def straight_flush straight.merge(type: :straight_flush) if flush && straight end def four_of_a_kind if values_per_occurence[4] { type: :four_of_a_kind, value: values_per_occurence[4].first, cards: values_per_occurence[1] } end end def full_house if values_per_occurence[3] && values_per_occurence[2] { type: :full_house, value: values_per_occurence[3].first, full_of: values_per_occurence[2].first } end end def flush if suits_per_occurence[5] { type: :flush, cards: values_per_occurence[1] } end end def straight card_values = cards.map(&:value) aces_as_ones = aces_as_ones(card_values) if aces_as_ones != card_values && consecutive_cards?(aces_as_ones) { type: :straight, value: 5 } elsif consecutive_cards?(card_values) { type: :straight, value: high_card } end end def three_of_a_kind if values_per_occurence[3] { type: :three_of_a_kind, value: values_per_occurence[3].first, cards: values_per_occurence[1] } end end def two_pair if values_per_occurence[2] && values_per_occurence[2].size == 2 { type: :two_pair, pairs: values_per_occurence[2], cards: values_per_occurence[1] } end end def pair if values_per_occurence[2] { type: :pair, value: values_per_occurence[2].first, cards: values_per_occurence[1] } end end def highest { type: :highest, cards: values_per_occurence[1] } end def values_per_occurence result = results_per_occurence_number(cards.map(&:value)) result.each do |nb_occurence, values| result[nb_occurence] = values.sort.reverse end result end def suits_per_occurence results_per_occurence_number(cards.map(&:suit)) end def compare_card_arrays(key, rank, other_rank) if rank.key?(key) cards = rank.fetch(key) other_cards = other_rank.fetch(key) if cards != other_cards (cards - other_cards).max <=> (other_cards - cards).max end end end def compare_value(key, rank, other_rank) if rank.key?(key) if rank.fetch(key) != other_rank.fetch(key) rank.fetch(key) <=> other_rank.fetch(key) end end end def consecutive_cards?(card_values) array_consecutive_integers?(card_values) end def aces_as_ones(card_values) number_aces = card_values.select { |i| i == 14 }.count result = card_values.clone if number_aces >= 1 result.delete(14) number_aces.times do result << 1 end end result end def high_card cards.map(&:value).max end def results_per_occurence_number(array) grouped_values = array.group_by { |i| i } result = {} grouped_values.each do |key, value| if result[value.count] result[value.count] << key else result[value.count] = [key] end end result end def array_consecutive_integers?(array) array.sort! difference_always_1 = true i = 0 while difference_always_1 && i < (array.size - 1) difference_between_values = array[i + 1] - array[i] difference_always_1 = difference_between_values == 1 i += 1 end difference_always_1 end end
true
8f8927942c4486d0e116963cfd755a1d3120816d
Ruby
liamtlr/learn_to_program
/ch14-blocks-and-procs/grandfather_clock.rb
UTF-8
259
3
3
[]
no_license
def grandfather_clock &block twenty_hour_time = Time.new.hour if twenty_hour_time > 12 twelve_hour_time = twenty_hour_time - 12 else twelve_hour_time = twenty_hour_time end twelve_hour_time.times do puts "DONG!" end end grandfather_clock
true
e60ce9c2f3df1813941d219590d80c538f532479
Ruby
dgriego/code-challenges
/hacker-rank/ruby/sock-merchant.rb
UTF-8
2,495
3.828125
4
[]
no_license
# integers represent sock colors # # this is represented as an array of integers where # each integer represents an individual sock # # large pile of socks that need to be matched, think laundry day.. ugghg that sucks # ok....fine, I'll pair the sucks # # the result should be a count of how many pairs of matching socks there are. # each sock is unique and can only be used in one pair, as sucks would # behave because we don't have sock cloning technology quite yet. # # Examples # # constraints: # 1 <= n <= 100, the sock count should be greater than equal to 1 and less than or equal to 100 # 1 <= ar[i], each Int:color must be greater or equal to 1 # # 5 socks # Array:[1, 3, 4, 2, 1] = Int:1 pair [(1, 1)] # # 3 socks # Array:[2, 2, 1] = Int:1 pair [(2, 2)] # # 8 socks # Array:[1, 1, 3, 3, 2, 2] = Int:3 pairs [(1, 1), (3, 3), (2, 2)] # # Data Structure # # because the colors will be integers within an array, we can naturally assume to loop # through each element in the array and validate a count # # my appraoch will be to use the array argument to loop through a collect counts of # each object in the array, which I can extract to produce a pairs count # # the 'counts' will be a hash of counts of each object in the array argument # # Algorithm # # check constraint, sock count argument # n >= 1 && n <= 100, # print message for correction and return 0 # # initialize empty counts hash # initialize pair_counts integer # # begin looping through colors # begin incrementing the count of each color by adding # the current object as a key in the hash with the value # being the number of occurences # # if any keys match current value? # update the hash where key exists by 1 # else # set the key in the hash and initialize to 1 # # here we should have a hash with counts # # Begin loop through hash # divide each count by 2 and increment the pair_counts with the result # the logic being that an number represents a 'pair' # # finally, # return pair_count def sockMerchant(n, ar) pair_value = 2 unless (n.between?(1, 100)) puts 'number of socks must be between 1 and 100' return 0 end color_counts = {} pairs_count = 0 ar.each do |color| if (color_counts.has_key? color) color_counts[color] += 1 else color_counts[color] = 1 end end color_counts.values.each do |count| pairs_count += count / pair_value end pairs_count end # sockMerchant(0, []) puts sockMerchant(5, [1, 3, 3, 2, 1])
true
75c3e9a657ae6e0f098a9add4d554949a21aa611
Ruby
guppy0356/rspec-receive
/user.rb
UTF-8
382
2.96875
3
[]
no_license
class User def initialize(name, age) @name = name @age = age end def insert postgresql.insert(attributes) end def attributes {name: @name, age: @age} end private def postgresql @postgresql ||= PostgreSql.new end end # Postgresql に接続するクライアント class PostgreSql def insert(attributes) # do something end end
true
d7fdf5741eac2dcad5effe45d3fb7f4bd7fe9174
Ruby
hellokenta1024/til
/algorithm/singly-linked-list-check-if-it-contains-circle.rb
UTF-8
1,081
4.40625
4
[ "MIT" ]
permissive
=begin You have a singly-linked list ↴ and want to check if it contains a cycle. A cycle occurs when a node’s @next points back to a previous node in the list. The linked list is no longer linear with a beginning and end—instead, it cycles through a loop of nodes. Write a method contains_cycle() that takes the first node in a singly-linked list and returns a boolean indicating whether the list contains a cycle. =end class LinkedListNode attr_accessor :value, :next def initialize(value) @value = value @next = nil end end def contains_cycle(first_node) checked_nodes = [first_node] next_node = first_node.next while next_node != nil return true if checked_nodes.include?(next_node) checked_nodes.push(next_node) next_node = next_node.next end return false end first_node = LinkedListNode.new("hara") node2 = LinkedListNode.new("kenta") node3 = LinkedListNode.new("kenta") node4 = LinkedListNode.new("kenta") first_node.next = node2 node2.next = node3 node3.next = node4 node4.next = node2 puts contains_cycle(first_node)
true
02e650ae4dd2c9ebdceaa9491838224b7ff41100
Ruby
vpnfpfvl/FBC_rubyTutorial
/CHAPTER04/chapter4-3q06.rb
UTF-8
39
2.84375
3
[]
no_license
array = [1, 3] array.unshift 1 p array
true
0def8de84d0095848b23527fe888e36acea99631
Ruby
mstmari/school-domain-v-000
/lib/school.rb
UTF-8
407
3.4375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# code here! require 'pry' class School attr_accessor :name, :roster def initialize(name) @name = name @roster = {} end def add_student (student_name, grade) roster[grade] ||= [] roster[grade] << student_name end def grade(grade) roster[grade] end def sort sorted_students = {} roster.each do |grade, student| sorted_students[grade] = student.sort end sorted_students end end
true
c12c001962e5cb46c33ee378768dfe408c941445
Ruby
phrase/phraseapp-ruby
/test/auth_test.rb
UTF-8
1,197
2.5625
3
[ "MIT" ]
permissive
require "minitest/autorun" require 'phraseapp-ruby/auth' describe PhraseApp::Auth::Credentials do let(:token) { "123456789" } let(:username) { "tom" } let(:password) { "secret-password" } let(:credentials) { PhraseApp::Auth::Credentials.new( token: token, username: username, password: password ) } it "host" do assert_equal "https://api.phraseapp.com", credentials.host end it "token" do assert_equal "123456789", credentials.token end it "username" do assert_equal "tom", credentials.username end it "password" do assert_equal "secret-password", credentials.password end it "validate!" do assert_equal nil, credentials.validate! end it "if no username or token given validate should raise" do invalid_credentials = PhraseApp::Auth::Credentials.new( token: "", username: "" ) assert_raises(PhraseApp::Auth::ValidationError) { invalid_credentials.validate! } end it "if not username or token given authenticate should raise" do nil_credentials = PhraseApp::Auth::Credentials.new assert_raises(PhraseApp::Auth::ValidationError) { nil_credentials.authenticate(nil) } end end
true
52287542d129db17177281774a6e58bdc4f12ea3
Ruby
yTakkar/Fun-With-Ruby
/strings.rb
UTF-8
339
3.65625
4
[]
no_license
str = "Hello, World!!" puts str.size puts str.include? "H" puts str.count "!" puts str.chop puts str.chomp "!!" puts str.upcase puts str.downcase puts str.delete "ll" str.each_char { |chr| puts chr } puts str.start_with?"d" puts str.end_with?"!!" puts str.replace "Hello, India!!" puts str.reverse str.split(", ").each do |i| puts i end
true
78d4404d303b09f897e3e760947195056d7feb28
Ruby
DaFaD/progetto_cyber_challenge
/test/models/user_studente_test.rb
UTF-8
6,805
2.625
3
[]
no_license
require 'test_helper' class UserStudenteTest < ActiveSupport::TestCase # test "the truth" do # assert true # end def setup @userStudente = UserStudente.new(name: "Matteo", surname: "Vari", email: "mattew98.01@gmail.com", username: "Mattew98-01", fiscalCode: "VRAMTT98M06C858Y", birthDay: Date.new(1998, 8, 6), password: "foobar", password_confirmation: "foobar") end test "should be valid" do assert @userStudente.valid? end test "name should be present" do @userStudente.name = " " assert_not @userStudente.valid? end test "surname should be present" do @userStudente.surname = "" assert_not @userStudente.valid? end test "email should be present" do @userStudente.email = " " assert_not @userStudente.valid? end test "username should be present" do @userStudente.username = " " assert_not @userStudente.valid? end test "fiscal code should be present" do @userStudente.fiscalCode = " " assert_not @userStudente.valid? end test "birth day should be present" do @userStudente.birthDay = nil assert_not @userStudente.valid? end test "name should not be too long" do @userStudente.name = "a" * 51 assert_not @userStudente.valid? end test "surname should not be too long" do @userStudente.surname = "a" * 51 assert_not @userStudente.valid? end test "email should not be too long" do @userStudente.email = "a" * 246 + "@gmail.com" assert_not @userStudente.valid? end test "username should not be too long" do @userStudente.username = "a" * 51 assert_not @userStudente.valid? end test "fiscal code should not be longer than 16 char" do @userStudente.fiscalCode = "a" * 17 assert_not @userStudente.valid? end test "fiscal code should not be shorter than 16 char" do @userStudente.fiscalCode = "a" * 15 assert_not @userStudente.valid? end test "email validation should accept valid addresses" do valid_addresses = %w[nome.85-92@gmail.com utente@gmail.it utente@gmail.com cognome.1749374@studenti.uniroma1.it] valid_addresses.each do |valid_address| @userStudente.email = valid_address assert @userStudente.valid?, "#{valid_address.inspect} should be valid" end end test "email validation should reject invalid addresses" do invalid_addresses = %w[user@example,com user_at_foo.org user.name@example. foo@bar_baz.com foo@bar+baz.com utente@hotmail.it utente@live.com nome.cognome@alice.com utente@gmail..com.] invalid_addresses.each do |invalid_address| @userStudente.email = invalid_address assert_not @userStudente.valid?, "#{invalid_address.inspect} should be invalid" end end test "fiscal code validation should accept valid codes" do valid_codes = %w[RSSMRC80A01H501W DVLFNC93M52F205E rssmrc80a01h501w dvlfnc93m52f205e RMCNTN01S07C858L rmcntn01s07c858l] valid_codes.each do |valid_code| @userStudente.fiscalCode = valid_code assert @userStudente.valid?, "#{valid_code.inspect} should be valid" end end test "fiscal code validation should reject invalid codes" do invalid_codes = %w[RSSMRC80901H501W DVLFNC9EM52F205E rssmrc80z01z501w dvlfnc93752f205e RMCNTN01S07W858L rmcntn01s0jc858l RS8MRC80A01H501W] invalid_codes.each do |invalid_code| @userStudente.fiscalCode = invalid_code assert_not @userStudente.valid?, "#{invalid_code.inspect} should be invalid" end end test "email addresses should be unique" do altroStudente = UserStudente.new(name: "Gianfranco", surname: "Verdi", email: "mattew98.01@gmail.com", username: "Giangi", fiscalCode: "GNFVRD00H04H501Q", birthDay: Date.new(2000, 6, 4), password: "foobar2", password_confirmation: "foobar2") @userStudente.save assert_not altroStudente.valid? end test "email addresses should be unique (case-insensitive)" do altroStudente = UserStudente.new(name: "Gianfranco", surname: "Verdi", email: "mattew98.01@gmail.com", username: "Giangi", fiscalCode: "GNFVRD00H04H501Q", birthDay: Date.new(2000, 6, 4), password: "foobar2", password_confirmation: "foobar2") altroStudente.email = @userStudente.email.upcase @userStudente.save assert_not altroStudente.valid? end test "email addresses should be saved as lower-case" do mixed_case_email = "Foo@GmaIL.CoM" @userStudente.email = mixed_case_email @userStudente.save assert_equal mixed_case_email.downcase, @userStudente.reload.email end test "usernames should be unique" do altroStudente = UserStudente.new(name: "Gianfranco", surname: "Verdi", email: "giangi@gmail.com", username: "Mattew98-01", fiscalCode: "GNFVRD00H04H501Q", birthDay: Date.new(2000, 6, 4), password: "foobar2", password_confirmation: "foobar2") @userStudente.save assert_not altroStudente.valid? end test "usernames should be unique (case-insensitive)" do altroStudente = UserStudente.new(name: "Gianfranco", surname: "Verdi", email: "giangi@gmail.com", username: "Mattew98-01", fiscalCode: "GNFVRD00H04H501Q", birthDay: Date.new(2000, 6, 4), password: "foobar2", password_confirmation: "foobar2") altroStudente.username = @userStudente.username.upcase @userStudente.save assert_not altroStudente.valid? end test "usernames should be saved as lower-case" do mixed_case_username = "PrOVa" @userStudente.username = mixed_case_username @userStudente.save assert_equal mixed_case_username.downcase, @userStudente.reload.username end test "fiscal codes should be unique" do altroStudente = UserStudente.new(name: "Gianfranco", surname: "Verdi", email: "giangi@gmail.com", username: "Giangi", fiscalCode: "VRAMTT98M06C858Y", birthDay: Date.new(2000, 6, 4), password: "foobar2", password_confirmation: "foobar2") @userStudente.save assert_not altroStudente.valid? end test "fiscal codes should be unique (case-insensitive)" do altroStudente = UserStudente.new(name: "Gianfranco", surname: "Verdi", email: "giangi@gmail.com", username: "Giangi", fiscalCode: "vramtt98m06c858y", birthDay: Date.new(2000, 6, 4), password: "foobar2", password_confirmation: "foobar2") altroStudente.fiscalCode = @userStudente.fiscalCode.upcase @userStudente.save assert_not altroStudente.valid? end test "fiscal codes should be saved as lower-case" do mixed_case_fiscalCode = "RsSmRC80A01H501w" @userStudente.fiscalCode = mixed_case_fiscalCode @userStudente.save assert_equal mixed_case_fiscalCode.downcase, @userStudente.reload.fiscalCode end test "password should have a minimum length of 6 characters" do @userStudente.password = @userStudente.password_confirmation = "a" * 5 assert_not @userStudente.valid? end test "authenticated? should return false for a user with nil digest" do assert_not @userStudente.authenticated?(:remember, '') end end
true
b59ca62afe5fba2bac72eac67fae70f9f4f79250
Ruby
Alicespyglass/fizzbuzz
/lib/fizzbuzz.rb
UTF-8
206
3.484375
3
[]
no_license
def fizzbuzz(number) # only return fizz if num = 3 if (number % 3 == 0) && (number % 5 == 0) 'fizzbuzz' elsif number % 3 == 0 'fizz' elsif number % 5 == 0 'buzz' else number end end
true
6a6ebb4bb6c15fe2e62c350dea4ebbda74011037
Ruby
bitdomo/bs2
/Scripts/_.50.rb
UTF-8
4,096
2.9375
3
[]
no_license
#============================================================================== # ■ RGSS3 誤選択防止処理 Ver1.01 by 星潟 #------------------------------------------------------------------------------ # イベントで選択肢を選ぶ際に # 選択肢ウィンドウインデックスを-1にし # そのままでは選択できない状態にします。 # 上下の方向キーを押す事で、はじめて選択可能となります。 # これにより、決定キー連打による誤選択を防止することが出来ます。 #------------------------------------------------------------------------------ # Ver1.01 非選択状態で上キーを押した際に、下から二番目になる問題を修正。 #============================================================================== module OUT_CURSOR #誤選択防止用のスイッチIDを指定します。 #ここで指定したIDのスイッチがONの時、誤選択防止処理が有効になります。 #0にした場合は常時防止処理が行われ、TYPE2の設定が無意味になります。 S_ID = 0 #誤選択防止の非選択状態で決定キーを押した際どうするかを指定します。 #(true:何もしない/false:ブザーを鳴らす) TYPE1 = true #誤選択防止用のスイッチが誤選択防止処理後どうするかを決定します。 #(true:何もしない/false:falseに戻す) TYPE2 = false end class Window_ChoiceList < Window_Command #-------------------------------------------------------------------------- # 入力処理の開始 #-------------------------------------------------------------------------- alias start_out_cursor start def start #誤選択防止処理のフラグを取得。 flag = out_cursor_flag #フラグに応じて処理内容を決定。 @out_cursor = flag #本来の処理を実行。 start_out_cursor #処理内容を初期化。 @out_cursor = false end #-------------------------------------------------------------------------- # 誤選択防止フラグ #-------------------------------------------------------------------------- def out_cursor_flag #指定スイッチIDが0の場合はtrueを返す。 return true if OUT_CURSOR::S_ID == 0 #指定スイッチがONの時、設定に応じて該当スイッチをtrueにしつつ #trueを返す。 if $game_switches[OUT_CURSOR::S_ID] $game_switches[OUT_CURSOR::S_ID] = false unless OUT_CURSOR::TYPE2 return true end #falseを返す。 false end #-------------------------------------------------------------------------- # 項目の選択 #-------------------------------------------------------------------------- alias select_out_cursor select unless $! def select(index) #処理内容を分岐。 @out_cursor ? select_out_cursor(-1) : select_out_cursor(index) end #-------------------------------------------------------------------------- # カーソルを上に移動 #-------------------------------------------------------------------------- alias cursor_up_out_cursor cursor_up unless $! def cursor_up(wrap = false) #非選択状態の場合は一旦0にしておく。 @index = 0 if @index == -1 #本来の処理を実行。 cursor_up_out_cursor(wrap) end #-------------------------------------------------------------------------- # 決定ボタンが押されたときの処理 #-------------------------------------------------------------------------- alias process_ok_out_cursor process_ok unless $! def process_ok #インデックスが-1の場合、設定内容次第では何もしない。 return if self.index == -1 && OUT_CURSOR::TYPE1 #本来の処理を実行。 process_ok_out_cursor end end
true
3c0f35fe6e2d3d134dbffc90afb99a7398f948c6
Ruby
NaCl-Ltd/yarunee-2018
/lib/nanobot/model.rb
UTF-8
2,686
3.078125
3
[]
no_license
class Nanobot # 形状データを表すクラス class Model # .mdlファイルを読み込む def self.load(mdl_path) new(File.binread(mdl_path)) end # 全マスがVoidなモデルを生成する def self.empty(resolution) raise ArgumentError if resolution <= 0 b = "0" * resolution**3 mdl = [resolution].pack("C*") + [b].pack("b*") new(mdl) end # mdl: .mdlファイルの中身(String) def initialize(mdl) m = mdl.unpack("C*") @resolution = m[0] b = mdl.unpack("b*")[0] @voxels = b[8..-1] calc_bounding_box end attr_reader :max_y, :min_x, :min_z, :max_x, :max_z, :x_size, :y_size, :z_size # マップサイズを返す def resolution @resolution end # ある座標にmatterがあるとき真を返す def [](x, y, z) v = @voxels[x * @resolution * @resolution + y * @resolution + z] !v.nil? && v != "0" end def to_source s = Array.new(@resolution) { Array.new(@resolution) { Array.new(@resolution) }} @resolution.times do |x| @resolution.times do |y| @resolution.times do |z| s[y][z][x] = @voxels[x * @resolution * @resolution + y * @resolution + z] end end end s.reverse! @resolution.times do |y| s[y] = s[y].reverse @resolution.times do |z| s[y][z] = s[y][z].join end s[y] = s[y].join("\n") end s.join("\n\n") end # ひさし(突き出している部分)があるとき真を返す def has_eaves? (1..@resolution-1).any? { |y| (0..@resolution-1).any? { |x| (0..@resolution-1).any? { |z| self[x, y, z] ? (self[x, y-1, z] ? false : true) : false } } } end private # bounding boxを計算する def calc_bounding_box @min_x = (0...resolution).find{|x| (0...resolution).any?{|y| (0...resolution).any?{|z| self[x, y, z] }} } @min_z = (0...resolution).find{|z| (0...resolution).any?{|x| (0...resolution).any?{|y| self[x, y, z] }} } @max_x = (0...resolution).to_a.reverse.find{|x| (0...resolution).any?{|y| (0...resolution).any?{|z| self[x, y, z] }} } @max_z = (0...resolution).to_a.reverse.find{|z| (0...resolution).any?{|x| (0...resolution).any?{|y| self[x, y, z] }} } @max_y = (0...resolution).to_a.reverse.find{|y| (0...resolution).any?{|x| (0...resolution).any?{|z| self[x, y, z] }} } @x_size = @max_x - @min_x + 1 @y_size = @max_y + 1 @z_size = @max_z - @min_z + 1 end end end
true
dc835ca9a0307a60f78590702d172a6577661d85
Ruby
cdcarter/gingko
/app/models/bracket.rb
UTF-8
2,332
3.03125
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
require 'ostruct' require 'facets/array' class Bracket < ActiveRecord::Base has_many :game_assignments has_many :games has_many :bracketings has_many :teams, :through => :bracketings has_many :room_assignments has_many :rooms, :through => :room_assignments belongs_to :tournament belongs_to :phase def generate_round_robin b = OpenStruct.new b.rooms = self.rooms.map {|x| x.id} if self.teams.size % 2 == 1 self.teams << Team.create(:name => "bye", :tournament => self.tournament) r = Room.create(:name => "bye", :tournament => self.tournament) self.rooms << r end b.rounds = self.teams.size - 1 b.games = Hash.new b.teams = self.teams n = (self.teams.size / 2) - 1 m = self.teams.size - 1 1.upto(b.rounds) do |round| 0.upto(n) do |k| team_1 = b.teams[k] team_2 = b.teams[m - k] if [team_1, team_2].map{|t| t.name}.include? "bye" thisgame = Game.new thisgame.round = round thisgame.tournament = self.tournament thisgame.bracket = self thisgame.phase = self.phase thisgame.room = self.rooms.find(:first, :conditions => ["name =?","bye"]) [team_1,team_2].map {|t| GameAssignment.create(:team=>t, :bracket=>self, :tournament=>self.tournament, :game=>thisgame) } thisgame.save self.games << thisgame else room = b.rooms.pop thisgame = Game.new thisgame.round = round thisgame.tournament = self.tournament thisgame.bracket = self thisgame.phase = self.phase thisgame.room_id = room [team_1,team_2].map {|t| GameAssignment.create(:team=>t, :bracket=>self, :tournament=>self.tournament, :game=>thisgame) } thisgame.save self.games << thisgame b.rooms.unshift(room) end end b.teams = [b.teams[0]] + b.teams[1,m].rotate # I think this may be the best that can be done for eight teams if round % 3 == 0 b.rooms = b.rooms.rotate else b.rooms = b.rooms.rotate.rotate end # ideal except for you know what #bracket.rooms = bracket.rooms.rotate.rotate end return self.games end end
true
46886832f262a70a45bbfe47ecd339d191c9069c
Ruby
skyfox93/week-1-group-review-nyc-web-102918
/review-question-3.rb
UTF-8
1,184
3.4375
3
[]
no_license
# begin to build a simple program that models Instagram # you should have a User class, a Photo class and a comment class class User attr_accessor :name def initialize(name) @name=name end end ##end user class class Photo attr_accessor :user def initialize(user) @user=user end def make_comment(comment) if self.user Comment.new(comment,self,self.user) else Comment.new(comment,self) end def comments Comment.all.select{|comment|comment.photo==self} end end #end photo class class Comment attr_accessor :comment, :user :photos @@all=[] def initialize(comment,user,photo) @comment=comment @user=user @photo=photo end def self.all @@all end sandwich_photo = Photo.new(user) sophie = User.new("Sophie") sandwich_photo.user = sophie sandwich_photo.user.name # => "Sophie" user.photos # => [#<Photo:0x00007fae2880b370>] sandwich_photo.comments # => [] sandwich_photo.make_comment("this is such a beautiful photo of your lunch!! I love photos of other people's lunch") sandwich_photo.comments # => [#<Comment:0x00007fae28043700>] Comment.all #=> [#<Comment:0x00007fae28043700>]
true
dc5cb81bebf5792e3240094ad318bdcd73c1cbb5
Ruby
CeliaTHP/Day2
/exo_07_a.rb
UTF-8
148
3.09375
3
[]
no_license
puts "Bonjour, c'est quoi ton blase ?" #récupère la variable user_name, qui sera donnée par l'utilisateur. user_name = gets.chomp puts user_name
true
395a5901ef89370c47a0ef2899ba9c01e1fe45d0
Ruby
abbshr/Kedi
/lib/kedi/container.rb
UTF-8
933
2.671875
3
[ "MIT" ]
permissive
module Kedi class Container attr_reader :pipelines def initialize # 每个 pipe 按 unique name 装入 @pipelines = {} end # 激活所有 pipes def run @pipelines.each &:streaming end def pause(id = nil) if id @pipelines[id]&.pause else @pipelines.each &:pause end end def resume(id = nil) if id @pipelines[id]&.resume else @pipelines.each &:resume end end def shutdown @pipelines.each &:stop end def restart @pipelines.each &:restart end def reload(id = nil) if id @pipelines[id]&.reload else @pipelines.each &:reload end end def remove(id) @pipelines.delete id end def add(pipeline) @pipelines[pipeline.name] = pipeline end def stats # TODO # 内部状态统计 end end end
true
7db0470508eab41fb86a591846442a2b9ebe36a0
Ruby
droptheplot/apipony
/spec/apipony/parameter_spec.rb
UTF-8
1,109
2.78125
3
[ "MIT" ]
permissive
describe Apipony::Parameter do let(:parameter) { Apipony::Parameter.new(:name) } describe '#type' do it 'returns :string by default' do expect(parameter.type).to eq(:string) end end describe '#required' do it 'returns false by default' do expect(parameter.required).to be false end end describe '#required?' do it 'should be an alias to #required' do expect(parameter.method(:required?).original_name).to eq( parameter.method(:required).original_name ) end end describe '#==' do example_options = { example: :example, description: :description, type: :integer, required: true } it 'returns true if objects are equal' do one = Apipony::Parameter.new(:name, example_options) another = Apipony::Parameter.new(:name, example_options) expect(one).to eq(another) end it 'returns false if objects are not equal' do one = Apipony::Parameter.new(:name, example_options) another = Apipony::Parameter.new(:age) expect(one).not_to eq(another) end end end
true
ee1154672fc424d3928deb717cd4dd4f5d51cfe6
Ruby
Rob-rls/geckoboard-techtest
/lib/geckoboard_request.rb
UTF-8
869
2.78125
3
[]
no_license
require 'geckoboard' require 'date' class GeckoboardRequest def initialize @client = Geckoboard.client('e70c81cd6610f867dd72bcc56d8b1b47') check_api_key load_dataset end def update_dataset(weather_data) @dataset.put(weather_data) end private def check_api_key puts "API Key is Valid" if @client.ping end def load_dataset @dataset = @client.datasets.find_or_create('london.weather', fields: [ Geckoboard::DateTimeField.new(:timestamp, name: 'Time'), Geckoboard::NumberField.new(:temp, name: 'Temperature'), Geckoboard::NumberField.new(:windspeed, name: 'Wind Speed'), Geckoboard::NumberField.new(:winddirection, name: 'Wind Direction'), Geckoboard::PercentageField.new(:humidity, name: 'Humidity'), Geckoboard::NumberField.new(:rain, name: 'Rain Volume') ]) end end
true
5155ada31007c06e90eee2d1238babbf6f9feb6d
Ruby
emill3000/my-collect-v-000
/lib/my_collect.rb
UTF-8
132
3.265625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def my_collect(collection) i = 0 list = [] while i < collection.length list << yield(collection[i]) i += 1 end list end
true
5d3e9f398e06b2d322a783ceceb661208a13cf29
Ruby
jaredonline/baconator
/app/models/bacon/array.rb
UTF-8
726
3.6875
4
[]
no_license
# Special array class for quick insertion of sorted elements # specifically for sorting BaconNodes by their depth. # This way we can #shift the first one off the array and be # confident we're searching from the best position # class Bacon::Array < Array def self.[](*array) self.new(array) end def initialize(array = nil) super(array.sort_by(&:depth)) if array end def <<(value) insert(index_for_value(value.depth), value) end private def index_for_value(value) index = 0 max = length - 1 while index <= max lookup = (max + index) / 2 if value < self[lookup].depth max = lookup - 1 else index = lookup + 1 end end index end end
true
7204ab2eeec26b1b79f66faeee6f0ba85c51145c
Ruby
tiyd-ruby-2016-09/text_miner
/spec/separator_spec.rb
UTF-8
5,070
3.140625
3
[]
no_license
require 'separator' describe Separator do before do @s = Separator.new end describe '#words' do it 'returns an Array of words' do expect(@s.words('hello')).to eq ['hello'] expect(@s.words('hello world')).to eq ['hello', 'world'] expect(@s.words('raggggg hammer dog')).to eq ['raggggg', 'hammer', 'dog'] expect(@s.words('18-wheeler tarbox')).to eq ['18-wheeler', 'tarbox'] expect(@s.words('12')).to eq nil end end describe '#phone_number' do it 'returns a hash with phone number and area code' do expect(@s.phone_number('919-555-1212')).to eq({'area_code': '919', 'number': '555-1212'}) expect(@s.phone_number('(919) 555-1212')).to eq({'area_code': '919', 'number': '555-1212'}) expect(@s.phone_number('9195551212')).to eq({'area_code': '919', 'number': '555-1212'}) expect(@s.phone_number('919.555.1212')).to eq({'area_code': '919', 'number': '555-1212'}) expect(@s.phone_number('919 555-1212')).to eq({'area_code': '919', 'number': '555-1212'}) expect(@s.phone_number('555-121')).to eq nil end end describe '#money' do it 'returns a hash with currency symbol and amount' do expect(@s.money('$4')).to eq({'currency': '$', 'amount': 4.0}) expect(@s.money('$19')).to eq({'currency': '$', 'amount': 19.0}) expect(@s.money('$19.00')).to eq({'currency': '$', 'amount': 19.0}) expect(@s.money('$3.58')).to eq({'currency': '$', 'amount': 3.58}) expect(@s.money('$1000')).to eq({'currency': '$', 'amount': 1000.0}) expect(@s.money('$1000.00')).to eq({'currency': '$', 'amount': 1000.0}) expect(@s.money('$1,000')).to eq({'currency': '$', 'amount': 1000.0}) expect(@s.money('$1,000.00')).to eq({'currency': '$', 'amount': 1000.0}) expect(@s.money('$5,555,555')).to eq({'currency': '$', 'amount': 5555555.0}) expect(@s.money('$5,555,555.55')).to eq({'currency': '$', 'amount': 5555555.55}) expect(@s.money('$45,555,555.55')).to eq({'currency': '$', 'amount': 45555555.55}) expect(@s.money('$456,555,555.55')).to eq({'currency': '$', 'amount': 456555555.55}) expect(@s.money('$1234567.89')).to eq({'currency': '$', 'amount': 1234567.89}) expect(@s.money('$12,34')).to eq nil expect(@s.money('$1234.9')).to eq nil expect(@s.money('$1234.999')).to eq nil expect(@s.money('$')).to eq nil expect(@s.money('31')).to eq nil expect(@s.money('$$31')).to eq nil end end describe '#zipcode' do it 'returns a hash with five digit zip code and plus four if exists' do expect(@s.zipcode('63936')).to eq({'zip': '63936', 'plus4': nil}) expect(@s.zipcode('50583')).to eq({'zip': '50583', 'plus4': nil}) expect(@s.zipcode('06399')).to eq({'zip': '06399', 'plus4': nil}) expect(@s.zipcode('26433-3235')).to eq({'zip': '26433', 'plus4': '3235'}) expect(@s.zipcode('64100-6308')).to eq({'zip': '64100', 'plus4': '6308'}) expect(@s.zipcode('7952')).to eq nil expect(@s.zipcode('115761')).to eq nil expect(@s.zipcode('60377-331')).to eq nil expect(@s.zipcode('8029-3924')).to eq nil end end describe '#date' do it 'returns a hash of day, month, and year' do expect(@s.date('9/4/1976')).to eq({'month': 9, 'day': 4, 'year': 1976}) expect(@s.date('1976-09-04')).to eq({'month': 9, 'day': 4, 'year': 1976}) expect(@s.date('2015-01-01')).to eq({'month': 1, 'day': 1, 'year': 2015}) expect(@s.date('02/15/2004')).to eq({'month': 2, 'day': 15, 'year': 2004}) expect(@s.date('9/4')).to eq nil expect(@s.date('2015')).to eq nil end end # ADVANCED MODE BEGINS describe '#date' do it 'returns a hash of day, month, year - advanced' do expect(@s.date('2014 Jan 01')).to eq({'month': 1, 'day': 1, 'year': 2014}) expect(@s.date('2014 January 01')).to eq({'month': 1, 'day': 1, 'year': 2014}) expect(@s.date('Jan. 1, 2015')).to eq({'month': 1, 'day': 1, 'year': 2015}) expect(@s.date('07/40/2015')).to eq nil expect(@s.date('02/30/2015')).to eq nil end end describe '#email' do it 'returns the parts of an email address' do expect(@s.email('stroman.azariah@yahoo.com')).to eq({ 'local': 'stroman.azariah', 'domain': 'yahoo.com' }) expect(@s.email('viola91@gmail.com')).to eq({ 'local': 'viola91', 'domain': 'gmail.com' }) expect(@s.email('legros.curley')).to eq nil end end describe '#address' do it 'returns a hash of address info' do expect(@s.address('368 Agness Harbor Port Mariah, MS 63293')).to eq({ 'address': '368 Agness Harbor', 'city': 'Port Mariah', 'state': 'MS', 'zip': '63293', 'plus4': None }) expect(@s.address('8264 Schamberger Spring, Jordanside, MT 98833-0997')).to eq({ 'address': '8264 Schamberger Spring', 'city': 'Jordanside', 'state': 'MT', 'zip': '98833', 'plus4': '0997' }) expect(@s.address('Lake Joellville, NH')).to eq nil end end end
true
8af3af050c9fba65226f2234ba103069933fe8bb
Ruby
skarger/rails-deadlock-example
/app/models/parallel_mapper.rb
UTF-8
480
2.71875
3
[]
no_license
# uncommenting will make things work #require_relative './collaborator_one.rb' #require_relative './collaborator_two.rb' class ParallelMapper def work_in_threads data = [1, 2, 3] Parallel.map(data, in_threads: 3) do |item| ActiveRecord::Base.connection_pool.with_connection do |conn| puts "ParallelMapper instance: work_in_threads: #{item}" collaborator_one = CollaboratorOne.new(item) collaborator_one.perform end end end end
true
190f47306c54544a7df5342f0c42a6ced852bbae
Ruby
avinoth/slack-snippet
/app.rb
UTF-8
4,592
2.734375
3
[ "MIT" ]
permissive
require 'sinatra' require 'active_support/json/encoding' require 'json' require 'sinatra/activerecord' require './config/environments' require './models/user' require './models/snippet' get '/gateway' do message = "" @trigger = params[:command] @user = User.find_by(slack_user_id: params[:user_id]) if @user and @user.token != params[:token] message += "Unauthorized Request." return message elsif !@user @user = User.create(name: params[:user_name], slack_user_id: params[:user_id], token: params[:token]) message += "Welcome #{@user.name} to snippy :tada: \n" end command = extract_content params[:text] unless command[:success] message += command[:message] return message end if command[:content].present? title = command[:content][0].strip.downcase snippet = command[:content][1] end case command[:action] when '-n' @snippet = @user.snippets.find_by(title: title) if @snippet message += duplicate_entry title else @snippet = @user.snippets.new({title: title, snippet: snippet.strip}) message += save_snippet end when '-g' @snippet = @user.snippets.find_by(title: title) unless @snippet message += not_found_msg title else message += @snippet.snippet end when '-e' @snippet = @user.snippets.find_by(title: title) unless @snippet message += not_found_msg title else if command[:tag] if @user.snippets.find_by(title: snippet) message += duplicate_entry snippet else @snippet.title = snippet.strip message += save_snippet end else @snippet.snippet = snippet.strip message += save_snippet end end when '-d' @snippet = @user.snippets.find_by(title: title) unless @snippet message += not_found_msg title else @snippet.destroy message += "Snippet is successfully destroyed. It is un-recoverable." end when '-s' query = title if @user.snippets.find_by(title: query) message += "You have a title with exact match of your search query. If you intend to get the snippet try `#{@trigger} -g #{query}` command instead." end results = @user.snippets.where("title ILIKE ? OR snippet ILIKE ?", "%#{query}%", "%#{query}%") if results.present? message += "Your Search results:- \n " + results.map.with_index {|s, i| "#{i+1}. #{s.title} - #{truncate(s.snippet, 30)}"}.join("\n") else message += "Your Search query didn't yield any results. Try again with different keywords." end when '-r' if @user.snippets.present? message += "Total Snippets saved: #{@user.snippets.count}n \n" snippets = @user.snippets.order('updated_at desc') message += "Last 3 snippets updated, \n" message += snippets.limit(3).map.with_index {|s, i| "#{i+1}. #{s.title} - #{s.updated_at.strftime('%F %H:%M')}"}.join("\n") else message += "You don't have any snippets created. Create one now by `-n title -c content" end end message end def extract_content text keywords = {"-n" => 2, "-g" => 1, "-e" => 2, "-d" => 1, "-s" => 1, "-r" => 0} action = text[0..1] if !keywords.keys.include?(action) return {success: false, message: "Invalid Command. Valid commands are `#{keywords.keys.join(", ")}`"} end if text.include? " -t " command = text.gsub(action, "").strip.split(" -t ") tag = true else command = text.gsub(action, "").strip.split(" -c ") tag = false end if keywords[action] != command.length return {success: false, message: "Invalid Format. Valid format are \n `-n title -c content`, \n `-g title`, \n `-s query`, \n `-e title -c newContent` OR `-e title -t newTitle `, \n `-d title`"} else return {success: true, action: action, content: command, tag: tag} end end def not_found_msg title "Unable to find #{title}. Check if spelling is correct. You can search for snippets instead by `#{@trigger} -s #{title}`" end def save_snippet if @snippet.save! return "Snippet saved successfully. You can access it by `#{@trigger} -g #{@snippet.title}`. \n" else return "There was some error saving the snippet. Please try again." end end def truncate(content, max=10) content.length > max ? "#{content[0...max]}..." : content end def duplicate_entry title "Snippet already with the name #{title} exists. If you are trying to edit use `#{@trigger} -e #{title}`" end
true
7fdd438bd79d763a9a093617fd550dd060da173b
Ruby
hyzs25/homework
/ruby/human.rb
UTF-8
1,430
4.125
4
[]
no_license
#module 理解为一组方法的集合 #include module表示将module里的所有方法都定义成class的instance mathod module Puruanimal def blood 'warm' end def eat_milk? true end end module Fish def blood 'cold' end def eat_milk? false end end class Human include Puruanimal attr_accessor :name, :age attr_reader :sex #def sex @sex = sex attr_writer :income #def income=(new_income) def initialize(name,age,sex,income=nil) @name = name @age = age @sex = sex end def introduce() print "I am #{@name},I am #{@age} years old, I am a #{@sex}\n" end #类方法,无须实例化,直接调用· def Human.home 'earth' end def self.attr() # = Human.attr "eat,sleep" end #================================ end class Man < Human attr_accessor :huzi def initialize(name,age,huzi) super(name,age,'man')#调用父类的同名方法 @huzi = huzi end end class Woman < Human def initialize(name,age) super(name,age,'woman') end end class Liyu include Fish end liyu = Liyu.new() puts liyu.blood puts liyu.eat_milk? # tom = Human.new('tom',30,'man') # tom.introduce # tom.name="tommy" # tom.age="35" # puts tom.sex # tom.income= 5000 # tom.introduce tom = Man.new('tom',30,'white') tom.introduce puts tom.huzi kitty = Woman.new('kitty',25) kitty.introduce
true
0e6e4945a2e9a458a2b50b1612d1e35e64187a4a
Ruby
maedi/ticket_terminal
/helpers/app_helper.rb
UTF-8
979
2.703125
3
[]
no_license
module AppHelper # Project path. @@root = nil ## # Expose app to components. # # @param app [App] The main Sinatra::Base instance. ## def self.set_app(app) @@app ||= app end ## # Expose session to components. # # @param session [Session] The server session. ## def self.set_session(session) @@session ||= session end ## # Load database from JSON file. # # @param root [String] Absolute path to the root of the project. # @return [Hash] The database. ## def self.load_db(root) @@db ||= begin # Get data. tickets_file = File.read(File.join(root, 'data/tickets.json')) tickets_data = JSON.parse(tickets_file) # Build database. db = { :tickets => {} } tickets_data.each do |ticket| db[:tickets][ticket['uuid']] = { :name => ticket['name'], :price => ticket['price'] } end # Return database. db end end end
true
4f01c4df7a775ecdcffb0d2c8136e5fb9dfa082b
Ruby
paulor8bit/find-the-number
/main.rb
UTF-8
4,127
3.6875
4
[]
no_license
def boas_vindas puts puts " P /_\ P " puts " /_\_|_|_/_\ " puts " n_n | ||. .|| | n_n Bem vindo ao " puts " |_|_|nnnn nnnn|_|_| Jogo de Adivinhação!" puts " |' ' | |_| |' ' | " puts " |_____| ' _ ' |_____| " puts " \__|_|__/ " puts puts "Qual é o seu nome?" nome = gets.strip puts "\n\n\n\n\n\n" puts "Começaremos o jogo para você, #{nome}" nome #manda nome para fora do def end def pede_dificuldade puts "Qual o nivel de dificuldade? 1: Facil, 2: Quase Facil, 3: Medio, 4: Dificil a 5: Super Dificil" dificuldade = gets.to_i end def sorteia_numero_secreto (dificuldade) #sorteado sai do def sorteando_numero case dificuldade #caso dificuldade tenha valor 1 a 5 when 1 maximo = 10 when 2 maximo = 30 when 3 maximo = 100 when 4 maximo = 150 else maximo = 200 end puts "Escolhendo um número secreto entre 1 e #{maximo}..." sorteado = rand(maximo) + 1 #faz sortear numero de 1 a 200 puts "Escolhido... que tal adivinhar hoje nosso número secreto?" sorteado #manda para script principal #numero acima para sair do def end def pede_um_numero (chutes, tentativa, limite_de_tentativas) #tentativa, limite e chutes entra e chute sai do pede_um_numero puts "\n\n\n\n\n\n" puts "Tentativa #{tentativa} de #{limite_de_tentativas}" puts "Chutes até agora: #{chutes}"#impressao do array porem esta com erro puts "Entre com um numero" chute = gets.strip puts "Sera que você acertou?" + chute chute # manda para script principal end def verifica_se_acertou (numero_secreto, chute) acertou = numero_secreto == chute.to_i if acertou ganhou return true #Se acertou ja sai deste DEF end maior = numero_secreto > chute.to_i if maior puts "o numero é maior" else puts "O numero é menor" end false #aqui também é um return false end def ganhou puts puts " OOOOOOOOOOO " puts " OOOOOOOOOOOOOOOOOOO " puts " OOOOOO OOOOOOOOO OOOOOO " puts " OOOOOO OOOOO OOOOOO " puts " OOOOOOOO # OOOOO # OOOOOOOO " puts " OOOOOOOOOO OOOOOOO OOOOOOOOOO " puts "OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO " puts "OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO " puts "OOOO OOOOOOOOOOOOOOOOOOOOOOOOO OOOO " puts " OOOO OOOOOOOOOOOOOOOOOOOOOOO OOOO " puts " OOOO OOOOOOOOOOOOOOOOOOOO OOOO " puts " OOOOO OOOOOOOOOOOOOOO OOOO " puts " OOOOOO OOOOOOOOO OOOOOO " puts " OOOOOO OOOOOO " puts " OOOOOOOOOOOO " puts puts " Acertou! " puts end def joga (nome, dificuldade) numero_secreto = sorteia_numero_secreto dificuldade pontos_ate_agora = 1000 limite_de_tentativas = 5 chutes = [] #array for tentativa in 1..limite_de_tentativas chute = pede_um_numero chutes, tentativa, limite_de_tentativas #Pegar e mandar dados do Def pede_um_numero chutes << chute # Contador para o array e size para ver o tamanho da array #total_de_chutes += 1 # Contador para o array total_de_chutes = total_de_chutes + 1 pontos_a_perder = (chute.to_i - numero_secreto.to_i).abs / 2.0 # .abs transforma em numero positivo ou usar if abaixo #if pontos_a_perder < 0 # pontos_a_perder = (pontos_a_perder * (-1)) #end pontos_ate_agora -= pontos_a_perder #é igual a pontos_ate_agora = pontos_ate_agora - pontos_a_perder if verifica_se_acertou numero_secreto, chute break end end puts "Você ganhou #{pontos_ate_agora} de pontos" puts "O numero certo era: #{numero_secreto} " end def nao_quer_jogar? puts "Deseja jogar novamente? (S/N)" quero_jogar = gets.strip nao_quero_jogar = quero_jogar.upcase == "N" #upcase deixa o sempre em maiusculo end nome = boas_vindas dificuldade = pede_dificuldade loop do joga nome, dificuldade break if nao_quer_jogar? end
true
8dbda0887fd629c18d9bab166670c7b1a7976fbf
Ruby
flawrencis/CodeLessons
/Basics/RubyBasics/personal_chef.rb
UTF-8
1,391
3.765625
4
[]
no_license
class PersonalChef def make_toast(color) if color.nil? puts "How am I supposed to do that?!?" else puts "Making your toast #{color}" end return self end def make_eggs(quantity) quantity.times do puts "Making an egg." end puts "I'm done!" return self end def make_milkshake(flavor) puts "Making your Milkshake #{flavor}!" return self end def good_morning today = Date.today.strftime('%A') day_of_year = Date.today.yday puts "Hey! Happy #{today}! It is the #{day_of_year} day in the calendar!" end def gameplan(meals) meals.each do |meal| puts "We'll have #{meal}..." end all_meals = meals.join(", ") puts "In summary: #{all_meals}" end def inventory produce = {apples: 3, oranges: 1, carrots: 12} produce.each do |item, quantity| puts "There are #{quantity} #{item} in the fridge." end end def water_status(minutes) if minutes < 7 puts "The water is not boiling yet" elsif minutes == 7 puts "It's just barely boiling" elsif minutes == 8 puts "It's boiling!" else puts "Hot! Hot! hot!" end return self end def countdown(counter) until counter == 0 puts "The counter is #{counter}" counter = counter - 1 end return self end end class Butler def open_front_door puts "Opening front door" end def open_door(door_name) puts "Opening the #{door_name} door!" end end
true
7b720a1522575b7e79b2af9a0867fa321f532a16
Ruby
eslamelkholy/Ruby-Codewars-Problem-Solving
/17-facebook like system.rb
UTF-8
485
3.65625
4
[]
no_license
def likes(names) if (names.length == 0) return "no one likes this" elsif (names.length == 1) return names[0] + " likes this" elsif (names.length == 2) return names[0] + " and " + names[1] +" like this" elsif (names.length == 3) return names[0] + ", "+ names[1] + " and " + names[2] +" like this" else return names[0] + ", " + names[1] +" and " + (names.length - 2).to_s + " others like this" end end
true
9dc397a926feecb5e04e65ca573c2cf7081db9cb
Ruby
radioactive001/learn_ruby
/06_timer/timer.rb
UTF-8
267
3.109375
3
[]
no_license
class Timer attr_accessor :seconds, def initialize @seconds=0 end #seconds def time_string s=@seconds%60 m=@seconds/60 h=m/60 m=m%60 @time_string="%02d:%02d:%02d" %[h,m,s] end #time_string end #class
true
10a2c625d8697974fb54161eb950995b7396322a
Ruby
c1505/game-chooser
/app/models/search.rb
UTF-8
774
2.765625
3
[]
no_license
class Search # Searches the google api specifically to boardgamegeek.com and returns JSON. def initialize(query) @query = query @api_key = Rails.application.secrets.google_api_key @url = "https://www.googleapis.com/customsearch/v1?key=#{@api_key}&cx=006396486437962354856:dhkps_7te2y&q=#{@query}" end def link results = fetch.parsed_response["items"] if results results.first["link"] else "" end end def game_id if link.include?("boardgamegeek.com/boardgame") link[/\d+/] end # FIXME validate that this is a digit # FIXME should this be an error message that tells me that no game was found end private def fetch encoded_url = URI.encode(@url) HTTParty.get(encoded_url) end end
true
5a5649c9b0fec9464b687831063f35be198f0694
Ruby
Tomistong/Leetcode-Ruby-1
/hard-ruby/315-count-smaller-numbers-after-self.rb
UTF-8
791
4.09375
4
[]
no_license
# You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i]. # Example: # Input: [5,2,6,1] # Output: [2,1,1,0] # Explanation: # To the right of 5 there are 2 smaller elements (2 and 1). # To the right of 2 there is only 1 smaller element (1). # To the right of 6 there is 1 smaller element (1). # To the right of 1 there is 0 smaller element. def count_smaller(nums) index_to_num_hash = Hash.new(0) final_hash = {} nums.each_with_index do |num, i| index_to_num_hash[i] = num final_hash[i] ||= 0 (0..i - 1).each do |j| if index_to_num_hash[j] > num final_hash[j] += 1 end end end final_hash.values end
true
573dc18a1cc19dc43f11f7c025243537d188db7e
Ruby
IceDragon200/mruby-sfml-audio
/docstub/sound_source.rb
UTF-8
1,808
2.75
3
[]
no_license
module SFML # Base class defining a sound's properties class SoundSource < AlResource # Enumeration of the sound source states module Status # @return [Integer] Stopped = 0 # @return [Integer] Paused = 1 # @return [Integer] Playing = 2 end # @param [Float] pitch # @return [self] def set_pitch(pitch) end # @param [Float] volume # @return [self] def set_volume(volume) end # @overload set_position(position) # @param [Vector3f] position # @overload set_position(x, y, z) # @param [Float] x # @param [Float] y # @param [Float] z # @return [self] def set_position(*args) end # @param [Boolean] bool # @return [self] def set_relative_to_listener(bool) end # @param [Float] distance # @return [self] def set_min_distance(distance) end # @param [Float] attenuation # @return [self] def set_attenuation(attenuation) end # @return [Float] def get_pitch end # @return [Float] def get_volume end # @return [Vector3f] def get_position end # @return [Boolean] def is_relative_to_listener end # @return [Float] def get_min_distance end # @return [Float] def get_attenuation end alias :pitch= :set_pitch alias :volume= :set_volume alias :position= :set_position alias :relative_to_listener= :set_relative_to_listener alias :min_distance= :set_min_distance alias :attenuation= :set_attenuation alias :pitch :get_pitch alias :volume :get_volume alias :position :get_position alias :relative_to_listener? :is_relative_to_listener alias :min_distance :get_min_distance alias :attenuation :get_attenuation end end
true
5b9fe8a1c15bdea6592d6872ca7f7ec6bcb53352
Ruby
alovak/time_report
/spec/time_report_spec.rb
UTF-8
530
2.765625
3
[ "MIT" ]
permissive
require 'spec_helper' describe TimeReport do describe "#output" do it "returns tasks with time for each day" do input = <<-JSON 22.01 10:00 - 11:31 First task 1 11:40 - 12:00 Last task 2 21.01 06:00 - 08:00 First task 3 09:00 - 10:00 Last task 4 JSON report = TimeReport::Processor.new(input) report.run expect(report.output).to eq(<<-OUT) 01:51 # 22.01 01:31 # First task 1 00:20 # Last task 2 03:00 # 21.01 02:00 # First task 3 01:00 # Last task 4 Perfecto! OUT end end end
true
d10fa963a8d578639c6ab404b3e27d32b16fa990
Ruby
IsolatePy/Learn-How-To-Code-With-Ruby
/7- Arrays I - Creation, Addition, and Modification/More_With_Array.rb
UTF-8
169
3.703125
4
[]
no_license
a = [1,2,3,4,5,6,7,8,9,"Ali"] p a.join b = a.join("-") p b.split("-") #you can write array with %w z = %w(my name is Ali and this is great Ruby is amazing) p z p z[0]
true
16450b7c84ac0e790176eff3afe977968836818a
Ruby
coreywhiting/fanfueled
/app/controllers/baseball_matchup_controller.rb
UTF-8
4,789
2.5625
3
[]
no_license
class BaseballMatchupController < ApplicationController def index @first_week = week_range_params[:first] || 1 #TODO find default last week @last_week = week_range_params[:last] || 99 @stats = [ :runs, :hr, :rbi, :sb, :obp, :slg, :ip, :qs, :sv, :era, :whip, :k9 ] #CALCULATIONS @members = Member.all.order(espn_id: :desc) #TEAM AVERAGES #weekly averages for a team over start/end week parameters @team_averages = get_team_averages #STAT MEAN/STDEV #for all members, find mean and st dev of a stat over a week. will be used for z-scores and matchups @stat_means = {} @stat_stddev = {} @stat_means,@stat_stddev = get_stat_means_and_stddev #ZSCORES #how far away from the mean is each member? #winners and losers represent a team > or < .5 standard deviations from the mean @zscores = get_z_scores #MATCHUPS @matchups = Hash.new{|h, k| h[k] = []} @members.each do |m| @matchups[m.espn_id][12] = 0 #winners @matchups[m.espn_id][13] = 0 #losers @stats.each_with_index do |stat,i| @matchups[m.espn_id][i] = @zscores[15][i] - @zscores[m.espn_id][i] # if i == 9 || i == 10 # @matchups[m.espn_id][i] = @matchups[m.espn_id][i] * -1 # end if (@matchups[m.espn_id][i] > 0.5) @matchups[m.espn_id][12] = @matchups[m.espn_id][12] + 1 #winners elsif (@matchups[m.espn_id][i] < -0.5) @matchups[m.espn_id][13] = @matchups[m.espn_id][13] + 1 #losers end end end end private def week_range_params params.fetch(:week_range, {}).permit(:first, :last) end def get_team_averages team_averages = Array.new @members.each do |m| team_averages[m.espn_id] = { :runs => BaseballMatchup.where(espn_id: m.espn_id, week: @first_week..@last_week).average(:runs), :hr => BaseballMatchup.where(espn_id: m.espn_id, week: @first_week..@last_week).average(:hr), :rbi => BaseballMatchup.where(espn_id: m.espn_id, week: @first_week..@last_week).average(:rbi), :sb => BaseballMatchup.where(espn_id: m.espn_id, week: @first_week..@last_week).average(:sb), :obp => BaseballMatchup.where(espn_id: m.espn_id, week: @first_week..@last_week).average(:obp), :slg => BaseballMatchup.where(espn_id: m.espn_id, week: @first_week..@last_week).average(:slg), :ip => BaseballMatchup.where(espn_id: m.espn_id, week: @first_week..@last_week).average(:ip), :qs => BaseballMatchup.where(espn_id: m.espn_id, week: @first_week..@last_week).average(:qs), :sv => BaseballMatchup.where(espn_id: m.espn_id, week: @first_week..@last_week).average(:sv), :era => BaseballMatchup.where(espn_id: m.espn_id, week: @first_week..@last_week).average(:era), :whip => BaseballMatchup.where(espn_id: m.espn_id, week: @first_week..@last_week).average(:whip), :k9 => BaseballMatchup.where(espn_id: m.espn_id, week: @first_week..@last_week).average(:k9) } end return team_averages end def get_stat_means_and_stddev stat_means = {} stat_stddev = {} @stats.each do |s| stat_means[s] = BaseballMatchup.where(week: @first_week..@last_week).average(s) squared_numbers_minus_means = Array.new numbers = Array.new #get all average of stat into an array @team_averages.each do |t| if t != nil numbers << t[s] end end numbers.each do |n| squared_numbers_minus_means << (n.to_f - stat_means[s].to_f) * (n.to_f - stat_means[s].to_f) end mean_squared_diffs = squared_numbers_minus_means.inject{ |sum, el| sum + el }.to_f / squared_numbers_minus_means.size stat_stddev[s] = Math.sqrt(mean_squared_diffs) end return stat_means, stat_stddev end def get_z_scores zscores = Hash.new{|h, k| h[k] = []} @members.each do |m| zscores[m.espn_id][12] = 0 #winners zscores[m.espn_id][13] = 0 #losers @stats.each_with_index do |stat,i| zscores[m.espn_id][i] = (@team_averages[m.espn_id][stat].to_f - @stat_means[stat].to_f) / @stat_stddev[stat].to_f if i == 9 || i == 10 zscores[m.espn_id][i] = zscores[m.espn_id][i] * -1 end if (zscores[m.espn_id][i] > 0.5) zscores[m.espn_id][12] = zscores[m.espn_id][12] + 1 #winners elsif (zscores[m.espn_id][i] < -0.5) zscores[m.espn_id][13] = zscores[m.espn_id][13] + 1 #losers end end end return zscores end end
true
e4d5e526a2268fc80a9954858dfe973644fa0a6e
Ruby
jnatalini/problems
/binary_search.rb
UTF-8
828
4.09375
4
[]
no_license
#!/usr/bin/ruby require 'byebug' #Given a sorted array A[] ( 0 based index ) and a key "k" you need to complete the function bin_search to determine the position of the key if the key is present in the array. If the key is not present then you have to return -1. The arguments left and right denotes the left most index and right most index of the array A[] . def binary_search(input, number) if input.size == 1 && input[0] == number 0 elsif input.size == 1 && input[0] != number nil else mid = input.size / 2 result = if input[mid] > number binary_search(input[0..(mid-1)], number) elsif input[mid] < number binary_search(input[mid..-1], number) + mid else mid end result end end input = [] ARGV.each do |num| input << num.to_i end p binary_search(input, 9)
true
d6055619995f3298cc7493abe20cfb03e5ecacde
Ruby
ktlacaelel/ix
/bin/ix-files
UTF-8
119
2.703125
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby STDIN.each_line do |line| fname = line.chomp if File.exists?(fname) puts fname end end
true
826b0f6af5a76f737d5e5a029157ee2b2d775a07
Ruby
nickell75/phase-0-tracks
/ruby/word_game/word_game.rb
UTF-8
3,284
4.40625
4
[]
no_license
=begin # Pseudocode a class for a word-guessing game that meets the following specifications. create a class word_game Method for player input user input - player enters a string(word or phrase) Method for guesses limited guesses based on the length of the string guessing the same thing twice doesnt count as a guess Method for Feedback feedback from program - output guessed letters that are correct - if the secret word is "unicorn", the user will start out seeing something like "_ _ _ _ _ _ _", which would become "_ _ _ c _ _ _" after the user enters a guess of "c". Method for final output final message - congratulatory message if they win taunting message if they lose Assume your driver code will handle input and output as far as the user is concerned. In other words, write a class designed for a computer program to use, not one designed for a human to use directly, then use driver code to bridge the gap between human and Ruby object. =end #_____________________________Computer Logic_________________________________________ class Word_Game attr_reader :word_array attr_accessor :word, :guess, :guess_count, :guesses, :already_used, :is_game_over, :blank def initialize(word) @word = word @guess = guess @is_game_over = false @guess_count = 0 @word_array = [] @already_used = [] @blank = [] @word_index = [] @guesses end def check_word @blank = ("-" * @word.length).split('') if @word != @guess && @guesses != 1 # Input from Player @guesses = @word.length - @guess_count puts "You have #{@guesses} guesses remaining, \nGuess the word:" @guess = gets.chomp @word_array = @word.split('') guess_array = @guess.split('') # Compare each letter guess_array.each do |letter| if @word_array.include?(letter) @word_index = @blank match_letter = letter match_index = @word_array.index(letter) @word_index[match_index] = letter end end else @is_game_over = true end end def blank puts "Not the correct word, Try Again: " @blank = @word_index.join('') puts "Hint: " + @blank end def check_duplicate if @already_used.include?(@guess) "You have already tried #{guess}!" else @guess_count += 1 @already_used << @guess end end def message if @is_game_over == true || @guesses == 0 puts "No more guesses left :(\nGAME OVER!!" @is_game_over = true elsif @is_game_over == true && @guesses != 0 puts "You got it!! Great Job!!\nGame Over!" #@is_game_over = true end end end #_____________________________DRIVER Code_________________________________________ puts "Enter a word to start playing:" word = gets.chomp game = Word_Game.new(word) while game.is_game_over != true game.blank if game.is_game_over != true && game.guesses != 0 game.check_word game.check_duplicate end end game.message
true
c3e9c1abbbd86b4511110122d80139f0ea4ba5b3
Ruby
a-thom/advent-of-code
/2020/day12_01.rb
UTF-8
1,081
3.5625
4
[]
no_license
require 'byebug' instructions = [] File.read('day12_input.txt').lines.map do |line| action, value = line.match(/(\w)(\d+)/)[1, 2] instruction = { action: action, value: value.to_i } instructions << instruction end puts instructions.inspect def change_direction(current, instruction) directions = %w(N E S W) sign = instruction[:action] == 'R' ? 1 : -1 directions[(directions.index(current) + instruction[:value]/90 * sign)%4] end def move(position, direction, distance) ix = direction == 'N' || direction == 'S' ? 0 : 1 sign = direction == 'S' || direction == 'W' ? -1 : 1 position[ix] = position[ix] + distance * sign position end orientation = 'E' position = [0, 0] instructions.each do |instruction| case instruction[:action] when 'L', 'R' orientation = change_direction(orientation, instruction) when 'F' position = move(position, orientation, instruction[:value]) when 'N', 'S', 'E', 'W' position = move(position, instruction[:action], instruction[:value]) end end puts orientation puts position.map(&:abs).sum
true
00ae62d9c6c9f63fa8530cb421738302c99a6a54
Ruby
YashTotale/learning-ruby
/basics/enumerables/merge.rb
UTF-8
430
3.328125
3
[ "MIT" ]
permissive
h1 = { a: 2, b: 4, c: 6 } h2 = { a: 3, b: 4, d: 8 } h1.merge(h2) # -> { a: 3, b: 4, c: 6, d: 8 } h2.merge(h1) # -> { a: 2, b: 4, c: 6, d: 8 } h1.merge(h2) { |key, old, new| new } # -> { a: 3, b: 4, c: 6, d: 8 } h1.merge(h2) { |key, old, new| old } # -> { a: 2, b: 4, c: 6, d: 8 } h1.merge(h2) { |k, o, n| o < n ? o : n } # -> { a: 2, b: 4, c: 6, d: 8 } h1.merge(h2) { |k, o, n| o * n } # -> { a: 6, b: 16, c: 6, d: 8 }
true
bebf81adaea6cfab4d3c1f302b9afcd509fba330
Ruby
sailakshmiv/TicTacToe
/lib/tic_tac_toe/tic_tac_toe_game.rb
UTF-8
941
3.234375
3
[]
no_license
class TicTacToeGame attr_accessor :current_turn, :game_board attr_reader :check_winner, :computer_ai include Constants def initialize(game_board = GameBoard.new, check_winner = CheckWinner, computer_ai = ComputerAI) @game_board = game_board @check_winner = check_winner @computer_ai = computer_ai @current_turn = X end def board game_board.board end def move(location) switch_turn if game_board.move(location, current_turn) board end def win?(turn = previous_turn) check_winner.new(board, turn).win? end def computer_move computer_ai.new(game_board, O, check_winner).best_move end def previous_turn current_turn == X ? O : X end def remaining_moves game_board.remaining_indices_count end def clear game_board.board = Array.new(9, '-') @current_turn = X end private def switch_turn @current_turn = current_turn == X ? O : X end end
true
5b9218cdf75afa40d02e5fc199b3e3e98300d922
Ruby
gwiederecht11/sp18-hw1
/hw1.rb
UTF-8
987
3.109375
3
[]
no_license
def squared_sum(a, b) # Q1 CODE HERE sum = a + b return sum * sum end def sort_array_plus_one(a) n = a.length i = 0 while i < n do minIndex = i k = i + 1 while k < n do if a[k] < a[minIndex] then minIndex = k end k +=1 end temp = a[minIndex] a[minIndex] = a[i] a[i] = temp + 1 i+=1 end return a end def combine_name(first_name, last_name) return first_name + " " + last_name end def blockin_time(a) # DO NOT EDIT THIS CODE BELOW require './foobar' Foobar.baz a end def scrabble(word) values = { a: 1, b: 3, c: 3, d: 2, e: 1, f: 4, g: 2, h: 4, i: 1, j: 8, k: 5, l: 1, m: 3, n: 1, o: 1, p: 3, q: 10, r: 1, s: 1, t: 1, u: 1, v: 4, w: 4, x: 8, y: 4, z: 10, } sum = 0 for p in 0...word.length do a = word[p].chr.to_sym sum+= values[a] end return sum # Q5 CODE HERE end
true
ab7df1b657805f642160dd89e00075464e2fb851
Ruby
lite72/puavo-oauth-client
/src/client.rb
UTF-8
4,308
2.671875
3
[]
no_license
require 'sinatra/base' require 'haml' require 'addressable/uri' require 'net/http' require 'uri' require 'json' require 'restclient' class Client < Sinatra::Base # Predefined application identification data set :redirect_uri, 'https://my.client.software/callback/' # We choose, and tell Opinsys our redirect_uri set :login_base_uri, 'https://opinsys.fi/oauth/authorize' set :authorization_base_uri, 'https://opinsys.fi/oauth/token' set :puavo_rest_base, 'https://opinsys.fi/' set :client_id, 'oauth_client_id/09d25700-95cd-012f-6c73-5254010000e5' set :client_secret, '09d24230-95cd-012f-6c72-5254010000e5' # At first our resource owner is thrown here and she sees "Puavo login" button. # When the user clicks the login button he will be redirected to Puavo login page get '/' do uri = Addressable::URI.new @state = '123456789' uri.query_values = { :client_id => settings.client_id, :redirect_uri => settings.redirect_uri, :state => @state, :response_type => 'code', :approval_prompt => 'auto', # This value isn't currently used by Puavo :access_type => 'offline' # This value isn't currently used by Puavo } # This url (containing query params) is used for login link/button @login_url = settings.login_base_uri + '?' + uri.query haml :hello end # After successful login Puavo throws our user here, along with parameters ( code, state ) get '/callback/' do # We could optionally check that the state parameters is the same we generated in the first step #throw PuavoBehavingStrangelyOrManInTheMiddle if not params["state"].eql? @state # Here we parse authorization uri and add credentials into it uri = Addressable::URI.parse( settings.authorization_base_uri ) # In our client_id slash is the only character that needs escaping when used as part of url uri.user= URI.escape( settings.client_id, "/" ) uri.password= settings.client_secret # We try to obtain tokens by using authorization code begin res = RestClient.post uri.to_s, { :grant_type => "authorization_code", :code => params["code"], :redirect_uri => settings.redirect_uri }.to_json, :content_type => :json, :accept => :json rescue Exception => e @error = e.to_s haml :error end # Successful transaction gives us JSON containing tokens token_data = JSON::parse res @@access_token = token_data["access_token"] @@refresh_token = token_data["refresh_token"] @@expires_in = token_data["expires_in"] @@token_type = token_data["token_type"] # always 'Bearer' # Now we can use the REST API and authorize requests with access token # 'GET oauth/whoami' REST request to Puavo with Authorization header begin res = RestClient.get settings.puavo_rest_base + "oauth/whoami", { :Authorization => "Bearer #{@@access_token}", :accept => :json } # Request error handling rescue Exception => e @error = e.to_s haml :error end # Check response data validity and parse data. Exception is raised if there's a JSON parse error. begin @user_data = JSON::parse res res rescue Exception => e @error = e.to_s haml :error end end get '/refresh_token' do uri = Addressable::URI.parse( settings.authorization_base_uri ) # In our client_id slash is the only character that needs escaping when used as part of url uri.user = URI.escape( settings.client_id, "/" ) uri.password = settings.client_secret begin res = RestClient.post uri.to_s, { :grant_type => "refresh_token", :refresh_token => @@refresh_token, }.to_json, :content_type => :json, :accept => :json rescue Exception => e @error = e.to_s haml :error end # Successful transaction gives us JSON containing tokens begin token_data = JSON::parse res @@refresh_token = token_data["refresh_token"] @@expires_in = token_data["expires_in"] @@token_type = token_data["token_type"] # always 'Bearer' @@access_token = token_data["access_token"] # ... rescue Exception => e @error = e.to_s haml :error end end end
true
9464edc14aa72003345fb01c49e521c22a2de802
Ruby
erikbjoern/ruby_exercise
/movie_titles.rb
UTF-8
1,009
3.765625
4
[]
no_license
the_fellowship_of_the_ring = {title: "The Fellowship of the Ring ", year: 2001} the_two_towers = {title: "The Two Towers ", year: 2002} the_return_of_the_king = {title: "The Return of the King ", year: 2003} nineteen_seventeen = {title: "1917 ", year: 2019} the_secret_life_of_walter_mitty = {title: "The Secret Life of Walter Mitty ", year: 2013} movie_titles = [the_fellowship_of_the_ring, the_two_towers, the_return_of_the_king, the_secret_life_of_walter_mitty, nineteen_seventeen] puts "\nWhat do you want to see listed? Titles? Release years? Both?" list = gets.chomp.downcase puts "" if list == "titles" movie_titles.each do |movie| puts movie[:title] end elsif list == "release years" movie_titles.each do |movie| puts movie[:year] end else list == "both" movie_titles.each do |movie| puts "#{movie[:title]} #{movie[:year]}" end end puts "\nThere you have it!" exit (0)
true
d1cfa0a5e2c2bafe9910ac9cce12152831ca4e4a
Ruby
ariendeau-usgs/Boiler
/Library/Boiler/cmd/help.rb
UTF-8
2,460
2.8125
3
[]
no_license
BOILER_HELP = <<-EOS :: commands :: help => <command> create => php => html => node serve => h5bp => foundation download => jquery => modernizr => underscore => backbone => custom github => init => commit version EOS BOILER_CREATE_HELP = <<-EOS == create ============================== Creates a blank php or html boilerplate == Usage: ============================== boil create <type> <project name> == Options thus far: =================== :: php :: node :: html :: ======================================== EOS BOILER_SERVE_HELP = <<-EOS == serve ================================ download boilerplates & names the project == Usage: =============================== boil serve <type> <project name> == Options thus far: =================== :: h5bp :: foundation :: ======================================== EOS BOILER_DOWNLOAD_HELP = <<-EOS == download============================== download javascript libs or files easily == Usage: =============================== boil download <option> == Options thus far: =================== :: modernizr :: jquery :: :: backbone :: underscore :: :: custom :: :: ======================================== *NOTE on custom urls This can be any url as long as it points to a file directly. Make sure that the url is in "" or '' EOS BOILER_GITHUB_HELP = <<-EOS == github =============================== Compresses common github processes == Commands: ============================ =============== init ==================== boil github init <url> ============== commit =================== boil github commit <message> <branch> ========================================= EOS module Boiler extend self def help case PROJECT_COMMAND when "create" puts BOILER_CREATE_HELP when "serve" puts BOILER_SERVE_HELP when "github" puts BOILER_GITHUB_HELP when "download" puts BOILER_DOWNLOAD_HELP else puts BOILER_HELP end end def help_s BOILER_HELP end end
true
838d78de10be97be95a8fe6c5168e9139decf408
Ruby
orlandorubydojo/2014-04-16-state-machine
/dog_spec.rb
UTF-8
1,085
3.25
3
[]
no_license
require './dog.rb' describe Dog do before do @baron = Dog.new("Baron") end it 'should have a name' do expect(@baron.name).to eq("Baron") end it 'should start out sleeping' do expect(@baron.state).to eq("sleeping") end it 'should wake up and play' do @baron.wake_up expect(@baron.state).to eq("playing") end it 'should stop playing and eat' do @baron.state = "playing" @baron.gets_hungry expect(@baron.state).to eq("eating") end it 'should finish eating and go to sleep' do @baron.state = "eating" expect(@baron.state).not_to eq("sleeping") @baron.gets_sleepy expect(@baron.state).to eq("sleeping") end it 'should not wake up and immediately eat' do @baron.gets_hungry expect(@baron.state).not_to eq("eating") end it 'should not wake up and immediately sleep' do expect(@baron.gets_sleepy).to be_false end it 'should bark while playing' do @baron.should_receive(:bark) @baron.wake_up end it 'should bark when barking' do expect(@baron.bark).to eq("woof") end end
true
0dd7f1603e6b1f9725523a065df52a4bce98664e
Ruby
kknd113/code
/easy/climbing_test.rb
UTF-8
489
3.875
4
[]
no_license
# You are climbing a stair case. It takes n steps to reach to the top. # # Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? # # Note: Given n will be a positive integer. # @param {Integer} n # @return {Integer} def climb_stairs(n) return 0 if n <= 0 return n if n <= 2 result = Array.new(n) result[0] = 0 result[1] = 1 result[2] = 2 (3...n).each do |i| result[i] = result[i-2] + result[i-1] end result[n-1] end
true
ffe90bd2f3e73dcc8a5d0e90410e2b85354fcbad
Ruby
shijith/ColoringProblem-Rails
/app/controllers/home_controller.rb
UTF-8
1,091
2.6875
3
[]
no_license
class HomeController < ApplicationController def index @nodes = {} @adj = {} @adj_arg = {} i = 0 @colors = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] d = [0, 0, 0] counter = 0 k = 0 @graph = {} while params[String(k)] @graph[k] = params[String(k)] k += 1 end k = 0 for a in @graph n = a[0] b = a[1].split(/,/) @nodes[n] = [b[-2], b[-1]]; b.pop() b.pop() if b != [""] @adj[n] = b for each in b c = Integer(each) if c > n if !@adj_arg[n] @adj_arg[n] = [] end @adj_arg[n].push(c) end end end end @colored = {} for color in @colors @colored[color] = [] end color = 0 for node,neigh in @adj while 1 flag = 1 a = neigh for conn in a if flag == nil break end for col in @colored[ @colors[color] ] if conn != "" if Integer(conn) == col color += 1 flag = nil break end else flag = nil break end end end if flag @colored[ @colors[color] ].push(node) color = 0 break end end end end end
true
54a8d49515e8f9e6fc493c91d2c9f429b5af8f1d
Ruby
alejandro-medici/retrospectiva
/vendor/plugins/tiny-git/lib/tiny_git/object/commit.rb
UTF-8
2,861
2.546875
3
[ "MIT" ]
permissive
module TinyGit module Object class Commit < Abstract PRETTY = %Q(%H%n%T%n%P%n%an <%ae> %aD%n%cn <%ce> %cD%n%s%n%b) def initialize(base, sha, options = {}) super(base, sha) @tree = nil @parents = nil @author = nil @committer = nil @message = nil @options = options.dup @checked = false set_commit(@options.delete(:init)) end def message check_commit @message.join("\n").chomp end # the first line of the message def summary check_commit @message.first end def tree check_commit @tree ||= Tree.new(@base, @tree_data) end def parent parents.first end # array of all parent commits def parents check_commit @parents ||= @parent_data.map{ |sha| TinyGit::Object::Commit.new(@base, sha) } end # true if this is a merge commit # (i.e. it has more than one parent) def merge? parents.size > 1 end def author check_commit @author end def committer check_commit @committer end def date committer.date end def commit? true end def changes check_commit @changes ||= @change_data.map{ |line| TinyGit::Change.parse(line) }.flatten end private def set_commit(data) return if data.nil? @sha = data['sha'] if data['sha'] @committer = TinyGit::Author.new(data['committer']) @author = TinyGit::Author.new(data['author']) @message = data['message'] @parent_data = data['parent'] @tree_data = data['tree'] @change_data = data['changes'] @checked = true end # see if this object has been initialized and do so if not def check_commit return if @checked options = @options.merge(:max_count => 1, :raw => true, :pretty => "format:'#{PRETTY}'") lines = @base.command_lines(:log, @objectish, options) hash = process_commit_data(lines) set_commit(hash) end def process_commit_data(lines) result = { 'message' => [], 'changes' => [] } ['sha', 'tree', 'parent', 'author', 'committer'].each do |key| result[key] = lines.shift end lines.each do |line| result[line =~ /^#{Change::PATTERN}/ ? 'changes' : 'message'] << line end result.update('parent' => result['parent'].split(" ")) end end end end
true
33b648c86f5e11eb440ba2dda736674abdfefa48
Ruby
dpick/crypto
/hw2/decrypt_vigenere.rb
UTF-8
737
3.15625
3
[]
no_license
require 'vigenere' ciphertext = "lpekwylwxmykyrevyvzkabngccpqjgosbaavemjotasinaaueinwfvsixifmlrzwxjlzevypzxdqfieszwgpnikzlytgaazgsezxwgaizqfvzxdmtqzodmjutwpmjylwnmsftrcjmvtxdivpzteklwciowjezrrmjulxewfutrebspoadilkdxdmmupsbitqzoppgwrlpidknisqljzypxaeeynmkqcgkvngcwwbaqywkazgheokgpdmzmjkykevzgcssvekyhwaogwpwakjpgkcdfqsnbzgssplsaxezmzgcjamdxpvuadgptuiffdxqxafhlabzgcxdmhnpeocjgzjiickykwlskdcypskyakcdfmiswjvsxdmltzyxtwqqkablkykqxspotekckykppwflmoqwuhlavkwohavdaladqlgcexjavhmpphkyoagwucejkdqdixgzgcxdmjgheovgvsmjokqgingjgxenssdwievljlxjwjfthwtaepxdqfmtxowngccicujzypwxvsisiqvzlaijvsinitdtxoiqvzmpawnqsdlwccsdlwccmopsnwfatsvpadmfusippgwrlpqlqginixvpvsijfdmpwuefvnmvvzlazljlxopwqfkdblqsermoqyhazwflxppaumypilvsipqegtxwtdupiimvsfmpmfceyniddfxspwpelazsdmmpiuvfehtqvzsgiocegdwmvzjebkylmobuqlxlwumpxwvvnzsgmvcempiffelavzwcvemvqyehqugdxwzlgoxkpwtqiabxqcmpndcdlalsecsoazgcqevvvsepazgsezvwxpvxmxqciomwplvwjtkeaebzgtxdmjcheealezepxgevipwjchepkzvzxwswqfxknavlrzjmtymjookelycjkzwebqusinifcnvkakvsibqwnoebbwttxwvvhzvpcfceihgocdnqalkyxeuwvzwamavasllgyyehijipvwjtkelktwwyhazljplalyg" key_length = key_length_guess(ciphertext) dot_values, shift_values = [ ], [ ] 1.upto(key_length).each do |start_letter| letter_frequency_array = ciphertext.every_nth_letter(key_length, start_letter).letter_frequencies dot_values << letter_frequency_array.dot_product(ENGLISH_FREQUENCIES) 1.upto(ENGLISH_FREQUENCIES.size - 1).each do |i| dot_values << letter_frequency_array.dot_product(ENGLISH_FREQUENCIES.rotate!) end ENGLISH_FREQUENCIES.rotate! shift_values << dot_values.find_index(dot_values.max) dot_values = [ ] end puts "The key length is #{key_length}" key = shift_values.map { |i| (i + LOW).chr }.join("") puts "The key is #{key}" puts decrypt(ciphertext, key)
true
80e36c8fd8aad289e7a0acc587c28b67476c7f16
Ruby
mrkchoi/aa_prep
/02_ruby/06_data_structures/03_knights_travails_v2/knights_travails.rb
UTF-8
1,795
3.46875
3
[]
no_license
require_relative './poly_tree_node.rb' require 'byebug' class KnightPathFinder DELTAS = [ [-2, -1], [-2, 1], [-1, -2], [-1, 2], [2, -1], [2, 1], [1, -2], [1, 2], ] def self.valid_moves(pos) possible_moves(pos).select {|coords| on_board?(coords)} end def initialize(root_position) @root_position = root_position @checked_positions = [@root_position] end def new_move_positions(pos) new_positions = (KnightPathFinder.valid_moves(pos)) - @checked_positions @checked_positions += new_positions new_positions end def build_move_tree root_node = PolyTreeNode.new(@root_position) root_position = root_node.value queue = [root_node] until queue.empty? current_node = queue.shift possible_moves_for_current = new_move_positions(current_node.value) children = [] possible_moves_for_current.each do |move| new_child = PolyTreeNode.new(move) children << new_child new_child.parent = current_node current_node.add_child(new_child) end queue += children end root_node end def find_path(target_pos) target_node = build_move_tree.bfs(target_pos) trace_path_back(target_node) end def trace_path_back(target_node) path_to_target = [target_node.value] until target_node.parent.nil? path_to_target << target_node.parent.value target_node = target_node.parent end path_to_target.reverse end private def self.possible_moves(pos) x, y = pos DELTAS.map do |coords| cur_x, cur_y = coords [x - cur_x, y - cur_y] end end def self.on_board?(coord) coord.all? {|el| el.between?(0,7)} end end k = KnightPathFinder.new([0,0]) p k.find_path([1,3])
true
dab8a3ba44e877846e89fdc879d63ac333dce440
Ruby
dougal/cpu_latency_forwarder
/lib/cpu_latency_forwarder/command.rb
UTF-8
1,543
2.578125
3
[]
no_license
require 'optparse' module CPULatencyForwarder class Command def initialize @graphite_host = 'localhost' @graphite_port = '2003' @script_location = '/root/cpu_latency.bt' @flush_interval = 15 end def run! parse_options puts "Sampling..." store = SampleStore.new(@graphite_host, @graphite_port) epoch = Time.now + @flush_interval IO.popen(@script_location) do |f| while true do line = HistogramLine.new(f.gets) if line.has_data? store.record_sample(line.lower_bound, line.value) end if Time.now >= epoch store.flush! epoch = Time.now + @flush_interval end end end end private def parse_options parser = OptionParser.new do |opts| opts.banner = "Usage: ./bin/run" opts.on("-h HOSTNAME", String, "Specify the Graphite hostname. Default is 'localhost'.") do |v| @graphite_host = v end opts.on("-p PORT", Integer, "Specify the Graphite port. Default is '2003'.") do |v| @graphite_port = v end opts.on("-c PATH", String, "Specify the path of the CPU sampling script. Default is '/root/cpu_latency.bt'.") do |v| @script_location = v end opts.on("-i SECONDS", Integer, "Specify the period used to flush samples to Graphite. Default is '15'.") do |v| @flush_interval = v end end parser.parse! end end end
true
a6f5d322c769e534acb5494a15e540b3cf2082f0
Ruby
karlisV/appium_workshop
/features/pages/numbers.rb
UTF-8
619
2.59375
3
[]
no_license
require './features/modules/base_numbers' # contains all application's keyboard elements class NumbersScreen < BaseNumbersScreen def initialize(driver) @driver = driver end def type_element(type) type_elements = @driver.find_elements(id: 'select_unit_spinner') case type when 'base' type_elements.first when 'conversion' type_elements.last else raise 'Unsupported type' end end def type_popup_elements @driver.find_elements(id: 'select_unit_spinner_menu_name') end def conversion_section_element @driver.find_element(id: 'target_value') end end
true
5e72b6c0fd7154d386b7deef07b37cd1da694ea3
Ruby
larger96/stock-picker
/stock_picker.rb
UTF-8
760
4.25
4
[]
no_license
=begin Implement a method #stock_picker that takes in an array of stock prices, one for each hypothetical day. It should return a pair of days representing the best day to buy and the best day to sell. Days start at 0. =end def stock_picker(array) best_days = [] max_profit = 0 array.each do |buy| buy_idx = array.index(buy) array.each do |sell| sell_idx = array.index(sell) if buy_idx < sell_idx profit = sell - buy if profit > max_profit max_profit = profit best_days = [buy_idx, sell_idx] end end end end p best_days end stock_picker([17,3,6,9,15,8,6,1,10]) # => [1, 4] stock_picker([2,5,3,10,9,8,15,1,6,17]) # => [7, 9] stock_picker([14,3,17,8,10,12,23,2,5]) # => [1, 6]
true
60a95ce71cb5f7ff423e62645e47030db3d4df2c
Ruby
akshay0609/hotel_application
/test/models/category_test.rb
UTF-8
685
2.703125
3
[]
no_license
require 'test_helper' class CategoryTest < ActiveSupport::TestCase def setup @category = Category.new(category_type:"Deluxe Rooms", facility:"Queen size Bed", price:7000) end test "Should be valid" do assert @category.valid? end test "category type should be present" do @category.category_type = " " assert_not @category.valid? end test "facilities should be present" do @category.facility = " " assert_not @category.valid? end test "price should be present" do @category.price = nil assert_not @category.valid? end test "price should be numeric" do @category.price = "abcde" assert_not @category.valid? end end
true
eb918dafe7cd129fc4d825f957104cee5ab7bde5
Ruby
saloni1911/WDI_12_HOMEWORK
/Saloni/wk04/4-thu/animals.rb
UTF-8
2,895
3.8125
4
[]
no_license
require 'pry' class Animal def initialize(aname, age, gender, species, toys) @name = aname @age = age @gender = gender @species = species @toys = [] # @@counter += 1 # @@shelterani << self end def ani_toys(toy) @toys.push(toy) end def get_species @species end # class << Animal # def all # ObjectSpace.each_object(self).entries # end # end end # class Client # def initialize(cli_name, cli_children, cli_age) # @clientname = cli_name # @children = cli_children # @clientage = cli_age # @pets = [] # end # def client_pets(pet) # @pets.push(pet) # end # end # def shelter_ani(animals) # @shelteranimal.push(animals) # end # def shelter_client(clients) # @shelterclient = [] # end shelter = [] loop do puts 'menu of options:' puts '1. Create an animal', '2. Create an client', '3. Display all animals', '4. Display all clients', '5. Facilitate client adopts an animal', '6. Facilitate client puts an animal up for adoption', '7. Quit' print 'option: ' option = gets.chomp if option == "Create an animal" # animal = Animal.new(@aname, @age, @gender, @species, @toys) puts "What is the animal name?" @aname = gets.chomp puts "What is the age of animal?" @age = gets.chomp.to_i puts "What is the gender of animal?" @gender = gets.chomp puts "What is the species of animal?" @species = gets.chomp @toys = [] loop do puts "What are the toys of animal?" toy = gets.chomp @toys.push(toy) puts "Do you want to add more toys? Y or N" opt = gets.chomp if opt == "Y" # puts "What are the toys of animal?" toy = gets.chomp @toys.push(toy) end break if opt == "N" end @toys = animal.ani_toy animal = Animal.new(@aname, @age, @gender, @species, @toys) shelter.push(animal) end break if option == 'Quit' end print shelter # shelter = [] # puts animal1 = Animal.new('a', 3, 'm', 'gdf') # puts animal1.ani_toys("rrf") # puts shelter.push(animal1) # puts animal2 = Animal.new('b', 4, 'f', 'rrtf') # puts animal2.ani_toys("you") # puts shelter.push(animal2) # print shelter # def get_name # @name # end # Animal.all_instances # Animal.length # def create_animals(initialize) # print "variable name: " # variable_name = gets.chomp # puts "What is the animal name?" # aname = gets.chomp # puts "What is the age of animal?" # age = gets.chomp.to_i # puts "What is the gender of animal?" # gender = gets.chomp # puts "What is the species of animal?" # species = gets.chomp # puts "What are the toys of animal?" # a # end # Animal.new() # end # Animal.all # shelter = Animal.all # def get_species # @species # end # shelter[0].get_species # if option == "Create an animal" # print "variable name: " # create_animals binding.pry print shelter shelter[0] shelter[1] shelter[0].get_species
true
407b51c64eae2b0c251ec22545b68d4e00839cd7
Ruby
jordansissel/jruby-elasticsearch
/lib/jruby-elasticsearch/request.rb
UTF-8
646
2.609375
3
[]
no_license
require "jruby-elasticsearch/namespace" require "jruby-elasticsearch/actionlistener" class ElasticSearch::Request # Create a new index request. def initialize @handler = ElasticSearch::ActionListener.new end # See ElasticSearch::ActionListener#on def on(event, &block) #puts "Event[#{event}] => #{block} (#{@handler})" @handler.on(event, &block) return self end # Execute this index request. # This call is asynchronous. # # If a block is given, register it for both failure and success. def use_callback(&block) if block_given? on(:failure, &block) on(:success, &block) end end end
true
c4bfe7c47558e4c85578c13f5a5591dd1dc12851
Ruby
pivotal-cf/bookbinder
/spec/lib/bookbinder/ingest/git_accessor_spec.rb
UTF-8
11,755
2.515625
3
[ "Apache-2.0" ]
permissive
require 'pathname' require 'tmpdir' require_relative '../../../../lib/bookbinder/ingest/git_accessor' require_relative '../../../helpers/git_repo' require_relative '../../../helpers/redirection' module Bookbinder module Ingest describe GitAccessor do include GitRepo include Redirection it "clones to a given dir" do Dir.mktmpdir do |dir| init_repo(at_dir: "#{dir}/srcgorepo", file: 'foo', contents: 'bar', commit_message: 'baz') GitAccessor.new.clone("#{dir}/srcgorepo", 'destgorepo', path: dir) expect(Pathname("#{dir}/destgorepo/foo").read).to eq("bar\n") end end it "clones submodules" do Dir.mktmpdir do |dir| init_repo(at_dir: "#{dir}/submodule_gorepo", file: 'submodule_foo', contents: 'submodule_bar', commit_message: 'submodule_baz') init_repo(at_dir: "#{dir}/srcgorepo", file: 'foo', contents: 'bar', commit_message: 'baz') `#{<<-SCRIPT}` cd #{dir}/srcgorepo git submodule add ../submodule_gorepo my_submodule 2>&1 /dev/null git commit -m "Create submodule" SCRIPT GitAccessor.new.clone("#{dir}/srcgorepo", 'destgorepo', path: dir) expect(Pathname("#{dir}/destgorepo/my_submodule/submodule_foo").read).to eq("submodule_bar\n") end end it "only clones once for a given set of params for a single GitAccessor instance" do Dir.mktmpdir do |dir| path = Pathname(dir) init_repo(at_dir: path.join('srcrepo'), file: 'Gemfile', contents: 'gemstuffz', commit_message: 'new railz plz') git = GitAccessor.new git.clone(path.join('srcrepo'), 'destrepo', path: path) expect { git.clone(path.join('srcrepo'), 'destrepo', path: path) }. not_to change { path.join('destrepo', 'Gemfile').mtime } end end it "only clones once for a given set of params for multiple GitAccessor instances" do Dir.mktmpdir do |dir| path = Pathname(dir) init_repo(at_dir: path.join('srcrepo'), file: 'Gemfile', contents: 'gemstuffz', commit_message: 'new railz plz') first_git = GitAccessor.new second_git = GitAccessor.new first_git.clone(path.join('srcrepo'), 'destrepo', path: path) expect { second_git.clone(path.join('srcrepo'), 'destrepo', path: path) }. not_to change { path.join('destrepo', 'Gemfile').mtime } end end it "can clone and checkout in one call" do Dir.mktmpdir do |dir| path = Pathname(dir) init_repo(branch: 'mybranch', at_dir: path.join('srcgorepo'), file: 'foo', contents: 'bar', commit_message: 'baz') GitAccessor.new.clone(path.join("srcgorepo"), 'destgorepo', checkout: 'mybranch', path: path) expect(path.join('destgorepo', 'foo').read).to eq("bar\n") end end it "can checkout different branches of the same cached repo" do Dir.mktmpdir do |dir| path = Pathname(dir) init_repo(at_dir: path.join('srcrepo'), file: 'Gemfile', contents: 'gemstuffz', commit_message: 'new railz plz', branch: 'newbranch') git = GitAccessor.new git.clone(path.join('srcrepo'), 'destrepo', path: path, checkout: 'newbranch') expect(path.join('destrepo/Gemfile')).to exist git.clone(path.join('srcrepo'), 'destrepo', path: path, checkout: 'master') expect(path.join('destrepo/Gemfile')).not_to exist end end it "can access the date of the last non-excluded commit for a given file in an existing repo" do require 'time' Dir.mktmpdir do |dir| path = Pathname(dir) original_date = ENV['GIT_AUTHOR_DATE'] git = GitAccessor.new begin first_date = Time.new(2003, 1, 2) ENV['GIT_AUTHOR_DATE'] = first_date.iso8601 init_repo(at_dir: path.join('source', 'section-repo'), file: 'some-dir/Gemfile', contents: 'gemstuffz', commit_message: 'new railz plz') expect( git.author_date(path.join('source', 'section-repo', 'some-dir', 'Gemfile').to_s) ).to eq(first_date) second_date = Time.new(2003, 1, 5) ENV['GIT_AUTHOR_DATE'] = second_date.iso8601 swallow_stderr do system("cd #{path.join('source', 'section-repo', 'some-dir')}; echo '!' > Gemfile; git add .; git commit -q -m 'Some commit [exclude]';") end expect( git.author_date(path.join('source', 'section-repo', 'some-dir', 'Gemfile').to_s) ).to eq(first_date) ensure ENV['GIT_AUTHOR_DATE'] = original_date end end end it "can access the date of the last non-excluded commit for a preprocessing-sourced file in an existing repo" do require 'time' Dir.mktmpdir do |dir| path = Pathname(dir) original_date = ENV['GIT_AUTHOR_DATE'] git = GitAccessor.new begin date = Time.new(2000, 11, 5) ENV['GIT_AUTHOR_DATE'] = date.iso8601 init_repo(at_dir: path.join('output', 'preprocessing', 'sections', 'section-repo'), file: 'some-dir/Gemfile', contents: 'gemstuffz', commit_message: 'new railz plz') expect( git.author_date(path.join('output', 'preprocessing', 'sections', 'section-repo', 'some-dir', 'Gemfile').to_s, dita: true) ).to eq(date) ensure ENV['GIT_AUTHOR_DATE'] = original_date end end end it "returns nil when a preprocessing-sourced file is not found in the repo" do require 'time' Dir.mktmpdir do |dir| path = Pathname(dir) original_date = ENV['GIT_AUTHOR_DATE'] git = GitAccessor.new begin init_repo(at_dir: path.join('output', 'preprocessing', 'sections', 'section-repo'), file: 'some-dir/ghost.xml', contents: 'gemstuffz', commit_message: 'new railz plz') expect( git.author_date(path.join('output', 'preprocessing', 'sections', 'section-repo', 'some-dir', 'ghost.dita').to_s, dita: true) ).to be_nil ensure ENV['GIT_AUTHOR_DATE'] = original_date end end end it "returns nil if the given file has no non-excluded commits" do require 'time' Dir.mktmpdir do |dir| path = Pathname(dir) original_date = ENV['GIT_AUTHOR_DATE'] git = GitAccessor.new begin date = Time.new(2003, 1, 2) ENV['GIT_AUTHOR_DATE'] = date.iso8601 init_repo(at_dir: path.join('source', 'section-repo'), file: 'some-dir/Gemfile', contents: 'gemstuffz', commit_message: 'new railz plz [exclude]') expect( git.author_date(path.join('source', 'section-repo', 'some-dir', 'Gemfile').to_s) ).to be_nil ensure ENV['GIT_AUTHOR_DATE'] = original_date end end end it "returns nil if a given file is not checked into version control" do Dir.mktmpdir do |dir| path = Pathname(dir) FileUtils.mkdir(path.join('section-dir')) File.open(path.join('section-dir', 'Gemfile'), "a") do |io| io.write('bookbindery') end git = GitAccessor.new expect( git.author_date(path.join('section-dir', 'Gemfile').to_s) ).to be_nil end end it "can update a previous clone" do Dir.mktmpdir do |dir| path = Pathname(dir) init_repo(at_dir: path.join('srcrepo'), file: 'foo', contents: 'bar', commit_message: 'baz') git = GitAccessor.new git.clone(path.join("srcrepo"), 'destrepo', path: path) swallow_stderr do system("cd #{path.join('srcrepo')}; touch newfile; git add .; git commit -q -m foo") end result = git.update(path.join('destrepo')) expect(result).to be_success expect(path.join('destrepo', 'newfile')).to exist end end it "returns an error if update is for non-existent repo" do update = GitAccessor.new.update("someplacethatdoesntexistyo") expect(update).not_to be_success expect(update.reason).to match(/not found/) end it "returns an error if update causes merge overwrite error" do Dir.mktmpdir do |dir| path = Pathname(dir) init_repo(at_dir: path.join('srcrepo'), file: 'foo', contents: 'bar', commit_message: 'baz') git = GitAccessor.new git.clone(path.join("srcrepo"), 'destrepo', path: path) swallow_stderr do system("cd #{path.join('srcrepo')}; touch newfile; git add .; git commit -q -m foo") end system("cd #{path.join('destrepo')}; touch newfile") result = git.update(path.join('destrepo')) expect(result).not_to be_success expect(result.reason).to match(/merge error/) end end describe 'remote_tagging' do it "can tag and push in one step" do Dir.mktmpdir do |dir| path = Pathname(dir) init_repo(branch: 'branchiwanttotag', at_dir: path.join('srcrepo'), file: 'foo', contents: 'bar', commit_message: 'baz') git = GitAccessor.new git.remote_tag(path.join("srcrepo"), 'mytagname', 'branchiwanttotag') git.clone(path.join("srcrepo"), "destrepo", path: path) tags = `cd #{path.join('destrepo')}; git tag`.split("\n") expect(tags).to eq(["mytagname"]) end end it "raises an exception if tag exists" do Dir.mktmpdir do |dir| path = Pathname(dir) init_repo(branch: 'branchiwanttotag', at_dir: path.join('srcrepo'), file: 'foo', contents: 'bar', commit_message: 'baz') git = GitAccessor.new git.remote_tag(path.join("srcrepo"), 'mytagname', 'branchiwanttotag') expect { git.remote_tag(path.join("srcrepo"), 'mytagname', 'branchiwanttotag') }. to raise_error(GitAccessor::TagExists) end end it "raises an exception if tag ref is invalid" do Dir.mktmpdir do |dir| path = Pathname(dir) init_repo(branch: 'branchiwanttotag', at_dir: path.join('srcrepo'), file: 'foo', contents: 'bar', commit_message: 'baz') git = GitAccessor.new expect { git.remote_tag(path.join("srcrepo"), 'mytagname', 'nonexistent') }. to raise_error(GitAccessor::InvalidTagRef) end end end end end end
true
d55e5a44dd66df5dc89ea3fd99ff57db44123d39
Ruby
allbecauseyoutoldmeso/tic_tac_toe
/spec/game_spec.rb
UTF-8
1,817
3.265625
3
[]
no_license
require 'game' describe Game do subject(:game) { described_class.new(3) } describe '#current_player' do it 'is initially x' do expect(game.current_player.symbol).to eq 'x' end end describe '#switch_player' do it 'changes the player' do game.switch_player expect(game.current_player.symbol).to eq 'o' end end describe '#play' do it 'sets a cell to the current player' do game.play(0,0) expect(game.board.grid[0][0]).to eq 'x' end it 'raises an error if try to take a cell that is already taken' do game.play(0,0) expect { game.play(0,0) }.to raise_error 'cell already taken' end it 'switches the player if nobody wins' do game.play(0,0) expect(game.current_player.symbol).to eq 'o' end it 'prints a win message if a player wins' do game.board.grid[0][0] = 'x' game.board.grid[0][1] = 'x' expect { game.play(0,2) }.to output("x wins!\n").to_stdout end it 'prints a draw message if neither player wins' do game.board.grid[0][0] = 'x' game.board.grid[0][1] = 'x' game.board.grid[0][2] = 'o' game.board.grid[1][0] = 'o' game.board.grid[1][1] = 'o' game.board.grid[1][2] = 'x' game.board.grid[2][0] = 'o' game.board.grid[2][1] = 'x' expect { game.play(2,2) }.to output("draw!\n").to_stdout end it 'starts a new game if game over' do game.board.grid[0][0] = 'x' game.board.grid[0][1] = 'x' game.play(0,2) expect(game.board.grid.all? { |row| row.all? { |cell| cell == '' } }).to be_truthy end it 'allocates points to the winning player' do game.board.grid[0][0] = 'x' game.board.grid[0][1] = 'x' game.play(0,2) expect(game.cross.points).to eq 1 end end end
true
cf740d834431d14d4ba05ca36bfb83cb1136a448
Ruby
clairemariko/d2-homework
/ruby_functions_practice.rb
UTF-8
1,057
3.46875
3
[]
no_license
def return_10() return 10 end def add (num_1, num_2) return num_1 + num_2 end def subtract (num_1, num_2) return num_1 - num_2 end def multiply (num_1, num_2) return num_1 * num_2 end def divide (num_1, num_2) return num_1 / num_2 end def length_of_string(var_1) return var_1.length end #STUCK! def join_string(var_1, var_2) return var_1 + var_2 end def add_string_as_number(var_1, var_2) return var_1.to_f + var_2.to_f end def number_to_full_month_name(var_1) case var_1 when 1 return "January" when 3 return "March" when 9 return "September" end end def number_to_short_month_name(var_1) case var_1 when 1 return "Jan" when 3 return "Mar" when 9 return "Sep" end end def length_of_cube(var_1) return var_1**3 end def volume(var_1) return 4/3 * 3.14 * var_1**3 require 'date' christmas = Date.new(2016,12,25) today = Date.new(Date.today.year, ) end
true
74cbb8208c04ef67c5703221b5818b2f0eae78b0
Ruby
tetetratra/contest
/abc128/c.rb
UTF-8
652
2.90625
3
[]
no_license
N, M = gets.chomp.split.map(&:to_i) # N個のスイッチ, Mの電球 a = [] c = [] M.times do |_m| g = gets.split.map(&:to_i) c << g[0] # 電球に紐づくスイッチの個数 a << [*g[1..-1]] # 電球に紐づくスイッチ end b = gets.split.map(&:to_i) # i番目の電球が、紐づくスイッチのうちONのものを2で割ってこれに一致したら、点灯する count = 0 [true, false].repeated_permutation(N) do |sw| # arrには, M 個の {T, F}の組み合わせ count += 1 if a.map.with_index { |aa, aai| sw.select.with_index { |_s, i| aa.include?(i + 1) }.select { |s| s }.size % 2 == b[aai] }.all? { |a| a } end p count
true
41eab9a6f3e9739aca84e9595cf6048865cb571c
Ruby
srdja/aes-ruby
/lib/ruby/aes_cbc.rb
UTF-8
2,427
3.390625
3
[ "MIT" ]
permissive
# Cipher Block Chaining mode # # Plain text blocks are XORed with the previous block's cipher text, however the # first block requires a random IV to be XORed with since there is no previous # cipher text block. class AES_CBC def initialize(cipher) @cipher = cipher end # XORs the first buffer with the second and store def xor_buffer(b1, b2) rb = [] (0..15).each do |i| rb[i] = b1[i] ^ b2[i] end rb end def encrypt(msg, key, iv, add_padding) b_size = @cipher.block_size block_offset = msg.length % b_size # Add padding if add_padding padding = (block_offset == 0) ? 15 : (block_offset - 1) msg.push(0x80) (1..padding).each do |b| msg.push(0x00) end elsif block_offset != 0 raise ArgumentError.new("Message size is not a multiple of the block size") end blocks = msg.length / b_size cipher_text = [] xor = xor_buffer(iv, msg[(0..(b_size - 1))]) ct_block = @cipher.encrypt_block(xor, key) cipher_text.push(*ct_block) (1..(blocks - 1)).each do |b| pt_block = msg[((b_size * b)..(b_size * (b + 1) - 1))] xor = xor_buffer(ct_block, pt_block) ct_block = @cipher.encrypt_block(xor, key) cipher_text.push(*ct_block) end cipher_text end def decrypt(msg, key, iv, is_padded) b_size = @cipher.block_size if msg.length % b_size != 0 raise ArgumentError.new("Message size is not a multiple of the block size") end blocks = msg.length / b_size plain_text = [] cipher_text_block = msg[(0..(b_size - 1))] transition_block = @cipher.decrypt_block(cipher_text_block, key) plain_text_block = xor_buffer(iv, transition_block) plain_text.push(*plain_text_block) (1..(blocks - 1)).each do |b| block = msg[(b_size * b)..(b_size * (b + 1) - 1)] transition_block = @cipher.decrypt_block(block, key) plain_text_block = xor_buffer(cipher_text_block, transition_block) cipher_text_block = block plain_text.push(*plain_text_block) end # Remove padding if the message was padded if is_padded p_len = 0 (msg.length - 1).step(0, -1) do |b| byte = msg[i] p_len += 1 if byte == 0x80 break elsif byte != 0x00 raise ArgumentError.new("No padding found") end end x.pop(p_len) end plain_text end end
true
1b48a2ef0d5537fae1411fad4928545c756b4029
Ruby
kengonakajima/snippets
/ruby/dumper/dumper.rb
UTF-8
634
2.625
3
[]
no_license
# # Convert binary data to a C source with arrays named by file names # src = "/* generated source code by dumper.rb */\n" def to_array(name,data) ary = data.unpack("C*") l = ary.size out = "const char #{name}[#{l}] = {\n" l.times do |i| out += sprintf( "0x%02x",ary[i] )+ "," out += " " if (i%16) == 7 out += "\n" if (i%16) == 15 end out += "};\n" end ARGV.each do |path| data = File.open(path,"rb").read() nm = "g_data_" + File::basename(path).gsub(".","_") src += "\n" fileinfo = `file #{path}`.strip src += "/* file info: #{fileinfo} */\n" src += to_array(nm, data) end print src, "\n"
true
b609f332d8f51e58552f712f62715ea2063d6736
Ruby
chickensmitten/iambic
/lib/iambic/lexical_item.rb
UTF-8
525
3.15625
3
[]
no_license
module Iambic class LexicalItem attr_reader :word, :pronounciations def initialize(word, pronounciations) @word = word @pronounciations = pronounciations end def stress_patterns pronounciations.map &:to_stress_pattern end def string word.string end def to_s "#{string} (#{pronounciations.join(', ')})" end def ==(other) self.class == other.class && word == other.word && pronounciations == other.pronounciations end end end
true
c672b5e06d0e2ce26fc890dfd6a10fb6a1949a2c
Ruby
figursagsmats/sketchup-script-handler
/scripthandler.rb
UTF-8
2,566
2.71875
3
[]
no_license
module ScriptHandler class ScriptFileWatcher def initialize(script_path, is_single_file=false) @is_single_file = is_single_file @dir_path = File.dirname(script_path) @script_path = script_path @prev_ruby_files = [] @main_script = script_path.split("/").last # /some/path/to/script/main.rb => main.rb main_script_name = @main_script.split(".").first #eg main.rb => main #sem is just using a file as a variable for last modified time if (is_single_file) @sem = @dir_path + "/." + main_script_name + ".sem" else @sem = @dir_path + "/.sem" @pattern = @dir_path + "/**/*.rb" end require script_path update_last_modified_time() start_scanning() end def find_all_ruby_files() if (@is_single_file) all_ruby_files = [@script_path] else all_ruby_files = Dir.glob(@dir_path + "/**/*.rb") end end def check_all_files() all_ruby_files = find_all_ruby_files() #Has the list of files changed? diff = all_ruby_files - @prev_ruby_files unless(diff.empty?) puts "Added the following files to the watch list:" all_ruby_files.each() { |x| puts x } puts "The complete watch list is now:" all_ruby_files.each() { |x| puts x } end @prev_ruby_files = all_ruby_files all_ruby_files.each() { |x| if (File.mtime(x) > File.mtime(@sem)) update_last_modified_time() puts "Reloading #{x}..." load(x) puts "Done reloading #{x}!" end } nil end def update_last_modified_time File.new(@sem, "w").close() end def start_scanning #Starting timer that checks all ruby files for changes @timer_id = UI::start_timer(1, true) { check_all_files() } end def stop_scanning() #No use for this yet UI.stop_timer(@timer_id) end end def self.add_single_file_script(script_path) ScriptFileWatcher.new(script_path, true) end def self.add_multi_file_script(script_path) ScriptFileWatcher.new(script_path, false) end end
true
2ff303dea5dae2586f9cbf841f806d67b41e71de
Ruby
endorama/ruby-version-utils
/lib/version_manipulation.rb
UTF-8
1,593
2.953125
3
[ "MIT" ]
permissive
module VersionUtils def self.upgrade_major( version, update_build_version: false) version = self.parse(version) version[:major] += 1 if version[:minor] != nil version[:minor] = 0 end version = self.update_patch(version) version = self.update_pre_release(version) version = self.update_metadata(version, update_build_version) return self.format(version) end def self.upgrade_minor( version, update_build_version: false) version = self.parse(version) version[:minor] += 1 version = self.update_patch(version) version = self.update_pre_release(version) version = self.update_metadata(version, update_build_version) return self.format(version) end def self.upgrade_patch( version, update_build_version: false) version = self.parse(version) version[:patch] += 1 version = self.update_pre_release(version) version = self.update_metadata(version, update_build_version) return self.format(version) end def self.update_patch(version) if version[:patch] != nil version[:patch] = 0 end return version end def self.update_pre_release(version) version[:pre_release] = nil return version end def self.update_metadata(version, update_build_version) if update_build_version begin build_version = Integer(version[:metadata]) version[:metadata] = (build_version + 1).to_s rescue version[:metadata] = nil end else version[:metadata] = nil end return version end end
true
857b1856219c30bc8129c9ba589985b21745797a
Ruby
zettsu-t/cPlusPlusFriend
/scripts/convert_opcode/convert_opcode.rb
UTF-8
4,128
3.3125
3
[ "MIT" ]
permissive
#!/usr/bin/ruby # coding: utf-8 # Converting HEX strings to x86 mnemonics # # Usage: pass a HEX word to the first argument # $ ruby convert_opcode.rb coffee # > c0,ff,ee sar bh,0xee # # This script # - treats o as 0 and i,l as 1 and applies less common rules # - writes convert_opcode.out and does not delete it automatically require 'open3' INPUT_C_FILENAME = 'convert_opcode.c' OUTPUT_EXE_FILENAME = 'convert_opcode.out' class HexspeakToOpcodes def initialize(phrase) title, code_seq_set = get_code_seq_set(phrase) puts(title) code_seq_set.each do |code_seq| mnemonics = get_mnemonic(code_seq) puts(mnemonics, "---") end end # Converts "abc" to [[0x0a, 0xbc], [0xab, 0xc0]] def get_code_seq_set(arg) # Common rules phrase = arg.strip().downcase().tr("ilo", "110") # Less common rules phrase = phrase.strip().tr("gstz", "6572") phrase = phrase.strip().gsub("r", "12") title = "#{phrase.upcase()} as #{arg.upcase()}" matched = phrase.match(/\A([\da-f])+\z/) unless matched warn("#{arg} is not a HEX number") exit(1) end hex_digit_strs = phrase.size.even?() ? [phrase] : ['0' + phrase, phrase + '0'] code_seq_set = hex_digit_strs.map{ |digit_str| get_byte_seq(digit_str) } return title, code_seq_set end # Converts "0abc" to [0x0a, 0xbc] def get_byte_seq(hex_digit_str) return hex_digit_str.split('').each_slice(2).map do |hex_digits| "0x" + hex_digits.join("") end.join(",") end # Compiles code_seq and returns opcodes-mnemonic strings # which are matched to code_seq def get_mnemonic(code_seq) found = false code_remaining = split_to_bytes(code_seq) mnemonics = [] get_disassembly(code_seq).each_line do |raw_line| line = raw_line.downcase().strip() if found code_remaining, mnemonic = parse_mnemonic(code_remaining, line) unless mnemonic.empty? mnemonics << mnemonic end if code_remaining.empty? break end end # Find int3 if line.match(/\A\d+:\s+cc\s+int3\z/) found = true end end return mnemonics end # Converts "0xab,0xc0" to ["ab", "c0"] def split_to_bytes(line) line.strip().gsub("0x", "").split(/,|\s+/) end # Returns an opcodes-mnemonic string when bytes in code_seq are # fully or partially matched in opcodes of a line def parse_mnemonic(code_seq, line) code_remaining = [] mnemonic = '' matched = line.match(/\A\d+:\s+(([\da-f]{2}\s+)+)(\S.*)/) # Not a mnemonic unless matched return code_remaining, mnemonic end matched_asm = matched[3].strip().gsub(/\s+/, " ") matched_code = split_to_bytes(matched[1]) last_index = -1 code_seq.each_with_index do |code, index| if index >= matched_code.size || code != matched_code[index] break end last_index = index end if last_index < 0 return code_remaining, mnemonic end mnemonic = code_seq[0..last_index].join(',') + ' ' + matched_asm last_index += 1 # Partially matched if last_index == code_seq.size && last_index < matched_code.size mnemonic += " (" + matched_code[last_index..-1].join(',') + " added)" end # Fully matched and may continue to the following lines if last_index < code_seq.size && last_index == matched_code.size code_remaining = code_seq[last_index..-1] end return code_remaining, mnemonic end # Compiles, links and disassembles with code_seq def get_disassembly(code_seq) command = "gcc -mavx2 -O0 -g -c -o #{OUTPUT_EXE_FILENAME} #{INPUT_C_FILENAME}" command += ' -DMY_INSTRUCTIONS=\\"' + code_seq + '\\"' exec(command) command = "objdump -d -M intel #{OUTPUT_EXE_FILENAME}" exec(command) end # Executes a command and get its stdout lines def exec(command) stdoutstr, stderrstr, status = Open3.capture3(command) unless status.success? warn("#{command} failed") exit(1) end stdoutstr end end arg = ARGV.empty? ? "coffee" : ARGV[0] HexspeakToOpcodes.new(arg) 0
true
4d43a1c5d0e1d14061c04b22cf144f660d67aafe
Ruby
rranshous/openscreener
/pipeline_overrides.rb
UTF-8
1,711
2.90625
3
[]
no_license
require 'thread' Thread.abort_on_exception = true class FanPipe include Messenger def initialize create_new, get_key @create_new = create_new @get_key = get_key @handlers = {} bind_queues IQueue.new, IQueue.new end def handler_for_message m key = @get_key.call m raise "BAD KEY: #{m.keys} #{m[:conn_id]} #{key}" if key.nil? || key == '' if @handlers[key].nil? $log.info "Creating handler thread: #{key}" handler = @create_new.call $log.debug "Handler: #{handler}" @handlers[key] = handler Thread.new do # TODO: die if i dont get a msg for a while loop do handler.cycle sleep 0.01 end end # let all the threads know there is a new handler # the new handler will get this msg as well send_state_update key, :new_conn end @handlers[key] end def push_to_thread m handler = handler_for_message m handler.in_queue << m end def cycle $log.debug "PIPE FAN CYCLE" cycle_in_messages cycle_out_messages $log.debug "PIPE FAN CYCLE DONE" end def cycle_in_messages 1000.times do m = pop_message next if m.nil? $log.debug "Pushing to thread" push_to_thread m end end def cycle_out_messages @handlers.each do |key, h| 1000.times do m = h.out_queue.deq(true) rescue nil next if m.nil? $log.debug "Cycle out #{key}" push_message m end end end def send_state_update key, msg $log.debug "sending state update: #{key} #{msg}" @handlers.each do |k, h| h.in_queue << { source_key: key, pipe_message: msg, target_key: k } end end end
true
a09b33d144f98d89dc610d604b696d67d48046eb
Ruby
Austin-dv-Evans/programming-univbasics-2-statement-repetition-with-while-den01-seng-ft-051120
/casefamily.rb
UTF-8
415
2.734375
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
case "Robbie" when "Austin" puts "I love Renee!!" when "Renee" puts "I love my beautiful family and Austin too" when "Jeanie" puts "I am a beautiful princess!" when "Robbie" puts "Robbie smash! grrrrr!" when "Jerry" puts "woof woof" when "Woody" puts "woof woof" when "Dom" puts "I have the best kids!" when "Bobby" puts "Honey, kids, daddy's home!!" else puts "New phone who dis?" end
true
bf8c502bd78009d502ae99bb0acfe6cb96ea759e
Ruby
dillonkearns/legit
/lib/legit/cli.rb
UTF-8
3,399
2.625
3
[ "MIT" ]
permissive
require 'legit/helpers' module Legit class CLI < Thor include Thor::Actions include Legit::Helpers desc "log [ARGS]", "print a graph-like log" method_option :me, :type => :boolean, :desc => 'Only include my commits' def log(*args) command = [] command << Legit::Helpers::LOG_BASE_COMMAND command << "--author='#{repo.config['user.name']}'" if options[:me] args.each do |arg| command << arg end run_command(command.join(' ')) end desc "catch-todos [TODO_FORMAT]", "Abort commit if any todos in TODO_FORMAT found" method_option :enable, :type => :boolean, :desc => 'Enable todo checking' method_option :disable, :type => :boolean, :desc => 'Disable todo checking' method_option :warn, :type => :boolean, :desc => 'Turn on warn mode' def catch_todos(todo_format = "TODO") if options[:enable] repo.config.delete('hooks.catch-todos-mode') elsif options[:disable] repo.config['hooks.catch-todos-mode'] = 'disable' elsif options[:warn] repo.config['hooks.catch-todos-mode'] = 'warn' else if repo.config['hooks.catch-todos-mode'] == 'disable' say("[pre-commit hook] ignoring todos. Re-enable with `legit catch-todos --enable`", :yellow) else run_catch_todos(todo_format) end end end desc "bisect BAD GOOD COMMAND", "Find the first bad commit by running COMMAND, using GOOD and BAD as the first known good and bad commits" def bisect(bad, good, *command_args) command = command_args.join(' ') run_command("git bisect start #{bad} #{good}") run_command("git bisect run #{command}") run_command("git bisect reset") end desc "checkout REGEX", "fuzzy git checkout - can use ruby regex notation `legit checkout BUG-40\\d`" def checkout(branch_pattern) regex = Regexp.new(branch_pattern, Regexp::IGNORECASE) matching_branches = local_branches.select { |b| b.name =~ regex } matched_branch = case matching_branches.length when 0 say("No branches match #{regex.inspect}", :red) exit 1 when 1 matching_branches.first else matching_branches = matching_branches.sort_by { |b| b.name } branch_list = matching_branches.each_with_index.map { |branch, index| "#{index + 1}. #{branch.name}" } response = ask("Choose a branch to checkout:\n#{branch_list.join("\n")}", :yellow).to_i matching_branches[response - 1] end run_command("git checkout #{matched_branch.name}") end desc "delete BRANCH", "Delete BRANCH both locally and remotely" def delete(branch_name) delete_local_branch!(branch_name) || force_delete_local_branch?(branch_name) and delete_remote_branch?(branch_name) end private def run_catch_todos(todo_format) if todos_staged?(todo_format) if repo.config['hooks.catch-todos-mode'] == 'warn' exit 1 unless yes?("[pre-commit hook] Found staged `#{todo_format}`s. Do you still want to continue?", :yellow) else say("[pre-commit hook] Aborting commit... found staged `#{todo_format}`s.", :red) exit 1 end else say("[pre-commit hook] Success: No `#{todo_format}`s staged.", :green) end end end end
true
604295a481c4cd5c444f1276c07e7ce0d7de6b35
Ruby
dev1-sig/stresser
/lib/grapher.rb
UTF-8
3,386
2.78125
3
[]
no_license
require 'ruport' require 'gruff' require 'yaml' require 'csv' $LOAD_PATH.unshift File.join(File.dirname(__FILE__), '..', 'lib') module Grapher extend self # # Parses command line options and creates one or a bunch of # reports, stores them in the given directory, and advises # the user to go ahead and open them # def generate_reports(options) # Let's keep things clean prefix = Time.now.strftime("%Y_%m_%d_%H_%M") # Generate a single report or all of them? report_keys = reports(options[:report_definitions]).keys report_keys = [options[:report]] if report_keys.include?(options[:report]) # Generate report(s) report_keys.each do |report| begin outfile = File.join(options[:output_dir], "#{prefix}_#{report}.png") generate_report(report, options[:csv_file], outfile) rescue => e puts "Error generating #{report}: #{e.inspect}" end end # Tell user what to do next puts "~"*80 puts "Great, now open the images with" puts " open #{File.join(options[:output_dir], prefix)}*.png" end # # Generates a single report given by name. Uses the yml file for # report names # def generate_report(report_type, csv_file, outfile) puts "Generating #{report_type} to #{outfile}..." columns = (reports[report_type] or reports[reports.keys.first]) save_graph(csv_file, columns, outfile, title: report_type) end # # Creates and saves a graph # def save_graph(csv_file, columns, outfile, options = {}) # Draw graph g = graph(csv_file, columns, title: options[:title] ) # Save graph g.write(outfile) end # # Creates a graph from a csv file # # The headers are converted to symbols in the Ruby 1.9.X CSV library def graph(csv_file, columns, options = {}) table = CSV.table(csv_file, headers: true) # Prepare data structure data = Hash.new labels = table.values_at(:rate).flatten columns.each_index do |i| next unless i%2==0 col_name = columns[i+1].gsub(' ','_').gsub('/','') data[columns[i]] = table.values_at(col_name.to_sym).flatten end # Draw graph line_graph( options[:title], data, labels ) end # # Reads a YAML file that defines how reports are built # def reports(report = nil, yaml_file = File.join(File.dirname(__FILE__), "reports.yml")) YAML.load(File.read(yaml_file)) end protected def line_graph(title, data, labels) # Prepare line graph g = Gruff::Line.new g.title = title set_defaults(g) # Add datas data.each do |name, values| g.data(name, values.map(&:to_i)) end # Add labels g.labels = to_hash(labels) # Return graph g end def to_hash(array) return array if array.class == Hash hash = Hash.new array.each_with_index {|v, i| hash[i] = v.to_s } hash end def set_defaults(g) g.hide_dots = true g.line_width = 2 g.legend_font_size = 20 g.marker_font_size = 10 g.sort = false g.x_axis_label = "concurrency (amount of parallel req)" colors = %w{EFD279 95CBE9 024769 AFD775 2C5700 DE9D7F B6212D 7F5417}.map{|c| "\##{c}"} g.theme = { colors: colors, marker_color: "#cdcdcd", font_color: 'black', background_colors: ['#fefeee', '#ffffff'] } end end
true
50734af11d3c9e28dd7396329fe6346565852bbf
Ruby
AntoineInsa/stay_fit
/parse_swim.rb
UTF-8
4,166
3.125
3
[]
no_license
require 'nokogiri' require 'nori' require 'gyoku' require 'pry' def find_distance(time) average_pace = 120 # s/100m pool_length = 50 margin = 0.8 lap_time = average_pace * (100 / (pool_length * 2)) i = 1 while time > lap_time * (i + margin) do i += 1 end pool_length * 2 * i # if time < lap_time * (1 + margin) # pool_length * 2 # elsif time < lap_time * (2 + margin) # pool_length * 4 # elsif time < lap_time * (3 + margin) # pool_length * 6 # elsif time < lap_time * (4 + margin) # pool_length * 8 # else # 100000000 # end end def time_in_minutes(seconds) hours = seconds / 3600 seconds = seconds % 3600 minutes = seconds / 60 seconds = seconds % 60 result = "" result += "#{hours}h" if hours > 0 result += "#{minutes < 10 && hours > 0 ? '0' : ''}#{minutes}'" result += "#{seconds < 10 ? '0' : ''}#{seconds}\"" result end def add_distance(filename) result = Nori.new.parse(File.read(filename)) # result['TrainingCenterDatabase']['Activities']['Activity']['Lap'].first['Track']['Trackpoint'].first.keys # Operate # distances = result['TrainingCenterDatabase']['Activities']['Activity']['Lap'].map{|lap| find_distance(lap['TotalTimeSeconds'].to_i)} # Add a distance to first and last trackpoint, depending on time spent # ["140.0", "143.0", "139.0", "286.0", "144.0", "143.0", "140.0", "436.0", "144.0", "146.0", "291.0", "147.0"] aggregated_time = 0 aggregated_distance = 0 # Simplify # result['TrainingCenterDatabase']['Activities']['Activity']['Lap'].slice!(3..-1) puts "Filename : #{filename}" # count = result['TrainingCenterDatabase']['Activities']['Activity']['Lap'].count # puts "Laps: #{count}" # binding.pry laps = result['TrainingCenterDatabase']['Activities']['Activity']['Lap'] if laps.is_a?(Hash) aggregated_time = laps['TotalTimeSeconds'].to_i aggregated_distance = laps['DistanceMeters'].to_i if aggregated_distance == 0 aggregated_distance = find_distance(aggregated_time) laps['DistanceMeters'] = sprintf('%.1f', aggregated_distance) end # puts "Time: #{time_in_minutes(aggregated_time)} Distance: #{aggregated_distance}m" # aggregated_distance = laps['DistanceMeters'].to_i else laps.each_with_index do |lap, i| begin if lap['Track'].is_a?(Array) trackpoint = lap['Track'].first['Trackpoint'] lap['Track'] = {} lap['Track']['Trackpoint'] = trackpoint end lap['Track']['Trackpoint'].first['DistanceMeters'] = sprintf('%.1f', aggregated_distance) lap_time = lap['TotalTimeSeconds'].to_i lap_distance = find_distance(lap_time) aggregated_time += lap_time aggregated_distance += lap_distance lap['DistanceMeters'] = sprintf('%.1f', lap_distance) lap['Track']['Trackpoint'].last['DistanceMeters'] = sprintf('%.1f', aggregated_distance) rescue => e binding.pry end end end begin pace = 100 * aggregated_time / aggregated_distance humanized_time = time_in_minutes(aggregated_time) humanized_pace = time_in_minutes(pace) puts "Summary: #{aggregated_distance}m - #{aggregated_distance / 100} laps - #{humanized_time} - #{humanized_pace}/100m" rescue => e binding.pry end # Recreate the xml # output = Gyoku.xml(result) # File.write("output/files/#{filename}.tcx.xml", '<?xml version="1.0" encoding="UTF-8"?>' + output) # File.write("output/files/#{filename}.tcx", '<?xml version="1.0" encoding="UTF-8"?>' + output) { 'time' => aggregated_time, 'distance' => aggregated_distance, } end # MAIN path = "input/sample" files = `ls #{path}`.split("\n") total_distance = 0 total_time = 0 average_pace = 0 files.each do |file| result = add_distance("#{path}/#{file}") total_time += result['time'] total_distance += result['distance'] end average_pace = 100 * total_time / total_distance humanized_time = time_in_minutes(total_time) humanized_pace = time_in_minutes(average_pace) puts "Overall" puts "Summary: #{total_distance}m - #{total_distance / 100} laps - #{humanized_time} - #{humanized_pace}/100m"
true
1a37bb8aae88df2401853012df47d6e23fbc2803
Ruby
kasharaylo/RubyCore-Selenium
/Screencast/ep5.rb
UTF-8
289
2.984375
3
[]
no_license
# frozen_string_literal: true puts (2 + 3) * 5 puts 2 + 3 * 5 puts true && true puts (1 < 2) && (3 > 2) puts true && false puts false && false puts (1 > 2) && (3 > 2) puts false && true puts true || true puts (1 > 2) || (3 > 2) puts true || false puts false || false puts false || true
true
a84e73a7fdc093688544a153e8d43512bd0a56ec
Ruby
SoatGroup/redis
/redis_cluster/examples/cluster.rb
UTF-8
10,388
2.546875
3
[ "BSD-3-Clause" ]
permissive
# Copyright (C) 2013 Salvatore Sanfilippo <antirez@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. require 'rubygems' require 'redis' require './crc16' class RedisCluster RedisClusterHashSlots = 16384 RedisClusterRequestTTL = 16 RedisClusterDefaultTimeout = 1 def initialize(startup_nodes,connections,opt={}) @startup_nodes = startup_nodes @max_connections = connections @connections = {} @opt = opt @refresh_table_asap = false initialize_slots_cache end def get_redis_link(host,port) timeout = @opt[:timeout] or RedisClusterDefaultTimeout Redis.new(:host => host, :port => port, :timeout => timeout) end # Given a node (that is just a Ruby hash) give it a name just # concatenating the host and port. We use the node name as a key # to cache connections to that node. def set_node_name!(n) if !n[:name] n[:name] = "#{n[:host]}:#{n[:port]}" end end # Contact the startup nodes and try to fetch the hash slots -> instances # map in order to initialize the @slots hash. def initialize_slots_cache @startup_nodes.each{|n| begin @slots = {} @nodes = [] r = get_redis_link(n[:host],n[:port]) r.cluster("slots").each {|r| (r[0]..r[1]).each{|slot| ip,port = r[2] name = "#{ip}:#{port}" node = { :host => ip, :port => port, :name => name } @nodes << node @slots[slot] = node } } populate_startup_nodes @refresh_table_asap = false rescue # Try with the next node on error. next end # Exit the loop as long as the first node replies break } end # Use @nodes to populate @startup_nodes, so that we have more chances # if a subset of the cluster fails. def populate_startup_nodes # Make sure every node has already a name, so that later the # Array uniq! method will work reliably. @startup_nodes.each{|n| set_node_name! n} @nodes.each{|n| @startup_nodes << n} @startup_nodes.uniq! end # Flush the cache, mostly useful for debugging when we want to force # redirection. def flush_slots_cache @slots = {} end # Return the hash slot from the key. def keyslot(key) # Only hash what is inside {...} if there is such a pattern in the key. # Note that the specification requires the content that is between # the first { and the first } after the first {. If we found {} without # nothing in the middle, the whole key is hashed as usually. s = key.index "{" if s e = key.index "}",s+1 if e && e != s+1 key = key[s+1..e-1] end end RedisClusterCRC16.crc16(key) % RedisClusterHashSlots end # Return the first key in the command arguments. # # Currently we just return argv[1], that is, the first argument # after the command name. # # This is indeed the key for most commands, and when it is not true # the cluster redirection will point us to the right node anyway. # # For commands we want to explicitly bad as they don't make sense # in the context of cluster, nil is returned. def get_key_from_command(argv) case argv[0].to_s.downcase when "info","multi","exec","slaveof","config","shutdown" return nil else # Unknown commands, and all the commands having the key # as first argument are handled here: # set, get, ... return argv[1] end end # If the current number of connections is already the maximum number # allowed, close a random connection. This should be called every time # we cache a new connection in the @connections hash. def close_existing_connection while @connections.length >= @max_connections @connections.each{|n,r| @connections.delete(n) begin r.client.disconnect rescue end break } end end # Return a link to a random node, or raise an error if no node can be # contacted. This function is only called when we can't reach the node # associated with a given hash slot, or when we don't know the right # mapping. # # The function will try to get a successful reply to the PING command, # otherwise the next node is tried. def get_random_connection e = "" @startup_nodes.shuffle.each{|n| begin set_node_name!(n) conn = @connections[n[:name]] if !conn # Connect the node if it is not connected conn = get_redis_link(n[:host],n[:port]) if conn.ping == "PONG" close_existing_connection @connections[n[:name]] = conn return conn else # If the connection is not good close it ASAP in order # to avoid waiting for the GC finalizer. File # descriptors are a rare resource. conn.client.disconnect end else # The node was already connected, test the connection. return conn if conn.ping == "PONG" end rescue => e # Just try with the next node. end } raise "Can't reach a single startup node. #{e}" end # Given a slot return the link (Redis instance) to the mapped node. # Make sure to create a connection with the node if we don't have # one. def get_connection_by_slot(slot) node = @slots[slot] # If we don't know what the mapping is, return a random node. return get_random_connection if !node set_node_name!(node) if not @connections[node[:name]] begin close_existing_connection @connections[node[:name]] = get_redis_link(node[:host],node[:port]) rescue # This will probably never happen with recent redis-rb # versions because the connection is enstablished in a lazy # way only when a command is called. However it is wise to # handle an instance creation error of some kind. return get_random_connection end end @connections[node[:name]] end # Dispatch commands. def send_cluster_command(argv) initialize_slots_cache if @refresh_table_asap ttl = RedisClusterRequestTTL; # Max number of redirections e = "" asking = false try_random_node = false while ttl > 0 ttl -= 1 key = get_key_from_command(argv) raise "No way to dispatch this command to Redis Cluster." if !key slot = keyslot(key) if try_random_node r = get_random_connection try_random_node = false else r = get_connection_by_slot(slot) end begin # TODO: use pipelining to send asking and save a rtt. r.asking if asking asking = false return r.send(argv[0].to_sym,*argv[1..-1]) rescue Errno::ECONNREFUSED, Redis::TimeoutError, Redis::CannotConnectError, Errno::EACCES try_random_node = true sleep(0.1) if ttl < RedisClusterRequestTTL/2 rescue => e errv = e.to_s.split if errv[0] == "MOVED" || errv[0] == "ASK" if errv[0] == "ASK" asking = true else # Serve replied with MOVED. It's better for us to # ask for CLUSTER NODES the next time. @refresh_table_asap = true end newslot = errv[1].to_i node_ip,node_port = errv[2].split(":") if !asking @slots[newslot] = {:host => node_ip, :port => node_port.to_i} end else raise e end end end raise "Too many Cluster redirections? (last error: #{e})" end # Currently we handle all the commands using method_missing for # simplicity. For a Cluster client actually it will be better to have # every single command as a method with the right arity and possibly # additional checks (example: RPOPLPUSH with same src/dst key, SORT # without GET or BY, and so forth). def method_missing(*argv) send_cluster_command(argv) end end
true
e31b0a2dff067203c093c97bf1b0c69f555ec820
Ruby
nrk/ironruby
/External.LCA_RESTRICTED/Languages/Ruby/ruby-1.8.6p368/lib/ruby/gems/1.8/gems/arel-0.2.pre/lib/arel/engines/sql/predicates.rb
UTF-8
1,111
2.625
3
[]
no_license
module Arel module Predicates class Binary < Predicate def to_sql(formatter = nil) "#{operand1.to_sql} #{predicate_sql} #{operand1.format(operand2)}" end end class CompoundPredicate < Binary def to_sql(formatter = nil) "(#{operand1.to_sql(formatter)} #{predicate_sql} #{operand2.to_sql(formatter)})" end end class Or < CompoundPredicate def predicate_sql; "OR" end end class And < CompoundPredicate def predicate_sql; "AND" end end class Equality < Binary def predicate_sql operand2.equality_predicate_sql end end class GreaterThanOrEqualTo < Binary def predicate_sql; '>=' end end class GreaterThan < Binary def predicate_sql; '>' end end class LessThanOrEqualTo < Binary def predicate_sql; '<=' end end class LessThan < Binary def predicate_sql; '<' end end class Match < Binary def predicate_sql; 'LIKE' end end class In < Binary def predicate_sql; operand2.inclusion_predicate_sql end end end end
true
396ed0539b61cf303fb3b52700871bb9a7bd357d
Ruby
gree/lwf
/tools/swf2lwf/lib/rkelly/lexeme.rb
UTF-8
364
2.828125
3
[ "Zlib", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "BSL-1.0", "Apache-2.0", "Ruby", "LicenseRef-scancode-public-domain", "JSON" ]
permissive
require 'rkelly/token' module RKelly class Lexeme attr_reader :name, :pattern def initialize(name, pattern, &block) @name = name @pattern = pattern @block = block end def match(scanner) match = scanner.check(pattern) return Token.new(name, match.to_s, &@block) if match match end end end
true
460f241e0e477fbab9f29cfb6d258f31359330aa
Ruby
crsanders/hackarogue
/lib/classlist.rb
UTF-8
834
2.9375
3
[ "MIT" ]
permissive
class BaseClass attr_reader :hp, :inv, :equip, :lvl, :str, :mind, :dex, :vit, :class, :cash, :xp end class Squire < BaseClass def initialize @hp = 10 @inv = [] @equip = [] @lvl = 5 @str = 8 @mind = 3 @dex = 5 @vit = 10 @cash = 15 @class = "Squire" end end class Mage < BaseClass def intialize @hp = 6 @inv = [] @equip = [] @lvl = 3 @str = 3 @mind = 10 @dex = 3 @vit = 5 @cash = 5 @class = "Mage" end end class Archer < BaseClass def initialize @hp = 8 @inv = [] @equip = [] @lvl = 3 @str = 5 @mind = 5 @dex = 8 @vit = 7 @cash = 10 @class = "Archer" end end
true
fec327b1e9f97dc964b7c83307328810f4af9c59
Ruby
Toam99/Leprosorium
/app.rb
UTF-8
2,637
3.015625
3
[ "MIT" ]
permissive
require 'rubygems' require 'sinatra' require 'sinatra/reloader' require 'sqlite3' def init_db @db = SQLite3::Database.new 'leprosorium.db' @db.results_as_hash = true end # before called back each time reload executed # any page before do # individualization of DB init_db end # configure -> called each time for configuration of Apllication: # when changed programm code and page reload configure do # initialization of DB init_db # create table if not exists Posts @db.execute 'create table if not exists Posts ( id INTEGER PRIMARY KEY AUTOINCREMENT, created_date DATE, content TEXT )' # create table if not exists Comments @db.execute 'create table if not exists Comments ( id INTEGER PRIMARY KEY AUTOINCREMENT, created_date DATE, content TEXT, post_id integer )' end get '/' do # choose list of posts from DB in order by descending (descending = desc) @results = @db.execute 'select * from Posts order by id desc' erb :index end # the handler of post-inqury /new # (browser sends data-info into server) get '/new' do erb :new end # handler for post->requests /new # (браузер отправляет данные на сервер) post '/new' do # receive params from post-request content = params[:content] if content.length <= 0 @error = 'Type post text' return erb :new end # save info into DataBase @db.execute 'insert into Posts (content, created_date) values (?, datetime())', [content] # redirection to main_page--->Home redirect to '/' end # puts post info get '/details/:post_id' do # receive params from url post_id = params[:post_id] # receive list of posts # (we will have only One post) results = @db.execute 'select * from Posts where id = ?', [post_id] # we select this post into params @row @row = results[0] # we select commentary for our post @comments = @db.execute 'select * from Comments where post_id = ? order by id', [post_id] # return performance into details.erb erb :details end # the handler of post-inqury /details/.. # (browser sends data-info into server, we're receiving them) post '/details/:post_id' do # receive params from url post_id = params[:post_id] # receive params from from post-inquiry content = params[:content] # save info into DataBase @db.execute 'insert into Comments ( content, created_date, post_id ) values ( ?, datetime(), ? )', [content, post_id] # redirect to post page redirect to('/details/' + post_id) end
true
58bc534841be2e153c6acbe53e4a482639013d74
Ruby
c8af43d37a3ae1ab0789afe3f56e9a4b/random
/lib4chan/test/homepage_spec.rb
UTF-8
1,406
2.703125
3
[]
no_license
require 'lib/4chan.rb' describe FourChan do before :each do @fourchan = FourChan.new end it "should fetch the homepage" do homepage = @fourchan.home describe homepage do it "should be of the right class" do homepage.should be_a(FourChan::Homepage) end it "should contain summaries of the active threads" do active_thread_summaries = homepage.threadSummaries describe active_thread_summaries do it "should be of the right class" do active_thread_summaries.should be_a(FourChan::ThreadSummaries) end it "should contain thread summaries" do active_thread_summaries.length.should > 0 end it "should contain valid thread summaries" do active_thread_summaries.each do |summary| describe summary do it "should be of the right class" do summary.should be_a(FourChan::ThreadSummary) end summary.unique_public_methods.reject{|m| m =~ /=$|thread/}.each do |key| it "should have this accessor method" do summary.should respond_to(key) end it "should be populated with :#{key}" do summary.send(key).should_not be_nil end end end end end end end end end end class Object def unique_public_methods s_class = self.class.superclass methods - (s_class.instance_methods + s_class.methods) end end
true
576142a5a4e61ac6a5c3c8bd229c177f997e9976
Ruby
njh/dbpedialite
/spec/category_spec.rb
UTF-8
6,986
2.640625
3
[ "MIT" ]
permissive
require 'spec_helper' require 'category' describe Category do context "creating a category from a page id" do before :each do @category = Category.new(4309010) end it "should return an object of type Category" do @category.class.should == Category end it "should have the correct URI" do @category.uri.should == RDF::URI('http://www.dbpedialite.org/categories/4309010#id') end it "should not have any things yet" do @category.things.count.should == 0 end end context "create a category from a hash" do before :each do @category = Category.new( 'pageid' => 4309010, 'ns' => 14, 'title' => 'Category:Villages in Fife', 'displaytitle' => 'Category:Villages in Fife' ) end it "should return an object of type Category" do @category.class.should == Category end it "should have the correct URI" do @category.uri.should == RDF::URI('http://www.dbpedialite.org/categories/4309010#id') end it "should have the correct title" do @category.title.should == 'Category:Villages in Fife' end it "should have the correct diaplay title" do @category.title.should == 'Category:Villages in Fife' end it "should have the correct label" do @category.label.should == 'Villages in Fife' end end context "loading a category from the Wikipedia API" do before :each do page_info = { 'pageid' => 4309010, 'ns' => 14, 'title' => 'Category:Villages in Fife', 'displaytitle' => 'Category:Villages in Fife', 'touched' => '2010-11-04T04:11:11Z', 'lastrevid' => 325602311, 'counter' => 0, 'length' => 259 } category_members = [ {'pageid' => 2712,'ns' => 0, 'title' => 'Aberdour', 'displaytitle' => 'Aberdour'}, {'pageid' => 934787, 'ns' => 0, 'title' => 'Ceres, Fife', 'displaytitle' => 'Ceres, Fife'}, {'pageid' => 986129, 'ns' => 14, 'title' => 'Category:Villages with greens', 'displaytitle' => 'Category:Villages with greens'} ] allow(WikipediaApi).to receive(:page_info).with(:pageids => 4309010).and_return(page_info) allow(WikipediaApi).to receive(:category_members).with(4309010).and_return(category_members) @category = Category.load(4309010) end it "should have the correct page id" do @category.pageid.should == 4309010 end it "should have the correct uri" do @category.uri.should == RDF::URI('http://www.dbpedialite.org/categories/4309010#id') end it "should have the correct title" do @category.title.should == 'Category:Villages in Fife' end it "should have a label without the 'Category' prefix in it" do @category.label.should == 'Villages in Fife' end it "should have 2 things associated with the category" do @category.things.count.should == 2 end it "should have a first thing of class Thing" do @category.things.first.class.should == Thing end it "should have a first thing with title Aberdour" do @category.things.first.title.should == 'Aberdour' end it "should have one sub-category" do @category.subcategories.count.should == 1 end it "should have a first subcategory of class Category" do @category.subcategories.first.class.should == Category end it "should have a first subcategory with label Villages with greens" do @category.subcategories.first.label.should == 'Villages with greens' end end context "loading a non-category page from wikipedia" do before :each do page_info = { 'pageid' => 52780, 'ns' => 0, 'title' => 'U2', 'displaytitle' => 'U2', 'touched' => '2010-05-12T22:44:49Z', 'lastrevid' => 361771300, 'counter' => 787, 'length' => 78367 } allow(WikipediaApi).to receive(:page_info).with(:pageids => 52780).and_return(page_info) end it "should return raise a PageNotFound exception" do lambda {Category.load(52780)}.should raise_error( MediaWikiApi::NotFound, 'Page 52780 is not a category' ) end end context "converting a category to RDF" do before :each do @category = Category.new(4309010, :title => 'Category:Villages in Fife', :displaytitle => 'Category:Villages in Fife', :abstract => "Villages located in Fife, Scotland.", :things => [ Thing.new(1137426, :title => "Anstruther"), Thing.new(52780, :title => "Ceres, Fife") ], :subcategories => [ Category.new(1234567, :title => 'Category:Hamlets in Fife', :displaytitle => 'Category:Hamlets in Fife' ) ] ) @graph = @category.to_rdf end it "should return an RDF::Graph" do @graph.class.should == RDF::Graph end it "should return a graph with 13 triples" do @graph.count.should == 13 end it "should include an rdf:type triple for the category" do @graph.should have_triple([ RDF::URI("http://www.dbpedialite.org/categories/4309010#id"), RDF.type, RDF::OWL.Class ]) end it "should include a rdfs:label triple for the category" do @graph.should have_triple([ RDF::URI("http://www.dbpedialite.org/categories/4309010#id"), RDF::RDFS.label, RDF::Literal("Villages in Fife"), ]) end it "should include a rdf:type triple for the document" do @graph.should have_triple([ RDF::URI("http://www.dbpedialite.org/categories/4309010"), RDF.type, RDF::URI("http://xmlns.com/foaf/0.1/Document") ]) end it "should include a dc:title triple for the document" do @graph.should have_triple([ RDF::URI("http://www.dbpedialite.org/categories/4309010"), RDF::URI("http://purl.org/dc/terms/title"), RDF::Literal('dbpedia lite category - Villages in Fife') ]) end it "should include a foaf:primaryTopic triple linking the document to the category" do @graph.should have_triple([ RDF::URI("http://www.dbpedialite.org/categories/4309010"), RDF::FOAF.primaryTopic, RDF::URI("http://www.dbpedialite.org/categories/4309010#id") ]) end it "should have a RDF:type triple relating Ceres to Villages in Fife" do @graph.should have_triple([ RDF::URI("http://www.dbpedialite.org/things/52780#id"), RDF.type, RDF::URI("http://www.dbpedialite.org/categories/4309010#id") ]) end it "should have a RDFS:subClassOf triple subclassing Hamlets from Villages" do @graph.should have_triple([ RDF::URI("http://www.dbpedialite.org/categories/1234567#id"), RDF::RDFS.subClassOf, RDF::URI("http://www.dbpedialite.org/categories/4309010#id") ]) end end end
true
456e2d7e8ef99c89d967ed00f0de993f04cffb89
Ruby
cielavenir/procon
/atcoder/abc/tyama_atcoderABC033B.rb
UTF-8
136
2.859375
3
[ "0BSD" ]
permissive
#!/usr/bin/ruby h={} s=0 gets.to_i.times{ x,y=gets.split s+=h[x]=y.to_i } r=h.select{|k,v|v>s/2} puts !r.empty? ? r.keys[0] : :atcoder
true
10305547f9451edc45a63a35f26c4d52451641b9
Ruby
WizelineHackathon2018/amalgama-hacks
/app/services/facebook_api_log_in/facebook_api.rb
UTF-8
1,177
2.625
3
[]
no_license
require 'net/http' require 'uri' require 'json' class FacebookApi include ErrorRaiser def initialize( auth_code:, platform: ) @auth_code = auth_code @access_token = "?access_token=#{auth_code}" @platform = platform end def get_user_data response = get_data response.merge( { "avatar_url" => get_image["data"]["url"] } ) end def get_data facebook = URI.parse( Settings.facebook.graph_api_url + @access_token + "&fields=id,name,email,first_name,last_name,gender" ) get_response url: facebook end def get_image facebook_image = URI.parse( Settings.facebook.graph_api_url + "/picture" + @access_token + "&width=180&height=180&redirect=false" ) get_response url: facebook_image end private def get_response( url: ) response = Net::HTTP.get_response url @response_body = JSON.parse response.body generate_error if @response_body["error"].present? @response_body end def generate_error log_error error :facebook_graph_api_error, @response_body["error"]["message"] end def log_error LogFacebookError.with( auth_code: @auth_code, platform: @platform, error_message: @response_body["error"]["message"] ) end end
true
ab27530bd9b685ca4edc9c89830d87fd8844cdcd
Ruby
f1nesse13/aA_anagrams
/anagrams.rb
UTF-8
1,728
4.125
4
[]
no_license
def first_anagram?(str1, str2) all_variations = str1.chars.permutation.map(&:join) all_variations.include?(str2) end # first_anagram? increases exponetially with 3 letters having 6 possible combinations, 5 letters having 120 and 10 letters having a incredible 3628800 - O(kn) with more letters involving more variations on each letter p first_anagram?('elvis', 'lives') def second_anagram?(str1, str2) str2 = str2.split("") str1.chars.each do |chr| next if str2.find_index(chr) == nil idx = str2.find_index(chr) str2.delete_at(idx) end str2.join("") == '' end # second anagram is a O(n^2) complexity time wise - it has to iterate thru chars then again to find the index in the other string space complexity is O(1) since it doesn't store additional info only deletes chars from the second string # p second_anagram?('elvis', 'lives') def third_anagram?(str1, str2) str1.chars.sort! == str2.chars.sort! end # third anagram is O(n log n) since the sort method used by ruby has this complexity althrough if we were to expect larger arrays sort_by might be a better solution - the only other operation done is a comparision and (2 memory accesses?) - space complexity is O(1) # p third_anagram?('elvis', 'lives') def fourth_anagram?(str1, str2) counter = Hash.new(0) strs = str1+str2 strs.chars.each do |chr| counter[chr] += 1 end counter.all? { |key, val| val == (str1.count(key) * 2) } end # fourth_anagram? is a O(n) function - it only has to loop thru a combination of both strings and makes sure that each value in the hash has a count equal to double each letter - the only way this is obtainable is if both strings have the same characters p fourth_anagram?('elvis', 'lives')
true
3342994b446ee5c1af6eabe906973386f8b91486
Ruby
aaronsama/string-calculator-kata
/ruby/lib/string_calculator.rb
UTF-8
641
3.4375
3
[]
no_license
module StringCalculator class << self # Splits a set of comma separated numbers and sums them def add(numbers) split_numbers = numbers.split(default_delimiter(numbers)).map(&:to_i) negative_numbers = split_numbers.select(&:negative?) raise "negatives not allowed: #{negative_numbers.join(', ')}" if negative_numbers.any? split_numbers.inject(0) do |acc, num| acc += num > 1000 ? 0 : num end end private def default_delimiter(numbers) return /,|\n/ unless numbers.start_with?('//') %r{^//(?<delimiter>[^\n])\n} =~ numbers /#{delimiter}|\n/ end end end
true
3bf2f647a0468b0171e13ab9c6cd33e44f4de55f
Ruby
sapient/spelly
/test/test_bloomfilter.rb
UTF-8
560
2.75
3
[]
no_license
require 'test/unit' require File.join(File.dirname(__FILE__), "..", "lib", "spelly", "bloomfilter") class TestBloomfilter < Test::Unit::TestCase def test_adding_to_bloom bloom = BloomFilter.new(100) assert_equal 0, bloom.saturation bloom.add("test") assert bloom.includes?("test") assert !bloom.includes?("test2"), "Should not include test2" bloom.add("test2") assert bloom.includes?("test2") saturation = bloom.saturation assert saturation > 0 bloom.add("test3") assert saturation < bloom.saturation end end
true
273a84e0a19850f102a5d166ddc8a8b5ea109ad0
Ruby
arpannln/aA-projects
/W2D2/chess/rook.rb
UTF-8
380
3.046875
3
[]
no_license
require_relative 'slideable' require_relative 'piece' require_relative 'board' require 'byebug' class Rook < Piece attr_reader :direction, :color, :board attr_accessor :pos def initialize(color, pos, board) @direction = "straight" super end include Slideable def symbol :Rook end def to_s " \u2656 " end def moves super end end
true
fb809945ba8c11d51ad3404ff5e6ebee142ba813
Ruby
renuo/google-hash-code-team-und-struppi
/spec/parse/parser_spec.rb
UTF-8
1,290
2.65625
3
[]
no_license
require_relative '../spec_helper' require_relative '../../rides/parser' RSpec.describe Parser do context(:example_dataset) do let(:parser) do parser = Parser.new('rides/datasets/a_example.in') parser.parse parser end it 'parses the first line' do expect(parser.num_rows).to eq(3) expect(parser.num_columns).to eq(4) expect(parser.num_vehicles).to eq(2) expect(parser.num_rides).to eq(3) expect(parser.num_bonus).to eq(2) expect(parser.num_steps).to eq(10) end it 'parses the rides' do expect(parser.rides.length).to eq(3) expect(parser.rides[0].id).to eq(0) expect(parser.rides[1].id).to eq(1) expect(parser.rides[2].id).to eq(2) expect(parser.rides[0].coordinate_start.x).to eq(0) expect(parser.rides[0].coordinate_start.y).to eq(0) expect(parser.rides[0].coordinate_end.x).to eq(1) expect(parser.rides[0].start).to eq(2) expect(parser.rides[0].finish).to eq(9) expect(parser.rides[0].distance).to eq(4) expect(parser.rides[1].coordinate_start.x).to eq(1) expect(parser.rides[1].coordinate_start.y).to eq(2) expect(parser.rides[1].coordinate_end.x).to eq(1) expect(parser.rides[1].coordinate_end.y).to eq(0) end end end
true
adde518f97776658f82b19a242b315fc8e35f7cf
Ruby
databasically/harvestime
/lib/harvestime/invoice_filter.rb
UTF-8
1,230
2.5625
3
[ "MIT" ]
permissive
require'harvested' module Harvestime class InvoiceFilter def initialize(client) @client = client end def all_with_status(state) @client.invoices.all(status: state.to_s) end def all_invoices @client.invoices.all end def all_by_client_id(client_id) collection = [] all_invoices.each do |invoice| collection << invoice if invoice.client_id == client_id end collection end def all_with_status_and_client(state, client_id) collection = [] all_with_status(state).each do |invoice| collection << invoice if invoice.client_id == client_id end collection end # # Unnecessary # def outstanding_invoices # all_with_status(:unpaid) # end # def draft_invoices # all_with_status(:draft) # end # def partial_invoices # all_with_status(:partial) # end # def unpaid_invoices # all_with_status(:unpaid) # end # def paid_invoices # all_with_status(:paid) # end # # coupled # def outstanding_by_client_id(client_id) # all_with_status_and_client(:unpaid, client_id) # end end end
true
7f41c6b28ad2f3d6e143824c5bf7976e5e38c344
Ruby
jtibbertsma/flight-search
/lib/tasks/fetch_airports.rake
UTF-8
635
2.625
3
[]
no_license
require 'set' task fetch_airports: :environment do major_airports = Set.new( Typhoeus.get('http://www.nationsonline.org/oneworld/major_US_airports.htm') .body.scan(/\b[A-Z]{3}\b/) ) File.open(Rails.root.join('airports.dat')) do |file| file.each_line do |line| data = line.split(/,/) code = data[4][/\w+/] if major_airports.include? code name = data[1][/[\w\s]+/] latitude = data[6] longitude = data[7] Airport.create( name: name, code: code, latitude: latitude, longitude: longitude ) end end end end
true
dee4be8fefddf61bfa9b02e1f75939321e666a35
Ruby
CarlosCanizal/learn_to_program
/chapter_13/extend_built_in_classes.rb
UTF-8
436
4.09375
4
[]
no_license
load "../chapter_9/modern_roman_function.rb" load "../chapter_10/shuffle_function.rb" class Integer def factorial if self < 0 return 'You can\'t take the factorial of a negative number!' end if self <= 1 1 else self * (self-1).factorial end end def to_roman modern_roman self end end class Array def shuffle basic_shuffle(self) end end puts 4.to_roman puts 4.factorial p([1,2,3,4,5].shuffle)
true
2af9b664e1b420165bf9b71a5779e8971cb889e9
Ruby
learn-co-students/yale-web-2019
/06-uber/app/models/driver.rb
UTF-8
1,143
3.625
4
[]
no_license
class Driver @@all = [] attr_reader :name def initialize(name) @name = name @@all << self end def self.all @@all end def rides Ride.all.select do |ride| ride.driver == self end end def passengers self.rides.map do |ride| ride.passenger end end def passenger_names self.passengers.uniq.map do |passenger| passenger.name end end def total_distance sum = 0 self.rides.each do |ride| sum += ride.distance end sum end def self.mileage_cap(distance) @@all.select do |driver| driver.total_distance > distance end # self.all end end # ***- `Driver#name` # - Returns the driver's name # - `Driver#passenger_names` # - Returns an array of all Passengers' names a driver has driven. The names should be **unique** (no repeats). # - `Driver#rides` # - Returns an array of all Rides a driver has made # - ***`Driver.all` # - Returns an array of all Drivers # - `Driver.mileage_cap(distance)` # - Takes an argument of a distance (float) and returns an array of all Drivers who have driven over the mileage
true
37cc9539a9c70e5e03e86aa1b08b09c598159508
Ruby
masdjab/elang
/compiler/code.rb
UTF-8
211
2.578125
3
[]
no_license
module Elang class Code def self.align(code, align_size = 16) if (extra_size = (code.length % 16)) > 0 code = code + (0.chr * (16 - extra_size)) end code end end end
true
1395af8752ca35d1ae82cbae698f91745e3bbf83
Ruby
nulian/casted_hash
/lib/casted_hash.rb
UTF-8
3,509
3.03125
3
[ "MIT" ]
permissive
class CastedHash < Hash VERSION = "0.7.1" def initialize(constructor = {}, cast_proc = nil) raise ArgumentError, "`cast_proc` required" unless cast_proc @cast_proc = cast_proc @casting_keys = [] if constructor.is_a?(CastedHash) super() @casted_keys = constructor.instance_variable_get(:@casted_keys).dup regular_update(constructor) elsif constructor.is_a?(Hash) @casted_keys = [] super() update(constructor) else @casted_keys = [] super(constructor) end end alias_method :regular_reader, :[] unless method_defined?(:regular_reader) def [](key) cast! key end def fetch(key, *extras) value = cast!(key) if value.nil? super(convert_key(key), *extras) else value end end alias_method :regular_writer, :[]= unless method_defined?(:regular_writer) alias_method :regular_update, :update unless method_defined?(:regular_update) def []=(key, value) uncast! key regular_writer(convert_key(key), value) end alias_method :store, :[]= def merge(hash) self.dup.update(hash) end def update(other_hash) return self if other_hash.empty? if other_hash.is_a?(CastedHash) super(other_hash).tap do other_hash.keys.each do |key| if other_hash.casted?(key) casted!(key) elsif casted?(key) uncast!(key) end end end else other_hash.each_pair { |key, value| self[key] = value } self end end alias_method :merge!, :update def key?(key) super(convert_key(key)) end alias_method :include?, :key? alias_method :has_key?, :key? alias_method :member?, :key? def values_at(*indices) indices.collect {|key| self[convert_key(key)]} end def dup self.class.new(self, @cast_proc) end def delete(key) uncast! key super(convert_key(key)) end def values cast_all! super end def each cast_all! super end def casted_hash cast_all! self end def casted?(key) @casted_keys.include?(key.to_s) end def casting?(key) @casting_keys.include?(key.to_s) end def to_hash Hash.new.tap do |hash| keys.each do |key| hash[key] = regular_reader(key) end end end def casted Hash.new.tap do |hash| @casted_keys.each do |key| hash[key] = regular_reader(key) end end end def casted!(*keys) keys.map(&:to_s).each do |key| @casted_keys << key if key?(key) end end def casting!(*keys) keys.map(&:to_s).each do |key| @casting_keys << key if key?(key) end end protected def uncast!(*keys) @casted_keys.delete *keys.map(&:to_s) end def cast!(key) key = convert_key(key) return unless key?(key) return regular_reader(key) if casted?(key) raise SystemStackError, "already casting #{key}" if casting?(key) casting! key value = if @cast_proc.arity == 1 @cast_proc.call regular_reader(key) elsif @cast_proc.arity == 2 @cast_proc.call self, regular_reader(key) elsif @cast_proc.arity == 3 @cast_proc.call self, key, regular_reader(key) else @cast_proc.call end value = regular_writer(key, value) casted! key value ensure @casting_keys.delete convert_key(key) end def cast_all! keys.each{|key| cast! key} end def convert_key(key) key.kind_of?(Symbol) ? key.to_s : key end end
true