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
39735d0972a3b4bdfe5faa8705fbded84dadd9cc
Ruby
taratip/chillow
/spec/apartment_spec.rb
UTF-8
2,271
2.984375
3
[]
no_license
require 'spec_helper' describe Apartment do it 'should take 8 arguments to construct a apartment object' do expect(Apartment.new("123 Boston st.", "Boston", "MA", "02116", "1300", "2016-09-01", "2017-09-01", 4)).to be_a(Apartment) end it 'has readers for address, town, state, zip, rent, lease start date and lease end date' do apartment = Apartment.new("123 Boston st.", "Boston", "MA", "02116", "1300", "2016-09-01", "2017-09-01", 4) expect(apartment.address).to eq("123 Boston st.") expect(apartment.city_or_town).to eq("Boston") expect(apartment.state).to eq("MA") expect(apartment.zip_code).to eq("02116") expect(apartment.rent).to eq("1300") expect(apartment.lease_start_date.to_s).to eq("2016-09-01") expect(apartment.lease_end_date.to_s).to eq("2017-09-01") expect(apartment.capacity).to eq 4 end it 'has a reader for occupants' do apartment = Apartment.new("123 Boston st.", "Boston", "MA", "02116", "1300", "2016-09-01", "2017-09-01", 4) expect(apartment.occupants.size).to eq 0 end let(:apartment) { Apartment.new("123 Boston st.", "Boston", "MA", "02116", "1300", "2016-09-01", "2017-09-01", 4) } describe '#add_item' do it 'occupant number should be one' do occupant = Occupant.new("John", "Doe") apartment.add_item(occupant) expect(apartment.occupants.size).to eq 1 end end describe '#remove_item' do it 'occupant number should be zero' do john = Occupant.new("John", "Doe") apartment.add_item(john) apartment.remove_item(john) expect(apartment.occupants.size).to eq 0 end end describe '#full?' do it 'return true if no vacant space' do apartment.add_item(Occupant.new("John", "Doe")) apartment.add_item(Occupant.new("John", "Doe")) apartment.add_item(Occupant.new("John", "Doe")) apartment.add_item(Occupant.new("John", "Doe")) expect(apartment.full?(apartment.occupants)).to eq true end it 'return false if there is vacant space' do apartment.add_item(Occupant.new("John", "Doe")) apartment.add_item(Occupant.new("John", "Doe")) apartment.add_item(Occupant.new("John", "Doe")) expect(apartment.full?(apartment.occupants)).to eq false end end end
true
308b235cbec26977094d74653e9e5171d0d3d353
Ruby
sametcilli/caesar_cipher
/caesar_cipher.rb
UTF-8
594
3.84375
4
[]
no_license
def convert(char, right) new_i = (char.ord + right) lowerlist = ("a".ord.."z".ord).to_a upperlist = ("A".ord.."Z".ord).to_a #p upperlist #p char.ord, new_i, upperlist[2], "Z".ord - new_i, upperlist["Z".ord - new_i].chr case char.ord when "a".ord.."z".ord lowerlist[(new_i - "z".ord) - 1].chr when "A".ord.."Z".ord upperlist[(new_i - "Z".ord) - 1].chr else char end end def caesar_cipher(input, right) words = input.split("") words.map!{|s| convert(s, right) } words.join() end puts caesar_cipher("What a string!", 5)
true
3d6dfb1ff2207573397b68d7fd2ae8c110704403
Ruby
szabgab/code-maven.com
/examples/ruby/split_comma_limit.rb
UTF-8
134
3.09375
3
[]
no_license
require 'pp' words_str = 'Foo,Bar,Baz,Moo,Zorg' words_arr = words_str.split(',', 3) pp words_arr # ["Foo", "Bar", "Baz,Moo,Zorg"]
true
52f6649b3ec35a4b7767f3e0dfd519f0f559fddc
Ruby
Messi2002/furima-28804
/spec/models/category_spec.rb
UTF-8
3,499
2.578125
3
[]
no_license
require 'rails_helper' RSpec.describe Item, type: :model do before do @item = FactoryBot.build(:item) @item.image = fixture_file_upload('public/images/test_image.png') end describe '商品情報の登録' do context '商品情報の登録がうまくいくとき' do it 'item,introduction,category_id,status_id,price,postage_payer_id,preparation_day_id,ship_location_id,imageが存在すれば登録できる' do expect(@item).to be_valid end it '価格の範囲が、¥300以上であること' do price = '300' expect(@item).to be_valid end it '価格の範囲が、¥9999999以下であること' do price = '9999999' expect(@item).to be_valid end it '販売価格は半角数字のみ入力可能であること' do price = '300' expect(@item).to be_valid end end context '商品情報の登録がうまくいかなかったとき' do it 'itemが空だと登録できない' do @item.item = '' @item.valid? expect(@item.errors.full_messages).to include("Item can't be blank") end it 'introductionが空だと登録できない' do @item.introduction = ' ' @item.valid? expect(@item.errors.full_messages).to include("Introduction can't be blank") end it 'category_idを選択しないと登録できない' do @item.category_id = 1 @item.valid? expect(@item.errors.full_messages).to include('Category must be other than 1') end it 'status_idを選択しないと登録できない' do @item.status_id = 1 @item.valid? expect(@item.errors.full_messages).to include('Status must be other than 1') end it 'priceが空だと登録できない' do @item.price = ' ' @item.valid? expect(@item.errors.full_messages).to include("Price can't be blank") end it 'postage_payer_idを選択しないと登録できない' do @item.postage_payer_id = 1 @item.valid? expect(@item.errors.full_messages).to include('Postage payer must be other than 1') end it 'preparation_day_idを選択しないと登録できない' do @item.preparation_day_id = 1 @item.valid? expect(@item.errors.full_messages).to include('Preparation day must be other than 1') end it 'ship_location_idを選択しないと登録できない' do @item.ship_location_id = 1 @item.valid? expect(@item.errors.full_messages).to include('Ship location must be other than 1') end it 'priceが¥299以下だと登録できない' do @item.price = '299' @item.valid? expect(@item.errors.full_messages).to include('Price is out of setting range') end it 'priceが¥10000000以上だと登録できない' do @item.price = '10000000' @item.valid? expect(@item.errors.full_messages).to include('Price is out of setting range') end it 'priceが半角数字でないと登録できない' do @item.price = '10000' @item.valid? expect(@item.errors.full_messages).to include('Price is out of setting range') end it 'imageがないと登録できない' do @item.image = nil @item.valid? expect(@item.errors.full_messages).to include("Image can't be blank") end end end end
true
242bedef613b842fac25357d75a48ce2f7d699d6
Ruby
tochman/hash-demo
/lib/my_hash.rb
UTF-8
2,473
3.28125
3
[]
no_license
require 'terminal-table' require 'byebug' class MyHash attr_accessor :grid def initialize self.grid = populate_grid end def check_neighbours(coord) if all_water_cells?(coord) :all_water else :ships_around end end def populate_grid grid = {} [*'A'..'J'].each do |l| [*1..10].each do |n| grid["#{l}#{n}".to_sym] = 'w' end end grid end def draw_grid rows = get_grid_values table = Terminal::Table.new :headings => ['', *'1'..'10'], :rows => rows table.render end def as_html rows = get_grid_values html = '<table><tr><th>-</th>' [*'1'..'10'].each { |i| html.concat "<th>#{i}</th>" } html.concat '</tr>' rows.each do |row| html.concat '<tr>' row.each { |cell| html.concat "<td>#{cell}</td>" } html.concat '</tr>' end html.concat '</table>' html end require 'builder' def builder rows = get_grid_values html = Builder::XmlMarkup.new(indent: 2) html.table { html.tr { [*'0'..'10'].each {|h| html.th(h)} } rows.each do |row| html.tr { row.each { |value| html.td(value) }} end } end def get_grid_values grid_values = [] [*'A'..'J'].each do |letter| row_hash = self.grid.select { |key, value| key.to_s.match(letter) } arr = ["#{letter}"] arr.push(row_hash.values) grid_values.push(arr.flatten) end grid_values end def place_ship(coord) if self.grid[coord] == 'w' self.grid[coord] = 's' else raise 'can not do that' end end def all_water_cells?(coord) right_n = get_right_n_coord(coord) left_n = get_left_n_coord(coord) self.grid[right_n] == 'w' && self.grid[left_n] == 'w' end def get_coord(coord, direction) #get_coord(:A1, :down) method_to_run = self.method("get_#{direction}_n_coord".to_sym) method_to_run.call coord end def get_right_n_coord(coord) #byebug l = (coord[0].codepoints.first + 1).chr coord.to_s.gsub(coord[0],l).to_sym end def get_left_n_coord(coord) l = (coord[0].codepoints.first - 1).chr coord.to_s.gsub(coord[0],l).to_sym end def get_down_n_coord(coord) #byebug n = coord[1,2].next coord.to_s.gsub(coord[1,2],n).to_sym end def get_up_n_coord(coord) #byebug n = (coord[1,2].to_i) -1 coord.to_s.gsub(coord[1,2],n.to_s).to_sym end end
true
07733dd9000e8c776ca8402f38530ff1f0ea8b68
Ruby
tenzin2017/ruby_fundamentals1
/exercise4_4.rb
UTF-8
196
3.671875
4
[]
no_license
puts "Enter your name" user_name = gets.chomp if (user_name.length > 10) puts " Hi! #{user_name}" elsif (user_name.length < 10) puts "Hello! #{user_name}" else puts "Hey! #{user_name}" end
true
b03d95273dbacd6c287c1a67c196e816c4311c26
Ruby
mateowh/checkout
/spec/promotion_spec.rb
UTF-8
1,492
3.0625
3
[]
no_license
require 'promotion' require 'items/lavender_heart' class DummyTestClass include Promotion end RSpec.describe Promotion do let(:dummy_class) { DummyTestClass.new } describe '.discount_60_spend' do let(:basket_total) { 100 } let(:items) { [] } subject { dummy_class.discount_60_spend(basket_total, items) } it 'returns a discount of 10% of the basket total for values > 60' do expect(subject).to eq(10) end context 'when basket total is 60 or less' do let(:basket_total) { 60 } it 'returns 0' do expect(subject).to eq(0) end end end describe '.discount_2_hearts' do let(:basket_total) { 100 } let(:heart_1) { LavenderHeart.new } let(:heart_2) { LavenderHeart.new } let(:items) { [heart_1, heart_2] } subject { dummy_class.discount_2_hearts(basket_total, items) } it 'discounts each lavender heart to £8.50' do expect(subject).to eq(1.5) end context 'when there are less than 2 lavender hearts' do let(:items) { [heart_1] } it 'returns 0 discount' do expect(subject).to eq(0) end end context 'when there are 2 other items (not lavender hearts)' do let(:other_item_1) { instance_double('PersonalisedCufflinks') } let(:other_item_2) { instance_double('PersonalisedCufflinks') } let(:items) { [other_item_1, other_item_2] } it 'does not discount anything' do expect(subject).to eq(0) end end end end
true
2878b4e108a1048f3cdf5d5ce3a19fb56e4d36f8
Ruby
rossyoung5/tts-ruby_projects
/array_example.rb
UTF-8
221
3.5
4
[]
no_license
fruit = ["apple", "orange", "banana"] fruit << "tomato" fruit.push("kiwi") fruit.each_with_index do |fruit_item, index| puts "#{fruit_item} with an index of #{index}" end fruit.each { |fruit_item| puts "#{fruit_item}"}
true
e3f22fdc747a063bf84a0faf5690fc2fd2b475eb
Ruby
LoveMyData/atdis
/lib/atdis/model.rb
UTF-8
7,044
2.5625
3
[ "MIT" ]
permissive
require 'multi_json' require 'active_model' require 'date' module ATDIS module TypeCastAttributes extend ActiveSupport::Concern included do class_attribute :attribute_types end module ClassMethods # of the form {section: Fixnum, address: String} def set_field_mappings(p) define_attribute_methods(p.keys.map{|k| k.to_s}) # Convert all values to arrays. Doing this for the sake of tidier notation self.attribute_types = {} p.each do |k,v| v = [v] unless v.kind_of?(Array) self.attribute_types[k] = v end end end end ErrorMessage = Struct.new :message, :spec_section do def empty? message.empty? end # Make this behave pretty much like a string def to_s message end end class Model include ActiveModel::Validations include Validators include ActiveModel::AttributeMethods include TypeCastAttributes attribute_method_suffix '_before_type_cast' attribute_method_suffix '=' attr_reader :attributes, :attributes_before_type_cast # Stores any part of the json that could not be interpreted. Usually # signals an error if it isn't empty. attr_accessor :json_left_overs, :json_load_error attr_accessor :url validate :json_loaded_correctly! validate :json_left_overs_is_empty # Partition the data into used and unused by returning [used, unused] def self.partition_by_used(data) used, unused = {}, {} if data.respond_to?(:each) data.each do |key, value| if attribute_keys.include?(key) used[key] = value else unused[key] = value end end else unused = data end [used, unused] end def self.read_url(url) r = read_json(RestClient.get(url.to_s).to_str) r.url = url.to_s r end def self.read_json(text) begin data = MultiJson.load(text, symbolize_keys: true) interpret(data) rescue MultiJson::LoadError => e a = interpret({response: []}) a.json_load_error = e.to_s a end end def self.interpret(*params) used, unused = partition_by_used(*params) new(used.merge(json_left_overs: unused)) end def json_loaded_correctly! if json_load_error errors.add(:json, ErrorMessage["Invalid JSON: #{json_load_error}", nil]) end end def json_errors_local r = [] # First show special json error if !errors[:json].empty? r << [nil, errors[:json]] end errors.keys.each do |attribute| # The :json attribute is special if attribute != :json e = errors[attribute] r << [{attribute => attributes_before_type_cast[attribute.to_s]}, e.map{|m| ErrorMessage["#{attribute} #{m}", m.spec_section]}] unless e.empty? end end r end def json_errors_in_children r = [] attributes.each do |attribute_as_string, value| attribute = attribute_as_string.to_sym e = errors[attribute] if value.respond_to?(:json_errors) r += value.json_errors.map{|a, b| [{attribute => a}, b]} elsif value.kind_of?(Array) f = value.find{|v| v.respond_to?(:json_errors) && !v.json_errors.empty?} r += f.json_errors.map{|a, b| [{attribute => [a]}, b]} if f end end r end def json_errors json_errors_local + json_errors_in_children end # Have we tried to use this attribute? def used_attribute?(a) !attributes_before_type_cast[a].nil? end def json_left_overs_is_empty if json_left_overs && !json_left_overs.empty? # We have extra parameters that shouldn't be there errors.add(:json, ErrorMessage["Unexpected parameters in json data: #{MultiJson.dump(json_left_overs)}", "4"]) end end def initialize(params={}) @attributes, @attributes_before_type_cast = {}, {} params.each do |attr, value| self.send("#{attr}=", value) end if params end def self.attribute_keys attribute_types.keys end # Does what the equivalent on Activerecord does def self.attribute_names attribute_types.keys.map{|k| k.to_s} end def self.cast(value, type) # If it's already the correct type (or nil) then we don't need to do anything if value.nil? || value.kind_of?(type) value # Special handling for arrays. When we typecast arrays we actually typecast each member of the array elsif value.kind_of?(Array) value.map {|v| cast(v, type)} elsif type == DateTime cast_datetime(value) elsif type == URI cast_uri(value) elsif type == String cast_string(value) elsif type == Fixnum cast_fixnum(value) elsif type == RGeo::GeoJSON cast_geojson(value) # Otherwise try to use Type.interpret to do the typecasting elsif type.respond_to?(:interpret) type.interpret(value) if value else raise end end private def attribute(attr) @attributes[attr] end def attribute_before_type_cast(attr) @attributes_before_type_cast[attr] end def attribute=(attr, value) @attributes_before_type_cast[attr] = value @attributes[attr] = Model.cast(value, attribute_types[attr.to_sym][0]) end def self.cast_datetime(value) # This would be much easier if we knew we only had to support Ruby 1.9 or greater because it has # an implementation built in. Because for the time being we need to support Ruby 1.8 as well # we'll build an implementation of parsing by hand. Ugh. # Referencing http://www.w3.org/TR/NOTE-datetime # In section 4.3.1 of ATDIS 1.0.4 it shows two variants of iso 8601, either the full date # or the full date with hours, seconds, minutes and timezone. We'll assume that these # are the two variants that are allowed. if value.respond_to?(:match) && value.match(/^\d\d\d\d-\d\d-\d\d(T\d\d:\d\d:\d\d(Z|(\+|-)\d\d:\d\d))?$/) begin DateTime.parse(value) rescue ArgumentError nil end end end def self.cast_uri(value) begin URI.parse(value) rescue URI::InvalidURIError nil end end def self.cast_string(value) value.to_s end # This casting allows nil values def self.cast_fixnum(value) value.to_i if value end def self.cast_geojson(value) RGeo::GeoJSON.decode(hash_symbols_to_string(value)) end # Converts {foo: {bar: "yes"}} to {"foo" => {"bar" => "yes"}} def self.hash_symbols_to_string(hash) if hash.respond_to?(:each_pair) result = {} hash.each_pair do |key, value| result[key.to_s] = hash_symbols_to_string(value) end result else hash end end end end
true
3b6296a28d7537d4ea290859ef15811aabb25fa3
Ruby
tyrbo/mastermind
/test/game_test.rb
UTF-8
878
2.78125
3
[]
no_license
require './test/test_helper.rb' require './lib/game.rb' class GameTest < MiniTest::Test def test_a_game_starts_with_zero_guesses g = Game.new assert_equal 0, g.guesses.count end def test_add_a_guess g = Game.new g.start g.guess('RGBY') assert_equal 1, g.guesses.count end def test_only_valid_guesses_are_added g = Game.new g.start g.guess(nil) assert_equal 0, g.guesses.count g.guess('RRRR') assert_equal 1, g.guesses.count end def test_cant_guess_if_game_isnt_started g = Game.new assert_raises(GameNotStarted) { g.guess('RGBY') } end def test_starting_a_game_should_generate_a_new_sequence g = Game.new g.start assert g.sequence end def test_starting_another_game_should_raise_exception g = Game.new g.start assert_raises(GameAlreadyStarted) { g.start } end end
true
dba7f017b8d40a1b80ad3864cd0230c5bda8d813
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/word-count/9f2a3f9824d942929f0f3ba07fbce575.rb
UTF-8
304
3.359375
3
[]
no_license
class Words attr_reader :sentence def initialize(string) @sentence = normalize(string) end def count sentence.each_with_object(Hash.new(0)) do |word, hash| hash[word] += 1 end end private def normalize(string) string.downcase.gsub(/\W+/, ' ').split(" ") end end
true
1815f19b6b233d5906a5e74ed21de6ce01ef3b23
Ruby
lynettepod/programming-book
/Ch7-Hashes/hash_ex2.rb
UTF-8
473
4.125
4
[]
no_license
#hash_ex2.rb # Merge will not change the original hash; Merge! is destructive and will change the original hash to the result of the merged hash created h1 = {a: 120, b: 90, c: 60} h2 = {a: 200, b: 700, d: 89, e: 200} h3 = h1.merge(h2) # Merged with regular merge; both original hashes stay the same #h3 = h1.merge!(h2) #Merged with merge!; h1 original hash is overwritten with the merged hash h3 puts "This is h1" p h1 puts "This is h2" p h2 puts "This is h3" p h3
true
fd6a200506a8ae60cd46dc9e7e3a2dd145306dac
Ruby
laurenherdman/learn_ruby
/03_simon_says/simon_says.rb
UTF-8
613
3.84375
4
[]
no_license
def echo (input) input end def shout (cap) cap.upcase end def repeat (string, num = 2) output = [] while num > 0 output.push(string) num -= 1 end output.join(' ') end def start_of_word(word, number) word[0..number-1] end def first_word(some_words) first_word = some_words.split(' ') first_word[0] end def titleize (title) lowercase = ["and", "over", "the"] string_array = [] title.split.map do |word| if lowercase.include?(word) string_array.push(word) else string_array.push(word.capitalize) end end output = string_array.join (' ') output[0] = output[0].upcase output end
true
103677abe043e6a9e5f9269f02dfd19e06329305
Ruby
probpgh/learnruby_exercises
/ex13b.rb
UTF-8
245
2.859375
3
[]
no_license
alpha, bravo, charlie, delta, echo = ARGV puts "Your first variable is: #{alpha}" puts "Your second variable is: #{bravo}" puts "Your third variable is: #{charlie}" puts "Your fourth variable is: #{delta}" puts "Your fifth variable is: #{echo}"
true
990875ad4df4bcaa8d1260d7c4fac56edfee8f9c
Ruby
richcole/Griff
/cass_browser/util.rb
UTF-8
488
3.484375
3
[]
no_license
def min_of(x,y) if x != nil && x <= y then return x else return y end end def max_of(x,y) if x != nil && x >= y then return x else return y end end def contents_of_file(filename) result = nil File.open(filename) { |file| return file.read() } return result end def count_in xs count = 0 for x in xs do count += 1 end return count end def time_block(text) before = Time.now yield after = Time.now puts "Time (" + text + "): " + (after - before).to_s end
true
22934debc44681c7a1f105c2cf5cbfe48d93979d
Ruby
illogic-al/rosalind-ruby-solutions
/lib/rna.rb
UTF-8
395
3.140625
3
[]
no_license
require_relative 'dna' class RNA attr_reader :bases, :dna_bases, :rna_bases def initialize(sequence) @bases = Gandalf.the_validator(sequence) end def dna_bases? @bases.include? "T" end def rna_bases? @bases.include? "U" end def dna_to_rna @rna_bases = @bases.gsub("T", "U") end def print_rna_bases dna_bases? ? dna_to_rna : @rna_bases end end
true
a72e09eab7fbe87d395ee7869c1c9e77349bdc68
Ruby
tcweinlandt/TnTStats
/TnT_replay_parser.rb
UTF-8
2,340
2.765625
3
[]
no_license
require 'rubygems' require 'nokogiri' require 'cgi' require 'open-uri' def parse(filename) @doc = Nokogiri::XML(File.open(filename)) player_names = @doc.xpath("//Name") player_ids = @doc.xpath("//m_SteamID") player_teams = @doc.xpath("//Team") player_picks = @doc.xpath("//Card") names = [] ids = [] teams = [] picks = [] player_names.each {|name| names << name.to_s} player_ids.each {|id| ids << id.to_s} player_teams.each {|team| teams << team.to_s} player_picks.each {|card| picks << card.to_s} parsed_to_string(teams,names,ids,picks) end def parsed_to_string(teams,names,ids,picks) playarr = [] names.delete_at(0) ids.each_index do |i| playarr[i]=[] playarr[i] << teams[i][6] playarr[i] << names[i][6..-8] playarr[i] << ids[i][11..-13] newpicks = picks.slice!(0,6) playarr[i] << picks_to_str(newpicks) end playarr end def picks_to_str(picks_arr) outstr = '' picks_arr.each do |pick| if pick[6] == 'w' case pick[13,2] when 'li'; outstr << '0' when 'sq'; outstr << '1' when 'to'; outstr << '2' when 'pi'; outstr << '3' when 'mo'; outstr << '4' when 'fe'; outstr << '5' when 'ch'; outstr << '6' when 'sn'; outstr << '7' when 'fa'; outstr << '8' when 'sk'; outstr << '9' when 'bo'; outstr << 'a' when 'fo'; outstr << 'b' when 'ba'; outstr << 'c' when 'wo'; outstr << 'd' when 'ow'; outstr << 'e' end else case pick[16,3] when 'bar'; outstr << 'f' when 'lan'; outstr << 'g' when 'mac'; outstr << 'h' when 'bal'; outstr << 'i' when 'art'; outstr << 'j' end end end outstr end stats_arr = parse("Straw_beats_rofl.xml") winner_name = "" winner_id = "" winner_picks = "" loser_name = "" loser_id = "" loser_picks = "" if stats_arr[0][0] = 1 winner_name = CGI::escape(stats_arr[0][1]) winner_id = stats_arr[0][2] winner_picks = stats_arr[0][3] loser_name = CGI::escape(stats_arr[1][1]) loser_id = stats_arr[1][2] loser_picks = stats_arr[1][3] else winner_name = CGI::escape(stats_arr[1][1]) winner_id = stats_arr[1][2] winner_picks = stats_arr[1][3] loser_name = CGI::escape(stats_arr[0][1]) loser_id = stats_arr[0][2] loser_picks = stats_arr[0][3] end sitename = "http://localhost:3000/matches/create" open("#{sitename}/#{winner_name}/#{winner_id}/#{winner_picks}/#{loser_name}/#{loser_id}/#{loser_picks}")
true
22d75ae628ee3454153d8fbfb3f7063a81c8a3b9
Ruby
hambrice/playlister-sinatra-v-000
/app/models/artist.rb
UTF-8
354
2.875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class Artist < ActiveRecord::Base has_many :songs has_many :genres, through: :songs #binding.pry def slug self.name.split.collect do |word| #binding.pry word.downcase.gsub(/\W/,"") end.join("-") end def self.find_by_slug(slug) Artist.all.select do |artist| artist.slug == slug end[0] end end
true
f1b9cba29fcd5510925f9bd4c96b4899bcc8ecd2
Ruby
ankush-amura/ShopReg
/app/models/customer.rb
UTF-8
964
2.875
3
[]
no_license
class Customer < ApplicationRecord # this is the callback that needs to perform capitalization opoeration as soon as customer is created after_initialize do |user| puts "u have Successfully Created A customer" user.name.capitalize! end # this callback is responsible for updating the contact to some country code before_save do |user| user.contact="+91 "+user.contact end # validates the presence of name while submitting the data to the database model validates :name, presence: true # validates the confirmation of the email if both the written emails are same validates :email ,confirmation: true # validates password with confirmation and uniqueness and length attributes validates :password , confirmation: true , uniqueness: true , length: {minimum: 8} # validates contact info for its uniqueness and numericality validates :contact , uniqueness: true , numericality: true , length: { is: 10 } end
true
fa609a22f6ab4d9116ad7e1bfa093d981d3e1550
Ruby
bryansray/loottrackr
/spec/models/character_spec.rb
UTF-8
2,959
2.875
3
[]
no_license
require 'spec_helper' describe Character do it "should have looted many items" do character = Character.create item = Item.create loot = Loot.create :item => item, :character => character character.should have(1).items end it "should be able to equip a specific item", :focus => false do head_item = Item.new :name => "Head Item" character = Character.new :name => "Bryan" character.equip_item :name => "Head Item", :slot => :head character.should have(1).equipped_items end it "should only be able to have one slot equipped at a time", :focus => false do character = Character.new :name => "Bryan" head_item_1 = character.equipped_items.build :name => "Head Item 1", :slot => 'head' head_item_2 = character.equipped_items.build :name => "Head Item 2", :slot => 'head' character.should have(1).equipped_items end it "should have only specific items equipped", :focus => true do character = Character.new item1 = Item.new :slot => :head item2 = Item.new :slot => :head loot = Loot.new :item => item1, :character => character loot = Loot.create :item => item2, :character => character, :equipped => true # testing = character.loots.includes(:item).where(:items => { :slot => :head }) # pp testing character.should have(1).equipped_items end it "should be able to calcuate their gear score" do character = Character.create item1 = Item.create :level => 410 item2 = Item.create :level => 410 loot = Loot.create :item => item1, :character => character, :equipped => true loot = Loot.create :item => item2, :character => character, :equipped => true character.should have(2).equipped_items character.gear_level.should == 410 end it "should average out all the equipped items" do character = Character.create item1 = Item.create :level => 410 item2 = Item.create :level => 397 loot = Loot.create :item => item1, :character => character, :equipped => true loot = Loot.create :item => item2, :character => character, :equipped => true character.gear_level.should == 403.5 end it "should return zero if there is no equipped items" do character = Character.create item1 = Item.create :level => 410 item2 = Item.create :level => 397 loot = Loot.create :item => item1, :character => character loot = Loot.create :item => item2, :character => character character.gear_level.should == 0 end it "should return true if there is no item equipped in the specified slot" do character = Character.new character.should be_free_slot_for(:head) end it "should return false if the character has an item equipped in that slot" do head_slot_item = Item.new :slot => Slot.new(:name => "Head") character = Character.new :equipped_items => [head_slot_item] character.should_not be_free_slot_for(:head) end end
true
356138ffba8566e6742cf376709bcffb95637905
Ruby
daveguymon/think_like_a_programmer
/decode_a_message.rb
UTF-8
840
3.390625
3
[]
no_license
def decoder(sequence) upcase = ("A".."Z").to_a downcase = ("a".."z").to_a punctuation = ["!", "?", ",", ".", " ", ";", '"', "'"] mode = "up" decoded_message = [] sequence.each do |integer| if mode == "punct" remainder = integer % 9 else remainder = integer % 27 end if remainder == 0 if mode == "punct" mode = "up" elsif mode == "up" mode = "down" elsif mode = "down" mode = "punct" end next end decoded_message << upcase[remainder - 1] if mode == "up" decoded_message << downcase[remainder - 1] if mode == "down" decoded_message << punctuation[remainder - 1] if mode == "punct" end return decoded_message.join end code = [18, 12312, 171, 763, 98423, 1208, 216, 11, 500, 18, 241, 0, 32, 20620, 27, 10] decoder(code)
true
d968d1cac553bd7244530aaef97b0229a35d446c
Ruby
ricardosikic/ruby-materia
/clase7-madlibgame/ex1.rb
UTF-8
403
3.28125
3
[]
no_license
# Este famoso juego es sobre crear frases a traves de la informacion recogida # y almacenada en las variables puts 'ingresa un color' color_rosas = gets.chomp() puts 'ingresa tipo de flores' nombre_flores = gets.chomp() puts 'ingresa nombre de famoso' nombre_celebridad = gets.chomp() puts ('las rosas son ' + color_rosas) puts (nombre_flores + ' azules') puts ('te quiero ' + nombre_celebridad)
true
f13fdbad4a1dabb0f762e37d6a82e9f315ec0d99
Ruby
Precnet/Lesson_8
/cargo_train.rb
UTF-8
950
3.28125
3
[]
no_license
# frozen_string_literal: true require_relative 'train.rb' require_relative 'train_iterator.rb' class CargoTrain < Train attr_reader :carriages include TrainIterator def initialize(train_number) super('cargo', 0, train_number) @carriages = [] end def add_carriage(carriage) error = 'Can`t add new carriages while train is moving.' raise RailwayError, error unless @current_speed.zero? error_message = 'Wrong carriage for this type of train!' raise RailwayError, error_message unless carriage_correct?(carriage) carriages.push(carriage) super() end def remove_carriage(carriage_number) error_message = 'There are no such carriages.' unless @carriages.map(&:number).include?(carriage_number) raise ArgumentError, error_message end @carriages.reject! { |carriage| carriage.number == carriage_number } super() end def number_of_carriages @carriages.length end end
true
95d6117f3cbf358c621cd90cceb077843dd5daae
Ruby
litola/phase-0-tracks
/ruby/iteration.rb
UTF-8
1,014
3.8125
4
[]
no_license
def print_block x = 20 y = 10 puts "this is before running the block" yield(x, y) puts "this is after running the block" end print_block { |x,y| puts "name is #{x} and age is #{y}."} sports = ["Footbal", "Soccer", "Tennis"] leagues = { football: "NFL", soccer: "MLS", tennis: "Summer Circuit" } sports.each {|s| puts "sport: #{s}"} leagues.each{|key, value| puts "The #{key} league is #{value}"} sports.map! do |s| s = s.upcase + " LEAGUE" end p sports numbers = [ 25, 14, 2, 4, 56, 12] numbers.delete_if {|number| number <= 12} p numbers numbers = [ 25, 14, 2, 4, 56, 12] lnumbers = numbers.take_while{|number| number < 55 } p lnumbers numbers = [ 25, 14, 2, 4, 56, 12] lownumbers = numbers.select {|number| number <= 12} p lownumbers letters = { :a => "A", :b => "B", :c => "C" } letters.delete_if{|key,value| key == 'b'.to_sym} p letters letters = { "a" => "A", "b" => "B", "c" => "C" } fletters = letters.select{|k,v| k < "b"} p fletters
true
9a603faf25c182c4c79f3639ebd1cc590524ff02
Ruby
ChristineBuell/phase-0-tracks
/ruby/list/todo_list.rb
UTF-8
264
3.359375
3
[]
no_license
class TodoList def initialize(array) @array = array end def get_items @array end def add_item(item) @array << item end def delete_item(item) @array.delete(item) @array end def get_item(index) @array[index] end end
true
ea1ed1d56fdc164a129aa3050098ca5b5b120abd
Ruby
jbhdeconinck/oystercard2310
/spec/oystercard_spec.rb
UTF-8
1,995
2.953125
3
[]
no_license
require 'oystercard' describe Oystercard do let(:max_balance) {Oystercard::MAX_BALANCE} let(:min_balance) {Oystercard::MIN_FARE} let(:station) { double(:station, name: "Aldgate", zone: "1") } let(:journey) { double(:journey, fare: 1, start_journey: station, reset: nil, entry_station: station, exit_station: station, in_progress?: true, end_journey: nil)} let(:empty_card) { Oystercard.new } subject(:new_card) { Oystercard.new(balance: 20, journey: journey)} it 'balance is zero when initialized' do expect(empty_card.balance).to eq 0 end describe '#top_up' do it 'balance increases by top up amount' do expect {new_card.top_up 1}.to change{subject.balance}.by 1 end it 'error if over maximum balance' do msg = "Over maximum balance of #{max_balance}" expect { empty_card.top_up(max_balance + 1) }.to raise_error msg end end describe '#touch_in' do it 'raises error when insufficient balance' do msg = "you have insufficient funds, please top up by #{min_balance}" expect {empty_card.touch_in(station)}.to raise_error msg end end describe '#touch_out' do let(:journey) { double(:journey, fare: 1, start_journey: station, reset: nil, entry_station: station, exit_station: station, in_progress?: false, end_journey: nil)} it 'check balance changes at touch out by minimum balance' do new_card.touch_in(station) expect { new_card.touch_out(station) }.to change{ subject.balance }.by(-min_balance) end it 'touching out changes journey status to not be in journey' do new_card.touch_in(station) new_card.touch_out(station) expect(new_card.in_journey?).to eq false end it 'checks touching out logs the journey' do new_card.touch_out(station) expect(new_card.log).to eq [journey] end it 'forgets the entry station upon touching out' do new_card.touch_out(station) expect(new_card.station).to eq nil end end end
true
ab493f4cda2003b8bfc67793a0e3a7898835d151
Ruby
ElvinGarcia/ttt-10-current-player-q-000
/lib/current_player.rb
UTF-8
400
3.46875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# #turn_count could be done with 3 lines of code def turn_count(board) moves_taken=0 board.each{|token| unless token ==" " || token == "" || token == nil moves_taken+=1 end } return moves_taken end def current_player(board) board.reject!{|item|item == "" || item == " " || item == nil} if board.length.even? == true return "X" else return "O" end end
true
bcf442a751e55f3648d4708f371110ae5c50459a
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/pig-latin/01166fb8262e4516811bedef7fb7a4f9.rb
UTF-8
586
2.953125
3
[]
no_license
module PigLatin extend self def translate phrase phrase.gsub(WORD, &method(:translate_word)) end WORD = /\p{L}+/ VOWEL_START = Regexp.union( /^[aeiou]/, /^[yx][^aeiou]/ ) CONSONANT_START = Regexp.union( /^[^aeiou]*qu/, /^[^aeiou]+/ ) private_constant :WORD, :VOWEL_START, :CONSONANT_START private def translate_word word case word when VOWEL_START word + "ay" when CONSONANT_START beginning, rest = Regexp.last_match, Regexp.last_match.post_match "#{rest}#{beginning}ay" else word end end end
true
a81be894e2b0ed6574aa444a8438cde98da0ac50
Ruby
mmilata/vpsadminos
/osctld/lib/osctld/db/pooled_list.rb
UTF-8
969
2.609375
3
[]
no_license
require 'osctld/db/list' module OsCtld class DB::PooledList < DB::List # Find object by `id` and `pool`. # # There are two ways to specify a pool: # - use the `pool` argument # - when `pool` is `nil` and `id` contains a colon, it is parsed as # `<pool>:<id>` def find(id, pool = nil, &block) if pool.nil? && id.index(':') pool, id = id.split(':') end sync do obj = objects.detect do |v| next if v.id != id next(true) if pool.nil? if pool.is_a?(Pool) v.pool.name == pool.name elsif pool.is_a?(String) v.pool.name == pool else fail "invalid pool type '#{pool.class}', extected OsCtld::Pool or String" end end if block block.call(obj) else obj end end end def contains?(id, pool = nil) !find(id, pool).nil? end end end
true
3daaf1408b398f79287c8c92e272687823abbe72
Ruby
Thoanguyen65/ProjectEuler
/ex07/ex07.rb
UTF-8
353
3.828125
4
[]
no_license
# What is the 10001st prime number def check_prime?(n) (2..n - 1).each do | i| if n % i == 0 return false end end return true end #start: number 3 count_position = 1 number = 1 until count_position == 10001 number += 2 if check_prime?(number) count_position += 1 end end puts "answer: #{number}"
true
4aa4c3acd77a777bbcb58d124a61c2780c269498
Ruby
civol/HDLRuby
/lib/HDLRuby/hruby_rsim.rb
UTF-8
48,422
2.625
3
[ "MIT" ]
permissive
require "HDLRuby/hruby_high" # require "HDLRuby/hruby_low_resolve" require "HDLRuby/hruby_bstr" require "HDLRuby/hruby_values" module HDLRuby::High ## # Library for describing the Ruby simulator of HDLRuby # ######################################################################## class SystemT ## Enhance a system type with Ruby simulation. # Tell if the simulation is in multithread mode or not. attr_reader :multithread # The current global time. attr_reader :time ## Add untimed objet +obj+ def add_untimed(obj) @untimeds << obj end ## Add timed behavior +beh+. # Returns the id of the timed behavior. def add_timed_behavior(beh) @timed_behaviors << beh @total_timed_behaviors += 1 return @total_timed_behaviors - 1 end ## Remove timed beahvior +beh+ def remove_timed_behavior(beh) # puts "remove_timed_behavior" @timed_behaviors.delete(beh) end ## Add +sig+ to the list of active signals. def add_sig_active(sig) # puts "Adding activated signal=#{sig.fullname}" @sig_active << sig end ## Advance the global simulator. def advance # # Display the time # self.show_time shown_values = {} # Get the behaviors waiting on activated signals. until @sig_active.empty? do # puts "sig_active.size=#{@sig_active.size}" # puts "sig_active=#{@sig_active.map {|sig| sig.fullname}}" # Look for the behavior sensitive to the signals. # @sig_active.each do |sig| # sig.each_anyedge { |beh| @sig_exec << beh } # if (sig.c_value.zero? && !sig.f_value.zero?) then # # puts "sig.c_value=#{sig.c_value.content}" # sig.each_posedge { |beh| @sig_exec << beh } # elsif (!sig.c_value.zero? && sig.f_value.zero?) then # sig.each_negedge { |beh| @sig_exec << beh } # end # end @sig_active.each do |sig| next if (sig.c_value.eql?(sig.f_value)) # next if (sig.c_value.to_vstr == sig.f_value.to_vstr) # puts "for sig=#{sig.fullname}" sig.each_anyedge { |beh| @sig_exec << beh } if (sig.c_value.zero?) then # puts "sig.c_value=#{sig.c_value.content}" sig.each_posedge { |beh| @sig_exec << beh } elsif (!sig.c_value.zero?) then sig.each_negedge { |beh| @sig_exec << beh } end end # Update the signals. @sig_active.each { |sig| sig.c_value = sig.f_value } # puts "first @sig_exec.size=#{@sig_exec.size}" @sig_exec.uniq! {|beh| beh.object_id } # puts "now @sig_exec.size=#{@sig_exec.size}" # Display the activated signals. @sig_active.each do |sig| if !shown_values[sig].eql?(sig.f_value) then self.show_signal(sig) shown_values[sig] = sig.f_value end end # Clear the list of active signals. @sig_active.clear # puts "sig_exec.size=#{@sig_exec.size}" # Execute the relevant behaviors and connections. @sig_exec.each { |obj| obj.execute(:par) } @sig_exec.clear @sig_active.uniq! {|sig| sig.object_id } # puts "@sig_active.size=#{@sig_active.size}" # Compute the nearest next time stamp. @time = (@timed_behaviors.min {|b0,b1| b0.time <=> b1.time }).time end # puts "@time=#{@time}" # Display the time self.show_time end ## Run the simulation from the current systemT and outputs the resuts # on simout. def sim(simout) HDLRuby.show "Initializing Ruby-level simulator..." HDLRuby.show "#{Time.now}#{show_mem}" # Merge the included. self.merge_included! # Process par in seq. self.par_in_seq2seq! # Initializes the time. @time = 0 # Initializes the time and signals execution buffers. @tim_exec = [] @sig_exec = [] # Initilize the list of untimed objects. @untimeds = [] # Initialize the list of currently exisiting timed behavior. @timed_behaviors = [] # Initialize the list of activated signals. @sig_active = [] # Initializes the total number of timed behaviors (currently # existing or not: used for generating the id of the behaviors). @total_timed_behaviors = 0 # Initilizes the simulation. self.init_sim(self) # Initialize the displayer. self.show_init(simout) # Initialize the untimed objects. self.init_untimeds # puts "End of init_untimed." # Maybe there is nothing to execute. return if @total_timed_behaviors == 0 # Is there more than one timed behavior. if @total_timed_behaviors <= 1 then # No, no need of multithreading. @multithread = false # Simple execute the block of the behavior. @timed_behaviors[0].block.execute(:seq) else # Yes, need of multithreading. @multithread = true # Initializes the run mutex and the conditions. @mutex = Mutex.new @master = ConditionVariable.new @master_flag = 0 @slave = ConditionVariable.new @slave_flags_not = 0 @num_done = 0 # First all the timed behaviors are to be executed. @timed_behaviors.each {|beh| @tim_exec << beh } # But starts locked. @slave_flags_not = 2**@timed_behaviors.size - 1 # Starts the threads. @timed_behaviors.each {|beh| beh.make_thread } HDLRuby.show "Starting Ruby-level simulator..." HDLRuby.show "#{Time.now}#{show_mem}" # Run the simulation. self.run_init do # # Wake the behaviors. # @timed_behaviors.each {|beh| beh.run } until @tim_exec.empty? do # Execute the time behaviors that are ready. self.run_ack self.run_wait # Advance the global simulator. self.advance # # Display the time # self.show_time # shown_values = {} # # Get the behaviors waiting on activated signals. # until @sig_active.empty? do # # # Update the signals. # # @sig_active.each { |sig| sig.c_value = sig.f_value } # # puts "sig_active.size=#{@sig_active.size}" # # Look for the behavior sensitive to the signals. # @sig_active.each do |sig| # sig.each_anyedge { |beh| @sig_exec << beh } # if (sig.c_value.zero? && !sig.f_value.zero?) then # # puts "sig.c_value=#{sig.c_value.content}" # sig.each_posedge { |beh| @sig_exec << beh } # elsif (!sig.c_value.zero? && sig.f_value.zero?) then # sig.each_negedge { |beh| @sig_exec << beh } # end # end # # Update the signals. # @sig_active.each { |sig| sig.c_value = sig.f_value } # # puts "first @sig_exec.size=#{@sig_exec.size}" # @sig_exec.uniq! {|beh| beh.object_id } # # Display the activated signals. # @sig_active.each do |sig| # if !shown_values[sig].eql?(sig.f_value) then # self.show_signal(sig) # shown_values[sig] = sig.f_value # end # end # # Clear the list of active signals. # @sig_active.clear # # puts "sig_exec.size=#{@sig_exec.size}" # # Execute the relevant behaviors and connections. # @sig_exec.each { |obj| obj.execute(:par) } # @sig_exec.clear # @sig_active.uniq! {|sig| sig.object_id } # # puts "@sig_active.size=#{@sig_active.size}" # end # # Advance time. # @time = (@timed_behaviors.min {|b0,b1| b0.time <=> b1.time }).time break if @timed_behaviors.empty? # Schedule the next timed behavior to execute. @tim_exec = [] @timed_behaviors.each do |beh| @tim_exec << beh if beh.time == @time end # puts "@tim_exec.size=#{@tim_exec.size}" # puts "@timed_bevaviors.size=#{@timed_behaviors.size}" end end end end ## Initialize the simulation for system +systemT+. def init_sim(systemT) # puts "init_sim for #{self} (#{self.name})" # Recurse on the signals. self.each_signal { |sig| sig.init_sim(systemT) } # Recure on the scope. self.scope.init_sim(systemT) end ## Initialize the untimed objects. def init_untimeds @untimeds.each do |obj| if obj.is_a?(Behavior) then obj.block.execute(:seq) else obj.execute(:seq) end end end ## Initialize run for executing +ruby_block+ def run_init(&ruby_block) @mutex.synchronize(&ruby_block) end ## Request for running for timed behavior +id+ def run_req(id) # puts "run_req with id=#{id} and @slave_flags_not=#{@slave_flags_not}" @slave.wait(@mutex) while @slave_flags_not[id] == 1 end ## Tell running part done for timed behavior +id+. def run_done(id) # puts "run_done with id=#{id}" @num_done += 1 @slave_flags_not |= 2**id if @num_done == @tim_exec.size # puts "All done." @master_flag = 1 @master.signal end end ## Wait for all the run to complete. def run_wait # puts "run_wait" @master.wait(@mutex) unless @master_flag == 1 @num_done = 0 @master_flag = 0 end ## Acknowledge the run request the executable timed behavior. def run_ack # puts "run_ack" mask = 0 @tim_exec.each { |beh| mask |= 2**beh.id } mask = 2**@total_timed_behaviors - 1 - mask @slave_flags_not &= mask @slave.broadcast end ## Initializes the displayer def show_init(simout) # Sets the simulation output. @simout = simout end ## Displays the time. def show_time @simout.puts("# #{@time}ps") end ## Displays the value of signal +sig+. def show_signal(sig) @simout.puts("#{sig.fullname}: #{sig.f_value.to_vstr}") end ## Displays value +val+. def show_value(val) @simout.print(val.to_vstr) end ## Displays string +str+. def show_string(str) @simout.print(str) end ## Returns the name of the signal with its hierarchy. def fullname @fullname ||= (self.parent ? self.parent.fullname + ":" : "") + self.name.to_s return @fullname end end class Scope ## Enhance a scope with Ruby simulation. ## Initialize the simulation for system +systemT+. def init_sim(systemT) # Recurse on the inner signals. self.each_inner { |sig| sig.init_sim(systemT) } # Recurse on the behaviors. self.each_behavior { |beh| beh.init_sim(systemT) } # Recurse on the systemI. self.each_systemI { |sys| sys.init_sim(systemT) } # Recurse on the connections. # self.each_connection { |cnx| cnx.init_sim(systemT) } self.each_connection do |cnx| # Connection to a real expression? if !cnx.right.is_a?(RefObject) then # Yes. cnx.init_sim(systemT) else # No, maybe the reverse connection is also required. # puts "cnx.left.object=#{cnx.left.object.fullname} cnx.right.object=#{cnx.right.object.fullname}" cnx.init_sim(systemT) if cnx.left.is_a?(RefObject) then sigL = cnx.left.object prtL = sigL.parent if prtL.is_a?(SystemT) and prtL.each_inout.any?{|e| e.object_id == sigL.object_id} then # puts "write to right with sigL=#{sigL.fullname}." Connection.new(cnx.right.clone,cnx.left.clone).init_sim(systemT) end end end end # Recurse on the sub scopes. self.each_scope { |sco| sco.init_sim(systemT) } end ## Returns the name of the signal with its hierarchy. def fullname @fullname ||= self.parent.fullname + ":" + self.name.to_s return @fullname end end ## Extends the TypeTuple class for Ruby simulation. class TypeTuple # Add the possibility to change the direction. def direction=(dir) @direction = dir == :little ? :little : :big end end ## Extends the TypeStruct class for Ruby simulation. class TypeStruct # Add the possibility to change the direction. def direction=(dir) @direction = dir == :little ? :little : :big end end ## # Describes a behavior. class Behavior ## Execute the expression. def execute(mode) return self.block.execute(mode) end ## Initialize the simulation for system +systemT+. def init_sim(systemT) # Add the behavior to the list of untimed objects. systemT.add_untimed(self) # Process the sensitivity list. # Is it a clocked behavior? events = self.each_event.to_a if events.empty? then # No events, this is not a clock behavior. # And it is not a time behavior neigther. # Generate the events list from the right values. # First get the references. refs = self.block.each_node_deep.select do |node| node.is_a?(RefObject) && !node.leftvalue? && !node.parent.is_a?(RefObject) end.to_a # Keep only one ref per signal. refs.uniq! { |node| node.fullname } # puts "refs=#{refs.map {|node| node.fullname}}" # The get the left references: the will be removed from the # events. left_refs = self.block.each_node_deep.select do |node| node.is_a?(RefObject) && node.leftvalue? && !node.parent.is_a?(RefObject) end.to_a # Keep only one left ref per signal. left_refs.uniq! { |node| node.fullname } # Remove the inner signals from the list. self.block.each_inner do |inner| refs.delete_if {|r| r.fullname == inner.fullname } end # Remove the left refs. left_refs.each do |l| refs.delete_if {|r| r.fullname == l.fullname } end # Generate the event. events = refs.map {|ref| Event.new(:anyedge,ref.clone) } # Add them to the behavior for further processing. events.each {|event| self.add_event(event) } end # Now process the events: add the behavior to the corresponding # activation list of the signals of the events. self.each_event do |event| sig = event.ref.object case event.type when :posedge sig.add_posedge(self) when :negedge sig.add_negedge(self) else sig.add_anyedge(self) end end # Now process the block. self.block.init_sim(systemT) end ## Returns the name of the signal with its hierarchy. def fullname return self.parent.fullname end end ## # Describes a timed behavior. # # NOTE: # * this is the only kind of behavior that can include time statements. # * this kind of behavior is not synthesizable! class TimeBehavior ## Get the current time of the behavior. attr_accessor :time ## Get the id of the timed behavior. attr_reader :id ## Initialize the simulation for system +systemT+. def init_sim(systemT) @sim = systemT # Add the behavior to the list of timed behavior. @id = systemT.add_timed_behavior(self) # Initialize the time to 0. @time = 0 # Initialize the statements. self.block.init_sim(systemT) end # Create the execution thread def make_thread systemT = @sim @thread = Thread.new do # puts "In thread." # sleep systemT.run_init do begin # puts "Starting thread" systemT.run_req(@id) # self.block.execute(:par) self.block.execute(:seq) # puts "Ending thread" rescue => e puts "Got exception: #{e.full_message}" end systemT.remove_timed_behavior(self) systemT.run_done(@id) end end end ## (Re)start execution of the thread. def run # Run. @thread.run end end ## # Describes an event. class Event # Nothing to do. end ## # Module for extending signal classes with Ruby-level simulation. module SimSignal # Access the current and future value. attr_accessor :c_value, :f_value ## Initialize the simulation for +systemT+ def init_sim(systemT) # Initialize the local time to -1 @time = -1 @sim = systemT # Recurse on the sub signals if any. if self.each_signal.any? then self.each_signal {|sig| sig.init_sim(systemT) } return end # No sub signal, really initialize the current signal. if self.value then @c_value = self.value.execute(:par).to_value @f_value = @c_value.to_value # puts "init signal value at=#{@c_value.to_bstr}" # The signal is considered active. systemT.add_sig_active(self) else # @c_value = Value.new(self.type,"x" * self.type.width) # @f_value = Value.new(self.type,"x" * self.type.width) @c_value = Value.new(self.type,"x") @f_value = Value.new(self.type,"x") end end ## Adds behavior +beh+ activated on a positive edge of the signal. def add_posedge(beh) # Recurse on the sub signals. self.each_signal {|sig| sig.add_posedge(beh) } # Apply on current signal. @posedge_behaviors ||= [] @posedge_behaviors << beh end ## Adds behavior +beh+ activated on a negative edge of the signal. def add_negedge(beh) # Recurse on the sub signals. self.each_signal {|sig| sig.add_negedge(beh) } # Apply on current signal. @negedge_behaviors ||= [] @negedge_behaviors << beh end ## Adds behavior +beh+ activated on a any edge of the signal. def add_anyedge(beh) # Recurse on the sub signals. self.each_signal {|sig| sig.add_anyedge(beh) } # Apply on current signal. @anyedge_behaviors ||= [] @anyedge_behaviors << beh end ## Iterates over the behaviors activated on a positive edge. def each_posedge(&ruby_block) @posedge_behaviors ||= [] @posedge_behaviors.each(&ruby_block) end ## Iterates over the behaviors activated on a negative edge. def each_negedge(&ruby_block) @negedge_behaviors ||= [] @negedge_behaviors.each(&ruby_block) end ## Iterates over the behaviors activated on any edge. def each_anyedge(&ruby_block) @anyedge_behaviors ||= [] @anyedge_behaviors.each(&ruby_block) end ## Execute the expression. def execute(mode) # puts "Executing signal=#{self.fullname} in mode=#{mode} with c_value=#{self.c_value} and f_value=#{self.f_value}" return @mode == :seq ? self.f_value : self.c_value # return @mode == :seq || mode == :seq ? self.f_value : self.c_value end ## Assigns +value+ the the reference. def assign(mode,value) # # Set the next value. # @f_value = value # Set the mode. @mode = mode # @f_value = value.cast(self.type) # Cast not always inserted by HDLRuby normally if @sim.time > @time or !value.impedence? then # puts "assign #{value.content} to #{self.fullname}" @f_value = value.cast(self.type) # Cast not always inserted by HDLRuby normally @time = @sim.time end end ## Assigns +value+ at +index+ (integer or range). def assign_at(mode,value,index) # @f_value = @f_value.assign_at(mode,value,index) # Sets the next value. if (@f_value.equal?(@c_value)) then # Need to duplicate @f_value to avoid side effect. @f_value = Value.new(@f_value.type,@f_value.content.clone) end @f_value[index] = value # Sets the mode @mode = mode end ## Returns the name of the signal with its hierarchy. def fullname @fullname ||= self.parent.fullname + ":" + self.name.to_s return @fullname end end ## # Describes a signal. class SignalI include SimSignal end ## # Describes a constant signal. class SignalC include SimSignal end ## # Describes a system instance. # # NOTE: an instance can actually represented muliple layers # of systems, the first one being the one actually instantiated # in the final RTL code. # This layering can be used for describing software or partial # (re)configuration. class SystemI ## Initialize the simulation for system +systemT+. def init_sim(systemT) # Recurse on the Eigen system. self.systemT.init_sim(systemT) end end ## # Describes a non-HDLRuby code chunk. class Chunk # TODO end ## # Decribes a set of non-HDLRuby code chunks. class Code # TODO end ## # Describes a statement. # # NOTE: this is an abstract class which is not to be used directly. class Statement ## Initialize the simulation for system +systemT+. def init_sim(systemT) raise "init_sim must be implemented in class #{self.class}" end ## Executes the statement in +mode+ (:blocking or :nonblocking) # NOTE: to be overrided. def execute(mode) raise "execute must be implemented in class #{self.class}" end end ## # Decribes a transmission statement. class Transmit ## Initialize the simulation for system +systemT+. def init_sim(systemT) self.left.init_sim(systemT) self.right.init_sim(systemT) end ## Executes the statement. def execute(mode) # puts "execute Transmit in mode=#{mode} for left=#{self.left.object.fullname}" if left.is_a?(RefObject) self.left.assign(mode,self.right.execute(mode)) end end ## # Describes an if statement. class If ## Initialize the simulation for system +systemT+. def init_sim(systemT) self.yes.init_sim(systemT) # self.each_noif { |cond,stmnt| stmnt.init_sim(systemT) } self.each_noif do |cond,stmnt| cond.init_sim(systemT) stmnt.init_sim(systemT) end self.no.init_sim(systemT) if self.no end ## Executes the statement. def execute(mode) # puts "execute hif with mode=#{mode}" # Check the main condition. if !(self.condition.execute(mode).zero?) then self.yes.execute(mode) else # Check the other conditions (elsif) success = false self.each_noif do |cond,stmnt| if !(cond.execute(mode).zero?) then stmnt.execute(mode) success = true break end end self.no.execute(mode) if self.no && !success end end end ## # Describes a when for a case statement. class When ## Initialize the simulation for system +systemT+. def init_sim(systemT) self.statement.init_sim(systemT) end end ## # Describes a case statement. class Case ## Initialize the simulation for system +systemT+. def init_sim(systemT) self.each_when { |wh| wh.init_sim(systemT) } self.default.init_sim(systemT) if self.default end ## Executes the statement. def execute(mode) unless self.each_when.find do |wh| if wh.match.eql?(self.value.execute(mode)) then wh.statement.execute(mode) return end end self.default.execute(mode) if self.default end end end ## # Describes a delay: not synthesizable. class Delay ## Get the time of the delay in pico seconds. def time_ps case self.unit when :ps return self.value.to_i when :ns return self.value.to_i * 1000 when :us return self.value.to_i * 1000000 when :ms return self.value.to_i * 1000000000 when :s return self.value.to_i * 1000000000000 end end end ## # Describes a print statement: not synthesizable! class Print ## Initialize the simulation for system +systemT+. def init_sim(systemT) @sim = systemT end ## Executes the statement. def execute(mode) self.each_arg.map do |arg| case arg when StringE @sim.show_string(arg.content) when SignalI @sim.show_signal(arg) when SignalC @sim.show_signal(arg) else @sim.show_value(arg.execute(mode)) end end end end ## # Describes a system instance (re)configuration statement: not synthesizable! class Configure ## TODO end ## # Describes a wait statement: not synthesizable! class TimeWait ## Initialize the simulation for system +systemT+. def init_sim(systemT) @sim = systemT end ## Executes the statement. def execute(mode) @behavior ||= self.behavior @behavior.time += self.delay.time_ps if @sim.multithread then # Multi thread mode: synchronize. # puts "Stopping #{@behavior.object_id} (@behavior.time=#{@behavior.time})..." @sim.run_done(@behavior.id) # puts "Rerunning #{@behavior.object_id} (@behavior.time=#{@behavior.time})..." @sim.run_req(@behavior.id) else # No thread mode, need to advance the global simulator. @sim.advance end end end ## # Describes a timed loop statement: not synthesizable! class TimeRepeat ## Initialize the simulation for system +systemT+. def init_sim(systemT) # Recurde on the statement. self.statement.init_sim(systemT) end ## Executes the statement. def execute(mode) self.number.times { self.statement.execute(mode) } end end ## # Describes a timed terminate statement: not synthesizable! class TimeTerminate ## Initialize the simulation for system +systemT+. def init_sim(systemT) @sim = systemT end ## Executes the statement. def execute(mode) # @behavior ||= self.get_behavior # @behavior.terminate exit end end ## # Describes a block. class Block ## Initialize the simulation for system +systemT+. def init_sim(systemT) # Recurse on the inner signals. self.each_inner { |sig| sig.init_sim(systemT) } # Recurde on the statements. self.each_statement { |stmnt| stmnt.init_sim(systemT) } end ## Executes the statement. def execute(mode) # puts "execute block of mode=#{self.mode}" self.each_statement { |stmnt| stmnt.execute(self.mode) } end ## Returns the name of the signal with its hierarchy. def fullname @fullname ||= self.parent.fullname + ":" + self.name.to_s return @fullname end end class If ## Returns the name of the signal with its hierarchy. def fullname return self.parent.fullname end end class When ## Returns the name of the signal with its hierarchy. def fullname return self.parent.fullname end end class Case ## Returns the name of the signal with its hierarchy. def fullname return self.parent.fullname end end # Describes a timed block. # # NOTE: # * this is the only kind of block that can include time statements. # * this kind of block is not synthesizable! class TimeBlock ## Initialize the simulation for system +systemT+. def init_sim(systemT) self.each_statement { |stmnt| stmnt.init_sim(systemT) } end ## Executes the statement. def execute(mode) # puts "TimeBlock" self.each_statement do |stmnt| # puts "Going to execute statement: #{stmnt}" stmnt.execute(self.mode) end # puts "End TimeBlock" end end ## # Describes a connection. class Connection ## Initialize the simulation for system +systemT+. def init_sim(systemT) # Add the connection to the list of untimed objets. systemT.add_untimed(self) # Recurse on the left and right. self.left.init_sim(systemT) self.right.init_sim(systemT) # Process the sensitivity list. # Is it a clocked behavior? events = [] # Generate the events list from the right values. # First get the references. refs = self.right.each_node_deep.select do |node| node.is_a?(RefObject) && !node.parent.is_a?(RefObject) end.to_a # Keep only one ref per signal. refs.uniq! { |node| node.fullname } # puts "connection input: #{self.left.fullname}" # puts "connection refs=#{refs.map {|node| node.fullname}}" # # Generate the event. # events = refs.map {|ref| Event.new(:anyedge,ref) } # # Add them to the behavior for further processing. # events.each {|event| self.add_event(event) } # Now process the events: add the connection to the corresponding # activation list of the signals of the events. refs.each {|ref| ref.object.add_anyedge(self) } end ## Executes the statement. def execute(mode) # puts "connection left=#{left.object.fullname}" # self.left.assign(mode,self.right.execute(mode)) self.left.assign(:seq,self.right.execute(mode)) end end ## # Describes an expression. # # NOTE: this is an abstract class which is not to be used directly. class Expression ## Initialize the simulation for system +systemT+. def init_sim(systemT) # By default: do nothing. end ## Executes the expression in +mode+ (:blocking or :nonblocking) # NOTE: to be overrided. def execute(mode) raise "execute must be implemented in class #{self.class}" end end ## # Describes a value. class Value ## Initialize the simulation for system +systemT+. def init_sim(systemT) # Nothing to do. end # include Vprocess ## Executes the expression. def execute(mode) return self end end ## # Describes a cast. class Cast ## Initialize the simulation for system +systemT+. def init_sim(systemT) # Recurse on the child. self.child.init_sim(systemT) end ## Executes the expression. def execute(mode) # puts "child=#{self.child}" # puts "child object=#{self.child.object}(#{self.child.object.name})" if self.child.is_a?(RefObject) # Shall we reverse the content of a concat. if self.child.is_a?(Concat) && self.type.direction != self.child.type.direction then # Yes, do it. res = self.child.execute(mode,:reverse) else res = self.child.execute(mode) end # puts "res=#{res}" # Cast it. res = res.cast(self.type,true) # Returns the result. return res end end ## # Describes an operation. # # NOTE: this is an abstract class which is not to be used directly. class Operation ## Left to the children. end ## # Describes an unary operation. class Unary ## Initialize the simulation for system +systemT+. def init_sim(systemT) # Recurse on the child. self.child.init_sim(systemT) end ## Execute the expression. def execute(mode) # puts "Unary with operator=#{self.operator}" # Recurse on the child. tmp = self.child.execute(mode) # puts "tmp=#{tmp}" # Apply the operator. return tmp.send(self.operator) end end ## # Describes an binary operation. class Binary ## Initialize the simulation for system +systemT+. def init_sim(systemT) # Recurse on the children. self.left.init_sim(systemT) self.right.init_sim(systemT) end ## Execute the expression. def execute(mode) # Recurse on the children. tmpl = self.left.execute(mode) tmpr = self.right.execute(mode) # Apply the operator. return tmpl.send(self.operator,tmpr) end end ## # Describes a selection operation (generalization of the ternary operator). # # NOTE: choice is using the value of +select+ as an index. class Select ## Initialize the simulation for system +systemT+. def init_sim(systemT) # Recurse on the children. self.select.init_sim(systemT) self.each_choice { |choice| choice.init_sim(systemT) } end ## Execute the expression. def execute(mode) unless @mask then # Need to initialize the execution of the select. width = (@choices.size-1).width width = 1 if width == 0 @mask = 2**width - 1 @choices.concat([@choices[-1]] * (2**[email protected])) end # Recurse on the select. tmps = self.select.execute(mode).to_i & @mask # puts "select tmps=#{tmps}, @choices.size=#{@choices.size}" # Recurse on the selection result. return @choices[tmps].execute(mode) end end ## # Describes a concatenation expression. class Concat ## Initialize the simulation for system +systemT+. def init_sim(systemT) # Recurse on the children. self.each_expression { |expr| expr.init_sim(systemT) } end ## Execute the expression. def execute(mode, reverse=false) # Recurse on the children. tmpe = self.each_expression.map { |expr| expr.execute(mode) } # Ensure the order of the elements matches the type. if (self.type.direction == :little && !reverse) || (self.type.direction == :big && reverse) then tmpe.reverse! end # puts "concat result=#{Vprocess.concat(*tmpe).to_bstr}" # Concatenate the result. return Vprocess.concat(*tmpe) end end ## # Describes a reference expression. # # NOTE: this is an abstract class which is not to be used directly. class Ref ## Initialize the simulation for system +systemT+. def init_sim(systemT) raise "assign must be implemented in class #{self.class}" end ## Assigns +value+ to the reference. # Must be overriden. def assign(mode,value) raise "assign must be implemented in class #{self.class}" end ## Assigns +value+ at +index+ (integer or range). def assign_at(mode,value,index) raise "assign_at must be implemented in class #{self.class}" end end ## # Describes concatenation reference. class RefConcat ## Initialize the simulation for system +systemT+. def init_sim(systemT) self.each_ref { |ref| ref.init_sim(systemT) } end ## Execute the expression. def execute(mode) # Recurse on the children. tmpe = self.each_ref.map { |ref| ref.execute(mode) } # Concatenate the result. return tmpe.reduce(:concat) end ## Assigns +value+ the the reference. def assign(mode,value) # puts "self.type=#{self.type}" # Flatten the value type. value.type = [value.type.width].to_type pos = 0 width = 0 # Recurse on the children. @refs.reverse_each do |ref| # puts "ref.type=#{ref.type}" width = ref.type.width # puts "pos=#{pos} width=#{width}, pos+width-1=#{pos+width-1}" # puts "value.content=#{value.content}" # puts "value[(pos+width-1).to_expr..pos.to_expr].content=#{value[(pos+width-1).to_expr..pos.to_expr].content}" ref.assign(mode,value[(pos+width-1).to_expr..pos.to_expr]) # Prepare for the next reference. pos += width end end ## Assigns +value+ at +index+ (integer or range). def assign_at(mode,value,index) # Get the refered value. refv = self.execute(mode,value) # Assign to it. refv.assign_at(mode,value,index) # Update the reference. self.assign(mode,refv) end end ## # Describes a index reference. class RefIndex ## Initialize the simulation for system +systemT+. def init_sim(systemT) self.ref.init_sim(systemT) end ## Execute the expression. def execute(mode) # Recurse on the children. tmpr = self.ref.execute(mode) idx = self.index.execute(mode) # puts "tmpr=#{tmpr} idx=#{idx} tmpr[idx]=#{tmpr[idx]}" return tmpr[idx] end ## Assigns +value+ the the reference. def assign(mode,value) # Compute the index. idx = self.index.execute(mode).to_i # Assigns. self.ref.assign_at(mode,value,idx) end ## Assigns +value+ at +index+ (integer or range). def assign_at(mode,value,index) # Get the refered value. refv = self.execute(mode) # Assign to it. refv = refv.assign_at(mode,value,index) # Update the refered value. self.assign(mode,refv) end end ## # Describes a range reference. class RefRange ## Initialize the simulation for system +systemT+. def init_sim(systemT) self.ref.init_sim(systemT) end ## Execute the expression. def execute(mode) # Recurse on the children. tmpr = self.ref.execute(mode) rng = (self.range.first.execute(mode)).. (self.range.last.execute(mode)) # puts "tmpr=#{tmpr} rng=#{rng} tmpr[rng]=#{tmpr[rng]}" return tmpr[rng] end ## Assigns +value+ the the reference. def assign(mode,value) # Compute the index range. rng = (self.range.first.execute(mode).to_i).. (self.range.last.execute(mode).to_i) # Assigns. self.ref.assign_at(mode,value,rng) end ## Assigns +value+ at +index+ (integer or range). def assign_at(mode,value,index) # Get the refered value. refv = self.execute(mode) # Assign to it. refv = refv.assign_at(mode,value,index) # Update the refered value. self.assign(mode,refv) end end ## # Describes a name reference. class RefName # Not used? end ## # Describe a this reference. # # This is the current system. class RefThis # Not used. end ## # Describes a high-level object reference: no low-level equivalent! class RefObject ## Initialize the simulation for system +systemT+. def init_sim(systemT) # puts "init_sim for RefObject=#{self}" @sim = systemT # Modify the exectute and assign methods if the object has # sub signals (for faster execution). if self.object.each_signal.any? then ## Execute the expression. self.define_singleton_method(:execute) do |mode| # Recurse on the children. iter = self.object.each_signal iter = iter.reverse_each unless self.object.type.direction == :big tmpe = iter.map {|sig| sig.execute(mode) } # Concatenate the result. # return tmpe.reduce(:concat) return Vprocess.concat(*tmpe) end ## Assigns +value+ the the reference. self.define_singleton_method(:assign) do |mode,value| # puts "RefObject #{self} assign with object=#{self.object}" # Flatten the value type. value.type = [value.type.width].to_type pos = 0 width = 0 # Recurse on the children. iter = self.object.each_signal iter = iter.reverse_each unless self.object.type.direction == :big iter.each do |sig| width = sig.type.width sig.assign(mode,value[(pos+width-1).to_expr..pos.to_expr]) # Tell the signal changed. if !(sig.c_value.eql?(sig.f_value)) then @sim.add_sig_active(sig) end # Prepare for the next reference. pos += width end end end end ## Execute the expression. def execute(mode) return self.object.execute(mode) end ## Assigns +value+ the the reference. def assign(mode,value) self.object.assign(mode,value) # puts "name=#{self.object.name} value=#{value.to_vstr}" # puts "c_value=#{self.object.c_value.content}" if self.object.c_value # puts "f_value=#{self.object.f_value.content}" if self.object.f_value if !(self.object.c_value.eql?(self.object.f_value)) then @sim.add_sig_active(self.object) end end ## Assigns +value+ at +index+ (integer or range). def assign_at(mode,value,index) # puts "name=#{self.object.name} value=#{value.to_vstr}" self.object.assign_at(mode,value,index) # puts "c_value=#{self.object.c_value.content}" if self.object.c_value # puts "f_value=#{self.object.f_value.content}" if self.object.f_value if !(self.object.c_value.eql?(self.object.f_value)) then @sim.add_sig_active(self.object) end end end ## # Describes a string. # # NOTE: This is not synthesizable! class StringE end end
true
85bdc2b5fb30084c66307a123b9afcba091cd4f1
Ruby
smart-rb/smart_types
/spec/types/value/string_spec.rb
UTF-8
4,224
2.53125
3
[ "MIT" ]
permissive
# frozen_string_literal: true RSpec.describe 'SmartCore::Types::Value::String' do shared_examples 'type casting' do specify 'type-casting' do expect(type.cast(:test)).to eq('test') expect(type.cast('test')).to eq('test') expect(type.cast(nil)).to eq('') expect(type.cast({})).to eq('{}') expect(type.cast({ a: 1, 'b' => :test })).to eq('{:a=>1, "b"=>:test}') expect(type.cast([])).to eq('[]') expect(type.cast([1, 'test', :test])).to eq('[1, "test", :test]') expect(type.cast(Object.new)).to match(/\A\#<Object:\dx\w{16}>\z/) castable = Class.new { def to_s; 'test'; end; }.new expect(type.cast(castable)).to eq('test') non_castable_1 = Class.new { undef_method :to_s; }.new non_castable_2 = Class.new { def to_s; 2; end }.new non_castable_3 = BasicObject.new expect { type.cast(non_castable_1) }.to raise_error(SmartCore::Types::TypeCastingError) expect { type.cast(non_castable_2) }.to raise_error(SmartCore::Types::TypeCastingError) expect { type.cast(non_castable_3) }.to raise_error(SmartCore::Types::TypeCastingError) end end shared_examples 'type-checking / type-validation (non-nilable)' do specify 'type-checking' do expect(type.valid?('test')).to eq(true) expect(type.valid?(nil)).to eq(false) expect(type.valid?(Object.new)).to eq(false) expect(type.valid?(BasicObject.new)).to eq(false) expect(type.valid?({})).to eq(false) expect(type.valid?([])).to eq(false) expect(type.valid?(:test)).to eq(false) end specify 'type-validation' do expect { type.valid?('test') }.not_to raise_error expect { type.validate!(nil) }.to raise_error(SmartCore::Types::TypeError) expect { type.validate!(Object.new) }.to raise_error(SmartCore::Types::TypeError) expect { type.validate!(BasicObject.new) }.to raise_error(SmartCore::Types::TypeError) expect { type.validate!({}) }.to raise_error(SmartCore::Types::TypeError) expect { type.validate!([]) }.to raise_error(SmartCore::Types::TypeError) expect { type.validate!(:test) }.to raise_error(SmartCore::Types::TypeError) end end shared_examples 'type-checking / type-validation (nilable)' do specify 'type-checking' do expect(type.valid?('test')).to eq(true) expect(type.valid?(nil)).to eq(true) expect(type.valid?(Object.new)).to eq(false) expect(type.valid?(BasicObject.new)).to eq(false) expect(type.valid?({})).to eq(false) expect(type.valid?([])).to eq(false) expect(type.valid?(:test)).to eq(false) end specify 'type-validation' do expect { type.valid?('test') }.not_to raise_error expect { type.valid?(nil) }.not_to raise_error expect { type.validate!(Object.new) }.to raise_error(SmartCore::Types::TypeError) expect { type.validate!(BasicObject.new) }.to raise_error(SmartCore::Types::TypeError) expect { type.validate!({}) }.to raise_error(SmartCore::Types::TypeError) expect { type.validate!([]) }.to raise_error(SmartCore::Types::TypeError) expect { type.validate!(:test) }.to raise_error(SmartCore::Types::TypeError) end end context 'non-nilable type' do let(:type) { SmartCore::Types::Value::String } include_examples 'type casting' include_examples 'type-checking / type-validation (non-nilable)' end context 'runtime-based non-nilable type' do let(:type) { SmartCore::Types::Value::String() } include_examples 'type casting' include_examples 'type-checking / type-validation (non-nilable)' end context 'nilable type' do let(:type) { SmartCore::Types::Value::String.nilable } include_examples 'type casting' include_examples 'type-checking / type-validation (nilable)' end context 'runtime-based nilable type' do let(:type) { SmartCore::Types::Value::String().nilable } include_examples 'type casting' include_examples 'type-checking / type-validation (nilable)' end specify 'has no support for runtime attributes' do expect { SmartCore::Types::Value::String('test') }.to raise_error( SmartCore::Types::RuntimeAttriburtesUnsupportedError ) end end
true
39277d64bbc9b1c7375ee667cf18d6c0d44ce65d
Ruby
marmo002/w2d3assignment2
/exercise14.rb
UTF-8
873
3.890625
4
[]
no_license
my_dogs = [ { :name => 'Ralph', :position => 5 }, { :name => 'Cindy', :position => 8 }, { :name => 'Jade', :position => 11 } ] def get_absent_dogs(my_dogs) absent_dogs = my_dogs.select do |each_dog| each_dog[:position] > 10 end end bad_dogs = get_absent_dogs(my_dogs) p bad_dogs def call_absent_dogs(bad_dogs) list = [] bad_dogs.each do |each_dog| list << each_dog[:name] end return list.each { |name| puts "Come back, #{name}!!"} end call_absent_dogs(bad_dogs) numbers = (1..5).to_a new_numbers = numbers.map do |num| num * 2 end p new_numbers # # my_dogs.map! { |i| # # i[:position] += 5 # # i # # } # p my_dogs def chase_squirrel(dogs) dogs.map! { |i| i[:position] += 5 i } end puts chase_squirrel(my_dogs) def return_dogs(dogs) dogs.map! { |each| each[:position] = 0 each } end puts return_dogs(my_dogs)
true
6442d1a11ecc511821b4a69beea6bc1c1a817588
Ruby
valdineireis/wbotelhos-com-br
/spec/initializers/slug_spec.rb
UTF-8
567
2.9375
3
[ "MIT" ]
permissive
# coding: utf-8 require 'spec_helper' describe String do let(:text) { "City - São João del-rey ('!@#$alive%ˆ&*~^]}" } it 'slug blank' do ' '.slug.should == '' end it 'slug space' do 'a b'.slug.should == 'a-b' end it 'slug last dash' do 'a b !'.slug.should == 'a-b' end it 'keeps underscore' do '_'.slug.should == '_' end it 'replaces hyphen separator to just hyphen' do 'a - a'.slug.should == 'a-a' end it 'slug none alpha alphanumeric' do %(ok!@#$\%ˆ&*()+-={}|[]\\:";'<>?,./).slug.should == 'ok' end end
true
4881aabcd25d080a2c4deeb308b3510b57732b3e
Ruby
fzondlo/elevators
/spec/elevator_router_spec.rb
UTF-8
977
2.703125
3
[]
no_license
require 'pry' require_relative '../elevator_router' require_relative 'spec_helper' describe ElevatorRouter, "Manage Elevators" do context "defaulted with 5 floors" do let(:subject) { described_class.new(5) } it "has a top floor" do expect(subject.top_floor).to eq 5 end it "has a bottom floor" do expect(subject.bottom_floor).to eq 1 end describe "#elevator_count" do it "counts the number of elevators" do expect(subject.elevator_count).to eq 1 end end describe "#elevator_locations" do it "shows you elevator location" do expect(subject.elevator_locations).to eq({0=>1}) end end describe "#move" do it "moves elevator" do subject.add_destination(2) subject.move expect(subject.elevator_locations).to eq({0=>2}) end #it "moves to multiple destinations" do #end end end context "highrise (5 elevators)" do end end
true
242b86f11b43152407d5d40ab97443b3d76e8dd9
Ruby
ericsoderberg/pbc3
/app/controllers/books_controller.rb
UTF-8
1,725
2.59375
3
[]
no_license
class BooksController < ApplicationController def index @books = VerseParser::BIBLE_BOOKS.map{|b| b[0]} @testaments = [{name: 'Old Testament', sections: []}, {name: 'New Testament', sections: []}] testament = @testaments[0] section = nil @max_count = 0 @books.each do |book| if 'Genesis' == book section = {:name => 'Pentatuch', :books => []} testament[:sections] << section elsif 'Joshua' == book section = {:name => 'History', :books => []} testament[:sections] << section elsif 'Job' == book section = {:name => 'Poetry', :books => []} testament[:sections] << section elsif 'Isaiah' == book section = {:name => 'Major Prophets', :books => []} testament[:sections] << section elsif 'Hosea' == book section = {:name => 'Minor Prophets', :books => []} testament[:sections] << section elsif 'Matthew' == book testament = @testaments[1] section = {:name => 'Gospels', :books => []} testament[:sections] << section elsif 'Acts' == book section = {:name => 'Church History', :books => []} testament[:sections] << section elsif 'Romans' == book section = {:name => 'Epistles', :books => []} testament[:sections] << section elsif 'Revelation' == book section = {:name => 'Prophecy', :books => []} testament[:sections] << section end count = Message.count_for_book(book) section[:books] << {:book => book, :count => count} @max_count = [@max_count, count].max end end def show @book = params[:id] @messages = Message.find_by_verses(@book) end end
true
29c4e2ce9bb5c00950ebe0012cc3a23d99c947b5
Ruby
mmlamkin/api-muncher
/test/lib/recipe_test.rb
UTF-8
973
2.71875
3
[]
no_license
require 'test_helper' describe Recipe do it "raises an error without all required parameters" do proc { Recipe.new }.must_raise ArgumentError proc { Recipe.new("Name") }.must_raise ArgumentError end it "must initialize parameters correctly" do recipe = Recipe.new("name", "www.fooditem.com", ['ingredients'], "chicken.jpg", ["dairy free" "soy free"], "www.foodz", "food network") recipe.name.must_equal "name" recipe.uri.must_equal "www.fooditem.com" recipe.ingredients.must_equal ['ingredients'] recipe.image.must_equal "chicken.jpg" recipe.dietary_info.must_equal ["dairy free" "soy free"] recipe.url.must_equal "www.foodz" recipe.source.must_equal "food network" end it "retrieves the id from the uri" do recipe = Recipe.new("name", "www.fooditem.com_123", ['ingredients'], "chicken.jpg", ["dairy free" "soy free"], "www.foodz", "food network") recipe.get_id.must_equal "123" end end
true
2fbf5b50b6e0cb7391bb57609e8c157773af9832
Ruby
jmspsi126/Ruby-sample-userve-
/app/services/payments/stripe.rb
UTF-8
1,053
2.671875
3
[]
no_license
class Payments::Stripe UnsupportedAmountType = Class.new(StandardError) def initialize(stripe_token) @stripe_token = stripe_token @error = nil end def charge!(amount:, description:) amount_in_cents = amount_to_cents(amount) raise UnsupportedAmountType("Amount should be > 0 #{amount}") if amount_in_cents.zero? Stripe::Charge.create( :amount => amount_in_cents, :currency => "usd", :source => stripe_token, # obtained with Stripe.js :description => description ) rescue Stripe::CardError => error # Display this to user, Probably invalid card @error = error return false rescue => error @error = 'Payment by card was unavailable, please try again' NewRelic::Agent.notice_error(error) # TO DO: Send an error message to us to handle this, Generic problem or problem with Stripe(e.g. creds, too manny requests) return false end attr_reader :error private attr_reader :stripe_token def amount_to_cents(amount) (amount.to_f * 100).to_i end end
true
c2992ff09dd4fe1a431ff970ecd90583f8abbed6
Ruby
Varsha1986/ruby_20-8-master
/ruby_20-8-master/polymorphism.rb
UTF-8
369
3.453125
3
[]
no_license
class Duck def initialize(speaking,flying) @speaking = speaking @flying = flying end end class Penguin < Duck def speak @speaking end def fly @flying end end class Bird < Duck def speak @speaking end def fly @flying end end parrot=Penguin.new("woohhhs","fly") puts parrot.speak puts parrot.fly s=Bird.new("woohhhs","fly") puts s.speak puts s.fly
true
7b1db84456493b849b7dd2b6a649ce519b2fce59
Ruby
charlesbjohnson/super_happy_interview_time
/rb/lib/leetcode/lc_394.rb
UTF-8
1,490
3.625
4
[ "MIT" ]
permissive
# frozen_string_literal: true module LeetCode # 394. Decode String module LC394 # Description: # Given an encoded string, return its decoded string. # # The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. # Note that k is guaranteed to be a positive integer. # # You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. # # Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. # For example, there will not be input like 3a or 2[4]. # # Examples: # # Input: s = "3[a]2[bc]" # Output: "aaabcbc" # # Input: s = "3[a2[c]]" # Output: "accaccacc" # # Input: s = "2[abc]3[cd]ef" # Output: "abcabccdcdcdef" # # @param {String} s # @return {String} def decode_string(s) stack = [] count = "" result = "" i = 0 while i < s.length if ("0".."9").cover?(s[i]) count += s[i] elsif s[i] == "[" stack.push([count.to_i, result]) count = "" result = "" elsif s[i] == "]" count, before = stack.pop result = before + (result * count) count = "" else result += s[i] end i += 1 end result end end end
true
18205ddfa9fced3a77d4badb689917049e7702a1
Ruby
Nuix/SuperUtilities
/RubyTests/PlaceholderResolver_MultiValue.rb
UTF-8
7,346
2.75
3
[ "Apache-2.0" ]
permissive
# Demonstrates basic usage of placeholder resolver and multi value placeholders. script_directory = File.dirname(__FILE__) # Initialize super utilities require File.join(script_directory,"SuperUtilities.jar") java_import com.nuix.superutilities.SuperUtilities java_import com.nuix.superutilities.misc.PlaceholderResolver java_import com.nuix.superutilities.misc.NamedStringList $su = SuperUtilities.init($utilities,NUIX_VERSION) pr = PlaceholderResolver.new animals = ["Cat","Dog","Bird"] colors = ["Green","Red","Blue","Black","White"] names = ["Fido","Fluffy","|St. Awesome|","\\/iolet"] nsl_animals = NamedStringList.new nsl_animals.setName("animals") nsl_animals.addAll(animals) nsl_colors = NamedStringList.new nsl_colors.setName("colors") nsl_colors.addAll(colors) nsl_names = NamedStringList.new nsl_names.setName("names") nsl_names.addAll(names) nsls = [ nsl_animals, nsl_colors, nsl_names ] pr.set("age","5") template = "The {animals} '{names}' is {age} and has a {colors} name tag." puts "Template: #{template}" result = pr.resolveTemplateMultiValues(template,nsls) result.each_with_index do |value,value_index| puts "#{(value_index+1).to_s.rjust(3)}.) #{value}" end template = "C:\\{age}\\{animals}\\{colors}NameTag_{names}.txt" puts "Path Template: #{template}" result = pr.resolveTemplatePathMultiValues(template,nsls) result.each_with_index do |value,value_index| puts "#{(value_index+1).to_s.rjust(3)}.) #{value}" end =begin OUTPUT: Template: The {animals} '{names}' is {age} and has a {colors} name tag. 1.) The Cat '\/iolet' is 5 and has a Blue name tag. 2.) The Cat '|St. Awesome|' is 5 and has a White name tag. 3.) The Cat 'Fluffy' is 5 and has a Blue name tag. 4.) The Dog '|St. Awesome|' is 5 and has a White name tag. 5.) The Cat '\/iolet' is 5 and has a White name tag. 6.) The Bird 'Fluffy' is 5 and has a Green name tag. 7.) The Bird '|St. Awesome|' is 5 and has a Black name tag. 8.) The Cat '|St. Awesome|' is 5 and has a Blue name tag. 9.) The Cat 'Fluffy' is 5 and has a White name tag. 10.) The Dog '\/iolet' is 5 and has a White name tag. 11.) The Bird '|St. Awesome|' is 5 and has a Green name tag. 12.) The Bird 'Fido' is 5 and has a White name tag. 13.) The Bird 'Fido' is 5 and has a Black name tag. 14.) The Dog 'Fido' is 5 and has a Black name tag. 15.) The Dog 'Fluffy' is 5 and has a Green name tag. 16.) The Bird '|St. Awesome|' is 5 and has a White name tag. 17.) The Cat '|St. Awesome|' is 5 and has a Black name tag. 18.) The Cat '\/iolet' is 5 and has a Black name tag. 19.) The Bird '|St. Awesome|' is 5 and has a Blue name tag. 20.) The Cat '|St. Awesome|' is 5 and has a Green name tag. 21.) The Cat '|St. Awesome|' is 5 and has a Red name tag. 22.) The Bird '\/iolet' is 5 and has a Black name tag. 23.) The Bird 'Fluffy' is 5 and has a Red name tag. 24.) The Bird 'Fido' is 5 and has a Blue name tag. 25.) The Dog 'Fluffy' is 5 and has a White name tag. 26.) The Bird '\/iolet' is 5 and has a Red name tag. 27.) The Dog 'Fluffy' is 5 and has a Red name tag. 28.) The Cat 'Fido' is 5 and has a Black name tag. 29.) The Cat 'Fido' is 5 and has a Blue name tag. 30.) The Bird 'Fido' is 5 and has a Red name tag. 31.) The Bird '\/iolet' is 5 and has a Blue name tag. 32.) The Dog '\/iolet' is 5 and has a Green name tag. 33.) The Dog '\/iolet' is 5 and has a Blue name tag. 34.) The Dog '|St. Awesome|' is 5 and has a Green name tag. 35.) The Cat '\/iolet' is 5 and has a Green name tag. 36.) The Cat 'Fluffy' is 5 and has a Green name tag. 37.) The Bird 'Fluffy' is 5 and has a Blue name tag. 38.) The Bird 'Fluffy' is 5 and has a White name tag. 39.) The Dog 'Fido' is 5 and has a Red name tag. 40.) The Bird '|St. Awesome|' is 5 and has a Red name tag. 41.) The Cat 'Fido' is 5 and has a Green name tag. 42.) The Bird '\/iolet' is 5 and has a Green name tag. 43.) The Cat 'Fluffy' is 5 and has a Red name tag. 44.) The Cat 'Fluffy' is 5 and has a Black name tag. 45.) The Dog '|St. Awesome|' is 5 and has a Red name tag. 46.) The Dog 'Fluffy' is 5 and has a Black name tag. 47.) The Bird 'Fido' is 5 and has a Green name tag. 48.) The Bird 'Fluffy' is 5 and has a Black name tag. 49.) The Dog 'Fido' is 5 and has a White name tag. 50.) The Bird '\/iolet' is 5 and has a White name tag. 51.) The Dog '\/iolet' is 5 and has a Black name tag. 52.) The Dog '|St. Awesome|' is 5 and has a Black name tag. 53.) The Dog 'Fido' is 5 and has a Blue name tag. 54.) The Cat 'Fido' is 5 and has a Red name tag. 55.) The Dog '\/iolet' is 5 and has a Red name tag. 56.) The Dog '|St. Awesome|' is 5 and has a Blue name tag. 57.) The Cat 'Fido' is 5 and has a White name tag. 58.) The Dog 'Fido' is 5 and has a Green name tag. 59.) The Cat '\/iolet' is 5 and has a Red name tag. 60.) The Dog 'Fluffy' is 5 and has a Blue name tag. Path Template: C:\{age}\{animals}\{colors}NameTag_{names}.txt 1.) C:\5\Dog\BlueNameTag_Fido.txt 2.) C:\5\Cat\BlueNameTag_Fido.txt 3.) C:\5\Dog\RedNameTag__St. Awesome_.txt 4.) C:\5\Bird\RedNameTag____iolet.txt 5.) C:\5\Dog\WhiteNameTag_Fluffy.txt 6.) C:\5\Dog\GreenNameTag____iolet.txt 7.) C:\5\Dog\BlackNameTag__St. Awesome_.txt 8.) C:\5\Cat\GreenNameTag_Fido.txt 9.) C:\5\Bird\BlackNameTag_Fluffy.txt 10.) C:\5\Cat\BlackNameTag__St. Awesome_.txt 11.) C:\5\Cat\RedNameTag_Fido.txt 12.) C:\5\Bird\RedNameTag_Fluffy.txt 13.) C:\5\Cat\GreenNameTag_Fluffy.txt 14.) C:\5\Bird\GreenNameTag____iolet.txt 15.) C:\5\Cat\BlueNameTag_Fluffy.txt 16.) C:\5\Dog\WhiteNameTag_Fido.txt 17.) C:\5\Bird\BlueNameTag__St. Awesome_.txt 18.) C:\5\Dog\BlueNameTag_Fluffy.txt 19.) C:\5\Cat\WhiteNameTag_Fluffy.txt 20.) C:\5\Bird\GreenNameTag__St. Awesome_.txt 21.) C:\5\Bird\BlackNameTag____iolet.txt 22.) C:\5\Cat\BlueNameTag____iolet.txt 23.) C:\5\Bird\BlueNameTag_Fluffy.txt 24.) C:\5\Cat\RedNameTag__St. Awesome_.txt 25.) C:\5\Dog\GreenNameTag_Fido.txt 26.) C:\5\Cat\GreenNameTag__St. Awesome_.txt 27.) C:\5\Bird\RedNameTag_Fido.txt 28.) C:\5\Bird\WhiteNameTag____iolet.txt 29.) C:\5\Dog\BlackNameTag_Fluffy.txt 30.) C:\5\Dog\RedNameTag_Fluffy.txt 31.) C:\5\Dog\WhiteNameTag__St. Awesome_.txt 32.) C:\5\Dog\RedNameTag_Fido.txt 33.) C:\5\Cat\WhiteNameTag____iolet.txt 34.) C:\5\Dog\BlackNameTag_Fido.txt 35.) C:\5\Bird\BlackNameTag_Fido.txt 36.) C:\5\Cat\WhiteNameTag_Fido.txt 37.) C:\5\Cat\RedNameTag____iolet.txt 38.) C:\5\Bird\GreenNameTag_Fluffy.txt 39.) C:\5\Bird\WhiteNameTag__St. Awesome_.txt 40.) C:\5\Cat\GreenNameTag____iolet.txt 41.) C:\5\Bird\BlueNameTag____iolet.txt 42.) C:\5\Bird\GreenNameTag_Fido.txt 43.) C:\5\Bird\BlackNameTag__St. Awesome_.txt 44.) C:\5\Dog\GreenNameTag__St. Awesome_.txt 45.) C:\5\Cat\BlackNameTag_Fluffy.txt 46.) C:\5\Dog\BlueNameTag____iolet.txt 47.) C:\5\Bird\BlueNameTag_Fido.txt 48.) C:\5\Cat\BlueNameTag__St. Awesome_.txt 49.) C:\5\Cat\BlackNameTag____iolet.txt 50.) C:\5\Cat\BlackNameTag_Fido.txt 51.) C:\5\Dog\RedNameTag____iolet.txt 52.) C:\5\Cat\RedNameTag_Fluffy.txt 53.) C:\5\Dog\GreenNameTag_Fluffy.txt 54.) C:\5\Dog\BlueNameTag__St. Awesome_.txt 55.) C:\5\Cat\WhiteNameTag__St. Awesome_.txt 56.) C:\5\Bird\RedNameTag__St. Awesome_.txt 57.) C:\5\Dog\BlackNameTag____iolet.txt 58.) C:\5\Bird\WhiteNameTag_Fluffy.txt 59.) C:\5\Dog\WhiteNameTag____iolet.txt 60.) C:\5\Bird\WhiteNameTag_Fido.txt =end
true
2039c34610ac9379d4b2b3759b9faada730fb383
Ruby
jamiemills98/ruby-challenges
/03_largest_number.rb
UTF-8
324
3.734375
4
[]
no_license
# Your code here largest_number = [] puts "Type in any number" number_1 = gets.to_i largest_number << number_1 puts "Type in any number" number_2 = gets.to_i largest_number << number_2 puts "The largest number you entered is: " puts largest_number.max
true
d52e1db392546b87f36b481663384a6af731db5f
Ruby
stuartstein777/CodeWars
/6KYU/Grouped by commas/solution.rb
UTF-8
417
3.484375
3
[]
no_license
def solution(n) s = n.to_s len = s.length puts len if len <= 3 return n.to_s elsif len % 3 == 0 return s.chars.each_slice(3).map { |x| x.join("") }.join(",") elsif (len - 1) % 3 == 0 return s[0] + "," + s.chars[1..-1].each_slice(3).map { |x| x.join("") }.reverse.join(",") else return s[0] + s[1] + "," + s.chars[2..-1].each_slice(3).map { |x| x.join("") }.reverse.join(",") end end
true
8023ce3e56cb3af7cf5827d2945c36d848ea4bdb
Ruby
ethansagin/school-domain-online-web-ft-041519
/lib/school.rb
UTF-8
398
3.671875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class School attr_reader :name, :roster def initialize(name) @name = name @roster = {} end def add_student(stu_name, stu_grade) roster[stu_grade] ||= [] roster[stu_grade] << stu_name end def grade(num) roster[num] end def sort new_var = {} roster.each do |key, value| new_var[key] = value.sort end new_var end end
true
2468fb54e5dd4ba7fbfec93bb9701b771f9204bd
Ruby
wonda-tea-coffee/yukicoder
/51.rb
UTF-8
86
2.65625
3
[]
no_license
w = gets.chomp.to_i d = gets.chomp.to_i d.downto(2) do |i| w -= w/(i*i) end puts w
true
678c54b818a4845ee045fe468fad12260aa1fd21
Ruby
lsethi-xoriant/FandomRails4
/app/helpers/linked_call_to_action_helper.rb
UTF-8
11,484
2.609375
3
[]
no_license
module LinkedCallToActionHelper # Internal: Custom class and methods useful to represent the set of trees containing a call # to action following linking paths defined in interaction_call_to_actions table and cta answer call_to_action_id. # Based on Node class, every single tree is identified by its root Node. class CtaForest # Internal: Builds the graph of all the reachable call to actions from a given cta. # reachable_cta_id_set is the all reachable call to actions ids from starting call to action set. # # starting_cta_id - Call to action id to reach. # return_tree - Boolean value for structure to return. # # Returns the graph starting from starting_cta_id and the cycles boolean value. def self.build_linked_cta_graph(starting_cta_id) cache_key = starting_cta_id cta_ids = CtaForest.get_neighbourhood_map().keys cache_timestamp = get_cta_max_updated_at(cta_ids) seen_nodes, cycles = cache_forever(get_linked_cta_graph_cache_key(cache_key, cache_timestamp)) do reachable_cta_id_set = build_reachable_cta_set(starting_cta_id, Set.new([starting_cta_id]), []) seen_nodes = {} cycles = [] reachable_cta_id_set.each do |cta_id| if seen_nodes[cta_id].nil? and !in_cycles(cta_id, cycles) tree = Node.new(cta_id) tree, cycles = add_next_cta(seen_nodes, tree, cycles, [cta_id]) end end [seen_nodes, cycles] end [seen_nodes, cycles] end def self.build_trees(starting_cta_id) seen_nodes, cycles = build_linked_cta_graph(starting_cta_id) reachable_cta_id_set = build_reachable_cta_set(starting_cta_id, Set.new([starting_cta_id]), []) trees = [] reachable_cta_id_set.each do |cta_id| if (InteractionCallToAction.find_by_call_to_action_id(cta_id).nil? && Answer.where(:call_to_action_id => cta_id).count == 0) or (cycles.any? and cta_id == starting_cta_id) # add roots trees << seen_nodes[cta_id] end end return trees, cycles end # Internal: Builds the undirected graph of all linked call to actions # # Returns a hash of (cta_id => Set of reachable cta ids) couples def self.get_neighbourhood_map() cache_timestamp = get_cta_max_updated_at() neighbourhood_map = cache_forever(get_linked_ctas_cache_key(cache_timestamp)) do neighbourhood_map = {} InteractionCallToAction.all.each do |interaction_call_to_action| if interaction_call_to_action.interaction_id.present? cta_linking_id = Interaction.find(interaction_call_to_action.interaction_id).call_to_action_id cta_linked_id = interaction_call_to_action.call_to_action_id add_neighbour(neighbourhood_map, cta_linking_id, cta_linked_id) add_neighbour(neighbourhood_map, cta_linked_id, cta_linking_id) end end Answer.all.each do |answer| if answer.call_to_action_id cta_linking_ids = Interaction.where(:resource_type => "Quiz", :resource_id => answer.quiz_id).pluck(:call_to_action_id) cta_linked_id = answer.call_to_action_id cta_linking_ids.each do |cta_linking_id| add_neighbour(neighbourhood_map, cta_linking_id, cta_linked_id) add_neighbour(neighbourhood_map, cta_linked_id, cta_linking_id) end end end neighbourhood_map end end # Internal: Recursive method to build the tree starting from a root node (tree variable). # # seen_nodes - Support variable consisting of a hash of { value => Node } elements. It should be empty at the beginning. # tree - Variable containing the call to actions tree. It should contain the root Node at the beginning. # cycles - Array containing the cycles, if there are any. A cycle is an array of integers corresponding to the call to action ids cycle path. # path - Support variable consisting of an array containing the cta ids path followed since the beginning. It should be empty at first and filled every recursion call. # # Returns the tree builded from the Node given at the beginning and the cycles array. def self.add_next_cta(seen_nodes, tree, cycles, path) cta = CallToAction.find(tree.value) if seen_nodes[tree.value].nil? seen_nodes.merge!({ tree.value => tree }) if cta.interactions.any? cta.interactions.each do |interaction| children_cta_ids = InteractionCallToAction.where(:interaction_id => interaction.id).pluck(:call_to_action_id) + call_to_action_linked_to_answers(interaction.id) children_cta_ids.each do |children_cta_id| if path.include?(children_cta_id) # cycle cycles << path return seen_nodes[path[0]], cycles else if seen_nodes[children_cta_id].nil? path << children_cta_id cta_child_node = Node.new(children_cta_id) else cta_child_node = seen_nodes[children_cta_id] end tree.children << cta_child_node unless is_a_child(tree, children_cta_id) # to avoid double adding add_next_cta(seen_nodes, cta_child_node, cycles, path) end end end end end return tree, cycles end def self.in_cycles(cta_id, cycles) cycles.each do |cycle| return true if cycle.include?(cta_id) end false end def self.is_a_child(node, cta_id) node.children.each do |child| return true if child.value == cta_id end false end def self.add_neighbour(neighbourhood_map, cta1, cta2) if neighbourhood_map[cta1].nil? neighbourhood_map[cta1] = Set.new [cta2] else neighbourhood_map[cta1].add(cta2) end end def self.build_reachable_cta_set(cta_id, reachable_cta_id_set, visited) neighbourhood_map = get_neighbourhood_map() neighbours = neighbourhood_map[cta_id] unless neighbours.nil? reachable_cta_id_set += neighbours visited << cta_id neighbours.each do |neighbour| unless visited.include?(neighbour) reachable_cta_id_set += build_reachable_cta_set(neighbour, reachable_cta_id_set, visited) end end end reachable_cta_id_set end def self.call_to_action_linked_to_answers(interaction_id) res = [] interaction = Interaction.find(interaction_id) if interaction.resource_type == "Quiz" Answer.where(:quiz_id => interaction.resource_id).each do |answer| res << answer.call_to_action_id if answer.call_to_action_id end end res end end # Internal: Simple class to define a tree Node. A node value class can be anything. # # Examples # # n = Node.new("Banana") # # => #<LinkedCallToActionHelper::Node:0x007fd237682930 @value="Banana", @children=[]> # # n.children.push(Node.new("Apple")) # # => [#<LinkedCallToActionHelper::Node:0x007fd237637368 @value="Apple", @children=[]>] # # n.children.push(Node.new("Pear")) # # => [#<LinkedCallToActionHelper::Node:0x007fd237637368 @value="Apple", @children=[]>, # #<LinkedCallToActionHelper::Node:0x007fd237626040 @value="Pear", @children=[]>] # # n # # => #<LinkedCallToActionHelper::Node:0x007fd237669bb0 @value="Banana", # @children=[#<LinkedCallToActionHelper::Node:0x007fd237637368 @value="Apple", @children=[]>, # #<LinkedCallToActionHelper::Node:0x007fd237626040 @value="Pear", @children=[]>]> class Node attr_accessor :value, :children def initialize(value = nil) @value = value @children = [] end end def is_linking?(cta_id) CallToAction.find(cta_id).interactions.each do |interaction| return true if (InteractionCallToAction.find_by_interaction_id(interaction.id) || call_to_action_answers_linked_cta(cta_id).any?) end false end def is_linked?(cta_id) InteractionCallToAction.find_by_call_to_action_id(cta_id) || Answer.find_by_call_to_action_id(cta_id) end def call_to_action_answers_linked_cta(cta_id) res = [] Interaction.where(:resource_type => "Quiz", :call_to_action_id => cta_id).each do |interaction| Answer.where(:quiz_id => interaction.resource_id).each do |answer| res << { answer.id => answer.call_to_action_id } if answer.call_to_action_id end end res end def save_interaction_call_to_action_linking(cta) ActiveRecord::Base.transaction do cta.interactions.each do |interaction| interaction.save! InteractionCallToAction.where(:interaction_id => interaction.id).destroy_all # if called on a new cta, linked_cta is a hash containing a list of { "condition" => <condition>, "cta_id" => <next cta id> } hashes links = interaction.resource.linked_cta rescue nil unless links if params["call_to_action"]["interactions_attributes"] params["call_to_action"]["interactions_attributes"].each do |key, value| links = value["resource_attributes"]["linked_cta"] if value["id"] == interaction.id.to_s end end end if links links.each do |key, link| if CallToAction.exists?(link["cta_id"].to_i) condition = link["condition"].blank? ? nil : { link["condition"] => link["parameters"] }.to_json InteractionCallToAction.create(:interaction_id => interaction.id, :call_to_action_id => link["cta_id"], :condition => condition ) else cta.errors.add(:base, "Non esiste una call to action con id #{link["cta_id"]}") end end end end build_jstree_and_check_for_cycles(cta) if cta.errors.any? raise ActiveRecord::Rollback end end return cta.errors.empty? end def build_jstree_and_check_for_cycles(current_cta) current_cta_id = current_cta.id trees, cycles = CtaForest.build_trees(current_cta_id) data = [] trees.each do |root| data << build_node_entries(root, current_cta_id) end res = { "core" => { "data" => data } } if cycles.any? message = "Sono presenti cicli: \n" cycles.each do |cycle| cycle.each_with_index do |cta_id, i| message += (i + 1) != cycle.size ? "#{CallToAction.find(cta_id).name} --> " : "#{CallToAction.find(cta_id).name} --> #{CallToAction.find(cycle[0]).name}\n" end end current_cta.errors[:base] << message end res.to_json end def build_node_entries(node, current_cta_id) if node.value == current_cta_id icon = "fa fa-circle" else cta_tags = get_cta_tags_from_cache(CallToAction.find(node.value)) if cta_tags.include?('step') icon = "fa fa-step-forward" elsif cta_tags.include?('ending') icon = "fa fa-flag-checkered" else icon = "fa fa-long-arrow-right" end end res = { "text" => "#{CallToAction.find(node.value).name}", "icon" => icon } if node.children.any? res.merge!({ "state" => { "opened" => true }, "children" => (node.children.map do |child| build_node_entries(child, current_cta_id) end) }) end res end end
true
1e121bbf5eb3b86073ad6923ee96ac941b3d08a9
Ruby
kimono-k/ruby-training-field
/fundamentals/14hashes.rb
UTF-8
138
3.984375
4
[]
no_license
# Hashes -> Associative Array, key => value, dictionary states = { 1 => "Hyuna", 2 => "Kim" } puts states[1] # prints value inside key
true
8b2fa7b3757de9b1279dd5e63e779fbaff198478
Ruby
shazgorn/waroforbs
/app/model/town_aid.rb
UTF-8
1,330
2.609375
3
[]
no_license
require 'prime' class TownAid include Celluloid include Celluloid::Notifications include Celluloid::Internals::Logger def initialize(town) @town = town @awakenenings = 0 @town_aids = 0 @online = true subscribe('user_auth', :user_auth) subscribe('user_quit', :user_quit) end def user_auth(topic, user_id) if @town.user.id == user_id @online = true end end def user_quit(topic, user_id) if @town.user.id == user_id @online = false end end def run info "Town aid for town id=#{@town.id} started" now = Time.now.to_f sleep now.ceil - now + 0.001 every(Config[:res_spawner_tick]) do aid end end ## # Spawn loot boxes or resources for online users only # Should limit number of chests near single town def aid if Time.now - @town.created_time > 604800 # week terminate end if @online @awakenenings += 1 if Prime.prime? @awakenenings if @town_aids % 2 == 0 class_to_spawn = Resource else class_to_spawn = Chest end info 'publish spawn_random_res_near' publish 'spawn_random_res_near', @town, class_to_spawn @town_aids += 1 end if @town_aids > Config[:max_town_aid] terminate end end end end
true
d388c7d7dd3e7bf9dae91e3a53b7f952b3c14367
Ruby
jenpoole/reverse-each-word-cb-000
/reverse_each_word.rb
UTF-8
352
4
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def reverse_each_word(phrase) # phrase = phrase.split # convert string to array reversed_phrase = [] phrase.split.collect do |word| # convert string to array and iterate over each reversed_phrase << word.reverse # reverse each word in the array & add to new array end reversed_phrase.join(" ") # convert new array back to a string end
true
65a2de4092321ed576ce39f3b6d583746261c2e0
Ruby
KevinKra/Enigma
/test/encrypt_test.rb
UTF-8
575
2.828125
3
[]
no_license
require "minitest" require "minitest/autorun" require "minitest/pride" require 'mocha/minitest' require_relative "../lib/Encrypt.rb" class EncryptTest < Minitest::Test def setup @encrypt = Encrypt.new @key = "12345" @date = "121219" end def test_it_exists assert_instance_of Encrypt, @encrypt end def test_it_handles_encryption assert_equal "yvbbeqrr", @encrypt.handle_encryption("Hello Aa", @key, @date) end def test_it_handles_decryption assert_equal "hello aa", @encrypt.handle_encryption(false, "yvbbeqrr", @key, @date) end end
true
15eecdcd19e93a53d625b3aaeb331a5f5f7e396c
Ruby
Davkang/guessing-game
/guessing-game.rb
UTF-8
1,476
4.65625
5
[]
no_license
# Accept user input and save it as a variable. # Start a while loop. The while loop should run for as long as the user hasn't found the correct answer. # try again. # After the user has found the correct answer, the loop should exit and a congratulatory message should display. # require 'pry' score = 0 # Ask the user what difficulty they would like to play at - "easy" or "hard" puts "Welcome to the Guessing Game! What difficulty would you like?" puts "Type easy or hard:" # Pick a random number. If the user chose "easy", the number should be between 1 and 10. # random_number = rand() + 1 difficulty = gets.chomp # Depending on which level the user chose, say that you picked a random number between 1 and 10 or 20, and that the user now has to guess it. if difficulty == "easy" random_number = rand(10) + 1 puts "I've picked a number between 1 and 10. Now guess it!" # If the user chose "hard", the number should be between 1 and 20 elsif difficulty == "hard" random_number = rand(20) + 1 puts "I've picked a number between 1 and 20. Now guess it!" end # binding.pry # score = score + 1 score += 1 user_guess = gets.chomp # Each time the loop runs, the user should be asked to pick a number. As long as the answer isn't correct, the user should be asked to while user_guess != random_number.to_s puts "Wrong guess, try again!" score += 1 user_guess = gets.chomp end puts "You win! Nice job!" puts "Your score was: " + score.to_s
true
a58d52306c08a1ce0c6b1542f472302be0e0c433
Ruby
nick-stebbings/ruby-rb101-109
/small_problems/Easy_8/ex10.rb
UTF-8
602
4.65625
5
[]
no_license
# Write a method that takes a non-empty string argument, and returns the middle # character or characters of the argument. If the argument has an odd length, # you should return exactly one character. If the argument has an even length, # you should return exactly two characters. def center_of(str) len = str.length if len.even? then str[((len/2)-1),2] else str[len/2] end end puts center_of('I love ruby') # => 'e' puts center_of('Launch School') # => ' ' puts center_of('Launch') # => 'un' puts center_of('Launchschool') # => 'hs' puts center_of('x') # => 'x'
true
f0328c90d353df2f6aff87e6b701e69857092191
Ruby
a8t/reinfoce25aug
/reinforce.rb
UTF-8
52
2.796875
3
[]
no_license
def word_counter(string) string.split.count end
true
e26da332d7849edfc82a2c06ecde0f9da8c813d5
Ruby
air1bzz/organ_cooker
/lib/organ_cooker/windchest.rb
UTF-8
3,427
3.828125
4
[ "MIT" ]
permissive
require 'organ_cooker/shared' module OrganCooker ## # Represents a +windchest+ for a pipe organ. Not to be confused with the # keyboard. A windchest can have more music notes than a keyboard. # Ex : "Grand-Orgue", "Pedal", "Positif"... class WindChest include Shared ## # The +name+ of the windchest # @overload name # Gets the current name # @api public # @overload name=(value) # Sets the new name # @api public # @param value [String] the new name # @return [string] attr_reader :name ## # The +number of notes+ # @overload nb_notes # Gets the current number of notes # @api public # @overload nb_notes=(value) # Sets the new number of notes # @api public # @param value [Fixnum] the new number of notes # @return [Fixnum] the number of notes attr_reader :nb_notes ## # The +lowest note+ # @overload first_note # Gets the current lowest note # @api public # @overload first_note=(value) # Sets the new lowest note # @api public # @param value [OrganCooker::Note] the new lowest note # @return [OrganCooker::Note] the lowest note attr_reader :first_note ## # The +height+ of pipe's +foot+ # @overload foot_height # Gets the current foot height # @api public # @overload foot_height=(value) # Sets the new foot height # @api public # @param value [Numeric] the new foot height # @return [Numeric] the foot height attr_reader :foot_height def nb_notes=(nb_notes) raise ArgumentError, 'Number of notes must be an integer' unless nb_notes.is_a? Fixnum raise ArgumentError, 'Number of notes must be positive' if nb_notes <= 0 @nb_notes = nb_notes end def first_note=(note) raise ArgumentError, "#{note} is not a OrganCooker::Note object" unless note.is_a? Note @first_note = note end def foot_height=(height) raise ArgumentError, 'The diapason must be a number.' unless height.is_a? Numeric raise ArgumentError, 'The height must be positive' if height <= 0 @foot_height = height end ## # Initialize a +windchest+ object # @param name [String] the name of the keyboard (ex: "grand-orgue") # @param nb_notes [Fixnum] the number of notes # @param first_note [OrganCooker::Note] the lowest note # @param foot_height [Numeric] the pipe's foot height # @example # w = OrganCooker::WindChest.new("grand-orgue", 48, "C1".to_note, 220) def initialize(name, nb_notes = 61, first_note = OrganCooker::Note.new('C1'), foot_height = 200) self.name = name self.nb_notes = nb_notes self.first_note = first_note self.foot_height = foot_height end ## # Finds the +last note+ of the windchest # @api public # @return [OrganCooker::Note] the last note # @example # w.last_note #=> B4 def last_note @first_note.find_last_note(@nb_notes) end ## # Displays a +string representation+ of the object # @api public # @return [String] a string representation # @example # p.to_s #=> "WindChest: Grand-Orgue" def to_s "== Windchest: #{@name} ==\nfrom #{@first_note.to_s} to #{self.last_note.to_s} (#{@nb_notes} notes)" end end end
true
78b763f6e881c196518c03aaa44f2cef84595d05
Ruby
rmatambo8/Ruby-Small-Problems
/easy_5/time_of_day_2.rb
UTF-8
1,510
4.40625
4
[]
no_license
# Prompt: Write two methods that each take a time of day in 24 hr format # and return the number of minutes before and after # midnight respecfully. Both methods should return a value in the range # 0..1439 # code needed =begin P (understand the Problem) - I am given a time in hours and minutes - Convert them to integer values - one method should return how much time after midnight - another should return time before midnight - return range should be in the 0 to 1439 range. (Examples) after "24:00" == 0 before "24:00" == 0 after "12:34" == 754 before "12:34" == 686 rules - return should be between 0..1439 - before midnight counts from 1440 - after midnight counts from 0 -cannot use date and time methods D (Data structures): -Input:str -Processing: Arr -Output:Int Approach: - init a new arr. - init a const for the number of min's in a day - init a const for the number of hours in a day - convert the string into two integers separated by the colon - sum the numbers and subtract them from 1440 if necessary. =end def after_midnight(str) arr = str.split(':').map{|x| x.to_i} sum = (arr[0])*60 + arr[1] sum = sum % 1440 sum end def before_midnight(str) arr = str.split(':').map{|x| x.to_i} sum = 1440 - arr[0]*60 - arr[1] sum = sum % 1440 end p after_midnight('00:00') == 0 p before_midnight('00:00') == 0 p after_midnight('12:34') == 754 p before_midnight('12:34') == 686 p after_midnight('24:00') == 0 p before_midnight('24:00') == 0
true
f02e55152ae8e1f626691142dd93ab4c51f37a62
Ruby
jjhay-bot/batch8-activities
/rubyActivities/codingExercise/count_positives.rb
UTF-8
212
3.296875
3
[]
no_license
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15] newArray = [] positive = array.select {|x| x > 0 } negative = array.select {|x| x < 0 } newArray.push(positive.length, negative.sum) print newArray
true
7d40bd26c76c710392e0d574f5663b64d29a8876
Ruby
pdpino/music-app
/app/controllers/application_controller.rb
UTF-8
2,535
2.59375
3
[]
no_license
class ApplicationController < ActionController::Base protect_from_forgery with: :exception # makes methods available in the views helper_method :current_user, :is_current_user_admin?, :is_in?, :has_create_permission, :has_modify_permission? def current_user # REVIEW: this method is called a lot of times, the query is being done again and again? # ruby optimizes it? begin @current_user ||= User.find(session[:user_id]) if session[:user_id] rescue ActiveRecord::RecordNotFound # Can't find user @current_user = nil session[:user_id] = nil # necessary for closing session? # REVIEW: notify user?? end end def has_create_permission # NOTE: this method could seem like an overkill (just 'current_user' could be used), but adds semantic to the calling and may need to be more powerful in the future (e.g., checking roles) current_user || false end def has_modify_permission?(user) # NOTE: 'modify permissions' includes editing and deleting user == current_user || is_current_user_admin? end def is_current_user_admin? current_user && is_user_admin?(current_user) end def is_user_admin? user user.role == 'admin' end def require_user # TODO: show message redirect_to login_path unless current_user end def require_no_user # TODO: message redirect_to root_path if current_user end def require_admin redirect_to root_path unless is_current_user_admin? end def require_self(user) redirect_to :back unless user == current_user end def is_in? instance_array, searched_instance # Helper method: # Boolean inidicating if 'searched_instance' is in 'instance_array', searching with the id # Used in the views like: # is_in?(@song_albums, an_album), to check if is the album is one of the song instance_array && instance_array.index { |instance| instance.id == searched_instance.id } end def index # USE AS HOME if is_current_user_admin? selected_home = "admin" elsif current_user selected_home = "user" artists = current_user.favorite_artists @artists_news = artists.map do |artist| artist.news end.flatten songs = current_user.favorite_songs @songs_news = songs.map do |song| song.news end.flatten albums = current_user.favorite_albums @albums_news = albums.map do |album| album.news end.flatten else selected_home = "guest" end render :index, locals: { selected_home: selected_home } end end
true
871361e44c10cccb90a04699d2ae87d841fa90dc
Ruby
tk-com2415/kadai-ruby-oop-3
/human.rb
UTF-8
409
3.46875
3
[]
no_license
require './animal' require './thinkable' class Human < Animal include Thinkable # インスタンスが持つ変数(値) attr_accessor :name, :age, :hobby # インスタンスを初期化するための、特別なメソッド def initialize(name,age,hobby) self.name = name self.age = age self.hobby = hobby end end # tanaka = Human.new("田中",25,"電車") # tanaka.think
true
7c538038a99c860f0f11a6ba1cb2cf422ce877aa
Ruby
jbkimble/module_3_diagnostic
/app/services/nrel_fuel.rb
UTF-8
494
2.984375
3
[]
no_license
class NrelFuel attr_reader :name, :address, :fuel_type, :distance, :access_times def initialize(attributes={}) @name = attributes[:station_name] @address = attributes[:street_address] @fuel_type = attributes[:fuel_type_code] @distance = attributes[:distance] @access_times = attributes[:access_days_time] end def self.top_10_stations(zipcode) NrelFuelService.new.fuel_stations(zipcode).map do |station| NrelFuel.new(station) end end end
true
39f88316a0f275cd22542f0ddeaaea2a9d353684
Ruby
sarabrandao21/grocery-store
/lib/customer.rb
UTF-8
716
3.1875
3
[]
no_license
require 'csv' class Customer attr_reader :id attr_accessor :email, :address def initialize(id, email, address = {}) @id = id @email = email @address = address end def self.all all_customer = [] CSV.read('./data/customers.csv').each do |customer| all_customer << Customer.new(customer[0].to_i, customer[1], { :street => customer[2], :city => customer[3], :state => customer[4], :zip => customer[5] }) end return all_customer end def self.find(id_customer) id_find = all.find do |customer| id_customer == customer.id end return id_find end end
true
a3ad9dbfb4d83a354c1f541195daa0a551e07262
Ruby
NosaPrecious/oo-basics-dc-web-career-040119
/lib/shoe.rb
UTF-8
620
3.640625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Make your shoe class here! class Shoe def initialize(brand_name) @brand= brand_name end def brand @brand end def color=(color_type) @color= color_type end def color @color end def size=(size_type) @size= size_type end def size @size end def material=(material_type) @material= material_type end def material @material end def condition=(state_of_shoe) @condition= state_of_shoe end def condition @condition end def cobble puts "Your shoe is as good as new!" self.condition= "new" end end
true
caf3e4eea765549a51ffb76699aa987b95030c7c
Ruby
hanrattyjen/learn_to_program
/ch14-blocks-and-procs/better_program_logger.rb
UTF-8
525
3.203125
3
[]
no_license
$logger_depth = 0 def better_log desc, &block prefix = ' '*$logger_depth puts prefix + 'Beginning "' + desc + '"...' $logger_depth = $logger_depth + 1 result = block.call $logger_depth = $logger_depth - 1 puts prefix + '..."' + desc + '" finished, returning: ' + result.to_s end better_log 'outer block' do better_log 'some little block' do better_log 'some teeny-tiny block' do 'lOtS oF lOve'.downcase end 7 * 3 * 2 end better_log 'yet another block' do '!doof iahT ekil I'.reverse end '0' == 0 end
true
5836a6354681e363e9101d67fcbc1a231e59638b
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/rna-transcription/4665bbdbf8784c2a9b15be46245bb280.rb
UTF-8
149
2.6875
3
[]
no_license
class Complement def self.of_dna(s) return s.tr('GCTA', 'CGAU') end def self.of_rna(s) return s.tr('CGAU', 'GCTA') end end
true
657da3cfb73267766eb6b02a152305158adc16c6
Ruby
fideliom/problem
/server.rb
UTF-8
440
2.703125
3
[]
no_license
require 'socket' server = TCPServer.open(2000) loop { client = server.accept request = client.read verb, file = request.split(' ') print verb if (File.exist?(file)) if verb == 'GET' content = File.open(file).read response = "HTTP/1.0 200 OK\r\n\r\nContent-Type: text/html\r\n\r\nContent-Length: #{content.length}\r\n\r\n #{content}" client.write(response) end end }
true
89d2b8a2e3363f512244ebcf204ad02eaccd0155
Ruby
liuqiaoping7/CourseSelect
/app/models/grade.rb
UTF-8
841
2.515625
3
[ "MIT" ]
permissive
class Grade < ActiveRecord::Base belongs_to :course belongs_to :user validates :grade_h, numericality: {only_integer: true,greater_than_or_equal_to:0,less_than_or_equal_to:100, message: " 平时成绩 is not a valid grade,please input 平时成绩>=0&&<=100" } validates :grade_e, numericality: {only_integer: true,greater_than_or_equal_to:0,less_than_or_equal_to:100, message: " 考试成绩 is not a valid grade,please input 考试成绩>=0&&<=100" } validates :grade_hp, numericality: {only_integer: true,greater_than_or_equal_to:0,less_than_or_equal_to:100, message: " 所占比重is not a valid percent,please input percent>=0&&<=100" } validate :percent_equal_to_100 def percent_equal_to_100 if(grade_ep+grade_hp)!=100 errors.add(:grade_ep, "所占比重之和必须为100") end end end
true
edd105bbc232a38e892b7b3b8138476d96627290
Ruby
nikkigraybeal/rb101
/exercises/easy6/does_list_include.rb
UTF-8
499
4.09375
4
[]
no_license
# Write a method named include? that takes an Array and a search value as arguments. This method should return true if the search value is in the array, false if it is not. You may not use the Array#include? method in your solution. def include?(array, val) includes = array.select { |i| i == val } includes.size > 0 ? true : false end p include?([1,2,3,4,5], 3) == true p include?([1,2,3,4,5], 6) == false p include?([], 3) == false p include?([nil], nil) == true p include?([], nil) == false
true
67f198f5837e925a17f7ff56e30e1428d64506da
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/leap/e4b3a6c886a441a58e9e8f7d7a73b1f4.rb
UTF-8
353
3.578125
4
[]
no_license
class Year def initialize(year) @year = year end def leap? evenly_divisible_by_4? and (evenly_divisible_by_400? or not_evenly_divisible_by_100?) end def evenly_divisible_by_4? @year % 4 == 0 end def not_evenly_divisible_by_100? not @year % 100 == 0 end def evenly_divisible_by_400? @year % 400 == 0 end end
true
317a1b26c246b6354c6c047b8ed0cda8c68a7b95
Ruby
chylli/calculator-ruby
/spec/lexer_spec.rb
UTF-8
2,026
3.140625
3
[]
no_license
require 'lexer' describe Lexer do it 'should parse "" as end token' do for str in ['', ' ', ' '] do lexer = Lexer.new(str) expect(lexer.next_token.kind).to eq(Token::End) end end it 'should parse "5" as number and has end token' do for str in ['5', '5 ', ' 5 ', ' 5'] do lexer = Lexer.new(str) a = lexer.next_token expect(a.kind).to eq(Token::Num); expect(a.value).to eq(5); expect(lexer.next_token.kind).to eq(Token::End) end end it 'should parse "(" as LParen' do for str in ['(', '( ', ' ( ', ' ('] do lexer = Lexer.new(str) a = lexer.next_token expect(a.kind).to eq(Token::LParen); end end it 'should parse ")" as RParen' do for str in [')', ') ', ' ) ', ' )'] do lexer = Lexer.new(str) a = lexer.next_token expect(a.kind).to eq(Token::RParen); end end it 'should parse "+" as Plus' do lexer = Lexer.new('+') a = lexer.next_token expect(a.kind).to eq(Token::Plus); end it 'should parse "-" as Minus' do lexer = Lexer.new('-') a = lexer.next_token expect(a.kind).to eq(Token::Minus); end it 'should parse "*" as Multiply' do lexer = Lexer.new('*') a = lexer.next_token expect(a.kind).to eq(Token::Multiply); end it 'should parse "/" as Multiply' do lexer = Lexer.new('/') a = lexer.next_token expect(a.kind).to eq(Token::Divide); end it 'should get same token after revert' do lexer = Lexer.new('/') a = lexer.next_token lexer.goback b = lexer.next_token expect(a).to eq(b); end it 'should get next token for every next_token' do lexer = Lexer.new('5*3') a = lexer.next_token b = lexer.next_token expect(a.kind).to eq(Token::Num) expect(b.kind).to eq(Token::Multiply) end it 'should parse "sqrt" as a function' do lexer = Lexer.new('sqrt') a = lexer.next_token expect(a.kind).to eq(Token::Function) expect(a.value).to eq('sqrt') end end
true
298e3d09af8ac30d8173b998e6c8482043409d9e
Ruby
glukhikh/multicloud-core
/lib/multicloud/core/entities/directory.rb
UTF-8
874
2.625
3
[]
no_license
module Multicloud module Core module Entities # The cloud storage resource (base for file/dir). class Directory < Resource attr_reader :resource_list # Creates a new directory. # @param [String] name - The directory name. # @param [String] path - The directory path. # @param [Integer] created_at - The directory created_at timestamp. # @param [Integer] updated_at - The directory updated_at timestamp. # @param [ResourceList] resource_list - The resource list. def initialize(name:, path:, created_at:, updated_at:, resource_list: nil) super( name: name, path: path, type: 'dir', created_at: created_at, updated_at: updated_at ) @resource_list = resource_list end end end end end
true
df5dcc1b34b6d8f117662afbd0a3fbfe4102f2d9
Ruby
eregon/adventofcode
/2020/16a_parse.rb
UTF-8
365
2.765625
3
[]
no_license
fields, mine, others = File.read('16.txt').split("\n\n") valid = fields.lines.flat_map { |line| line[/^[\w ]+: ((\d+-\d+)( or \d+-\d+)*)$/, 1].split(' or ').map { |range| range =~ /(\d+)-(\d+)/ and ($1.to_i..$2.to_i) } } p others.lines.drop(1).flat_map { |line| line.chomp.split(',').map(&:to_i) }.select { |n| valid.none? { |range| range === n } }.sum
true
802664841d2df8b80103a637657ec895b69f0eea
Ruby
ncaq/aoj-code
/10025/main.rb
UTF-8
202
2.75
3
[]
no_license
a, b, c = gets.split(' ').map(&:to_i) rc = c * Math::PI / 180 h = b * Math::sin(rc) puts [a * h / 2, a + b + Math::sqrt((a ** 2) + (b ** 2) - 2 * a * b * Math::cos(rc)), h].map{ |f| sprintf("%.8f", f)}
true
8846a7177bbaf210fed414a2c2dbdb0dc33b1828
Ruby
levibostian/Trent
/lib/github/github.rb
UTF-8
1,560
3.015625
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'net/http' require 'json' require_relative '../log' # Functions to run on GitHub class GitHub def initialize(api_key) @api_key = api_key end # Comment on Pull Request def comment(message) # https://docs.travis-ci.com/user/environment-variables/#convenience-variables # Must check if 'false' because `TRAVIS_PULL_REQUEST` always has a value. if ENV['TRAVIS_PULL_REQUEST'].to_s == 'false' Log.warning("Not in pull request, skipping GitHub comment. Message: #{message}") return end result = comment_on_pull_request(message) if !result[:successful] puts "Status code: #{result[:status_code]}" puts "Body: #{result[:body]}" Log.fatal('Commenting on GitHub pull request failed.') else Log.success('Successfully commented on GitHub pull request.') end end private def comment_on_pull_request(message) puts "Commenting on GitHub pull request: #{ENV['TRAVIS_REPO_SLUG']}/#{ENV['TRAVIS_PULL_REQUEST']}" uri = URI("https://api.github.com/repos/#{ENV['TRAVIS_REPO_SLUG']}/issues/#{ENV['TRAVIS_PULL_REQUEST']}/comments") req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json') req['Authorization'] = "token #{@api_key}" req.body = { body: message }.to_json http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true res = http.request(req) status_code = res.code.to_i { status_code: status_code, body: res.body, successful: res.is_a?(Net::HTTPSuccess) && status_code < 400 } end end
true
74047fd41020397b1c76be5269f11cc77e66b3dc
Ruby
jeremiahlukus/exploringTests
/test/models/article_test.rb
UTF-8
917
2.5625
3
[]
no_license
require 'test_helper' class ArticleTest < ActiveSupport::TestCase def setup @article = Article.create(title: "Article1", description: "This is an article",) end test 'article should be valid' do assert @article.valid? end test 'title should be present' do @article.title = " " assert_not @article.valid? end test 'title should not be to short' do @article.title = 'aaaa' assert_not @article.valid? end test 'title should not be to long' do @article.title = "a" * 51 assert_not @article.valid? end test 'description should be present' do @article.description = " " assert_not @article.valid? end test 'desciption should not be to short' do @article.description = 'aaaa' assert_not @article.valid? end test 'description should not be to long' do @article.description = "a" * 151 assert_not @article.valid? end end
true
e756522783b9380135d59a5767083ed768a80d1e
Ruby
beaucouplus/inch_test
/spec/import/csv_spec.rb
UTF-8
5,899
2.515625
3
[]
no_license
require 'rails_helper' describe Import::Csv, type: :csv do subject { Import::Csv.new(file_path: generated_csv.path) } after(:each) { File.delete(path) if File.exist?(path) } describe 'for buildings' do let(:path) { 'spec/import/buildings.csv' } let(:generated_csv) do CSV.open(path, 'wb') do |csv| csv << %w[reference address zip_code city country manager_name] csv << ['1', '10 Rue La bruyère', '75009', 'Paris', 'France', 'Martin Faure'] csv << ['2', '40 Rue René Clair', '75018', 'Paris', 'France', 'Martin Faure'] end end describe '#import' do it 'imports csv data as an array of hashes' do rows = subject.import.rows expect(rows).to be_kind_of(Array) expect(rows.first).to be_kind_of(Hash) expect(rows.first['zip_code']).to eq('75009') end end describe 'filename' do before { subject.import } it 'returns filename' do expect(subject.filename).to eq 'buildings' end end describe '#target_model' do before { subject.import } it 'imports csv data as an array of hashes' do expect(subject.target_model).to eq(Building) end end describe '#save' do context 'when there is no previous record' do before { subject.import } it 'populates table with imported records' do subject.save expect(Building.count).to eq(2) expect(Building.first.zip_code).to eq('75009') end end context 'when building already has a profile and we ask to update authorized fields' do before { subject.import } before do create_building_profile(reference: '1', manager_name: 'Martin Faure', zip_code: '75020') end it 'updates record with new data' do expect(Building.find_by(reference: '1').zip_code).to eq('75020') subject.save expect(Building.find_by(reference: '1').reload.zip_code).to eq('75009') end end context 'when building already has a profile and we ask to update a protected field' do before { subject.import } before do create_building_profile(reference: '1', manager_name: 'Martin Faure', zip_code: '75020') create_building_profile(reference: '1', manager_name: 'Pepito Rodriguez', zip_code: '75011') end let(:building_one) { Building.find_by(reference: '1') } it 'does not update protected field but updates other fields' do expect(building_one.manager_name).to eq('Pepito Rodriguez') expect(building_one.zip_code).to eq('75011') subject.save expect(building_one.reload.manager_name).to eq('Pepito Rodriguez') expect(building_one.reload.zip_code).to eq('75009') end end end end describe 'for people' do let(:path) { 'spec/import/people.csv' } let(:generated_csv) do CSV.open(path, 'wb') do |csv| csv << %w[reference firstname lastname home_phone_number mobile_phone_number email address] csv << ['1', 'Henri', 'Dupont', '0123456789', '0623456789', '[email protected]', '10 Rue La bruyère'] csv << ['2', 'Jean', 'Durand', '0123336789', '0663456789', '[email protected]', '40 Rue René Clair'] end end describe '#save' do let(:person_one) { Person.find_by(reference: '1') } context 'when there is no previous record' do before { subject.import } it 'populates table with imported records' do subject.save expect(Person.count).to eq(2) expect(Person.first.email).to eq('[email protected]') end end context 'when person already has a profile and the csv contains new data' do before { subject.import } before do create_person_profile(reference: '1', email: '[email protected]', lastname: 'Snow', home_phone_number: nil) end it 'updates record with new data' do expect(person_one.lastname).to eq('Snow') subject.save expect(person_one.reload.lastname).to eq('Dupont') end end context 'when person already has a profile and we ask to update a protected field' do before { subject.import } before do create_person_profile(reference: '1', email: '[email protected]', lastname: 'Snow', home_phone_number: nil) create_person_profile(reference: '1', email: '[email protected]', lastname: 'Gigantic', home_phone_number: '0123456789') create_person_profile(reference: '1', email: '[email protected]', lastname: 'Mice', home_phone_number: '0875446799') end it 'updates record with new data' do expect(person_one.lastname).to eq('Mice') expect(person_one.email).to eq('[email protected]') expect(person_one.home_phone_number).to eq('0875446799') subject.save expect(person_one.reload.lastname).to eq('Dupont') expect(person_one.reload.email).not_to eq('[email protected]') expect(person_one.reload.home_phone_number).not_to eq('0123456789') end end end end def create_building_profile(reference:, manager_name:, zip_code:) with_building = Building.last ? :with_existing_building : nil building_profile = create(:building_profile, with_building, manager_name: manager_name, zip_code: zip_code) building = building_profile.building building.update(reference: reference, current_profile_id: building_profile.id) end def create_person_profile(reference:, email:, lastname:, home_phone_number:) with_person = Person.last ? :with_existing_person : nil with_phone_number = home_phone_number ? { home_phone_number: home_phone_number } : {} person_profile = create(:person_profile, with_person, { email: email, lastname: lastname }.merge(with_phone_number)) person = person_profile.person person.update(reference: reference, current_profile_id: person_profile.id) end end
true
e7bc3f8ffb1cf41762db4ab00b6cb40c42e887d8
Ruby
johndewolf/piglatin_with_tdd
/app.rb
UTF-8
251
2.96875
3
[]
no_license
require './PigLatinTranslation' require './Word' require "pry" puts 'Please enter a phrase to be translated' phrase = gets.chomp phrase = PigLatinTranslation.new(phrase) phrase.split_array phrase.create_word_objects puts phrase.translated_words
true
ecf4273e6bce700f7fac5672380edec332df9874
Ruby
JordanStafford/Ruby
/PDP/Arrays /EX12.RB
UTF-8
270
3.796875
4
[]
no_license
#Write a Ruby program to create a new array with the elements in reverse order from a given an array of integers length def array_checking_function(numbers) reversed = numbers[2], numbers[1], numbers[0] return reversed end print array_checking_function([1, 5, 98])
true
1c5c6a04b76f796cb538053f04fbe381e4706c29
Ruby
fearoffish/rehabilitate
/lib/rehabilitate/plugins/scp.rb
UTF-8
1,151
2.703125
3
[]
no_license
require 'rehabilitate/plugin' require 'uri' require 'net/ssh' require 'net/scp' class Scp < Rehabilitate::Plugin def upload(options) location = parse_upload_string(options.location) remote_dir = "#{location[:dir]}/#{options._base_backup_name}" log "Connecting to #{location[:host]} with user: #{location[:user]}:#{location[:pass]}" options._backup_files.collect! do |local_file| remote_file = "#{remote_dir}/#{File.basename(local_file)}" log "Uploading '#{local_file}' to '#{remote_file}'" Net::SCP.upload!( location[:host], location[:user], local_file, remote_file, :password => location[:pass], :recursive => true ) end end private # e.g. user:[email protected]/backup-dir def parse_upload_string(upload_string) location = {} location[:user], remaining = upload_string.split(":") location[:pass], remaining = remaining.split("@") location[:host] = remaining.split("/").first location[:dir] = remaining.split("/")[1..-1].join("/") location end end
true
992d8142e389d0982dd0d1add606f7c4bb5424ff
Ruby
BrentPalmer/Intro-to-Programming-Exercises
/loopsanditerators_exercises/exercise_4.rb
UTF-8
108
3.453125
3
[]
no_license
def countdown(num) if num <= 0 puts "Done!" else puts num countdown(num - 1) end end countdown(10)
true
aa38a6c3fbbf772f7b4e0e8f218cb7d5a24a6b73
Ruby
cheezenaan/procon
/atcoder/agc024/a.rb
UTF-8
126
3.0625
3
[]
no_license
a, b, c, k = gets.split.map(&:to_i) MAX = 10 ** 18 if (a - b).abs > MAX puts "Unfair" else puts (a - b) * (-1) ** k end
true
32e65fbf72aa865b29be2634fcbb1449a7b13740
Ruby
dnswann/ruby-challenges
/ruby_challenges/always_three3.rb
UTF-8
138
3.71875
4
[]
no_license
# use 3 lines and single variable puts "Give me a number" number_one = gets.to_i print (number_one + 5) * (2 - 4) / (2 - number_one) + 1
true
057b9c90b4fc36bb5af579fdfc396b4ac75df53c
Ruby
yous/acmicpc-net
/problem/1008/ruby-1.8.short.rb
UTF-8
90
2.71875
3
[]
no_license
# encoding: utf-8 a,b=gets.split;p a.to_f/b.to_f # a, b = gets.split # p a.to_f / b.to_f
true
3edd54f500d20f50f5ee51675764dee432aa1922
Ruby
heroku/legacy-cli
/lib/heroku/command/labs.rb
UTF-8
4,039
2.546875
3
[ "MIT" ]
permissive
require "heroku/command/base" # manage optional features # class Heroku::Command::Labs < Heroku::Command::Base # labs # # list experimental features # #Example: # # === User Features ([email protected]) # [+] dashboard Use Heroku Dashboard by default # # === App Features (glacial-retreat-5913) # [ ] preboot Provide seamless web dyno deploys # [ ] user-env-compile Add user config vars to the environment during slug compilation # $ heroku labs -a example # def index validate_arguments! user_features, app_features = api.get_features(app).body.sort_by do |feature| feature["name"] end.partition do |feature| feature["kind"] == "user" end # general availability features are managed via `settings`, not `labs` app_features.reject! { |f| f["state"] == "general" } display_app = app || "no app specified" styled_header "User Features (#{Heroku::Auth.user})" display_features user_features display styled_header "App Features (#{display_app})" display_features app_features end alias_command "labs:list", "labs" # labs:info FEATURE # # displays additional information about FEATURE # #Example: # # $ heroku labs:info user_env_compile # === user_env_compile # Docs: http://devcenter.heroku.com/articles/labs-user-env-compile # Summary: Add user config vars to the environment during slug compilation # def info unless feature_name = shift_argument error("Usage: heroku labs:info FEATURE\nMust specify FEATURE for info.") end validate_arguments! feature_data = api.get_feature(feature_name, app).body styled_header(feature_data['name']) styled_hash({ 'Summary' => feature_data['summary'], 'Docs' => feature_data['docs'] }) end # labs:disable FEATURE # # disables an experimental feature # #Example: # # $ heroku labs:disable ninja-power # Disabling ninja-power feature for [email protected]... done # def disable feature_name = shift_argument error "Usage: heroku labs:disable FEATURE\nMust specify FEATURE to disable." unless feature_name validate_arguments! feature = api.get_features(app).body.detect { |f| f["name"] == feature_name } message = "Disabling #{feature_name} " error "No such feature: #{feature_name}" unless feature if feature["kind"] == "user" message += "for #{Heroku::Auth.user}" else error "Must specify an app" unless app message += "for #{app}" end action message do api.delete_feature feature_name, app end end # labs:enable FEATURE # # enables an experimental feature # #Example: # # $ heroku labs:enable ninja-power # Enabling ninja-power feature for [email protected]... done # def enable feature_name = shift_argument error "Usage: heroku labs:enable FEATURE\nMust specify FEATURE to enable." unless feature_name validate_arguments! feature = api.get_features.body.detect { |f| f["name"] == feature_name } message = "Enabling #{feature_name} " error "No such feature: #{feature_name}" unless feature if feature["kind"] == "user" message += "for #{Heroku::Auth.user}" else error "Must specify an app" unless app message += "for #{app}" end feature_data = action(message) do api.post_feature(feature_name, app).body end display "WARNING: This feature is experimental and may change or be removed without notice." display "For more information see: #{feature_data["docs"]}" if feature_data["docs"] end private # app is not required for these commands, so rescue if there is none def app super rescue Heroku::Command::CommandFailed nil end def display_features(features) longest_name = features.map { |f| f["name"].to_s.length }.sort.last features.each do |feature| toggle = feature["enabled"] ? "[+]" : "[ ]" display "%s %-#{longest_name}s %s" % [ toggle, feature["name"], feature["summary"] ] end end end
true
7cffb1639db535ce271477b74d580b03cf540d4c
Ruby
lfriedrichs/ruby-oo-object-relationships-kickstarter-lab-seattle-web-012720
/lib/backer.rb
UTF-8
370
2.875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Backer attr_accessor :name def initialize(name) @name = name end def back_project(project) ProjectBacker.new(project, self) end def backed_projects ProjectBacker.all.collect { |project_backer| project_backer.project if project_backer.backer == self }.select {|value| value != nil } end end
true
022d1227a4e6d71e238107a2473261cdf3d24984
Ruby
gonzalo-m/maze-solver
/maze.rb
UTF-8
13,824
3.484375
3
[]
no_license
#!/usr/local/bin/ruby #------------------------------------------------------------------------------ # Maze Solver #------------------------------------------------------------------------------ HEADER = 1 CELL = 2 PATH = 3 $simple_maze_format = "" $invalid_output = "" $invalid_maze = false def parse(file) # header line = file.gets while line =~ /^[\s]*$\n/ # skip empty lines line = file.gets end if line_valid?(line, HEADER) # parse it valid_header = line.split(/[^0-9]/) valid_header.delete("") size, x_start, y_start, x_end, y_end = valid_header # valid header $simple_maze_format << size + " " + x_start + " " $simple_maze_format << y_start + " " + x_end + " " + y_end + "\n" else # invalid header $invalid_maze = true $invalid_output << line end # cells and paths while line = file.gets if line =~ /^[\s]*$\n/ next end if line =~ /^"/ #/path/i if valid_multiple_paths?(line) parse_multiple_paths(line) elsif line_valid?(line, PATH) parse_single_path(line) else # invalid path (single) $invalid_maze = true $invalid_output << line end else # process cell if line_valid?(line, CELL) # parse it parse_cell(line) else # invalid cell $invalid_maze = true $invalid_output << line end end end $invalid_output.insert(0, "invalid maze\n") if $invalid_maze puts $invalid_output else puts $simple_maze_format end end def line_valid?(line, type) case type when HEADER header_regex = /maze:\s\d+\s\d+:\d+\s->\s\d+:\d+/ return header_regex =~ line ? true : false # validate header when CELL cell_regex = /\d+,\d+:\s([udlr]{0,4})\s(-?\d*.\d+){0,1}(,-?\d*.\d+){0,4}\s*$/ return cell_regex =~ line ? true : false when PATH sing_path_regex = /"[^: ]+:\(\d+,\d+\)(,[udlr])*"/ return sing_path_regex =~ line ? true : false end end def more_than_one_direction?(dirs) return dirs.count('u') > 1 || dirs.count('d') > 1 || dirs.count('l') > 1 || dirs.count('r') > 1 end def valid_multiple_paths?(line) mult_paths_regexp = /^"[^: ]+:\(\d+,\d+\)(,[udlr])*"(,"[^: ]+:\(\d+,\d+\)(,[udlr])*")+\s*$/ return mult_paths_regexp =~ line end def parse_cell(line) valid_cell = line.chomp coors, values = valid_cell.split(/:/) x_coor, y_coor = coors.split(/,/) values = values.lstrip values = values.rstrip if values != nil dirs, weights_values = values.split(/\s/) if dirs != nil if dirs.length > 4 || more_than_one_direction?(dirs) #invalid line $invalid_maze = true $invalid_output << line else # valid dirs and weight weights_array = weights_values.split(/,/) weights = "" weights_array.each { |w| weights << " " + w } $simple_maze_format << x_coor + " " + y_coor + " " + dirs + weights + "\n" end else # coordinates only $simple_maze_format << x_coor + " " + y_coor + "\n" end end end def parse_multiple_paths(line) mult_paths = line.chomp.strip # break it into chunks sing_paths = mult_paths.split(/","/) sing_paths.each { |p| if p[0] != "\"" p.insert(0, "\"") end if p[-1] != "\"" p.insert(-1, "\"") end if line_valid?(p, PATH) parse_single_path(p) else # invalid path (multipe) $invalid_maze = true $invalid_output << line break end } end def parse_single_path(single_path) name, values = single_path.split(/:/) # name # replace scaped for normal quotes name.gsub!("\\\"","\"") name.sub!("\"", "") coords, dirs = values.split(/\),/) # coordinates coords.sub!("(", "") x_coor, y_coor = coords.split(/,/) # directions dirs.sub!("\"", "") dirs.chomp! dirs.gsub!(",", "") $simple_maze_format << "path " + name + " " + x_coor + " " + y_coor + " " + dirs + "\n" end class Maze def initialize(file) line = file.gets if line == nil return end # header @size = line.split(/\s/)[0].to_i @x_start = line.split(/\s/)[1].to_i @y_start = line.split(/\s/)[2].to_i @x_end = line.split(/\s/)[3].to_i @y_end = line.split(/\s/)[4].to_i # cells and paths @cells = Array.new(@size){Array.new(@size)} @paths = Array.new i = p = 0 while line = file.gets if line =~ /path/i # create path name, x, y, dirs = Path.parse(line) @paths[p] = Path.new(name, x, y, dirs) p += 1 else # create cell x, y, dw_hash = Cell.parse(line) @cells[x][y] = Cell.new(dw_hash) i += 1 end end end attr_accessor "size", "x_start", "y_start", "x_end", "y_end", "cells", "paths" def to_s s = "#{size} #{x_start} #{y_start} #{x_end} #{y_end}\n" for y in (0...@size) for x in (0...@size) if @cells[x][y] != nil s += x.to_s + " " + y.to_s + " " + @cells[x][y].to_s + "\n" end end end @paths.each { |p| s += p.to_s} return s end # returns the number of closed cells or a formatted string # indicating the number of open walls in each cell, depending # on the parameter ("closed" or "open") def properties(which) case which when "closed" count = 0 for y in 0...@size for x in 0...@size if @cells[x][y] == nil #closed count += 1 elsif @cells[x][y].dw_hash.empty? count += 1 end end end puts count when "open" u = d = l = r = 0 for y in 0...@size for x in 0...@size if @cells[x][y] != nil && !@cells[x][y].dw_hash.empty? @cells[x][y].dw_hash.keys.each { |k| case k when "u" u += 1 when "d" d += 1 when "l" l += 1 when "r" r += 1 end } end end end wall_counts = "u: #{u}, d: #{d}, l: #{l}, r: #{r}" puts wall_counts end end def rank_paths_by_cost @paths.each { |p| x_coor = p.x_start y_coor = p.y_start path_dirs = p.dirs w_sum = 0 path_dirs.each_char { |d| if cells[x_coor][y_coor] != nil w_sum += cells[x_coor][y_coor].dw_hash[d] == nil ? 0 : cells[x_coor][y_coor].dw_hash[d] case d when "u" y_coor -= 1 when "d" y_coor += 1 when "l" x_coor -= 1 when "r" x_coor += 1 else puts "Error: unknown direction" end else # puts "Error: closed cell" end } p.cost = w_sum } result = @paths.sort { |x, y| x.cost <=> y.cost } result.each_with_index { |x, i| if i != 0 then print ", " end print x.name } print "\n" end def pretty_print for y in 0...@size print "+" # plus signs (vertcal dirs) for x in 0...@size if @cells[x][y] == nil # closed cell print "-" else direcs = @cells[x][y].dw_hash.keys if direcs.include? "u" print " " else print "-" end end print "+" end print "\n" # pipes (horizontal dirs) print "|" for x in 0...@size if x == x_start && y == y_start print "s" elsif x == x_end && y == y_end print "e" else print " " end if @cells[x][y] == nil # closed cell print "|" else direcs = @cells[x][y].dw_hash.keys if direcs.include? "r" print " " else print "|" end end end print "\n" end # outer bottom wall print "+" for i in 0...@size print "-+" end print "\n" end def solvable? m_graph = Graph.new(self) m_graph.doDFS([x_start, y_start], [x_end, y_end]) end class Cell def initialize(dw_hash) @dw_hash = dw_hash end attr_accessor "dw_hash" def to_s s = "" @dw_hash.keys.each { |k| s += k} @dw_hash.keys.each { |k| s += " " + dw_hash[k].to_s} return s end def self.parse(line) x_pos, y_pos, dirs, weights = line.split(/\s/, 4) # convert coordinates to int x_pos = x_pos.to_i y_pos = y_pos.to_i weights = weights.split(/\s/) # convert strings to floats weights.collect! {|f| f.to_f} # check that dir and weight's can be evenly mapped dirs_len = dirs.length weights_len = weights.length if dirs_len != weights_len puts "Error: Invalid Cell" exit end dw_hash = Hash.new dirs.split("").each_with_index { |x, i| dw_hash[x] = weights[i]} return [x_pos, y_pos, dw_hash] end end class Path def initialize(name, x, y, dirs) @name = name @x_start = x @y_start = y @dirs = dirs @cost = 0 end attr_accessor "name", "x_start", "y_start", "dirs", "cost" def to_s return "#{@name} #{@x_start} #{@y_start} #{@dirs}" end def self.parse(line) line.chomp! elements = line.split(/[^0-9a-zA-Z]/, 5) if elements[0].casecmp("path") == 0 elements.shift end name = elements[0] x_start = elements[1].to_i y_start = elements[2].to_i dirs = elements[3] return [name, x_start, y_start, dirs] end end end class Graph def initialize(maze) @adj_map = Hash.new{|hash, key| hash[key] = Array.new} @data_map = Hash.new start_pos = [maze.x_start, maze.y_start] end_pos = [maze.x_end, maze.y_end] add_vertex(start_pos, "s") add_vertex(end_pos, "e") for y in 0...maze.size for x in 0...maze.size from_vertex = [x, y] if maze.cells[x][y] == nil then next end # closed cell maze.cells[x][y].dw_hash.keys.each { |d| case d when 'u' y_coor = y - 1 to_vertex = [x, y_coor] when 'd' y_coor = y + 1 to_vertex = [x, y_coor] when 'l' x_coor = x - 1 to_vertex = [x_coor, y] when 'r' x_coor = x + 1 to_vertex = [x_coor, y] else # puts "Error: unknown direction" end add_directed_edge(from_vertex, to_vertex) } end end end def add_directed_edge(from_vertex, to_vertex) @adj_map[from_vertex].push(to_vertex) end def add_vertex(vertex_pos, data) @data_map[vertex_pos] = data end attr_accessor "adj_map", "data_map" def to_s return "#{adj_map} #{data_map}" end def doDFS(start_vertex, end_vertex) visited_vertices = Hash.new stack = Array.new stack.push(start_vertex) while !stack.empty? curr_vertex = stack.pop if visited_vertices[curr_vertex] == nil # not visited # mark as visited visited_vertices[curr_vertex] = "v" if curr_vertex == end_vertex return true end end while (edge = @adj_map[curr_vertex].pop) != nil stack.push(edge) end end return false end # DFS Algorithm # 1 let S be a stack # 3 S.push(v) # 4 while S is not empty # 5 v ← S.pop() # 6 if v is not labeled as discovered: # 7 label v as discovered # 8 for all edges from v to w in G.adjacentEdges(v) do # 9 S.push(w) end #----------------------------------------------------------- # the following is a parser that reads in a simpler version # of the maze files. Use it to get started writing the rest # of the assignment. You can feel free to move or modify # this function however you like in working on your assignment. def read_and_print_simple_file(file) line = file.gets if line == nil then return end # read 1st line, must be maze header sz, sx, sy, ex, ey = line.split(/\s/) puts "header spec: size=#{sz}, start=(#{sx},#{sy}), end=(#{ex},#{ey})" # read additional lines while line = file.gets do # begins with "path", must be path specification if line[0...4] == "path" p, name, x, y, ds = line.split(/\s/) puts "path spec: #{name} starts at (#{x},#{y}) with dirs #{ds}" # otherwise must be cell specification (since maze spec must be valid) else x, y, ds, w = line.split(/\s/,4) puts "cell spec: coordinates (#{x},#{y}) with dirs #{ds}" ws = w.split(/\s/) ws.each {|w| puts " weight #{w}"} end end end #------------------------------------------------------------------------------ # EXECUTABLE CODE #------------------------------------------------------------------------------ #---------------------------------- # check # of command line arguments if ARGV.length < 2 fail "usage: maze.rb <command> <filename>" end command = ARGV[0] file = ARGV[1] maze_file = open(file) #---------------------------------- # perform command case command when "parse" parse(maze_file) when "print" maze = Maze.new(maze_file) maze.pretty_print when "solve" maze = Maze.new(maze_file) puts maze.solvable? when "closed" maze = Maze.new(maze_file) maze.properties("closed") when "open" maze = Maze.new(maze_file) maze.properties("open") when "paths" maze = Maze.new(maze_file) if maze.paths.empty? puts "None" else maze.rank_paths_by_cost end else fail "Invalid command" end
true
f6ccd5e0f580e710888cfe58982a1532ef971c1d
Ruby
jsonreeder/aa-homeworks
/W1D5/stack.rb
UTF-8
449
3.296875
3
[]
no_license
class Stack def initialize @contents = [] end def add(el) @contents << el end def remove @contents.pop end def show p @contents end end def stack_tests puts "Initialize stack" stack = Stack.new puts "\nAdd 4 to stack" stack.add(4) stack.show puts "\nAdd q to stack" stack.add('q') stack.show puts "\nRemove q from stack" stack.remove stack.show end stack_tests if __FILE__ == $PROGRAM_NAME
true
0a5e052c689486af75da68814896f10bf155d7bb
Ruby
SCCP2016/ruby_mid_answer
/8/8_2.rb
UTF-8
1,533
4.09375
4
[]
no_license
# 手続き型の解答。理解しにくい male = STDIN.gets.split female = STDIN.gets.split # あふれた分の人は結婚できないので、苗字を書き換える人を少ない方に合わせる n = (male.size > female.size) ? female.size : male.size # 文字がキャピタルかどうかを真偽値で返す関数 def is_upper?(ch) ('a'.ord <= ch.ord && ch.ord <= 'z'.ord) ? false : true end # 入力文字列を苗名に分割する関数 def split_name(name) # 名前の部分にあたる配列 ret = [] # 入力文字列を一文字ずつに分割した配列のコピー o_name = name.chars while true do a = o_name.pop if a != nil then # 文字列の尻から取り出した文字が大文字ならループを脱出する if is_upper?(a) then ret.push(a) break end end ret.push(a) # 上記の処理で、「retにはo_nameの末尾から最初に衝突する大文字までの文字列が逆順に格納されている」という状況ができる end # o_nameには苗字のみが残されており、retには名前が逆順に格納されているので配列として返却 return [o_name.join, ret.reverse.join] end for i in 0..n-1 do puts split_name(male[i])[0] + split_name(female[i])[1] end # RubyTaro # lname: RubyTar # fname: o # lname: RubyTa # fname: or # lname: RubyT # fname: ora # lname: Ruby # fname: oraT # LstName: Ruby # FstName: Taro
true
abf1ddb2cb9c332308274fe93db711e7d469580a
Ruby
qaisjp/adventofcode
/2021/day09/main.rb
UTF-8
3,771
3.296875
3
[]
no_license
# frozen_string_literal: true # typed: true # AoC class AoC def initialize(data) @grid = data.map {_1.chars.map(&:to_i)} @row_size = @grid.first.size end def adjacents(y, x, coords: false, &blk) _coords = [ [y-1, x], [y+1, x], [y, x-1], [y, x+1], ] results = [] _coords.each do |coord| y, x = coord next if y < 0 || y >= @grid.size next if x < 0 || x >= @row_size if coords val = [y, x] else val = @grid[y][x] end if blk conditional = blk.call(y, x, @grid[y][x]) if conditional results << val end else results << val end end results end def adjacents_lower(y, x) this = @grid[y][x] adjacents(y, x, coords: true) { _3 < this } end def is_lowest(y, x) num = @grid[y][x] # check if this num is >= any any adjacent values adjacents(y, x) { num >= _3 }.empty? end def one total = 0 @grid.each_with_index do |row, y| row.each_with_index do |num, x| if is_lowest(y, x) # puts "#{y}, #{x} is lowest" total += num + 1 end end end total end def new_basin_matrix @grid.map {_1.map {0}} end def two matrix = new_basin_matrix # for each location... @grid.each_with_index do |row, y| row.each_with_index do |num, x| # 9 is a wall, don't mark this point next if num == 9 matrix[y][x] = 1 end end # puts "#{matrix.map(&:join).join("\n")}" # puts island_sizes = [] # for each location @grid.each_with_index do |row, y| row.each_with_index do |num, x| # nothing to infect if this isn't a basin next if matrix[y][x] == 0 # so this is a random spot in a basin. size = 1 matrix[y][x] = 0 # puts "On #{y}, #{x}" # puts "#{matrix.map(&:join).join("\n")}" # puts # start infecting/exploring the basin adjacents_to_explore = [] currently_exploring = adjacents(y, x, coords: true) { |y, x, num| matrix[y][x] == 1 } # puts "Starts exploring #{currently_exploring}" while !currently_exploring.empty? new_adjacents = [] currently_exploring.each do |y, x| next if matrix[y][x] == 0 # this might have been visited already in an earlier iteration matrix[y][x] = 0 size += 1 this_adjacents = adjacents(y, x, coords: true) { |y, x, num| matrix[y][x] == 1 } new_adjacents += this_adjacents # puts "On #{y},#{x}, this #{this_adjacents}" end currently_exploring = new_adjacents end # puts "Size of island at #{y},#{x} is #{size}" island_sizes << size end end island_sizes.sort.reverse[0..2].inject(:*) end end $examples = [ 15, 1134, ] def test(part) runner = AoC.new File.read("example.txt").split("\n") one = runner.one this = $examples.first if one != this puts "Example part 1 was #{one}, expected #{this}" else puts "Example part 1 passes (#{one})" passed = true end if passed puts "\n\n--- Example part 2" two = runner.two this = $examples[1] if two != this puts "\n\nExample part 2 was #{two}, expected #{this}" else puts "\n\nExample part 2 passes (#{this})" end end end def main n = ARGV.shift if ARGV.empty? runner = AoC.new File.read("input.txt").split("\n") else runner = AoC.new ARGF.readlines.to_a end test(n) puts "\n\n--- Part #{n} solution" if n == '1' puts "Result: #{runner.one}" elsif n == '2' puts "Result: #{runner.two}" end end main
true
3d11acff1960c84430099340e3351156989fcdd3
Ruby
pokrpokr/little_demo
/main.rb
UTF-8
2,297
2.71875
3
[]
no_license
require File.expand_path('../read_data', __FILE__) require File.expand_path('../query_data', __FILE__) require File.expand_path('../oa_get_binding', __FILE__) class Main def initialize(type) # type: [:FY, :JP, :JD, :DX] case type when :FY file_path = Config::FY_PATH new_file_path = Config::FY_NEW_PATH api_name = 'fydd' when :JP file_path = Config::JP_PATH new_file_path = Config::JP_NEW_PATH api_name = 'jpdd' when :JD file_path = Config::JD_PATH new_file_path = Config::JD_NEW_PATH api_name = 'jddd' when :DX file_path = Config::DX_PATH new_file_path = Config::DX_NEW_PATH api_name = 'dxfwdd' end @new_file_path = new_file_path @read_data = ReadData.new(file_path) @api_name = api_name api_url = Config::FORMAL_API_URL userName = Config::FORMAL_USERNAME password = Config::FORMAL_PASSWORD oa_get_binding = OaGetBinding.new(api_url, userName, password) @result = oa_get_binding.request @query = QueryData.new(api_url) end def run if @result[:result] binding = @result[:binding] else puts '登录失败' and return end result = @read_data.read_data puts '@@@' * 50 puts result[:mat].length result[:mat].each do |data| n = 0 new_name = shuffle_generate(data.name) while result[:names].include?(new_name) n += 1 puts '***' * 50 puts "#{data.id}-#{n}" new_name = shuffle_generate(new_name) end result[:names] << new_name data.name = new_name result[:aft] << data end puts '###' * 50 puts result[:aft].length CSV.open(@new_file_path, 'wb', encoding: 'gb18030') do |csv| if result[:aft].count == 0 csv << ['无订单数据'] else csv << %w(id[记录ID] name[订单编号] success[是否成功]) result[:aft].each do |record| sql = "update #{@api_name} set name='#{record.name}' where id='#{record.id}'" query_result = @query.query_data(@api_name, binding, sql) csv << [record.id, record.name, query_result[:result]] end end end end private def shuffle_generate(num) sub_s = num.match(/\A\S{2,4}(-)\d{8}/)[0] suc_n = num.sub(sub_s, '') shuffle_s = '' suc_n.length.times do shuffle_s += ('0'..'9').to_a.shuffle[0] end generate_num = sub_s + shuffle_s generate_num end end
true
653a93df5443404822ee83891aa2298e02f6ca36
Ruby
kevinfalank-devbootcamp/rspec_bank_drill
/account_spec.rb
UTF-8
2,773
3.0625
3
[]
no_license
require "rspec" require_relative "account" describe Account do let(:account) { Account.new("0123456789") } let(:invalid_account) { Account.new("0123456789", "BADINPUT") } describe "#initialize" do context "with valid input" do it "creates a new Account with the account number" do account.should be_an_instance_of(account.class) end end context "with invalid input" do it "raises an argument error when given an invalid account number" do expect{ Account.new("ABC") }.to raise_error(InvalidAccountNumberError) end end end describe "#transactions" do context "with valid input" do it "requires a numeric or an unnamed starting_balance argument" do expect(account.transactions).to eq([0]) end end context "with invalid input" do it "requires a numeric starting_balance argument" do expect { invalid_account }.to raise_error(InvalidStartingBalance) end end end describe "#balance" do it "returns the sum of transactions" do expect(account.balance).to eq(0) end end describe "#account_number" do it "returns a masked account number" do expect(account.acct_number).to eq ("******6789") end end describe "deposit!" do context "with valid input" do it "returns the current account balance" do expect(account.deposit!(100)).to eq(100) end end context "with invalid input" do it "raises an argument error when given an invalid deposit amount" do expect{ account.deposit!(-100) }.to raise_error(NegativeDepositError) end end context "with invalid input" do it "raises an argument error when given an invalid deposit type" do expect {account.deposit!("a")}.to raise_error(InvalidTransactionTypeError) end end end describe "#withdraw!" do context "with valid input causing overdraft" do it "raises an argument error when given an withdrawl amount greater than current balance" do expect {account.withdraw!(100)}.to raise_error(OverdraftError) end end context "with valid input" do it "returns the current account balance" do expect(account.withdraw!(0)).to eq(0) end end context "with invalid input" do it "raises an argument error when given an invalid withdraw type" do expect {account.withdraw!("a")}.to raise_error(InvalidTransactionTypeError) end end end end =begin What are the valid inputs, if any, for this method? What constitutes expected return values? What constitutes unexpected return values? Does the method cause changes to the state of the program? What defines a happy path scenario? What about a sad path? =end
true
5dfd339cacab100449507aa272c519b43135169f
Ruby
User4574/Advent-of-Code-2019
/day01/part2
UTF-8
303
3.53125
4
[]
no_license
#!/usr/bin/env ruby def fuel_required(mass) fuel_queue = [mass] loop do new_fuel = (fuel_queue.last / 3) - 2 return (fuel_queue.sum - mass) if new_fuel <= 0 fuel_queue << new_fuel end end input = $stdin.readlines.map(&:strip).map(&:to_i) puts input.map{ |x| fuel_required(x) }.sum
true
5215f4f809d2ef0e6829c888fe5bafbfacfdfed9
Ruby
diaandco/oops
/lib/oops/tasks.rb
UTF-8
3,752
2.609375
3
[ "MIT" ]
permissive
require 'oops/opsworks_deploy' require 'aws-sdk-s3' require 'rake' module Oops class Tasks attr_accessor :prerequisites, :additional_paths, :includes, :excludes, :format def self.default_args { prerequisites: ['assets:clean', 'assets:precompile'], additional_paths: [], includes: ['public/assets', 'public/packs'], excludes: ['.gitignore'], format: 'zip' } end def initialize(&block) self.class.default_args.each do |key, value| public_send("#{key}=", value) end yield(self) create_task! end def add_file file_path, path if format == 'zip' sh *%W{zip -r -g build/#{file_path} #{path}} elsif format == 'tar' sh *%W{tar -r -f build/#{file_path} #{path}} end end def remove_file file_path, path if format == 'zip' sh *%W{zip build/#{file_path} -d #{path}} elsif format == 'tar' sh *%W{tar --delete -f build/#{file_path} #{path}} end end private include Rake::DSL def create_task! # Remove any existing definition Rake::Task["oops:build"].clear if Rake::Task.task_defined?("oops:build") namespace :oops do task :build, [:filename] => prerequisites do |t, args| args.with_defaults filename: default_filename file_path = args.filename sh %{mkdir -p build} sh %{git archive --format #{format} --output build/#{file_path} HEAD} (includes + additional_paths).each do |path| add_file file_path, path end excludes.each do |path| remove_file file_path, path end puts "Packaged Application: #{file_path}" end end end end end # Initialize build task with defaults Oops::Tasks.new do end namespace :oops do task :upload, :filename do |t, args| args.with_defaults filename: default_filename file_path = args.filename s3 = s3_object(file_path) puts "Starting upload..." s3.upload_file("build/#{file_path}") puts "Uploaded Application: #{s3.public_url}" end task :deploy, :app_name, :stack_name, :filename do |t, args| raise "app_name variable is required" unless (app_name = args.app_name) raise "stack_name variable is required" unless (stack_name = args.stack_name) args.with_defaults filename: default_filename file_path = args.filename file_url = s3_url file_path ENV['AWS_REGION'] ||= 'us-east-1' if !s3_object(file_path).exists? raise "Artifact \"#{file_url}\" doesn't seem to exist\nMake sure you've run `RAILS_ENV=deploy rake opsworks:build opsworks:upload` before deploying" end ops = Oops::OpsworksDeploy.new args.app_name, args.stack_name deployment = ops.deploy(file_url) STDOUT.sync = true STDOUT.print "Deploying" loop do STDOUT.print "." break if deployment.finished? sleep 5 end STDOUT.puts "\nStatus: #{deployment.status}" raise "Deploy failed. Check the OpsWorks console." if deployment.failed? end private def s3_object file_path s3 = Aws::S3::Resource.new s3.bucket(bucket_name).object("#{package_folder}/#{file_path}") end def s3_url file_path s3_object(file_path).public_url.to_s end def build_hash @build_hash ||= `git rev-parse HEAD`.strip end def default_filename ENV['PACKAGE_FILENAME'] || "git-#{build_hash}.zip" end def package_folder raise "PACKAGE_FOLDER environment variable required" unless ENV['PACKAGE_FOLDER'] ENV['PACKAGE_FOLDER'] end def bucket_name raise "DEPLOY_BUCKET environment variable required" unless ENV['DEPLOY_BUCKET'] ENV['DEPLOY_BUCKET'] end end
true
6193909f1de520e172986f7732f05c1814928dad
Ruby
toyokazu/jwk-tool
/bin/jwk_tool
UTF-8
1,889
2.71875
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby # -*- coding: utf-8 -*- require 'rubygems' unless defined?(gem) #here = File.dirname(__FILE__) #$LOAD_PATH << File.expand_path(File.join(here, '..', 'lib')) require 'json/jwt' require 'optparse' class JwkTool attr_accessor :options def output_usage_and_exit(parser = @parser) $stderr.puts parser exit end def initialize(argv, options = {}) @argv = argv @options = options if @argv.size < 1 @argv << "-h" end parse! end def parser @parser ||= OptionParser.new do |opts| opts.banner = "Usage: #{$0} [options]" opts.separator "" opts.separator "options:" opts.on("-g", "--generate", "Generate key pairs as file.") { |v| options[:command] = :generate } opts.on("-k", "--key=file", String, "Specify private key file name.", "Default: priv_key") { |v| options[:key] = v } opts.separator "" opts.on("-h", "--help", "Show this help message.") { output_usage_and_exit(opts) } end end def parse! parser.parse!(@argv) end def run! case options[:command] when :generate generate else output_usage_and_exit end end def generate if options[:key].nil? $stderr.puts "-g, --generate option requires -k, --key to specify key file name" exit end privkey_file = options[:key] pubkey_file = "#{options[:key]}.pub" # generate RSA key pair ssl_pkey = OpenSSL::PKey::RSA.new(2048) # create JSON Web Key (private) for receiver jwk = JSON::JWK.new(ssl_pkey) # create JSON Web Key (public) for sender jwk_pub = JSON::JWK.new(ssl_pkey.public_key) begin open(pubkey_file, "w") {|f| f.write(jwk_pub.to_json)} open(privkey_file, "w") {|f| f.write(jwk.to_json)} rescue => e $stderr.puts "#{e.class}, #{e.message}" end end end jwk_tool = JwkTool.new(ARGV) jwk_tool.run!
true
3dfbfce713bfc5dbc7f633288c91345b0645adfd
Ruby
suesunmi/tictactoe
/lib/game.rb
UTF-8
1,215
3.5625
4
[]
no_license
require 'board' require 'human_player' require 'unbeatable_player' module TicTacToe class Game def whats_next(preference, string_board, position) @board = TicTacToe::Board.new(string_board) if string_board == "_________" && preference == "2" player_a = TicTacToe::HumanPlayer.new("X", @board) @board.play(position, player_a.marker) else @board.play(position, next_player(string_board)) end if evaluate == :continue && preference == "1" player_a = TicTacToe::UnbeatablePlayer.new("X", @board) player_a.make_next_play end evaluate end def next_player(string_board) return "" if string_board == "" || string_board == nil exes = string_board.delete("_O") ohs = string_board.delete("_X") next_marker = [exes,ohs].min { |a,b| a.length <=> b.length } if next_marker == ohs "O" elsif next_marker == exes "X" end end def evaluate if @board.has_winner :winner elsif @board.full? :scratch else :continue end end def board @board.to_s end def winner @board.winner end end end
true
1fa013b58a76ac890f5a791a6fd1b9d1ebcdbdcb
Ruby
mediagreenhouse/spontaneous
/lib/spontaneous/extensions/string.rb
UTF-8
1,115
2.78125
3
[ "MIT" ]
permissive
# encoding: UTF-8 module Spontaneous module Extensions module String def /(path) File.join(self, path.to_s) end def or(alternative) return alternative if empty? self end alias_method :'|', :or def value(format = :html) self end HTML_ESCAPE_TABLE = { '&' => '&amp;', '<' => '&lt;', '>' => '&gt;', '"' => '&quot;', "'" => '&#039;', } def escape_html self.gsub(%r{[#{HTML_ESCAPE_TABLE.keys.join}]}) { |s| HTML_ESCAPE_TABLE[s] } end JS_ESCAPE_MAP = { '\\' => '\\\\', '</' => '<\/', "\r\n" => '\n', "\n" => '\n', "\r" => '\n', '"' => '\\"', "'" => "\\'" } unless defined?(JS_ESCAPE_MAP) def escape_js self.gsub(/(\\|<\/|\r\n|[\n\r"'])/) { JS_ESCAPE_MAP[$1] } end # Makes it easier to pass either a field or a String around # in templates def to_html self end end end end class String include Spontaneous::Extensions::String end
true
1f336f79d0fffd0a2648cb61f744db81b059f20f
Ruby
jasmarc/kmeans
/lib/coordinate.rb
UTF-8
920
3.1875
3
[]
no_license
class Coordinate < Array attr_accessor :data, :cluster def Coordinate.centroid(coordinates) centroid = Coordinate.new(coordinates.first.size) { 0 } coordinates.each do |coordinate| centroid.add(coordinate) end centroid.map! { |x| x/coordinates.size.to_f } centroid.sphere! return centroid end def add(other) if(self.size != other.size) then raise "Dimension error." end self.each_index do |idx| self[idx] += other[idx] end end def distance_to(other) if(self.size != other.size) then raise "Dimension error." end sum = 0 self.each_index do |idx| sum += self[idx] * other[idx] end return 1 - sum end def norm Math.sqrt(self.inject(0.0) { |acc, e| acc + e*e }) end def sphere! norm = self.norm self.map! { |x| x/norm } unless norm == 0 end def to_s "(#{self.join(", ")})" end end
true
3db8f68712d6ac6f6cedec85f5f8d9810c3b3a73
Ruby
wozwas/JP-Text-Adventure
/app/navigation.rb
UTF-8
360
3.671875
4
[]
no_license
def current_room(x,y) current_position = [x, y] if current_position[0] == 0 && current_position[1] == 0 puts "You're at the start, what direction do you go?" elsif current_position[0] == 1 && current_position[1] == 1 #add rooms following this convention else puts "You're in a dark hallway, where do you go?" end end current_room(2,0)
true
b18a8d3caf53fbb7f82aff749c01893d7150c49c
Ruby
acareaga/module_one
/week1/super_fizz.rb
UTF-8
1,064
4.0625
4
[]
no_license
def is_divisible_by_seven?(input) input % 7 == 0 end def is_divisible_by_five?(input) input % 5 == 0 end def is_divisible_by_three?(input) input % 3 == 0 end (1..1000).each do |number| if is_divisible_by_three?(number) && is_divisible_by_five?(number) && is_divisible_by_seven?(number) print "SuperFizzBuzz" elsif is_divisible_by_three?(number) && is_divisible_by_seven?(number) print "SuperFizz" elsif is_divisible_by_five?(number) && is_divisible_by_seven?(number) print "SuperBuzz" elsif is_divisible_by_three?(number) print "Fizz" elsif is_divisible_by_five?(number) print "Buzz" elsif is_divisible_by_seven?(number) print "Super" else print number end end # buzz_words = { # 7 => "Super", # 3 => "Fizz", # 5 => "Buzz" } # # 1000.times do |number| # final_answer = "" # buzz_words.keys.each do |key| # if number % key == 0 # final_answer << buzz_words[key] # end # end # if final_answer == "" # puts number # else # puts final_answer # end # end
true
4d9c8a64aefcc95355dbd96962cb49616269e59a
Ruby
andreasbanelli/projet_exo_ruby
/04_pig_latin/pig_latin.rb
UTF-8
243
2.875
3
[]
no_license
#write your code here def pig_latin(word) if word =~ (/\A[aeiou]/i) word = word + 'ay' elsif word =~ (/\A[^aeiou]/i) match = /\A[^aeiou]/i.match(word) word = match.post_match + match.to_s + 'ay' end word end
true
db2ab5fef47d478d5bdc57305a4c82fe2a73171b
Ruby
bolthar/thunkgen
/lib/thunkgen.rb
UTF-8
446
2.984375
3
[]
no_license
require File.join(File.dirname(__FILE__), "printer.rb") require File.join(File.dirname(__FILE__), "paragraph_factory.rb") printer = Printer.new paragraph_factory = ParagraphFactory.new #paragraphs (rand(5) + 2).times do print printer.build_sentences(paragraph_factory.get_paragraph.get_phrases) print "\n\n" end #always print a bait at the end print printer.build_sentences(paragraph_factory.get_bait.get_phrases) print "\n\nthunk\n"
true
18542b45c9fbdcd03066937793c74eaeec347366
Ruby
shogo-08020318/awesome_events
/app/models/event.rb
UTF-8
1,709
2.625
3
[]
no_license
class Event < ApplicationRecord # event.rbの場合 # アソシエーション :関連付け名, class_name: クラス名 # eventモデルはuserモデルと「user」という関連付けの名前で紐づく # bolongs_to :user, class_name: 'User' # eventモデルはuserモデルと「owner」という関連付けの名前で紐づく belongs_to :owner, class_name: 'User' # こっちが子供、親のDNAを受け継いだファイル has_many :tickets, dependent: :destroy validates :name, length: { maximum: 50 }, presence: true validates :place, length: { maximum: 100 }, presence: true validates :content, length: { maximum: 2000 }, presence: true validates :start_at, presence: true validates :end_at, presence: true validate :start_at_should_be_before_end_at def created_by?(user) return false unless user # unlessは, trueがfalse、falseがtrue # return false if user.nil?でもOK # owner_idはeventのカラム。schemaをみれば一目瞭然。 owner_id == user.id # user&.id end private def start_at_should_be_before_end_at # 開始日と終了日が存在すればfalseなので、if文が実行される # 開始日と終了日が存在しなければ、returnが実行される # unlessは, trueがfalse、falseがtrue return unless start_at && end_at # 上記と等価 # unless start_at && end_at # return # end # return if !(start_at && end_at) # return unless true => false # return if start_at.blank? || end_at.blank? # 開始日と終了日を比較 errors.add(:start_at, 'は終了時間よりも前に設定してください') if start_at >= end_at end end
true