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
c6132a88aa39f06e7d58c242999d64974c855c0c
Ruby
mustache/mustache
/test/fixtures/lambda.rb
UTF-8
459
2.71875
3
[ "MIT" ]
permissive
require 'mustache' class Lambda < Mustache self.path = File.dirname(__FILE__) attr_reader :calls def initialize(*args) super @calls = 0 @cached = nil end def rendered lambda do |text| return @cached if @cached @calls += 1 @cached = render(text) end end def not_rendered lambda { |text| "{{= | =}}#{text}" } end end if $0 == __FILE__ puts Lambda.to_html(Lambda.template, :name => "Jonny") end
true
0b51c8886c295b935d93c11a0ed3cca00432903e
Ruby
kanpou0108/launchschool
/intro_ruby_programming_exercises/9_more_stuff/5_error.rb
UTF-8
519
3.734375
4
[]
no_license
# Why does the following code... # Give us the following error when we run it? # # block.rb1:in `execute': wrong number of arguments (0 for 1) (ArgumentError) # from test.rb:5:in `<main>' def execute(block) block.call end execute { puts "Hello from inside the execute method!" } # we are not passing any argument to the method # to pass a block we have to insert & before the block parameter # Solution # The method parameter block is missing the ampersand sign & that allows a block to be passed as a parameter.
true
432fd92ce4ce106fb1538125cdf5cd12553e5427
Ruby
cmvandrevala/footprints-public
/lib/crafters/crafters_interactor.rb
UTF-8
488
2.75
3
[]
no_license
class CraftersInteractor attr_reader :crafter class InvalidData < RuntimeError end def initialize(crafter) @crafter = crafter end def update(attributes) validate(attributes) crafter.update!(attributes) rescue ActiveRecord::RecordInvalid => e raise InvalidData.new(e.message) end private def validate(attributes) if attributes.symbolize_keys[:skill].to_i <= 0 raise InvalidData.new('Please provide at least one skill') end end end
true
0d45a216a2639b949d1f6d39bb697967a39a07c9
Ruby
ChrstphGrnr/activerecord-tvland-online-web-ft-021119
/app/models/actor.rb
UTF-8
413
2.640625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Actor < ActiveRecord::Base has_many :characters has_many :shows, through: :characters def full_name self.first_name + " " + self.last_name end def list_roles chars = self.characters.map {|c| c.name} shows = self.shows.map{|s| s.name} chars_and_shows = [] chars.each_with_index do |c, i| chars_and_shows << c + " - " + shows[i] end chars_and_shows end end
true
99a442790ce4a7c2b5e8ab1e1c24e1e2bc55fc21
Ruby
goyalmunish/structure_flatter
/lib/structure_flatter/array_hash_structure.rb
UTF-8
2,304
3.625
4
[ "MIT" ]
permissive
require 'active_support/core_ext/string' module StructureFlatter class ArrayHashStructure attr_reader :ahs # Initializing element # passed structure should be a simple or complex structure comprising Hashes and Arrays def initialize(array_hash_structure = nil) @ahs = array_hash_structure end # Flattening the given structure def flatten_structure!(strt = ahs) case strt when Array strt.each do |array_element| flatten_structure!(array_element) if ((array_element.class == Array) || (array_element.class == Hash)) end when Hash strt.each do |hash_key, hash_value| if hash_value.class == Array # trying to flatten the value flatten_key_value_pair!(hash_key, hash_value) # recursive call flatten_structure!(hash_value) elsif hash_value.class == Hash hash_value.each do |hash_value_key, hash_value_value| # recursive call flatten_structure!(hash_value_value) end else # do nothing end end else # do nothing end strt end private # Trying to flatten the given key value pair def flatten_key_value_pair!(key, value) if is_key_value_pair_flattable?(key, value) value.each_index do |index| value[index] = value[index].values.first end end [key, value] end # Checking if given key value pair is flattable def is_key_value_pair_flattable?(key, value) # key should be plural return false unless key.to_s.pluralize == key.to_s # value should be Array return false unless value.class == Array # checking each element of value (which is Array) value.each do |value_element| # should be hash return false unless value_element.class == Hash # it should have only one key-value pair return false unless value_element.count == 1 # its key should be singular form of original key return false unless (value_element.keys.first.to_s != key.to_s) && (value_element.keys[0].to_s.pluralize == key.to_s) end true end end end
true
baee0b281b5da3dd0d9770dc3603a3cfc96bc24a
Ruby
Lewington-pitsos/launch_excercises
/small_problems/excercise_5/q7.rb
UTF-8
194
3.046875
3
[]
no_license
def counter str hash = Hash.new(0) str.split(" ").each do |i| i.gsub!(/\W+/, "") hash[i.length] += 1 end hash end p counter ('Hey diddle diddle, the cat and the fiddle!')
true
dd63922507b6ed0447cea5caa5d9fec26c6c380c
Ruby
95-Samb/advent-of-code
/2019-day 2/spec/intcode_spec.rb
UTF-8
2,204
2.828125
3
[]
no_license
# frozen_string_literal: true require_relative '../intcode.rb' describe Intcode do context 'for a single 4 opcode before 99' do it 'returns 2,0,0,0,99 for 1,0,0,0,99' do expect(Intcode.new.execute([1, 0, 0, 0, 99])).to eq([2, 0, 0, 0, 99]) end it 'returns 2,1,0,0,99 for 1,1,0,0,99' do expect(Intcode.new.execute([1, 1, 0, 0, 99])).to eq([2, 1, 0, 0, 99]) end it 'returns 1,2,0,1,99 for 1,1,0,1,99' do expect(Intcode.new.execute([1, 1, 0, 1, 99])).to eq([1, 2, 0, 1, 99]) end it 'returns 2,1,0,0,99 for 2,1,0,0,99' do expect(Intcode.new.execute([2, 1, 0, 0, 99])).to eq([2, 1, 0, 0, 99]) end it 'returns 1,2,1,2,99 for 1,2,0,2,99' do expect(Intcode.new.execute([1, 2, 0, 2, 99])).to eq([1, 2, 1, 2, 99]) end it 'returns 2,2,6,2,99 for 2,2,3,2,99' do expect(Intcode.new.execute([2, 2, 3, 2, 99])).to eq([2, 2, 6, 2, 99]) end it 'returns 1,0,1,2,99,0 for 1,0,5,2,99,0' do expect(Intcode.new.execute([1, 0, 5, 2, 99, 0])).to eq([1, 0, 1, 2, 99, 0]) end it 'returns 1,6,2,2,99,0,2 for 1,6,5,2,99,0,2' do expect(Intcode.new.execute([1, 6, 5, 2, 99, 0, 2])).to eq([1, 6, 2, 2, 99, 0, 2]) end end context 'for a double opcode before 99' do it 'returns 2,4,0,0,1,0,0,1,99 for 1,0,0,0,1,0,0,1,99' do expect(Intcode.new.execute([1, 0, 0, 0, 1, 0, 0, 1, 99])).to eq([2, 4, 0, 0, 1, 0, 0, 1, 99]) end it 'returns 2,4,0,0,2,0,0,1,99 for 1,0,0,0,2,0,0,1,99' do expect(Intcode.new.execute([1, 0, 0, 0, 2, 0, 0, 1, 99])).to eq([2, 4, 0, 0, 2, 0, 0, 1, 99]) end it 'returns 1,1,1,0,2,0,0,1,99 for 1,0,1,0,2,0,0,1,99' do expect(Intcode.new.execute([1, 0, 1, 0, 2, 0, 0, 1, 99])).to eq([1, 1, 1, 0, 2, 0, 0, 1, 99]) end it 'returns 1,1,4,1,2,0,0,1,99 for 1,0,4,1,2,0,0,1,99' do expect(Intcode.new.execute([1, 0, 4, 1, 2, 0, 0, 1, 99])).to eq([1, 1, 4, 1, 2, 0, 0, 1, 99]) end end context 'for a triple opcode before 99' do it 'returns 4,8,0,0,1,0,0,0,1,0,0,1,99 for 1,0,0,0,1,0,0,0,1,0,0,1,99' do expect(Intcode.new.execute([1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 99])).to eq([4, 8, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 99]) end end end
true
f772334254fe5d112c1527c8c5422af3d13de9b6
Ruby
dddotcom/algorithms_practice
/sorting/merge_sort/ruby_merge_sort.rb
UTF-8
690
4.0625
4
[]
no_license
def merge_sort(arr) if arr.length <= 1 return arr end middleIndex = (arr.length/2).floor leftArr = arr[0...middleIndex] rightArr = arr[middleIndex...arr.length] return merge(merge_sort(leftArr), merge_sort(rightArr)) end def merge(leftArr, rightArr) mergedArr = [] while leftArr.length > 0 && rightArr.length > 0 do if leftArr[0] < rightArr[0] mergedArr.push(leftArr.shift) else mergedArr.push(rightArr.shift) end end return mergedArr + leftArr + rightArr end puts merge_sort([5,2,8,1,7,6,4,3,9]).inspect puts merge_sort([14, 7, 3, 12]).inspect puts merge_sort([5, 8, 2, 5, 3, 5, 1, 7, 8, 5, 6, 5, 1]).inspect puts merge_sort([1]).inspect
true
249e08252ec6caf490d5e9e591443a123d85ec69
Ruby
mechnicov/credit-card-checker
/spec/credit_card_checker_spec.rb
UTF-8
1,263
2.703125
3
[]
no_license
require 'credit_card_checker' RSpec.describe CreditCardChecker do describe '.identify_type' do context 'input is correct' do let(:cards) { %w(371234567890123 6011123456789012 5412345678901234 4417123456789112 1234567890123456) } it 'should correctly identify card type' do types = cards.map { |card_number| CreditCardChecker.identify_type(card_number) } expect(types).to eq %w(AMEX Discover MasterCard Visa unknown) end end context 'input is incorrect' do let(:incorrect) { 'jfkdmvpie;w' } it 'should return nil' do expect(CreditCardChecker.identify_type(incorrect)).to be_nil end end end describe '.check_validity' do context 'card is valid' do let(:valid_card) { '4408041234567893' } it 'should issue that the card is valid' do expect(CreditCardChecker.check_validity(valid_card)).to eq 'valid' end end context 'card is not valid' do let(:invalid_card) { '4417123456789112' } it 'should issue that the card is not valid' do expect(CreditCardChecker.check_validity(invalid_card)).to eq 'not valid' end end end end
true
94cd9278c3b820fba39f0a0e54adb7a4435ea20f
Ruby
AngelChaos26/openpay-solidus-ruby
/config/initializers/error.rb
UTF-8
810
2.53125
3
[]
no_license
Conekta::Error.class_eval do attr_reader :category, :description, :http_code, :error_code, :request_id, :fraud_rules def initialize(options={}) @category = options["category"] @error_code = options["error_code"] @request_id = options["request_id"] #if options["details"] #@details = options["details"].collect{|details| #Conekta::ErrorDetails.new(details) #} #else #temp_details = Conekta::ErrorDetails.new({ # "message" => options["message_to_purchaser"], # "debug_message" => options["description"], # "param" => options["param"] # }) #@details = [temp_details] #end @message = options["description"] @fraud_rules = options["fraud_rules"] super end end
true
555d21aed13bbaf8c56de92b1fec0e32ce924374
Ruby
watir/watir
/lib/watir/scroll.rb
UTF-8
2,871
2.796875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
# frozen_string_literal: true module Watir module Scrolling def scroll Scroll.new(self) end end class Scroll def initialize(object) @driver = object.browser.wd @object = object @origin = nil end # Scrolls by offset. # @param [Fixnum] left Horizontal offset # @param [Fixnum] top Vertical offset # def by(left, top) if @origin @driver.action.scroll_from(@origin, left, top).perform else @object.browser.execute_script('window.scrollBy(arguments[0], arguments[1]);', Integer(left), Integer(top)) end self end # Scrolls to specified location. # @param [Symbol] param # def to(param = :top) return scroll_to_element if param == :viewport args = @object.is_a?(Watir::Element) ? element_scroll(param) : browser_scroll(param) raise ArgumentError, "Don't know how to scroll #{@object} to: #{param}!" if args.nil? @object.browser.execute_script(*args) self end # Sets an origin point for a future scroll # @param [Integer] x_offset # @param [Integer] y_offset def from(x_offset = 0, y_offset = 0) @origin = if @object.is_a?(Watir::Element) Selenium::WebDriver::WheelActions::ScrollOrigin.element(@object.we, x_offset, y_offset) else Selenium::WebDriver::WheelActions::ScrollOrigin.viewport(x_offset, y_offset) end self end private def scroll_to_element @driver.action.scroll_to(@object.we).perform end def element_scroll(param) script = case param when :top, :start 'arguments[0].scrollIntoView();' when :center <<-JS var bodyRect = document.body.getBoundingClientRect(); var elementRect = arguments[0].getBoundingClientRect(); var left = (elementRect.left - bodyRect.left) - (window.innerWidth / 2); var top = (elementRect.top - bodyRect.top) - (window.innerHeight / 2); window.scrollTo(left, top); JS when :bottom, :end 'arguments[0].scrollIntoView(false);' else return nil end [script, @object] end def browser_scroll(param) case param when :top, :start 'window.scrollTo(0, 0);' when :center y = '(document.body.scrollHeight - window.innerHeight) / 2 + document.body.getBoundingClientRect().top' "window.scrollTo(window.outerWidth / 2, #{y});" when :bottom, :end 'window.scrollTo(0, document.body.scrollHeight);' when Array ['window.scrollTo(arguments[0], arguments[1]);', Integer(param[0]), Integer(param[1])] end end end end
true
539771cab2906f501be64e6ba7196960f12671f5
Ruby
jsuich/Flashcards
/test.rb
UTF-8
668
2.828125
3
[]
no_license
# Richard and Josh's version class Controller attr_reader :deck, :view def initialize(src_file, view = View.new) @deck = Deck.new(parse_file(src_file)) @view = view end def parse_file open() end def run_game def execute(command, args) case command when 'deck' view.render(deck.tasks) when 'add' task_content = content_from(args) deck.add(Task.new(task_content)) when 'delete' deck.delete(id_from(args)) when 'complete' task = deck.find(id_from(args)) task.complete end end def content_from(args) args.join(' ') end def id_from(args) args.first.to_i end end
true
beb69616947ec3adfa54040f7d371d090e128dae
Ruby
GalaxyAstronaut/Portfolio
/three.rb
UTF-8
168
3.78125
4
[]
no_license
def sum_of_elements(array) sum = 0 array.each do |el| sum += el end sum end puts sum_of_elements([1,2,3]) puts sum_of_elements([10,20,30])
true
ce9788f32b149811c0781f55a40f7d658cc752c1
Ruby
brlst16/ruby-object-attributes-lab-onl01-seng-pt-120819
/lib/dog.rb
UTF-8
375
3.609375
4
[]
no_license
class Dog # setter method where the argument is set equal to the instance variable def name=(dog_name) @name = dog_name end # getter method where the instance variable in the setter method is ? def name @name end # setter method for breed def breed=(dog_breed) @breed = dog_breed end def breed @breed end end
true
316b86819aac3a86ef47be034e01280bbe2e0b61
Ruby
SimpleFinance/chef-handler-cookbook-copy
/lib/chef-handler-cookbook-copy.rb
UTF-8
1,769
2.71875
3
[ "Apache-2.0" ]
permissive
# lib/chef-handler-cookbook-copy.rb # # Author: Simple Finance <ops@simple.com> # Copyright 2013 Simple Finance Technology Corporation. # Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # # Chef handler to edit MOTD with useful info after a run require 'rubygems' require 'chef' require 'chef/handler' class ChefCookbookCopy < Chef::Handler attr_reader :path, :mode, :always_copy def initialize(options = defaults) @path = options[:path] @mode = options[:mode] @always_copy = options[:always_copy] end def defaults return { :path => '/var/cache/chef/cookbooks', :mode => 0755, :always_copy => true } end def copy_cookbooks cookbook_paths = Array(Chef::Config[:cookbook_path]) cookbook_paths.each_with_index do |origin, index| dst = ::File.join(@path, "cookbooks-#{index}") FileUtils.mkdir_p(dst, :mode => @mode) if !Dir.exists?(dst) Dir.entries(origin).sort[2..-1].each do |cookbook| FileUtils.cp_r(::File.join(origin, cookbook), dst) end end end def report if run_status.success? || @always_copy Chef::Log.info "Copying cookbooks to #{@path}" copy_cookbooks end end end
true
a4400fa345131c6b0e57c1062bc8bc1166c8533d
Ruby
wassi12495/collections_practice_vol_2-web-103017
/collections_practice.rb
UTF-8
1,738
3.734375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# your code goes here def begins_with_r(array) array.all? {|item| item.split("").first == "r"} end def contain_a(array) a_words = [] array.each do |word| if word.split("").any?{|letter| letter == "a"} a_words << word end end a_words end # Return first element that starts with "wa" def first_wa(array) array.find do |word| # Set the word to string first, test array includes non-strings if word.to_s.split("").first(2).join == "wa" return word end end end #Remove anything that is not a string in the array def remove_non_strings(array) array_of_strings = [] array.each do |item| if item.is_a?(String) array_of_strings << item end end array_of_strings end # Count how many times something appears in an array def count_elements(array) hash_array = [] array.each do |name_hash| name_hash.each do |category, name| new_hash = { :name => name, :count => array.count({category => name}) } hash_array << new_hash end end hash_array.uniq end def merge_data(keys, data) array = [] keys.each do |person| first_name = person[:first_name] data.each do |person_data| if person_data[first_name] array << person.merge(person_data[first_name]) end end end array end def find_cool(cool) array = [] cool.each do |person| if person[:temperature] == "cool" array << person end end array end def organize_schools(schools) organized = {} schools.each do |school_name, location| loc = location[:location] if organized[loc] organized[loc] << school_name else organized[loc] = [] organized[loc] << school_name end end organized end
true
e04c4da2d88cfa8d0451441fbf21d024ca862f2f
Ruby
dhf0820/ids-core
/sys_models/deviceable.rb
UTF-8
1,394
3
3
[]
no_license
module Deviceable def add_device(device, primary) puts "Add Device to #{self.full_name} - #{device}" remove_device(device) if primary remove_primary set_primary(device) end new_device = {} new_device[:device_id] = device.id.to_s new_device[:device_name] = device.name new_device[:class_id] = device.delivery_class_id.to_s new_device[:class_name] = device.delivery_class_name new_device[:is_primary] = primary self.devices << new_device device.owner = self device.save end # Remove the specified Device. If it is the current primary device, reset the primary to Mail def remove_device(device) return if self.devices.empty? self.devices.delete_if {|h| h[device.id] == device.id} if self.primary_device[:device_id] == device.id.to_s set_primary(MailDeliveryClass.default_device) # removed primary reset to MAIL end end def set_primary(device) self.primary_device = {device_id: device.id, device_name: device.name, class_id: device.delivery_class_id, class_name: device.delivery_class_name} end def get_primary_device prim_dev = self.devices.select {|dev| dev[:is_primary] == true} if prim_dev.count == 0 return nil end prim_dev[0] end def remove_primary prim_dev = self.devices.select {|dev| dev[:is_primary] == true} if prim_dev.count > 0 prim_dev.each do |dev| dev[:is_primary] = false end end end end
true
e1793b5ed5906fdf9e4a0e8f420fd64268118130
Ruby
schmurfy/monitoring_protocols
/lib/monitoring_protocols/collectd/parser.rb
UTF-8
4,803
2.578125
3
[ "MIT" ]
permissive
module MonitoringProtocols module Collectd class Parser < Parser # part type HOST = 0x0000 TIME = 0x0001 TIME_HR = 0X0008 PLUGIN = 0x0002 PLUGIN_INSTANCE = 0x0003 TYPE = 0x0004 TYPE_INSTANCE = 0x0005 VALUES = 0x0006 INTERVAL = 0x0007 INTERVAL_HR = 0X0009 MESSAGE = 0x0100 SEVERITY = 0x0101 PART_TYPE_AS_STRING = { HOST => 'host', TIME => 'time', TIME_HR => 'time_hr', PLUGIN => 'plugin', PLUGIN_INSTANCE => 'plugin_instance', TYPE => 'type', TYPE_INSTANCE => 'type_instance', VALUES => 'values', INTERVAL => 'interval', INTERVAL_HR => 'interval_hr', MESSAGE => 'message', SEVERITY => 'severity' }.freeze STR_FIELDS = [HOST, PLUGIN, PLUGIN_INSTANCE, TYPE, TYPE_INSTANCE, MESSAGE] INT_FIELDS = [TIME, TIME_HR, INTERVAL, INTERVAL_HR, SEVERITY] COUNTER = 0x00 GAUGE = 0x01 DERIVE = 0x02 ABSOLUTE = 0x03 def self.parse_part_header(buffer) type, length, rest = buffer.unpack('nna*') [type, length - 4, rest] end INT64_MAX = (1 << 63) INT64_SIGN_BIT = (1 << 64) # uint to int # "val = val - #{1 << nbits} if (val >= #{1 << (nbits - 1)})" def self.parse_int64(buffer, signed = false) # [v>>32, v & 0xffffffff].pack("NN")}.join hi, lo, buffer = buffer.unpack("NNa*") n = (hi << 32 | lo) if signed && (n >= INT64_MAX) n = n - INT64_SIGN_BIT end [n, buffer] end def self.parse_part(buffer) type, length, buffer = parse_part_header(buffer) case when INT_FIELDS.include?(type) then val, buffer = parse_int64(buffer) when STR_FIELDS.include?(type) then val, buffer = buffer.unpack("Z#{length}a*") when type == VALUES then val, buffer = parse_part_values(length, buffer) else val, buffer = buffer.unpack("a#{length}a*") raise ParseError, "unknown part: #{type}, data: #{val.inspect}" end # just convert to seconds if (type == TIME_HR) type = TIME val = (val >> 30) end if (type == INTERVAL_HR) type = INTERVAL val = (val >> 30) p [:interval, val] end [ PART_TYPE_AS_STRING[type], val, buffer ] end def self.parse_part_values(length, buffer) # first we need to read the types of all the values values_count, buffer = buffer.unpack("na*") *types, buffer = buffer.unpack("C#{values_count}a*") values = types.map! do |type| case type when COUNTER, ABSOLUTE then val, buffer = parse_int64(buffer) when GAUGE then val, buffer = buffer.unpack("Ea*") when DERIVE then val, buffer = parse_int64(buffer, true) end val end [values, buffer] end COPY_FIELDS = [ :time, :host, :plugin, :plugin_instance, :type, :type_instance, :interval ].freeze def self.parse_packet(buffer, initial_values = {}) packet = NetworkMessage.new(initial_values, COPY_FIELDS) begin type, value, buffer = parse_part(buffer) packet.send("#{type}=", value) end until packet.message || packet.values [packet, buffer] end def self.parse(buffer) packets = [] last_packet = {} # 4 = part header size while buffer.bytesize >= 4 packet, buffer = parse_packet(buffer, last_packet) packets << packet last_packet = packet if packet.data? end packets end # def initialize # @buffer = "" # @last_packet = {} # end # def feed(data) # ret = [] # @buffer << data # if @buffer.bytesize >= 4 # pkt, @buffer = self.class.parse_packet(@buffer, @last_packet) # if pkt.data? # ret << pkt # @last_packet = pack # end # end # ret # end end end register_parser(:collectd, Collectd::Parser) end
true
763e799310fd1d91ebd735e4de63e5f34ffa1a2a
Ruby
katheroine/languagium
/ruby/strings/string_notation.rb
UTF-8
429
3.046875
3
[]
no_license
#!/usr/bin/ruby2.7 s = "hello" puts("\"hello\": #{s} (#{s.class})") s = 'hello' puts("'hello': #{s} (#{s.class})") s = %q(hello) puts("%q(hello): #{s} (#{s.class})") s = %Q(hello) puts("%Q(hello): #{s} (#{s.class})") s = %q[hello] puts("%q[hello]: #{s} (#{s.class})") s = %Q[hello] puts("%Q[hello]: #{s} (#{s.class})") s = %q|hello| puts("%q|hello|: #{s} (#{s.class})") s = %Q|hello| puts("%Q|hello|: #{s} (#{s.class})")
true
e189c5a9b73615dce7f118fffa78be62e9bfb297
Ruby
nixsterchan/ProjectAnotherPin
/app/models/cart.rb
UTF-8
693
3.15625
3
[]
no_license
class Cart < ApplicationRecord has_many :order_items def total_quantity # go over each order item and add up @count = 0 # next, loop over each thing in the order item and add quantity to the count order_items.all.each do |item| # find the count and add one to it @count = @count + item.quantity end @count end def total_price @total = 0 order_items.all.each do |item| @total = @total + item.product.price * item.quantity end @total end def total_price_in_dollars @total = 0 order_items.all.each do |item| @total = @total + item.product.price_in_dollars * item.quantity end @total end end
true
896a8818bf06106a906269b5ea088533e6d19a07
Ruby
szabba/parallax2-polyglot
/ruby/parallax2.rb
UTF-8
4,911
2.9375
3
[]
no_license
require 'sdl' FOREGROUND_VEL_X = 100.0 FOREGROUND_VEL_Y = 50.0 SCREEN_W = 640 SCREEN_H = 480 TILE_W = 48 TILE_H = 48 MAP_W = 16 MAP_H = 16 class TiledLayer def initialize(map, tiles) @x = @y = 0 @v_x = @v_y = 0 @map = map @tiles = tiles end def x @x end def y @y end def set_pos(x, y) @x = x @y = y end def v_x @v_x end def v_y @v_y end def set_v(x, y) @v_x = x @v_y = y end def animate(dt) @x += dt * @v_x @y += dt * @v_y end def limit_bounce max_x = MAP_W * TILE_W - SCREEN_W max_y = MAP_H * TILE_H - SCREEN_H if @x >= max_x @v_x = -@v_x @x = max_x * 2 - @x elsif @x <= 0 @v_x = -@v_x @x = -@x end if @y >= max_y @v_y = -@v_y @y = max_y * 2 - @y elsif @y <= 0 @v_y = -@v_y @y = -@y end end def link(other, ratio) @x = other.x * ratio @y = other.y * ratio end def render(screen) map_x = (@x / TILE_W).to_i map_y = (@y / TILE_H).to_i fine_x = (@x % TILE_W).to_i fine_y = (@y % TILE_H).to_i (-fine_y).step(SCREEN_H, TILE_H) do | y | map_x_loop = map_x (-fine_x).step(SCREEN_W, TILE_W) do | x | draw_tile( screen, @tiles, x, y, @map[map_y][map_x_loop]) map_x_loop += 1 end map_y += 1 end end end foreground_map = [ "3333333333333333", "3 2 3 3", "3 222 3 222 3", "3333 22 22 3", "3 222 3", "3 222 2 2 333", "3 2 2 222 3", "3 222 223", "3 333 3", "3 22 23 323 23", "3 22 32 333 23", "3 333", "3 3 22 33 3", "3 222 2 3 3", "3 3 3 3 3", "3333333333333333"] middle_map = [ " 1 1 ", " 1 1", " 1 ", " 1 1 1 ", " 1 ", " 1 ", " 1 1 ", " 1 1 ", " 1 ", " 1 ", " 1 1 ", " 1 1 ", " 1 ", " 1 ", " 1 1 ", " "] background_map = [ "0000000000000000", "0000000000000000", "0000000000000000", "0000000000000000", "0000000000000000", "0000000000000000", "0000000000000000", "0000000000000000", "0000000000000000", "0000000000000000", "0000000000000000", "0000000000000000", "0000000000000000", "0000000000000000", "0000000000000000", "0000000000000000"] def draw_tile(screen, tiles, x, y, tile) if tile == " " return end SDL::Surface.blit( tiles, 0, (tile.ord - "0".ord) * TILE_H, TILE_W, TILE_H, screen, x, y) end # Program body bpp = 0 flags = 0 for arg in ARGV if arg == "-d" flags |= SDL::DOUBLEBUF elsif arg == "-f" flags |= SDL::FULLSCREEN else bpp = -arg.to_i end end SDL.init(SDL::INIT_VIDEO) SDL.setVideoMode(SCREEN_W, SCREEN_H, bpp, flags) screen = SDL.getVideoSurface SDL::WM.setCaption("Parallax Scrolling Example 2", "Parallax 2") tiles = SDL::Surface.loadBMP('tiles.bmp').display_format() tiles.set_color_key(SDL::SRCCOLORKEY, tiles.format.map_rgb(255, 0, 255)) foreground_layer = TiledLayer.new(foreground_map, tiles) middle_layer = TiledLayer.new(middle_map, tiles) background_layer = TiledLayer.new(background_map, tiles) foreground_layer.set_v(FOREGROUND_VEL_X, FOREGROUND_VEL_Y) tick1 = SDL::getTicks() frame_count = 0 done = false while not done event = SDL::Event.poll() case event when SDL::Event::MouseButtonDown done = true end tick2 = SDL::getTicks() dt = (tick2 - tick1) * 0.001 puts("frame: %d, dt: %d ms, fps: %.0f" % [ frame_count, tick2 - tick1, dt > 0 ? 1.0 / dt : 0]) tick1 = tick2 frame_count += 1 foreground_layer.animate(dt) foreground_layer.limit_bounce() middle_layer.link(foreground_layer, 0.5) background_layer.link(foreground_layer, 0.25) background_layer.render(screen) middle_layer.render(screen) foreground_layer.render(screen) draw_tile(screen, tiles, 0, 0, '4') screen.flip() SDL.delay(1) end
true
62a10168816851fbc605cf0b79baddff02ca70db
Ruby
UseK/CCParser
/lib/clone_set.rb
UTF-8
559
2.796875
3
[]
no_license
#encoding: utf-8 $LOAD_PATH << File.dirname(__FILE__) require "clone_piece" class CloneSet < Array def include_package? package @pkg_list ||= update_pkg_list @pkg_list.include? package.to_s end def update_pkg_list pkg_list = [] self.each do |cp| pkg_list << cp.package end pkg_list.uniq end end if $0 == __FILE__ cs = CloneSet.new cs << ClonePiece.new("0.0\t6,8,4\t14,38,43\t39") cs << ClonePiece.new("0.1\t6,8,4\t14,38,43\t39") p cs.include_package? 0 p cs.include_package? "0" p cs.include_package? 1 end
true
e3d0b794739aec7f1e796c43e62f06629ea9fb46
Ruby
hmcfletch/project-euler
/ruby/067.rb
UTF-8
1,425
4.0625
4
[]
no_license
# By starting at the top of the triangle below and moving to adjacent numbers on # the row below, the maximum total from top to bottom is 23. # 3 # 7 4 # 2 4 6 # 8 5 9 3 # That is, 3 + 7 + 4 + 9 = 23. # Find the maximum total from top to bottom in triangle.txt (right click and # 'Save Link/Target As...'), a 15K text file containing a triangle with # one-hundred rows. # NOTE: This is a much more difficult version of Problem 18. It is not possible # to try every route to solve this problem, as there are 299 altogether! If you # could check one trillion (1012) routes every second it would take over twenty # billion years to check them all. There is an efficient algorithm to solve it. # ;o) triangle = [] f = File.open("../data_files/p067_triangle.txt", "r") do |f| f.each_line do |line| triangle << line.split(" ").map{ |j| j.to_i } end end height = triangle.length width = triangle[height-1].length values = Array.new(height) (1..(triangle.length)).each do |i| values[i-1] = Array.new(i) end (0..(height-1)).each do |i| # row (0..i).each do |j| # column if i-1 < 0 values[i][j] = triangle[i][j] elsif j-1 < 0 values[i][j] = values[i-1][j] + triangle[i][j] elsif i == j values[i][j] = values[i-1][j-1] + triangle[i][j] else values[i][j] = [values[i-1][j] + triangle[i][j], values[i-1][j-1] + triangle[i][j]].max end end end puts values[height-1].max
true
261a5d525a20c27854f976bd536e726f796e57e9
Ruby
5shadesofr3d/Ruby-System-Shell
/filewatch/file_watcher.rb
UTF-8
4,832
2.921875
3
[ "MIT" ]
permissive
require_relative 'file_command_parser' require_relative '../precision/precision' require_relative '../shell/command' require 'test/unit' class FileWatcher include Test::Unit::Assertions def initialize(args) #pre assert args.is_a? Array args.each { |a| assert a.is_a? String } parser = FileCommandParser.new(args) @command = parser.command[0] @args = parser.command[1] @delay = parser.delay alteration = parser.monitor_type if alteration == "-d" @alteration = "file_destroyed?" #alteration = "destroyed" elsif alteration == "-a" @alteration = "file_changed?" #alteration = "altered" else @alteration = "file_created?" #alteration = "created" end @observers = self.create_observer(parser.files) #post assert @command.is_a? String assert @delay.is_a? Numeric assert @delay >= 0 assert @observers.is_a? Array @observers.each {|o| assert o.is_a? Observer} assert @alteration.is_a? String assert valid? end def observers assert valid? return @observers end def valid? return false unless @command.is_a? String return false unless @delay.is_a? Numeric return false unless @alteration.is_a? String return false unless @observers.is_a? Array @observers.each { |file| return false unless file.is_a? Observer } return true end def create_observer(files) #pre assert files.is_a? Array files.each { |f| assert f.is_a? String } watchList = [] for file in files watchList += [Observer.new(file)] end #post assert watchList.is_a? Array watchList.each { |f| assert f.is_a? Observer } return watchList end def watch #pre assert valid? assert @observers.is_a? Array @observers.each {|o| assert o.is_a? Observer} assert @alteration.is_a? String assert @command.is_a? String assert @delay.is_a? Numeric assert @delay >= 0 while true for observer in @observers if observer.send(@alteration) puts "The file '#{observer.file}' was #{@alteration}... the command '#{@command}' will execute in #{@delay} milliseconds..." Precision::timer_ms(@delay, ForkCommand.new { self.exec_command } ) end end end #post end def exec_command #pre assert valid? #assert (@args.is_a? String) || (@args.is_a? NIL) try this out when applicable tests exist assert @command.is_a? String if @args.is_a? String exec(@command, @args) else exec(@command) end #post assert valid? end end class Observer include Test::Unit::Assertions def initialize(file) #pre assert file.is_a? String @file = file @time_altered = self.calculate_last_altered_time @exists = self.calculate_file_exists #post assert @file.is_a? String assert @time_altered.is_a? Time assert (@exists == true || @exists == false) assert valid? end def file #pre assert valid? assert @file.is_a? String return @file end def exists assert valid? return @exists end def time_altered assert valid? return @time_altered end def valid? return false unless (@exists == true || @exists == false) return false unless @file.is_a? String return false unless @time_altered.is_a? Time return true end def calculate_last_altered_time #dont assert class invariant as this is called during setup # pre assert @file.is_a? String begin aTime = File.stat(@file).atime rescue aTime = Time.new(0) end #post assert aTime.is_a? Time return aTime end def calculate_file_exists #dont assert class invariant as this is called during setup # pre assert @file.is_a? String doesFileExist = true begin File::Stat.new(@file) rescue doesFileExist = false end #post assert (doesFileExist == true || doesFileExist == false) return doesFileExist end def file_created? #pre assert valid? assert (@exists == true || @exists == false) oldExistsStatus = @exists @exists = self.calculate_file_exists #post assert (@exists == true || @exists == false) assert (oldExistsStatus == true || oldExistsStatus == false) assert valid? if @exists and !oldExistsStatus return true end return false end def file_destroyed? #pre assert valid? assert (@exists == true || @exists == false) oldExistsStatus = @exists @exists = self.calculate_file_exists #post assert valid? assert (@exists == true || @exists == false) assert (oldExistsStatus == true || oldExistsStatus == false) if !@exists and oldExistsStatus return true end return false end def file_changed? #pre assert valid? assert @time_altered.is_a? Time oldTime = @time_altered @time_altered = self.calculate_last_altered_time #post assert valid? assert @time_altered.is_a? Time assert oldTime.is_a? Time # No change if oldTime == @time_altered return false else return true end end end
true
f30b3a87fc9028aba309489b4b463c136ab43d0d
Ruby
bukk530/railsbook
/lib/railsbook/facebook_redirect_login_helper.rb
UTF-8
2,915
2.828125
3
[ "MIT" ]
permissive
require 'securerandom' require 'uri' #TODO: Implement this class as a Rails Helper class module RailsBook class FacebookRedirectLoginHelper def initialize(redirect_url, session, params) @redirect_url = redirect_url @session = session @params = params end # Params: # -scope # -display_as_popup def get_login_url(options={}) @state = random_bytes(16) @session[:_fb_state] = @state uri_params = { client_id: ENV["app_id"], redirect_uri: @redirect_url, state: @state, sdk: RailsBook::SDK_NAME } unless options[:scope].nil? if options[:scope].is_a? String uri_params[:scope] = options[:scope] elsif options[:scope].is_a? Array uri_params[:scope] = options[:scope].join(',') end end uri_params[:display] = :popup if options[:display_as_popup] return "https://www.facebook.com/" + RailsBook::GRAPH_API_VERSION + "/dialog/oauth?" + URI.encode_www_form(uri_params) end def get_logout_url(session, next_page) if !session.instance_of? FacebookSession raise FacebookSDKException.new "not a valid session" end uri_params = { next: next_page, access_token: session.get_token } return "https://www.facebook.com/logout.php?" + URI.encode_www_form(uri_params) end def get_session_from_redirect @state = get_state if is_valid_redirect response_params = { client_id: ENV["app_id"], redirect_uri: @redirect_url, client_secret: ENV["app_secret"], code: get_code } facebook_response = FacebookRequest.new( FacebookSession::new_app_session, "GET", "/oauth/access_token", response_params ).execute.response if facebook_response["access_token"].present? return FacebookSession.new( facebook_response["access_token"], facebook_response["expires"] || 0 ) end end nil end private def is_valid_redirect !get_code.nil? and get_state.eql? @params[:state] end def get_state @session[:_fb_state] end def get_code @params[:code] end def random_bytes(bytes) if !bytes.is_a? Integer raise FacebookSDKException.new "random expects an integer" end if bytes < 1 raise FacebookSDKException.new "random expects an integer greater than zero" end SecureRandom.hex(bytes) end end end
true
79e8482d1802bb043e51cc42368f034954dfe83c
Ruby
edvfb9/support-plan
/app/models/time_slot.rb
UTF-8
1,159
2.59375
3
[]
no_license
class TimeSlot < ApplicationRecord has_many :semester_plan_connections belongs_to :semester_plan # returns day and start time by index/type of slot def self.find_slot_by_type(type) day = 0 time = 0 while type >= 4 type -= 4 day += 1 end days = ["Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag"] time = (type *2) +8 {day: days[day], start: time} end # return day def self.get_day(type) day = 0 while type >= 4 type -= 4 day += 1 end days = ["Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag"] days[day] end # returns time as strings def self.get_time(type) while type >= 4 type -= 4 end start = (type.to_i() * 2) +8 "#{start}:00 - #{start+2}:00" end def get_priority self.semester_plan_connections.inject(0) {|sum, x| sum + x.availability} end def get_type self.semester_plan_connections.first.typus end def get_users(av) users = [] self.semester_plan_connections.each do |c| if c.availability >= 1 && c.availability <= av users << c.user.id end end users end end
true
2ca800d3303ebdbcab3d180ce9e37b52987e6e9d
Ruby
alechoey/trLOLing
/collection/file_factory/time_stamped_file_factory.rb
UTF-8
816
2.796875
3
[]
no_license
require 'fileutils' require_relative './file_factory' module FileFactory class TimeStampedFileFactory < FileFactory def initialize(dir_path, filename, file_extension='') @dir = dir_path @filename = filename @file_extension = file_extension FileUtils.mkpath(dir_path) end def each filename_pattern = "*#{@filename}*#{@file_extension}" Dir.foreach @dir do |filename| next unless File.fnmatch? filename_pattern, filename yield File.join @dir, filename end end def next_filename time_string = Time.now.strftime '%Y%m%d%H%M%S%L' output_name = time_string output_name += "-#{@filename}" if !@filename.empty? output_name += ".#{@file_extension}" if !@file_extension.empty? output_name end end end
true
2d76cbe5bda88b760ba212098b5207702d1c9cd7
Ruby
durran/injectable
/lib/injectable/registry.rb
UTF-8
2,324
2.78125
3
[ "MIT" ]
permissive
# encoding: utf-8 require "injectable/registerable" module Injectable # The registry keeps track of all objects and their dependencies that need # to be injected at construction. # # @since 0.0.0 module Registry include Registerable extend self # Get an implementation for the provided name. # # @example Get an implementation. # Injectable::Registry.implementation(:persistable) # # @param [ Symbol ] name The name of the implementation. # # @return [ Class ] The implementing class. # # @since 0.0.2 def implementation(name) impl = implementations[name] raise(NotRegistered.new(name)) unless impl && !impl.empty? impl end # Add a constructor method signature to the registry. # # @example Add a signature. # Injectable::Registry.register_signature( # UserService, [ :user, :user_finder ] # ) # # @param [ Class ] klass The class to set the constructor signature for. # @param [ Array<Symbol> ] dependencies The dependencies of the # constructor. # # @since 0.0.0 def register_signature(klass, dependencies) signatures[klass] = dependencies.map { |name| name } end # Get the constructor method signature for the provided class. # # @example Get the constructor signature. # Injectable::Registry.signature(UserService) # # @param [ Class ] klass The class to get the signature for. # # @return [ Array<Class> ] The constructor signature. # # @since 0.0.0 def signature(klass) signatures[klass] end # This error is raised when asking for an implementing class that is not # registered in the registry. # # @since 0.0.2 class NotRegistered < Exception # @attribute [r] name The name of the requested implementation. attr_reader :name # Initialize the new error. # # @example Initialize the error. # NotRegistered.new(:persistable) # # @param [ Symbol ] name The name of the implementation. # # @since 0.0.2 def initialize(name) @name = name super("No implementation registered for name: #{name.inspect}.") end end private def signatures @signatures ||= {} end end end
true
4facb6342d82263b04a42f8c9f09bc5bad73d6b8
Ruby
ChocolateAceCream/codewar
/prime.rb
UTF-8
472
4.125
4
[]
no_license
=begin Is Prime Define a function isPrime that takes one integer argument and returns true or false depending on if the integer is a prime. Per Wikipedia, a prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. =end def find_prim(num) return false if num < 2 (2...num).each do |i| return false if num % i == 0 end return true end p find_prim(19) p find_prim(12) p find_prim(13)
true
957c7a1faa03553b490e35a73bc81b646d58dd61
Ruby
hchoroomi/rapi_doc
/spec/method_doc_spec.rb
UTF-8
3,160
2.609375
3
[ "MIT" ]
permissive
require 'spec_helper' describe RapiDoc::MethodDoc do before do @method_doc = RapiDoc::MethodDoc.new('a_type') end describe "#methods" do describe 'add_variable' do before do @name = 'any_name' @value = 'a_value' end it "should add a new attribute to the object with the same name" do @method_doc.add_variable(@name, @value) @method_doc.send(@name).should eq(@value) end it "the value should not be added to 'variables' attribute when adding with named other than 'param' " do expect { @method_doc.add_variable(@name, @value) }.to change { @method_doc.variables.count }.by(0) end describe "adding with named 'param'" do before do @name = 'param' end it "the value should be added to 'variables' attribute" do expect { @method_doc.add_variable(@name, @value) }.to change { @method_doc.variables.count }.by(1) end it "the added value should be at the last entry of 'variables' attribute" do @method_doc.add_variable(@name, @value) @method_doc.variables.last.should eq(@value) end end end describe 'add_output' do before do @name = 'any_name' @value = 'a_value' end it "should not be added to the 'outputs' attribute when adding with named other than 'output'" do expect { @method_doc.add_output(@name, @value) }.to change { @method_doc.outputs.count }.by(0) end describe "adding with named 'output'" do before do @name = 'output' end it "should add an output item to the 'outputs' attribute" do expect { @method_doc.add_output(@name, @value) }.to change { @method_doc.outputs.count }.by(1) end it "the added item should be at the last entry of 'outputs' attribute" do @method_doc.add_output(@name, @value) new_hash = eval("{#{@value}: ''}") @method_doc.outputs.last.should eq(new_hash) end it "the new output item should be a hash with key named the 'value' parameter" do @method_doc.add_output(@name, @value) @method_doc.outputs.last.keys.include?(@value.to_sym).should be_true end end end describe 'append_output' do before do @current_format_content = "any string" @last_hash = {format: @current_format_content} @method_doc.outputs << @last_hash end it 'should append the existing format content on the outputs' do value = "some string" @method_doc.append_output(value) @method_doc.outputs.last[:format].should eq(@current_format_content + value) end it 'the appended value should be html-escaped' do value = "<a>tag</a>" @method_doc.append_output(value) @method_doc.outputs.last[:format].should eq(@current_format_content + ERB::Util.html_escape(value)) end end end end
true
cf7797bfa701428e5810a509d1c85549712308fb
Ruby
toucan-stan/Intro-to-Programming-Companion-Workbook
/Int_Quiz_3/int_3.3.rb
UTF-8
1,574
4.34375
4
[]
no_license
#Tealeaf Introduction to Programming, Companion Workbook #Intermediate Quiz 3, Question 3 #Let's call a method, and pass both a string and an array as parameters and see #how even though they are treated in the same way by Ruby, the results can be different. #Study the following code and state what will be printed...and why: def tricky_method(a_string_param, an_array_param) a_string_param += "rutabaga" an_array_param << "rutabaga" end my_string = "pumpkins" my_array = ["pumpkins"] tricky_method(my_string, my_array) puts "My string looks like this now: #{my_string}" #Outputs "rutabaga" puts "My array looks like this now: #{my_array}" #Outputs ["pumpkins", "rutabaga"] #ANSWER: Same block of code as Intermediate Quiz 2, Question 3. #my_string is passed to the method as a_string_param; different variables that point to (reference) the same object. #the operation a_string_param += "rutabaga" can be rewritten as a_string_param = a_string_param + "rutabaga" #when a_string_param is assigned a new value, its association with the object is broken. The += operator will not #produce an effect on my_string outside of the method. #my_array is passed to the method as an_array_param; again, different variables that point to or reference the same object. #the operation an_array_param << "rutabaga" appends "rutabaga" to the object referenced by an_array_param. This #means that my_array, in turn, is permanently changed. #Variables point to objects, or places in memory. Mutating that object will in turn modify all variables that point to that object.
true
a854e19aae0a857ff87980f5b82db64ad65424a9
Ruby
svamja/project_euler
/p082-path-sum-three-ways.rb
UTF-8
2,260
3.65625
4
[]
no_license
# PROBLEM STATEMENT # The minimal path sum in the 5 by 5 matrix below, by starting in any cell in the left column and finishing in any cell in the right column, and only moving up, down, and right, is indicated in red and bold; the sum is equal to 994. # ⎛⎝⎜⎜⎜⎜⎜⎜131201630537805673968036997322343427464975241039654221213718150111956331⎞⎠⎟⎟⎟⎟⎟⎟ # Find the minimal path sum, in matrix.txt (right click and "Save Link/Target As..."), a 31K text file containing a 80 by 80 matrix, from the left column to the right column. # Approach start_time = Time.now # PROGRAM START # matrix = IO.readlines('./p082_matrix.txt') matrix.map! do |row| row.chomp! row.split(',').map(&:to_i) end # matrix = [ # [131, 673, 234, 103, 18], # [1, 1, 342, 965, 150], # [630, 1, 746, 422, 111], # [537, 1, 8999, 1, 1], # [805, 1, 55, 33, 22] # ] size = matrix.size (size-2).downto(0) do |col| alt_column = [] (0..size-1).each do |row| alt_column.push matrix[row][col] # for first row, simply add right side's value for now if row == 0 matrix[row][col] += matrix[row][col+1] next end # if the value above is lower than on the right, add that if matrix[row][col] + matrix[row-1][col] < matrix[row][col] + matrix[row][col+1] matrix[row][col] += matrix[row-1][col] else matrix[row][col] += matrix[row][col+1] end end (size-1).downto(0) do |row| # for last row, add right side's value if row == size-1 alt_column[row] += matrix[row][col+1] next end # if the value below is lower than current, replace it if alt_column[row] + alt_column[row+1] < matrix[row][col] matrix[row][col] = alt_column[row] + alt_column[row+1] alt_column[row] = matrix[row][col] else alt_column[row] += matrix[row][col+1] end end end first_column = matrix.map { |row| row[0] } puts first_column.min # PROGRAM END # end_time = Time.now diff_time = end_time - start_time puts puts "TECHNICAL" puts puts "Start time: #{start_time}" puts "End time: #{end_time}" puts "elapsed time: #{diff_time}"
true
ac59d5f20f48fede1d6f84f601e2c59a62d2c9cd
Ruby
lausan029/E7CP2A1
/ej2.rb
UTF-8
749
4.09375
4
[]
no_license
# # #Extraer todos los elementos que excedan mas de 5 caracteres utilizando el método .select. nombres = ["Violeta", "Andino", "Clemente", "Javiera", "Paula", "Pia", "Ray"] p nombres.select{ |nom| nom.length > 5 } #Utilizando .map crear una arreglo con los nombres en minúscula. arr_minus = nombres.map { |e| e.downcase } p arr_minus #Utilizando .select para crear un arreglo con todos los nombres que empiecen con P. nom_p = nombres.select{ |nom| nom.split("").first == 'P' } p nom_p #Utilizando .map crear un arreglo único con la cantidad de letras que tiene cada nombre. nuevo = nombres.map { |e| e.split("") } p nuevo #Utilizando .map y .gsub eliminar las vocales de todos los nombres. del = nombres.map { |nu| nu.delete('aeiou') } p del
true
4072c397aec140ab45d59713757568aa0f632d47
Ruby
lazyrain/zipdf
/zipdf.rb
SHIFT_JIS
2,118
2.625
3
[]
no_license
#! ruby -Ks require 'rubygems' require 'zip/zipfilesystem' require 'prawn' require 'fileutils' OUTPUT_PATH = ".\\temp\\" if ARGV[0].nil? print "t@Cw肳Ă܂...\n\n" exit(-1) end if File.extname(ARGV[0]) != ".zip" print "zipt@Cw肵Ă...\n\n" exit(-1) end print "zipdf s܂...\n\n" # w肵tH_ZIPt@C񋓂A # ׂď܂Ń[v zip_file = ARGV[0] pdf_name = File.basename( zip_file , ".zip" ) print "#{zip_file} => #{pdf_name}.pdf " Prawn::Document.generate(pdf_name + ".pdf", :size => "B5", :margin => 0) do index = 0 file_list = [] # ZIPt@C̒̃t@CoA\[g Zip::ZipInputStream.open( zip_file ) do |input_stream| while entry = input_stream.get_next_entry() # t@CȊO̓pX next unless entry.file? file_list << entry.name end end file_list.sort! # ZIPt@CWJĉ摜o file_list.each do |f| zip = Zip::ZipFile.open( zip_file ) entry = zip.find_entry(f) # ‚Ȃ΃XLbv next if entry.nil? if index % 10 == 0 print "." end d = File.dirname(entry.name) FileUtils.makedirs(OUTPUT_PATH + d) source = OUTPUT_PATH + entry.name start_new_page() if index > 0 # 摜o File.open(source, "w+b") do |wf| entry.get_input_stream do |stream| wf.puts(stream.read()) end end # WJ摜PDF֊i[ image source, :fit => bounds.top_right, :position => :center, :vposition => :center # WJ摜̌n File.delete source index += 1 end print "\n" render end
true
a00bd3e28b1a3a22fafa3cd60e8e9edf874acb8f
Ruby
beetlejuice/dou-votes
/votes_parser.rb
UTF-8
1,421
2.96875
3
[]
no_license
require 'open-uri' require 'nokogiri' VOTES_NUMBER_LOCATOR_CSS = "div#votersWidgetId > div.title > span" VOTER_IMG_LOCATOR_CSS = "div#votersWidgetId > ul > li > a > div > img" QUESTION_BLOCK_LOCATOR_CSS = "div#companyPollResultsId > div.l-question > ul > li" QUESTION_TITLE_LOCATOR_CSS = "div.title" QUESTION_STAT_LOCATOR_CSS = "div.info > em" class VotesParser attr_reader :page def initialize(page_url) @page = Nokogiri::HTML(open(page_url)) end def get_votes_number votes_string = @page.at_css(VOTES_NUMBER_LOCATOR_CSS).text votes_string[/^\d+/].to_i end def get_voters_list @page.css(VOTER_IMG_LOCATOR_CSS).map { |node| node.attribute('title') } end def get_votes_statistics stat = {} question_nodes = @page.css(QUESTION_STAT_LOCATOR_CSS) question_nodes.each do |node| question = node.css(QUESTION_TITLE_LOCATOR_CSS).text question_stat_str = node.css(QUESTION_STAT_LOCATOR_CSS).attribute('title') question_stat = parse_question_stat(question_stat_str) stat[question] = question_stat end stat end private def parse_question_stat(votes_string) question_stat = {} votes_string.scan(/([а-яА-Я ]+: \d+).?/).flatten.each do |answer_str| answer_key = answer_str.scan(/.+(?=: \d+)/) answer_value = answer_str.scan(/(?<=: )\d+/) question_stat[answer_key] = answer_value end question_stat end end
true
4e47cd815881b50f4abcf80626039f35e25292b5
Ruby
vaginessa/Jekyll-v3.0.3-Portable
/ruby/lib/ruby/gems/2.1.0/gems/predicated-0.2.6/lib/predicated/simple_templated_predicate.rb
UTF-8
1,894
2.90625
3
[]
no_license
require "predicated/predicate" require "predicated/evaluate" module Predicated def SimpleTemplatedPredicate(&block) result = nil Module.new do extend SimpleTemplatedShorthand result = instance_eval(&block) end result end class And def fill_in(placeholder_replacement) And.new(left.fill_in(placeholder_replacement), right.fill_in(placeholder_replacement)) end end class Or def fill_in(placeholder_replacement) Or.new(left.fill_in(placeholder_replacement), right.fill_in(placeholder_replacement)) end end class Not def fill_in(placeholder_replacement) Not.new(inner.fill_in(placeholder_replacement)) end end class Operation def fill_in(placeholder_replacement) self.class.new(placeholder_replacement, right) end end class Call def fill_in(placeholder_replacement) self.class.new(placeholder_replacement, method_sym, right) end end class Placeholder; end module SimpleTemplatedShorthand include Shorthand def Eq(right) ::Predicated::Equal.new(Placeholder, right) end def Lt(right) ::Predicated::LessThan.new(Placeholder, right) end def Gt(right) ::Predicated::GreaterThan.new(Placeholder, right) end def Lte(right) ::Predicated::LessThanOrEqualTo.new(Placeholder, right) end def Gte(right) ::Predicated::GreaterThanOrEqualTo.new(Placeholder, right) end def Call(method_sym, right=[]) ::Predicated::Call.new(Placeholder, method_sym, right) end end class Operation < Binary def to_s if left == Placeholder "#{self.class.shorthand}(#{part_to_s(right)})" else super end end end class Call < Operation def to_s if left == Placeholder "Call(#{method_sym.to_s}(#{part_to_s(right)}))" else super end end end end
true
5e5f531a5aa36d6e9d4069a613abc8066e7888d5
Ruby
tong-wu/zd_challenge
/spec/tools/search_spec.rb
UTF-8
1,046
2.578125
3
[]
no_license
require "spec_helper" require "./tools/search.rb" describe Search do describe "#search" do let(:stub_db) do [ { "_id": 1, "name": "personOne", "role": "employee", }, { "_id": 2, "name": "personTwo", "role": "admin", }, { "_id": 3, "name": "personThreee", "role": "admin", }, ] end let(:searcher) { Search.new(stub_db) } context "when theres is no results" do it "returns an empty array" do expect(searcher.search(:_id, "12345")).to eq([]) end end context "when there are matches" do it "returns the results of the matches" do expected_result = [ { _id: 2, name: "personTwo", role: "admin", }, { _id: 3, name: "personThreee", role: "admin", }, ] expect(searcher.search(:role, "admin")).to eq(expected_result) end end context "when field does not exist" do it "returns an empty array" do expect(searcher.search(:who_cares, "1")).to eq([]) end end end end
true
de0f1b59170c8460b1541e7834f1cf99f576af3e
Ruby
allisonharris/ruby_the_hard_way
/ex16.rb
UTF-8
902
3.796875
4
[]
no_license
# getting the file we will use from the command line filename = ARGV.first script = $0 puts "We're going to read #{filename}" puts "If you don't want that, hit CTRL-C (^C)." puts "If you do want that, hit RETURN." print "? " #we give it the CTRL-C or we hit RETURN STDIN.gets puts "Opening the file..." # opening a file with the write option target = open(filename, 'w') puts "Truncating the file..." # this step erases the contents of the file target.truncate(target.size) puts "Now I'm going to ask you for three lines." # these three steps let us enter the three lines print "line 1: "; line1 = STDIN.gets.chomp() print "line 2: "; line2 = STDIN.gets.chomp() print "line 3: "; line3 = STDIN.gets.chomp() puts "I'm going to write these to the file." # one target.write line instead of six target.write(line1 + "\n" + line2 + "\n" + line3 + "\n") puts "And finally, we close it." target.close()
true
ca0a251acbb887346c0aff6a5885f8a849cc1c35
Ruby
mehtaculous/sep-assignments
/02-algorithms/06-improving-complexity/improving_complexity_version3.rb
UTF-8
401
3.484375
3
[]
no_license
# Improving Space Complexity def space_complexity(*arrays) arrays.flatten sorted_array = [arrays.delete_at(-1)] for val in arrays length = sorted_array.length length.times do |i| if val <= sorted_array[i] sorted_array.insert(i, val) break elsif i == length - 1 sorted_array << val break end end end return sorted_array end
true
6dd2af82407c602473cc44ed13b41f1a4383c79f
Ruby
naorespawn/rubybook
/chapter_11/warikan3.rb
UTF-8
277
4.03125
4
[]
no_license
def warikan(bill, number) warikan = bill / number puts "1人あたりの値段は#{warikan}円です" rescue ZeroDivisionError puts "0人では割り勘できません" end # begin,end節を省略できる warikan(100, 0) warikan(100, 1) warikan(100, 2)
true
33fd2451ddcfa900d5d8cdb0cfc2b030c71df56e
Ruby
brookearyan/array-CRUD-lab-web-082817
/lib/array_crud.rb
UTF-8
604
3.96875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def create_an_empty_array empty_array = [] end def create_an_array cats = ["Fluffy", "Bijou", "Coco", "Stephanie"] end def add_element_to_end_of_array(array, element) array.push(element) end def add_element_to_start_of_array(array, element) array.unshift(element) end def remove_element_from_end_of_array(array) array.pop end def remove_element_from_start_of_array(array) array[0] end def retrieve_element_from_index(array, index_number) array[index_number] end def retrieve_first_element_from_array(array) array[0] end def retrieve_last_element_from_array(array) array[-1] end
true
883d7e929e3ce42444b884dfbb3b32d037a92b49
Ruby
FLWallace105/sports-jacket
/lib/recharge_limit.rb
UTF-8
683
3.3125
3
[]
no_license
#recharge_limit.rb module ReChargeLimits def determine_limits(recharge_header, limit) puts "recharge_header = #{recharge_header}" puts "sleeping 1 second" sleep 1 my_numbers = recharge_header.split("/") my_numerator = my_numbers[0].to_f my_denominator = my_numbers[1].to_f my_limits = (my_numerator/ my_denominator) puts "We are using #{my_limits} % of our API calls" if my_limits > limit puts "Sleeping 10 seconds" sleep 10 else puts "not sleeping at all" end end end
true
1b24e067c1a9c6c4e1163eb3bf3370e39e97e1ec
Ruby
darrenmwong/Study_Hall
/ClassNoteArray.rb
UTF-8
220
2.546875
3
[]
no_license
Class Notes #looping array then putting it in reverse arr[1,2,3,4,5] count = 0 len = arr.size while count < len arr.push arr.shift count += 1 end Git and Github #manage a file or project over the set of time
true
cd23daafca62a0f75d150b15babd7cde08edda31
Ruby
lhorlacher/manchester_coding_game
/scaffolds/simple.rb
UTF-8
1,781
4.1875
4
[]
no_license
# "Simple" challenge. Each "pulse" from the source is represented by a single # "1" or "0". A pair of pulses is called a "frame", and will represent a binary # "bit". # # If the frame is "01", then the bit is a "0". # If the frame is "10", then the bit it a "1". # # You should never receive a frame that is "00" or "11"; if you see one of those # then you probably have a timing problem somewhere. # # Read 8 bit and join them together to get one binary "byte". # # The first byte you read will be the "payload size" and will need to be # converted in to an integer. This number tells you how many remaining bytes are # left in the source stream. # # Once you have read the payload size, keep reading one byte from the source and # convert it in a character (not an integer). Keep doing this until you have # read the number of bytes indicated by payload size. # # Then, stop reading the source and combine all your characters in to a string. # Check if this new string is the correctly decoded data by calling the # `#payload_correct?` method. If that returns true then it is correct. require_relative '../manchester' @source = Manchester::Simple.new @payload = '' def get_pulse @source.read_signal.to_s end def make_frame frame = '' 2.times do frame << get_pulse end frame end def frame_to_binary if make_frame == '01' '0' else '1' end end def make_byte byte = '' 8.times do byte << frame_to_binary end byte end def payload_size make_byte.to_i(2) end def byte_to_char make_byte.to_i(2).chr end def decode_message payload_size.times do @payload << byte_to_char end end decode_message puts "Decoded payload is #{@payload.inspect}." if @source.payload_correct?(@payload) puts "Payload is correct!" else puts "Payload is not correct." end
true
67ffca8eaf4823d3ae37d5801681294fd0b88567
Ruby
Granit/smartset
/app/models/currency.rb
UTF-8
776
2.609375
3
[]
no_license
class Currency < ActiveRecord::Base #has_and_belongs_to_many :countries has_many :monetizations, :dependent => :destroy has_many :countries, :through => :monetizations def initialize(keys={}) super self.collected ||= false end def self.by_name(name) #find(:all, :conditions => ["name = ?", name.to_s]) where(:name => name.to_s) end def self.by_currencycode(code) #find(:all, :conditions => ["name = ?", name.to_s]) where(:currencycode => code.to_s) end def self.by_visited(v) self.all.select {|currency| currency.monetizations[0].visited == v} end def self.by_visited_and_name(v, name) self.where(:name => name).select {|currency| currency.monetizations[0].visited == v} end def self.collected?(v) where(:collected => v) end end
true
9849c52b339d9928d744e646e344b758cc3e8f2a
Ruby
marcus02219/padrino
/lib/dreamwalk_padrino_api/api_request.rb
UTF-8
2,338
2.71875
3
[ "MIT" ]
permissive
class ApiRequest < Sequel::Model unrestrict_primary_key plugin(:timestamps, update_on_create: true) plugin(:paranoid) many_to_one :api_user_token # # Verifies if an API request is valid based on its HTTP_AUTHORIZATION header. # # @param auth_header = nil [String] HTTP_AUTHORIZATION header to check # @param secret = nil [String] application secret used to hash the signature # @param api_user_token = nil [ApiUserToken] if the request is being made on behalf of a user # @return [Boolean] indicating if the request is valid or not # def self.authorised?(auth_header = nil, secret = nil, api_user_token = nil) # check parameters return false if auth_header.blank? return false if secret.blank? # check the structure of the HTTP_AUTHORIZATION header return false unless auth_header.start_with?("DREAMWALK-TOKEN-V1") auth_hash = extract_hash_from_authorization_header(auth_header) return false if auth_hash["nonce"].blank? return false if auth_hash["signature"].blank? # check the HMAC SHA256 signature hash return false unless OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), secret, auth_hash["nonce"]) == auth_hash["signature"] # check if the nonce already exists in the database return false unless self.where(id: auth_hash["nonce"]).count == 0 # if an api_user_token was passed, check if it's a valid object before saving if api_user_token.present? return false if api_user_token.new? or api_user_token.deleted_at.present? end # try to save the request return false unless create(id: auth_hash["nonce"], api_user_token: api_user_token) # if we made it this far, return true true end # # Private class method used to extract a hash of authorisation parameters from a # request's HTTP_AUTHORIZATION header string. # # @param authorization_header [String] the HTTP_AUTHORIZATION string # @return [Hash] extracted authorisation parameters # def self.extract_hash_from_authorization_header(authorization_header) hash = {} authorization_header.gsub(/DREAMWALK-TOKEN-V1/, "").gsub(/, ?/, " ").split(" ").each do |item| parts = item.split("=") hash[parts[0]] = parts[1].gsub!(/"/,"") end hash end private_class_method :extract_hash_from_authorization_header end
true
7670afef65bc67d8e16ee4fe01c3f1da1f63a169
Ruby
nabhanelrahman/dotfiles
/.bin/download-archiver
UTF-8
1,916
3.109375
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
#!/usr/bin/env ruby require 'fileutils' require 'digest/md5' class DownloadArchiver attr_reader :files attr_reader :md5_to_files def initialize(dir) @base_dir = dir _scan_for_files _hash_files end def remove_duplicates @md5_to_files.each_value do |v| if v.size > 1 for i in 1..v.size - 1 @removed_files ||= Array.new @removed_files << v[i] FileUtils.rm v[i] end end end puts "#{@removed_files.size} has been removed" if @removed_files && @removed_files.size > 0 @md5_to_files.clear # Re-scan the folder _scan_for_files end def archive _archive_files_by_date end private def _scan_for_files @files = Array.new @md5_to_files = Hash.new Dir.glob(@base_dir + File::Separator + '*').each do |f| if !File.directory? f @files << f end end end def _hash_files @files.each do |f| digest = Digest::MD5.hexdigest(File.read f) @md5_to_files[digest] ||= Array.new @md5_to_files[digest] << f end end def _archive_files_by_date # Register today's date today = Time.new() @files.each do |f| fh = File.new(f) if !File.directory?(f) && (fh.mtime.year != today.year || fh.mtime.month != today.month) f_year_path = @base_dir + File::Separator + fh.mtime.year.to_s f_month_path = f_year_path + File::Separator + fh.mtime.month.to_s FileUtils.mkdir f_year_path if !File::exists?(f_year_path) || !File.directory?(f_year_path) FileUtils.mkdir f_month_path if !File::exists?(f_month_path) || !File.directory?(f_month_path) FileUtils.mv(f, f_month_path + File::Separator + File.basename(f)) end end end end # Register the base downloads path downloads_path = ENV['HOME'] + '/Downloads' da = DownloadArchiver.new(downloads_path) da.remove_duplicates da.archive
true
89053eef38de6259ad6c28881bcaf6e20de7db06
Ruby
sugyan/aoj
/volume-21/2131/2131.rb
UTF-8
272
3.03125
3
[]
no_license
def calc(d) loop.with_index do |_, i| next if i == 0 n = (i * Math::PI).to_i n += 1 if Math::PI > (n + 0.5) / i if (Math::PI - 1.0 * n / i).abs < d return "#{n}/#{i}" end end end loop do d = gets.to_f break if d == 0.0 puts calc(d) end
true
a1b90a100043322fed09f955f5b0eb0d8eb4679e
Ruby
Ayat-allahBouramdane/EnergyDataSimulationChallenge
/challenge3/webapp/toshihiro_yokota/app/services/city_chart_service.rb
UTF-8
377
2.75
3
[]
no_license
class CityChartService private_class_method :new def self.call(cities) new.call(cities) end def call(cities) cities.select(:id, :name).map do |city| { name: city.name, data: city.energies .group(:year, :month) .order(:year, :month) .sum(:energy_production) } end end end
true
ad0707a958cf777311895eaa715dcca6801447e1
Ruby
gogolqx/nand2tetris-3
/projects/08/vm_translator/lib/vm/instruction/function.rb
UTF-8
712
2.59375
3
[ "MIT" ]
permissive
module VM module Instruction class Function attr_reader :name, :arity, :context def initialize(line, context) @context = context _, @name, arity = line.split @arity = arity.to_i end def commented_assemblies ["// function #{name} #{arity}"] + to_assemblies end def to_assemblies label_assemblies + initialize_local_variables_assemblies end private def label_assemblies %W( (#{name}) ) end def initialize_local_variables_assemblies 1.upto(arity).map do |idx| PushConstant.new("0", context).to_assemblies end.flatten end end end end
true
bfa1998e2a3e44e402d9a6f00a22b14521b349d9
Ruby
dacmanj/financials
/app/models/account.rb
UTF-8
643
2.5625
3
[]
no_license
# == Schema Information # # Table name: accounts # # id :integer not null, primary key # name :string(255) # created_at :datetime not null # updated_at :datetime not null # section_id :integer # side :integer # class Account < ActiveRecord::Base attr_accessible :name, :section_id, :side_name, :side belongs_to :section; before_save { if self.side == 0 self.side = self.section.side; end } def section_name self.section.name end def side_name sideText = ['Debit', 'Invalid', 'Credit'] sideText[self.side.nil? ? 0 : self.side+1 ] end end
true
86c45dbeb7fc0d90092d4253e671e7215334a2ec
Ruby
afurmanov/tagged_logger
/examples/one_tag_per_classes.rb
UTF-8
671
2.796875
3
[ "MIT" ]
permissive
require File.join(File.dirname(__FILE__), '/examples_helper') puts "\n<<<#{File.basename(__FILE__, ".rb")}>>> \n".upcase class LogFoo def foo logger.info("#{self.class}#foo") end end Ftp = Class.new LogFoo Http = Class.new LogFoo Sockets = Class.new LogFoo TaggedLogger.rules do format { |level, tag, message| "#{tag}: #{message}\n"} puts "- Only logging from within classes Ftp, Http and Sockets will be shown in output (no LogFoo)" puts " tag is also printed and it is 'Network' after renaming took place:" rename [Ftp, Http, Sockets] => :Network info :Network, :to => Logger.new(STDOUT) end [Ftp, Http, Sockets, LogFoo].each { |c| c.new.foo }
true
0afe491df820ff554b9160981165209ac20aabdf
Ruby
raluka/ruby_colearning_warmup
/warmup-004/warmup-004.rb
UTF-8
53
3.078125
3
[]
no_license
def count_words(answer) answer.split(" ").count end
true
53d9f7aa5b3bf4ebaeb47014450982ed65cfe038
Ruby
tylerpporter/date_night
/test/bst_test.rb
UTF-8
3,812
3.359375
3
[]
no_license
require_relative 'test_helper.rb' require './lib/bst.rb' require './lib/node.rb' class BinarySearchTreeTest < Minitest::Test def setup @tree = BinarySearchTree.new end def test_it_exists assert_instance_of BinarySearchTree, @tree end def test_it_creates_a_root_node @tree.insert(89, "Seven") assert_instance_of Node, @tree.root end def test_it_creates_a_tree_of_nodes @tree.insert(61, "Bill & Ted's Excellent Adventure") @tree.insert(16, "Johnny English") @tree.insert(92, "Sharknado 3") @tree.insert(50, "Hannibal Buress: Animal Furnace") assert_equal ({"Johnny English" => 16}), @tree.root.left.movie assert_equal ({"Sharknado 3" => 92}), @tree.root.right.movie end def test_it_can_verify_presence_of_score @tree.insert(61, "Bill & Ted's Excellent Adventure") @tree.insert(16, "Johnny English") @tree.insert(92, "Sharknado 3") @tree.insert(50, "Hannibal Buress: Animal Furnace") assert_equal true, @tree.include?(16) assert_equal false, @tree.include?(45) end def test_it_can_return_the_depth_of_a_given_node @tree.insert(61, "Bill & Ted's Excellent Adventure") @tree.insert(16, "Johnny English") @tree.insert(92, "Sharknado 3") @tree.insert(50, "Hannibal Buress: Animal Furnace") assert_equal 1, @tree.depth_of(92) assert_equal 2, @tree.depth_of(50) assert_nil @tree.depth_of(42) end def test_it_can_return_the_movie_with_max_score @tree.insert(61, "Bill & Ted's Excellent Adventure") @tree.insert(16, "Johnny English") @tree.insert(92, "Sharknado 3") @tree.insert(50, "Hannibal Buress: Animal Furnace") @tree.insert(93, "Seven") assert_equal ({"Seven"=>93}), @tree.max end def test_it_can_return_the_movie_with_min_score @tree.insert(61, "Bill & Ted's Excellent Adventure") @tree.insert(16, "Johnny English") @tree.insert(92, "Sharknado 3") @tree.insert(50, "Hannibal Buress: Animal Furnace") @tree.insert(14, "Cats") assert_equal ({"Cats"=>14}), @tree.min end def test_it_can_sort_nodes_ascending sorted = [{"Johnny English"=>16}, {"Hannibal Buress: Animal Furnace"=>50}, {"Bill & Ted's Excellent Adventure"=>61}, {"Sharknado 3"=>92}] @tree.insert(61, "Bill & Ted's Excellent Adventure") @tree.insert(16, "Johnny English") @tree.insert(92, "Sharknado 3") @tree.insert(50, "Hannibal Buress: Animal Furnace") assert_equal sorted, @tree.sort end def test_it_can_use_file_data_to_add_nodes assert_equal 99, @tree.load('./lib/movies.txt') end def test_it_can_report_health_at_given_depth @tree.insert(98, "Animals United") @tree.insert(58, "Armageddon") @tree.insert(36, "Bill & Ted's Bogus Journey") @tree.insert(93, "Bill & Ted's Excellent Adventure") @tree.insert(86, "Charlie's Angels") @tree.insert(38, "Charlie's Country") @tree.insert(69, "Collateral Damage") assert_equal [[98, 7, 100]], @tree.health(0) assert_equal [[58, 6, 85]], @tree.health(1) assert_equal [[36, 2, 28], [93, 3, 42]], @tree.health(2) end def test_it_can_return_number_of_leaves @tree.insert(98, "Animals United") @tree.insert(58, "Armageddon") @tree.insert(36, "Bill & Ted's Bogus Journey") @tree.insert(93, "Bill & Ted's Excellent Adventure") @tree.insert(86, "Charlie's Angels") @tree.insert(38, "Charlie's Country") @tree.insert(69, "Collateral Damage") assert_equal 2, @tree.leaves end def test_height_of_tree @tree.insert(98, "Animals United") @tree.insert(58, "Armageddon") @tree.insert(36, "Bill & Ted's Bogus Journey") @tree.insert(93, "Bill & Ted's Excellent Adventure") @tree.insert(86, "Charlie's Angels") @tree.insert(38, "Charlie's Country") @tree.insert(69, "Collateral Damage") assert_equal 4, @tree.height end end
true
653e3fed452c90562905aac08150044770a93505
Ruby
pickledyamsman/ruby-music-library-cli-v-000
/lib/music_library_controller.rb
UTF-8
1,776
3.390625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class MusicLibraryController def initialize(path = './db/mp3s') MusicImporter.new(path).import end def call input = "" while input.downcase != "exit" puts "What would you like to do?" input = gets.chomp case input when "list songs" list_songs puts "Would you like to do anything else?" when "list artists" list_artists puts "Would you like to do anything else?" when "list genres" list_genres puts "Would you like to do anything else?" when "play song" play_song puts "Would you like to do anything else?" when "list artist" list_artist_songs puts "Would you like to do anything else?" when "list genre" list_genre_songs puts "Would you like to do anything else?" when "exit" break else puts "This is not a valid input. Try again!" end end end def list_songs Song.all.each_with_index do |song, index| puts "#{index+1}. #{song.artist.name} - #{song.name} - #{song.genre.name}" end end def list_artists Artist.all.each {|artist| puts "#{artist.name}"} end def list_genres Genre.all.each {|genre| puts "#{genre.name}"} end def play_song Song.all.each do |song| puts "Playing #{song.artist.name} - #{song.name} - #{song.genre.name}" end end def list_artist_songs Artist.all.each do |artist| artist.songs.each do |song| puts "#{song.artist.name} - #{song.name} - #{song.genre.name}" end end end def list_genre_songs Genre.all.each do |genre| genre.songs.each do |song| puts "#{song.artist.name} - #{song.name} - #{song.genre.name}" end end end end
true
4b00c3ca38fcb87efae8eccd267577f5d37f0153
Ruby
Jp1200/ruby-enumerables-introduction-to-map-and-reduce-lab-austin-web-012720
/lib/my_code.rb
UTF-8
1,266
3.4375
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# My Code here.... def map_to_negativize(source_array) i = 0 new_array = [] while i < source_array.length do new_array << source_array[i]*(-1) i += 1 end return new_array end def map_to_no_change(source_array) i = 0 new_array = [] while i < source_array.length do new_array << source_array[i] i += 1 end return new_array end def map_to_double(source_array) i = 0 new_array = [] while i < source_array.length do new_array << source_array[i]*(2) i += 1 end return new_array end def map_to_square(source_array) i = 0 new_array = [] while i < source_array.length do new_array << source_array[i]*source_array[i] i += 1 end return new_array end def reduce_to_total(source_array, starting_point = 0) i = 0 total = starting_point while i < source_array.length do total += source_array[i] i += 1 end return total end def reduce_to_all_true(source_array) i = 0 while i < source_array.length do if source_array[i] == false return false end i += 1 end return true end def reduce_to_any_true(source_array) i = 0 while i < source_array.length do if source_array[i] return true end i += 1 end return false end
true
5c02f8ac3794d860b3ded5d467cb9c762cec0e87
Ruby
hulloemily/study_playlist
/models/model.rb
UTF-8
2,970
2.546875
3
[]
no_license
#we want this method to take us to the modified subject page based on the original subject chosen def choose_subject(choice) page = {} case choice when "History" page[:picture] = "http://history.appstate.edu/sites/history.appstate.edu/files/images/Map2.jpg" page[:description] = "Helpin' out your history work." page[:title] = "History" page[:playlist] = '<iframe src="http://8tracks.com/mixes/5900222/player_v3_universal" width="300" height="250" style="border: 0px none;"></iframe> <p class="_8t_embed_p" style="font-size: 11px; line-height: 12px;"><a href="http://8tracks.com/hulloemily/afternoon-sunlight?utm_medium=trax_embed">Afternoon Sunlight</a> from <a href="http://8tracks.com/hulloemily?utm_medium=trax_embed">hulloemily</a> on <a href="http://8tracks.com?utm_medium=trax_embed">8tracks Radio</a>.</p>' return page when "Math" page[:picture] = "http://i.livescience.com/images/i/000/055/367/iFF/mathematics.jpg?1375288368" page[:description] = "Making you a maverick in your math class." page[:title] = "Math" page[:playlist] = '<iframe src="http://8tracks.com/mixes/6212984/player_v3_universal" width="300" height="250" style="border: 0px none;"></iframe> <p class="_8t_embed_p" style="font-size: 11px; line-height: 12px;"><a href="http://8tracks.com/akahavya/for-mathematics?utm_medium=trax_embed">For Mathematics</a> from <a href="http://8tracks.com/akahavya?utm_medium=trax_embed">akahavya</a> on <a href="http://8tracks.com?utm_medium=trax_embed">8tracks Radio</a>.</p>' return page when "English" page[:picture] = "http://www.newsgram.com/wp-content/uploads/2015/06/13-tips-words-cloud1-1.jpg" page[:description] = "Enriching your English experience." page[:title] = "English" page[:playlist] = '<iframe src="http://8tracks.com/mixes/5205003/player_v3_universal" width="300" height="250" style="border: 0px none;"></iframe> <p class="_8t_embed_p" style="font-size: 11px; line-height: 12px;"><a href="http://8tracks.com/courfeycute/life-is-a-song?utm_medium=trax_embed">life is a song</a> from <a href="http://8tracks.com/courfeycute?utm_medium=trax_embed">courfeycute</a> on <a href="http://8tracks.com?utm_medium=trax_embed">8tracks Radio</a>.</p>' return page when "Science" page[:picture] = "https://pbs.twimg.com/profile_images/510984202343297024/5zFWeSu7.png" page[:description] = "Sickening your science studiousness." page[:title] = "Science" page[:playlist] = '<iframe src="http://8tracks.com/mixes/4599250/player_v3_universal" width="300" height="250" style="border: 0px none;"></iframe> <p class="_8t_embed_p" style="font-size: 11px; line-height: 12px;"><a href="http://8tracks.com/zainabsohanky/come-dance-with-me?utm_medium=trax_embed">Come Dance With Me</a> from <a href="http://8tracks.com/zainabsohanky?utm_medium=trax_embed">zainabsohanky</a> on <a href="http://8tracks.com?utm_medium=trax_embed">8tracks Radio</a>.</p>' return page end end
true
81afc06cd629c5b9634b987600a2649b702d89a9
Ruby
mattmalane/ruby_small_problems
/easy_9/grade_book.rb
UTF-8
313
3.453125
3
[]
no_license
def get_grade(num1, num2, num3) average = (num1 + num2 + num3) / 3 case average when 90..100 then 'A' when 80..89 then 'B' when 70..79 then 'C' when 60..69 then 'D' when 0..59 then 'F' else "A+" end end get_grade(95, 90, 93) == "A" get_grade(50, 50, 95) == "D" get_grade(100, 100, 104) == "A+"
true
a75b3f3ae271e702fa379996081aa833e271e444
Ruby
krpk1900/AtCoder
/ABC/ABC180/ABC180_B.rb
UTF-8
509
3.671875
4
[]
no_license
N = gets.chomp.to_i xs = gets.chomp.split.map(&:to_i) def calc_manhattan_distance(xs) manhattan_distance = 0 xs.each do |x| manhattan_distance += x.abs end return manhattan_distance end def calc_euclidean_distance(xs) sum_square = 0 xs.each do |x| sum_square += x**2 end return Math.sqrt(sum_square) end def calc_chebyshev_distance(xs) xs.map(&:abs).max end puts calc_manhattan_distance xs puts calc_euclidean_distance xs puts calc_chebyshev_distance xs
true
71d3fe3dd2b1ba674e074992ccf7f3ed1db46e03
Ruby
tjhubert/phone_rails
/app/models/user.rb
UTF-8
1,744
2.53125
3
[]
no_license
class User < ActiveRecord::Base include VerifyPhoneNumberHelper # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable validates :phone_number, uniqueness: true before_save :set_phone_attributes, if: :phone_verification_needed? after_save :send_sms_for_phone_verification, if: :phone_verification_needed? def verify_phone_verification_code_with_code_entered(code_entered) verify_phone(code_entered) end def generate_new_code_and_send_sms self.set_phone_attributes if self.save! send_sms_for_phone_verification end end def phone_verification_needed? phone_number.present? && !phone_number_verified end def set_phone_attributes self.phone_number_verified = false self.phone_verification_code = generate_phone_verification_code # removes all white spaces, hyphens, and parenthesis self.phone_number.gsub!(/[\s\-\(\)]+/, '') end private # increase protection def verify_phone(code_entered) if self.phone_verification_code == code_entered mark_phone_as_verified! end end def mark_phone_as_verified! update!(phone_number_verified: true, phone_verification_code: nil, phone_verification_code_sent_at: nil, phone_verified_at: DateTime.now) end def send_sms_for_phone_verification send_verification_code_to(self) end def generate_phone_verification_code # begin verification_code = SecureRandom.hex(3) # end while self.class.exists?(phone_verification_code: verification_code) verification_code end end
true
6b786c5b05a0fcfbf0534dadf65e6d7d7c64e3a8
Ruby
boudejo/lookatrails
/config/initializers/config.rb
UTF-8
8,293
2.609375
3
[]
no_license
# ------------------------------------------------------------------------------------------------------------------------------ # EXTENSIONS # ------------------------------------------------------------------------------------------------------------------------------ # Extends ActiveRecord with: # - default named scopes: http://www.pathf.com/blogs/2008/06/more-named-scope-awesomeness/ # - concerned_with functionality: http://paulbarry.com/articles/2008/08/30/concerned-with-skinny-controller-skinny-model # - forwardable extension: http://blog.jayfields.com/2007/02/ruby-forwardable-addition.html class << ActiveRecord::Base def concerned_with(*concerns) concerns.each do |concern| require_dependency "#{name.underscore}/#{concern}" end end end class ActiveRecord::Base def dom_path(sep = '_') self.class.to_s.downcase + sep + self.id.to_s end def extract_options_from_args!(args) if args.last.is_a?(Hash) then args.pop else {} end end def saved? !new_record? end def change_asset_folder(from, to) if self.respond_to?(:asset_folder) && self.respond_to?(:asset_folder_name) then if from != to then asset_folder_path = RAILS_ROOT+"/public/assets/#{self.class.to_s.pluralize.downcase}/" asset_folder_path_to = asset_folder_path+self.asset_folder_name(to)+"/" asset_folder_path_was = asset_folder_path+self.asset_folder_name(from)+"/" if !File.exists?(asset_folder_path_to) then if File.exists?(asset_folder_path_was) then File.rename(asset_folder_path_was, asset_folder_path_to) else FileUtils.mkdir_p(asset_folder_path_to) end end end end end def set_status(status, previous = nil, date = false) self.status = status self.prev_status = previous if !previous.nil? self.status_change_at = Time.now if date end def revert_status(status) self.set_status(status, status) end end # This wil be a new feature in rails 2.2 class Module def delegate(*methods) options = methods.pop unless options.is_a?(Hash) && to = options[:to] raise ArgumentError, "Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, :to => :greeter)." end prefix = options[:prefix] || '' orig_prefix = prefix if prefix != true and !prefix.empty? prefix += '_' end methods.each do |method| call_method = method if options.has_key? :method then method = options[:method] end if options.has_key? :default code = "(#{to} && #{to}.__send__(#{method.inspect}, *args, &block)) || #{options[:default].inspect}" else code = "#{to}.__send__(#{method.inspect}, *args, &block)" end prefix = to.to_s + '_' if orig_prefix == true module_eval(<<-EOS, "(__DELEGATION__)", 1) def #{prefix}#{call_method}(*args, &block) return nil unless #{to} #{code} end EOS end end end module Enumerable def otherwise empty? ? yield : self end end class Array def invert res=[] each do |e,i| res.push([i, e]) end res end def keys res=[] each do |e,i| res.push(e) end res end def values res=[] each do |e,i| res.push(i) end res end def symbolize; map { |e| e.to_sym }; end def stringify; map { |e| e.to_s }; end end class String #:nodoc: def actionize self.downcase.gsub(' ', '_') end def parameterize(sep = '_') self.gsub(/[^a-z0-9]+/i, sep) end def permalinkize t = Iconv.new("ASCII//TRANSLIT", "utf-8").iconv(self) t = t.downcase.strip.gsub(/[^-_\s[:alnum:]]/, '').squeeze(' ').tr(' ', '-') (t.blank?) ? '-' : t end end class Float alias_method :orig_to_s, :to_s def to_s(arg = nil) if arg.nil? orig_to_s else sprintf("%.#{arg}f", self) end end end # ------------------------------------------------------------------------------------------------------------------------------ # DATE CONFIGURATION # ------------------------------------------------------------------------------------------------------------------------------ # Date and time format date_formats = { :default => '%d/%m/%Y', :date_with_day => '%a %d/%m/%Y' } ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(date_formats) ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(:default => '%d/%m/%Y %H:%M') # Date and time validation ValidatesTimeliness::Formats.remove_us_formats # Apply patch for date and date input require 'dateformat_patch' # ------------------------------------------------------------------------------------------------------------------------------ # ASSETS CONFIGURATION # ------------------------------------------------------------------------------------------------------------------------------ default_scripts = [ 'lib/jquery/jquery-1.2.6', 'lib/jquery/plugins/utils/jquery.uuid', 'lib/jquery/plugins/utils/jquery.domec', 'lib/jquery/plugins/utils/jquery.clock', 'lib/jquery/plugins/utils/jquery.livequery', 'lib/jquery/plugins/utils/jquery.jqmodal', 'lib/jquery/plugins/utils/jquery.form', 'lib/jquery/plugins/utils/jquery.countdown', #'lib/jquery/plugins/ajax/jquery.ajaxManager', 'lib/jquery/plugins/ajax/jquery.blockUI', 'lib/jquery/plugins/ajax/jquery.using', #'lib/jquery/plugins/utils/jquery.metadata.min', 'lib/jquery/plugins/ajax/jquery.history.fixed', #'lib/jquery/plugins/ajax/jquery.ajaxify', 'lib/inflection', 'lib/dateformat' ] dev_scripts = [ 'lib/jquery/plugins/debug/jquery.dump' ] default_scripts = default_scripts | dev_scripts if RAILS_ENV == 'development' ActionView::Helpers::AssetTagHelper.register_javascript_expansion :default_scripts => default_scripts ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion :default_styles => [] # ------------------------------------------------------------------------------------------------------------------------------ # MAIL CONFIGURATION # ------------------------------------------------------------------------------------------------------------------------------ class ActionMailer::Base def app_setup_mail @from = "#{APP.setting('mail.sender.name')} <#{APP.setting('mail.sender.address')}>" headers "Reply-to" => APP.setting('mail.sender.address') @subject = APP.setting('mail.subject_prefix')+' ' @sent_on = Time.now @body[:sent_on] = Time.now @body[:debug_info] = '' end def debug_mail @body[:debug_info] = %{ DEBUG INFO: * receivers: #{@recipients} } @recipients = "#{APP.setting('debug.mail.name')} <#{APP.setting('debug.mail.address')}>" end end # ------------------------------------------------------------------------------------------------------------------------------------- # SASS PLUGIN CONFIGURATION # ------------------------------------------------------------------------------------------------------------------------------------- Sass::Plugin.options = { :template_location => RAILS_ROOT + "/public/sass/styles", :load_paths => [RAILS_ROOT + "/public/sass/import", RAILS_ROOT + "/public/sass/import/plugins"], :style => (RAILS_ENV == 'development') ? :expanded : :compressed } # ------------------------------------------------------------------------------------------------------------------------------------- # DEFAULTS # ------------------------------------------------------------------------------------------------------------------------------------- DEFAULT_COUNTRIES = APP.setting('data.countries.default') ActionView::Base.field_error_proc = Proc.new do |html_tag, instance| msg = instance.error_message error_style = "background-color: #f2afaf" if html_tag =~ /<(input|textarea|select)[^>]+style=/ style_attribute = html_tag =~ /style=['"]/ html_tag.insert(style_attribute + 7, "#{error_style}; ") elsif html_tag =~ /<(input|textarea|select)/ first_whitespace = html_tag =~ /\s/ html_tag[first_whitespace] = " style='#{error_style}' " end html_tag end
true
00aabeed4c8b05fddcc4ca634df772342fe4ea12
Ruby
tadd/steep
/smoke/block/d.rb
UTF-8
526
3.078125
3
[ "MIT" ]
permissive
# @type var a: ^(Integer) -> String a = -> (x) { x.to_s } # @type var b: Array[Float] # !expects IncompatibleAssignment: lhs_type=::Array[::Float], rhs_type=::Array[::String] b = [1,2,3].map(&a) # !expects IncompatibleAssignment: lhs_type=::Array[::Float], rhs_type=::Array[::String] b = [1,2,3].map(&:to_s) # !expects* UnresolvedOverloading: receiver=::Array[::Integer], method_name=map, [1,2,3].map(&:no_such_method) # !expects* UnresolvedOverloading: receiver=::Array[::Integer], method_name=map, [1,2,3].map(&:divmod)
true
0f2801ba6c3fc80872db08b52aa098be82d06565
Ruby
patslat/Checkers
/checkers.rb
UTF-8
1,637
3.4375
3
[]
no_license
require 'colorize' require 'yaml' require './HumanPlayer.rb' require './Board.rb' require './Piece.rb' class InvalidMoveError < StandardError end class Checkers def initialize @board = Board.new @players = { :black => HumanPlayer.new(:black), :red => HumanPlayer.new(:red) } @turn = :black end def play until game_over? @board.display prompt_choose_piece piece_loc = @players[@turn].get_coord next if not valid_piece_choice?(piece_loc) piece = @board.get_piece(piece_loc) prompt_move_sequence move_sequence = @players[@turn].get_coords next if not piece.valid_move_sequence?(move_sequence) piece.perform_moves!(move_sequence) piece.promote if piece.row == 0 || piece.row == 7 swap_turns end swap_turns announce_winner end private def valid_piece_choice?(coord) if (piece = @board.get_piece(coord)).nil? || !@board.valid_coord?(coord) false else piece.color == @turn end end def announce_winner "#{@turn.to_s.capitalize} wins!" end def game_over? @board.get_pieces(@turn).none? do |piece| piece.has_valid_moves? end end def swap_turns @turn = @turn == :black ? :red : :black end def prompt_choose_piece puts "#{@turn.to_s.capitalize}, please enter the coordinates of the piece you would like to move: " end def prompt_move_sequence puts "Please enter the coordinates of the location(s) you would like to move the piece to: " end end if __FILE__ == $PROGRAM_NAME c = Checkers.new c.play end
true
2285ef69f589e7a9ade741755b6fafe0f5032f3d
Ruby
blake-enyart/battleship_explosion
/test/cell_test.rb
UTF-8
2,354
3.171875
3
[]
no_license
require './lib/ship' require './lib/cell' require 'minitest/autorun' require 'minitest/pride' require 'pry' class CellTest < Minitest::Test def setup @cell = Cell.new("B4") @nina = Ship.new("Cruiser", 3) @cell_1 = Cell.new("B1") @cell_2 = Cell.new("C3") end def test_cell_exist assert_instance_of Cell, @cell end def test_empty_method_detects_ship_not_present assert_nil @cell.ship assert_equal true, @cell.empty? end def test_place_ship_fills_ship_attr_and_changes_empty_status @cell.place_ship(@nina) assert_equal false, @cell.empty? assert_equal @nina, @cell.ship end def test_fired_upon_recognizes_status_with_input @cell.place_ship(@nina) assert_equal false, @cell.fired_upon? assert_equal 3, @cell.ship.health @cell.fire_upon assert_equal 2, @cell.ship.health assert_equal true, @cell.fired_upon? end def test_render_period_if_ship_not_fired_upon @cell_2.place_ship(@nina) assert_instance_of Ship, @cell_2.ship assert_equal false, @cell_2.fired_upon? assert_equal ".", @cell_2.render end def test_render_period_if_empty_cell_not_fired_upon assert_nil @cell_1.ship assert_equal false, @cell_1.fired_upon? assert_equal ".", @cell_1.render end def test_render_shows_miss_when_firing_on_empty_cell assert_nil @cell.ship assert_equal ".", @cell.render assert_equal ".", @cell.render(true) @cell.fire_upon assert_equal "M", @cell.render end def test_render_hits_cell_with_ship @cell_2.place_ship(@nina) assert_equal 3, @cell_2.ship.health assert_equal false, @cell_2.fired_upon? assert_equal Ship, @cell_2.ship.class assert_equal "S", @cell_2.render(true) @cell_2.fire_upon assert_equal true, @cell_2.fired_upon? assert_equal 2, @cell_2.ship.health assert_equal "H", @cell_2.render end def test_render_sinks_ship @cell_2.place_ship(@nina) assert_equal "S", @cell_2.render(true) @cell_2.fire_upon assert_equal "H", @cell_2.render assert_equal 2, @cell_2.ship.health @cell_2.fire_upon assert_equal "H", @cell_2.render assert_equal 1, @cell_2.ship.health @cell_2.fire_upon assert_equal "X", @cell_2.render assert_equal 0, @cell_2.ship.health assert_equal true, @cell_2.ship.sunk? end end
true
474c75f9bf6c7c522bc4c306d694280073d79a6c
Ruby
mattlqx/pre-commit-search-and-replace
/lib/search-and-replace.rb
UTF-8
3,760
3.03125
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'tempfile' # A set of files represented as a collection that can each be parsed for a search string or regexp and optionally, # atomically move a string-replaced version of the file in place. class SearchAndReplace attr_reader :search attr_reader :replacement def initialize(files, search, search_opts: nil, replacement: nil) @files = files @search = pattern(search, options: search_opts) @replacement = replacement @tempfiles = [] end def self.from_config(files, config) opts = ((config['insensitive'] && Regexp::IGNORECASE) || 0) | ((config['extended'] && Regexp::EXTENDED) || 0) new(files, config['search'], search_opts: opts, replacement: config['replacement']) end # Determines if string is regexp and converts to object if so def pattern(string, options: nil) !%r{^/.*/$}.match(string).nil? ? Regexp.new(string[1..-2], options) : string end def parse_files @files.map { |f| parse_file(f) } end # Searches a file for pattern and returns occurrence objects for each and the path to the tempfile if # replacement is specified def parse_file(filename) # rubocop:disable Metrics/AbcSize all_occurrences = [] file = IO.open(IO.sysopen(filename, 'r')) tempfile = Tempfile.new('pre-commit-search') unless @replacement.nil? until file.eof? line = file.gets occurrences = search_line(filename, file.lineno, line) all_occurrences += occurrences tempfile&.write(occurrences.empty? ? line : line.gsub(@search, @replacement)) end unless tempfile.nil? tempfile.close @tempfiles << tempfile # Hold on to a reference so it's not garbage collected yet end file.close FileMatches.new(self, filename, all_occurrences, tempfile&.path) end # Searches a line for pattern and writes string replaced line to newfile if specified def search_line(filename, lineno, line) occurrences = [] offset = 0 match = false until match.nil? match = line.index(@search, offset) offset = match + 2 if match.is_a?(Integer) # Don't log a match if there isn't one or if the replacement on a regex would yield no change next if !match.is_a?(Integer) || (!@replacement.nil? && line.gsub(@search, @replacement) == line) occurrences << Occurrence.new(filename, lineno, match + 1, line) end occurrences end # A collection of occurrences in a file class FileMatches attr_reader :filename attr_reader :search attr_accessor :occurrences attr_accessor :replacement_file_path def initialize(sar, filename, occurrences = [], replacement_file_path = nil) @occurrences = occurrences @replacement_file_path = replacement_file_path @search = sar @filename = filename end # :nocov: def to_s "file: #{filename}, search: '#{search.search}', replacement: '#{search.replacement || 'nil'}', " \ "count: #{occurences.length}" end def method_missing(method, *args) if @occurrences.respond_to?(method) @occurrences.send(method, *args) else super end end def respond_to_missing?(method, *_args) @occurrences.respond_to?(method) || respond_to?(method) end # :nocov: end # Object for recording position of a search hit class Occurrence attr_accessor :file attr_accessor :lineno attr_accessor :col attr_accessor :context def initialize(file, lineno, col, context) @file = file @lineno = lineno @col = col @context = context end def to_s "#{file}, line #{lineno}, col #{col}:\n" \ " #{context.tr("\t", ' ').chomp}\n" \ " #{' ' * (col - 1)}^" end end end
true
7841d1269c89aaf107ee3ab8784810ce7a3570ec
Ruby
brycemooore/duckat
/app/models/user.rb
UTF-8
1,540
2.71875
3
[]
no_license
class User < ApplicationRecord has_many :items, foreign_key: 'seller_id', class_name: 'Item' has_many :bids, foreign_key: 'user_id' has_many :bidded_items, through: :bids, source: :item has_many :comments has_many :comment_items, through: :comments, source: :item # before_create :default_values before_save :round_balance validates :username, uniqueness: true, presence: true has_secure_password def winning_items items = self.bidded_items items.select do |item| item.auction_winner == self end end def add_item(name, desc, price, date, image) Item.create(seller_id: self.id, name: name, description: desc, asking_price: price, end_date: date, image: image) end def make_bid(item, amount) Bid.create(user_id: self.id, item_id: item.id, bid_amount: amount) end def sorted_bids_asc self.bids.sort { |b| b.bid_amount } end def my_highest_bid self.sorted_bids_asc[-1] end def total_bid self.sorted_bids_asc.map do |bid| bid.bid_amount end.reduce(:+) end def items_sorted_by_price self.items.sort_by { |item| item.asking_price }.reverse end def most_bids_on_item self.items.sort_by do |item| item.bids.count end[-1] end private def default_values self.balance = 0.00 end def round_balance self.balance = self.balance.round(2) end end
true
33f5795c558d4bd5d9dcc8aae00716a85cbc653a
Ruby
pghalliday/yard-cucumber
/lib/cucumber/city_builder.rb
UTF-8
13,036
2.96875
3
[ "MIT" ]
permissive
module Cucumber module Parser class CityBuilder include Gherkin::Rubify # # The Gherkin Parser is going to call the various methods within this # class as it finds items. This is similar to how Cucumber generates # it's Abstract Syntax Tree (AST). Here instead this generates the # various YARD::CodeObjects defined within this template. # # A namespace is specified and that is the place in the YARD namespacing # where all cucumber features generated will reside. The namespace specified # is the root namespaces. # # @param [String] file the name of the file which the content belongs # def initialize(file) @namespace = YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE find_or_create_namespace(file) @file = file end # Return the feature that has been defined. This method is the final # method that is called when all the work is done. It is called by # the feature parser to return the complete Feature object that was created # # @return [YARD::CodeObject::Cucumber::Feature] the completed feature # # @see YARD::Parser::Cucumber::FeatureParser def ast @feature end # # Feature that are found in sub-directories are considered, in the way # that I chose to implement it, in another namespace. This is because # when you execute a cucumber test run on a directory any sub-directories # of features will be executed with that directory so the file is split # and then namespaces are generated if they have not already have been. # # The other duty that this does is look for a README.md file within the # specified directory of the file and loads it as the description for the # namespace. This is useful if you want to give a particular directory # some flavor or text to describe what is going on. # def find_or_create_namespace(file) @namespace = YARD::CodeObjects::Cucumber::CUCUMBER_NAMESPACE File.dirname(file).split('/').each do |directory| @namespace = @namespace.children.find {|child| child.is_a?(YARD::CodeObjects::Cucumber::FeatureDirectory) && child.name.to_s == directory } || @namespace = YARD::CodeObjects::Cucumber::FeatureDirectory.new(@namespace,directory) {|dir| dir.add_file(directory)} end if @namespace.description == "" && File.exists?("#{File.dirname(file)}/README.md") @namespace.description = File.read("#{File.dirname(file)}/README.md") end end # # Find the tag if it exists within the YARD Registry, if it doesn' t then # create it. # # We note that the tag was used in this file at the current line. # # Then we add the tag to the current scenario or feature. We also add the # feature or scenario to the tag. # # @param [String] tag_name the name of the tag # @param [parent] parent the scenario or feature that is going to adopt # this tag. # def find_or_create_tag(tag_name,parent) #log.debug "Processing tag #{tag_name}" tag_code_object = YARD::Registry.all(:tag).find {|tag| tag.value == tag_name } || YARD::CodeObjects::Cucumber::Tag.new(YARD::CodeObjects::Cucumber::CUCUMBER_TAG_NAMESPACE,tag_name.gsub('@','')) {|t| t.owners = [] ; t.value = tag_name } tag_code_object.add_file(@file,parent.line) parent.tags << tag_code_object unless parent.tags.find {|tag| tag == tag_code_object } tag_code_object.owners << parent unless tag_code_object.owners.find {|owner| owner == parent} end # # Each feature found will call this method, generating the feature object. # This is once, as the gherking parser does not like multiple feature per # file. # def feature(feature) #log.debug "FEATURE" @feature = YARD::CodeObjects::Cucumber::Feature.new(@namespace,File.basename(@file.gsub('.feature','').gsub('.','_'))) do |f| f.comments = feature.comments.map{|comment| comment.value}.join("\n") f.description = feature.description f.add_file(@file,feature.line) f.keyword = feature.keyword f.value = feature.name f.tags = [] feature.tags.each {|feature_tag| find_or_create_tag(feature_tag.name,f) } end end # # Called when a background has been found # # @see #scenario def background(background) #log.debug "BACKGROUND" @background = YARD::CodeObjects::Cucumber::Scenario.new(@feature,"background") do |b| b.comments = background.comments.map{|comment| comment.value}.join("\n") b.description = background.description b.keyword = background.keyword b.value = background.name b.add_file(@file,background.line) end @feature.background = @background @background.feature = @feature @step_container = @background end # # Called when a scenario has been found # - create a scenario # - assign the scenario to the feature # - assign the feature to the scenario # - find or create tags associated with the scenario # # The scenario is set as the @step_container, which means that any steps # found before another scenario is defined belong to this scenario # # @param [Scenario] statement is a scenario object returned from Gherkin # @see #find_or_create_tag # def scenario(statement) #log.debug "SCENARIO" scenario = YARD::CodeObjects::Cucumber::Scenario.new(@feature,"scenario_#{@feature.scenarios.length + 1}") do |s| s.comments = statement.comments.map{|comment| comment.value}.join("\n") s.description = statement.description s.add_file(@file,statement.line) s.keyword = statement.keyword s.value = statement.name statement.tags.each {|scenario_tag| find_or_create_tag(scenario_tag.name,s) } end scenario.feature = @feature @feature.scenarios << scenario @step_container = scenario end # # Called when a scenario outline is found. Very similar to a scenario, # the ScenarioOutline is still a distinct object as it can contain # multiple different example groups that can contain different values. # # @see #scenario # def scenario_outline(statement) #log.debug "SCENARIO OUTLINE" outline = YARD::CodeObjects::Cucumber::ScenarioOutline.new(@feature,"scenario_#{@feature.scenarios.length + 1}") do |s| s.comments = statement.comments.map{|comment| comment.value}.join("\n") s.description = statement.description s.add_file(@file,statement.line) s.keyword = statement.keyword s.value = statement.name statement.tags.each {|scenario_tag| find_or_create_tag(scenario_tag.name,s) } end outline.feature = @feature @feature.scenarios << outline @step_container = outline end # # Examples for a scenario outline are called here. This section differs # from the Cucumber parser because here each of the examples are exploded # out here as individual scenarios and step definitions. This is so that # later we can ensure that we have all the variations of the scenario # outline defined to be displayed. # def examples(examples) #log.debug "EXAMPLES" example = YARD::CodeObjects::Cucumber::ScenarioOutline::Examples.new(:keyword => examples.keyword, :name => examples.name, :line => examples.line, :comments => examples.comments.map{|comment| comment.value}.join("\n"), :rows => matrix(examples.rows)) # add the example to the step containers list of examples @step_container.examples << example # For each example data row we want to generate a new scenario using our # current scenario as the template. example.data.length.times do |row_index| # Generate a copy of the scenario. scenario = YARD::CodeObjects::Cucumber::Scenario.new(@step_container,"example_#{@step_container.scenarios.length + 1}") do |s| s.comments = @step_container.comments s.description = @step_container.description s.add_file(@file,@step_container.line_number) s.keyword = @step_container.keyword s.value = "#{@step_container.value} (#{@step_container.scenarios.length + 1})" end # Generate a copy of the scenario steps. @step_container.steps.each do |step| step_instance = YARD::CodeObjects::Cucumber::Step.new(scenario,step.line_number) do |s| s.keyword = step.keyword.dup s.value = step.value.dup s.add_file(@file,step.line_number) s.text = step.text.dup if step.has_text? s.table = clone_table(step.table) if step.has_table? end # Look at the particular data for the example row and do a simple # find and replace of the <key> with the associated values. example.values_for_row(row_index).each do |key,text| text ||= "" #handle empty cells in the example table step_instance.value.gsub!("<#{key}>",text) step_instance.text.gsub!("<#{key}>",text) if step_instance.has_text? step_instance.table.each{|row| row.each{|col| col.gsub!("<#{key}>",text)}} if step_instance.has_table? end # Connect these steps that we created to the scenario we created # and then add the steps to the scenario created. step_instance.scenario = scenario scenario.steps << step_instance end # Add the scenario to the list of scenarios maintained by the feature # and add the feature to the scenario scenario.feature = @feature @step_container.scenarios << scenario end end # # Called when a step is found. The step is refered to a table owner, though # not all steps have a table or multliline arguments associated with them. # # If a multiline string is present with the step it is included as the text # of the step. If the step has a table it is added to the step using the # same method used by the Cucumber Gherkin model. # def step(step) #log.debug "STEP" @table_owner = YARD::CodeObjects::Cucumber::Step.new(@step_container,"#{step.line}") do |s| s.keyword = step.keyword s.value = step.name s.add_file(@file,step.line) end @table_owner.comments = step.comments.map{|comment| comment.value}.join("\n") multiline_arg = if step.respond_to?(:multiline_arg) && !step.multiline_arg.nil? rubify(step.multiline_arg) elsif step.respond_to?(:rows) && !step.rows.nil? rubify(step.rows) elsif step.respond_to?(:doc_string) && !step.doc_string.nil? rubify(step.doc_string) end case(multiline_arg) when gherkin_multiline_string_class @table_owner.text = multiline_arg.value when Array #log.info "Matrix: #{matrix(multiline_arg).collect{|row| row.collect{|cell| cell.class } }.flatten.join("\n")}" @table_owner.table = matrix(multiline_arg) end @table_owner.scenario = @step_container @step_container.steps << @table_owner end # Defined in the cucumber version so left here. No events for the end-of-file def eof end # When a syntax error were to occurr. This parser is not interested in errors def syntax_error(state, event, legal_events, line) # raise "SYNTAX ERROR" end private def matrix(gherkin_table) gherkin_table.map {|gherkin_row| gherkin_row.cells } end # # This helper method is used to deteremine what class is the current # Gherkin class. # # @return [Class] the class that is the current supported Gherkin Model # for multiline strings. Prior to Gherkin 2.4.0 this was the PyString # class. As of Gherkin 2.4.0 it is the DocString class. def gherkin_multiline_string_class if defined?(Gherkin::Formatter::Model::PyString) Gherkin::Formatter::Model::PyString elsif defined?(Gherkin::Formatter::Model::DocString) Gherkin::Formatter::Model::DocString else raise "Unable to find a suitable class in the Gherkin Library to parse the multiline step data." end end def clone_table(base) base.map {|row| row.map {|cell| cell.dup }} end end end end
true
931bb68be216dc511547ebd028bdfc97ae6dc965
Ruby
nickrw/rajax
/controller/main.rb
UTF-8
1,659
2.53125
3
[]
no_license
class MainController < Controller def index @title = "Rajax test pad" %{ <p>Rajax is a work-in-progess Ramaze ajax helper, it is ORM agnostic (in fact, you don't even need to be using a database in order to take advantage of it)</p> <p>Rajax can do the following:</p> <hr /> <h3>Edit things in-page</h3> <p>The <strong>click2edit</strong> helper method allows you to make text editable, submitting results, plus additional parameters you specify, to a controller of your choice.</p> <p><strong><a href='/click2edit/'>View examples</a></strong></p> <hr /> <h3>Delete items from a page</h3> <p>The <strong>click2delete_button</strong> method gives you the HTML for a button which, when clicked, deletes an iitem from the page if a success response is given by the ajax controller. Parameters you specify are passed to the ajax controller.</p> <p>The <strong>click2delete_wrapper</strong> method wraps HTML around the item you want to be deletable. This method must contain the output of a click2delete_button for it to be of any use. You specify to this method what sort of tag you would like the wrapper to use, E.G. :tr for a table-row or :div for a block element.</p> <p><strong><a href='/click2delete/'>View examples</a></strong></p> <hr /> <h3>Handle forms submission/response in-page</h3> <p>The <strong>ajaxform</strong> method wraps <form> tags around the given input which stop the form from submitting normally, instead sending the data to the ajax controller.</p> <p><strong><a href='/ajaxform/'>View example</a></strong></p> } end end
true
1b85bdb653f6da9b1321785291c346dffa2dbb68
Ruby
christopherslee/intro_to_dsls
/lib/part_3/monthly_score.rb
UTF-8
832
3.484375
3
[]
no_license
class MonthlyScore attr_reader :paid_balances def initialize(accounts) # keep track of which accounts are paid @paid_balances = {} accounts.each do |account| @paid_balances[account.to_sym] = 0 end end # iterate over all the paid balances and calculate the monthly score def calculate_score score = 0 paid_balances.each_pair do |account, value| score += (value > 0 ? 1 : -2) end score end def pay_bill(account_name, amount) paid_balances[account_name.to_sym] = amount end def process(actions) # TODO part 3 # Convert the actions proc back to a block and use instance eval to # execute it in the context of this object # # Finally, after all the bills have been paid, tally up the score # for the month using calculate_score end end
true
46bf553010cbfbca97b1259d4a20b4459f023e87
Ruby
onfido/tradesman
/lib/tradesman/parser.rb
UTF-8
870
3.0625
3
[ "MIT" ]
permissive
module Tradesman class Parser attr_reader :class_name, :action_string, :subject_string, :parent_string PARSE_REGEX = /(Create|Update|Delete)(.+)/ PARSE_REGEX_WITH_PARENT = /(Create)([A-Z]+.+)For([A-Z]+.+)/ def initialize(class_name) @class_name = class_name @match = class_name.to_s.match(regex) @action_string, @subject_string, @parent_string = @match.values_at(1, 2, 3) if @match end def match? !!@match end def action str_to_sym(@action_string) end def subject str_to_sym(@subject_string) end def parent return nil unless @parent_string str_to_sym(@parent_string) end private def regex /.+For[A-Z]+.+/.match(@class_name) ? PARSE_REGEX_WITH_PARENT : PARSE_REGEX end def str_to_sym(str) str.underscore.symbolize end end end
true
c9636851746b2ee0147b62543d364bafdb7af635
Ruby
tylermcgraw/launchcode_ruby_book
/hashes/exercise_two.rb
UTF-8
136
2.6875
3
[]
no_license
person = { name: "Tyler", age: 23 } place = { state: "California" } p person.merge(place) p person person.merge!(place) p person
true
ba8a6d9416c0a472cf3595e7013a86642a1d7976
Ruby
amckinnell/advent_of_code_2020
/day_11/puzzle_11_1/main.rb
UTF-8
329
2.765625
3
[]
no_license
require_relative "configure_zeitwerk" seating_system = SeatingSystem.new(File.read("../input_11.txt")) rounds = 0 loop do seating_system.next_round break unless seating_system.changed? rounds += 1 raise "Too many rounds" if 100 < rounds end p "#{seating_system.occupied_seats} occupied_seats after #{rounds} rounds"
true
03239c1c5568a00fd5ce88ccb795736f7f0fbacf
Ruby
kenhufford/aA-projects
/W4D2/chess/king.rb
UTF-8
287
3.078125
3
[]
no_license
require_relative "piece.rb" class King < Piece attr_reader :symbol def initialize(color, board, pos) super @symbol = :K end def move_diffs [ [1,1], [1,-1], [-1,1], [-1,-1], [0,1], [0,-1] [1,0], [-1,0], ] end end
true
01baee124745ba56bdc41228c5e1c5a38ec2d021
Ruby
edhowland/viper
/minitest/test_vfs.rb
UTF-8
1,281
2.546875
3
[ "MIT" ]
permissive
# vfs_tests.rb - tests for VFS require_relative 'test_helper' class VFSTest < MiniTest::Test def setup @vm = VirtualMachine.new @vm.mount '/v', env:@vm.ios, frames:@vm.fs @vroot = @vm.fs[:vroot] end def test_normal_open Hal.chdir File.dirname(__FILE__) Hal.open __FILE__, 'r' end def test_virtual_layer Hal.open '/v/xxx', 'w' end def test_open_non_existant_raises_errno assert_raises Errno::ENOENT do Hal.open 'xyzzy', 'r' end end def test_non_existant_long_path assert_raises Errno::ENOENT do Hal.open 'tmp/a/b/c/d/hello', 'r' end end def test_open_vfs_ok Hal.open '/v', 'r' end def test_vfs_non_existant_file_raises assert_raises Errno::ENOENT do Hal.open '/v/xxx', 'r' end end def test_vfs_non_existant_long_path_raises assert_raises Errno::ENOENT do Hal.open '/v/xxx/yyy/zzz/hello', 'r' end end def test_vfs_root_one_level_path_returns_nil assert @vroot['/v/xxxyyyzzz'].nil?, 'Expected VFSRoot to return nil, but it did not' end def test_vroot_returns_nil_given_2_or_more_non_existant_paths #assert @vroot['/v/xxx/ttt'], 'Expected VFSRoot to return nil, but it did not' assert_is @vroot['/v/xxx/yyy/zzz'], NilClass end end
true
7be85354492288b536e60b54c4ad71d6b16f6c2f
Ruby
kjkkuk/ruby_trainee
/HumanJobPet/spec/human_spec.rb
UTF-8
582
2.75
3
[]
no_license
# frozen_string_literal: true require 'rspec' require_relative '../lib/human' RSpec.describe Human do let(:job) { double('job') } let(:pet) { double('pet') } let(:human) { described_class.new(job, pet) } describe '#work' do it 'should work and get salary' do allow(job).to receive(:salary) expect(human.work).to eq("You worked and received a salary: #{job.salary}") end end describe '#feed' do it 'should feed pet' do expect(pet).to receive(:food) { 'meat' } expect(human.feed).to eq('You feed your pet meat') end end end
true
98e36aa008e2b7f9abc6ec16d13b37a0aa28328a
Ruby
jonassode/MyYaml
/MyYaml.rb
UTF-8
947
3.15625
3
[]
no_license
require 'yaml' class MyYamlList # It's a List # Each Entry Is Unique # Sorted Alphabetically Ascending def self.load(file_name) content = [] if File.exist?(file_name+'.yaml') content = YAML::load(File.read(file_name+'.yaml')) end return content end def self.save(object, file_name) File.open( file_name+'.yaml', 'w+' ) do |out| YAML.dump( object, out ) end end def self.add(object, file_name) list = MyYamlList.load(file_name) list << object MyYamlList.save(list.uniq.sort, file_name) end end class MyYamlHash # It's a Hash # Saved exactly as the object def self.load(file_name) content = Hash.new() if File.exist?(file_name+'.yaml') content = YAML::load(File.read(file_name+'.yaml')) end return content end def self.save(object, file_name) File.open( file_name+'.yaml', 'w+' ) do |out| YAML.dump( object, out ) end end end
true
d79509f5d0481cea2df3b46530b141071f84739c
Ruby
Irwin1985/lets_build_a_simple_interpreter-1
/lib/parser.rb
UTF-8
1,624
3.6875
4
[]
no_license
require_relative 'token.rb' require_relative 'lexer.rb' require_relative 'bin_op.rb' require_relative 'num.rb' require_relative 'interpreter.rb' class Parser def initialize(lexer) @lexer = lexer @current_token = @lexer.get_next_token end def error raise 'Invalid syntax' end def eat(token_type) if @current_token.type == token_type @current_token = @lexer.get_next_token else error end end def factor token = @current_token if token.type == :integer eat(:integer) return Num.new(token) elsif token.type == :lparen eat(:lparen) node = expr eat(:rparen) return node end end def term node = factor while [:div, :mul].include?(@current_token.type) token = @current_token if token.type == :mul eat(:mul) elsif token.type == :div eat(:div) end node = BinOp.new(node, token, factor) end return node end def expr node = term while [:plus, :minus].include?(@current_token.type) token = @current_token if token.type == :plus eat(:plus) elsif token.type == :minus eat(:minus) end node = BinOp.new(node, token, term) end return node end def parse return expr end end def run puts "Interpreter: type exit to leave" while true print 'calc> ' user_input = gets.chomp case user_input when "exit" break else lexer = Lexer.new(user_input) interpreter = Interpreter.new(lexer) result = interpreter.expr end end end #run
true
d80c24eab8984fb04fe042aab613ef53ebab348f
Ruby
bitjourney/mato
/lib/mato/anchor_builder.rb
UTF-8
1,334
2.5625
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'erb' module Mato class AnchorBuilder # assumes use of font-awesome # specify it as "<span aria-hidden=\"true\" class=\"octicon octicon-link\"></span>" if you use octicon DEFAULT_ANCHOR_ICON_ELEMENT = '<i class="fa fa-link"></i>' CSS_CLASS_NAME = "anchor" attr_reader :anchor_icon_element attr_reader :context def initialize(anchor_icon_element = DEFAULT_ANCHOR_ICON_ELEMENT) @anchor_icon_element = anchor_icon_element @id_map = {} end # @param [Nokogiri::XML::Node] hx def make_anchor_element(hx) id = make_anchor_id(hx) %{<a id="#{id}" href="##{id}" aria-hidden="true" class="#{CSS_CLASS_NAME}">#{anchor_icon_element}</a>} end def make_anchor_id(hx) prefix = make_anchor_id_prefix(hx.inner_text) "#{prefix}#{make_anchor_id_suffix(prefix)}" end private def make_anchor_id_suffix(text) @id_map[text] ||= -1 unique_id = @id_map[text] += 1 if unique_id > 0 "-#{unique_id}" else "" end end def make_anchor_id_prefix(text) prefix = ERB::Util.url_encode(text.downcase.gsub(/[^\p{Word}\- ]/u, "").tr(" ", "-")) if prefix.empty? "user-content" # GitHub compatible else prefix end end end end
true
4931ee31805b4f840fc7d8f1f2a0785690c9657b
Ruby
maurcs/geokit-rails
/cardinalize/test/cardinalize_test.rb
UTF-8
1,207
3.203125
3
[ "MIT" ]
permissive
require 'test_helper' class CardinalizeTest < Test::Unit::TestCase # Replace this with your real tests. def test_a_floats_cardinality assert_equal 10.0.cardinalize, "North" assert_equal 310.5.cardinalize, "Northwest" assert_equal 175.2.cardinalize, "South" assert_equal 40.0.cardinalize, "Northeast" assert_equal -40.0.cardinalize, "Northwest" assert_equal 600.5.cardinalize, "Southwest" end def test_an_integer_cardinality assert_equal 10.cardinalize, "North" assert_equal 310.cardinalize, "Northwest" assert_equal 175.cardinalize, "South" assert_equal 40.cardinalize, "Northeast" assert_equal -40.cardinalize, "Northwest" assert_equal 600.cardinalize, "Southwest" end def test_a_strings_cardinality assert_equal "10".cardinalize, "North" assert_equal "310".cardinalize, "Northwest" assert_equal "175".cardinalize, "South" assert_equal "40".cardinalize, "Northeast" assert_equal "-40".cardinalize, "Northwest" # to_f makes this 0.0 assert_equal "aaaaaaa".cardinalize, "North" end def test_an_arrays_cardinality courses = 10.times.inject([]){|a,i|a << rand(360).to_f} assert_equal courses.cardinalize, courses.collect{|i| i.cardinalize} end end
true
e02f2f1d5df433cf147d0d466341d33cf5ec468b
Ruby
Oomori-K/MaruBatsu
/Display.rb
UTF-8
328
3.796875
4
[]
no_license
class Display def output(point) puts(" 0 1 2") for y in 0..4 y.even? ? print(y/2," ") : print(" ") for x in 0..10 print(point[y][x]) end print("\n") end end #手番の表示 def player_turn(turn) turn ? (puts "<Player ○>") : (puts "<Player ×>") end end
true
fa43e41aae9b4829da122af436d5e224ef7ce292
Ruby
darthzippy/blog
/models/post.rb
UTF-8
773
2.875
3
[]
no_license
require "stringex" require "pp" class Post include Model def errors @errors = {} if @title.blank? @errors[:title] = "Title must not be empty." end if !@published_at_raw.blank? && @published_at.blank? @errors[:published_at] = "Published At must be a valid date-time." end if @body.blank? && (!@published_at.blank? || !@published_at_raw.blank?) @errors[:body] = "You cannont publish an empty post." end @errors end def published_at=(value) @published_at_raw = value @published_at = self.class.typecast_time(value) end def published? !@published_at.blank? && @published_at < Time::now end def to_url @slug ||= title.to_url end def slug to_url end end
true
6492a0e25c8afd74aad180de95eb7bc61a92f3e4
Ruby
chujot/zstudy
/test4.rb
UTF-8
1,014
3.109375
3
[]
no_license
require 'sinatra' get '/test' do if params['c'] == 'd' result = params['a'].to_i + params['b'].to_i elsif params['c'] == 'e' result = params['a'].to_i - params['b'].to_i elsif params['c'] == 'f' result = params['a'].to_i / params['b'].to_i elsif params['c'] == 'g' result = params['a'].to_i * params['b'].to_i end if result == nil answer = "数値を入れて計算してみよう" else answer = "答えは#{result}だよ(・∀・)" end %Q{ <form> <input name="a" value='#{params['a']}'> <select name="c"> <option value="d"> + </option> <option value="e"> − </option> <option value="f"> ÷</option> <option value="g"> × </option> </select> <input name="b" value='#{params['b']}'> = <input value="#{result}" readonly> <input type="reset" value="クリア"> <input type="submit" value="送信"> </form> #{answer} } end
true
68ff5b0f282d04f15fe9f0728a1b93804632b80b
Ruby
gshalev/edx_courses
/SAAS/HW1/part3.rb
UTF-8
306
3.6875
4
[]
no_license
def combine_anagrams(words) # YOUR CODE HERE my_hash = Hash.new {|hash,key| hash[key] = []} words.each do |w| my_key = w.downcase.chars.sort.join my_hash[my_key].push(w) end my_arr = [] my_hash.values.each do |val| my_arr.push(val) end return my_arr end #combine_anagrams
true
4bd7494cf5021a923eb280a38759700a5429af50
Ruby
kupolak/codewars
/Ruby/7 KYU/Sorted? yes? no? how?.rb
UTF-8
148
3.1875
3
[]
no_license
def is_sorted_and_how(arr) if arr == arr.sort "yes, ascending" elsif arr == arr.sort.reverse "yes, descending" else "no" end end
true
1c0e1fcdab1442bd551a0e1772fa850ad12ae977
Ruby
tlcowling/euler
/ruby/probem89.rb
UTF-8
1,860
3.75
4
[]
no_license
#Problem 89 #=============== =begin The rules for writing Roman numerals allow for many ways of writing each number (see About Roman Numerals...). However, there is always a "best" way of writing a particular number. For example, the following represent all of the legitimate ways of writing the number sixteen: IIIIIIIIIIIIIIII VIIIIIIIIIII VVIIIIII XIIIIII VVVI XVI The last example being considered the most efficient, as it uses the least number of numerals. The 11K text file, roman.txt (right click and 'Save Link/Target As...'), contains one thousand numbers written in valid, but not necessarily minimal, Roman numerals; that is, they are arranged in descending units and obey the subtractive pair rule (see About Roman Numerals... for the definitive rules for this problem). Find the number of characters saved by writing each of these in their minimal form. Note: You can assume that all the Roman numerals in the file contain no more than four consecutive identical units. =end timer_start = Time.now before, after = 0,0 @@map = { "M" => 1000, "CM" => 900, "D" => 500, "CD" => 400, "C" => 100, "XC" => 90, "L" => 50, "XL" => 40, "X" => 10, "IX" => 9, "V" => 5, "IV" => 4, "I" => 1 } def toRoman(number) result = "" @@map.each do |roman, arabic| while number >=arabic result += roman number -= arabic end end result end corrections = { 'IIII' => 'IV', 'VIIII' => 'IX', 'XXXX' => 'XL', 'LXXXX' => 'XC', 'CCCC' => 'CD', 'DCCCC' => 'CM' } reg = /IIII|VIIII|XXXX|LXXXX|CCCC|DCCCC/ File.open("roman.txt", "r").lines {|roman| roman.chomp! before += roman.size roman.gsub!(reg) {|r| corrections[r] } after += roman.size } p "The difference is #{before - after}" p "It took #{(Time.now - timer_start)*1000} milliseconds"
true
65c2481d9c9aa8ea7d84dc2448b0a5ea7440abe3
Ruby
rubygems/gemstash
/lib/gemstash/cache.rb
UTF-8
2,816
2.625
3
[ "MIT" ]
permissive
# frozen_string_literal: true require "lru_redux" require "forwardable" module Gemstash # Cache object which knows about what things are cached and what keys to use # for them. Under the hood is either a Memcached client via the dalli gem, or # an in memory client via the lru_redux gem. class Cache EXPIRY = Env.current.config[:cache_expiration] extend Forwardable def_delegators :@client, :flush def initialize(client) @client = client end def authorization(auth_key) @client.get("auths/#{auth_key}") end def set_authorization(auth_key, value) @client.set("auths/#{auth_key}", value, EXPIRY) end def invalidate_authorization(auth_key) @client.delete("auths/#{auth_key}") end def dependencies(scope, gems) key_prefix = "deps/v1/#{scope}/" keys = gems.map {|g| "#{key_prefix}#{g}" } @client.get_multi(keys) do |key, value| yield(key.sub(key_prefix, ""), value) end end def set_dependency(scope, gem, value) @client.set("deps/v1/#{scope}/#{gem}", value, EXPIRY) end def invalidate_gem(scope, gem) @client.delete("deps/v1/#{scope}/#{gem}") Gemstash::SpecsBuilder.invalidate_stored if scope == "private" end end # Wrapper around the lru_redux gem to behave like a dalli Memcached client. class LruReduxClient MAX_SIZE = Env.current.config[:cache_max_size] EXPIRY = Gemstash::Cache::EXPIRY extend Forwardable def_delegators :@cache, :delete def_delegator :@cache, :[], :get def_delegator :@cache, :clear, :flush def initialize @cache = LruRedux::TTL::ThreadSafeCache.new MAX_SIZE, EXPIRY end def alive! true end def get_multi(keys) keys.each do |key| found = true # Atomic fetch... don't rely on nil meaning missing value = @cache.fetch(key) { found = false } next unless found yield(key, value) end end def set(key, value, expiry) @cache[key] = value end end # Wrapper around the redis-rb gem to behave like a dalli Memcached client. class RedisClient extend Forwardable def_delegator :@cache, :del, :delete def initialize(redis_servers) require "redis" @cache = ::Redis.new(:url => redis_servers) end def alive! @cache.ping == "PONG" end def get(key) val = @cache.get(key) YAML.load(val, permitted_classes: [Gemstash::Authorization, Set]) unless val.nil? end def get_multi(keys) @cache.mget(*keys).each do |k, v| next if v.nil? yield(k, YAML.load(v)) end end def set(key, value, expiry) @cache.set(key, YAML.dump(value), :ex => expiry) end def flush @cache.flushdb end end end
true
a60ac9f65011ed59cb3f52ac37a75eabcb7a71c1
Ruby
torubylist/ruby_learning
/alg/two_num.rb
UTF-8
560
3.671875
4
[]
no_license
def two_sum(nums,target) len = nums.length (0...len).each do |i| if nums[i] > target then next end num2 = i + 1 (num2...len).each do |j| if nums[j] > target then next end sum = nums[i] + nums[j] if sum == target then index1 = i + 1 index2 = j + 1 puts "index1=#{index1},index2=#{index2}" new_nums = Array[index1,index2] return new_nums else next end end end end nums = Array[3,5,19,14,32] target = 19 puts two_sum(nums,target).inspect
true
e0fe34efe424bae5cf09ef08d6eec16a97f30290
Ruby
migcont/1_prueba_ruby
/programa.rb
UTF-8
2,269
3.71875
4
[]
no_license
def create_data_structure(file) array_of_hashes = [] #array nuevo #manejo de archivo file = File.open(file, 'r') data = file.readlines.map(&:chomp) file.close data = data.map { |e| e.split(', ') } # separar los datos data.each do |line| student = { name: line.shift, #asignar los nombres y las variables grades: line.map(&:to_s) #el resto son las notas } array_of_hashes << student end puts "====MOSTRANDO CONTENIDO CSV=====" puts array_of_hashes puts "====TERMINADO CONTENIDO CSV=====" return array_of_hashes end def calculate_average(array_of_grades) #pendiente transformar los 0 a 1 7 antes eran una A array_of_grades.inject(0) { |sum, val| sum + val } / array_of_grades.length #return array_of_grades #puts array_of_grades end #manejo de datos #opcion 1 def promedio #average array_of_hashes = create_data_structure('datos.csv') # hacer el archivo array_of_hashes.each_index do |student_hash| average = calculate_average(student_hash[:grades]) name = student_hash[:name] file.puts "#{name}, #{average}" end end #opcion2 def inasistencias array_of_hashes = create_data_structure('datos.csv') puts "==========INICIO DEL EJERICIO2===========" array_of_hashes.each_index do |e| name = array_of_hashes[e][:name] a = (array_of_hashes[e][:grades]).count("A") puts "#{name} tiene: #{a} ausencias." end puts "==========FIN DEL EJERICIO2==============" end #opcion3 def aprobados end #opciones de menu option = 0 puts 'Informacion de alumnos: ', "\n" while option puts 'Ingrese una opcion: ', "\n" puts 'Ingrese: 1 para ver el nombre de cada alumno y sus notas' puts 'Ingrese: 2 para mostrar la cantidad de inasistencias totales' puts 'Ingrese: 3 para mostrar a los alumnos aprobados' puts 'Ingrese: 4 para salir' option = gets.to_i case option when 1 #solo un archivo nombre y notas por alumno #promedio promedio when 2 #por cada persona => nombre y cantidad inasistencias when 3 #sin ingreso nota (5-defaul o si ingresa el valor) permitir ingresar notas manuales / ingrese nota minima de aprobacion aprobados when 4 puts 'salir', "\n" exit else puts 'Opcion no valida, ingresa una entre 1 y 4', "\n" end end
true
f9fdeff762eb004c28e9c255632184146190783a
Ruby
marmo002/w9d2assignment1
/exercise1.rb
UTF-8
682
2.796875
3
[]
no_license
require 'httparty' toronto_wards_response = HTTParty.get('https://represent.opennorth.ca/boundaries/toronto-wards/') toronto_wards_jason = JSON.parse(toronto_wards_response.body) @wards = toronto_wards_jason["objects"] @wards.map do |ward| puts ward['name'] # puts "#{ward['name']}" end puts "******************************************" toronto_commons_response = HTTParty.get('https://represent.opennorth.ca/representatives/house-of-commons/') toronto_commons_json = JSON.parse(toronto_commons_response.body) @commons = toronto_commons_json['objects'] @commons.each do |member| puts "Name: #{member['name']}" puts "Member of: #{member['party_name']}" puts "---" end
true
7361b7fba354224574b6e5fd8bc17559714e5eb0
Ruby
patassetbuilders/oop_2
/lesson_4/OO_exersizes_easy2.rb
UTF-8
3,356
4.1875
4
[]
no_license
require 'pry' class Oracle def predict_the_future "You will " + choice.sample end def choice ["eat a nice lunch", "take a nap soon", "stay at work late"] end end oracle = Oracle.new puts oracle.predict_the_future puts oracle.predict_the_future puts oracle.predict_the_future puts oracle.predict_the_future puts oracle.predict_the_future puts oracle.predict_the_future puts oracle.predict_the_future puts oracle.predict_the_future puts oracle.predict_the_future # "it will return the string 'You will' + # one of the phrases from the choices array class RoadTrip < Oracle def choice ["visit Vegas", "fly to Fiji", "romp in Rome"] end end trip = RoadTrip.new puts trip.predict_the_future # Question 2 # method look up for choices starts with the class of object that # is making the call, and # stops looking once it finds the method with that name # so even though predict_the_future method is in the super class # ruby will first search for choice.sample in the calling RoadTrip class # Question 3 # you call ancestors method on the class module Taste def flavor(flavor) puts "#{flavor}" end end class Orange include Taste end class HotSauce include Taste end puts HotSauce.ancestors puts Orange.ancestors # Question 4 class BeesWax attr_accessor :type # replaces getter and settor methods def initialize(type) @type = type end #def type # @type # end #def type=(t) # @type = t # end def describe_type puts "I am a #{@type} of Bees Wax" end end wax_1 = BeesWax.new('old') puts wax_1.type # Question 5 # excited_dog = "excited dog"- local variable # @excited_dog = "excited dog" - instance variable @ # @@excited_dog = "excited dog" - class variable @@ # Question 6 class Television def self.manufacturer # method logic puts "Hi from class method" end def model # method logic end end # self.manufacturer is a class method as denoted by the self. my_tv = Television.new puts Television.manufacturer # question 7 class Cat @@cats_count = 0 def initialize(type) @type = type @age = 0 @@cats_count += 1 end def self.cats_count puts self @@cats_count end end pussy = Cat.new('tabby') # puts pussy.cats_count => returns no method error puts Cat.cats_count # The @@cat_count variable is a class variable # in this case its job is to keep track of the number of # instances of the cat class that have been created # the cats_count method can be called dierectly on the Cat class but # not on the cat object # question 8 # make Bingo class a sub class of Games class Game def play "Start the game!" end end class Bingo < Game def rules_of_play #rules of play end end quick_money = Bingo.new puts quick_money.play # => Start the game! # question 9 # would depend if which class the of the instance object calling the play # method. If it was a game object the play method would be called # if it was a bingo instance then the bingo play method woyuld be called # see method look up # Question 10 # main benefits of object oriented programming # encapulation - don't need to understand the implementation # objects states can only be accessed by instance methods # polymorphism - reuse code # ability to chunk problems into into smaller managible pieces. # model real world problems
true
41b4f0aa8ab7bd2c664ab8bb804c77d2729309f6
Ruby
anne-other/multi_class_weekend_homework
/guests.rb
UTF-8
429
3.625
4
[]
no_license
class Guest attr_reader :name, :wallet, :fav_song def initialize(name, wallet, fav_song) @name = name @wallet = wallet @fav_song = fav_song end def pay_fee(room) @wallet -= room.entrance_fee() end def have_fav_song(room) if room.find_song(fav_song()).class == Song return "Whoo!" else return "Boo!" end end def buy_drink(drink) @wallet -= drink.price() end end
true
beb5fdf6aaa163a931af5121f856122137a5339e
Ruby
mericda/sinatra-deploys
/password-gen/guessthenumber.rb
UTF-8
1,476
4.53125
5
[]
no_license
# guess the number v0.1 # version: basics puts "Guess the Number" puts "Ready..." puts "Set." puts "Go!" # The object of the game is to guess the number. # The program will begin by picking a random number between 1 and 10. # use rand # This will be stored in a variable. #store in variable secret = rand 1..9 # = number from 0.00-1.00 #counting rounds, starting by 0 counter = 0 #check which round is itsay what to do in each while counter < 3 do # The program will then ask (using the command line) to guess the number puts "Guess a number between 1 and 10" # The player will enter a number (or maybe not # you might need to check for that!) guess = gets.chomp # convert the number to an integer. guess = guess.to_i # The program will check to see if the number matches. if guess == secret # If it does, the player wins and they're congratulated puts "That's right! It was #{guess}!" break # If it doesn't, they're offered another chance to guess the number else puts "Sorry, it is not." end if counter == 2 then # The program will allow the user up to 3 guesses. puts "You run out of attempts.The secret number was #{secret}." break end if counter == 1 then puts "You have one guess left. Try it again." else puts "You have two guesses left. Try it again." end counter = counter +1 end # The program will loop until quit
true
02332e516ff836b67c3f166ffc5b3fa1cf411b0d
Ruby
a2ikm/erbc
/lib/erbc/writer.rb
UTF-8
412
2.671875
3
[]
no_license
module Erbc class Writer attr_reader :request def initialize(request) @request = request end def write(result) with_output_io do |io| io.write(result) end end private def with_output_io if output = request.output File.open(output, "w") do |io| yield(io) end else yield($stdout) end end end end
true
2016ed33c5a3097618f6e3cfb079a6dde61c97f5
Ruby
mjago/CW
/lib/cw/threads.rb
UTF-8
3,647
2.8125
3
[ "MIT" ]
permissive
# encoding: utf-8 module CW class Threads attr_reader :threads def initialize context, processes Thread.abort_on_exception = true @context = context @processes = processes @threads = [] end def start_threads @processes.collect do |th| @threads << start_thread(@context, th) end end def start_thread context, th { :thread => Thread.new do context.send th end, :name => th } end def kill_thread thread thread[:thread].kill end def kill_thread_x x @threads.each_with_index do |th,idx| if th[:name] == x kill_thread th @threads.delete_at idx end end end def join x @threads.each do |th| if th[:name] == x th[:thread].join end end end def add context, th @threads << start_thread(context, th) end def monitor_threads exiting = false loop do sleep 0.5 # @threads.each do |th| # if thread_false_or_nil?(th) ##todo exiting = true # unless Cfg.config["exit"] ## puts "** #{th[:name].to_s.gsub('_',' ')} quit unexpectedly!**" # if th[:thread].backtrace # STDERR.puts th[:thread].backtrace.join("\n \\_ ") # end # end # end # print_threads_status exiting = true if(Cfg.config["exit"]) break if exiting end @threads.each do |th| th[:thread].kill.join end #close_threads if exiting end def kill_open_threads @threads.each do |thread| unless thread_false_or_nil?(thread) kill_thread thread end end end def thread_false_or_nil? th if(th[:thread].status == false) return true end if(th[:thread].status.nil?) return true end end def wait_for_threads Cfg.config.params["exit"] = false loop do alive = false sleep 0.1 @threads.each { |th| if thread_false_or_nil? th elsif th[:name] != :monitor_keys_thread alive = true end } break unless alive end threads.each {|th| if(th[:name] == :monitor_keys_thread) kill_thread th end sleep 0.1 } end def print_threads_status @threads.each do |thread| puts "\r" print "#{thread[:name]} = " # p thread[:thread].status end end def kill_monitor_keys_thread_maybe thread kill_thread(thread) unless thread_false_or_nil?(thread) end def any_thread_open? @threads.each do |thread| # print "status " # p thread if(thread[:name] == :monitor_keys_thread) kill_monitor_keys_thread_maybe thread else unless thread_false_or_nil?(thread) return true end end end nil end def force_kill puts "exiting" # puts "Forcing kill!\r" kill_open_threads # print_threads_status system("stty -raw echo") sleep 0.2 exit(1) end def close_threads await_termination_count = 0 loop do sleep 0.1 break unless any_thread_open?() # print_threads_status await_termination_count += 1 force_kill if(await_termination_count >= 30) end end def run start_threads monitor_threads system("stty -raw echo") puts "\r" end end end
true
936a20e0c1da6e1704490c9c04523849ecd58ae2
Ruby
NiestrojMateusz/Launch-School-101
/exercises/Easy3/3_count_char.rb
UTF-8
1,737
4.59375
5
[]
no_license
# Counting the Number of Characters # Write a program that will ask a user for an input of a word or multiple words and give back the number of characters. Spaces should not be counted as a character. # input: # Please write word or multiple words: walk # output: # There are 4 characters in "walk". # input: # Please write word or multiple words: walk, don't run # output: # There are 13 characters in "walk, don't run". #=============================PseudoCode====================================== #-get a words from a user and stor it in a variable #-split the word to array #-check the size of the array #============================================================================= puts "Please write word or multiple words: " input = gets.chomp char_arr = input.split("") char_arr.delete(" ") chars_num = char_arr.size puts "There are #{chars_num} characters in \"#{input}\"" #=============================other users solution============================= # def num_chars(string) # count = string.length - string.count(' ') # puts "There are #{count} characters in \"#{string}\"." # end # puts 'Please write word or multiple words:' # num_chars(gets.chomp) #=============================with regexp====================================== # def remove_spaces(input) # input.gsub(/\W+\s/,'').length # end # print 'Please write a word or multiple words: ' # input = gets.chomp # puts "There are #{remove_spaces(input)} characters in \"#{input}\"." #============================================================================== # print 'Please write word or multiple words: ' # input = gets.chomp # number_of_characters = input.delete(' ').size # puts "There are #{number_of_characters} characters in \"#{input}\"."
true
b45b21faf7d8bafb879669920a7cb392faf47b1f
Ruby
ShadyLogic/craigscraper
/app/controllers/concerns/scraper.rb
UTF-8
1,817
2.703125
3
[ "MIT" ]
permissive
require 'nokogiri' require 'open-uri' require 'httparty' module Scraper BASE_URL = "http://sfbay.craigslist.org" extend ActiveSupport::Concern def archive_posts(links) posts = [] links.each do |link| p "*"*100 p link p "*"*100 post = Nokogiri::HTML(open(link)) posts << scrape_info(post) end posts end def new_links(address, first_link) current_doc = Nokogiri::HTML(open(address)) current_links = create_urls_from_links(gather_links(current_doc)) new_links = [] unless current_links.first == first_link current_links.each_index do |i| if current_links[i] == first_link return new_links else new_links << current_links[i] end end end new_links end def gather_links(address) doc = Nokogiri::HTML(open(address)) links = doc.search('.row > a:first-child').map do |link| link.attributes['href'].value end links.map { |link| BASE_URL + link } end def scrape_info(post) info = { title: scrape_title(post), text: scrape_text(post), images: scrape_images(post) } # unless info[:images].empty? # info[:images].map { |url| upload_image(url)} # end info end def scrape_title(post) post.css('title').inner_text end def scrape_text(post) post.css('#postingbody').inner_text end def scrape_images(post) parsed_post = post.css('script')[2].inner_text.split("\"") parsed_post.select{ |item| item.include?(".jpg") && !item.include?("50x50") } end def upload_image(url) body = { 'image' => url } headers = { "Authorization" => "Client-ID " + '8756023387f86f7' } response = HTTParty.post('https://api.imgur.com/3/image', :body => body, :headers => headers) image_url = response["data"]["link"] return image_url end end
true
af932e60260e41ff10ef2bfa4d238ba9be15866e
Ruby
cjford/nand2tetris
/projects/10/compiler/compiler.rb
UTF-8
750
2.921875
3
[]
no_license
require_relative './tokenizer.rb' require_relative './symbol_table' require_relative './parse_tree' class Compiler def initialize(args) @args = args end def compile input_files.each do |input_file| tokenizer = Tokenizer.new(input_file) parse_tree = ParseTree.new(tokenizer, input_file) parse_tree.build end end private def input_files raise 'Please specify a file or directory for compilation' unless @args[0] if @args[0].match(/^\S+\.jack$/) && File.file?(@args[0]) return [@args[0]] elsif File.directory?(@args[0]) return Dir.glob("#{@args[0]}/*.jack") end raise 'Specified input file/directory was not found' end end compiler = Compiler.new(ARGV) compiler.compile
true
8cecaa0d804262485030d44c892d77f297a82299
Ruby
lluzak/form_objects
/spec/params_converter_spec.rb
UTF-8
3,397
2.59375
3
[ "MIT" ]
permissive
require 'spec_helper' describe FormObjects::ParamsConverter do let(:event_attributes) { { "0" => { "name" => "Name 0" }, "1" => { "name" => "Name 1" } } } let(:params) { { "events_attributes" => event_attributes } } let(:converted_attributes) { [{"name" => "Name 0"}, {"name" => "Name 1"}] } subject { described_class.new(params) } describe "#params" do describe "date parameters" do describe "only three params" do let(:params) { { "event" => { "date(1i)" => "2014", "date(2i)" => "12", "date(3i)" => "16" } } } it "returns date as string" do subject.params["event"]["date"].should == "2014.12.16 00:00:00" end end describe "only four params" do let(:params) { { "event" => { "date(1i)" => "2014", "date(2i)" => "12", "date(3i)" => "16", "date(4i)" => "12" } } } it "returns date as string" do subject.params["event"]["date"].should == "2014.12.16 12:00:00" end end describe "only five params" do let(:params) { { "event" => { "date(1i)" => "2014", "date(2i)" => "12", "date(3i)" => "16", "date(4i)" => "12", "date(5i)" => "30" } } } it "returns date as string" do subject.params["event"]["date"].should == "2014.12.16 12:30:00" end end describe "all parameters" do let(:params) { { "event" => { "date(1i)" => "2014", "date(2i)" => "12", "date(3i)" => "16", "date(4i)" => "12", "date(5i)" => "30", "date(6i)" => "45" } } } it "returns date as string" do subject.params["event"]["date"].should == "2014.12.16 12:30:45" end end end describe "nested parameters" do it "returns events_attributes converted to array" do subject.params["events_attributes"].should == converted_attributes end it "returns HashWithIndifferentAccess" do subject.params.should be_kind_of(HashWithIndifferentAccess) end it "does not modify original params" do subject.params.should_not == params end describe "events_attributes in nested" do let(:params) { { "event" => { "events_attributes" => event_attributes } } } it "returns events_attributes converted to array" do subject.params["event"]["events_attributes"].should == converted_attributes end end describe "events_attributes should keep sequence" do let(:event_attributes) { { "1" => { "name" => "Name 1" }, "0" => { "name" => "Name 0" } } } it "returns events_attributes converted to array" do subject.params["events_attributes"].should == [{"name" => "Name 0"}, {"name" => "Name 1"}] end end describe "event_attributes is not Hash which pretends Array" do let(:event_attributes) { { "first_attribute" => { "name" => "Name 0" } } } it "returns non-converted events_attributes" do subject.params["events_attributes"].should == event_attributes end end describe "event_attributes is Hash which almost pretends Array (wrong attributes sequence)" do let(:event_attributes) { { "0" => { "name" => "Name 0" }, "2" => {"name" => "Name 2"} } } it "returns non-converted events_attributes" do subject.params["events_attributes"].should == event_attributes end end end end end
true
9e9e0ea3416d914f119ac305cf2d5153d4e766da
Ruby
evgeniradev/ruby_data_structures_and_algorithms
/data_structures/kueue.rb
UTF-8
694
3.828125
4
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class Kueue def initialize @first = nil @last = nil @length = 0 end attr_reader :length def peek first end def enqueue(value) node = Node.new(value) if last last.next = node else @first = node end @last = node @length += 1 puts 'Node enqueued.' node end def dequeue return puts('Queue is empty.') if length.zero? node = @first @last = nil if length == 1 @first = node.next @length -= 1 puts 'Node dequeued.' node end private attr_reader :first, :last end class Node def initialize(value) @value = value @next = nil end attr_accessor :value, :next end
true
aa9af1d681344932f9583c5c4a3a3a261a359aab
Ruby
fabrod/ruby-learning
/input.rb
UTF-8
418
4
4
[]
no_license
print "How old are you? " age = gets.chomp print "How tall are you? " height = gets.chomp print "How much do you weigh? " weight = gets.chomp puts "So, you're #{age} years old, #{height} tall and #{weight} you weight." print "Como te llamas?" name = gets.chomp print "Cuando vas para la Republica Dominicana? " travel = gets.chomp puts "Hello Mr #{name} nice to meet you ,You are going in #{travel} to Dominicana. "
true