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
016672e432d58c7fd32f45e97e49805cb29d1d55
Ruby
yurkaronin/rubyrush
/rubles-to-dollars-converter/1.rb
UTF-8
756
3.453125
3
[]
no_license
# Напишите конвертер валют рубли-доллары: # программу, которая спрашивает курс, потом спрашивает у пользователя, # сколько у него рублей, а потом выдает результат в долларах. today = Time.now puts "Сколько сейчас стоит 1 доллар на бирже?" rate = gets.to_f.round(2) puts "на сегодня #{today}", "Курс $ по отношению к ₽ составляет: #{rate}" puts "\n" puts "А сколько к вас с собой рублей?" stock = gets.to_f purchase = (stock / rate).round(2) puts "Ваших денег хватит на покупку: #{purchase} $"
true
b26ed65cd4239183b94ca017a685b868d58bb518
Ruby
habutai/Bears-have-Teeth-and-Claws
/my_sort.rb
UTF-8
334
3.0625
3
[]
no_license
def my_sort(sortlist) return sortlist if sortlist.size <= 1 for i in 0..(sortlist.length - 1) for j in 0..(sortlist.length - i - 2) if (sortlist[j + 1] <=> sortlist[j]) == -1 sortlist[j], sortlist[j + 1] = sortlist[j + 1], sortlist[j] end end end return sortlist end
true
46c67e011082436b84ad18098b85fd2052895fe3
Ruby
ZongZiWang/E-PKUer-Server
/app/models/restaurant.rb
UTF-8
2,934
2.59375
3
[]
no_license
class Restaurant < ActiveRecord::Base attr_accessible :average_cost, :status_busy, :status_normal, :status_loose, :category, :description, :dishes, :evaluation, :image_url, :info_summary, :info_tel, :info_time, :location_latitude, :location_longitude, :location_name, :location_zone, :name has_many :dishes, :dependent => :destroy has_many :restaurant_comments, :dependent => :destroy has_many :complaints, :dependent => :destroy before_destroy :ensure_not_referenced_by_any_dish_or_comment_or_complaint validates :name, :image_url, :evaluation, :presence => true validates :average_cost, :numericality => {:greater_than_or_equal_to => 0.01} validates :name, :uniqueness => true validates :image_url, :format => { :with => %r{\.(gif|jpg|png)$}i, :message => 'must be a URL for GIF, JPG or PNG image.' } def evaluation if self.restaurant_comments.count == 0 then return 0 end _evaluation = 0 self.restaurant_comments.each { |comment| _evaluation += comment.evaluation } return _evaluation / self.restaurant_comments.count end def average_cost if self.restaurant_comments.count == 0 then return 0 end _average_cost = 0 self.restaurant_comments.each { |comment| _average_cost += comment.cost } return _average_cost / self.restaurant_comments.count end def busy if self.status_normal >= self.status_busy && self.status_normal >= self.status_loose return 1 else if self.status_loose >= self.status_busy return 2 else return 0 end end end def recommendations _recommendations = self.dishes.sort { |dish1, dish2| dish2.recommendation_count <=> dish1.recommendation_count } # _recommendations.delete_if { |dish| dish.recommendation_count == 0 } end def partial_recommendations _dishes = self.dishes.sort { |dish1, dish2| dish2.recommendation_count <=> dish1.recommendation_count } # _dishes.delete_if { |dish| dish.recommendation_count == 0 } _partial_recommendations = Array.new _dishes.first(3).each do |dish| _partial_recommendations.push({ id: dish.id, name: dish.name, recommendation_count: dish.recommendation_count }) end _partial_recommendations end def partial_dishes _count = self.dishes.count _partial_dishes = Array.new self.dishes.last(3).each do |dish| _partial_dishes.push({ id: dish.id, name: dish.name }) end _partial_dishes end def partial_comments _count = self.restaurant_comments.count _partial_comments = Array.new self.restaurant_comments.last(3).each do |comment| _partial_comments.push({ id: comment.id, user_name: comment.user.name, evaluation: comment.evaluation, content: comment.content }) end _partial_comments end private def ensure_not_referenced_by_any_dish_or_comment_or_complaint if dishes.empty? && restaurant_comments.empty? && complaints.empty? return true else errors.add(:base, 'Dishes, Comments or Complaints present') return false end end end
true
aea35615e3b7ce8c184b09115ce25fa93951e0d1
Ruby
leotangram/Saludame3
/solution.rb
UTF-8
300
2.625
3
[]
no_license
require 'sinatra' get '/' do erb :index end post '/views/:name' do @name = params[:nick] erb :hola end # # get '/' do # # if params[:nombre] # # name = params[:nombre] # # "<h1>Hola #{name}!</h1>" # # else # # "<h1>Hola #{name = "desconocido"}!" # # end # # redirect '/' # # end
true
b530bf889d0067a56fd2ff30ba460850252e0f48
Ruby
alexwlchan/alexwlchan.net
/src/_plugins/tag_separator.rb
UTF-8
908
2.640625
3
[ "CC-BY-4.0", "LicenseRef-scancode-unknown-license-reference", "MIT", "AGPL-3.0-or-later" ]
permissive
# This plugin allows me to include a small SVG as an image as a separator. # # Example usage: # # {% separator "scroll.svg" %} # # References: # # - Accessible SVGs https://css-tricks.com/accessible-svgs/ # Explains in more detail how to ensure accessibility is preserved with # inline SVGs. # module Jekyll class SeparatorTag < Liquid::Tag def initialize(_tag_name, name, _tokens) super @name = name.strip.tr! '"', '' end def render(context) site = context.registers[:site] src = site.config['source'] svg_path = "#{src}/theme/_separators/#{@name}" svg_doc = File.open(svg_path) { |f| Nokogiri::XML(f) } svg_doc.root.set_attribute('role', 'separator') <<~HTML #{svg_doc.to_xml(indent: 0).gsub('<?xml version="1.0"?>', '')} HTML end end end Liquid::Template.register_tag('separator', Jekyll::SeparatorTag)
true
89bdc88d8506477337a2260e71540e272d7779a5
Ruby
pheinrich/euler
/solved/problem_0190.rb
UTF-8
3,032
3.0625
3
[ "MIT" ]
permissive
require 'projectEuler' class Problem_0190 def title; 'Maximising a weighted product' end def difficulty; 50 end # Let S_m = (x_1, x_2, ... , x_m) be the m-tuple of positive real numbers # with x_1 + x_2 + ... + x_m = m for which P_m = x_1 * x_2^2 * ... * x_m^m # is maximised. # # For example, it can be verified that [P_10] = 4112 ([ ] is the integer # part function). # # Find Σ[P_m] for 2 ≤ m ≤ 15. def solve( first = 2, last = 15 ) # Use the Lagrangean method to maximize f(x, y, z, ...) subject to the # constraint that g(x, y, z, ...) = b. In our case, # # f(x_1, x_2, x_3, ...) = x_1 · x_2^2 · x_3^3 · ... · x_m^m, # g(x_1, x_2, x_3, ...) = x_1 + x_2 + x_3 + ... + x_m, and # b = m # # Start with the simplest case, when m = 2 and f = x_1·x_2^2. First we # introduce a new variable, λ (the Lagrange multiplier), to set up the # Lagrangean. The Lagrange function appropriate to the problem statement # is: # # L(x_1, x_2, λ) = f(x_1, x_2) + λ[b - g(x_1, x_2)] # = x_1·x_2^2 + 2λ - λ(2 - x_1 - x_2) # # Now set the partial derivatives equal to zero and solve for the x_n: # # ∂L/∂x_1 = x_2^2 - λ = 0 # ∂L/∂x_2 = 2·x_1·x_2^2 - λ = 0 ==> x_2^2 = 2·x_1·x_2^2 # x_2 = 2·x_1 # ∂L/∂λ = 2 - x_1 - x_2 = 0 ==> 2 = x_1 + 2·x_1 # = 3·x_1 # So x_1 = 2/3 and x_2 = 4/3. # # Repeating this exercise for larger m gradually reveals a pattern in the # solutions generated in each case. It becomes clear that x_1 = m / t_m, # where t_m is the m-th triangle number [1, 3, 6, 10, 15, ...]. We also # see that x_2 = 2·x_1, x_3 = 3·x_1, and in general, x_k = k·x_1. Substi- # tuting the appropriate expression for each x_i, we get: # # f = x_1 · (2·x_1)^2 · (3·x_1)^3 · ... · (m·x_1)^m # # We could factor out the scalars and combine exponents, but the product # is actually a hyperfactorial and grows enormous very quickly. Instead, # we'll reduce each term separately and use the very small exponentiated # factors to keep the scalars under control. sum = 0 first.upto( last ) do |m| # x = m / t_m reduces to something rather simple. x = 2.0 / (m + 1) # Compute P_m and add its integer part to the total. sum += ((1..m).reduce( 1 ) {|acc, i| acc * (i*x)**i}).floor end sum end def solution; 'MzcxMDQ4Mjgx' end def best_time; 0.00006723 end def effort; 10 end def completed_on; '2016-08-05' end def ordinality; 2_927 end def population; 619_609 end def refs ['http://privatewww.essex.ac.uk/~wangt/Presession%20Math/Lecture%204.pdf', 'http://oeis.org/A002109', 'https://en.wikipedia.org/wiki/Level_set', 'https://en.wikipedia.org/wiki/Hessian_matrix', 'https://en.wikipedia.org/wiki/Second_partial_derivative_test'] end end
true
4ec3392ab565868c916fa2e2df8434277d130684
Ruby
hirengondhiya/HirenGondhiya_T1A1
/q16.rb
UTF-8
2,571
4.125
4
[]
no_license
# An allergy test produces a single numeric score which contains the information about all the allergies the person has (that they were tested for). The list of items (and their value) that were tested are: # eggs (1) # peanuts (2) # shellfish (4) # strawberries (8) # tomatoes (16) # chocolate (32) # pollen (64) # cats (128) So if Tom is allergic to peanuts and chocolate, he gets a score of 34. # Write a program that, given a person’s score can tell them: # a. whether or not they’re allergic to a given item # b. the full list of allergies. allergies = { "1": "eggs", "2": "peanuts", "4": "shellfish", "8": "strawberries", "16": "tomatoes", "32": "chocolate", "64": "pollen", "128": "cats", "256": "dogs" } def get_name invalid_input=false if invalid_input puts "Did not get your name. Please try again." end print "Please enter your name: " return gets.chomp end user_name = get_name while user_name == "" user_name = get_name true end def allergies_list(allergies, invalid_input=false) if invalid_input puts "Please enter values from given categories only. Please try again." end puts "Which allergy do you want to test for? " puts "Please enter an allergy only from following: #{allergies.values.map {|a| a.capitalize}.join(", ")}" return gets.chomp end item = allergies_list(allergies) while !(allergies.each_value.map {|a| a.upcase}.include? item.upcase) item = allergies_list(allergies, true) end def input_score max_score, invalid_input=false if invalid_input puts "Only Integer values from 0 to #{max_score} are acceptable. Please try again." end puts "Please enter your allergy score (Integer value between 0 and #{max_score} both inclusive): " return gets.chomp.to_i end total_score=0 allergies.keys.each {|k| total_score += k.to_s.to_i} score = input_score total_score while score < 0 || score > total_score score = input_score true end if (score > 0) s = score m = (allergies.keys.map {|k| k.to_s.to_i}.minmax)[1] puts m tested_allergies = [] while (m > 0) if (s/m > 0) tested_allergies.push(allergies[m.to_s.to_sym]) s = s % m end m = m/2 end puts "#{user_name} is tested #{tested_allergies.include?(item) ? 'positive' : 'negative'} for #{item} allergy." puts "#{user_name} is allergic to: #{tested_allergies.map {|t| t != nil ? t.capitalize : nil}.join(", ")}" else puts "#{user_name} is not allergic to anything." end
true
02cdec48a48183a488fcc813cd4831b352033a6f
Ruby
ipc103/intro-ruby
/02_book_finder.rb
UTF-8
1,008
3.75
4
[]
no_license
require 'rest-client' require 'json' require 'pry' def title(book) book['volumeInfo']['title'] end def authors(book) book['volumeInfo']['authors'].join(" and ") end def list_price(book) if book['saleInfo'].has_key?('listPrice') book['saleInfo']['listPrice']['amount'] else 'Not For Sale' end end def retail_price(book) if book['saleInfo'].has_key?('retailPrice') book['saleInfo']['retailPrice']['amount'] else 'Not For Sale' end end url = 'https://www.googleapis.com/books/v1/volumes?q=ruby+programming' response = RestClient.get(url) data = JSON.parse(response) books = data["items"] books.each do |book| puts "#{title(book)} by #{authors(book)}" puts "List Price: #{list_price(book)}" puts "Retail Price: #{retail_price(book)}" end # 1. Make a web request and get back the JSON string # 2. Turn that JSON string into a hash so I can access the data # 3. Display that data to the user through the command line # Title, author names, list price, retail price
true
7aa425c57f6c58d1e5c55ed7be911e860fa1ac14
Ruby
Jalindner/phase-0-tracks
/ruby/solo.rb
UTF-8
4,257
3.796875
4
[]
no_license
class Dragon attr_accessor :type, :favorite_treasure, :egg_amt #initialize for Dragon #Dragon type #favorite_treasure #number of eggs def initialize(type, favorite_treasure) @type = type @favorite_treasure = favorite_treasure @egg_amt = 0 #print_dragon end #breathe #what is exhaled depends on the dragon's type #known types are stored in a hash #verify that the type is in the hash #if the type is included, print the value associated with the matching key #if a type is not found, panic! def breathe example_types = {"classical" => "fire streaks", "mooshoo" => "fire balls", "undead" => "miasma", "rainbow" => "cheap electronica loops", "deep-sea" => "nothing"} if example_types.include?(@type) puts "The #{@type} dragon exhales #{example_types[@type]}!" puts " " else puts "The #{type} dragon is not in our database, proceed with caution!" puts " " end end #update_eggs #takes an integer as an arguement #egg_amt = integer arguement #print updated egg_amt def update_eggs(new_amt) @egg_amt = new_amt puts "This dragon now has #{@egg_amt} of eggs" puts " " end #update_treasure #takes a string as an arguement #favorite_treasure = string arguement #print updated favorite_treasure def update_treasure(new_treasure) @favorite_treasure = new_treasure puts "This dragon's new favorite treasure is #{@favorite_treasure}" puts " " end #print_dragon #prints out all current data about selected dragon def print_dragon puts "This is a #{@type} dragon" puts "This dragon is known to have #{@egg_amt} eggs" puts "This dragon's favorite treasure is #{@favorite_treasure}" puts " " end end #Initial driver code #naoki = Dragon.new("mooshoo", "jade structures") #naoki.breathe #naoki.update_eggs(2) #naoki.print_dragon #naoki.update_treasure("gold coins") #naoki.print_dragon dragons = [] choice = " " puts "Thank you for using our dragon reporting system!" until choice == "e" puts "-Type 'n' to create a new dragon or 'e' to exit and finish your report." choice = gets.chomp if choice == "n" puts "Enter the dragon's type" type = gets.chomp puts "Enter the dragon's favorite treasure" treasure = gets.chomp dragons << Dragon.new(type, treasure) elsif choice == "e" break else puts "Invalid input" end end dragons.length.times do |index| puts "-Dragon number #{index + 1}" dragons[index].print_dragon end dragon_choice = " " edit_choice = " " puts "Is their further information about the dragon(s) you would like to add?" until dragon_choice == "e" puts "-Enter the dragons associated number on the printed list to select that dragon to edit." puts "-Enter 'list' to review the data so far." puts "-Enter 'e' to exit the program and finish your edits" dragon_choice = gets.chomp if dragon_choice == "e" break elsif dragon_choice == "list" dragons.length.times do |index| puts "-Dragon number #{index + 1}" dragons[index].print_dragon end else puts "-Enter 'eggs' to update the amount of eggs the dragon has or 'treasure to update its favorite treasure." puts "-Enter 'breathe' to test the dragon's breath." puts "-Enter 'e' to exit to the previous menu." until edit_choice == "e" edit_choice = gets.chomp if edit_choice == "eggs" puts "Enter the new amount of eggs" new_eggs = gets.to_i dragons[dragon_choice.to_i - 1].update_eggs(new_eggs) break elsif edit_choice == "treasure" puts "Enter the new favorite treasure" new_treasure = gets.chomp dragons[dragon_choice.to_i - 1].update_treasure(new_treasure) break elsif edit_choice == "breathe" dragons[dragon_choice.to_i - 1].breathe break elsif edit_choice == "e" break else puts "Invalid choice" end end end end dragons.length.times do |index| puts "-Dragon number #{index + 1}" dragons[index].print_dragon end
true
93665b2880bde9d2c796911473836af971aae86f
Ruby
danshep/tabletop-dice
/lib/dice/parser.rb
UTF-8
6,068
3.140625
3
[]
no_license
module Dice class ParserError < StandardError;end class Parser SPACE = ' '[0] def initialize(string) #p ['parsing', string] @stack = [] @string = string @index = -1 state_start end def output @stack.first end private def next_char @string[@index+=1] end def unexpected(c) if c error("Unexpected character #{c.chr}") else error('Unexpected end of string') end end def error(string) message = "Error at char #{@index}: #{string}" message += "\n#{@string}" message += "\n" + " " * @index + "^" raise ParserError.new(message) end def state_start(c = next_char) @options = {} case c when ?+ then state_start_roll when ?- then @options[:negative] = true state_start_roll when SPACE then state_start when nil validate_end else state_start_roll(c) end end def state_start_roll(c = next_char) case c when (?1..?9) then @count = c - ?0 state_parse_count when SPACE then state_start_roll when ?( @stack << Brackets.new state_start_roll when (?a..?z), (?A..?Z) @attribute = c.chr state_parse_attribute else unexpected(c) end end def state_parse_attribute(c = next_char) case c when (?a..?z), (?A..?Z), ?_ @attribute += c.chr state_parse_attribute when ?( @stack << Function.new(@attribute, @options) state_start_roll else @calc = Lookup.new(@attribute, @options) state_end_roll(c) end end def state_parse_count case c = next_char when (?0..?9) then @count = @count * 10 + (c - ?0) state_parse_count when ?d, ?D then @option_name = :sides state_start_option_value #when ?+, ' '[0], ?-, nil else @calc = Constant.new(@options[:negative] ? -@count : @count) state_end_roll(c) #else unexpected(c) end end def state_start_option_value case c = next_char when (?1..?9) then @option_value = c - ?0 state_parse_option_value else unexpected(c) end end def state_parse_option_value c = next_char if (?0..?9) === c then @option_value = @option_value * 10 + (c - ?0) state_parse_option_value else @options[@option_name] = @option_value case c when ?r @option_name = :brutal state_start_option_value when ?k @option_name = :keep state_start_option_value else @calc = Roll.new(@count, @options) state_end_roll(c) end end end def validate_end unless @stack.size == 1 && @stack.last.complete? unexpected(nil) end end def state_end_roll(c = next_char) #p ['end roll', @calc] case c when SPACE state_start_type else state_next_part(c) end end def state_next_part(c = next_char) case c when nil add_element @calc, nil validate_end when ?+, ?- add_element @calc, Addition state_start(c) if c when ?* add_element @calc, Multiplication state_start when ?/ add_element @calc, Division state_start when ?) add_element @calc, nil if Brackets === @stack.last @calc = @stack.pop state_end_roll else unexpected(c) end else unexpected(c) end end def state_start_type(c = next_char) case c when (?a..?z), (?A..?Z), ?_ @damage_type = c.chr state_parse_type else state_end_roll(c) end end def state_parse_type(c = next_char) case c when (?a..?z), (?A..?Z), ?_ @damage_type += c.chr state_parse_type else state_continue_type(c) end end def state_end_type(c = next_char) case c when SPACE state_continue_type else add_element @calc, TypedSet, :damage_type => @damage_type @calc = @stack.pop state_next_part(c) end end def state_continue_type(c = next_char) case c when SPACE state_continue_type when ?a return unexpected(c) unless ?n === (c = next_char) return unexpected(c) unless ?d === (c = next_char) return unexpected(c) unless SPACE === (c = next_char) c = next_char while c == SPACE return unexpected(c) unless (?a..?z) === c || (?A..?Z) === c || ?_ === c @damage_type += ' and ' state_parse_type(c) else state_end_type(c) end end def add_element(element, set_class, *args) #p ['adding ', set_class, element.to_s] if(@stack.empty?) @stack << (set_class ? set_class.new(element, *args) : element) elsif set_class.nil? @stack.last << element while @stack.size > 1 && !(Brackets === @stack.last) pop = @stack.pop @stack.last << pop end else while set_class.after?(@stack.last) @stack.last << element element = @stack.pop end if(@stack.last && @stack.last.class == set_class) @stack.last << element else new = set_class.new(element, *args) @stack << new end end #p ['new stack', @stack.map(&:to_s)] end end end
true
471093acd1db22289ba872051e44e2229b34e144
Ruby
milo-codes/ecosystem_model_tdd_hw
/specs/bear_spec.rb
UTF-8
1,000
3.34375
3
[]
no_license
require("minitest/autorun") require("minitest/rg") require_relative("../bear.rb") require_relative("../river.rb") require_relative("../fish.rb") class BearTest < MiniTest::Test def setup() @bear1 = Bear.new("Yogi", "Grizzly", "Howdie!") @river1 = River.new("Elb", 27) @fish1 = Fish.new("Joe") end def test_has_name() assert_equal("Yogi", @bear1.name()) end def test_starts_with_empty_stomach() assert_equal(0, @bear1.stomach().length()) end def test_can_take_fish_from_river() @bear1.take_fish(@river1, @fish1) assert_equal(26, @river1.fish_count()) end def test_fish_now_in_stomach() @bear1.eat_fish(@fish1) assert_equal(1, @bear1.food_count()) end def test_stomach_empty_after_puke() @bear1.puke() assert_equal(0, @bear1.food_count()) end def test_roar() assert_equal("Howdie!", @bear1.roar()) end def test_change_roar() @bear1.change_roar("FEAR ME!") assert_equal("FEAR ME!", @bear1.roar()) end end
true
fac2188f701c9f9381594f460016b65d46c7d154
Ruby
makerscraft/labs_interview
/source/app/models/school.rb
UTF-8
241
2.5625
3
[]
no_license
class School < ActiveRecord::Base attr_accessible :name, :school_url, :school_img_url has_many :courses def self.short_school_name(school_name) max_school_name_length = 39 school_name.slice(0, max_school_name_length) end end
true
05dcda0eb681ae6f7ef5dd855b3d89814b77ef1d
Ruby
ilke-zilci/sdl-ng
/lib/sdl/types/sdl_type.rb
UTF-8
548
2.796875
3
[ "Apache-2.0" ]
permissive
## # An SDLType is a wrapper around a basic Ruby type module SDL::Types::SDLType def self.included(base) base.extend ClassMethods end module ClassMethods ## The Ruby type, which is to be wrapped attr :wrapped_type ## The codes, which are to be used to refer to this type attr :codes ## # Sets the wrapped Ruby type def wraps(type) @wrapped_type = type end ## # Registers the codes +symbols+ to be used to refer to this type def codes(*symbols) @codes = symbols end end end
true
09de5b5ee354eb96ef23bdf91f8736d795203efa
Ruby
Shopify/liquid
/test/integration/tags/if_else_tag_test.rb
UTF-8
9,528
2.59375
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'test_helper' class IfElseTagTest < Minitest::Test include Liquid def test_if assert_template_result(' ', ' {% if false %} this text should not go into the output {% endif %} ') assert_template_result( ' this text should go into the output ', ' {% if true %} this text should go into the output {% endif %} ', ) assert_template_result(' you rock ?', '{% if false %} you suck {% endif %} {% if true %} you rock {% endif %}?') end def test_literal_comparisons assert_template_result(' NO ', '{% assign v = false %}{% if v %} YES {% else %} NO {% endif %}') assert_template_result(' YES ', '{% assign v = nil %}{% if v == nil %} YES {% else %} NO {% endif %}') end def test_if_else assert_template_result(' YES ', '{% if false %} NO {% else %} YES {% endif %}') assert_template_result(' YES ', '{% if true %} YES {% else %} NO {% endif %}') assert_template_result(' YES ', '{% if "foo" %} YES {% else %} NO {% endif %}') end def test_if_boolean assert_template_result(' YES ', '{% if var %} YES {% endif %}', { 'var' => true }) end def test_if_or assert_template_result(' YES ', '{% if a or b %} YES {% endif %}', { 'a' => true, 'b' => true }) assert_template_result(' YES ', '{% if a or b %} YES {% endif %}', { 'a' => true, 'b' => false }) assert_template_result(' YES ', '{% if a or b %} YES {% endif %}', { 'a' => false, 'b' => true }) assert_template_result('', '{% if a or b %} YES {% endif %}', { 'a' => false, 'b' => false }) assert_template_result(' YES ', '{% if a or b or c %} YES {% endif %}', { 'a' => false, 'b' => false, 'c' => true }) assert_template_result('', '{% if a or b or c %} YES {% endif %}', { 'a' => false, 'b' => false, 'c' => false }) end def test_if_or_with_operators assert_template_result(' YES ', '{% if a == true or b == true %} YES {% endif %}', { 'a' => true, 'b' => true }) assert_template_result(' YES ', '{% if a == true or b == false %} YES {% endif %}', { 'a' => true, 'b' => true }) assert_template_result('', '{% if a == false or b == false %} YES {% endif %}', { 'a' => true, 'b' => true }) end def test_comparison_of_strings_containing_and_or_or awful_markup = "a == 'and' and b == 'or' and c == 'foo and bar' and d == 'bar or baz' and e == 'foo' and foo and bar" assigns = { 'a' => 'and', 'b' => 'or', 'c' => 'foo and bar', 'd' => 'bar or baz', 'e' => 'foo', 'foo' => true, 'bar' => true } assert_template_result(' YES ', "{% if #{awful_markup} %} YES {% endif %}", assigns) end def test_comparison_of_expressions_starting_with_and_or_or assigns = { 'order' => { 'items_count' => 0 }, 'android' => { 'name' => 'Roy' } } assert_template_result( "YES", "{% if android.name == 'Roy' %}YES{% endif %}", assigns, ) assert_template_result( "YES", "{% if order.items_count == 0 %}YES{% endif %}", assigns, ) end def test_if_and assert_template_result(' YES ', '{% if true and true %} YES {% endif %}') assert_template_result('', '{% if false and true %} YES {% endif %}') assert_template_result('', '{% if true and false %} YES {% endif %}') end def test_hash_miss_generates_false assert_template_result('', '{% if foo.bar %} NO {% endif %}', { 'foo' => {} }) end def test_if_from_variable assert_template_result('', '{% if var %} NO {% endif %}', { 'var' => false }) assert_template_result('', '{% if var %} NO {% endif %}', { 'var' => nil }) assert_template_result('', '{% if foo.bar %} NO {% endif %}', { 'foo' => { 'bar' => false } }) assert_template_result('', '{% if foo.bar %} NO {% endif %}', { 'foo' => {} }) assert_template_result('', '{% if foo.bar %} NO {% endif %}', { 'foo' => nil }) assert_template_result('', '{% if foo.bar %} NO {% endif %}', { 'foo' => true }) assert_template_result(' YES ', '{% if var %} YES {% endif %}', { 'var' => "text" }) assert_template_result(' YES ', '{% if var %} YES {% endif %}', { 'var' => true }) assert_template_result(' YES ', '{% if var %} YES {% endif %}', { 'var' => 1 }) assert_template_result(' YES ', '{% if var %} YES {% endif %}', { 'var' => {} }) assert_template_result(' YES ', '{% if var %} YES {% endif %}', { 'var' => [] }) assert_template_result(' YES ', '{% if "foo" %} YES {% endif %}') assert_template_result(' YES ', '{% if foo.bar %} YES {% endif %}', { 'foo' => { 'bar' => true } }) assert_template_result(' YES ', '{% if foo.bar %} YES {% endif %}', { 'foo' => { 'bar' => "text" } }) assert_template_result(' YES ', '{% if foo.bar %} YES {% endif %}', { 'foo' => { 'bar' => 1 } }) assert_template_result(' YES ', '{% if foo.bar %} YES {% endif %}', { 'foo' => { 'bar' => {} } }) assert_template_result(' YES ', '{% if foo.bar %} YES {% endif %}', { 'foo' => { 'bar' => [] } }) assert_template_result(' YES ', '{% if var %} NO {% else %} YES {% endif %}', { 'var' => false }) assert_template_result(' YES ', '{% if var %} NO {% else %} YES {% endif %}', { 'var' => nil }) assert_template_result(' YES ', '{% if var %} YES {% else %} NO {% endif %}', { 'var' => true }) assert_template_result(' YES ', '{% if "foo" %} YES {% else %} NO {% endif %}', { 'var' => "text" }) assert_template_result(' YES ', '{% if foo.bar %} NO {% else %} YES {% endif %}', { 'foo' => { 'bar' => false } }) assert_template_result(' YES ', '{% if foo.bar %} YES {% else %} NO {% endif %}', { 'foo' => { 'bar' => true } }) assert_template_result(' YES ', '{% if foo.bar %} YES {% else %} NO {% endif %}', { 'foo' => { 'bar' => "text" } }) assert_template_result(' YES ', '{% if foo.bar %} NO {% else %} YES {% endif %}', { 'foo' => { 'notbar' => true } }) assert_template_result(' YES ', '{% if foo.bar %} NO {% else %} YES {% endif %}', { 'foo' => {} }) assert_template_result(' YES ', '{% if foo.bar %} NO {% else %} YES {% endif %}', { 'notfoo' => { 'bar' => true } }) end def test_nested_if assert_template_result('', '{% if false %}{% if false %} NO {% endif %}{% endif %}') assert_template_result('', '{% if false %}{% if true %} NO {% endif %}{% endif %}') assert_template_result('', '{% if true %}{% if false %} NO {% endif %}{% endif %}') assert_template_result(' YES ', '{% if true %}{% if true %} YES {% endif %}{% endif %}') assert_template_result(' YES ', '{% if true %}{% if true %} YES {% else %} NO {% endif %}{% else %} NO {% endif %}') assert_template_result(' YES ', '{% if true %}{% if false %} NO {% else %} YES {% endif %}{% else %} NO {% endif %}') assert_template_result(' YES ', '{% if false %}{% if true %} NO {% else %} NONO {% endif %}{% else %} YES {% endif %}') end def test_comparisons_on_null assert_template_result('', '{% if null < 10 %} NO {% endif %}') assert_template_result('', '{% if null <= 10 %} NO {% endif %}') assert_template_result('', '{% if null >= 10 %} NO {% endif %}') assert_template_result('', '{% if null > 10 %} NO {% endif %}') assert_template_result('', '{% if 10 < null %} NO {% endif %}') assert_template_result('', '{% if 10 <= null %} NO {% endif %}') assert_template_result('', '{% if 10 >= null %} NO {% endif %}') assert_template_result('', '{% if 10 > null %} NO {% endif %}') end def test_else_if assert_template_result('0', '{% if 0 == 0 %}0{% elsif 1 == 1%}1{% else %}2{% endif %}') assert_template_result('1', '{% if 0 != 0 %}0{% elsif 1 == 1%}1{% else %}2{% endif %}') assert_template_result('2', '{% if 0 != 0 %}0{% elsif 1 != 1%}1{% else %}2{% endif %}') assert_template_result('elsif', '{% if false %}if{% elsif true %}elsif{% endif %}') end def test_syntax_error_no_variable assert_raises(SyntaxError) { assert_template_result('', '{% if jerry == 1 %}') } end def test_syntax_error_no_expression assert_raises(SyntaxError) { assert_template_result('', '{% if %}') } end def test_if_with_custom_condition original_op = Condition.operators['contains'] Condition.operators['contains'] = :[] assert_template_result('yes', %({% if 'bob' contains 'o' %}yes{% endif %})) assert_template_result('no', %({% if 'bob' contains 'f' %}yes{% else %}no{% endif %})) ensure Condition.operators['contains'] = original_op end def test_operators_are_ignored_unless_isolated original_op = Condition.operators['contains'] Condition.operators['contains'] = :[] assert_template_result( 'yes', %({% if 'gnomeslab-and-or-liquid' contains 'gnomeslab-and-or-liquid' %}yes{% endif %}), ) ensure Condition.operators['contains'] = original_op end def test_operators_are_whitelisted assert_raises(SyntaxError) do assert_template_result('', %({% if 1 or throw or or 1 %}yes{% endif %})) end end def test_multiple_conditions tpl = "{% if a or b and c %}true{% else %}false{% endif %}" tests = { [true, true, true] => true, [true, true, false] => true, [true, false, true] => true, [true, false, false] => true, [false, true, true] => true, [false, true, false] => false, [false, false, true] => false, [false, false, false] => false, } tests.each do |vals, expected| a, b, c = vals assigns = { 'a' => a, 'b' => b, 'c' => c } assert_template_result(expected.to_s, tpl, assigns, message: assigns.to_s) end end end
true
224b584e22675b6a6c857eacd58946819d111952
Ruby
kamarsh1/connect-four
/spec/human_player_spec.rb
UTF-8
767
3.296875
3
[]
no_license
require_relative '../app/models/player' require_relative '../app/models/human_player' describe 'HumanPlayer' do let(:some_name) { 'Charmander' } let(:color) { 'Orange' } let(:humanPlayer) { HumanPlayer.new(some_name, color) } let(:pick_col_message) { "#{some_name} pick a column (1 through 7)\n" } describe 'pick_a_column' do before do allow(humanPlayer).to receive(:gets).and_return('2') end it 'asks the player to pick a column' do current_player = humanPlayer expect { current_player.pick_a_column(current_player) }.to output(pick_col_message).to_stdout end it 'gets a number from input' do current_player = humanPlayer expect(current_player.pick_a_column(current_player)).to eq(2) end end end
true
9a77d30cdb057a10bd419cca473ab05ba386b652
Ruby
brittmmendez/oo-kickstarter-v-000
/lib/backer.rb
UTF-8
209
2.703125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Backer attr_accessor :backed_projects, :name def initialize(name) @name=name @backed_projects=[] end def back_project(project) @backed_projects<<project project.backers<<self end end
true
898d0997c3b2d4c6dc87b53e99cef440d7be0c47
Ruby
eval/mollie-payment
/spec/mollie/ideal_spec.rb
UTF-8
2,353
2.53125
3
[ "MIT" ]
permissive
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe Mollie::Ideal do context "#banks" do it "returns an array with hashes containing keys :id and :name" do VCR.use_cassette('banks') do banks = described_class.banks banks.class.should == Array banks.first.keys.should =~ [:id, :name] end end end context "#request_transaction" do subject{ Mollie::Ideal.new('123456')} it "should return a hash with the correct keys and values" do VCR.use_cassette('request_transaction') do t = subject.request_transaction(:amount => 12345, :bank_id => '0031', :description => 'description goes here', :report_url => 'http://example.org/report', :return_url => 'http://example.org/return') t.class.should == Hash expected_keys_with_values = {:transaction_id => nil, :amount => 12345, :currency => 'EUR', :url => nil} check_hash_keys_and_values(t, expected_keys_with_values) end end end context "#verify_transaction" do subject{ Mollie::Ideal.new('123456')} it "should return a hash with the correct keys and values" do VCR.use_cassette('verify_transaction') do t = subject.verify_transaction(:transaction_id => 'e0be830d5e46289e7da9636beb84729e') t.class.should == Hash expected_keys_with_values = {:transaction_id => 'e0be830d5e46289e7da9636beb84729e', :amount => 12345, :currency => 'EUR', :payed => false, :status => 'CheckedBefore'} check_hash_keys_and_values(t, expected_keys_with_values) end end end protected # Checks target for: # - existance of supplied keys # - value for given key if supplied # # @example passing example # check_hash_keys_and_values({:a => 1, :b => 'anything'}, {:a => 1, :b => nil}) def check_hash_keys_and_values(target, keys_and_values) keys_and_values.each do |key, value| if value target[key].should == value else target.keys.should include(key) end end end end
true
2cb80c593c962ea4c711c4f936f91f2af6e8b65b
Ruby
Jbeltrez/oo-inheritance-code-along-onl01-seng-pt-070620
/lib/car.rb
UTF-8
505
3.953125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require_relative "./vehicle.rb" class Car < Vehicle def go "VRRROOOOOOOOOOOOOOOOOOOOOOOM!!!!!" end end #Well, when your program is being executed, at the point at which the #go method is invoked, the compiler will first look in the class to which the instance of car that we are calling the method on belongs. If it finds a #go method there, it will execute that method. If it doesn't find such a method there, it will move on to look in the parent class that this class inherits from.
true
45004d5ef703224915bd2754c32cce45b0d5fb05
Ruby
brianqhe/terminal-card-app
/src/spec/test_spec.rb
UTF-8
726
3.15625
3
[]
no_license
require_relative '../model/game' # Rspec test to ensure a random card is picked from its corresponding value describe 'card number' do it 'picks a key in a hash' do expect(Game.random_key({'key' => 'value'})).to eq('key') expect(Game.random_key({'key1' => 'value 1', 'key2' => 'value2'})).to eq('key1').or(eq('key2')) end end # Rspec test to make sure a random suit is picked correctly describe 'select suit' do it 'picks a suit from the array' do expect(Game.random_suit(["A"])).to eq("A") expect(Game.random_suit(["A", "B"])).to eq("A").or(eq("B")) expect(Game.random_suit(["♠", "♦", "♥", "♣"])).to eq("♠").or(eq("♦")).or(eq("♥")).or(eq("♣")) end end
true
5c15174ec5f544957811b6f506f5ce53b2327a3e
Ruby
chihaso/memo_app
/lib/memo.rb
UTF-8
503
2.71875
3
[]
no_license
# frozen_string_literal: true require "securerandom" module MyMemoApp class Memo def initialize(path) @path = path end def save(memo_text) File.open("#{@path}#{SecureRandom.uuid}", "w", 0o0666) do |file| file.puts memo_text end end def memo_text File.read(@path) end def memo_text_show File.read(@path).gsub("\n", "<br>") end def edit(new_text) File.open(@path, "w") { |file| file.puts new_text } end end end
true
d53381b388f50f542b40714163ef75946950735b
Ruby
Contactability/em-synchrony
/examples/all.rb
UTF-8
1,078
2.53125
3
[ "MIT" ]
permissive
require "lib/em-synchrony" EM.synchrony do # open 4 concurrent MySQL connections db = EventMachine::Synchrony::ConnectionPool.new(size: 4) do EventMachine::MySQL.new(host: "localhost") end # perform 4 http requests in parallel, and collect responses multi = EventMachine::Synchrony::Multi.new multi.add :page1, EventMachine::HttpRequest.new("http://service.com/page1").aget multi.add :page2, EventMachine::HttpRequest.new("http://service.com/page2").aget multi.add :page3, EventMachine::HttpRequest.new("http://service.com/page3").aget multi.add :page4, EventMachine::HttpRequest.new("http://service.com/page4").aget data = multi.perform.responses[:callback].values # insert fetched HTTP data into a mysql database, using at most 2 connections at a time # - note that we're writing async code within the callback! EM::Synchrony::Iterator.new(data, 2).each do |page, iter| db.async_query("INSERT INTO table (data) VALUES(#{page});") db.callback { iter.return(http) } end puts "All done! Stopping event loop." EventMachine.stop end
true
2ddc7577c86ef6eb5450a0dc9d6bf18ed13285af
Ruby
mahendhar9/programming_problems
/fibonacci_sequence_generator.rb
UTF-8
490
4.3125
4
[]
no_license
# Build a method that returns an array of the Fibonacci sequence of a pre-defined number of values. # Input # fibonacci 10 # Expected Output # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] require 'rspec' def fibonacci(num) (1..num).inject([0, 1]) {|arr| arr << arr.last(2).inject(:+)} end # print fibonacci(10) describe "fibonacci" do it "returns an array of the fibonacci sequence given a value" do expect(fibonacci(10)).to eq([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]) end end
true
d24ec7ad976a88267720b3a494d7b37d118f3e09
Ruby
chandley/precourse
/Hardway/adventure.rb
UTF-8
1,288
3.59375
4
[]
no_license
rooms = ['inventory','dining room','kitchen','drawing room','hall'] room_moves = [{},{"n" => 3, "e" => 2},{'w' => 1},{'n' => 4, 's' => 1},{'s' => 3}] items = {'plate of food' => 1, 'butter knife' =>1, 'sofa' => 3} monsters = {'hobgoblin' => 2} def show_room room_number, rooms, room_moves, items, monsters puts "You are in the #{rooms[room_number]}" room_moves[room_number].each do |direction,new_room| puts "you see an exit #{direction.upcase}" end items.each {|item,location| puts ("there is " + item) if location==room_number} monsters.each {|monster,location| puts (monster + " goes AARGH") if location==room_number} end def move_room room_number, direction, room_moves new_room = room_moves[room_number][direction] # need to add check if new room no good # new_room = room_number if new_room < 1 end def user_move room_number, room_moves puts "which direction" print "> " new_room = move_room room_number,$stdin.gets.chomp,room_moves # new_room = room_number if new_room.nil? # not a good check if new_room.nil? new_room = room_number end return new_room end current_room = 1 (1..3).each do |i| show_room current_room, rooms, room_moves, items, monsters current_room = user_move current_room, room_moves end
true
488f2ce77a554cb5b3275525f25c971a73ac6a95
Ruby
millarj/tealeaf_ruby_exercises
/exercises/solution_10.rb
UTF-8
295
3.4375
3
[]
no_license
hash_with_array_values = {teams: ['Packers', 'Seahawks', '49ers']} # hash values as arrays puts hash_with_array_values puts hash_with_array_values.class array_of_hashes = [{model: 'Toyota'}, {model: 'Jeep'}, {model: 'Range Rover'}] # array of hashes p array_of_hashes p array_of_hashes.class
true
7137306dc5a7cf042936422dbb384689f30b6980
Ruby
jaimelr/game-of-life
/lib/life.rb
UTF-8
5,145
3.71875
4
[]
no_license
class Board attr_accessor :array, :width, :height def initialize(width, height) @width = width @height = height @array = Array.new(@width) do Array.new(@height) { Cell.new(rand(0..1)) } end end def reset @array.each do |row| row.each { |cell| cell.id = 0 } end end def display @array.each do |row| row.each { |cell| print cell.id } print "\n" end end end class Cell attr_accessor :id def initialize(id) @id = id end def is_alive? if @id != 0 return true end return false end def dies @id = 0 end def resuscitates @id = 1 end end class Game attr_reader :board def initialize(board) @board = board @temp_board = Marshal::load(Marshal.dump(board)) @temp_board.reset end def play(loop_size) loop_size.times do thick @board = Marshal::load(Marshal.dump(@temp_board)) @board.display @temp_board.reset sleep 0.5 system('clear') end end def thick @board.array.each_with_index do |row, y| row.each_with_index do |cell, x| neighborhood = get_neighborhood(x, y) if cell.is_alive? if deserves_to_die?(neighborhood) @temp_board.array[y][x].dies else @temp_board.array[y][x].id = 1 end else if deserves_to_revive?(neighborhood) @temp_board.array[y][x].resuscitates else @temp_board.array[y][x].id = 0 end end end end end private def get_neighborhood(x, y) neighborhood = Array.new coordinates = { x: x - 1, y: y - 1 } 3.times do 3.times do if outter_coordinates?(coordinates) neighborhood << Cell.new(0) else if coordinates[:x] == x && coordinates[:y] == y coordinates[:x] += 1 next end neighborhood.push(board.array[coordinates[:y]][coordinates[:x]]) end coordinates[:x] += 1 end coordinates[:x] = x -1 coordinates[:y] += 1 end return neighborhood end def outter_coordinates?(coordinates) if coordinates[:x] < 0 || coordinates[:x] > board.width - 1 || coordinates[:y] < 0 || coordinates[:y] > board.height - 1 return true end return false end def deserves_to_die?(neighborhood) points = 0 neighborhood.each { |cell| points += 1 if cell.is_alive? } return true if points < 2 || points > 3 return false if points == 2 || points == 3 end def deserves_to_revive?(neighborhood) points = 0 neighborhood.each { |cell| points += 1 if cell.is_alive? } return true if points == 3 return false end end class Life def self.start puts 'Conway\'s Game of Life - JJaimelr version' puts 'WELCOME' puts 'Please choose an option to watch the game in action' puts '[1] random' puts '[2] pattern' option = gets.chomp.to_s case option when 'random', '1' puts 'Enter the loop size' loop_size = gets.chomp.to_i board = Board.new(40, 40) blinkerBoard = Board.new(5, 5) board.display game = Game.new(board) game.play loop_size when 'pattern', '2' self.watch_pattern else puts '*Confused* Do you enter the number (or name) of the option? If so, could you please try again?' end end def self.watch_pattern puts 'Enter the name or the number of the pattern' puts '[1] blinker' puts '[2] beacon' puts '[3] block' puts '[4] pulsar' puts '[5] glider' pattern = gets.chomp puts 'Enter the loop size' loop_size = gets.chomp.to_i case pattern when 'blinker', '1' board = Board.new(5, 5) board.reset board.array[2][1] = Cell.new(1) board.array[2][2] = Cell.new(1) board.array[2][3] = Cell.new(1) when 'beacon', '2' board = Board.new(6, 6) board.reset board.array[1][1] = Cell.new(1) board.array[1][2] = Cell.new(1) board.array[2][1] = Cell.new(1) board.array[4][3] = Cell.new(1) board.array[4][4] = Cell.new(1) board.array[3][4] = Cell.new(1) when 'block', '3' board = Board.new(4, 4) board.reset board.array[1][1] = Cell.new(1) board.array[1][2] = Cell.new(1) board.array[2][1] = Cell.new(1) board.array[2][2] = Cell.new(1) when 'pulsar', '4' board = Board.new(6, 6) board.reset board.array[2][2] = Cell.new(1) board.array[2][3] = Cell.new(1) board.array[2][4] = Cell.new(1) board.array[3][1] = Cell.new(1) board.array[3][2] = Cell.new(1) board.array[3][3] = Cell.new(1) when 'glider', '5' board = Board.new(20, 20) board.reset board.array[1][2] = Cell.new(1) board.array[2][3] = Cell.new(1) board.array[3][1] = Cell.new(1) board.array[3][2] = Cell.new(1) board.array[3][3] = Cell.new(1) board.display else puts 'Pattern not found' end game = Game.new(board) board.display game.play loop_size end end Life.start
true
e88def9d4ea72dd69219583553c7c860f73400bc
Ruby
marcjrayner/OO_karaoke_practice
/guest.rb
UTF-8
160
2.671875
3
[]
no_license
class Guest attr_reader :name, :fav_song def initialize(name, wallet, fav_song) @name = name @wallet = wallet @fav_song = fav_song end end
true
7083da9f568150ee1a1e0ba402cb7ae5ce9f5b14
Ruby
artyom-ukhabin/AdviceMeAgain
/app/services/content_based_filtering/vector_objects/user_content_preference.rb
UTF-8
2,034
2.828125
3
[]
no_license
module ContentBasedFiltering module VectorObjects class UserContentPreference #TODO: dependencies #TODO: 1) content genres #TODO: 2) content vectors #TODO: 3) content rates => likes DATASTORE_CONNECTOR_CLASS = DatastoreConnectors::UserContentPreferencesConnector INITIAL_VECTOR_VALUE = 0 def initialize @datastore_connector = DATASTORE_CONNECTOR_CLASS.new @content_vectors_datastore = VectorObjects::Content::DATASTORE_CONNECTOR_CLASS.new end def update(user, content_type) user_vector = build_user_vector(user, content_type) update_datastore(user, content_type, user_vector) end def destroy(user_id) @datastore_connector.destroy(user_id) end private def build_user_vector(user, content_type) raw_vector = raw_user_vector(content_type) fill_raw_vector(user, content_type, raw_vector) end def raw_user_vector(content_type) type_genres = "#{content_type.camelize}Genre".constantize.all type_genres.inject({}) do |raw_vector, genre| raw_vector.merge({ genre.name => INITIAL_VECTOR_VALUE }) end end def fill_raw_vector(user, content_type, raw_vector) content_rates = user.content_rates.with_type(content_type) content_rates.each do |rate| content_vector = @content_vectors_datastore.vector_for(rate.content_id, content_type) raw_vector.each do |genre_name, value| raw_vector[genre_name] = accumulate_content_value(value, content_vector[genre_name], rate) end end raw_vector end def accumulate_content_value(user_value, content_value, rate) if rate.high? user_value + content_value elsif rate.low? user_value - content_value end end def update_datastore(user, content_type, user_vector) @datastore_connector.update(user, content_type, user_vector) end end end end
true
bd70a74aa34eb7f51d2b6087b0ee530b3a006e77
Ruby
ahamedali95/dice-roll-ruby-prework
/dice_roll.rb
UTF-8
242
3.890625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Create method `roll` that returns a random number between 1 and 6 # Feel free to google "how to generate a random number in ruby" # def roll # rand(1...7) # end # # # puts roll() def roll nums = Array (1...7) nums[rand(0...6)] end
true
0d0a37ba90edea7b7d2b6ab58251f157f4d6e131
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/gigasecond/d6efb0026bad44a184d082e9cac1c26a.rb
UTF-8
113
2.8125
3
[]
no_license
require 'date' require 'time' class Gigasecond def self.from(date) date + (10**9) / (24*60*60) end end
true
68dacbd744d5c3f7c422adf579b63e7344e0be3b
Ruby
MarvinClerge/OO-mini-project-web-112017
/app/models/RecipeIngredient.rb
UTF-8
398
3.21875
3
[]
no_license
class RecipeIngredient @@all = [] attr_accessor :recipe, :ingredient def initialize(recipe: nil, ingredient: nil) @recipe = recipe @ingredient = ingredient @@all << self end def self.all @@all end def self.recipes self.all.map do |inst| inst.recipe end end def self.ingredients self.all.map do |inst| inst.ingredient end end end
true
2769e3734d905368c92451524df753fe44124fb2
Ruby
ivncastillo/desafio_patrones_anidados
/patrones.rb
UTF-8
2,922
3.125
3
[]
no_license
def letra_o(n) # Parte superior n.times do print "*" end print "\n" # Parte del medio (n - 2).times do print "*" (n - 2).times do print " " end print "*" print "\n" end # Parte inferior n.times do print "*" end end def letra_i(n) # Parte superior n.times do print "*" end print "\n" # Parte del medio (n - 1).times do (n/2).times do print " " end print "*" (n/2 - 1).times do print " " end print "\n" end # Parte inferior n.times do print "*" end end def letra_z(n) # Parte superior n.times do print "*" end print "\n" # Parte del medio k=0 (n - 2).times do k+=1 (n).times do |i| if (i+1)==n-k print "*" else print " " end end print "\n" end # Parte inferior n.times do print "*" end end def letra_x(n) # Parte superior k=0 n/2.times do k+=1 n.times do |i| if i+1==k || n-i==k print "*" else print " " end end print "\n" end # Parte medio n.times do |i| if (i+1)==n/2+1 print "*" else print " " end end print "\n" # Parte inferior k=n n/2.times do k-=2 n.times do |i| if i+1==k || n-i==k print "*" else print " " end end print "\n" end end def numero_cero(n) # Parte superior n.times do print "*" end print "\n" # Parte del medio k=0 (n - 2).times do print "*" k+=1 (n - 2).times do |i| if (i+1)==k print "*" else print " " end end print "*" print "\n" end # Parte inferior n.times do print "*" end end def navidad(n) #parte superior k=n-2 n-3.times do k=k-1 contador_vacios=0 n.times do |i| if contador_vacios<k print " " contador_vacios+=1 else print "*" contador_vacios=0 end end print "\n" end #tronco (n - 3).times do (n/2).times do print " " end print "*" (n/2 - 1).times do print " " end print "\n" end #base n.times do |i| if (i+1)>n-4 && (i+1)<=n-1 print "*" else print " " end end end
true
2ff13e7e334071615ef923a6056784b9125c23ee
Ruby
paulmillen/tic_tac_toe
/lib/board.rb
UTF-8
1,568
3.546875
4
[]
no_license
class Board attr_reader :grid def initialize @grid = [ [1,1,1], [1,1,1], [1,1,1] ]; end def claim_field(row, column, player) fail ArgumentError, 'field occupied' if field_occupied?(row, column) @grid[row][column] = player return "#{player.to_s} Wins" if winner? return 'Draw' if draw? end private def field_occupied?(row, column) @grid[row][column] != 1 end def winner? @grid.each do |row| return true if row.all? { |field| field === :X } return true if row.all? { |field| field === :O } end return true if @grid[0][0] === :X && @grid[1][0] === :X && @grid[2][0] === :X return true if @grid[0][0] === :O && @grid[1][0] === :O && @grid[2][0] === :O return true if @grid[0][1] === :X && @grid[1][1] === :X && @grid[2][1] === :X return true if @grid[0][1] === :O && @grid[1][1] === :O && @grid[2][1] === :O return true if @grid[0][2] === :X && @grid[1][2] === :X && @grid[2][2] === :X return true if @grid[0][2] === :O && @grid[1][2] === :O && @grid[2][2] === :O return true if @grid[0][0] === :X && @grid[1][1] === :X && @grid[2][2] === :X return true if @grid[0][0] === :O && @grid[1][1] === :O && @grid[2][2] === :O return true if @grid[0][2] === :X && @grid[1][1] === :X && @grid[2][0] === :X return true if @grid[0][2] === :O && @grid[1][1] === :O && @grid[2][0] === :O false end def draw? @grid.each do |row| row.each do |field| return false if field === 1 end end true end end
true
f2e180da2f5137f1951a52029db2cbde6ac56b3f
Ruby
prashantmukhopadhyay/Cats2
/app/models/cat.rb
UTF-8
352
2.796875
3
[]
no_license
class Cat < ActiveRecord::Base COLORS = ["black","brown","white", "spotted"] SEX = ["M","F"] attr_accessible :age, :birth_date, :color, :name, :sex validates :age, :birth_date, :color, :name, :sex, presence: true validates :age, numericality: true validates :color, inclusion: { in: COLORS } validates :sex, inclusion: { in: SEX } end
true
7343b0383d4c5c37dff3bec5fae7bf9f9df289ab
Ruby
jfoong/ruby-ucsc-api
/lib/ucsc/hg18/activerecord.rb
UTF-8
15,906
3.078125
3
[]
no_license
def overlap_sql(slice, start, stop) ' WHERE chrom = "' + slice.chromosome + '" AND ((chromStart BETWEEN ' + start.to_s + ' AND ' + stop.to_s + ')' + ' OR (chromEnd BETWEEN ' + start.to_s + ' AND ' + stop.to_s + ')' + ' OR (chromStart <= ' + start.to_s + ' AND chromEnd >= ' + stop.to_s + ')' + ' );' end # # = ucsc/hg18/activerecord.rb - ActiveRecord mappings to UCSC hg18 database # # Copyright:: Copyright (C) 2008 Jan Aerts <jan.aerts@gmail.com> # License:: The Ruby License # # = DESCRIPTION # == What is it? # The UCSC module provides an API to the UCSC databases # stored at genome-mysql.cse.ucsc.edu. This is the same information that is # available from http://genome.ucsc.edu # # The Ucsc::Hg18 module covers the hg18 (= NCBI build 36) assembly. # # == ActiveRecord # The UCSC API provides a ruby interface to the UCSC mysql databases # at genome-mysql.cse.ucsc.edu. Most of the API is based on ActiveRecord to # get data from that database. In general, each table is described by a # class with the same name: the cnpRedon table is covered by the # CnpRedon class, the dgv table is covered by the Dgv class, # etc. As a result, accessors are available for all columns in each table. # For example, the cnpRedon table has the following columns: chrom, chromStart, # chromEnd and name. Through ActiveRecord, these column names become available # as attributes of CnpRedon objects: # puts my_cnp_redon.name # puts my_cnp_redon.chrom # puts my_cnp_redon.chromStart # puts my_cnp_redon.chromEnd # # ActiveRecord makes it easy to extract data from those tables using the # collection of #find methods. There are three types of #find methods (e.g. # for the CnpRedon class): # a. find based on primary key in table: # # not possible with the UCSC database # b. find_by_sql: # my_cnp = CnpRedon.find_by_sql('SELECT * FROM cnpRedon WHERE name = 'cnp1'") # c. find_by_<insert_your_column_name_here> # my_cnp = CnpRedon.find_by_name('cnp1') # my_cnp2 = CnpRedon.find_by_chrom_and_chromStart('chr1',377) # To find out which find_by_<column> methods are available, you can list the # column names using the column_names class methods: # # puts Ucsc::Hg18::CnpRedon.column_names.join("\t") # # For more information on the find methods, see # http://ar.rubyonrails.org/classes/ActiveRecord/Base.html#M000344 # module Ucsc # = DESCRIPTION # The Ucsc::Hg18 module covers the hg18 database from # genome-mysql.cse.ucsc.edu and covers mainly sequences and their annotations. # For a more information about the database tables, click on the "Describe # table schema" in the Table Browser. module Hg18 # = DESCRIPTION # The Sliceable mixin holds the get_slice method and can be included # in any class that lends itself to having a position on a chromosome. module Sliceable def slice start, stop, strand = nil, nil, nil if self.class.column_names.include?('chromStart') start = self.chromStart end if self.class.column_names.include?('chromEnd') stop = self.chromEnd end if self.class.column_names.include?('strand') strand = self.strand end return Ucsc::Hg18::Slice.new(self.chrom, Range.new(start.to_i, stop.to_i), strand) end end # = DESCRIPTION # The Feature mixin holds common methods for all feature-like classes, such # as how to print itself to the screen. module Feature include Sliceable def to_s return self.class.to_s + "\t" + self.slice.to_s + "\t" + self.name end end # = DESCRIPTION # From Structural Variants description page when clicking the "Describe # table schema" in the table browser: # "All hybridizations were performed in duplicate incorporating a # dye-reversal using proprietary 1 Mb GenomeChip V1.2 Human BAC Arrays # consisting of 2,632 BAC clones (Spectral Genomics, Houston, TX). The # false positive rate was estimated at ~1 clone per 5,264 tested." class CnpIafrate < DBConnection include Ucsc::Hg18::Feature set_table_name 'cnpIafrate2' set_primary_key nil def self.find_by_slice(slice) start = slice.range.begin stop = slice.range.end return CnpIafrate.find_by_sql('SELECT * FROM cnpIafrate' + overlap_sql(slice, start, stop)) end end # = DESCRIPTION # From Structural Variants description page when clicking the "Describe # table schema" in the table browser: # "DNA samples were obtained from Coriell Cell Repositories. The reference # DNA used for all hybridizations was from a single male of Czechoslovakian # descent, Coriell ID GM15724 (also used in the Sharp study). # # A locus was considered a CNV (copy number variation) if the log ratio of # fluroescence measurements for the individuals assayed exceeded twice the # standard deviation of the autosomal clones in replicate dye-swapped # experiments. A CNV was classified as a CNP if altered copy number was # observed in more than 1% of the 269 individuals." class CnpLocke < DBConnection include Ucsc::Hg18::Feature set_table_name 'cnpLocke' set_primary_key nil def self.find_by_slice(slice) start = slice.range.begin stop = slice.range.end return CnpLocke.find_by_sql('SELECT * FROM cnpLocke' + overlap_sql(slice, start, stop)) end end # = DESCRIPTION # From Structural Variants description page when clicking the "Describe # table schema" in the table browser: # "Experiments were performed with the International HapMap DNA and # cell-line collection using two technologies: comparative analysis of # hybridization intensities on Affymetric GeneChip Human Mapping 500K early # access arrays (500K EA) and comparative genomic hybridization with a # Whole Genome TilePath (WGTP) array." class CnpRedon < DBConnection include Ucsc::Hg18::Feature set_table_name 'cnpRedon' set_primary_key nil def self.find_by_slice(slice) start = slice.range.begin stop = slice.range.end return CnpRedon.find_by_sql('SELECT * FROM cnpRedon' + overlap_sql(slice, start, stop)) end end # = DESCRIPTION # From Structural Variants description page when clicking the "Describe # table schema" in the table browser: # "Following digestion with BglII or HindIII, genomic DNA was hybridized to # a custom array consisting of 85,000 oligonucleotide probes. The probes # were selected to be free of common repeats and have unique homology # within the human genome. The average resolution of the array was ~35kb; # however, only intervals in which three consecutive probes showed # concordant signals were scored as CNPs. All hybridizations were performed # in duplicate incorporating a dye-reversal, with the false positive rate # estimated to be ~6%." class CnpSebat < DBConnection include Ucsc::Hg18::Feature set_table_name 'cnpSebat2' set_primary_key nil def self.find_by_slice(slice) start = slice.range.begin stop = slice.range.end return CnpSebat.find_by_sql('SELECT * FROM cnpSebat2' + overlap_sql(slice, start, stop)) end end # = DESCRIPTION # From Structural Variants description page when clicking the "Describe # table schema" in the table browser: # "All hybridizations were performed in duplicate incorporating a # dye-reversal using a custom array consisting of 2,194 end-sequence or # FISH-confirmed BACs, targeted to regions of the genome flanked by # segmental duplications. The false positive rate was estimated at ~3 # clones per 4,000 tested." class CnpSharp < DBConnection include Ucsc::Hg18::Feature set_table_name 'cnpSharp2' set_primary_key nil def self.find_by_slice(slice) start = slice.range.begin stop = slice.range.end return CnpSharp.find_by_sql('SELECT * FROM cnpSharp2' + overlap_sql(slice, start, stop)) end end # = DESCRIPTION # From Structural Variants description page when clicking the "Describe # table schema" in the table browser: # "Paired-end sequences from a human fosmid DNA library were mapped to the # assembly. The average resolution of this technique was ~8kb, and included # 56 sites of inversion not detectable by the array-based approaches. # However, because of the physical constraints of fosmid insert size, this # technique was unable to detect insertions greater than 40 kb in size." class CnpTuzun < DBConnection include Ucsc::Hg18::Feature set_table_name 'cnpTuzun' set_primary_key nil def self.find_by_slice(slice) start = slice.range.begin stop = slice.range.end return CnpTuzun.find_by_sql('SELECT * FROM cnpTuzun' + overlap_sql(slice, start, stop)) end end # = DESCRIPTION # From Structural Variants description page when clicking the "Describe # table schema" in the table browser: # "" class Dgv < DBConnection include Ucsc::Hg18::Feature set_table_name 'dgv' set_primary_key nil def to_s return self.class.to_s + "\t" + self.slice.to_s + "\t" + self.reference + "\t" + self.method end def self.find_by_slice(slice) start = slice.range.begin stop = slice.range.end return Dgv.find_by_sql('SELECT * FROM dgv' + overlap_sql(slice, start, stop)) end end # = DESCRIPTION # From Simple Repeats description page when clicking the "Describe # table schema" in the table browser: # "This track displays simple tandem repeats (possibly imperfect) located # by Tandem Repeats Finder (TRF), which is specialized for this purpose. # These repeats can occur within coding regions of genes and may be quite # polymorphic. Repeat expansions are sometimes associated with specific # diseases." class SimpleRepeat < DBConnection include Ucsc::Hg18::Feature set_table_name 'simpleRepeat' set_primary_key nil def self.find_by_slice(slice) start = slice.range.begin stop = slice.range.end return SimpleRepeat.find_by_sql('SELECT * FROM simpleRepeat' + overlap_sql(slice, start, stop)) end end # = DESCRIPTION # From Structural Variants description page when clicking the "Describe # table schema" in the table browser: # "This track shows regions detected as putative genomic duplications # within the golden path. The following display conventions are used to # distinguish levels of similarity: # * Light to dark gray: 90 - 98% similarity # * Light to dark yellow: 98 - 99% similarity # * Light to dark orange: greater than 99% similarity # * Red: duplications of greater than 98% similarity that lack sufficient # Segmental Duplication Database evidence (most likely missed overlaps) # For a region to be included in the track, at least 1 Kb of the total # sequence (containing at least 500 bp of non-RepeatMasked sequence) had # to align and a sequence identity of at least 90% was required." class GenomicSuperDup < DBConnection include Ucsc::Hg18::Feature set_table_name 'genomicSuperDups' set_primary_key nil def self.find_by_slice(slice) start = slice.range.begin stop = slice.range.end return GenomicSuperDup.find_by_sql('SELECT * FROM genomicSuperDups' + overlap_sql(slice, start, stop)) end end # = DESCRIPTION # From Exapted Repeat description page when clicking the "Describe # table schema" in the table browser: # "This track displays conserved non-exonic elements that have been # deposited by mobile elements (repeats), a process termed "exaptation" # (Gould et al., 1982). These regions were identified during a genome-wide # survey (Lowe et al., 2007) with the expectation that regions of this type # may act as distal transcriptional regulators for nearby genes. A previous # case study experimentally verified an exapted mobile element acting as a # distal enhancer (Bejerano et al. , 2006)." class ExaptedRepeat < DBConnection include Ucsc::Hg18::Feature set_table_name 'exaptedRepeats' set_primary_key nil def self.find_by_slice(slice) start = slice.range.begin stop = slice.range.end return ExaptedRepeat.find_by_sql('SELECT * FROM exaptedRepeats' + overlap_sql(slice, start, stop)) end end #TODO: The repeatmasker features are distributed over different tables; one for # each chromosome. # # = DESCRIPTION # # From RepeatMasker description page when clicking the "Describe # # table schema" in the table browser: # # "This track was created by using Arian Smit's RepeatMasker program, which # # screens DNA sequences for interspersed repeats and low complexity DNA # # sequences. The program outputs a detailed annotation of the repeats that # # are present in the query sequence, as well as a modified version of the # # query sequence in which all the annotated repeats have been masked. # # RepeatMasker uses the RepBase library of repeats from the Genetic # # Information Research Institute (GIRI). RepBase is described in Jurka, J. # # (2000) in the References section below." # class RepeatMasker < DBConnection # include Ucsc::Hg18::Feature # # set_table_name 'rmsk' # set_primary_key nil # end # = DESCRIPTION # From Interrupted Repeat description page when clicking the "Describe # table schema" in the table browser: # "This track shows joined fragments of interrupted repeats extracted from # the output of the RepeatMasker program, which screens DNA sequences for # interspersed repeats and low complexity DNA sequences using the RepBase # library of repeats from the Genetic Information Research Institute (GIRI). # RepBase is described in Jurka, J. (2000) in the References section below. # # The detailed annotations from RepeatMasker are in the RepeatMasker track. # This track shows fragments of original repeat insertions which have been # interrupted by insertions of younger repeats or through local # rearrangements. The fragments are joined using the ID column of # RepeatMasker output." class InterruptedRepeat < DBConnection include Ucsc::Hg18::Feature set_table_name 'nestedRepeats' set_primary_key nil def self.find_by_slice(slice) start = slice.range.begin stop = slice.range.end return InterruptedRepeat.find_by_sql('SELECT * FROM nestedRepeats' + overlap_sql(slice, start, stop)) end end # = DESCRIPTION # From Microsatellite description page when clicking the "Describe # table schema" in the table browser: # "This track displays regions that are likely to be useful as # microsatellite markers. These are sequences of at least 15 perfect # di-nucleotide and tri-nucleotide repeats, and tend to be highly # polymorphic in the population." class Microsatellite < DBConnection include Ucsc::Hg18::Feature set_table_name 'microsat' set_primary_key nil def self.find_by_slice(slice) start = slice.range.begin stop = slice.range.end return Microsatellite.find_by_sql('SELECT * FROM microsat' + overlap_sql(slice, start, stop)) end end end end
true
9361bf59183aedda54a1b34476fc0b795543bbb3
Ruby
isabelgm/The-Well-Grounded-Rubyist
/lib/chapter 5/class_variables_and_class_hierarchy.rb
UTF-8
809
3.78125
4
[]
no_license
class Parent @@value = 100 end class Child < Parent @@value = 200 end class Parent puts @@value end # What gets printed is 200. The Child class is a subclass of Parent, and that means # Parent and Child share the same class variables—not different class variables with the # same names, but the same actual variables. When you assign to @@value in Child, # you’re setting the one and only @@value variable that’s shared throughout the hierarchy—that # is, by Parent and Child and any other descendant classes of either of them. # The term class variable becomes a bit difficult to reconcile with the fact that two (and # potentially a lot more) classes share exactly the same ones. # Class variables are popular because they’re the easiest way to distribute data # in that configuration.
true
36605547f4a096fa6e4de70a0a2645be90193376
Ruby
XertyBoi/NumberStrings
/number_string/bounds_object.rb
UTF-8
271
2.59375
3
[]
no_license
class Bound attr_accessor :max_bounds,:divide,:size_string,:array_to_select,:needs_and def initialize(max,div,string,need_and,array) @max_bounds = max @divide = div @size_string = string @array_to_select = array @needs_and = need_and end end
true
1d37d86527249e46e93d381c357005aa8949de5e
Ruby
michelleroos/rspec-debugging-blocks-procs
/rspec/lib/part_1.rb
UTF-8
553
4.15625
4
[]
no_license
def average(num_1, num_2) sum = num_1 + num_2 avg = sum / 2.0 avg end def average_array(arr) sum = 0.0 arr.each { |num|sum += num } avg = sum/arr.length avg end def repeat(str, num) str*num end def yell(string) string.upcase + "!" end def alternating_case(sentence) new_sentence = [] sentence.split.each_with_index do |word, i| if i % 2 == 0 new_sentence << word.upcase else new_sentence << word.downcase end end return new_sentence.join(" ") end
true
a4876cec7bff5c5dfe979fa4fc5f61c37cd76a47
Ruby
tony2nite/amzwish
/lib/amzwish/wishlist.rb
UTF-8
1,801
3.078125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
require 'nokogiri' module Amzwish class Wishlist include Enumerable attr_accessor :list_id, :email class << self def find(email, website = Services::WebsiteWrapper.new) website.find_for(email) end end def initialize(email, wishlist_id = "WISHLIST-ID", website = Services::WebsiteWrapper.new) @email = email @website = website @list_id = wishlist_id end def books # we're making a copy here to_a end def each each_page{|p| p.books.each{|b| yield b}} end alias_method :each_book, :each private def each_page has_more_pages = true page_num = 1 while(has_more_pages) do page = Page.new(@website.get_page(@list_id, page_num)) yield page has_more_pages = page.has_next? page_num += 1 end end class Page def initialize(html) @page = Nokogiri::HTML(html) @page.encoding = 'utf-8' end def has_next? # look and see if the 'Next' at the end of the page is an active link @page.xpath('//div[@class="pagDiv"]/span[@class="pagSide"]/a/span/text()').any?{|t| t.to_s.include?("Next")} end def books @page.xpath('//tbody[@class="itemWrapper"]').collect do |e| title = e.xpath('.//a[1]/text()').to_s asin = e.xpath("@name").to_s.split('.').last price = e.xpath('.//span[@class="price"]/strong/text()') if price.empty? price = nil else price = price.to_s.strip price = price.scan(/[\d\.]+/)[0].to_f end Book.new(asin, title, price) end end end end end
true
94ae50b954e3147fb608bca26904ba6012580d31
Ruby
vivianafb/MetodosRuby
/3 strings/Ejercicio1.rb
UTF-8
402
4.34375
4
[]
no_license
# Dado el siguiente string y caracter, crear un metodo que reciba como parametro el string # y el caracter. Luego debe buscar si existe ese caracter dentro del string. # hint: El metodo .include? de un string busca si un caracter # o string dado esta contenido en este. cadena = 'Hola Mundo!' caracter = 'o' def inside_it?(phrase, letter) phrase.include?(letter) end puts inside_it?(cadena, caracter)
true
3179555662daf4aabc7f45d0e5ca1911a227d1a7
Ruby
Kirbstomper/hw-ruby-intro
/lib/ruby_intro.rb
UTF-8
2,054
4.125
4
[]
no_license
# When done, submit this entire file to the autograder. # Christopher Smith # Marcus Andra # Part 1 def sum(x) # YOUR CODE HERE sum = 0 x.each{|el| sum += el}# for each element in the array, adds it to the overall sum return sum end def max_2_sum arr # YOUR CODE HERE arr = arr.sort.reverse size = arr.size case size # Using a case for the size of the array when 1 return arr[0] when 0 return 0 else return arr[0]+arr[1] end end def sum_to_n? arr, n # YOUR CODE HERE #Nest for loop magic if arr.size>1 for a in 0...(arr.size)# Outter for integer a for b in a+1...(arr.size)# Inner for integer b return true if ((arr[a]+arr[b]) == n) # returns true should any combination sum to n end end end return false# Returns false if not possible to sum to n end # Part 2 def hello(name) # YOUR CODE HERE return "Hello, #{name}" end def starts_with_consonant? s # YOUR CODE HERE return /^[^aeiou\d\W]/i =~ s # Using Regex it first checks at the beginning of the string if it matches any vowels, then if it matches any numbers then if it matches any special characters. #The /i is to make it case insensitive end def binary_multiple_of_4? s # YOUR CODE HERE if (/^$/ =~ s)||(/[a-z2-9\W]/i =~ s) #Checks using regex first if the string is empty, then if the string contains anything other than 1s and 0s return false else return (s.to_i % 4) == 0 #if a binary string, converts to int and checks using mod if it is divisible by 4 end end # Part 3 class BookInStock # YOUR CODE HERE def initialize(isbn_number, price) # I have other ways on writing method starts_with_consonant?, let me know if you want it raise ArgumentError if (price<=0 || isbn_number=="") @isbn_number = isbn_number @price = price end def isbn return @isbn_number end def isbn=(isbn_number) @isbn_number = isbn_number end def price @price end def price=(price) @price = price end def price_as_string "$%0.2f" % @price end end
true
9aeaa7267baab74b53a0e1b20ab9dca7d6a2f1ec
Ruby
sharonsheah/coding-challenges2
/01-Ruby/01-Programming-basics/Optional-01-Colorful-Algorithm/spec/colorful_spec.rb
UTF-8
577
3.25
3
[]
no_license
require "colorful" describe "colorful?" do it "returns false if provided with something other than a number" do expect(colorful?("not_a_number_but_a_string")).to eq false end colorful_numbers = [ 5, 34, 263 ] not_colorful_numbers = [ 70, 236 ] colorful_numbers.each do |number| it "returns true for #{number} which is colorful" do expect(colorful?(number)).to eq true end end not_colorful_numbers.each do |number| it "returns false for #{number} which is not colorful" do expect(colorful?(number)).to eq false end end end
true
1c30177a3a3ae3e1055f113d69845cc3d7290acc
Ruby
vase4kin/test_rail_integration
/lib/test_rail_integration/generator/test_run_parameters.rb
UTF-8
904
2.640625
3
[ "MIT" ]
permissive
require_relative 'API_client' module TestRail class TestRunParameters VENTURE_REGEX ||= TestRail::TestRailDataLoad.test_rail_data[:ventures] ENVIRONMENT_REGEX ||= TestRail::TestRailDataLoad.test_rail_data[:environments] CHECK_TEST_RUN_NAME ||= TestRail::TestRailDataLoad.test_rail_data[:check_test_run_name] EXEC_COMMAND ||= TestRail::TestRailDataLoad.test_rail_data[:exec_command] attr_accessor :environment, :venture, :command # # Checking of correct naming of created test run and return parameters for running test run # def initialize(env=nil) @venture = "" @environment = "" if env if env[0] @venture = env[0] if env[0].match(/(#{VENTURE_REGEX})/) end if env[1] @environment = env[1] if env[1].match(/(#{ENVIRONMENT_REGEX})/) end end @command = EXEC_COMMAND end end end
true
fda21af91438e62768255710bbf715399f7a347f
Ruby
biancapower/ruby-exercises-week2
/atm/atm.rb
UTF-8
268
3.734375
4
[]
no_license
puts "Welcome to the bank!" puts "What transaction would you like to do? 'withdraw' or 'deposit'?" transaction = gets.chomp if transaction == "withdraw" puts "Thank you for your withdrawal" elsif transaction == "deposit" puts "Thank you for your deposit" end
true
4ef7a8e2558f120d1a99bb1418ad2c508b088bca
Ruby
Wumingla/rubymotion_cookbook
/ch_6/06_custompins/app/my_annotation.rb
UTF-8
943
2.875
3
[]
no_license
class MyAnnotation #pin constants from the header file REUSABLE_PIN_RED = "Red" REUSABLE_PIN_GREEN = "Green" REUSABLE_PIN_PURPLE = "Purple" # this portion needs to be settable attr_accessor :pinColor # these need to be implemented this way as part of MKAnnotation def coordinate; @coordinate; end def title; @title; end def subtitle; @subtitle; end # use this as a class method def self.reusableIdentifierforPinColor(paramColor) result = case paramColor when MKPinAnnotationColorRed REUSABLE_PIN_RED when MKPinAnnotationColorGreen REUSABLE_PIN_GREEN when MKPinAnnotationColorPurple REUSABLE_PIN_PURPLE end result end def initWithCoordinates(paramCoordinates, title:paramTitle, subTitle:paramSubTitle) @coordinate = paramCoordinates @title = paramTitle @subtitle = paramSubTitle @pinColor = MKPinAnnotationColorGreen self end end
true
6f41a0dcb3ef8ea139e41608b57c870a87ebff38
Ruby
KellyMarcilliat/black_thursday
/lib/item_repository.rb
UTF-8
863
3.0625
3
[]
no_license
require 'csv' require_relative '../lib/item' require_relative '../lib/repository_helper' require 'bigdecimal' class ItemRepository include RepositoryHelper attr_reader :items, :all def initialize(filepath) @filepath = filepath @items = [] @all= [] end def create_items CSV.foreach(@filepath, headers: true, header_converters: :symbol) do |row| @all << Item.new(row) end end def find_all_by_merchant_id(merchant_id) @all.find_all do |item| item.merchant_id == merchant_id end end def create(attributes) attributes[:id] = create_id item = Item.new(attributes) @all << item end def update(id, attributes) if find_by_id(id) != nil find_by_id(id).update_attributes(attributes) end end def inspect "#<#{self.class} #{@merchants.size} rows>" end end
true
65971a9f86d026ce36836dd3eba254c7fc7be1c7
Ruby
CamillaCdC/seic38-homework
/Stacey Brosnan/week04/monday/mortgageCalculator.rb
UTF-8
301
3.53125
4
[]
no_license
print "What is the fixed yearly interest rate? " i = gets.to_f/12 print "What is the principle? " p = gets.to_i print "What is the number of monthly payments? " n = gets.to_i monthly_payment = p * (i * (1 + i) ** n) / ((1 + i) ** n - 1) print "Your montly payment will be #{monthly_payment} \n"
true
bb5e17d3f878f4d87cfebb7d317be63ddaf36d8a
Ruby
bloopletech/gistory
/lib/gistory/diff_to_html.rb
UTF-8
4,431
2.671875
3
[ "MIT" ]
permissive
class Gistory::DiffToHtml #FIXME LOLWUT def self.h(str) Rack::Utils.escape_html str end #TODO All the below needs to be tested def self.diff_to_html_rename(diff) { :type => 'rename', :message => diff.diff.ucfirst.gsub("\n", " => "), :content => [] } end def self.diff_to_html_binary(diff) if diff.new_file { :type => 'new', :message => "Created binary file #{h diff.b_path}", :content => [] } elsif diff.deleted_file { :type => 'delete', :message => "Deleted binary file #{h diff.a_path}", :content => [] } else { :type => 'change', :message => "Changed binary file #{h diff.a_path}", :content => [] } end end #TODO: REFACTOR THIS SHIT SOMETHING FURIOUS def self.lines_to_raw_changes(lines) changes = [] line_offset = 1 should_change = false lines.each do |l| # puts "line_offset: #{line_offset}, l: #{l}, changes: #{changes.inspect}" if l =~ /^\@\@ \-\d+(?:|,\d+) \+(\d+)(?:|,\d+) \@\@/ line_offset = $1.to_i == 0 ? 1 : $1.to_i else if l == '\ No newline at end of file' changes.last[:nl_notice] = true if !changes.empty? line_offset -= 1 elsif l =~ /^\+/ changes << { :start => line_offset, :lines => [], :times => 0, :mode => :add, :nl_notice => false } if should_change or changes.empty? or changes.last[:mode] != :add should_change = false changes.last[:times] += 1 changes.last[:lines] << l[1..-1] elsif l =~ /^-/ changes << { :start => line_offset, :lines => [], :times => 0, :mode => :remove, :nl_notice => false } if should_change or changes.empty? or changes.last[:mode] != :remove should_change = false changes.last[:times] += 1 changes.last[:lines] << l[1..-1] line_offset -= 1 else should_change = true end line_offset += 1 end end changes end def self.process_newline_warnings_on_changes(changes) return changes if changes.length <= 1 || !changes.detect { |change| change[:nl_notice] } #Remove edge cases if (changes[-2][:nl_notice] || changes[-1][:nl_notice]) && changes[-2][:lines].first == changes[-1][:lines].first && changes[-2][:lines].length == 1 && changes[-1][:lines].length == 1 #Handles adding/removing a newline to the end of a file, i.e. a one line remove and a one line add changes.pop changes.pop elsif changes[-2][:mode] == :remove && changes[-1][:mode] == :add if changes[-1][:nl_notice] && changes[-2][:times] > 1 && changes[-1][:lines].length == 1 && changes[-2][:lines].first == changes[-1][:lines].first #Handles removing where there's no end nl both before and after changes[-2][:start] += 1 changes.pop elsif changes[-2][:nl_notice] && changes[-2][:lines].length == 1 && changes[-1][:times] > 1 && changes[-2][:lines].first == changes[-1][:lines].first #Handles adding where there's no end nl both before and after changes.delete_at(-2) changes[-1][:lines].shift changes[-1][:start] += 1 end end changes end def self.changes_to_html(changes) changes.select { |change| change.key?(:lines) }.each do |change| change[:lines] = change[:lines].map do |line| line_space_fixed = h(line).gsub(/ /, " &nbsp;") "<div>#{line_space_fixed == '' ? "&nbsp;" : line_space_fixed}</div>" end.join end changes end def self.diff_to_html_textual(diff) # puts "COMMIT =========================================================================================" content_lines = diff.diff.split(/\n/)[2..-1] changes = self.lines_to_raw_changes(content_lines) changes = self.process_newline_warnings_on_changes(changes) changes = self.changes_to_html(changes) if diff.new_file { :type => 'new', :message => "Created file #{h diff.b_path}", :content => changes } elsif diff.deleted_file { :type => 'delete', :message => "Deleted file #{diff.a_path}", :content => changes } else { :type => 'change', :message => "Changed file #{diff.a_path}", :content => changes } end end def self.diff_to_html(diff) if diff.diff =~ /^rename/ diff_to_html_rename diff elsif diff.diff =~ /^Binary/ diff_to_html_binary diff else diff_to_html_textual diff end end end
true
aedb1cf458e073d34f7157c3df0b50010cb9fb57
Ruby
codereport/LeetCode
/0202_Problem_1.rb
UTF-8
444
2.984375
3
[]
no_license
# code_report Solution # Problem Link (Contest): https://leetcode.com/contest/weekly-contest-202/problems/three-consecutive-odds/ # Problem Link (Practice): https://leetcode.com/problems/three-consecutive-odds/ # Note this problem is very similar to MCO (Max Consecutive Ones) def three_consecutive_odds(arr) return arr.map{ |x| x.odd? ? 1 : 0 } .chunk_while( &:== ) .map( &:sum ) .max >= 3 end
true
eb30d762ea41bf46232bd9951d2f0a0e47cb5183
Ruby
StarPerfect/pets_and_customers
/test/day_care_test.rb
UTF-8
1,520
2.859375
3
[]
no_license
require 'Minitest/autorun' require 'Minitest/pride' require './lib/day_care' require './lib/customer' require './lib/pet' class DayCareTest < Minitest::Test def setup @daycare = DayCare.new('AAA DayCare') @spaz = Pet.new({name: 'Spaz', type: 'Boxer'}) @sativa = Pet.new({name: 'Sativa', type: 'Boxer'}) @dog_mom = Customer.new('Corina', 1) @dog_mom.adopt(@spaz) @dog_mom.adopt(@sativa) @lucy_loo = Pet.new({name: 'Lucy Loo', type: 'Scottish Fold'}) @cindy_who = Pet.new({name: 'Cindy Who', type: 'Munchkin Cat'}) @cat_mom = Customer.new('Kesley', 2) @cat_mom.adopt(@lucy_loo) @cat_mom.adopt(@cindy_who) @kitty = Pet.new({name: 'Kitty', type: 'Exotic Shorthair'}) @puppy = Pet.new({name: 'Puppy', type: 'Chow Chow'}) @generic_mom = Customer.new('Elizabeth', 3) @generic_mom.adopt(@kitty) @generic_mom.adopt(@puppy) @daycare = DayCare.new('AAA DayCare') end def test_daycare_exists assert_instance_of DayCare, @daycare end def test_attributes assert_equal 'AAA DayCare', @daycare.name assert_equal [], @daycare.customers end def test_add_customers @daycare.add_customer(@dog_mom) assert_equal [@dog_mom], @daycare.customers end def test_find_customer_by_id @daycare.add_customer(@dog_mom) @daycare.add_customer(@cat_mom) assert_equal @dog_mom, @daycare.find(1) end def test_find_unfed @daycare.add_customer(@dog_mom) @spaz.feed assert_equal [@sativa], @daycare.find_unfed end end
true
8ed084a6b8ab5a335410c5a57da5282f0e5d5615
Ruby
s34rching/ruby-basics
/s12-hashes-part-1/length_empty_methods.rb
UTF-8
144
2.859375
3
[]
no_license
menu = { burger: 1.52, taco: 10.4, chips: 5.12 } menu_1 = {} p menu.length # counts pairs p menu_1.length p menu.empty? p menu_1.empty?
true
566faec565629bc8a51f2a198964d7530bf3bcad
Ruby
jatin-baweja/advanced-ruby-exercise
/exercise5/bin/main.rb
UTF-8
246
3.40625
3
[]
no_license
#!/usr/bin/env ruby string1 = "Sample String" string2 = "Another Sample String" def string1.inspect_value inspect end class << string1 def uppercase upcase end end puts string1.inspect_value puts string1.uppercase puts string2.uppercase
true
c5dee900ee9d0d2dd2b70963ef60834469d73afb
Ruby
thuongho/awktion
/lib/place_bid.rb
UTF-8
1,119
3.34375
3
[]
no_license
# a class to make sure that new bids are not less than current bid class PlaceBid # makes that auction variable public to the outside attr_reader :auction, :status def initialize options @value = options[:value].to_f @user_id = options[:user_id].to_i @auction_id = options[:auction_id].to_i end def execute # find the auction by the auction id # instance variable to make it avail @auction = Auction.find @auction_id # debugging - make sure that code below desn't execute # binding.pry # add status to end of auction if auction.ended? && auction.top_bid.user_id == @user_id @status = :won return false end # prevent the bid object to be created if value is less than current bid if @value <= auction.current_bid return false end # instantiate a new bid using the value and user id # a new bid that is build around the auction and user id bid = auction.bids.build value: @value, user_id: @user_id if bid.save return true else # return false in case cannot save return false end end end
true
57fe4b6d80afb538fa4859a3ec5f95fff5928f3e
Ruby
C-FO/zaim
/lib/zaim/api/users.rb
UTF-8
835
2.71875
3
[ "MIT" ]
permissive
require 'zaim/api/utils' require 'zaim/user' module Zaim module API module Users include Zaim::API::Utils # Returns the requesting user if authentication was successful, otherwise raises {Zaim::Error::Unauthorized} # # @see https://dev.zaim.net/home/api#user_verify # @note Authentication Required # @raise [Zaim::Error::Unauthorized] Error raised when supplied user credentials are not valid. # @return [Zaim::User] The authenticated user. # @param options [Hash] A customizable set of options. # @example Return the requesting user if authentication was successful # client.user_verify def user_verify(options={}) object_from_response(Zaim::User, :get, '/home/user/verify', options) end alias current_user user_verify end end end
true
31252031a890875cf12ed0ab92a613e180fd8c03
Ruby
gsaslis/github-release-downloads-count
/count.rb
UTF-8
2,100
3.03125
3
[ "MIT" ]
permissive
require 'net/http' require 'json' def countReleaseDownloads(release) releaseDownloadsTotal = 0 releaseAssets = release['assets'] unless releaseAssets.nil? releaseAssets.each do |asset| releaseDownloadsTotal += asset['download_count'] end puts " ; #{release['name']} ; #{release['published_at']} ; #{releaseDownloadsTotal}" end releaseDownloadsTotal end def getReleasesForRepo(user, repo, token) releasesURI = URI("https://api.github.com/repos/#{user}/#{repo['name']}/releases") releasesHttp = Net::HTTP.new(releasesURI.host, releasesURI.port) releasesRequest = Net::HTTP::Get.new(releasesURI.request_uri) releasesRequest.add_field 'Authorization', "Token #{token}" releasesHttp.use_ssl = true releasesResponse = releasesHttp.request(releasesRequest) releases = JSON.parse(releasesResponse.body) releases end def getMaxUserRepositoriesAllowedByGithubAPI(user, authToken, current_page) url = "https://api.github.com/users/#{user}/repos?per_page=100&page=#{current_page}" uri = URI(url) http = Net::HTTP.new(uri.host, uri.port) request = Net::HTTP::Get.new(uri.request_uri) request.add_field 'Authorization', "Token #{authToken}" http.use_ssl = true response = http.request(request) repos = JSON.parse(response.body) repos end authToken = ENV['GITHUB_AUTH_TOKEN'] user = ENV['GITHUB_USERNAME'] pages = 2 # we have less than 200 repos current_page = 1 # pages don't start at 0 : P allUserRepos = [] userDownloadsTotal = 0 while current_page <= pages do repos = getMaxUserRepositoriesAllowedByGithubAPI(user, authToken, current_page) repos.each do |repo| projectDownloadsTotal = 0 puts "#{repo['name']}" allUserRepos.push "#{repo['name']}" releases = getReleasesForRepo(user, repo, authToken) releases.each do |release| projectDownloadsTotal += countReleaseDownloads(release) end puts "Total Downloads ; ; ; #{projectDownloadsTotal} \n\n" userDownloadsTotal += projectDownloadsTotal end current_page=current_page+1 end puts "User Total Downloads ; ; ; #{userDownloadsTotal}"
true
49d15d1a34d7acf435934f33b39e5e6175ec55c0
Ruby
mikekarnes123/backend_prework
/day_7/fizzbuzz.rb
UTF-8
139
3.34375
3
[]
no_license
1.upto 100 do |x| if x % 3 == 0 && x % 5 == 0 p "FizzBuzz" elsif x % 5 == 0 p "Buzz" elsif x % 3 == 0 p "Fizz" else puts x end end
true
a36e221280d280c71b526c8fe5837cb2ed9f1f45
Ruby
jshwartz/palindrome
/lib/palindromes.rb
UTF-8
436
3.625
4
[]
no_license
require ('pry') class String define_method(:palindrome?) do if self == self.reverse "You have a Palindrom" else "You do not have a Palindrom" end end end class String define_method(:reverse_string) do char_array = self.split("") char_number = char_array.count() rev_char_array = [] char_number.times do rev_char_array.push(char_array.pop) end rev_char_array.join end end
true
bc0797bb81ecf305cbce4c2473ff1ae4487ca12c
Ruby
diogobira/mc4arm
/dispatcher.rb
UTF-8
323
2.90625
3
[]
no_license
require 'parametros' require 'simulador' class Dispatcher def initialize(file,runtimes) @p = Parametros.new(file) @s = Simulador.new(@p) @t = runtimes end def run threads = Array.new (1..@t).each do |i| #threads << Thread.new {@s.executar} @s.executar end #threads.each {|thr| thr.join} end end
true
274de3fb9614bde44c9677c7af041929566611df
Ruby
astine/ROQTI
/spec/chapter_1_spec.rb
UTF-8
1,836
3.109375
3
[]
no_license
require_relative '../lib/ROQTI' #Exercise 1 describe InterestRates,"#Annualized_interest_rate" do it "should return the annualized rate of an investment for a gross rate of 10% for the time period between 30 November 2006 and 1 March 2008" do #Y + m/12 + D/360 = periods periods = (1 + (2/12) + (29/360)) return InterestRates.annualized_interest_rate(0.10, periods) end end #Exercise 2.1 describe InterestRates,"#savings_account" do it "should return the gross annual interest rate" do capital = 1000 interest = 40 InterestRates.gross_interest_rate(interest, capital).should eq(0.04) end end #ex 2.2 describe InterestRates,"#savings_account" do it "should return the amount of interest for 2006" do capital = 1040 rate = 0.04 periods = 12 InterestRates.interest_paid(capital, rate, periods).should eq(41.6) end end #Ex 2.3 describe InterestRates,"#savings_account" do it "should return interest in july 2005" do capital = 1000 rate = 0.04 periods = 6 InterestRates.interest_paid(capital, rate, periods).should eq(19.8) end end #Ex 3 describe InterestRates,"#savings_account" do it "should return the savings amount in 10 years" do capital = 500 periods = 10 interest = 530.52 InterestRates.future_balance(capital, interest, periods).should eq(2124) end end #Ex 8 describe InterestRates,"#present_value" do it "should return present values" do a_capital = 100000 a_period = 1 b_capital = 1000000 b_period = 10 c_capital = 100000 c_period = -10 rate = 0.04 InterestRates.present_value(a_capital, a_period, rate).should eq(96154) InterestRates.present_value(b_capital, b_period, rate).should eq(675564) InterestRates.present_value(c_capital, c_period, rate).should eq(148024) end end
true
c07fc79912b2db1f94e33b1e85a9e74bf0a10247
Ruby
beaucouplus/launchschool_ruby_more_topics
/challenges/diamond.rb
UTF-8
1,200
3.828125
4
[]
no_license
# Requirements # The first row contains one 'A'. # The last row contains one 'A'. # All rows, except the first and last, have exactly two identical letters. # The diamond is horizontally symmetric. # The diamond is vertically symmetric. # The diamond has a square shape (width equals height). # The letters form a diamond shape. # The top half has the letters in ascending order. # The bottom half has the letters in descending order. # The four corners (containing the spaces) are triangles. # A # B B # C C # B B # A # A > 0 # B B 1 + 0 > 1 # C C 1 + 2 > 2 # D D 1 + 4 > 3 # E E 1 + 6 > 4 # D D # C C # B B # A require 'pry' class Diamond def self.make_diamond(letter) letters = ("A"..letter).to_a first_triangle = letters.map.with_index do |ltr, idx| external_spaces = " " * (letters.size - 1 - idx) if idx.zero? external_spaces + ltr + external_spaces + "\n" binding.pry else internal_spaces = " " * (1 + (2 * (idx - 1))) external_spaces + ltr + internal_spaces + ltr + external_spaces + "\n" end end (first_triangle + first_triangle.reverse[1..-1]).join end end
true
7816411a4f69b8d28203af0a447839903c171f0a
Ruby
chetan/continuum
/lib/continuum/http/httpi.rb
UTF-8
668
2.734375
3
[]
no_license
module Continuum class BaseClient private # Fetch a list of URLs. HTTPI adapter fetches each serialily. # # @param [Array<String>] def do_multi_get_http(uris) uris = [uris] if not uris.kind_of? Array uris.map do |uri| HTTPI.get(uri).body end end # POST the given requests. HTTPI adapter will post each serially. # # @param [Array<Array<String, String>>] reqs Array of reqs, where req is [uri, body] def do_multi_post_http(reqs) reqs.map do |req| HTTPI.post(HTTPI::Request.new(:url => req.shift, :body => req.shift)).body end end end # BaseClient end # Continuum
true
398696bad381cc1188363b88578760ec3aa221e5
Ruby
tcannonfodder/duck-hunt
/test/validators/rejected_values_test.rb
UTF-8
1,328
2.875
3
[ "MIT" ]
permissive
require File.expand_path('../../test_helper', __FILE__) class DuckHuntRejectedValuesValidatorTest < DuckHuntTestCase def setup @validator = DuckHunt::Validators::RejectedValues.new([1,2,3]) end test "should create an instance with the provided value" do validator = DuckHunt::Validators::RejectedValues.new([1,2,3]) assert_equal [1,2,3], validator.values end test "should raise an exception if a value is not provided" do assert_raises ArgumentError do DuckHunt::Validators::RejectedValues.new end end test "should raise an exception if the value provided is not a hash" do assert_raises ArgumentError do DuckHunt::Validators::RejectedValues.new(3) end end test "returns true if the value provided is not one of the rejected values" do assert_equal true, @validator.valid?(4) assert_equal true, @validator.valid?(0) end test "returns false if the value provided is one of the rejected values" do assert_equal false, @validator.valid?(1) assert_equal false, @validator.valid?(2) assert_equal false, @validator.valid?(3) end test "should have the correct error message based on the value provided" do validator = DuckHunt::Validators::RejectedValues.new([1,2,3]) assert_equal "a rejected value", validator.error_message end end
true
021c918c9c6215bb36a29487a518d43f3b8e5703
Ruby
LuisMarta/lab1
/case-control.rb
UTF-8
236
2.65625
3
[]
no_license
def validar_ip_servidor_pop(ip_para_validar) case ip_para_validar when "192.168.2.1" puts "Ip invlido" when "192.168.2.3" puts "ip invalido" when "192.168.2.2" puts "Ip valido" end end validar_ip_servidor_pop("192.168.2.2")
true
4b560aa152c39b65a70e6322a73cf4f6f041ad9b
Ruby
jeffgrayjr/aA-homework
/data-structures/skeleton/lib/knightpathfinder.rb
UTF-8
1,944
3.671875
4
[]
no_license
require_relative "00_tree_node.rb" class KnightPathFinder def initialize(starting_pos) @root_node = PolyTreeNode.new(starting_pos) @considered_positions = [] self.build_move_tree end def self.valid_move(pos) possible_moves = [] [-2, -1, 1, 2].each do |x| if x == -2 || x == 2 [-1, 1].each {|y| possible_moves << [pos[0] + x, pos[1] + y]} else [-2, 2].each {|y| possible_moves << [pos[0] + x, pos[1] + y]} end end valid_moves = possible_moves.select do |move| move[0] >= 0 && move[0] < 8 && move[1] >= 0 && move[1] < 8 end return valid_moves end def new_move_positions(pos) valid_moves = KnightPathFinder.valid_move(pos).select {|move| !@considered_positions.include?(move)} @considered_positions += valid_moves return valid_moves end def build_move_tree queue = [@root_node] until queue.length == 0 ele = queue.shift children = self.new_move_positions(ele.value) p children p "\n" children.each do |child| ele.add_child(PolyTreeNode.new(child)) end ele.children.each {|child| queue << child} end end def find_path(end_pos) queue = [@root_node] until queue.length == 0 ele = queue.shift return trace_path_back(ele) if ele.value == end_pos ele.children.each {|child| queue << child} end nil end def trace_path_back(end_node) path = [] queue = [end_node] loop do ele = queue.shift path << ele.value if ele.parent == nil return path.reverse else queue << ele.parent end end return path end end
true
e05cccb2347c34daa28940c99f046588d6d530cb
Ruby
sirivatd/UrlShortener
/URL_Shrntr/URLShortener/bin/cli
UTF-8
1,206
3.171875
3
[]
no_license
#!/usr/bin/env ruby require 'launchy' def get_input puts "Enter your email." email = gets.chomp current_user = User.where(email: email) raise "User does not exists" if current_user == [] puts "Logged in succesfully" while 1 puts "Would you like to visit or shorten a URL? ('v' for visit, 's' for shorten)" choice = gets.chomp if choice.upcase == "S" puts "Please enter a URL" long_url = gets.chomp begin ShortenedUrl.shorten(current_user.first, long_url) puts "Succesfully updated database!" rescue => e print e.message end else display_short_urls end end end def display_short_urls begin urls = ShortenedUrl.all urls.each do |url| puts("Id: #{url.id}, Long_url: #{url.long_url}, Short_url: #{url.short_url}") end puts "Please enter the id of the URL you want to visit" chosen_id = gets.chomp.to_i raise "Chosen Id does not exists" unless ShortenedUrl.where(id: chosen_id).exists? target_url = ShortenedUrl.where(id: chosen_id) p target_url.first.long_url Launchy.open(target_url.first.long_url) rescue => e e.message end end if __FILE__ == $PROGRAM_NAME get_input end
true
178c134a74695ca4829f641b4189a90b5b163e80
Ruby
letianpai/letian.fight
/code_library/ruby/lang/hashmap.rb
UTF-8
4,839
3.9375
4
[]
no_license
#!/usr/bin/env ruby # coding: utf-8 # 建立hash months = Hash.new # 使用 empty? 测试 Hash 是否为空 p months.empty? # 使用 length, size返回 Hash的大小 p months.length p months.size # 如果指定了默认参数, 则当没有指定元素时候,则返回默认元素 months2 = Hash.new('abc') p months2[:aa] # 可以使用类方法[] 来建立一个 Hash. months3 = Hash[:aaa, 10, :bbb, 20, :ccc, 30] p months3[:aaa] x = 'abc' months3[x] = 1000 # 直接作为key , 就不能通过sym访问 months3[x.to_sym] = 1000 p months3[:abc] p months3[x] # 返回一个 hash 所有的key, 使用keys, 返回所有的key p months3.keys p months3.values # 判断是否包含一个key p months3.has_key?(:aaa) p months3.has_value?(1000) # 返回多个key 的值, 使用 values_at # 这里 :ddd 返回 nil p months3.values_at :aaa, :bbb, :ddd # 通过某个 value 返回key , 使用 index p months3.key 10 # 通过 select 方法, 使用一个block 来返回一个符合条件的新的多维数组 zip = { 82442 => "Ten Sleep", 83025 => "Teton Village", 83127 => "Thayne", 82443 => "Thermopolis", 82084 => "Tie Siding", 82336 => "Tipton", 82240 => "Torrington", 83110 => "Turnerville", 83112 => "Turnerville" } p zip.select { |key, val| key > 83000 } ## # 迭代 Hash # 可以通过 each, each_key, each_value, each_pair 来迭代一个Hash # # each 方法对于hash 每一条数据调用一个 block: # zip.each{ |k, v| puts "#{k}/#{v}" } puts # each 和 each_pair 区别, each 可以有一个或者两个参数, 而 each_pair 必须有两个参数 zip.each_pair{ |k, v| puts "#{k}/#{v}" } # each_key 方法只传递key 给block zip.each_key{ |key| print key, " " } # 同理, each_value 方法则只传递value 给block zip.each_value{ |value| print value, " "} ## # 修改 Hash # # Hash 的 []= 方法会替换/添加一个 key-value 的值给一个存在的 Hash # # 比如 rhode_island = { 1 => "Bristol", 2 => "kent", 3 => "Newport", 4 => "Providence", 5 => "Washington" } # 使用 []= 来添加或修改一个值: rhode_island[6] = "Dunthorpe" p rhode_island # 也可以使用 store 方法来添加值: rhode_island.store(7, "Seven") p rhode_island ## # 合并Hash # # 两个 hash: # delaware = { 1 => "kent", 2 => "New Castle", 3 => "Sussex" } rhode_island = { 1 => "Bristol", 2 => "Kent" , 3 => "Newport" , 4 => "Providence", 5 => "Washington" } # merge 方法组合两个hash, 获得一份 hash 拷贝, 第二个hash 相同的key值会覆盖第一个 merge_arr = rhode_island.merge delaware p merge_arr ## # 排序Hash # # 当在一个 Hash 上使用 sort 方法, 将会返回一个key, value 构成的两个元素的二维数组, # 注意: hash 本身是没有任何排序信息的 rhode_island = { 1 => "Bristol", 2 => "Kent" , 3 => "Newport" , 4 => "Providence" , 5 => "Washington" } p rhode_island p rhode_island.sort #=> 注意 Hash没有sort! 方法 ## # 删除和清除一个 Hash # # 可以使用 delete 方法来删除一个 hash 的key->value, delete 方法使用一个key 来找到相应部分并且 destory 它 # p rhode_island.delete(5) #=> 返回删除的元素 # 也可以在调用 delete 的时候传入一个 block, 则在指定的key 不存在的时候, 返回block内容 rhode_island.delete(6) { |key| puts "not found key #{key}, bubba" } # delete_if 方法也可以使用一个 block, 当block 里最后表达式结果为 true, 则对应的记录被删除 # 下面删除key 小于 3的记录 rhode_island.delete_if{|key, value| key < 3} p rhode_island # reject 方法类似 delete_if, 但是它返回hash中标识删除的备份, 并不修改原数据。 而reject!则和delete_if 相等 rhode_island = { 1 => "Bristol", 2 => "Kent" , 3 => "Newport" , 4 => "Providence" , 5 => "Washington" } puts "====" p rhode_island.reject {|key, value| key < 3} # 使用clear 方法会删除Hash 内所有数据, 删除后数据为 empty counties = {"delavars" => 3, "Rhode Island" => 5} counties.clear p counties.empty? # => true ## # 替换 Hash # # 如果要替换一个 hash 的全部内容, 使用replace 方法: temp = {"delaware" => 3} counties.replace(temp) p counties p counties.replace({"delaware" => 4}) ## # 转换 Hash 为其他类型 # # 可以通过 to_a 把 Hash 转换为一个数组 fitzgerald = {1920 => "This Side of Paradise", 1925 => "The Geet Gateby", 1934 => "Tender Is ths Night"} # 使用 to_a 转换为数组 p fitzgerald.to_a # to_a 转换一个 hash 为一个多维数组, hash 的key=value 值被转换为两个元素的数组值 # 通过 to_s 转换一个 hash 为一个字符串: novels = fitzgerald.to_s p novels # "{1920=>\"This Side of Paradise\", 1925=>\"The Geet Gateby\", 1934=>\"Tender Is ths Night\"}" # 给数组使用 to_hash 则不会生成新hash ,两个内容的 object_id 相等
true
9a3c2e695c2a788f9bef42412e5d85e29e39c4d1
Ruby
richieganney/runlength
/lib/runlength_decode.rb
UTF-8
245
2.859375
3
[]
no_license
def runlength_decode(s) str1 = s.scan /A+|B+|C+|D+|E+|F+|G+|H+|I+|J+|K+|L+|M+|N+|O+|P+|Q+|R+|S+|T|U+|V+|W+|X+|Y+|Z+/ str2 = s.gsub(/[A-Z]/, ',').split(',').map(&:to_i).zip(str1).map { |rl| rl[0].to_i.zero? ? 0 : rl[1] * rl[0].to_i }.join end
true
5b6fcfe946755a90cd22e9c992e940c194d8a7ea
Ruby
maetl/nanogenmo2015
/encounter.rb
UTF-8
3,100
3.140625
3
[]
no_license
require 'calyx' class Encounter < Calyx::Grammar start :monster rule :monster, '{monster_stats}. {monster_state}' rule :monster_description, '' rule :monster_stats, 'GIANT SPIDER (STRENGTH 18, STAMINA 12)', 'GOBLIN (STRENGTH 12, STAMINA 8)' rule :monster_state, :aggressive, :timid, :watchful, :inattentive rule :aggressive, 'You must FIGHT. The monster gains initiative.' rule :timid, "It seems afraid of you. Make a successful attack roll to scare it off.\n\n- If you succeed, the creature {runs_away} into the shadows. You may continue to the exits.\n- If you fail, you must FIGHT. You gain initiative." rule :runs_away, 'runs away', 'runs off', 'scuttles off', 'scuttles away', 'disappears', 'retreats' rule :watchful, 'You must FIGHT. You gain initiative.' rule :inattentive, "The creature is asleep. Make a successful attack roll to sneak past without it noticing you.\n\n- If you startle and wake the creature, you must FIGHT.\n- If you sneak past unnoticed, you may continue to the exits." end encounter = Encounter.new puts encounter.generate class MonsterEncounter < Calyx::Grammar start :monster_deadly rule :monster_encounter, [:monster_deadly, 0.05], [:monster_hostile, 0.45], [:monster_neutral, 0.5] rule :monster_deadly, :monster_basilisk rule :monster_hostile, '' rule :monster_neutral, '' rule :monster_bulky, '{bulky_movement.capitalize} {room_movement} is' rule :room_movement, 'towards you', 'ahead of you' rule :bulky_movement, 'moving', 'lumbering', 'moving sluggishly', 'stamping', 'stomping', 'trampling' rule :monster_basilisk, '{monster_bulky} a giant basilisk. As you {freeze_reaction}, the {reptilian_adj} {reptilian_noun} {head_movement} its head and {petrifying_gaze_strike}. {petrifying_gaze_death}' rule :petrifying_gaze_strike, 'its petrifying gaze {strikes} you head on', 'you {stare_directly} into its petrifying gaze' rule :petrifying_gaze_death, '{last_memory_flash} is the {horrific} projection from its eyes as your {petrifying_gaze_body} into {petrifying_gaze_stone}.' rule :petrifying_gaze_body, 'body rapidly {fuses}', 'body {fuses}' rule :petrifying_gaze_stone, 'cold stone', 'solid stone' rule :strikes, 'strikes', 'meets', 'hits' rule :stare_directly, 'stare straight', 'stare directly' rule :fuses, 'freezes', 'fuses', 'hardens' rule :last_memory_flash, 'The {last_memory_final} thing you {last_memory_experience}', 'Your {last_memory_final} {last_memory_moment}' rule :last_memory_experience, 'remember', 'see', 'experience', 'are consciously aware of' rule :last_memory_moment, 'experience', 'moment of awareness', 'moment of experience' rule :last_memory_final, 'final', 'last', 'very last' rule :reptilian_adj, 'scaly', 'dull coloured', 'scabrous', 'encrusted' rule :reptilian_noun, 'monster', 'reptile', 'lizard' rule :freeze_reaction, '{pause} with {shock}' rule :head_movement, 'turns', 'raises', 'lifts' rule :shock, 'shock', 'fright', 'fear' rule :pause, 'freeze', 'pause', 'step back', 'stand frozen' rule :horrific, 'horrifying', 'terrifying', 'abyssal' end
true
43082869d31791bc5a20d675e653b1a3f30a6c75
Ruby
hugovila/polygon
/spec/square_spec.rb
UTF-8
1,933
3.390625
3
[]
no_license
require './polygon' require './quadrilateral' require './parallelogram' require './square' describe Polygon do describe Quadrilateral do describe Parallelogram do describe Square do it "is a child of Polygon" do one_ancestor_to_expect = Polygon expect(Square.ancestors).to include(one_ancestor_to_expect) end it "is a child of Quadrilateral" do one_ancestor_to_expect = Quadrilateral expect(Square.ancestors).to include(one_ancestor_to_expect) end it "is a child of Parallelogram" do one_ancestor_to_expect = Parallelogram expect(Square.ancestors).to include(one_ancestor_to_expect) end it "have 1 sides and not raise_error" do equals_sides = 3 expect{ Square.new(equals_sides) }.not_to raise_error end it "can be created with one side" do sides_of_square = 4 expect(Square.new(3).my_number_of_sides).to eq(sides_of_square) end it "need to have 1 sides" do expect { Square.new(2,2) }.to raise_error(ArgumentError) end it "need to have 1 sides" do expect { Square.new(2,3,6,5,4) }.to raise_error(ArgumentError) end it "sides should have positive numbers" do expect{Square.new(-3)}.to raise_error(ArgumentError) expect{Square.new(-3)}.to raise_error(ArgumentError) expect{Square.new(-4)}.to raise_error(ArgumentError) end it "all sides should be numbers" do expect{ Square.new("lado") }.to raise_error(ArgumentError) end it "returns its own perimeter" do expect(Square.new(5).perimeter).to eq(20) end it "return its own area" do base = 2 area = base * base expect(Square.new(base).area).to eq(area) end end end end end
true
7f9bd84814153f40c8d51c0091408f9ddb4b91b9
Ruby
landongrindheim/dry-configurable
/lib/dry/configurable/class_methods.rb
UTF-8
2,209
2.609375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# frozen_string_literal: true require 'set' require 'dry/configurable/constants' require 'dry/configurable/dsl' require 'dry/configurable/methods' require 'dry/configurable/settings' module Dry module Configurable module ClassMethods include Methods # @api private def inherited(klass) super parent_settings = (respond_to?(:config) ? config._settings : _settings) klass.instance_variable_set('@_settings', parent_settings) end # Add a setting to the configuration # # @param [Mixed] key # The accessor key for the configuration value # @param [Mixed] default # The default config value # # @yield # If a block is given, it will be evaluated in the context of # a new configuration class, and bound as the default value # # @return [Dry::Configurable::Config] # # @api public def setting(*args, &block) setting = __config_dsl__.setting(*args, &block) _settings << setting __config_reader__.define(setting.name) if setting.reader? self end # Return declared settings # # @return [Set<Symbol>] # # @api public def settings @settings ||= Set[*_settings.map(&:name)] end # Return declared settings # # @return [Settings] # # @api public def _settings @_settings ||= Settings.new end # Return configuration # # @return [Config] # # @api public def config @config ||= Config.new(_settings) end # @api private def __config_dsl__ @dsl ||= DSL.new end # @api private def __config_reader__ @__config_reader__ ||= begin reader = Module.new do def self.define(name) define_method(name) do config[name] end end end if included_modules.include?(InstanceMethods) include(reader) end extend(reader) reader end end end end end
true
3745988992e0f4b7252eef776815bffa8f0f825a
Ruby
nakaaza/AtCoder
/practice/practice_contest/A.rb
UTF-8
160
3.234375
3
[]
no_license
# https://atcoder.jp/contests/practice/tasks/practice_1 a = gets.to_i b, c = gets.chomp.split(' ').map { |e| e.to_i } s = gets.chomp print "#{a + b + c} #{s}"
true
bea69fbcf540c9247e421c54f4a25302e75dcf9f
Ruby
ahrke/Launch_School
/lesson_5/practice_problems_1.rb
UTF-8
8,106
3.796875
4
[]
no_license
# Problem 1 # How would you order this array of number strings by descending numeric value? arr = ['10', '11', '9', '7', '8'] puts "#{arr.map {|value| value.to_i }.sort.reverse}" # alternatively arr.sort do |a,b| b.to_i <=> a.to_i end # Problem 2 # How would you order this array of hashes based on the year of publication of # each book, from the earliest to the latest? books = [ {title: 'One Hundred Years of Solitude', author: 'Gabriel Garcia Marquez', published: '1967'}, {title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', published: '1925'}, {title: 'War and Peace', author: 'Leo Tolstoy', published: '1869'}, {title: 'Ulysses', author: 'James Joyce', published: '1922'} ] puts "sorted books, by year: " sorted_books = books.sort_by {|hash| hash[:published] } puts sorted_books # Problem 3 # For each of these collection objects demonstrate how you would reference the letter 'g'. arr1 = ['a', 'b', ['c', ['d', 'e', 'f', 'g']]] puts "does it have a 'g'? #{arr1.flatten.include?('g')}" arr2 = [{first: ['a', 'b', 'c'], second: ['d', 'e', 'f']}, {third: ['g', 'h', 'i']}] p3_arr2 = arr2.flatten.map {|hash| hash.values } puts p3_arr2.flatten.include?('g') arr3 = [['abc'], ['def'], {third: ['ghi']}] p3_arr3 = arr3.map {|ele| ele.map {|el| if el.to_s.size == 3 el else el[1] end } } puts p3_arr3.flatten.join.split('').include?('g') hsh1 = {'a' => ['d', 'e'], 'b' => ['f', 'g'], 'c' => ['h', 'i']} puts hsh1.values.flatten.include?('g') hsh2 = {first: {'d' => 3}, second: {'e' => 2, 'f' => 1}, third: {'g' => 0}} p3_hsh2 = hsh2.map {|hsh| hsh[1].keys } puts p3_hsh2.flatten.include?('g') # Problem 4 # For each of these collection objects where the value 3 occurs, demonstrate how # you would change this to 4. arr1 = [1, [2, 3], 4] arr1[1][1] = 4 p arr1 arr2 = [{a: 1}, {b: 2, c: [7, 6, 5], d: 4}, 3] arr2[-1] = 4 p arr2 hsh1 = {first: [1, 2, [3]]} hsh1[:first][2][0] = 4 p hsh1 hsh2 = {['a'] => {a: ['1', :two, 3], b: 4}, 'b' => 5} hsh2[['a']][:a][2] = 4 p hsh2 # Problem 5 # Given this nested Hash: munsters = { "Herman" => { "age" => 32, "gender" => "male" }, "Lily" => { "age" => 30, "gender" => "female" }, "Grandpa" => { "age" => 402, "gender" => "male" }, "Eddie" => { "age" => 10, "gender" => "male" }, "Marilyn" => { "age" => 23, "gender" => "female"} } # figure out the total age of just the male members of the family. total_male_age = 0 munsters.each {|k,v| if v["gender"] == "male" total_male_age += v["age"] end } puts total_male_age # Problem 6 # One of the most frequently used real-world string properties is that of # "string substitution", where we take a hard-coded string and modify it with # various parameters from our program. # Given this previously seen family hash, print out the name, age and gender of # each family member: munsters = { "Herman" => { "age" => 32, "gender" => "male" }, "Lily" => { "age" => 30, "gender" => "female" }, "Grandpa" => { "age" => 402, "gender" => "male" }, "Eddie" => { "age" => 10, "gender" => "male" }, "Marilyn" => { "age" => 23, "gender" => "female"} } munsters.each {|k,v| puts "#{k.to_s} is #{v['age']} years old, and is a #{v['gender']}" } # Problem 7 # Given this code, what would be the final values of a and b? Try to work this # out without running the code. a = 2 b = [5, 8] arr = [a, b] arr[0] += 2 arr[1][0] -= a # a = 4, b = [3,8] puts a puts b # wrong, a = 2, b = [3,8] # arr[0] is modifying the array, not the element. arr[1][0] is modifying the # array # Problem 8 # Using the each method, write some code to output all of the vowels from the strings. hsh = {first: ['the', 'quick'], second: ['brown', 'fox'], third: ['jumped'], fourth: ['over', 'the', 'lazy', 'dog']} hsh.each {|k,v| str = v.join puts str.delete('^aeiou') } # Problem 9 # Given this data structure, return a new array of the same structure but with # the sub arrays being ordered (alphabetically or numerically as appropriate) in # descending order. arr = [['b', 'c', 'a'], [2, 1, 3], ['blue', 'black', 'green']] p9_arr = arr.map {|ele| ele.sort {|a,b| b <=> a } } p p9_arr # Problem 10 # Given the following data structure and without modifying the original array, # use the map method to return a new array identical in structure to the original # but where the value of each integer is incremented by 1. q10_og_arr = [{a: 1}, {b: 2, c: 3}, {d: 4, e: 5, f: 6}] q10_arr = q10_og_arr.map {|sub_arr| sub_arr.map {|k,v| [k,v+1] }.to_h } p q10_arr # alternative method: [{a: 1}, {b: 2, c: 3}, {d: 4, e: 5, f: 6}].map do |hsh| incremented_hash = {} hsh.each do |key, value| incremented_hash[key] = value + 1 end incremented_hash end # Problem 11 # Given the following data structure use a combination of methods, including # either the select or reject method, to return a new array identical in # structure to the original but containing only the integers that are multiples of 3. arr = [[2], [3, 5, 7], [9], [11, 13, 15]] p11_arr = arr.map {|ele| ele.select {|num| num % 3 == 0 } } p p11_arr # Problem 12 # Given the following data structure, and without using the Array#to_h method, # write some code that will return a hash where the key is the first item in # each sub array and the value is the second item. arr = [[:a, 1], ['b', 'two'], ['sea', {c: 3}], [{a: 1, b: 2, c: 3, d: 4}, 'D']] # expected return value: {:a=>1, "b"=>"two", "sea"=>{:c=>3}, {:a=>1, :b=>2, :c=>3, :d=>4}=>"D"} p12_hash = {} arr.each {|hsh| p12_hash[hsh[0]] = hsh[1] } p p12_hash # Problem 13 # Given the following data structure, return a new array containing the same # sub-arrays as the original but ordered logically according to the numeric # value of the odd integers they contain. arr = [[1, 6, 7], [1, 4, 9], [1, 8, 3]] # The sorted array should look like this: # [[1, 8, 3], [1, 6, 7], [1, 4, 9]] p13_arr = arr.sort {|a,b| a[2] <=> b[2] } p p13_arr # the correct way (mine was wrong) is: arr.sort_by {|sub_arr| sub_arr.select {|ele| ele.odd? } } # Problem 14 # Given this data structure write some code to return an array containing the # colors of the fruits and the sizes of the vegetables. The sizes should be # uppercase and the colors should be capitalized. hsh = { 'grape' => {type: 'fruit', colors: ['red', 'green'], size: 'small'}, 'carrot' => {type: 'vegetable', colors: ['orange'], size: 'medium'}, 'apple' => {type: 'fruit', colors: ['red', 'green'], size: 'medium'}, 'apricot' => {type: 'fruit', colors: ['orange'], size: 'medium'}, 'marrow' => {type: 'vegetable', colors: ['green'], size: 'large'}, } p14_arr = [] hsh.map {|_,v| p14_arr << v[:colors] p14_arr << v[:size].upcase } p p14_arr # Problem 15 # Given this data structure write some code to return an array which contains # only the hashes where all the integers are even. arr = [{a: [1, 2, 3]}, {b: [2, 4, 6], c: [3, 6], d: [4]}, {e: [8], f: [6, 10]}] p15_arr = arr.map {|hsh| hsh.select {|_,v| v.all? {|num| num.even?} } } p p15_arr # Problem 16 # A UUID is a type of identifier often used as a way to uniquely identify # items...which may not all be created by the same system. That is, without any # form of synchronization, two or more separate computer systems can create new # items and label them with a UUID with no significant chance of stepping on # each other's toes. # It accomplishes this feat through massive randomization. The number of # possible UUID values is approximately 3.4 X 10E38. # Each UUID consists of 32 hexadecimal characters, and is typically broken into # 5 sections like this 8-4-4-4-12 and represented as a string. # It looks like this: "f65c57f6-a6aa-17a8-faa1-a67f2dc9fa91" # Write a method that returns one UUID when called with no parameters. def new_UUID uuid = "" sections = [8,4,4,4,12] sections.each {|num| num.times {|_| option = Random.rand(0..1) option == 1 ? uuid << Random.rand(97..122).chr : uuid << Random.rand(0..9).to_s } uuid << "-" } uuid[0..-2] end p new_UUID p new_UUID
true
e3ae227dc2c38ddea73c987f6b017f8b414359de
Ruby
jasongutierrez1989/badges-and-schedules-online-web-pt-031119
/conference_badges.rb
UTF-8
382
3.234375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Write your code here. def badge_maker(name) puts ('Hello, my name is #{name}.') end def batch_badge_creator(nameArray) count = 0 nameArray.each {|name|} do array[count] = 'Hello, my name is #{name}.' count += 1 end end def assign_rooms(speakerArray) count = 0 speakerArray.map {|speaker| "Hello, #{name}! You\'ll be assigned to room #{count}", count += 1} end
true
0b71972bfbb28b810413284ed48706b338cb7c0a
Ruby
KahTim/bitly-clone
/app/models/url.rb
UTF-8
438
2.59375
3
[ "MIT" ]
permissive
class Url < ActiveRecord::Base # This is Sinatra! Remember to create a migration! validates :ori_url, presence: true validates :short_url, :ori_url, uniqueness: true validates :ori_url, format: {with: /(((ftp|http|https):\/\/)|(\/)|(..\/))(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/, message: "valid URLs only"} def self.shorten x = [*('A'..'Z'),*('a'..'z'),*('0'..'9')].shuffle[0,5].join return x end end
true
02aa104f698d0ab50dbc60cf8a79595345875f3d
Ruby
GoldenLion07/Ruby_on_Rails_Excercises
/Numerology.rb
UTF-8
2,291
3.75
4
[]
no_license
puts "Please enter your birthdate in the Month/Day/Year format" birthdate = gets.chomp def birth_path_number(birthdate) birth_path_number = birthdate[0].to_i + birthdate[1].to_i + birthdate[2].to_i + birthdate[3].to_i + birthdate[4].to_i + birthdate[5].to_i + birthdate[6].to_i + birthdate[7].to_i + birthdate[8].to_i + birthdate[9].to_i birth_path_number = birth_path_number.to_s birth_path_number = birthdate[0].to_i + birthdate[1].to_i if (birth_path_number > 9) then birth_path_number = birth_path_number.to_s birth_path_number = birth_path_number[0].to_i + birth_path_number[1].to_i end return birth_path_number end def message(birth_number) case birth_number when 1 then puts "One is the leader. The number one indicates the ability to stand alone, and is a strong vibration. Ruled by the Sun." when 2 then puts "This is the mediator and peace-lover. The number two indicates the desire for harmony. It is a gentle, considerate, and sensitive vibration. Ruled by the Moon." when 3 then puts "Number Three is a sociable, friendly, and outgoing vibration. Kind, positive, and optimistic, Three’s enjoy life and have a good sense of humor. Ruled by Jupiter." when 4 then puts "This is the worker. Practical, with a love of detail, Fours are trustworthy, hard-working, and helpful. Ruled by Uranus." when 5 then puts "This is the freedom lover. The number five is an intellectual vibration. These are ‘idea’ people with a love of variety and the ability to adapt to most situations. Ruled by Mercury." when 6 then puts "This is the peace lover. The number six is a loving, stable, and harmonious vibration. Ruled by Venus." when 7 then puts "This is the deep thinker. The number seven is a spiritual vibration. These people are not very attached to material things, are introspective, and generally quiet. Ruled by Neptune." when 8 then puts "This is the manager. Number Eight is a strong, successful, and material vibration. Ruled by Saturn." when 9 then puts "This is the teacher. Number Nine is a tolerant, somewhat impractical, and sympathetic vibration. Ruled by Mars." else "I don't think that number exists..." end end birth_number = birth_path_number(birthdate) print "your birth path number is #{birth_number}" message = message(birth_number) puts message
true
2e9bb563913d17a3febad6d41ea8aeba7bfca37b
Ruby
azimux/ax_boolean_radio
/lib/azimux/boolean_radio_helper.rb
UTF-8
3,155
2.765625
3
[ "MIT" ]
permissive
module Azimux module BooleanRadioHelper VALID_OPTIONS = [:label, :additional_row_classes, :omit_clear_link] def invalid_boolean_radio_options?(options) options.keys.each do |key| unless VALID_OPTIONS.include? key.to_sym return key end end false end def boolean_radio_for f, field, options = {} invalid_option = invalid_boolean_radio_options?(options) raise "Invalid boolean radio option: #{invalid_option}" if invalid_option options = options.dup label = options.delete(:label) || field.to_s.humanize raise "unexpected nil f.object_name in boolean_radio_for" unless f.object_name tr_classes = "ax_boolean_row" if options[:additional_row_classes] tr_classes = ([tr_classes] + Array(options[:additional_row_classes])).join(" ") end tag_name = "#{f.object_name}[#{field}]" render :partial => "boolean_radio/boolean_radio_for", :locals => { :tag_name => tag_name, :label => label, :builder => f, :field => field, :options => options, :tr_classes => tr_classes } end def boolean_radio_tag object_name, field, checked, options = {} if checked checked = [true, "true"].include? checked end checked = false if checked == "false" options = options.dup label = options.delete(:label) || field.to_s.humanize tr_classes = "ax_boolean_row" if options[:additional_row_classes] tr_classes = ([tr_classes] + Array(options[:additional_row_classes])).join(" ") end tag_name = "#{object_name}[#{field}]" render :partial => "boolean_radio/boolean_radio_tag", :locals => { :tag_name => tag_name, :checked => checked, :label => label, :options => options, :tr_classes => tr_classes } end def boolean_range &block content_tag :table do safe_join([ content_tag(:th), content_tag(:th, brh_translation_wrapper(:"yes")), content_tag(:th, brh_translation_wrapper(:"no")), content_tag(:th), capture(&block) ]) end end #Translation hooks: #override this method to place a wrapper around calls to brh_translator # the default just calls whatever block is passed to it. # if no block is supplied, it acts like brh_translator def brh_translation_wrapper *args, &block if block_given? capture(&block) else brh_last_part_of_key(args[0]) end end #override this method to translate keys. To use rails default #translator, "t", do something like # Azimux::BooleanRadioHelper.module_eval { def brh_translator *args; t *args; end } # in your config.after_initialize block # default behavior is just to show the value in English. So # brh_translator "link.Clear" would come out as "Clear" def brh_translator *args brh_last_part_of_key(args[0]) end private def brh_last_part_of_key key key.to_s.split(".").last end end end
true
03d4f2a2ec174a454e78790c19147a2fc4798a1f
Ruby
orenomba/ruby_learn_to_program
/lib/chapter09/baby_dragon.rb
UTF-8
475
3.625
4
[]
no_license
# encoding: utf-8 class BabyDragon attr_reader :fullness def initialize @fullness = 0 end def eat if 100 < @fullness + 10 @fullness = 100 "お腹いっぱい" else @fullness += 10 yield if block_given? end end def walk @fullness -= 5 if @fullness < 0 @fullness = 0 return "もう歩けない" end yield if block_given? end def hungry? @fullness < 30 end end
true
5b7ae31fbee8e93ddc7a975ab8599a873c85ccb7
Ruby
avallabh/project_management
/spec/features/add_owner_spec.rb
UTF-8
1,066
2.59375
3
[]
no_license
require 'spec_helper' feature 'user adds a building', %Q{ As a real estate associate I want to record a building owner So that I can keep track of our relationships with owners } do # Acceptance Criteria: # I must specify a first name, last name, and email address # I can optionally specify a company name # If I do not specify the required information, I am presented with errors # If I specify the required information, the owner is recorded and I am redirected to enter another new owner scenario 'add an owner' do visit '/owners' click_on "Add Owner" fill_in "First Name", with: "John" fill_in "Last Name", with: "Smith" fill_in "Email", with: "person@example.com" click_on "Save Owner" expect(page).to have_content('Owner saved!') expect(page).to have_content("person@example.com") expect(page).to_not have_content("can't be blank") end scenario "don't submit all the required info" do visit '/owners' click_on "Add Owner" click_on "Save Owner" expect(page).to have_content("can't be blank") end end
true
fca79883911bacb142b6904b4e05347a01714221
Ruby
semahawk/harr
/test/interpreter_test.rb
UTF-8
1,609
3.484375
3
[ "MIT" ]
permissive
require "test_helper" require "interpreter" class InterpreterTest < Test::Unit::TestCase def test_comment assert_equal 4, Interpreter.new.eval("a = 8 + 4 - 8; a % Could have done it better but its midnight.").ruby_value end def test_number assert_equal 1, Interpreter.new.eval("1").ruby_value end def test_true assert_equal true, Interpreter.new.eval("true").ruby_value end def test_unary assert_equal false, Interpreter.new.eval("!true").ruby_value assert_equal true, Interpreter.new.eval("!nil").ruby_value assert_equal true, Interpreter.new.eval("!false").ruby_value end def test_assign assert_equal 2, Interpreter.new.eval("a = 2; 3; a").ruby_value end def test_method code = <<-CODE matey rawr(a) a ends rawr("Yarr!") CODE assert_equal "Yarr!", Interpreter.new.eval(code).ruby_value end def test_reopen_class code = <<-CODE ship Number matey ten 10 ends ends 1.ten CODE assert_equal 10, Interpreter.new.eval(code).ruby_value end def test_define_class code = <<-CODE ship Barrel matey explodes true ends ends Barrel.new.explodes CODE assert_equal true, Interpreter.new.eval(code).ruby_value end def test_if code = <<-CODE if true "Ayay!" ends CODE assert_equal "Ayay!", Interpreter.new.eval(code).ruby_value end def test_interpret code = <<-CODE ship Blackbeard matey sails "Adventure Time!" ends ends object = Blackbeard.new if object rawr(object.sails) ends CODE assert_prints("Nodes\nAdventure Time!\n") { Interpreter.new.eval(code) } end end
true
7a8c35888fd3ebb502fc3aee103957021ae2e816
Ruby
smthom05/cross_check
/lib/game_teams.rb
UTF-8
1,139
2.921875
3
[]
no_license
class GameTeams attr_reader :game_id, :team_id, :hoa, :won, :settled_in, :head_coach, :goals, :shots, :hits, :pim, :powerPlayOpportunities, :powerPlayGoals, :faceOffWinPercentage, :giveaways, :takeaways def initialize(attribute_array) @game_id = attribute_array[0].to_i @team_id = attribute_array[1].to_i @hoa = attribute_array[2] @won = attribute_array[3] @settled_in = attribute_array[4] @head_coach = attribute_array[5] @goals = attribute_array[6].to_i @shots = attribute_array[7].to_i @hits = attribute_array[8].to_i @pim = attribute_array[9].to_i @powerPlayOpportunities = attribute_array[10].to_i @powerPlayGoals = attribute_array[11].to_i @faceOffWinPercentage = attribute_array[12].to_f @giveaways = attribute_array[13].to_i @takeaways = attribute_array[14].to_i end def won? if @won == "TRUE" true elsif @won == "FALSE" false end end end
true
9e3b0c2e11c71c7586434995e7ee127666db893a
Ruby
sidk/ruby-code-sample-2
/challenge.rb
UTF-8
992
4.03125
4
[]
no_license
# SMS can only be a maximum of 160 characters. # If the user wants to send a message bigger than that, we need to break it up. # We want a multi-part message to have this added to each message: # " - Part 1 of 2" # You need to fix this method, currently it will crash with > 160 char messages. def slice_string(string, slice_size) #only works for up to 9 parts yield string and return if string.length <= slice_size appender = " - Part 1 of 1" slicerator = string.chars.each_slice(slice_size - appender.length) number_of_slices = slicerator.count slicerator.with_index do |slice, index| yield "#{slice.join} - Part #{index+1} of #{number_of_slices}" end end # This method actually sends the message via a SMS carrier # This method works, you don't change it, def deliver_message_via_carrier(text, to, from) puts text puts to puts from true end message = "test-test" * 50 slice_string(message, 160) {|slice| deliver_message_via_carrier(slice, :to, :from)}
true
515d59f5a18d130779eee79dda918e5ce9d13b25
Ruby
masa-1013/atcoder
/abc158/B_CountBalls.rb
UTF-8
128
2.71875
3
[]
no_license
n, a, b = gets.split().map(&:to_i) tmp = n.divmod(a+b) if tmp[1] >= a puts tmp[0] * a + a else puts tmp[0] * a + tmp[1] end
true
09174aba5bd21eb70213cb2b635436d22e702ad7
Ruby
js658g/SAF
/learn/savon/savon_test.rb
UTF-8
1,453
3.5625
4
[]
no_license
# $Id: savon_test.rb 95 2016-04-06 20:35:25Z e0c2506 $ # Simple demo calling a webservice that converts between temperature units. require 'savon' # First we create the client. client = Savon.client do # Tell em where the WSDL is wsdl "http://www.webservicex.net/ConvertTemperature.asmx?WSDL" # And this overrides the default behavior of sending XML keys in lower camel # case (myKeyHere) to use standard camel case (MyKeyHere) because this # particular webservice wants it that way. convert_request_keys_to :camelcase end # Just some fun letting the user enter their own values. puts "Enter in Fahremheit or Celsius? (f/C) " celsius = gets.strip.casecmp("C") == 0 puts "How many degrees #{celsius ? "C" : "F"}? " degrees = gets.to_i units = { true => "degreeCelsius", false => "degreeFahrenheit" } # Now lets actually call the webservice. ConvertTemp is defined in the WSDL as # an operation. response = client.call(:convert_temp) do # And here we build the message contents, passing the temperature #, from # unit, and to unit. message(temperature: degrees, from_unit: units[celsius], to_unit: units[!celsius]) end # We can check some http stuff too throw Exception.new("Oh noes it wasn't OK!!") unless response.http.code == 200 # Grabbing the response body. puts "That is #{response.body[:convert_temp_response][:convert_temp_result]} "\ "#{celsius ? "F" : "C"}"
true
674f71961b355d46f5321519da9d8b255d64a502
Ruby
dmcouncil/data_works
/lib/data_works/works.rb
UTF-8
2,726
2.703125
3
[ "MIT" ]
permissive
module DataWorks class Works include Visualization def initialize # we keep a registry of all models that we create @data = {} # keep a registry of the 'current default' model of a given type @current_default = {} # keep a registry of the 'limiting scope' for parentage @bounding_models = {} end def method_missing(method_name, *args, &block) method_name = method_name.to_s if method_name.starts_with? 'add_' add_model(method_name, *args) else get_model(method_name, *args) end end def find_or_add(model_name) record = find(model_name, 1) record ? record : send("add_#{model_name}") end def was_added(model_name, model) model_name = model_name.to_sym @data[model_name] ||= [] @data[model_name] << model end def set_current_default(for_model:, to:) @current_default[for_model] = to end def clear_current_default_for(model) @current_default.delete(model) end def set_restriction(for_model:, to:, &block) if block_given? @bounding_models[for_model] = to block_return = block.call clear_restriction_for(for_model) block_return elsif @bounding_models[for_model] = to to end end def clear_restriction_for(model) @bounding_models.delete(model) end private def add_model(method_name, *args) if method_name =~ /\Aadd_(\w+)\Z/ model_name = $1 many = args[0].kind_of? Integer end if model_name grafter = Grafter.new(self, (many ? model_name.singularize : model_name)) if many grafter.add_many(*args) else grafter.add_one(*args) end end end def get_model(method_name, *args) if method_name =~ /\A(\w+?)(\d+)\Z/ model_name = $1 index = $2 elsif method_name =~ /\Athe_(\w+)\Z/ model_name = $1 index = 1 end find(model_name, index) end def find(model_name, index) model_name = model_name.to_sym if index == 1 && get_default_for(model_name) get_default_for(model_name) elsif index == 1 @data[model_name] ||= [] @data[model_name].reject{|e| has_invalid_parent?(e)}.first else @data[model_name] ||= [] @data[model_name][index.to_i-1] end end def get_default_for(model) @bounding_models[model] || @current_default[model] || nil end def has_invalid_parent?(model) @bounding_models.each do |k,v| return true if (model.respond_to?(k) && model.send(k) != v) end false end end end
true
f75518a7185cb8f7a44cd085662d21711e90d0c2
Ruby
antarestrader/jzform
/spec/validation_spec.rb
UTF-8
3,142
2.546875
3
[ "MIT" ]
permissive
require File.join( File.dirname(__FILE__), '..', 'lib',"jzform" ) describe "JZForm::Form Validations:" do before(:each) do @form = JZForm.new(:name=>'form') @form << {:name=>'basic',:datatype=>:string} @answer = {'basic'=>'foobar'} end describe "values" do describe "when a valid answer is provided" do before(:each) do @form.value = @answer end it "should be valid" do @form.should be_valid end it "should provide a value when it is valid" do @form.value.should ==(@answer) end it "should not have errors in the rendered hash" do @form.render(:hash).should_not have_key(:errors) end end describe "when an invalid answer is provided" do before(:each) do @form.exclusive=true @answer[:foo] = 'bar' @form.value = @answer end it "should return nil for a value with an invalid answer" do @form.value.should be_nil end it "should have errors" do @form.errors.length.should > 0 end it "should have a current value" do @form.current_value.should == @answer end it "there should be errors in a rendered hash" do @form.render(:hash)[:errors].should_not be_nil end end describe "when a valid answer is provided in a hash" do before(:each) do @form.exclusive = true #will help to make tests fail more easily @form.value = {'form'=>@answer} end it "should be valid" do @form.should be_valid end it "should provide a value when it is valid" do @form.value.should ==(@answer) end it "should not have errors in the rendered hash" do @form.render(:hash).should_not have_key(:errors) end end end describe "Whole form" do describe "with exclusivity" do before(:each) do @form.exclusive = true end describe "and valid data" do before(:each) do @form.value = @answer end it "should be valid" do #puts @form.errors unless @form.valid? @form.should be_valid end end describe "and invalid data" do before(:each) do @answer[:foo] = 'bar' @form.value = @answer end it "should NOT be valid" do @form.should_not be_valid end it "should have one error" do @form.errors.length.should == 1 @form.errors[0][:message].should match(/foo/) @form.errors[0][:message].should match(/exclusive/) end end end end describe " of fields" do before(:each) do @form << {:name=>'req',:datatype=>:string, :validations=>{:not_empty=>true}} @answer['req'] = 'present' end it "should NOT be valid if any field is invalid" do @answer.delete 'req' @form.value = @answer @form.should_not be_valid end it "should be valid if all fields are valid" do @form.value = @answer @form.should be_valid @form.value.should ==(@answer) end end end
true
3b58b4cd069700a8a149f16fa2ce0cfebd50ea88
Ruby
MatheusMuriel/RubyHackerRank
/Mini-MaxSum/Mini-MaxSum.rb
UTF-8
342
3.40625
3
[]
no_license
#!/bin/ruby #https://www.hackerrank.com/challenges/mini-max-sum/problem require 'json' require 'stringio' # Complete the miniMaxSum function below. def miniMaxSum(arr) resp = arr.combination(4).minmax_by{|x| x.sum}.map{|x| x.sum} puts resp[0].to_s + " " + resp[1].to_s end arr = gets.rstrip.split(' ').map(&:to_i) miniMaxSum arr
true
a512d2f0f5c5229c79dd116547fa27f668e98309
Ruby
translunar/boolean
/benchmarks.rb
UTF-8
1,876
2.9375
3
[]
no_license
require 'set' require 'benchmark' f = 10_000 ar1 = (1..(10*f)).to_a # 100_000 elements ar2 = ((5*f)..(15*f)).to_a # also 100_000 elements set1 = ar1.to_set set2 = ar2.to_set sset1 = SortedSet.new(ar1) sset2 = SortedSet.new(ar2) n = 10 #20000 Benchmark.bm(10) do |testcase| testcase.report('Array'){ n.times{ ar1 & ar2 } } testcase.report('Set'){ n.times{ set1 & set2 } } testcase.report('SortedSet') { n.times{ sset1 & sset2 } } testcase.report('Set2'){ n.times{ ar1.select{ |element| set2.include? element } } } testcase.report('Set2present'){ n.times{ ar1.any?{ |element| set2.include? element } } } testcase.report('SortedSet2'){ n.times{ ar1.select{ |element| sset2.include? element } } } testcase.report('SortedSet2present'){ n.times{ ar1.any?{ |element| sset2.include? element } } } end =begin # Same with or without rbtree, roughly user system total real Array 0.710000 0.020000 0.730000 ( 0.727614) Set 0.830000 0.010000 0.840000 ( 0.844341) SortedSet 2.110000 0.010000 2.120000 ( 2.125546) Set2 0.390000 0.000000 0.390000 ( 0.399684) Set2present 0.220000 0.000000 0.220000 ( 0.213202) SortedSet2 0.900000 0.000000 0.900000 ( 0.907959) SortedSet2present 0.440000 0.000000 0.440000 ( 0.444069) =end require './lib/hypergeometric' Benchmark.bm(10) do |testcase| testcase.report('Native') { n.times { Hypergeometric.cdf(2,3,5,3000) }} testcase.report('Ruby') { n.times { Hypergeometric.ruby_cdf(2,3,5,3000) }} testcase.report('GSL') { n.times { 1.0 - Distribution::Hypergeometric.cdf(1,3,5,3000)}} end n = 10000 Benchmark.bm(10) do |testcase| testcase.report('GSL') { n.times { GSL::Sf.lnfact(rand(100000)) }} testcase.report('Native') { n.times { Distribution::MathExtension::ApproxFactorial.stieltjes_ln_factorial(rand(100000)) }} end
true
a1c0108deafa4cb2a966256af7e368a9f8490a21
Ruby
denyago/auithorization-gems-example
/test_heimdallr.rb
UTF-8
436
2.59375
3
[]
no_license
require './common.rb' require './heimdallr.rb' # read puts 'Read: ' + User.restrict(@current_user).pluck(:name).join(', ') # update user = User.restrict(@current_user).find_by_id(42) begin user.update_attributes!(name: '42th User') rescue => e puts "Boom! #{e}" end puts 'Write: ' + user.name puts 'Write again: ' + User.find(42).name puts (user.implicit.id || '#FILTERED') puts "How proxy object looks like:" puts user.inspect
true
9c41c2534257b2104b0afedac05c20528edf7041
Ruby
djtango/oystercard
/lib/journeylog.rb
UTF-8
828
3.046875
3
[]
no_license
require_relative 'journey' class JourneyLog attr_reader :journeys def initialize(journey_klass: Journey) @journey_klass = journey_klass @jr = @journey_klass.new @journeys = [] end def start_journey(station) current_journey outstanding_charges @jr.start(station) end def exit_journey(station) @jr.finish(station) if journey_complete? outstanding_charges add_journey end end def outstanding_charges amount = @jr.fare if @jr.complete? amount else add_journey amount end end def journey_complete? @jr.complete? end private attr_reader :journey_klass, :jr def current_journey @jr.complete? ? @jr = @journey_klass.new : @jr end def add_journey @journeys << @jr @jr = @journey_klass.new end end
true
6893414234cd65820aa5f184941723ac1b659fc1
Ruby
TypicalPolar/Ruby-Training
/ex36.rb
UTF-8
1,680
3.515625
4
[]
no_license
module Game_Functions def self.chance_roller(choice_limit) choice_limit -= 1 rand(0..choice_limit) end def self.set_switch_opt2(switch_value, goto1, goto2) # Would be nice if we could remove indivial set switches end end module Game_Level_1 def self.set_01 puts "You regain consciousness on the front steps of a spooky run-down house. What do you do?" puts "[1] Examine the house" puts "[2] Run away" set_01_switch(gets.chomp.to_i) end def self.set_01_switch(switch_value) if switch_value == 1 set_01_01 elsif switch_value == 2 set_01_02 else puts "[ERROR] Invalid Option. Try again" set_01 end end def self.set_01_01 puts "You notice the right window's lock has fatigued enough to likely be pried opened. You also notice a strange rock by the flower bed." puts "[1] Attempt to pry the window open" puts "[2] Walk to the flower bed and examine the strange rock" set_01_01_switch(gets.chomp.to_i) end def self.set_01_01_switch(switch_value) if switch_value == 1 set_01_01_A elsif switch_value == 2 set_01_01_B else puts "[ERROR] Invalid Option. Try again" set_01_01 end end def self.set_01_01_A end def self.set_01_01_B end def self.set_01_02 puts "You walk away from the prouch but as your take your first steps you hear rustling in the bushes in the flower bed." puts "[1] Look back" puts "[2] Ignore and continue" end def self.set_01_02_A end def self.set_01_02_B end end module Game_Testing def self.testing_1 puts Game_Functions.chance_roller(5) end end Game_Level_1.set_01
true
be896c5a5d3debc74fa9854a65cd0fa21ff268ca
Ruby
roniRamon/W3D2
/aa_questions/questions_database.rb
UTF-8
8,125
2.765625
3
[]
no_license
require 'sqlite3' require 'singleton' require 'byebug' class QuestionDatabase < SQLite3::Database include Singleton def initialize super('questions.db') self.type_translation = true self.results_as_hash = true end end class Users attr_accessor :fname, :lname def self.find_by_id(id) user = QuestionDatabase.instance.execute(<<-SQL, id) SELECT * FROM users WHERE id = ? SQL raise "NO user found" if user.length == 0 Users.new(user.first) end def self.find_by_name(fname, lname) user = QuestionDatabase.instance.execute(<<-SQL, fname, lname) SELECT * FROM users WHERE fname = ? AND lname = ? SQL raise "NO user found" if user.length == 0 Users.new(user.first) end def initialize(options) @id = options['id'] @fname = options['fname'] @lname = options['lname'] end def authored_questions user = Question.find_by_author(@id) end def authored_replies user = Replies.find_by_user_id(@id) end def followed_questions QuestionFollows.followed_questions_for_user_id(@id) end def liked_questions QuestionLikes.liked_questions_for_user_id(@id) end end class Question attr_accessor :title, :body, :user_id def self.find_by_id(id) qa = QuestionDatabase.instance.execute(<<-SQL, id) SELECT * FROM questions WHERE id = ? SQL raise "NO question found" if qa.length == 0 Question.new(qa.first) end def self.find_by_author(author_id) qa = QuestionDatabase.instance.execute(<<-SQL, author_id) SELECT * FROM questions WHERE user_id = ? SQL raise "Author not found" if qa.length == 0 qa.map {|elem| Question.new(elem)} end def self.most_followed(n) QuestionFollow.most_followed_questions(n) end def self.most_liked(n) QuestionLikes.most_liked_question(n) end def initialize(options) @id = options['id'] @title = options['title'] @body = options['body'] @user_id = options['user_id'] end def author user = Users.find_by_id(@user_id) user.fname + " " + user.lname end def question_replies Replies.find_by_user_id(@user_id) end def followers QuestionFollows.followers_for_question_id(@id) end def likers QuestionLike.likers_for_question_id(@id) end def num_likes QuestionLikes.num_likes_for_question_id(@id) end end class QuestionFollows attr_accessor :user_id, :question_id def self.find_by_id(id) qafollow = QuestionDatabase.instance.execute(<<-SQL, id) SELECT * FROM question_follows WHERE id = ? SQL raise "NO followers found" if qafollow.length == 0 QuestionFollows.new(qafollow.first) end def self.followers_for_question_id(question_id) qafollow = QuestionDatabase.instance.execute(<<-SQL, question_id) SELECT * FROM users JOIN question_follows qf ON qf.user_id = users.id WHERE question_id = ? SQL raise "NO followers found" if qafollow.length == 0 qafollow.map { |user| Users.new(user) } end def self.followed_questions_for_user_id(user_id) qafollow = QuestionDatabase.instance.execute(<<-SQL, user_id) SELECT * FROM questions JOIN question_follows qf ON qf.question_id = questions.id WHERE qf.user_id = ? SQL raise "NO Question found" if qafollow.length == 0 qafollow.map { |qa| Question.new(qa) } end def self.most_followed_questions(n) qa = QuestionDatabase.instance.execute(<<-SQL, n) SELECT * FROM questions JOIN question_follows ON question_follows.question_id = questions.id GROUP BY question_follows.question_id ORDER BY count(question_follows.user_id) desc LIMIT n SQL raise "NO Question found" if qafollow.length == 0 qa.map { |el| Question.new(el) } end def initialize(options) @id = options['id'] @user_id = options['user_id'] @question_id = options['question_id'] end end class Replies attr_accessor :title, :body, :question_id, :user_id, :parent_id attr_reader :id def self.find_by_id(id) replie = QuestionDatabase.instance.execute(<<-SQL, id) SELECT * FROM replies WHERE id = ? SQL raise "NO replie found" if replie.length == 0 Replies.new(replie.first) end def self.find_by_user_id(user_id) replie = QuestionDatabase.instance.execute(<<-SQL, user_id) SELECT * FROM replies WHERE user_id = ? SQL raise "NO replie found for this user" if replie.length == 0 replie.map { |el| Replies.new(el) } end def self.find_by_question_id(question_id) replie = QuestionDatabase.instance.execute(<<-SQL, question_id) SELECT * FROM replies WHERE question_id = ? SQL raise "NO replie found for this question" if replie.length == 0 replie.map { |el| Replies.new(el) } end def author user = Users.find_by_id(@user_id) user.fname + " " + user.lname end def question Question.find_by_id(@question_id) end def parent_reply # self.find_by_id(@parent_id) replie = QuestionDatabase.instance.execute(<<-SQL, @parent_id) SELECT * FROM replies WHERE id = ? SQL raise "NO parent replies found" if replie.length == 0 Replies.new(replie.first) end def child_replies replie = QuestionDatabase.instance.execute(<<-SQL, @id) SELECT * FROM replies WHERE parent_id = ? SQL raise "NO child replies found" if replie.length == 0 replie.map { |el| Replies.new(el) } end def initialize(options) @id = options['id'] @title = options['title'] @body = options['body'] @question_id = options['question_id'] @user_id = options['user_id'] @parent_id = options['parent_id'] end end class QuestionLikes attr_accessor :user_id, :question_id def self.find_by_id(id) like = QuestionDatabase.instance.execute(<<-SQL, id) SELECT * FROM question_likes WHERE id = ? SQL raise "NO likes found" if like.length == 0 QuestionLikes.new(like.first) end def self.likers_for_question_id(question_id) like = QuestionDatabase.instance.execute(<<-SQL, question_id) SELECT DISTINCT users.id, fname, lname FROM users JOIN question_likes ON question_likes.user_id = users.id WHERE question_likes.question_id = ? SQL raise "NO likes found" if like.length == 0 like.map {|user| QuestionLikes.new(user) } end def self.num_likes_for_question_id(question_id) l = QuestionDatabase.instance.execute(<<-SQL, question_id) SELECT count(user_id) FROM question_likes WHERE question_id = ? GROUP BY question_id SQL l.first['q'] end def self.liked_questions_for_user_id(user_id) l = QuestionDatabase.instance.execute(<<-SQL, user_id) SELECT questions.id, questions.title, questions.body, questions.user_id FROM questions JOIN question_likes ql ON questions.id = ql.question_id WHERE ql.user_id = ? SQL raise "NO liked questions found" if l.length == 0 l.map {|qa| Question.new(qa) } end def self.most_liked_questions(n) qa = QuestionDatabase.instance.execute(<<-SQL, n) SELECT * FROM questions JOIN question_likes ON question_likes.question_id = questions.id GROUP BY question_likes.question_id ORDER BY count(question_likes.user_id) desc LIMIT n SQL raise "NO Question found" if qafollow.length == 0 qa.map { |el| Question.new(el) } end def initialize(options) @id = options['id'] @user_id = options['user_id'] @question_id = options['question_id'] end end
true
eba9e0705345bfc388d350ca479f4e2ce5e272d1
Ruby
msrashid/Exercise-sets-for-101-109---Small-Problems
/adv1/ex9.rb
UTF-8
838
3.5625
4
[]
no_license
require "pry" def merge (first_array, second_array) return first_array if second_array.first == nil return second_array if first_array.first == nil merged_array = first_array + second_array returned_merged_array = [] loop do returned_merged_array += [merged_array.min] merged_array.delete_at(merged_array.index(merged_array.min)) break if returned_merged_array.size == (first_array + second_array).size end returned_merged_array end def merge_sort(array) sub_array = array 2.times do |x| iteration_array = (0..((sub_array.size / 2) - 1)).to_a.map { |x| (x * 2) + 1 } return_array = [] first = 0 iteration_array.each { |last| return_array += [array[first..last]]; first = last + 1} sub_array = return_array return_array = [] end p sub_array end p merge_sort([9, 5, 7, 1]) == [1, 5, 7, 9]
true
49001c746d4fedaac20e7a2397fceb577ee1a2ef
Ruby
fguerra92/rails_ejercicios
/recta.rb
UTF-8
430
3.390625
3
[]
no_license
#Ejercicio video Asociaciones #se pide crear la clase recta, considerando que una recta está construida a partir de dos puntos require_relative 'punto.rb' class Recta def initialize(p1, p2) @p1 = p1 @p2 = p2 end end puts Recta.new(Punto.new(2, 3), Punto.new(3, 4)) #QUizz # class Casa # attr_accessor :pisos # def initialize(pisos = 1) # pisos # end # end # casa1 = Casa.new(5) # puts casa1.pisos.class
true
b43eec5672d033a27730e0eefeb4c0ce52fe6335
Ruby
izcom/sorting_cards
/lib/round.rb
UTF-8
1,077
3.65625
4
[]
no_license
require './lib/card' require './lib/deck' require 'pry' class Round attr_accessor :deck :guesses :number_correct :percent_correct :current_card def initialize(deck) @deck = deck @guesses = [] @number_correct = 0 short = @deck.instance_variable_get(:@cards) @current_card = short[0] # initializes to the first card in the deck end def record_guess(guess) @guesses << guess @deck.shift end def current_card short = @deck.instance_variable_get(:@cards) @current_card = short[0] # returns the first card in @cards end def guesses @guesses end def number_correct total = 0 @guesses.each do |guess| if guess.correct? == true @number_correct += 1 total += 1 end end return total end def percent_correct puts "Number correct: " + @number_correct.to_s percent = 0 if @number_correct > 0.0 percent = @guesses.count.to_f / @number_correct.to_f end return percent end end
true
05c56b0667f420723fccda954dec593b9620ccbe
Ruby
thoughtbot/factory_bot
/spec/acceptance/attribute_existing_on_object_spec.rb
UTF-8
1,757
3
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
describe "declaring attributes on a Factory that are private methods on Object" do before do define_model("Website", system: :boolean, link: :string, sleep: :integer) FactoryBot.define do factory :website do system { false } link { "http://example.com" } sleep { 15 } end end end subject { FactoryBot.build(:website, sleep: -5) } its(:system) { should eq false } its(:link) { should eq "http://example.com" } its(:sleep) { should eq(-5) } end describe "assigning overrides that are also private methods on object" do before do define_model("Website", format: :string, y: :integer, more_format: :string, some_funky_method: :string) Object.class_eval do private def some_funky_method(args) end end FactoryBot.define do factory :website do more_format { "format: #{format}" } end end end after do Object.send(:undef_method, :some_funky_method) end subject { FactoryBot.build(:website, format: "Great", y: 12345, some_funky_method: "foobar!") } its(:format) { should eq "Great" } its(:y) { should eq 12345 } its(:more_format) { should eq "format: Great" } its(:some_funky_method) { should eq "foobar!" } end describe "accessing methods from the instance within a dynamic attribute " \ "that is also a private method on object" do before do define_model("Website", more_format: :string) do def format "This is an awesome format" end end FactoryBot.define do factory :website do more_format { "format: #{format}" } end end end subject { FactoryBot.build(:website) } its(:more_format) { should eq "format: This is an awesome format" } end
true
232e9f408e2084968ae5e87ee3e3b01963354f1d
Ruby
xarisd/unittesting-with-minitest
/presentation/code/01-poormans-testing/02-separate-files-with-helper/test_helper.rb
UTF-8
371
3.015625
3
[ "MIT" ]
permissive
# encoding: utf-8 ## General assertion methods def assert(condition, message) if condition puts "." else puts "FAIL : #{message}" end end def assert_equal(expected, actual, message) condition = (expected == actual) unless condition message = "#{message} \t expected:\t'#{expected}' \t actual:\t'#{actual}'" end assert(condition, message) end
true
bb80dee674bf6374d7ff8db987238152482fdc02
Ruby
GabrielNagy/facter-ng
/lib/framework/core/fact_filter.rb
UTF-8
454
2.5625
3
[ "MIT" ]
permissive
# frozen_string_literal: true module Facter # Filter inside value of a fact. # e.g. os.release.major is the user query, os.release is the fact # and major is the filter criteria inside tha fact class FactFilter def filter_facts!(searched_facts) searched_facts.each do |fact| value = fact.filter_tokens.any? ? fact.value.dig(*fact.filter_tokens.map(&:to_sym)) : fact.value fact.value = value end end end end
true
b0238fc3279d07e19c78c7470912dbcfcb745715
Ruby
cyzanfar/PrimeGenerator
/prime.rb
UTF-8
612
3.59375
4
[]
no_license
class Prime attr_accessor :number def initialize(number) self.number = number prime_serie end def is_prime?(num) counter = 2 root_num = Math.sqrt(num).ceil while counter <= root_num if num % counter == 0 && num != counter return false break else counter += 1 end end return true end def percentage_prime ((prime_serie.size / number.to_f) * 100) end def prime_serie prime_array = [1] counter = 2 while counter < number if is_prime?(counter) prime_array << counter counter += 1 end counter += 1 end prime_array end end
true
29211ac0b88e0859f37eb3c319693e6b438519a4
Ruby
20000414t/furima-34444
/spec/models/user_spec.rb
UTF-8
4,929
2.578125
3
[]
no_license
require 'rails_helper' RSpec.describe User, type: :model do before do @user = FactoryBot.build(:user) end describe 'ユーザー新規登録' do context '新規登録できる時' do it 'nameとemail、passwordとpassword_confirmation, name_familyとname_first, name_family_kanaとname_first_kanaが存在すれば登録できる' do expect(@user).to be_valid end end context '新規登録できない時' do it 'nameが空では登録できない' do @user.name = '' @user.valid? expect(@user.errors.full_messages).to include("Name can't be blank") end it 'emailが空では登録できない' do @user.email = '' @user.valid? expect(@user.errors.full_messages).to include("Email can't be blank") end it 'passwordが空では登録できない' do @user.password = '' @user.valid? expect(@user.errors.full_messages).to include("Password can't be blank") end it 'passwordが一致しなければ登録できない' do @user.password_confirmation = '' @user.valid? expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password") end it '全角漢字のみ苗字が空では登録できない' do @user.name_family = '' @user.valid? expect(@user.errors.full_messages).to include("Name family can't be blank", "Name family is invalid") end it '全角漢字の名前が空では登録できない' do @user.name_first = '' @user.valid? expect(@user.errors.full_messages).to include("Name first can't be blank", "Name first is invalid") end it 'カナの苗字が空では登録できない' do @user.name_family_kana = '' @user.valid? expect(@user.errors.full_messages).to include("Name family kana can't be blank", "Name family kana is invalid") end it 'かなの名前が空では登録できない' do @user.name_first_kana = '' @user.valid? expect(@user.errors.full_messages).to include("Name first kana can't be blank", "Name first kana is invalid") end it '誕生日が空では登録できない' do @user.birthday = '' @user.valid? expect(@user.errors.full_messages).to include("Birthday can't be blank") end it 'passwordは6文字以上でないと登録できないこと' do @user.password = 'a1' @user.valid? expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password", "Password is too short (minimum is 6 characters)", "Password is invalid") end it 'passwordは英語のみでは登録できないこと' do @user.password = 'aaaaaaaa' @user.valid? expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password") end it 'passwordは数字のみでは登録できないこと' do @user.password = '11111111' @user.valid? expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password") end it 'passwordは全角では登録できないこと' do @user.password = 'ああああ' @user.valid? expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password", "Password is too short (minimum is 6 characters)", "Password is invalid") end it 'emailは@を含まないと登録できない' do @user.email = '12345asd' @user.valid? expect(@user.errors.full_messages).to include("Email is invalid") end it 'emailは一意性であること' do @user.email = '123456a' another_user = @user.email @user.valid? expect(@user.errors.full_messages).to include("Email is invalid") end it '苗字が漢字・平仮名・カタカナ以外では登録できないこと' do @user.name_family = 'aaaaa1' @user.valid? expect(@user.errors.full_messages).to include("Name family is invalid") end it '名前が漢字・平仮名・カタカナ以外では登録できないこと' do @user.name_first = 'aaaaaaaa1' @user.valid? expect(@user.errors.full_messages).to include("Name first is invalid") end it 'カナの苗字が全角カタカナ以外では登録できないこと' do @user.name_family_kana = 'aaaaaa1' @user.valid? expect(@user.errors.full_messages).to include("Name family kana is invalid") end it 'カナの名前が全角カタカナ以外では登録できないこと' do @user.name_first_kana = 'aaaaaaa1' @user.valid? expect(@user.errors.full_messages).to include("Name first kana is invalid") end end end end
true
31fda2dde89bc76a6df04adc99d14d8afe36b7f8
Ruby
dsajwan98/article-api
/app/controllers/articles_controller.rb
UTF-8
1,140
2.515625
3
[]
no_license
class ArticlesController<ApplicationController before_action :set_article, only: [:update, :destroy] def create @article=Article.new @article.name=params[:name] @article.description=params[:description] if (@article.save) render json: {message: 'Created successfully'} else render json: {message: 'Not Created'} end end def index @articles=Article.all render json: {articles: @articles} end def update if (@article.update(article_params)) render json: {message: 'Updated successfully'} else render json: {message: 'Not Updated'} end end def destroy if (@article.destroy) render json: {message: 'Deleted successfully'} else render json: {message: 'Not Deleted'} end end private def article_params params.require(:article).permit(:name,:description) end def set_article @article=Article.find(params[:id].to_i) end end
true
473d82ceedc87d0ae55706ee566a3cad85b926c1
Ruby
stefanbarolin/THP2020
/DAY07/exo_11.rb
UTF-8
115
3.203125
3
[]
no_license
puts ("Ecris un chiffre !") print ("> ") number = gets.chomp.to_i number.times do puts ("Salut, ça farte ?") end
true