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
65856e1de9296d9f750ab3c87c8b8686bb4717b5
Ruby
MixMasterT/Daily-Projects
/spec/deck_spec.rb
UTF-8
1,071
3.390625
3
[]
no_license
require "deck" require "rspec" describe "#initialize" do subject(:deck) {Deck.new} it "start with a full deck" do expect(deck.cards.length).to eq(52) end let(:high_card) {double("ace of spades", value: :ace, suit: :spades)} it "provides a deck ordered from highest to lowest value" do expect(deck.cards.first.value).to eq(high_card.value) expect(deck.cards.first.suit).to eq(high_card.suit) end end describe "#shuffle!" do let(:high_card) {double("ace of spades", value: :ace, suit: :spades)} let(:low_card) {double("ace of spades", value: :two, suit: :clubs)} subject(:deck) {Deck.new} it "Shuffles a deck of cards" do deck.shuffle! expect(deck.cards.first.value).not_to eq(high_card.value) expect(deck.cards.last.value).not_to eq(low_card.value) end end describe "#draw_card" do subject(:deck) {Deck.new} it "pops the last card in cards array" do expect(deck.draw_card.value).to eq(:two) end it "reduces the number of cards in the deck" do deck.draw_card expect(deck.num_cards).to eq(51) end end
true
ff10fc58f0f5c1f976c13e92081952beb5efdb2b
Ruby
frm/covid_pt
/lib/covid_pt/report.rb
UTF-8
3,975
2.71875
3
[ "MIT" ]
permissive
require "rest-client" require "pdf-reader" require "nokogiri" module CovidPT class Report MUNICIPALITY_EDGE_CASES = { "Monsaraz" => "Reguengos de Monsaraz", "Graciosa" => "Santa Cruz da Graciosa", "Penaguião" => "Santa Marta de Penaguião", "António" => "Vila Real de Santo António", }.freeze def initialize(date) @date = Date.parse(date) rescue ArgumentError => e puts e.message puts "Argument: #{date}" end def generate return @report if @report @report = { overall: overall_report, regional: regional_report, date: @date } cleanup @report end private attr_reader :date, :pdf def overall_report numbers_in_pdf = first_page.text.scan(/\d+/) # numbers_in_pdf[0] is the 19 from COVID-19 # numbers_in_pdf[9] is the 1 from "1 de janeiro 2020" # numbers_in_pdf[11] is the 2020 from "1 de janeiro 2020" { cases_in_north: numbers_in_pdf[1].to_i, deaths_in_north: numbers_in_pdf[2].to_i, cases_in_azores: numbers_in_pdf[3].to_i, deaths_in_azores: numbers_in_pdf[4].to_i, cases_in_centre: numbers_in_pdf[5].to_i, deaths_in_centre: numbers_in_pdf[6].to_i, cases_in_madeira: numbers_in_pdf[7].to_i, deaths_in_madeira: numbers_in_pdf[8].to_i, total_suspect_cases: numbers_in_pdf[10].to_i, cases_in_lisbon: numbers_in_pdf[12].to_i, deaths_in_lisbon: numbers_in_pdf[13].to_i, total_confirmed_cases: numbers_in_pdf[14].to_i, total_unconfirmed_cases: numbers_in_pdf[15].to_i, cases_in_alentejo: numbers_in_pdf[16].to_i, deaths_in_alentejo: numbers_in_pdf[17].to_i, awaiting_lab_results: numbers_in_pdf[18].to_i, cases_in_algarve: numbers_in_pdf[19].to_i, deaths_in_algarve: numbers_in_pdf[20].to_i, total_recovered_cases: numbers_in_pdf[21].to_i, total_deaths: numbers_in_pdf[22].to_i, total_under_suspicion: numbers_in_pdf[23].to_i, } end def regional_report municipalities = third_page. text. sub(/\A.+(Abrantes)/m, "\\1"). sub(/(Vouzela\s+\d+).*\z/m, "\\1"). gsub(/(\d)\s+/, "\\1\n"). gsub(/\*/, ""). split("\n"). map { |s| s.split(/\s{2,}/).reject(&:empty?) }. reject { |m| m.length < 2 }. map { |m| m.last(2) }. map { |m| [m.first, m.last.to_i] }. to_h handle_municipality_edge_cases(municipalities) end def handle_municipality_edge_cases(municipalities) MUNICIPALITY_EDGE_CASES.map do |k, v| municipalities[v] = municipalities.delete(k) end municipalities end def first_page pdf.pages.first end def third_page pdf.pages[2] end def pdf @_pdf ||= PDF::Reader.new(download_pdf) end def download_pdf response = RestClient.get(pdf_url) File.write(filename, response.body) filename end def filename formatted_date = date.strftime("%Y%m%d") "#{day_identifier}_DGS_boletim_#{formatted_date}.pdf" end def pdf_url return @_pdf_url if @_pdf_url response = RestClient.get("https://covid19.min-saude.pt/relatorio-de-situacao/") doc = Nokogiri::HTML(response.body) li = doc.css("#content_easy > div.single_content > ul", "li").children.select do |li| li.content.match(/#{@date.strftime("%d/%m/%Y")}/) end.first @_pdf_url = li.css("a").first.attr("href") end # Calculate the numerical identifier of the report # based on the 01/06/2020 report, which was #91 def day_identifier day_baseline = Date.parse("2020-06-01") number_baseline = 91 baseline_shift = date.mjd - day_baseline.mjd number_baseline + baseline_shift end def cleanup File.delete(filename) end end end
true
b24aac29563fd7af8316cf34b2e34fc7a907d00d
Ruby
svillegascreative/learn_ruby
/02_calculator/calculator.rb
UTF-8
332
3.734375
4
[]
no_license
def add(x, y) x + y end def subtract(x, y) x - y end def sum(array) total = 0 array.each {|x| total += x} total.to_i end def multiply(x, y) x * y end def product(array) total = 1 array.each {|x| total *= x} total.to_i end def factorial(n) total = 1 (1..n).each do |num| total *= num end total end
true
b56871f9303b8f356d06ac12c058277357b2bf92
Ruby
pmimark/muskokaroastery09052017
/current/app/models/shopping_cart.rb
UTF-8
3,124
2.890625
3
[]
no_license
class ShoppingCart attr_reader :items, :promo_discount, :shipping, :discount_id, :order_id def initialize() # @items = options[:items] || [] # @promo_discount = options[:promo_discount] || 0 # @discount_id = options[:discount_id] || nil @items = [] @promo_discount = 0 @discount_id = nil end def set_promo_discount(percentage, id) @promo_discount = percentage @discount_id = id end def promo_discount_price # Go through each product in the list, check if the current discount counts towards it, # then generate the discount amount for that product * its quantity discount_price = 0 discount = Discount.find(@discount_id) unless @discount_id.blank? if @promo_discount > 0 @items.each do |item| if discount.products.exists?(:id => item.product.id) discount_price += item.price * @promo_discount / 100 end end end return (discount_price * 100).to_i / 100.0 # Round to two decimal places end # def add_product(product) # current_item = @items.find { |item| item.product == product } # if current_item # current_item.increment_quantity # else # current_item = ShoppingCartItem.new(product) # @items.push current_item # end # return current_item # end def add_cart_item(product, quantity, option, flavour, subscription) current_item = @items.find { |item| item.product == product && item.option == option && item.flavour == flavour && item.as_json['subscription'] == subscription } if current_item current_item.add_to_quantity(quantity) else current_item = ShoppingCartItem.new(product, quantity, option, flavour, subscription) @items.push current_item end return current_item end def remove_product(product, option, flavour) item = @items.find { |i| i.product == product && i.option == option && i.flavour == flavour } item_index = @items.index(item) @items.delete_at(item_index) return item.item_id end def one_more(product) current_item = @items.find { |item| item.product == product } return current_item.increment_quantity end def one_less(product) current_item = @items.find { |item| item.product == product } return current_item.decrement_quantity end def total_items return @items.sum { |item| item.quantity } end def subtotal return @items.sum { |item| item.price } end def update_item_quantity(item_name, new_quantity) @items.each do |item| if item.item_id == item_name item.change_quantity(new_quantity) break end end end def update_item_name(sub_name, name) @items.each do |item| item.subscription_name(name) break end end def update_item_period(sub_period, period) @items.each do |item| item.subscription_period(period) break end end def update_item_date(sub_date, date) @items.each do |item| item.subscription_date(date) break end end def total_price return subtotal - promo_discount_price end end
true
26dbdb3bf752b7012545c26cefb912534ebc0487
Ruby
clockworkpc/cpc-study-projects
/advent_of_code_2020/aoc2020ruby/spec/advent_of_code/day_06_custom_customs_spec.rb
UTF-8
2,742
3
3
[]
no_license
require './lib/advent_of_code/custom_customs' RSpec.describe AdventOfCode::CustomCustoms do let(:puzzle_input) { File.read('./spec/fixtures/input_day_06.txt') } let(:sample_input) do <<~'HEREDOC' abc a b c ab ac a a a a b HEREDOC end describe 'Part 2' do it 'counts 3 YES for the first group' do lines = <<~'HEREDOC' abc HEREDOC expect(subject.yes_group_all(lines)).to eq(3) end it 'counts 0 YES for the second group' do lines = <<~'HEREDOC' a b c HEREDOC expect(subject.yes_group_all(lines)).to eq(0) end it 'counts 1 YES for third group' do lines = <<~'HEREDOC' ab ac HEREDOC expect(subject.yes_group_all(lines)).to eq(1) end it 'counts 1 YES for fourth group' do lines = <<~'HEREDOC' a a a a HEREDOC expect(subject.yes_group_all(lines)).to eq(1) end it 'counts 1 YES for fifth group' do lines = <<~'HEREDOC' b HEREDOC expect(subject.yes_group_all(lines)).to eq(1) end it 'counts 6 YES for all groups in sample_input' do expect(subject.yes_groups_all(sample_input)).to eq(6) end it 'counts X YES for all groups is puzzle_input' do expect(subject.yes_groups_all(puzzle_input)).to eq(3360) end end describe 'Part 1' do it 'counts YES for an individual' do line = 'abc' expect(subject.yes_individual(line)).to eq(3) end it 'counts 3 YES for a group of 3' do lines = <<~'HEREDOC' a b c HEREDOC expect(subject.yes_group_any(lines)).to eq(3) end it 'counts 3 YES for a group of 2' do lines = <<~HEREDOC ab ac HEREDOC expect(subject.yes_group_any(lines)).to eq(3) end it 'counts 1 YES for a group of 4' do lines = <<~HEREDOC a a a a HEREDOC expect(subject.yes_group_any(lines)).to eq(1) end it 'counts 1 YES for a group of 1' do lines = <<~HEREDOC b HEREDOC expect(subject.yes_group_any(lines)).to eq(1) end # it 'collects responses from all groups' do # coll = [%w[a b c], %w[a b c], %w[a b c], ['a'], ['b']] # expect(subject.res_groups(sample_input)).to eq(coll) # end it 'returns 11 for combined YES from all groups in sample input' do expect(subject.yes_groups_any(sample_input)).to eq(11) end it 'returns combined YES from all groups in puzzle input' do puts subject.yes_groups_any(puzzle_input) end end end
true
82f44dc7d6a1905a70e60e2adcd8bbe510cc0e9d
Ruby
EMG114/cartoon-collections-001-prework-web
/cartoon_collections.rb
UTF-8
593
3.28125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def roll_call_dwarves(dwarf_list) dwarf_list.each_with_index do |dwarf, index| puts "#{index + 1}. #{dwarf}" end end def summon_captain_planet(natural_elements) natural_elements.map do |natural_element| natural_element.capitalize! natural_element << "!" end end def long_planeteer_calls(planeteer_calls) planeteer_calls.any? { |call| call.length > 4 } end def find_the_cheese(food_list) cheese_types = ["cheddar", "gouda", "camembert"] found_cheeses = [] return food_list.find { |food_item| cheese_types.include?(food_item) } end
true
fe4e50a01b5a8bfdc6bd375e3fd9ff19b2448ee0
Ruby
pusewicz/sonia
/widgets/foursquare/foursquare.rb
UTF-8
1,863
2.59375
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
module Sonia module Widgets class Foursquare < Sonia::Widget CHECKINS_URL = "http://api.foursquare.com/v1/checkins.json" def initialize(config) super(config) EventMachine::add_periodic_timer(150) { fetch_data } end def initial_push fetch_data end def format_checkin(checkin) { :name => "#{checkin["user"]["firstname"]} #{checkin["user"]["lastname"]}", :avatar_url => checkin["user"]["photo"], :venue => checkin["venue"]["name"], :when => time_ago_in_words(Time.now - Time.parse(checkin["created"])) } end private def fetch_data log_info "Polling `#{CHECKINS_URL}'" http = EventMachine::HttpRequest.new(CHECKINS_URL).get(headers) http.errback { log_fatal_error(http) } http.callback { handle_fetch_data_response(http) } end def handle_fetch_data_response(http) if http.response_header.status == 200 parse_response(http.response) else log_unsuccessful_response_body(http.response) end end def parse_response(response) messages = [] parse_json(response)["checkins"][0..5].map do |checkin| messages << format_checkin(checkin) if checkin["venue"] end push messages rescue => e log_backtrace(e) end def headers { :head => { 'Authorization' => [config.username, config.password] } } end def time_ago_in_words(seconds) case seconds when 0..60 then "#{seconds.floor} seconds" when 61..3600 then "#{(seconds/60).floor} minutes" when 3601..86400 then "#{(seconds/3600).floor} hours" else "#{(seconds/86400).floor} days" end end end end end
true
7dba1024dcd67da42d009358d12e5c44ea0a3e88
Ruby
brianchiang-tw/RoR_Intro
/class_methods_variables.ru
UTF-8
615
4.25
4
[]
no_license
class MathFunctions def self.double( var ) times_called; return (var * 2) end # Using << self class << self def times_called # Initialized to 0 by default @@times_called ||= 0; return @@times_called += 1 end end end # Outside of class def MathFunctions.triple( var ) times_called; return var*3 end # No instance created. # expected output # 10 puts MathFunctions.double(5) # expected output # 24 puts MathFunctions.triple(8) # expected output # 3 puts MathFunctions.times_called
true
7c6158ffe2cfe9b1b16a6182296cbecda9302182
Ruby
TenjinInc/procrastinator
/lib/procrastinator/task_store/simple_comma_store.rb
UTF-8
6,023
2.828125
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'csv' require 'pathname' module Procrastinator # Task storage strategies. # # All task stores must implement the API #read, #create, #update, #delete. module TaskStore # Simple Task I/O adapter that writes task information (ie. TaskMetaData attributes) to a CSV file. # # SimpleCommaStore is not designed for efficiency or large loads (10,000+ tasks). For critical production # environments, it is strongly recommended to use a more robust storage mechanism like a proper database. # # @author Robin Miller class SimpleCommaStore # Ordered list of CSV column headers HEADERS = [:id, :queue, :run_at, :initial_run_at, :expire_at, :attempts, :last_fail_at, :last_error, :data].freeze # CSV file extension EXT = 'csv' # Default filename DEFAULT_FILE = Pathname.new("procrastinator-tasks.#{ EXT }").freeze # CSV Converter lambda # # @see CSV READ_CONVERTER = proc do |value, field_info| if field_info.header == :data value elsif Task::TIME_FIELDS.include? field_info.header value.empty? ? nil : Time.parse(value) else begin Integer(value) rescue ArgumentError value end end end attr_reader :path def initialize(file_path = DEFAULT_FILE) @path = Pathname.new(file_path) if @path.directory? || @path.to_s.end_with?('/') @path /= DEFAULT_FILE elsif @path.extname.empty? @path = @path.dirname / "#{ @path.basename }.csv" end @path = @path.expand_path freeze end # Parses the CSV file for data matching the given filter, or all if no filter provided. # # @param filter [Hash] Specified attributes to match. # @return [Array<Hash>] def read(filter = {}) CSVFileTransaction.new(@path).read do |existing_data| existing_data.select do |row| filter.keys.all? do |key| row[key] == filter[key] end end end end # Saves a task to the CSV file. # # @param queue [String] queue name # @param run_at [Time, nil] time to run the task at # @param initial_run_at [Time, nil] first time to run the task at. Defaults to run_at. # @param expire_at [Time, nil] time to expire the task def create(queue:, run_at:, expire_at: nil, data: '', initial_run_at: nil) CSVFileTransaction.new(@path).write do |tasks| max_id = tasks.collect { |task| task[:id] }.max || 0 new_data = { id: max_id + 1, queue: queue, run_at: run_at, initial_run_at: initial_run_at || run_at, expire_at: expire_at, attempts: 0, data: data } generate(tasks + [new_data]) end end # Updates an existing task in the CSV file. # # @param id [Integer] task ID number # @param data [Hash] new data to save def update(id, data) CSVFileTransaction.new(@path).write do |tasks| task_data = tasks.find do |task| task[:id] == id end task_data&.merge!(data) generate(tasks) end end # Removes an existing task from the CSV file. # # @param id [Integer] task ID number def delete(id) CSVFileTransaction.new(@path).write do |existing_data| generate(existing_data.reject { |task| task[:id] == id }) end end # Generates a CSV string from the given data. # # @param data [Array] list of data to convert into CSV # @return [String] Generated CSV string def generate(data) lines = data.collect do |d| Task::TIME_FIELDS.each do |field| d[field] = d[field]&.iso8601 end CSV.generate_line(d, headers: HEADERS, force_quotes: true).strip end lines.unshift(HEADERS.join(',')) lines.join("\n") << "\n" end # Adds CSV parsing to the file reading class CSVFileTransaction < FileTransaction # (see FileTransaction#transact) def transact(writable: nil) super(writable: writable) do |file_str| yield(parse(file_str)) end end private def parse(csv_string) data = CSV.parse(csv_string, headers: true, header_converters: :symbol, skip_blanks: true, converters: READ_CONVERTER, force_quotes: true).to_a headers = data.shift || HEADERS data = data.collect do |d| headers.zip(d).to_h end correct_types(data) end def correct_types(data) non_empty_keys = [:run_at, :expire_at, :attempts, :last_fail_at] data.collect do |hash| non_empty_keys.each do |key| hash.delete(key) if hash[key].is_a?(String) && hash[key].empty? end hash[:attempts] ||= 0 # hash[:data] = (hash[:data] || '').gsub('""', '"') hash[:queue] = hash[:queue].to_sym hash end end end end end end
true
4f448ead00cbcc61f397e0958a6452eb7c957bfa
Ruby
GiovaniGil/CaixaEletronico
/test/models/cliente_test.rb
UTF-8
634
2.59375
3
[]
no_license
require "test_helper" class ClienteTest < ActiveSupport::TestCase def cliente @cliente ||= Cliente.new nome: "Giovani Paulino", email: 'j@j.com.br', password: Devise::Encryptor.digest(Cliente, 'password') end def test_valid assert cliente.valid?, "Erro no modelo Cliente: "+errors end def test_sem_nome cliente.nome = nil refute cliente.valid? end def test_tamanho_nome cliente.nome = "Abcdefghi" refute cliente.valid? end private def errors erro = "" if cliente.errors.any? cliente.errors.full_messages.each do |message| erro = erro + message + "|" end end erro end end
true
cdd539a12696b5b5a7ad6bf3265b3cb2412c5391
Ruby
gdistasi/omf-tools
/routing/static_routing.rb
UTF-8
978
2.515625
3
[]
no_license
require 'core/orbit.rb' require 'core/routing_stack.rb' class StaticRouting < RoutingStack def initialize(prefix) @prefix=prefix end def InstallStack @orbit.GetNodes().each do |node| node.GetInterfaces().each do |ifn| if (ifn.IsWifi()) then address=Address.new("#{@prefix}.#{ifn.GetChannel()}.#{node.GetId()+1}",24) ifn.AddAddress(address) @orbit.AssignAddress(node, ifn, address) end if (ifn.IsWifi()) then if (ifn.GetMode()=="station") then #@orbit.RunOnNode(node, "ip address del default; ip address add default #{@orbit.GetRealName(node, ifn)}") end end end end #do nothing, wired link ip addresses are assigned by Orbit class @orbit.GetTopology().GetWiredLinks().each do |link| end end #start the routing stack def StartStack #puts "StartStack not defined!" #exit 1 end def GetIpFromId(id) end end
true
96c4b781b17215b72149aaa78705a3938a45d90c
Ruby
jerryzhucs1999/ICS-Course
/ICS-Course/ch10/dictSort.rb
UTF-8
524
3.890625
4
[]
no_license
def dictionary_sort arr capital_sort arr, [] end def capital_sort unsorted, sorted if unsorted.length <= 0 return sorted end smallest = unsorted.pop still_unsorted = [] unsorted.each do |var| if var.downcase < smallest.downcase still_unsorted.push smallest smallest = var else still_unsorted.push var end end sorted.push smallest capital_sort still_unsorted, sorted end puts(dictionary_sort(['Hello', 'there', 'MY', 'Name', 'is', 'Jerry', 'Zhu', 'hello', 'zhu', 'Zhu']))
true
eb3bfef4c37928ab630f59f426ca9d7187495197
Ruby
Wenhui/BestBay
/app/models/comment.rb
UTF-8
1,110
2.890625
3
[]
no_license
#Corresponding database table: comments #This class describes a comment that a user can leave for an item. # #It has the following attributes: # [created_at] :datetime # [updated_at] :datetime # [id] :integer id of the comment # [item_id] :integer id of the item that is commented; must be present # [user_id] :integer id of the user who leaves a comment; must be present # [content] :string the body of the comment; must be present and is limited to 140 characters # Comment associations with other models: # The comment belongs to a user and to an item. class Comment < ActiveRecord::Base attr_accessible :content, :item_id, :user_id belongs_to :commenter, :class_name=>'User', :foreign_key => 'user_id' belongs_to :commented_item, :class_name =>'Item', :foreign_key => 'item_id' validates :content, :presence => true, :length => {maximum:140} validates :user_id, :presence => true validates :item_id, :presence => true default_scope order: 'comments.created_at DESC' end
true
3f2d272ca09bbb48a795d1c90498334fa6c66ec7
Ruby
Greg-Aubert/mini_game_POO
/lib/player.rb
UTF-8
3,079
3.734375
4
[]
no_license
class Player #génère une classe qui permettra la création de joueurs respectant les paramètres ci dessous attr_accessor :name, :life_points def initialize(name) @name = name #nom du personnage @life_points = 10 #nb de pdv du personnage end def show_state #permet d'afficher les points de vie du personnage en question ("self") puts "#{self.name} a #{self.life_points} points de vie" end def gets_damage(damage) #permet de réduire le capital de point de vie du perso self.life_points = life_points - damage if self.life_points <= 0 #si il a 0 pdv alors il meurt return "le joueur #{self.name} a été tué" end end def attacks(player) #permet à un perso d'attaquer un autre puts "le joueur #{self.name} attaque le joueur #{player.name}" attack_damage = compute_damage #compute fait appel à la def suivant compute_damage player.gets_damage( attack_damage) #gets_damage fait appel à la def précédente qui réduit le capital pdv puts "il lui inflige #{attack_damage} points de dommages" end def compute_damage return rand(1..6) #génère un chiffre aléatoire entre 1 et 6 end end class HumanPlayer < Player #génère une sous-classe respectant les mêmes éléments que Player avec des modifs attr_accessor :weapon_level def initialize(name) @life_points = 100 #nouveau capital pdv @weapon_level = 1 #nouvelle variable d'instance @name = name end def show_state #idem qu'avant mais phrase différente pour ajouter le weapon_level puts "#{self.name} a #{self.life_points} points de vie et une arme de niveau #{self.weapon_level}" end def compute_damage #idem qu'avant mais avec le multiplicateur weapon_level rand(1..6) * @weapon_level end def search_weapon #permet de changer le weapon_level avec un jet de dés aléatoire new_weapon = rand(1..6) #jet de dés aléatoire puts "Tu as trouvé une arme de niveau #{new_weapon}" if new_weapon > @weapon_level #si le lancer est supérieur au weapon_level existant, il le remplace @weapon_level = new_weapon puts "Youhou ! Elle est meilleure que ton arme actuelle : tu la prends." else #sinon pas de changement puts "C'est de la camelotte cette arme !" end end def search_health_pack #permet de récupérer de la vie grace à un lancer de dés aléatoire health_pack = rand(1..6) #lancer aléatoire avec conséquences selon résultat puts "jet de des #{health_pack}" if health_pack == 1 puts "Pas de chance, tu vas creuver" elsif health_pack == (2..5) puts "Bravo! 50 points de vie pour continuer la traque" if self.life_points+50 > 100 #si total est supérieur à 100, alors total est bloqué à 100 self.life_points = 100 else #sinon vie restant + 50 self.life_points+= 50 end else puts "Jakpot, tu récupères 80 points de vie" if self.life_points+80 > 100 #idem self.life_points = 100 else self.life_points+=80 #idem end end end end
true
b7b1e3edc7ba7f1875a7e0e684a21d0a369a7c0f
Ruby
aziparu/gilded_rose_kata_1
/test/models/gilded_rose_spec.rb
UTF-8
1,725
2.921875
3
[]
no_license
require 'rails_helper' describe GildedRose do describe '#update_quality' do it 'does not change the name' do items = [Item.new('foo', 0, 0)] GildedRose.new(items).update_quality() expect(items[0].name).to eq 'foo' end it 'does not degrade quality below zero' do no_quality_item = Item.new('bar', 1, 0) one_quality_item = Item.new('baz', 0, 1) items = [no_quality_item, one_quality_item] GildedRose.new(items).update_quality() expect(items.map(&:quality)).to all(eq 0) end context 'given a normal item' do context 'with quality of at least 2' do it 'degrades quality by 2 if the sell by date has passed ( <= 0)' do items = [Item.new('foo', -1, 3)] GildedRose.new(items).update_quality() expect(items[0].quality).to eq 1 end end it 'degrades quality by 1 if the sell by date has not passed ( > 0)' do items = [Item.new('foo', 1, 3)] GildedRose.new(items).update_quality() expect(items[0].quality).to eq 2 end end context 'given an Aged Brie' do let (:aged_brie) {Item.new('Aged Brie', 0, 0)} let (:subject) { GildedRose.new([aged_brie]) } context 'the sell date has passed' do it 'increases in quality 2 per day' do aged_brie.sell_in = 0 subject.update_quality expect(aged_brie.quality).to eq 2 end end context 'the sell date has not passed' do it 'increases in quality 1 per day' do aged_brie.sell_in = 1 subject.update_quality expect(aged_brie.quality).to eq 1 end end end it 'is getting complex' end end
true
5b01037c32c292880f94b1015f3c81989a173f4f
Ruby
Krolmir/ruby-exercises
/rb120_object_oriented_programming/oo_basics_4/prefix_the_name.rb
UTF-8
273
4.25
4
[]
no_license
# PRoblem: Add the proper accessor method so that name is returns with Mr. class Person attr_reader :name def name=(first_name) @name = "Mr. " + first_name end end person1 = Person.new person1.name = 'James' puts person1.name # Expected output: # Mr. James
true
f7186c4b8e4df24135ee70292fd596d773d5d2f0
Ruby
keithb418/lv-gsa
/test/selenium-ruby/spec/menu_spec.rb
UTF-8
1,202
2.625
3
[]
no_license
require_relative '../../selenium-ruby/pages/Welcome' require_relative '../../selenium-ruby/pages/Menu' describe 'Menu' do # GSA-7: Menu Button before(:all) do @welcome = Welcome.new (@driver) @menu = Menu.new (@driver) @welcome.return_proceed_button.click end it 'will have links to graph, medlist, about' do @menu.open_menu expect(@menu.return_graph_link).to be_truthy expect(@menu.return_about_link).to be_truthy expect(@menu.return_medlist_link).to be_truthy @menu.open_menu # click open a 2nd time will close it end # verify each link takes you to the correct page it 'clicking graph link will take you to the correct page' do @menu.open_menu @menu.return_graph_link.click expect(@menu.return_subheader_text).to match 'Medication Warnings Chart' end it 'clicking about will take you to the correct page' do @menu.open_menu @menu.return_about_link.click expect(@menu.return_subheader_text).to match 'About' end it 'clicking med list link will take you to the correct page' do @menu.open_menu @menu.return_medlist_link.click expect(@menu.return_subheader_text).to match 'Search for a medicine' end end
true
d5deb4324bc0cfd39269b3be970fd69a3f318136
Ruby
infochimps-labs/senor_armando
/lib/senor_armando/rack/set_content_type.rb
UTF-8
2,583
2.515625
3
[ "MIT" ]
permissive
require 'rack/mime' require 'rack/respond_to' require 'pathname' module SenorArmando module Rack # The render middleware will set the Content-Type of the response # based on the provided HTTP_ACCEPT headers. # # @example # use SenorArmando::Rack::SetContentType # class SetContentType include ::Rack::RespondTo include Goliath::Rack::AsyncMiddleware def initialize(app, types=nil) @app = app ::Rack::RespondTo.media_types = types ? [types].flatten : ['json'] @default = media_types.first end FILE_EXTENSION_RE = /\A(.*)\.([\w\-]*)\z/o def call(env) if FILE_EXTENSION_RE.match(env['PATH_INFO']) path, ext = [$1, $2] unless ::Rack::RespondTo.media_types.include?(ext) raise Goliath::Validation::BogusFormatError.new("Allowed formats [#{media_types.join(',')}] do not include .#{ext}") end env['PATH_INFO'] = path env['REQUEST_PATH'] = path env['HTTP_ACCEPT'] = concat_mime_type(env['HTTP_ACCEPT'], ::Rack::Mime.mime_type(".#{ext}", @default)) env.params['format'] = ext end super(env) end def post_process(env, status, headers, body) ::Rack::RespondTo.env = env # raise Goliath::Validation::BogusFormatError.new('yo what up') # the respond_to block is what actually triggers the # setting of selected_media_type, so it's required respond_to do |format| ::Rack::RespondTo.media_types.each do |type| format.send(type, Proc.new { body }) end end extra = { 'Content-Type' => get_content_type(env), 'Server' => Settings.app_name, 'Vary' => [headers.delete('Vary'), 'Accept'].compact.join(',') } [status, extra.merge(headers), body] end private def media_types ::Rack::RespondTo.media_types end def concat_mime_type(accept, type) (accept || '').split(',').unshift(type).compact.join(',') end def get_content_type(env) type = if env.respond_to? :params fmt = env.params['format'] fmt = fmt.last if fmt.is_a?(Array) if !fmt.nil? && fmt !~ /^\s*$/ ::Rack::RespondTo::MediaType(fmt) end end type = ::Rack::RespondTo.env['HTTP_ACCEPT'] if type.nil? type = ::Rack::RespondTo.selected_media_type if type == '*/*' "#{type}; charset=utf-8" end end end end
true
451f39330bc4af21e3985ec9e27668a98ebfd7b5
Ruby
shiratsu/shoppingrails
/lib/tasks/rakuten_category_crawl.rb
UTF-8
1,064
2.515625
3
[]
no_license
# coding: utf-8 require 'net/http' require 'uri' require 'json' require "date" class Tasks::RakutenCategoryCrawl # メイン処理 def self.execute d = Date.today now = d.strftime("%Y-%m-%d %H:%M:%S") #APIリクエスト回数 start = 0; apiRequestLimit = 2000 apikey = '1059788590851227265' category_id=0 url = 'https://app.rakuten.co.jp/services/api/IchibaGenre/Search/20120723' #jsonとってきてパース uri = URI.parse(url+'?applicationId='+apikey+'&genreId='+category_id.to_s+'&format=json') json = Net::HTTP.get(uri) result = JSON.parse(json) # puts result hash = result['children'] # puts hash #ループでバルクインサート作る category_list = [] hash.each do |category| # puts category if category['child']['genreId'] != nil category_list << Category.new(category_id: category['child']['genreId'], category_name: category['child']['genreName'], api_type: 3) end end # Category.import category_list end end
true
e3c20371cd10b6d392fef01152fa14e76978887f
Ruby
maureena/pippin
/db/seeds.rb
UTF-8
1,089
2.71875
3
[]
no_license
require 'faker' # Create Users 5.times do user = User.new( name: Faker::Name.name, email: Faker::Internet.email, password: Faker::Lorem.characters(10) ) user.skip_confirmation! user.save end users = User.all # Create Venues 20.times do Venue.create( name: Faker::Lorem.words(3).join(" "), body: Faker::Lorem.paragraph(2), address: Faker::Address.street_address, phone: Faker::PhoneNumber.cell_phone, website: Faker::Internet.url ) end venues = Venue.all # Create Categories 10.times do Category.create( name: Faker::Lorem.words(2).join(" ") ) end categories = Category.all # Create Events 50.times do e = Event.create( title: Faker::Lorem.sentence, body: Faker::Lorem.paragraph(2), price: Faker::Commerce.price) e.venues<<venues.sample e.categories<<categories.sample end events = Event.all User.first.update_attributes( email: 'maureen.adamo@gmail.com', password: 'helloworld', ) puts "Seed finished" puts "#{User.count} users created" puts "#{Event.count} events created" puts "#{Venue.count} venues created"
true
3d5be36abe18a69d97d09b21268486cd7543ccba
Ruby
quick919/sandox
/2017/12/testdriven_ruby/Money.rb
UTF-8
757
3.71875
4
[]
no_license
require_relative './ExpressionInterface' require_relative './Sum' class Money < ExpressionInterface attr_accessor :amount, :currency def initialize(amount, currency) @amount = amount @currency = currency end def ==(other_money) @amount == other_money.amount && @currency == other_money.currency end def self.dollar(amount) return Money.new(amount, "USD") end def self.franc(amount) return Money.new(amount, "CHF") end def times(multiplier) return Money.new(@amount * multiplier, currency) end def currency return @currency end def plus(addend) return Sum.new(self, addend) end def reduce(bank,to) rate = bank.rate(@currency, to) return Money.new(@amount / rate, to) end end
true
b46f4b832f3332dbe7bed0b6cd64627bb8fd523b
Ruby
careo/neverblock
/lib/neverblock/core/pool.rb
UTF-8
2,635
2.953125
3
[ "Ruby" ]
permissive
module NeverBlock # Author:: Mohammad A. Ali (mailto:oldmoe@gmail.com) # Copyright:: Copyright (c) 2008 eSpace, Inc. # License:: Distributes under the same terms as Ruby # # A pool of initialized fibers # It does not grow in size or create transient fibers # It will queue code blocks when needed (if all its fibers are busy) # # This class is particulary useful when you use the fibers # to connect to evented back ends. It also does not generate # transient objects and thus saves memory. # # Example: # fiber_pool = NeverBlock::FiberPool.new(150) # # loop do # fiber_pool.spawn do # #fiber body goes here # end # end # class FiberPool # gives access to the currently free fibers attr_reader :fibers # ongoing work attr_reader :busy_fibers # pending work attr_reader :queue # full pool, doesn't change attr_reader :pool # Prepare a list of fibers that are able to run different blocks of code # every time. Once a fiber is done with its block, it attempts to fetch # another one from the queue def initialize(count = 50, logger=nil) @fibers,@busy_fibers,@queue,@on_empty,@pool = [],{},[],[],[] count.times do |i| fiber = NB::Fiber.new do |block| loop do begin block.call rescue => e if logger && logger.respond_to?(:error) logger.error("Exception caught in fiber pool: #{e.class.name}: #{e.message}") logger.error("Backtrace: #{e.backtrace.join("\n")}") end end unless @queue.empty? block = @queue.shift else @busy_fibers.delete(NB::Fiber.current.object_id) @fibers << NB::Fiber.current @on_empty.shift.call while @on_empty.any? && @busy_fibers.empty? block = NB::Fiber.yield end end end @fibers << fiber @pool << fiber end end def on_empty(&blk) if @busy_fibers.empty? blk.call else @on_empty << blk end end # If there is an available fiber use it, otherwise, leave it to linger # in a queue def spawn(evented = true, &block) if fiber = @fibers.shift @busy_fibers[fiber.object_id] = fiber fiber[:neverblock] = evented fiber.resume(block) else @queue << block end self # we are keen on hiding our queue end end # FiberPool module Pool FiberPool = NeverBlock::FiberPool end end # NeverBlock
true
57dfb01328ca42c09e14068118622b487b512e8d
Ruby
zimbatm/monkeypatch
/lib/monkeypatch.rb
UTF-8
5,604
3.09375
3
[ "LicenseRef-scancode-public-domain" ]
permissive
=begin rdoc This is the public API to produce new patches. Once you have a patch, look at Patch and it's children to see how to use it. =end module MonkeyPatch # MonkeyPatch's version as a string VERSION = '0.1.2' # May be raised on check_conflicts class ConflictError < StandardError; end # A collection of patches. Used to collect one or more patches with the #& operator class PatchBundle def initialize(patches) #:nodoc: @patches = patches.to_a.uniq end # Aggregates Patch (es) and PatchBundle (s) def &(other) PatchBundle.new(@patches + other.to_a) end def to_a; @patches.dup end # Delegates to patches # TODO: determine what happens if a patch fails def patch_class(klass) @patches.each do |patch| patch.patch_class(klass) end end # Delegates to patches def patch_instance(obj) for patch in @patches patch.patch_instance(obj) end end end # Abstract definition of a patch. # # You cannot create Patch instance yourself, they are spawned from # MonkeyPatch class-methods. class Patch class << self # Hide new to force api usage private :new end # The callstack it was defined in attr_reader :from def initialize(&patch_def) #:nodoc: raise ArgumentError, "patch_def not given" unless block_given? @patch_def = patch_def @conditions = [] add_condition("Patch already applied") do |klass| !(klass.respond_to?(:applied_patches) && klass.applied_patches.include?(self)) end end # Combine patches together. Produces a PatchBundle instance. def &(other) PatchBundle.new([self]) & other end # Returns [self], used by #& def to_a; [self] end # Patches a class or module instance methods def patch_class(klass) raise ArgumentError, "klass is not a Class" unless klass.kind_of?(Class) return false if !check_conditions(klass) check_conflicts!(klass) # Apply apply_patch(klass) return true end # Patches the instance's metaclass def patch_instance(obj) meta = (class << obj; self end) patch_class(meta) end # Add a condition for patch application, like library version # # If condition is not matched, +msg+ is def add_condition(msg, &block) raise ArgumentError, "block is missing" unless block_given? @conditions.push [block, msg] end protected # Condition are checks that raise nothing # # If a condition isn't met, the patch is not applied # # Returns true if all conditions are matched def check_conditions(klass) #:nodoc: !@conditions.find do |tuple| if tuple[0].call(klass); false else warn tuple[1] true end end end # Re-implement in childs. Make sure super is called # # raises a ConflictError if an error is found def check_conflicts!(klass) #:nodoc: end def apply_patch(klass) #:nodoc: klass.extend IsPatched klass.class_eval(&@patch_def) klass.applied_patches.push self end end class MethodPatch < Patch # The name of the method to be patched attr_reader :method_name def initialize(method_name, &patch_def) #:nodoc: super(&patch_def) @method_name = method_name.to_s unless Module.new(&patch_def).instance_methods(true) == [@method_name] raise ArgumentError, "&patch_def does not define the specified method" end end protected def check_conflicts!(klass) #:nodoc: super if klass.respond_to? :applied_patches others = klass.applied_patches.select{|p| p.respond_to?(:method_name) && p.method_name == method_name } if others.any? raise ConflictError, "Conflicting patches: #{([self] + others).inspect}" end end end end # Spawned by MonkeyPatch.add_method class AddMethodPatch < MethodPatch protected def check_conflicts!(klass) #:nodoc: super if klass.method_defined?(method_name) raise ConflictError, "Add already existing method #{method_name} in #{klass}" end end end # Spawned by MonkeyPatch.replace_method class ReplaceMethodPatch < MethodPatch protected def check_conflicts!(klass) #:nodoc: super unless klass.method_defined?(method_name) raise ConflictError, "Replacing method #{method_name} does not exist in #{klass}" end end end # This module extends patched objects to keep track of the applied patches module IsPatched def applied_patches; @__applied_patches__ ||= [] end end @loaded_patches = [] class << self # All defined patches are stored here attr_reader :loaded_patches # Creates a new patch that adds a method to a class or a module # # Returns a Patch (AddMethodPatch) def add_method(method_name, &definition) new_patch AddMethodPatch.send(:new, method_name, &definition) end # Creates a new patch that replaces a method of a class or a module # # Returns a Patch (ReplaceMethodPatch) def replace_method(method_name, &definition) new_patch ReplaceMethodPatch.send(:new, method_name, &definition) end protected def new_patch(patch, &definition) #:nodoc: #patch.validate patch.instance_variable_set(:@from, caller[1]) @loaded_patches.push(patch) patch end end end
true
213632cbbe6cdcdfeb94762dc62e8b325f2fb218
Ruby
wonda-tea-coffee/atcoder
/abc/104/a.rb
UTF-8
88
2.796875
3
[]
no_license
r = gets.to_i if r < 1200 puts 'ABC' elsif r < 2800 puts 'ARC' else puts 'AGC' end
true
b2bbc4a0220a971289a3ea9ef5487926f97f1a17
Ruby
maxgud/Git_Assignment_Week_2_Dev_Point
/Ruby_Shopping/shopping_with_ruby.rb
UTF-8
9,003
3.59375
4
[]
no_license
@cash = 50.00 @a = 0 @b = 0 @c = 0 @d = 0 @e = 0 class Customer_Items attr_accessor :customer_item, :c_amount def initialize(customer_item, c_amount) @customer_item = customer_item @c_amount = c_amount end end class Store attr_accessor :item, :amount, :price def initialize(item, amount, price) @item = item @amount = amount @price = price end end @penned = Store.new("Pens", 250, 0.75) @penciled = Store.new("Pencils", 350, 0.25) @notepaded = Store.new("Notepads", 560, 1.25) @ledgered = Store.new("Ledgers", 900, 2.25) def store_inventory puts "---------------------------" puts "Our store inventory:" puts "Number of " + @penned.item + "(s)" puts @penned.amount puts "Price : $" + @penned.price.to_s puts "Number of " + @penciled.item + "(s)" puts @penciled.amount puts "Price : $" + @penciled.price.to_s puts "Number of " + @notepaded.item + "(s)" puts @notepaded.amount puts "Price : $" + @notepaded.price.to_s puts "Number of " + @ledgered.item + "(s)" puts @ledgered.amount puts "Price : $" + @ledgered.price.to_s puts "---------------------------" menu end def wallet puts "---------------------------" puts "Your current balance is $" + @cash.to_s puts "---------------------------" menu end def buy_an_item puts "Choose the number of the item you would like to buy.?" puts "---------------------------" puts "Our store inventory:" puts "1 -- Number of " + @penned.item + "(s)" puts @penned.amount puts "Price : $" + @penned.price.to_s puts "2 -- Number of " + @penciled.item + "(s)" puts @penciled.amount puts "Price : $" + @penciled.price.to_s puts "3 --Number of " + @notepaded.item + "(s)" puts @notepaded.amount puts "Price : $" + @notepaded.price.to_s puts "4 -- Number of " + @ledgered.item + "(s)" puts @ledgered.amount puts "Price : $" + @ledgered.price.to_s choice = gets.to_i case choice when 1 @a = 1 puts "How many pens would you like to buy at $" + @penned.price.to_s + "?" p_1 = gets.to_i if p_1 > @penned.amount puts "Our appologies, we don't have that many pens, please choose a different amount." puts "---------------------------" buy_an_item elsif (p_1*@penned.price) > @cash puts "Im sorry, you don't have enough money for "+ p_1.to_s + " pens." puts "The total cost is $" + (p_1*@penned.price).to_s menu elsif @penned.amount = @penned.amount - p_1 @cash = @cash - (p_1*@penned.price) @pen_item = Customer_Items.new(@penned.item, p_1) puts "You bought " + p_1.to_s + " pen(s)" puts "Your remaining balance: " + @cash.to_s menu end when 2 @b = 1 puts "How many pencils would you like to buy at $" + @penciled.price.to_s + "?" p_2 = gets.to_i if p_2 > @penciled.amount puts "Our appologies, we don't have that many pencils, please choose a different amount." puts "---------------------------" buy_an_item elsif (p_2*@penciled.price) > @cash puts "Im sorry, you don't have enough money for " + p_2.to_s + " pencil(s)." puts "The total cost is $" + (p_2*@penciled.price).to_s menu elsif @penciled.amount = @penciled.amount - p_2 @cash = @cash - (p_2*@penciled.price) @pencil_item = Customer_Items.new(@penciled.item, p_2) puts "You bought " + p_2.to_s + " pencil(s)" puts "Your remaining balance: " + @cash.to_s menu end when 3 @c = 1 puts "How many notepads would you like to buy at $" + @notepaded.price.to_s + "?" p_3 = gets.to_i if p_3 > @notepaded.amount puts "Our appologies, we don't have that many pencils, please choose a different amount." puts "---------------------------" buy_an_item elsif (p_3*@notepaded.price) > @cash puts "Im sorry, you don't have enough money for " + p_3.to_s + " notepad(s)." puts "The total cost is $" + (p_3*@notepaded.price).to_s menu elsif @notepaded.amount = @notepaded.amount - p_3 @cash = @cash - (p_3*@notepaded.price) @notepad_item = Customer_Items.new(@notepaded.item, p_3) puts "You bought " + p_3.to_s + " notepad(s)" puts "Your remaining balance: " + @cash.to_s menu end when 4 @d = 1 puts "How many notepads would you like to buy at $" + @ledgered.price.to_s + "?" p_4 = gets.to_i if p_4 > @ledgered.amount puts "Our appologies, we don't have that many ledgers, please choose a different amount." puts "---------------------------" buy_an_item elsif (p_4*@ledgered.price) > @cash puts "Im sorry, you don't have enough money for " + p_4.to_s + " ledger(s)." puts "The total cost is $" + (p_4*@ledgered.price).to_s menu elsif @ledgered.amount = @ledgered.amount - p_4 @cash = @cash - (p_4*@ledgered.price) @ledger_item = Customer_Items.new(@ledgered.item, p_4) puts "You bought " + p_4.to_s + " ledger(s)" puts "Your remaining balance: " + @cash.to_s menu end else puts "Invalid Choice Try again" buy_an_item end end def view_your_items puts "Your Basket" puts "---------------------------" if @a > 0 puts "The amount of " + @pen_item.customer_item + "(s)" puts @pen_item.c_amount else end if @b > 0 puts "The amount of " + @pencil_item.customer_item + "(s)" puts @pencil_item.c_amount else end if @c > 0 puts "The amount of " + @notepad_item.customer_item + "(s)" puts @notepad_item.c_amount else end if @d > 0 puts "The amount of " + @ledger_item.customer_item + "(s)" puts @ledger_item.c_amount else end if @a == 0 && @b == 0 && @c == 0 && @d == 0 puts "---------------------------" puts "Your Basket it empty." puts "---------------------------" else end menu end def sell_your_items if @a > 0 puts "---------------------------" puts "The number of pens you have : " + @pen_item.c_amount.to_s puts "How many pens would you like to sell for half of inital cost?" sell_pens = gets.to_i @pen_item.c_amount = (@pen_item.c_amount.to_i - sell_pens.to_i) puts "You now have " + @pen_item.c_amount.to_s + " pens." money_made = (@penned.price.to_f * 0.5 *sell_pens.to_f) puts "You made $" + money_made.to_s + ". This will be added to your wallet." @cash = @cash + money_made puts "---------------------------" end if @b > 0 puts "---------------------------" puts "The number of pencils you have : " + @pencil_item.c_amount.to_s puts "How many penils would you like to sell for half of inital cost?" sell_pencils = gets.to_i @pencil_item.c_amount = (@pencil_item.c_amount.to_i - sell_pencils.to_i) puts "You now have " + @pencil_item.c_amount.to_s + " pencils." money_made = (@penciled.price.to_f * 0.5 *sell_pencils.to_f) puts "You made $" + money_made.to_s + ". This will be added to your wallet." @cash = @cash + money_made puts "---------------------------" end if @c > 0 puts "---------------------------" puts "The number of notepads you have : " + @notepad_item.c_amount.to_s puts "How many notepads would you like to sell for half of inital cost?" sell_notepads = gets.to_i @notepad_item.c_amount = (@notepad_item.c_amount.to_i - sell_notepads.to_i) puts "You now have " + @notepad_item.c_amount.to_s + " notepads." money_made = (@notepaded.price.to_f * 0.5 *sell_notepads.to_f) puts "You made $" + money_made.to_s + ". This will be added to your wallet." @cash = @cash + money_made puts "---------------------------" end if @d > 0 puts "---------------------------" puts "The number of ledgers you have : " + @ledger_item.c_amount.to_s puts "How many ledgers would you like to sell for half of inital cost?" sell_ledgers = gets.to_i @ledger_item.c_amount = (@ledger_item.c_amount.to_i - sell_ledgers.to_i) puts "You now have " + @ledger_item.c_amount.to_s + " ledgers." money_made = (@ledgered.price.to_f * 0.5 *sell_ledgers.to_f) puts "You made $" + money_made.to_s + ". This will be added to your wallet." @cash = @cash + money_made puts "---------------------------" end if @a == 0 && @b == 0 && @c == 0 && @d == 0 puts "You have no items to sell." menu end menu end def user_selection choice = gets.to_i case choice when 1 store_inventory when 2 wallet when 3 buy_an_item when 4 view_your_items when 5 sell_your_items when 6 puts "Goodbye" exit else puts "Invalid Choice Try again" menu end end def menu if @e == 0 puts "Welcome, what is your name?" user_name = gets.chomp puts "Thanks you " + user_name + ". How much money did you bring?" @cash = gets.to_i @e = 1 puts "Welcome " + user_name.to_s puts "You have $" + @cash.to_s + " in your Wallet." end puts "---------------------------" puts "What would you like to do?" puts "1 -- See our Inventory." puts "2 -- View Your Wallet." puts "3 -- Buy an item." puts "4 -- View your items." puts "5 -- Sell an item." puts "6 -- Exit" puts "---------------------------" user_selection end menu
true
6bf84a7f7358c463eef09fe64a70a84dc3823207
Ruby
SHiroaki/Ruby
/dokusyu/sec3_numeric.rb
UTF-8
639
3.890625
4
[]
no_license
# coding: utf-8 # 数値の比較 i,j,k,m = 5,8,3,5 # <=> 左項が大きいときは1,左項と右項が等しい時は0, 右項が大きい時は-1を返す p i <=> j p i <=> k p i <=> m # prac3.2 puts "--------------------prac3.2--------------------" puts 10 / 3, 10 % 3 f = 10.3 d = -10.3 puts f.ceil puts d.floor t = 255 puts t.to_s(2) puts t.to_s(8) puts t.to_s(16) puts "--------------------理解度--------------------" puts (5.04 * 10.0).round / 10.0 puts (5.05 * 10.0).round / 10.0 a = 0.0 / 0 if a.integer? puts "整数です" elsif a.infinite? puts "無限大" elsif a.nan? puts "数値ではありません" end
true
f3d176ccac8d27430256e9a63e845419365cac6f
Ruby
shorrockin/adventofcode2020
/11.rb
UTF-8
2,531
3.375
3
[]
no_license
# typed: false # frozen_string_literal: true require './boilerplate.rb' require './coordinates.rb' require './11_test_data.rb' module State FLOOR = '.' EMPTY = 'L' OCCUPIED = '#' end # converts a sequence of lines into a Flat::Grid object def to_grid(lines) lines = lines.split("\n") if lines.is_a?(String) Flat::Grid.from_lines(lines) {|char, _, _| {state: char}} end # returns a hash of all the changes that we should make to a given coordinate def calculate_changes(grid, empty_if_greater, occupied_counter) grid.points.keys.each_with_object({}) do |coordinate, changes| seat_state = grid.at(coordinate)[:state] if seat_state != State::FLOOR occupied_count = occupied_counter.call(grid, coordinate) changes[coordinate] = State::OCCUPIED if occupied_count == 0 && seat_state == State::EMPTY changes[coordinate] = State::EMPTY if occupied_count >= empty_if_greater && seat_state == State::OCCUPIED end end end # loops through iterations of the cycle until we have no further changes at # which coordinate it returns a count of the coordinates which are occupied def stabilize(grid, empty_if_greater, occupied_counter) while (changes = calculate_changes(grid, empty_if_greater, occupied_counter)) && changes.any? changes.each {|coordinate, change| grid.set(coordinate, :state, change)} end grid.select(:state, State::OCCUPIED).length end AoC.part 1, clear_screen: true do count_occupied = proc do |grid, coordinate| grid.neighbors(coordinate, :state, State::OCCUPIED, Flat::Directions::Adjacent).length end Assert.equal 37, stabilize(to_grid(TEST_DATA), 4, count_occupied) stabilize(to_grid(AoC::IO.input_file), 4, count_occupied) end AoC.part 2 do count_occupied = proc do |grid, coordinate| Flat::Directions::Adjacent.count do |direction| target = coordinate while (target = target.move(direction)) break false if !grid.contains?(target) break true if grid.at(target)[:state] == State::OCCUPIED break false if grid.at(target)[:state] == State::EMPTY end end end Assert.equal 8, count_occupied.call(to_grid(TEST_VISIBILITY_DATA_ONE), Flat::Coordinate.new(3, 4)) Assert.equal 0, count_occupied.call(to_grid(TEST_VISIBILITY_DATA_TWO), Flat::Coordinate.new(1, 1)) Assert.equal 0, count_occupied.call(to_grid(TEST_VISIBILITY_DATA_THREE), Flat::Coordinate.new(3, 3)) Assert.equal 26, stabilize(to_grid(TEST_DATA), 5, count_occupied) stabilize(to_grid(AoC::IO.input_file), 5, count_occupied) end
true
c4769dd19ffe33ba81f01cf483ae010d6b75b2a6
Ruby
kchansf5/aA-homeworks
/W1D4/DIY_ADTs.rb
UTF-8
908
3.734375
4
[]
no_license
# Exercise 1 class Stack def initialize @stack = [] end def add(el) @stack << el end def remove @stack.pop end def show @stack end end # Exercise 2 class Queue def initialize @queue = [] end def enqueue(el) @queue << el end def dequeue @queue.shift end def show @queue end end # Exercise 3 class Map def initialize @map = [] end #looked at solution for assign (could not figure out how to reassign values #to pre-existing keys...) def assign(key, value) pair_index = @map.index {|pair| pair[0] == key} pair_index ? @map[pair_index][1] = value : @map.push([key, value]) [key, value] end def lookup(key) @map.each do |pair| if pair[0] == key return pair[1] end end nil end def remove(key) @map.reject! { |pair| pair[0] == key } end def show @map end end
true
a7e098b43d1108ec018ecc2b01d6a1179b0be6c4
Ruby
zhxbab/r2x
/generate_pram.rb
UTF-8
3,691
2.53125
3
[]
no_license
#!/usr/bin/env ruby_dv_1_9_2 #!/usr/bin/env ruby_dv_1_9_2 --disable-gems # require 'json' $chip = ARGV[0] $ucodedefine = ARGV[1] raise "chip not defined" if ! $chip $output = "#{$chip}_tracer_autogen.pm" $all_subs = [] def usage print "#{$0} <ucodedefine> covert pram ucode define file into la2avp tracer data structure\n" exit end def log(input) $handle.puts(input) end class ParseCommon def initialize(cfg) @cfg = cfg end # keys that we auto skip def default_skip(input) return true if input == "section" return false end def sub_name "Initialize#{$chip}#{self.class.to_s}" end def merge(input_cfg) @cfg.merge!(input_cfg) end def run $all_subs << sub_name log "package Tracer;" log "sub #{sub_name} {" @cfg.each do |key,val| if default_skip(key) else current_entry = match(key) if current_entry current_entry = current_entry.upcase # more consistent autogen code current_offset = val['offset'].hex current_size = val['size'] log("@{$#{@variable_name}{\"#{current_entry}\"}} = (#{sprintf("0x%x",current_offset)} , #{current_size} ); ") end end end log "}" log "1;" end end class Pram < ParseCommon def initialize(args) super(args) @variable_name = "DEFAULT_CHECKPOINT_PRAM" end def match(input) if input =~ /(\S+)_ADDR/ current_entry = $1 else raise "unexpected entry #{input}" end current_entry end end class UCPram < ParseCommon def initialize(args) super(args) @variable_name = "DEFAULT_CHECKPOINT_UC_PRAM" end def match(input) if input =~ /(\S+)_UCADDR/ current_entry = $1 else raise "unexpected entry #{input}" end current_entry end end class UCRegs < ParseCommon def initialize(args) super(args) @variable_name = "DEFAULT_CHECKPOINT_UC_REGS" end def match(input) input end end class UCCoreRegs < ParseCommon def initialize(args) super(args) @variable_name = "DEFAULT_CHECKPOINT_UC_CORE_REGS" end def match(input) input end end class Core < ParseCommon def initialize(args) super(args) @variable_name = "DEFAULT_CHECKPOINT_CORE" end # match all keys as it is def match(input) input end end =begin UncoreRegs merges the two section "uc_regs_tracer_dump" and "uc_L2_tracer_dump" =end @ucore_regs = nil usage if ARGV.empty? raise "no ucode define " if ! $ucodedefine $handle = File.open($output,"w") File.open($ucodedefine).each do |line| obj = JSON.parse(line) if obj['section'] == 'pram' parse = Pram.new(obj) parse.run elsif obj['section'] == 'uncore pram' parse = UCPram.new(obj) parse.run elsif obj['section'] == 'store_state_to_pram' #print "here. obj is #{obj}\n" parse = Core.new(obj) parse.run elsif (obj['section'] == 'uc_regs_tracer_dump') #|| (obj['section'] == 'uc_L2_tracer_dump') if ! @ucore_regs @ucore_regs = UCRegs.new(obj) else @ucore_regs.merge(obj) end elsif (obj['section'] == 'uc_core_tracer_dump') parse = UCCoreRegs.new(obj) parse.run # not used elsif obj['section'] == 'msr' elsif obj['section'] == 'fuse bank' elsif obj['section'] == 'fuse' elsif obj['section'] == 'defines' else raise "unexpected section #{obj['section']}" end end @ucore_regs.run # this generates the json after merge log "package Tracer;" log "sub Initialize#{$chip}Dumps {" $all_subs.each do |current| log " #{current}();" end log "}" $handle.close
true
0ff4c22ac07082373a798d046ffdf10cd81e4631
Ruby
Shiler/abi-bot
/lib/lp_updates_manager.rb
UTF-8
280
2.765625
3
[]
no_license
require_relative 'message.rb' class LPUpdatesManager def LPUpdatesManager.get_messages(updates) new_messages = [] updates.each do |update| update.first == 4 ? new_messages << Message.new(update[1], update[3], update[6]) : nil end new_messages end end
true
8f345aa24bc35f770bd13a3b25b47c5089b09cf5
Ruby
MysteriousSonOfGod/propython
/fundamentos/metaprog/roman.rb
UTF-8
187
3.3125
3
[]
no_license
class Roman def romanToInt(str) # ... end def method_missing(methId) str = methId.id2name romanToInt(str) end end r = Roman.new r.iv » 4 r.xxiii » 23 r.mm » 2000
true
af6b184a69f069dfbaf441f1c654737b626fac75
Ruby
crispyears/beer_exercise
/beer.rb
UTF-8
453
4.625
5
[]
no_license
require 'pry' #write a function that accepts a variable: age #if age is greater than 21, display "Yay, have a beer!" #if age is less than 21, display "Nay, don't have a beer!" def can_you_drink(age) if age.to_i < 21 puts "Nay don't have a beer!" else puts "Yay, have a beer!" end end #ask for the user's age puts "How old are you?" #store the user input in a variable: user_age user_age = gets.strip #run the function can_you_drink(user_age)
true
f3c8863d712094065ed74fb772488f75c849d898
Ruby
denys-kvyk/Projects
/TAQC with RUBY/pages/application.rb
UTF-8
2,350
2.546875
3
[]
no_license
require_relative '../data/application_source.rb' require_relative '../data/application_source_repository.rb' require_relative '../tools/browser_wrapper.rb' #require_relative './user/home_page.rb' #require_relative './user/shopping_cart.rb' require_relative 'user/home_page/home_page_atomic' require_relative 'user/home_page/home_page_business' require_relative 'user/home_page/home_page' require_relative 'user/cart_component/cart_atomic' require_relative 'user/cart_component/cart_component' require_relative 'user/cart_component/cart_business' require_relative 'user/shopping_cart/shopping_cart_atomic' require_relative 'user/shopping_cart/shopping_cart' require_relative 'user/shopping_cart/shopping_cart_business' class Application attr_reader :application_source, :browser private_class_method :new private @@instance = nil def initialize(application_source) @application_source = application_source end public def self.get(application_source = nil) if @@instance.nil? if application_source.nil? application_source = ApplicationSourceRepository.default end @@instance = new(application_source) @@instance.init(application_source) end return @@instance end def self.remove() if @@instance @@instance.browser.quit @@instance = nil end end def init(application_source) @browser = BrowserWrapper.new(application_source) end def load_home_page browser.open_url(application_source.baseUrl) #HomePage.new(browser.driver) HomePageBusiness.new(HomePageAtomic.new(browser.driver)) end def load_main_page browser.open_url(application_source.baseUrl) #HomePage.new(browser.driver) ShoppingCartBusiness.new(ShoppingCartAtomic.new(browser.driver)) end =begin def login_user browser.open_url(application_source.userLoginUrl) # TODO change page HomePage.new(browser.driver) end def logout_user browser.open_url(application_source.userLogoutUrl) # TODO change page HomePage.new(browser.driver) end def login_admin browser.open_url(application_source.adminLoginUrl) # TODO change page HomePage.new(browser.driver) end def logout_admin browser.open_url(application_source.adminLogoutUrl) # TODO change page HomePage.new(browser.driver) end =end end
true
84804cfaea652355ea492602a13c6a136a61a5ec
Ruby
maksimmanzhai/RubySchool
/lesson 09/app11.rb
UTF-8
178
3.640625
4
[]
no_license
#lesson 9 arr = [] while true puts "What is your favorite color? Stop for exit" color = gets.strip if color == "stop" puts arr.reverse.uniq! exit end arr << color end
true
7c02cf02887c5ddedb0dff0ff8768284399f777b
Ruby
csu-xiao-an/bricolage
/lib/bricolage/taskqueue.rb
UTF-8
2,239
2.859375
3
[ "MIT" ]
permissive
require 'bricolage/jobnet' require 'bricolage/exception' require 'fileutils' require 'pathname' module Bricolage class TaskQueue def initialize @queue = [] end def empty? @queue.empty? end def size @queue.size end def queued? not empty? end def each(&block) @queue.each(&block) end def consume_each lock save while task = self.next yield task deq end ensure unlock end def enq(task) @queue.push task end def next @queue.first end def deq task = @queue.shift save task end def save end def restore end def locked? false end def lock end def unlock end def unlock_help "[MUST NOT HAPPEN] this message must not be shown" end end class FileTaskQueue < TaskQueue def FileTaskQueue.restore_if_exist(path) q = new(path) q.restore if q.queued? q end def initialize(path) super() @path = path end def queued? @path.exist? end def save if empty? @path.unlink if @path.exist? return end FileUtils.mkdir_p @path.dirname tmpname = "#{@path}.tmp.#{Process.pid}" begin File.open(tmpname, 'w') {|f| each do |task| f.puts task.serialize end } File.rename tmpname, @path ensure FileUtils.rm_f tmpname end end def restore File.foreach(@path) do |line| enq JobTask.deserialize(line) end end def locked? lock_file_path.exist? end def lock FileUtils.touch lock_file_path end def unlock FileUtils.rm_f lock_file_path end def lock_file_path Pathname.new("#{@path}.LOCK") end def unlock_help "remove the file: #{lock_file_path}" end end class JobTask def initialize(job) @job = job end attr_reader :job def serialize [@job].join("\t") end def JobTask.deserialize(str) job, * = str.strip.split("\t") new(JobNet::Ref.parse(job)) end end end
true
920d9925671b1a24a8092ebcd8cf1d613d622ed7
Ruby
alyaluk/ruby-flashcards
/flashcard.rb
UTF-8
1,560
3.6875
4
[]
no_license
# Main file for your code. list = [] IO.foreach('flashcard_samples.txt') do |line| list << line end list.delete("\n") x = 1 $game = Hash.new random = [] $keys = [] points = 0 number = nil $multi = false size = list.length / 2 for i in (0...list.length/2) $game[list[x].gsub("\n","")] = list[x-1].gsub("\n","") random << list[x-1].gsub("\n","") $keys << list[x].gsub("\n","") x += 2 end def set(number) if number == nil return nil else $count = number end end def multiple if $multi == true choices = [$game.key($prompt), $keys.sample, $keys.sample] p choices.shuffle end end puts "Welcome to the Ruby Flashcard quiz! What type of game would you like to play? (multiple_choice/set/quit)" input = gets.chomp if input != "quit" if input == "set" puts "How many questions?" number = gets.chomp.to_i elsif input == "multiple_choice" $multi = true end sleep(0.5) puts "", "Instructions: guess all the commands correctly to finish the game. Type quit to end the game." answer = nil until answer == "quit" || random.empty? || $count == 0 sleep(0.5) puts "", "Which command is this?" $prompt = random.sample puts $prompt multiple answer = gets.chomp sleep(0.5) if $game[answer] == $prompt puts "", "Correct! :D" points += 1 number -= 1 unless number == nil random.delete($prompt) elsif answer != "quit" puts "Incorrect :(" end set(number) sleep(0.5) puts "", "You have answered #{points} correctly." end sleep(0.5) puts "", "Congratulations, you finished the game!" if answer != "quit" end
true
80451d0bf05d2bb796d1b153f9468f0f0f4b24d5
Ruby
spartalisdigital/lotu
/spec/lotu/actor_spec.rb
UTF-8
2,669
2.578125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'lotu' class Actress < Lotu::Actor collides_as :actress_in_distress use Lotu::SteeringSystem end class Fan < Actress use Lotu::StalkerSystem end describe "Actor" do before :each do @game = Lotu::Game.new(:parse_cli_options => false) @actor = Lotu::Actor.new @actress = Actress.new @fan = Fan.new @user = @actor end after :each do @actor.die @actress.die @fan.die end describe "When just created" do it "should have the appropiate number of systems" do @actor.systems.length.should be 0 end it "should have the appropiate type of systems" do @actor.systems.keys.should == [] end it "should have the appropiate behavior options set" do @actor.class.behavior_options.should == {} end it "#x == 0" do @actor.x.should == 0 end it "#y == 0" do @actor.y.should == 0 end it "#z == 0" do @actor.z.should == 0 end end describe "Behavior" do it_should_behave_like "system user" it_should_behave_like "eventful" it_should_behave_like "collidable" it_should_behave_like "controllable" end describe "Actor subclasses" do before :each do @user = @actress end describe "Behavior" do it_should_behave_like "system user" it_should_behave_like "eventful" it_should_behave_like "collidable" it_should_behave_like "controllable" end it "should have a different object hash for behavior_options" do @user.class.behavior_options.should_not be @actor.class.behavior_options end it "should have different values in behavior_options" do @user.class.behavior_options.should_not == @actor.class.behavior_options end describe "When just created" do it "should have the appropiate number of systems" do @user.systems.length.should be 1 end it "should have the appropiate type of systems" do @user.systems.keys.should == [Lotu::SteeringSystem] end it "should have the appropiate behavior options set" do @user.class.behavior_options.should == {Lotu::Collidable=>{:actress_in_distress=>{:shape=>:circle}}, Lotu::SystemUser=>{Lotu::SteeringSystem=>{}}} end it "#x == 0" do @user.x.should == 0 end it "#y == 0" do @user.y.should == 0 end it "#z == 0" do @user.z.should == 0 end end end describe "Basic methods and properties" do it{ @actor.should respond_to :x } it{ @actor.should respond_to :y } it{ @actor.should respond_to :parent } it{ @actor.should respond_to :color } end end
true
be4dca508bd9139de730faa72eedeae2f5a49ead
Ruby
junftnt/whistlepig
/build/gen-test-main.rb
UTF-8
771
3.046875
3
[ "BSD-3-Clause" ]
permissive
#!/usr/bin/env ruby abort "expecting one argument: the filename" unless ARGV.size == 1 fn = ARGV.shift funcs = [] IO.foreach(fn) do |l| if l =~ /TEST\((.+?)\)/ funcs << $1 end end puts %q! #include <stdio.h> #include "error.h" #include "test.h" ! puts funcs.map { |f| "TEST(#{f});" } puts %q! int main(int argc, char* argv[]) { (void) argc; (void) argv; int failures = 0, errors = 0, asserts = 0, tests = 0; //printf("Running tests...\n\n"); ! puts funcs.map { |f| "RUNTEST(#{f});" } puts %q! printf("%d tests, %d assertions, %d failures, %d errors\n", tests, asserts, failures, errors); if((errors == 0) && (failures == 0)) { // printf("Tests passed.\n"); return 0; } else { //printf("Tests FAILED.\n"); return -1; } } !
true
c2fcfc411b53e97e6300e921d6aab4467e9d14a3
Ruby
kylelong/ruby_tutorial
/hexToRgb.rb
UTF-8
926
3.828125
4
[]
no_license
=begin Converts hex codes to rgb https://www.mathsisfun.com/hexadecimals.html supports hashtag and non hashtag @param s string to be converted to RGB @return RGB representation of a string =end def hex_to_rgb(s) if s[0] == "#" #removes '#' from evalutation s = s[1..s.length] end if s.to_s.length < 6 abort("String must be exactly six characters.") end table = {"0" => 0, "1" => 1, "2" => 2, "3" => 3, "4" => 4, "5" => 5, "6" => 6, "7" => 7, "8" => 8, "9" => 9, "A" => 10, "B" => 11, "C" => 12, "D" => 13, "E" => 14, "F" => 15 } r = s[0..1] num_1 = table[r[0]] * 16 + table[r[1]] g = s[2..3] num_2 = table[g[0]] * 16 + table[g[1]] b = s[4..5] num_3 = table[b[0]] * 16 + table[b[1]] "(#{num_1}, #{num_2}, #{num_3})" end puts hex_to_rgb("#FF0000") #(255, 0, 0) puts hex_to_rgb("FFD700") #(255, 215, 0) puts hex_to_rgb("#808080") #(128, 128, 128) - Grey
true
023b8baeba2526a069533b435292bc15f3ba4d2a
Ruby
mfichman/portfolio
/app/helpers/chart_helper.rb
UTF-8
2,118
3.03125
3
[]
no_license
module ChartHelper def percent(value, total) "#{(value / total * 100).round}%" end def legend(labels) capture do labels.each_with_index do |label, n| yield label, n end end end # Takes an array of series, each of which is a list of values def line(series, style: 'fill') chart = Rasem::SVGImage.new(class: 'chart-image', preserveAspectRatio: 'none', viewBox: '0 0 1 1') do series.each_with_index do |values, n| path(class: "chart-#{style}-color-#{n}") do y_max = values.max || 0 y_min = values.min || 0 y_scale = y_max - y_min y_min = y_min - 0.1 * y_scale y_scale = 1.2 * y_scale y_first = values.first || 0 x_max = values.count.to_f x_min = 0 x_scale = x_max - x_min - 1 if style == 'fill' moveToA(0, 1) lineToA(x_min, 1 - (y_first - y_min) / y_scale) elsif style == 'stroke' moveToA(x_min, 1 - (y_first - y_min) / y_scale) else raise ArgumentError, 'invalid stroke' end values.each_with_index do |value, n| lineToA((n - x_min) / x_scale, 1 - (value - y_min) / y_scale) end if style == 'fill' lineToA(1, 1) elsif style == 'stroke' # pass else raise ArgumentError, 'invalid stroke' end end end end chart.to_s.html_safe end def pie(values) total = values.sum pos = 0 chart = Rasem::SVGImage.new(class: 'chart-image', viewBox: '-1 -1 2 2') do values.each_with_index do |value, n| path(class: "chart-fill-color-#{n}") do sector = 2 * Math::PI * (value / total) sx, sy = Math::cos(pos), Math::sin(pos) pos += sector ex, ey = Math::cos(pos), Math::sin(pos) large_arc = sector > Math::PI ? 1 : 0 moveToA(0, 0) lineToA(sx, sy) arcToA(ex, ey, 1, 1, 0, large_arc, 1) end end end chart.to_s.html_safe end end
true
fc1433afc1bfc560ba5b28bf8a85cb8cb11f7f1e
Ruby
mozulevskyi/schooling
/app/models/arrays.rb
UTF-8
2,197
3.53125
4
[]
no_license
a = Array.new(10).map(){rand(10)} #Дан целочисленный массив. Необходимо переставить в обратном порядке элементы массива, расположенные между его минимальным и максимальным элементами. a = [7, 2, 7, 1, 6, 3, 2, 9, 8] s = a.index(a.min) d = a.index(a.max) a[s+1..d-1].reverse #=> [2, 3, 6] #Дан целочисленный массив. Необходимо разместить элементы, расположенные до минимального, в конце массива. a = [7, 6, 1, 9, 2, 8, 7, 8, 2, 7] b = a.index(a.min) a.rotate(b) #=> [1, 9, 2, 8, 7, 8, 2, 7, 7, 6] #Дан целочисленный массив и интервал a..b. Необходимо найти количество элементов в этом интервале. a = [6, 5, 3, 3, 4, 0, 1, 6, 4, 6] b = a[2..6] b.size #=> 5 #Дан целочисленный массив и натуральный индекс (число, меньшее размера массива). Необходимо определить является ли элемент по указанному индексу локальным минимумом. a = [5, 0, 9, 1, 1, 9, 6, 8, 1, 4] i = a.index(6) a.min == i #=> false #Дан целочисленный массив. Необходимо найти элементы, расположенные между первым и вторым максимальным. a = [3, 2, 8, 6, 1, 4, 2, 8, 8, 1] b = a[(a.index(a.max) + 1)..-1] b[0..b.index(b.max)-1] #=> [6, 1, 4, 2] #Дан целочисленный массив. Необходимо поменять местами минимальный и максимальный элементы массива. a = [2, 8, 8, 0, 7, 3, 2, 4, 7, 3] b = a.index(a.min) f = a.index(a.max) c = a.max a[f] = a[b] a[b] = c #=> [2, 0, 8, 8, 7, 3, 2, 4, 7, 3] #Даны два массива. Необходимо найти количество не совпадающих по значению элементов. a = [1, 4, 1, 4, 0] b = [0, 2, 1, 1, 1] (a | b).size - (a&b).size #=> 2
true
9812b8d0388e92d3191da7b614beea34f04910e4
Ruby
abi-wilson25/Final-Project
/models/model.rb
UTF-8
6,555
2.828125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'net/http' require 'json' require 'pp' require "http" require "optparse" # Place holders for Yelp Fusion's OAuth 2.0 credentials. Grab them # from https://www.yelp.com/developers/v3/manage_app CLIENT_ID = "x0LOXFAjrgc9FObJNnszTQ" CLIENT_SECRET = "1mWDj5IL7JIGZ7KLnvzTNpWDy2777z3NHr4XvBf54MPLDRJGu3gJqxQG8J1gXPbR" # Constants, do not change these API_HOST = "https://api.yelp.com" SEARCH_PATH = "/v3/businesses/search" BUSINESS_PATH = "/v3/businesses/" # trailing / because we append the business id to the path TOKEN_PATH = "/oauth2/token" GRANT_TYPE = "client_credentials" DEFAULT_BUSINESS_ID = "yelp-san-francisco" DEFAULT_TERM = "dinner" DEFAULT_LOCATION = "San Francisco, CA" SEARCH_LIMIT = 5 def bearer_token # Put the url together url = "#{API_HOST}#{TOKEN_PATH}" raise "Please set your CLIENT_ID" if CLIENT_ID.nil? raise "Please set your CLIENT_SECRET" if CLIENT_SECRET.nil? # Build our params hash params = { client_id: CLIENT_ID, client_secret: CLIENT_SECRET, grant_type: GRANT_TYPE } response = HTTP.post(url, params: params) parsed = response.parse "#{parsed['token_type']} #{parsed['access_token']}" end # Returns a parsed json object of the request def search(start_lat, start_long, end_lat, end_long, radius, term) latitude=start_lat longitude=start_long puts latitude puts end_lat # place = [] # address= [] places_hash={ } while ((latitude-end_lat).abs>0.05) do puts "------------------------------------------" # latitude=((start_lat)..(end_lat)).step(0.001).to_a # longitude=((start_long)..(end_long)).step(0.001).to_a # s=start_long url = "#{API_HOST}#{SEARCH_PATH}" params = { # categories: term, term: term, latitude: latitude, longitude: longitude, radius: radius # limit: SEARCH_LIMIT } response = HTTP.auth(bearer_token).get(url, params: params) puts result=response.parse if result["businesses"]!=nil result["businesses"].each do |place| #need to change each loop places_hash[place["name"]]=place["location"]["address1"] end end puts latitude puts end_lat latitude=(latitude+(end_lat-start_lat)/5.0) longitude=(longitude+(end_long-start_long)/5.0) end puts places_hash return places_hash end def calculate_route(user_search, user_radius, user_interest) # user_interest=" " start_lat=0 start_long=0 end_lat=0 end_long=0 case user_search when "Colombus, OH to Detroit, MI" start_lat=39.9612 start_long=-82.9988 end_lat=42.3314 end_long=-83.0458 when "Indianapolis, IN to Detroit, MI" start_lat= 41.8781 start_long=-87.6298 end_lat=42.3314 end_long=-83.0458 when "Chicago, IL to Detroit, MI" start_lat=41.8781 start_long=-87.6298 end_lat=42.3314 end_long=-83.0458 else puts "input valid option" end return search(start_lat, start_long, end_lat, end_long, user_radius, user_interest) end def getstatement(user_interest) if user_interest=="Food" return result_statement="Here are some food options on your way to Detroit!" elsif user_interest=="Gas Station" return result_statement="Here are some gas stations on your way to Detroit!" elsif user_interest=="Scenic" return result_statement="Here are some scenic spots on your way to Detroit!" elsif user_interest=="Indoor Activities" return result_statement="Here are some indoor activities on your way to Detroit!" elsif user_interest=="Outdoor Activities" return result_statement="Here are some outdoor activities on your way to Detroit!" elsif user_interest=="Hotel" return result_statement="Here are some hotels on your way to Detroit!" end end # def find_coordinates(start_lat, start_long, end_lat, end_long) # # i=start_lat # # for i in start_lat..end_lat do # # i+=0.001 # # lat=i # # end # # lat=((start_lat)..(end_lat)).step(0.001).to_a # # s=start_long # # for s in start_long..end_long do # # s+=0.001 # # long=s # # end # # long=((start_long)..(end_long)).step(0.001).to_a # # end # lat=start_lat # long=start_long # type="restaurant" # # &#{keyword}=#{preferences.gsub(" ","+")} # # keyword="mexican" # # preferences="taco" # # while (lat-end_lat).abs>0 do # puts "here" # endpoint="https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=#{lat},#{long}&rankby=distance&type=restaurant&key=AIzaSyB5aLHFgdH3mumNwTwd6Cc0Ix22yXK-knU" # sample_uri = URI(endpoint) #opens a portal to the data at that link # sample_response = Net::HTTP.get(sample_uri) #go grab the data in the portal # sample_parsedResponse = JSON.parse(sample_response) #makes data easy to read # sample_parsedResponse["results"].each do |i| # puts i["name"] # end # # do |key, value| # # pp "The #{key} is #{value}" # # end # puts lat # puts long # # lat=lat+(end_lat-start_lat)/5.0 # # long=long+(end_long-start_long)/5.0 # # end # end # 35.9940° N, 78.8986° W # 40.7128° N, 74.0059° W # 40.8429° N, 73.2929° W # find_coordinates(48.8566,2.3522,35.9940,78.8986) # puts find_places(lat, long, restaurant, Mexican, taco) # Make a request to the Fusion API token endpoint to get the access token. # # host - the API's host # path - the oauth2 token path # # Examples # # bearer_token # # => "Bearer some_fake_access_token" # # Returns your access token # Make a request to the Fusion search endpoint. Full documentation is online at: # https://www.yelp.com/developers/documentation/v3/business_search # # term - search term used to find businesses # location - what geographic location the search should happen # # Examples # # search("burrito", "san francisco") # # => { # "total": 1000000, # "businesses": [ # "name": "El Farolito" # ... # ] # } # # search("sea food", "Seattle") # # => { # "total": 1432, # "businesses": [ # "name": "Taylor Shellfish Farms" # ... # ] # } # # search("new york") # search(42.3314,-83.0458,42.2808,-83.7430, 10000)
true
67943e61e34bce083af98957efc29f65d463da21
Ruby
opener-project/pos-tagger-en-es
/lib/opener/pos_taggers/en_es/es.rb
UTF-8
395
2.59375
3
[ "Apache-2.0" ]
permissive
module Opener module POSTaggers ## # Spanish POS tagger class. This class forces the language to Spanish # regardless of what the KAF document claims the language to be. # class ES < EnEs ## # @see [Opener::POSTaggers::Base#language_from_kaf] # def language_from_kaf(input) return 'es' end end # ES end # POSTaggers end # Opener
true
56da20330aca61e538e331713829369419e5adc0
Ruby
adambird/entity_stormotion
/spec/motion/sqlite_entity_store_spec.rb
UTF-8
2,195
2.53125
3
[ "MIT" ]
permissive
# Integration tests for the local store class DummyEntity include EntityStore::Entity attr_accessor :name def set_name(at, name) record_event DummyEntityNameSet.new(at: at, name: name) end end class DummyEntityNameSet include EntityStore::Event attr_accessor :name time_attribute :at def apply(entity) entity.name = name end end describe "SqliteEntityStore" do before do @store = EntityStormotion::SqliteEntityStore.new @store.open @store.clear @name = "asjdlakjdlkajd" @at = Time.now end describe "#add_entity" do before do @entity = DummyEntity.new @entity.set_name @at, @name @id = @store.add_entity @entity end it "should allow retrieval of the entity shell for the id" do @store.get_entity(@id).class.name.should == DummyEntity.name end end describe "#add_event" do before do @entity_id = "2234" @event = DummyEntityNameSet.new(at: Time.now, name: "skdfhskjf", entity_id: @entity_id, entity_version: 2) @store.add_event @event end it "should allow retrieval of the events for that entity" do @store.get_events(@entity_id).first.name.should == @event.name end it "should be of the correct type" do @store.get_events(@entity_id).first.class.name.should == DummyEntityNameSet.name end end describe "#snapshot_entity" do before do @entity = DummyEntity.new @entity.set_name @at, @name @entity.id = @store.add_entity @entity @store.snapshot_entity @entity end it "should populate the entity with the snapshot" do @store.get_entity(@entity.id).name.should == @name end end describe "Integration with EntityStore" do before do EntityStore::Config.setup do |config| config.store = @store end @entity = DummyEntity.new @entity_store = EntityStore::Store.new end describe "#save" do before do @entity.set_name(@at = Time.now, @name = "sdhfsfhof") @entity = @entity_store.save(@entity) end it "retrieved has name" do @entity_store.get(@entity.id).name.should == @name end end end end
true
ea755dba40d2abaa1269cd0f4dc3fefd5ab3764a
Ruby
ilpoldo/connie
/lib/connie/connie.rb
UTF-8
1,619
3.0625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
module Connie class DictionaryNotFound < StandardError; end class DictionaryNameNotAllowed < StandardError; end @dictionaries = {} @alphabet = %w(a A b B c C d D e E f F g G h H i I j J k K l L m M n N o O p P q Q r R s S t T u U v V w W x X y Y z Z) def self.dictionaries_paths;@dictionaries_paths;end def self.dictionaries;@dictionaries;end def self.[] dictionary_name @dictionaries[dictionary_name.to_sym] or Dictionary.new(dictionary_name.to_s) end def self.register_dictionary(dictionary) @dictionaries[dictionary.name.to_sym] = dictionary end # Picks a random line from a text file or a precise line if a number is provided def self.pick_a_line_from(file_path, line_no = false) File.open file_path, 'r' do |file| unless line_no file.inject { |choice, line| rand < 1/file.lineno.to_f ? line.strip : choice } else line = line_no % (file.lineno - 1) # cycles around the file file.readlines[line-1].strip end end end def self.reload_dictionaries @dictionaries = {} end # Returns a random letter def self.letter(variant=nil) index = rand(26)*2 index +=1 if variant == :uppercase @alphabet[index] end def self.digit rand(9) end def self.formats format, min = 1, max = 0 array = max > 0 ? Array.new(rand(max-min)+min) : Array.new(min) generator = case format when :W then lambda {Connie.letter(:uppercase)} when :w then lambda {Connie.letter} when :d then lambda {Connie.digit.to_s} end array.map{generator.call}.join end end
true
7485179d9e345f202a284ddbf1329c2c2b20fcf5
Ruby
takkkun/idol_master
/lib/idol_master/cinderella_girls/user.rb
UTF-8
1,472
2.6875
3
[]
no_license
require 'idol_master/cinderella_girls/idol' require 'idol_master/cinderella_girls/idol_store' require 'idol_master/cinderella_girls/ensure' require 'yaml' module IdolMaster module CinderellaGirls class User def initialize(path, options = {}) @options = options data = YAML.load_file(path) @status = Status.new(data['status']) @idols = fetch_idols(data['idols']) end attr_reader :status, :idols def ensure_idols(side) Ensure.new(@idols, side, @status.send(side)) end private def fetch_idols(idols) idol_store = @options[:idol_store] || {} idol_store = IdolStore.new(idol_store) if idol_store.is_a?(Hash) idol_store.open do |store| idols.map do |fields| fields = case fields when Integer then {id: fields} when Hash then Hash[fields.map { |k, v| [k.to_sym, v] }] else {} end idol_id = fields.delete(:id) fields = (idol_id ? store[idol_id] : {}).merge(fields) Idol.new(idol_id || 0, *[:name, :offence, :defence, :cost].map { |key| fields[key] }) end end end class Status def initialize(status) @offence = status['offence'] @defence = status['defence'] end attr_reader :offence, :defence end end end end
true
c192b0c0f6ae171e21c73e324511b0a8e15ea9b6
Ruby
stupendousC/ride-share-rails
/app/controllers/trips_controller.rb
UTF-8
4,926
2.53125
3
[]
no_license
class TripsController < ApplicationController def index # Where did the request come from? Per passenger? or per driver? or per trips index? @passenger = Passenger.find_by(id: params[:passenger_id]) @driver = Driver.find_by(id: params[:driver_id]) if @driver # showing trips for a specific driver @trips = Trip.where(driver_id: @driver.id) elsif @passenger # showing trips for a specific passenger @trips = Trip.where(passenger_id: @passenger.id) @can_rate = true else # just showing all Trips table for all passengers @trips = Trip.all end end def show trip_id = params[:id].to_i @trip = Trip.find_by(id: trip_id) if @trip.nil? if params[:id] == "new" # trying to request new trips via /trips/new? even though routes blocked? nice try! redirect_to nope_path(params: {msg: "Only passengers can request/create trips!"}) return else # trying to request new trips redirect_to nope_path(params: {msg: "No such trip exists!"}) return end end # this way I can use _trips_table.html.erb for single entry too @trips = [@trip] end def create # find available driver @driver = Driver.find_by(active: false) if @driver.nil? redirect_to nope_path(params: {msg: "No drivers available, maybe you should walk"}) return else # flip @driver.active to true. unless @driver.update(active: true) redirect_to nope_path(params: {msg: "Unexpected error, please call customer service at 1-800-LOL-SORRY"}) return end # When do we flip it back to false? Normally we'd do that when GPS hits destination... # For this project, we'll flip it when passenger rates the trip. end # make new trip default_cost = 1000 @trip = Trip.new(date: params[:date], rating: nil, cost: default_cost, driver_id: @driver.id, passenger_id: params[:passenger_id]) if @trip.save # update passenger instance's total_spent @passenger = Passenger.find_by(id: params[:passenger_id]) if @passenger[:total_spent] new_sum = @passenger[:total_spent] + @trip.cost else new_sum = @trip.cost end @passenger.update(total_spent: new_sum) # update driver instance's total_earned if @driver[:total_earned] prev_sum = @driver[:total_earned] new_sum = prev_sum + @driver.net_earning(@trip.cost) else new_sum = @driver.net_earning(@trip.cost) end @driver.update(total_earned: new_sum) redirect_to trip_path(@trip.id) return else # bad passenger_id triggers this redirect_to nope_path(params: {msg: "Trip request unsuccessful, please contact customer service at 1-800-lol-sorry"}) return end end def edit # individual passenger uses this to update ratings @trip = Trip.find_by(id:params[:id]) if @trip.nil? redirect_to nope_path(params: {msg: "No such trip exists!"}) return else @trips = [@trip] @rating = nil end end def update # individual passenger uses this to update ratings @trip = Trip.find_by(id: params[:id]) if @trip.nil? redirect_to nope_path(params: {msg: "No such trip exists!"}) return end driver_id = @trip.driver_id passenger_id = @trip.passenger_id rating = params[:rating].to_i if rating.nil? redirect_to nope_path(params: {msg: "No rating given!"}) return elsif @trip.update(rating: rating) # need to flip driver.active back to false, so they can work again driver = Driver.find_by(id: driver_id) if driver.update(active: false) redirect_to passenger_trips_path(passenger_id: passenger_id) return else redirect_to nope_path(params: {msg: "Unable to switch driver.active back to false, please call customer service at 1-800-LOL-SORRY"}) return end else # this happens when Trip model validation fails # such as when user presses submit w/o rating the trip first if rating == 0 redirect_to nope_path(params: {msg: "You must select a rating from 1 to 5. Please try again"}) return else redirect_to nope_path(params: {msg: "Unable to update rating, please call customer service at 1-800-LOL-SORRY"}) return end end end def destroy######### FIX A BUG HERE!!! SEE TRELLO!!!! # Only passengers can delete their own trips via links selected_trip = Trip.find_by(id: params[:id]) if selected_trip.nil? redirect_to nope_path(params: {msg: "No such trip exists!"}) return else selected_trip.destroy redirect_to passenger_path(id: selected_trip.passenger_id) return end end end
true
20331ec7aabec2e857396452c8347ab93ca67654
Ruby
hdemon/hdemon-backend
/response.rb
UTF-8
191
2.53125
3
[]
no_license
class Response attr_accessor :data, :message, :error def render { message: @message || "Success.", errors: @errors || [], data: @data }.to_json end end
true
e2ea3ecb23e0f0ce1e0583a7681d4e07ce3478e9
Ruby
JetechNY/ruby-oo-relationships-practice-boating-school-exercise
/app/models/student.rb
UTF-8
873
3.125
3
[]
no_license
require 'pry' class Student attr_accessor :first_name @@all = [] def initialize(first_name) @first_name = first_name @@all << self end def self.all @@all end def add_boating_test(testname, teststatus, instructor ) BoatingTest.new(self, testname, teststatus, instructor) end def all_instructors stud=BoatingTest.all.select {|test| test.student == self } stud.map {|inst|inst.instructor} end def self.find_student(first_name) self.all.select {|student_ist| student_ist.first_name == first_name} end def grade_percentage alltest= BoatingTest.all.select {|test| test.student == self } passedtest= alltest.map {|test| test.teststatus == "passed"} (passedtest.count.to_f/alltest.count)*100 #passed/alltest end end #
true
ec4c9b69e3c45e177bfae01feda716ef6431de7a
Ruby
radiospiel/vex
/lib/vex/base/hash/slop.rb
UTF-8
2,939
3.390625
3
[]
no_license
# # - allows to use hash.xx.yy where you would have to use # hash["xx"][:yy] etc. # # - supports # # hash.xx? # # as a shortcut for hash.key?(:xx) || hash.key?("xx") # # - does not support assignment, though; i.e. # # hash.yy = zz # # will raise a NoMethodError. # class Hash module Slop private def lookup_sloppy_key(key) return key if key?(key) return key.to_s if key?(key.to_s) return key.to_sym end def method_missing(sym, *args, &block) return super if block_given? if args.length == 1 && sym.to_s =~ /^(.*)=$/ return self[lookup_sloppy_key($1)] = args.first elsif args.length == 0 if sym.to_s =~ /^(.*)\?$/ # Return false if the entry does not exist. # Return true if the entry exists and evaluates to false # Return the entry otherwise. key = lookup_sloppy_key($1) return nil if !key?(key) return (self[key] || true).slop! else # fetch the entry, if it exists, or raise an IndexError return fetch(lookup_sloppy_key(sym)).slop! end end super rescue IndexError super end public def respond_to?(sym) super || case sym.to_s when /^(.*)[=\?]$/ true else key? lookup_sloppy_key(sym) end end end def slop! extend(Slop) end def sloppy? is_a?(Slop) end end class Array def slop! each(&:"slop!") end end class Object def slop dup.slop! rescue TypeError # e.g. "Can't dup NilClass" self end def slop! self end def sloppy? false end end module Hash::Slop::Etest def test_slop_hashes h = { :a => { "b" => "ccc" }} h1 = h.slop! assert h.sloppy? assert h1.sloppy? assert_equal("ccc", h.a.b) assert h1.object_id == h.object_id assert h.a? assert !h.b? assert h.a.b? assert !h.a.c? end def test_nil_entries h = { :a => nil, :b => false, :c => 1 } h.slop! assert_equal true, h.a? assert_equal true, h.b? assert_equal 1, h.c? assert_equal nil, h.d? assert_equal nil, h.a assert_equal false, h.b assert_equal 1, h.c assert_raises(NoMethodError) { h.d } end def test_slop_hashes_2 h = { :a => { "b" => "ccc" }} h1 = h.slop assert !h.sloppy? assert h1.sloppy? assert_equal("ccc", h1.a.b) assert h1.object_id != h.object_id assert h1.a? assert !h1.b? assert h1.a.b? assert !h1.a.c? end def test_slop_assigns h = { :a => { "b" => "ccc" }} h.slop! h.a = 2 assert_equal({ :a => 2}, h) h.b = 2 assert_equal({ :a => 2, :b => 2}, h) v = { :c => { :d => 2 } } assert !v.sloppy? h.b = v.dup assert_equal(2, h.b.c.d) assert !v.sloppy? assert h.b.sloppy? end end if VEX_TEST == "base"
true
57c2247c65571008dbb46f17ccd646878b13e24e
Ruby
bumpouce/ruby-oo-relationships-practice-blood-oath-exercise-seattle-web-030920
/tools/console.rb
UTF-8
2,404
2.90625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require_relative '../config/environment.rb' def reload load 'config/environment.rb' end # Insert code here to run before hitting the binding.pry # This is a convenient place to define variables and/or set up new object instances, # so they will be available to test and play around with in your console #Test cult setup: Cult.new(name, location, founding_year, slogan) cult1 = Cult.new("Church of Satan", "San Francisco", 1966, "Satanic Panic", 18) cult2 = Cult.new("Peoples Temple", "Jonestown", 1955, "Drink the Kool-Aid", 40) cult3 = Cult.new("Raelism", "Paris", 1976, "We come in peace") cult4 = Cult.new("The Family", "San Francisco", 1967, "Helter Skelter") Cult.find_by_name("Raelism") Cult.find_by_founding_year(1955) Cult.find_by_location("San Francisco") #Test follower setup: Follower.new(name, age, life_motto) follower1 = Follower.new("Charles Manson", 21, "Never Leave Me") follower2 = Follower.new("Jim Jones", 26, "This is Utopia") follower3 = Follower.new("Tony Alamo", 55, "God and Rock 'n' Roll") follower4 = Follower.new("Marcus Delon Wesson", 32, "Make your own congregation") follower5 = Follower.new("John Griggs", 21, "Try this LSD") #Test blood oath setup: BloodOath.new(follower, cult, initiation_date). Initiation date string: YYYY-MM-DD oath1 = BloodOath.new(follower1, cult1, "2000-03-13") oath2 = BloodOath.new(follower1, cult2, "1968-12-25") oath3 = BloodOath.new(follower2, cult4, "2000-03-13") oath4 = BloodOath.new(follower3, cult3, "1974-07-06") oath5 = BloodOath.new(follower3, cult2, "1995-06-29") oath6 = BloodOath.new(follower4, cult2, "1968-12-25") oath7 = BloodOath.new(follower5, cult1, "1984-11-30") oath8 = BloodOath.new(follower5, cult3, "1974-07-06") #Test recruit_follower (follower, initiation_date) cult1.recruit_follower(follower1, "2020-03-09") cult1.recruit_follower(follower3, "2020-03-09") cult1.recruit_follower(follower2, "2020-03-09") cult1.recruit_follower(follower4, "2020-03-09") # #Test join_cult(cult, initiation_date) follower1.join_cult(cult3, "1920-03-15") follower1.join_cult(cult4, "2020-03-15") follower2.join_cult(cult2, "2020-03-15") pop1 = cult1.cult_population pop2 = cult2.cult_population pop3 = cult3.cult_population pop4 = cult4.cult_population belong1 = follower1.cults belong2 = follower2.cults belong3 = follower3.cults belong4 = follower4.cults belong5 = follower5.cults binding.pry # puts "Mwahahaha!" # just in case pry is buggy and exits
true
a3eb31ac89d0023f601ad85143117e8f9014ae4b
Ruby
evgeniradev/ruby_data_structures_and_algorithms
/data_structures/linked_list.rb
UTF-8
1,559
3.78125
4
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class LinkedList def initialize(value) node = Node.new(value) @head = node @tail = node @length = 1 end attr_reader :head, :tail, :length def append(value) node = Node.new(value) @tail.next = node @tail = node @length += 1 node end def prepend(value) node = Node.new(value) node.next = @head @head = node @length += 1 node end def insert(value, i) return prepend(value) if i.zero? previous_node = find_previous_node(i) return append(value) if previous_node&.next.nil? node = Node.new(value) node.next = previous_node.next previous_node.next = node @length += 1 node end def remove_by_index(i) return 'You cannot delete the last node.' if @length == 1 if i.zero? node = @head @head = @head.next @length -= 1 return node end previous_node = find_previous_node(i) return 'Node does not exist.' if previous_node&.next.nil? @tail = previous_node if previous_node.next == @tail node = previous_node.next previous_node.next = previous_node.next.next @length -= 1 node end def print node = @head i = 0 while node puts "#{i}: #{node.value}" i += 1 node = node.next end end private def find_previous_node(i) node = @head (i - 1).times do node = node&.next break unless node end node end end class Node def initialize(value) @value = value @next = nil end attr_accessor :value, :next end
true
274fcd2156d5f4119bac4c6fda2895c2d0ac25fb
Ruby
Mstandley1985/ted_lasso_2103
/lib/team.rb
UTF-8
280
3.4375
3
[]
no_license
class Team attr_reader :name, :coach, :players def initialize(name, coach, players) @name = name @coach = coach @players = [] end def add_player(player) @players << player end def total_salary @players end end
true
610c04d27c66a85a9ddd6aafb919c9f74be1ab2c
Ruby
Ess91/black_history
/lib/black_history/oct_blackhistory.rb
UTF-8
673
3.03125
3
[ "MIT" ]
permissive
require 'pry' class BlackHistory::Oct_BlackHistory @@all = [] attr_accessor :events, :dates, :locations, :event_url, :descriptions def initialize #@events = events #@dates = dates #@locations = locations #@event_url = event_url # @descriptions = descriptions @@all << self end def self.all @@all end #Make the event the main instead of the locations, just to eliminate the duplication! # binding.pry BlackHistory::Oct_BlackHistory.all.map do |area| return area.events end #def self.list_dates # self.all.each.with_index(1) do |event, index| #puts "#{index}. #{event.dates}" #end #end end # end #end
true
f7947e36fb8fd6e511a09b0948ab73160e16fd11
Ruby
bgraves14/Battleships
/lib/ship.rb
UTF-8
180
3.28125
3
[]
no_license
class Ship attr_reader :coordinates, :placed def initialize @placed = false @coordinates = [] end def position(ship_position) @coordinates << ship_position end end
true
00d3c0c4e7832573ca491436162f87a31d35e293
Ruby
rn0rno/kyopro
/aoj/ruby/01_ITP/ITP1_10_C.rb
UTF-8
174
3
3
[]
no_license
#!/usr/bin/env ruby until (n = gets.to_i).zero? s = gets.chomp.split.map(&:to_f) ave = s.inject(:+) / n puts Math.sqrt(s.map { |i| (i - ave)**2 }.inject(:+) / n) end
true
e3a4107ede1dd1662924dee9e28e1eeaeaf25db2
Ruby
ShetlandJ/employee_system_practice
/company.rb
UTF-8
775
2.859375
3
[]
no_license
require_relative('employee') require_relative('manager') require_relative('supervisor') require_relative('cog') class Company def initialize(name, employees, performance, cash) @name = name @employees = employees @performance = performance @available_cash = cash end # getters def name() return @name end def employees() return @employees end def performance() return @performance end def cash() return @available_cash end # setters def set_name(name) @name = name end def add_employee(employee) @employees << employee end def set_performance(performance) @performance = performance end def add_investment(investment) @available_cash += investment end # behaviour end
true
0d5ea9dc40d07b0ace962a562d305e46940bfabf
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/gigasecond/6342e324c9394f49b0277d6dae67d47c.rb
UTF-8
157
2.84375
3
[]
no_license
module Gigasecond def self.from(date) seconds = date.to_time.to_i gigaseconds = seconds + 1_000_000_000 Time.at(gigaseconds).to_date end end
true
5d180f3de7b8acad5bfaf7781ec01557543624e5
Ruby
phil/playbox
/lib/controllers/interface.rb
UTF-8
1,592
2.921875
3
[]
no_license
require 'singleton' # Interface controller is responsible for managing connections and updating those connections as events are processed by thr player class InterfaceController include Singleton attr_accessor :connections def connections @connections ||= Array.new end def client_connected conn self.connections << conn broadcast_message "client connected #{conn}", :exclude_connections => [conn] end def client_disconected conn self.connections.delete_if { |c| c == conn } end def broadcast_message message, opts = Hash.new opts[:exclude_connections] ||= Array.new notification = JukeboxController.instance.info notification[:notification] = message puts "COMM OUT (broadcast): #{notification}" self.connections.each do |conn| next if opts[:exclude_connections].include?(conn) send_data_to notification, conn end end def send_message_to message, connection conn = self.connections.detect { |c| c == connection } response = JukeboxController.instance.info response[:response] = message puts "COMM OUT: #{response}" send_data_to response, conn end protected def send_data_to data, connection puts connection case connection.class.to_s when "TcpSocketInterface" puts "sending to tcp" connection.push JSON.generate(data) when "EventMachine::WebSocket::Connection" puts "sending to websocket" connection.send JSON.generate(data) else puts "Umm?" end end #def send_status_to status, connectin # self.connections.detect { |conn| conn == connection }.try :push, message #end end
true
3042b09ca5d0c3b8387e6724bc43c65af794c5dc
Ruby
rohita/MusicExplorer
/test/unit/lfm_album_test.rb
UTF-8
1,387
2.578125
3
[]
no_license
require 'test_helper' class LfmAlbumTest < ActiveSupport::TestCase def setup @album = LfmAlbum.find("Dummy", "Portishead") end test "can get album title" do assert_equal "Dummy", @album.title end test "can get album artist name" do assert_equal "Portishead", @album.artist_name end test "can get album release date" do assert_equal " 2 Feb 2005", @album.release_date end test "can get album image url" do assert_equal "http://userserve-ak.last.fm/serve/300x300/9485831.jpg", @album.image_url end test "can get album description" do expected = "Dummy is the 1994 debut album of the Bristol-based group Portishead. " + "It reached #2 on the UK Album Chart and #79 on the Billboard 200 chart, going gold in 1997. " + "Building on the promise of their earlier EP—&quot;Numb&quot;—it helped to cement the reputation " + "of Bristol as the capital of Trip hop, a nascent genre which was then often referred to simply as " + "&quot;the Bristol sound&quot;.The cover is a still of Gibbons from the short film that the band " + "created—To Kill a Dead Man—which originally got them signed due to their self composed soundtrack. " assert_equal expected, @album.description end test "favorite" do assert @album.is_favorite_of(1) assert !@album.is_favorite_of(2) end end
true
589f0f54ab5ea5018445c24f73213613e25fc305
Ruby
jodokusquack/connect_four
/spec/cell_spec.rb
UTF-8
821
3.25
3
[]
no_license
require './lib/cell.rb' RSpec.describe Cell do subject(:cell){ Cell.new(content: "X") } describe "#content" do it "returns the content of the cell" do expect(cell.content).to eq "X" end end describe "#to_s" do it "prints its content to the screen" do expect { puts cell }.to output("X\n").to_stdout end end describe "#==" do it "returns true if two cells have the same content" do other = Cell.new(content: "X") expect(cell == other).to eq true end it "returns false if the other cell has a different content" do other = Cell.new(content: "O") expect(cell == other).to eq false end it "returns false when compared to something that isn't a cell" do other = "X" expect( cell == other ).to eq false end end end
true
79ce3cd21e2e83b7f4d50fc3a671a778a5f15b0a
Ruby
billdevcode/phase-0
/week-4/calculate-grade/my_solution.rb
UTF-8
629
4.0625
4
[ "MIT" ]
permissive
# Calculate a Grade # I worked on this challenge [with: David Walden]. # Your Solution Below =begin input: integer output: string IF provided integer is between 90 to 100 grade is A so return "A" IF provided integer is between 80 to 89 grade is B so return "B" IF provided integer is between 70 to 79 grade is C so return "C" IF provided integer is between 60 to 69 grade is D so return "D" IF provided integer is under 60 grade is F so return "F" =end def get_grade(num) case num when 90..100 then "A" when 80..89 then "B" when 70..79 then "C" when 60..69 then "D" when 0..59 then "F" end end
true
991c7939c0f7281df0870918f8a8d7c26fb1f4e7
Ruby
B0NG0FURY/upcoming_releases
/lib/upcoming_releases/scraper.rb
UTF-8
2,036
2.859375
3
[ "MIT" ]
permissive
class UpcomingReleases::Scraper def self.scrape_release_page(release_url) doc = Nokogiri::HTML(open(release_url)) result = [] doc.css("div.product-page div.uk-grid div.album").each do |album| info = { :name => album.css("h5").text, :artist => album.css("h4 a").text, :label => album.css("h6 a").text, :info_url => album.css("a")[0]["href"] } result << info end result end def self.scrape_info_page(info_url) doc = Nokogiri::HTML(open(info_url)) info = {} description = doc.css("div.item-meta p").text.strip doc.css("div.item").each do |format| type = format.css("h5").text.downcase type = type.split(" ") #changes 2lp format to just lp to properly make a symbol out of 'type' for hash if type[0] == "2xlp" type[0] = "lp" end #changes from number to letters to properly make a symbol for hash if type[0] == '7"' type[0] = "seven_inch" end date = format.css("p").text date = date.slice(0..9) if type[0] == "lp" || type[0] == "cd" || type[0] == "mp3" || type[0] == "seven_inch" info[type[0].to_sym] = { :price => type[1], :release_date => date } end end info[:description] = description info end end #Release Page- #bands = doc.css("div.product-page div.uk-grid div.album") #artist = bands.css("h4 a").text #album = bands.css("h5").text #label = bands.css("h6 a").text #info_page = bands.css("a")[0]["href"] #Album info page- #album = doc.css("div.item").each do |format| #type = format.css("h5").text #type = type.split(" ") #date = format.css("p").text #date = date.slice(0..9) #formats[type[0].to_sym] = { #:price => type[1], #:release_date => date #}
true
675a3386462570212239f64fbdaaf38ce2a38eae
Ruby
renamabo/enigma-1
/spec/offset_spec.rb
UTF-8
504
2.625
3
[]
no_license
require './spec/spec_helper' require './lib/offset' RSpec.describe Offset do context 'instantiation' do it 'exists' do date = "16-05-2003" offset = Offset.new(date) expect(offset).to be_instance_of(Offset) end it 'has attributes' do date = "16-05-2003" offset = Offset.new(date) expect(offset.offset_a).to eq(2) expect(offset.offset_b).to eq(0) expect(offset.offset_c).to eq(0) expect(offset.offset_d).to eq(9) end end end
true
034ff1713b968c48ccd479389663010f70189f2d
Ruby
chrystalfaith/ruby-challenges
/blog.rb
UTF-8
965
3.765625
4
[]
no_license
class My_Blog def initialize @time_created = Time.now puts "What would you like to call your blog?" @blog_title = gets.chomp @all_posts = [] @total_posts = 0 end def create_post new_post = Blog_Post.new puts "This is my brand spanking new blog post!" @all_posts << new_post @total_posts += 1 end def collect_posts return @all_posts end def publish(all_posts) all_posts.each do |blog_post| puts blog_post.title puts blog_post.time_created puts blog_post.content end end end class Blog_Post def initialize @time_created = Time.now puts "Name your post:" @title = gets.chomp puts "Fill in your content:" @content = gets.chomp end def edit_content puts "New title" @title = gets.chomp puts "New text" @content = gets.chomp end end chrystals_blog = My_Blog.new post1 = chrystals_blog.create_post all_posts = chrystals_blog.collect_posts puts chrystals_blog.inspect chrystals_blog.publish(all_posts)
true
689b60db21d82c55fe22afa6a4e4af29956fbd3e
Ruby
simonrodonnell/function_testing
/ruby_functions_practice.rb
UTF-8
1,534
4.03125
4
[]
no_license
def return_10 return 10 end def add(first_number, second_number) return first_number + second_number end def subtract(first_number, second_number) return first_number - second_number end def multiply(first_number, second_number) return first_number * second_number end def divide(first_number, second_number) return first_number / second_number end def length_of_string(my_string) return my_string.length() end def join_string(string_1, string_2) return string_1 + string_2 end def add_string_as_number(string_1, string_2) return string_1.to_i() + string_2.to_i() end def number_to_full_month_name(number) case number when 1 "January" when 2 "February" when 3 "March" when 4 "April" when 5 "May" when 6 "June" when 7 "July" when 8 "August" when 9 "September" when 10 "October" when 11 "November" when 12 "December" end end def number_to_short_month_name(number) return number_to_full_month_name(number)[0..2] # case number # when 1 # "Jan" # when 2 # "Feb" # when 3 # "Mar" # when 4 # "Apr" # when 5 # "May" # when 6 # "Jun" # when 7 # "Jul" # when 8 # "Aug" # when 9 # "Sep" # when 10 # "Oct" # when 11 # "Nov" # when 12 # "Dec" # end end def volume_of_cube(length) return length ** 3 end def volume_of_sphere(radius) return (4 * Math::PI / 3 * (radius**3)) end def fahrenheit_to_celsius(fahrenheit) return (((fahrenheit - 32) * 5) / 9) end
true
9be4bb6dfc3f473cde03b2d6ffa839f4ef5befec
Ruby
chinmaydd/SnakeforRuby
/game.rb
UTF-8
1,993
3.703125
4
[]
no_license
class Board @board = [] 100.times do |i| row = [] @board<<row end @board.each do |row| 100.times do |i| row<<'0' end end def set_snake choice_x = rand(0..99) choice_y = rand(0..99) board[choice_x][choice_y]=3 end def set_food choice_x = rand(0..99) choice_y = rand(0..99) if(board[choice_x][choice_y] == 1) set_food else board[choice_x][choice_y] = 2 end end def update(snake) if board[snake.head_x][snake.head_y]==1 puts "Don't be a cannibal, bro." return end if board[snake.head_x][snake.head_y] == 2 length += 1 end if dir=='l' board[snake.head_x][snake.head_y - 1] = 3 elsif dir == 'r' board[snake.head_x][snake.head_y + 1] = 3 elsif dir == 'u' board[snake.head_x - 1][snake.head_y] = 3 elsif dir == 'd' board[snake.head_x + 1][snake.head_y] = 3 end board[snake.tail_x][snake.tail_y] = 0 end end class Snake @turn_pts_x = [50] @turn_pts_y = [50] @dir = 'u' @head_x = 50 @head_y = 50 @tail_x = 50 @tail_y = 51 @length = 2 def update_turn turn_pts_x << @head_x turn_pts_y << @head_y end def turn_right dir = 'r' update_turn end def go_up dir = 'u' update_turn end def go_down dir = 'd' update_turn end def turn_left dir = 'l' update_turn end end board = Board.new() snake = Snake.new()
true
7e34f5a8c859ed85395e6dfb72024066bb4ecf52
Ruby
b-shears/Relocate-Back-End-Rails
/app/poros/business.rb
UTF-8
644
3.4375
3
[]
no_license
class Business attr_reader :name, :image, :url, :phone, :distance, :location, :id def initialize(result) @name = result[:name] @image = result[:image] @url = result[:url] @phone = result[:phone] @distance = meters_to_miles(result[:distance]) @location = address(result[:location]) @id = result[:id] end def address(location) "#{location[:address1]} #{location[:address2]} #{location[:city]} #{location[:state]}, #{location[:zip_code]}" end def meters_to_miles(length) length * 0.000621371 if length end end
true
32e3f014dc2f0e6c49d8deff74364f9578e053ea
Ruby
anhbk93/rails_recipe_manager
/test/models/chef_test.rb
UTF-8
1,756
2.703125
3
[]
no_license
require 'test_helper' class ChefTest < ActiveSupport::TestCase def setup @chef = Chef.new( chefname: "Anh NV", email: "navait93@gmail.com" ) end test "chef should be valid" do assert @chef.valid? end test "chefname should be present" do @chef.chefname = " " assert_not @chef.valid? end test "chefname should not be too long" do @chef.chefname = "a" * 51 assert_not @chef.valid? end test "chefname should not be too short" do @chef.chefname = "a" assert_not @chef.valid? end test "email should not be too long" do @chef.email = "a" * 254 + "@mail.com" assert_not @chef.valid? end test "email validation should accept valid addresses" do valid_addresses = %w[chef@example.com chef@foo.COM A_US-ER@foo.bar.org first.last@foo.jp alice+bob@baz.cn] valid_addresses.each do |valid_address| @chef.email = valid_address assert @chef.valid?, "#{valid_address.inspect} should be valid" end end test "email validation should reject invalid addresses" do invalid_addresses = %w[chef@example,com chef_at_foo.org chef.name@example. foo@bar_baz.com foo@bar+baz.com] invalid_addresses.each do |invalid_address| @chef.email = invalid_address assert_not @chef.valid?, "#{invalid_address.inspect} should be invalid" end end test "email should be unique" do duplicate_chef = @chef.dup duplicate_chef.email = @chef.email.upcase @chef.save assert_not duplicate_chef.valid? end test "email addresses should be saved as lower-case" do mixed_case_email = "Foo@ExAMPle.CoM" @chef.email = mixed_case_email @chef.save assert_equal mixed_case_email.downcase, @chef.reload.email end end
true
2a67803c2605a8f753d833166784843ba9e3dd06
Ruby
houston/attentive
/test/entities/core_number_test.rb
UTF-8
1,660
2.515625
3
[ "MIT" ]
permissive
require "test_helper" class CoreNumberTest < Minitest::Test extend Attentive::Test::Entities entity("core.number").should do match("0").as(0) match("4").as(4) match("-5").as(-5) match("6.75").as(BigDecimal.new("6.75")) match("451,972.00").as(BigDecimal.new("451972.00")) match("$6.45").as(BigDecimal.new("6.45")) match("12.3%").as(BigDecimal.new("12.3")) match("45mm").as(45) match("45'").as(45) end entity("core.number.positive").should do match("34,811").as(34811) match("1,348.66").as(BigDecimal.new("1348.66")) ignore("0") ignore("-100") ignore("-0.00125") end entity("core.number.negative").should do match("-100").as(-100) match("-0.00125").as(BigDecimal.new("-0.00125")) ignore("0") ignore("34,811") ignore("1,348.66") end entity("core.number.integer").should do match("0").as(0) match("4").as(4) match("-5").as(-5) ignore("0.5") end entity("core.number.integer.positive").should do match("4").as(4) ignore("0") ignore("-5") end entity("core.number.integer.negative").should do match("-5").as(-5) ignore("0") ignore("4") end entity("core.number.float").should do match("0.0").as(BigDecimal.new("0.0")) match("0.5").as(BigDecimal.new("0.5")) ignore("0") ignore("4") ignore("-5") end entity("core.number.float.positive").should do match("4.00").as(BigDecimal.new("4.00")) ignore("0.0") ignore("-5.99") end entity("core.number.float.negative").should do match("-5.99").as(BigDecimal.new("-5.99")) ignore("0.0") ignore("4.00") end end
true
58efbc13b0c2b6e5370e876761d08b6f55c3c12b
Ruby
bmaland/hyde
/lib/jekyll/engines.rb
UTF-8
2,065
2.671875
3
[ "MIT" ]
permissive
module Jekyll module Engines def self.setup(config) # Set the Markdown interpreter (and Maruku self.config, if necessary) @@config = config case config['markdown'] when 'rdiscount' begin require 'rdiscount' rescue LoadError puts 'You must have the rdiscount gem installed first' end when 'maruku' begin require 'maruku' if config['maruku']['use_divs'] require 'maruku/ext/div' puts 'Maruku: Using extended syntax for div elements.' end if config['maruku']['use_tex'] require 'maruku/ext/math' puts "Maruku: Using LaTeX extension. Images in `#{config['maruku']['png_dir']}`." # Switch off MathML output MaRuKu::Globals[:html_math_output_mathml] = false MaRuKu::Globals[:html_math_engine] = 'none' # Turn on math to PNG support with blahtex # Resulting PNGs stored in `images/latex` MaRuKu::Globals[:html_math_output_png] = true MaRuKu::Globals[:html_png_engine] = config['maruku']['png_engine'] MaRuKu::Globals[:html_png_dir] = config['maruku']['png_dir'] MaRuKu::Globals[:html_png_url] = config['maruku']['png_url'] end rescue LoadError puts 'The maruku gem is required for markdown support!' end else raise "Invalid Markdown processor: '#{config['markdown']}' -- " + "did you mean 'maruku' or 'rdiscount'? " end end def self.textile(content) RedCloth.new(content).to_html end def self.markdown(content) @@config['markdown'] == "maruku" ? self.maruku(content) : self.rdiscount(content) end def self.maruku(content) Maruku.new(content).to_html end def self.rdiscount(content) RDiscount.new(content).to_html end def self.haml(content) require "haml" Haml::Engine.new(content, :suppress_eval => true).render end end end
true
7f6912750fb55a3a90f029d5d8b7711632169c80
Ruby
philcrooks/homework04.1
/models/wordformatter.rb
UTF-8
223
3.25
3
[]
no_license
class WordFormatter def WordFormatter.postcode(text) return text.upcase end def WordFormatter.camel_case(text) words = text.downcase.split(' ').map { | word | word.capitalize } return words.join end end
true
24af99edae29278f71df77aae0285113439e7352
Ruby
Paolavuolo/it-s_me_mario
/exo_13.rb
UTF-8
331
3.546875
4
[]
no_license
#liste d'email i = 1 email_list = Array.new() while (i <= 50) if (i<10) #cette ligne permet d'ajouter un 0, pour 01,02 etc.. email = "jean.dupont.0#{i}@email.fr" else email = "jean.dupont.#{i}@email.fr" end email_list.push (email) #.push() va permettre d'insérer les mails dans l'array i = i +1 end puts email_list
true
4ab9592a8faa69b0ab9ab660f034f1786f8c0d06
Ruby
primeapple/ruby-experiments
/experiments/tic-tac-toe/state.rb
UTF-8
1,806
3.65625
4
[]
no_license
class State SIZE = 3 def initialize(state = {}) @state = state if state == {} SIZE.times do |x| SIZE.times do |y| @state[[x, y]] = ' ' end end end end def next_state(x, y, char) raise ArgumentError.new('Wrong argument for x given') unless x.between?(0, 2) raise ArgumentError.new('Wrong argument for y given') unless y.between?(0, 2) raise ArgumentError.new('There was already a point at this spot') unless @state[[x, y]] == ' ' # TODO: maybe find a more efficient way to do this... hash = Marshal.load(Marshal.dump(@state)) hash[[x, y]] = char State.new(hash) end def winner winner = ' ' SIZE.times do |cord| if all_equal(@state[[cord, 0]], @state[[cord, 1]], @state[[cord, 2]]) winner = @state[[cord, 0]] break end if all_equal(@state[[0, cord]], @state[[1, cord]], @state[[2, cord]]) winner = @state[[0, cord]] break end end if all_equal(@state[[0, 0]], @state[[1, 1]], @state[[2, 2]]) || all_equal(@state[[0, 2]], @state[[1, 1]], @state[[2, 0]]) winner = @state[[1, 1]] end winner end def filled? SIZE.times do |y| SIZE.times do |x| return false if @state[[x, y]] == ' ' end end true end def print_state divider = " +#{'--' * SIZE}-+" puts " #{(0...SIZE).to_a.join(' ')}" puts divider SIZE.times do |y| print "#{y}| " SIZE.times do |x| print "#{@state[[x, y]]} " end puts '|' end puts divider end def possible_moves @state.keys.select { |key| @state[key] == ' '} end def remaining_moves @state.values.count(' ') end private def all_equal(x, y, z) x == y && y == z && z != ' ' end end
true
be290f71514d46b0fe49ad2fabc9c0e5f431ca13
Ruby
lebrancconvas/Ruby-Lab
/avc.rb
UTF-8
43
2.71875
3
[]
no_license
a = [1,2,3,4] b = a.map(a = a + 5) print(b)
true
de657d749e2706fe2aebebe0d51c014ff95a500e
Ruby
luong-komorebi/dd-trace-rb
/lib/ddtrace/augmentation/shim.rb
UTF-8
2,539
2.765625
3
[]
permissive
require 'set' require 'ddtrace/patcher' require 'ddtrace/augmentation/method_wrapping' module Datadog # A "stand-in" that intercepts calls to another object. i.e. man-in-the-middle. # This shim forwards all methods to object, except those overriden. # Useful if you want to intercept inbound behavior to an object without modifying # the object in question, especially useful if the overridding behavior shouldn't be global. class Shim extend Forwardable include Datadog::Patcher include Datadog::MethodWrapping METHODS = Set[ :override_method!, :shim, :shim?, :shim_target, :wrap_method!, :wrapped_methods ].freeze EXCLUDED_METHODS = Set[ # For all objects :__binding__, :__id__, :__send__, :extend, :itself, :object_id, :respond_to?, :tap ].freeze attr_reader :shim_target, :shim def self.shim?(object) # Check whether it responds to #shim? because otherwise the # Shim forwards all method calls, including type checks to # the wrapped object, to mimimize its intrusion. object.respond_to?(:shim?) end # Pass this a block to override methods def initialize(shim_target) @shim = self @shim_target = shim_target # Save a reference to the original :define_singleton_method # so methods can be defined on the shim after forwarding is applied. @definition_method = method(:define_singleton_method) # Wrap any methods yield(self) if block_given? # Forward methods forwarded_methods = ( shim_target.public_methods.to_set \ - METHODS \ - EXCLUDED_METHODS \ - wrapped_methods ) forward_methods!(*forwarded_methods) end def override_method!(method_name, &block) return unless block_given? without_warnings do @definition_method.call(method_name, &block).tap do wrapped_methods.add(method_name) end end end def wrap_method!(method_name, &block) super(shim_target.method(method_name), &block) end def shim? true end def respond_to?(method_name) return true if METHODS.include?(method_name) shim_target.respond_to?(method_name) end private def forward_methods!(*forwarded_methods) return if forwarded_methods.empty? singleton_class.send( :def_delegators, :@shim_target, *forwarded_methods ) end end end
true
e7b7e7f3e62e1472608de4b78c1b5e3d6e6e74f7
Ruby
helenpxx/ics_bc_s18
/week4/ch10/dict_sort.rb
UTF-8
642
3.859375
4
[]
no_license
def dict_sort(some_array) # This "wraps" recursive_sort. recursive_dict_sort some_array, [] end def recursive_dict_sort(unsorted_array, sorted_array) # Your fabulous code goes here. if unsorted_array.length == 0 sorted_array else min_index = min_ind unsorted_array min_elem = unsorted_array.delete_at min_index sorted_array.push min_elem recursive_dict_sort unsorted_array, sorted_array end end def min_ind(array) min_ind = 0 ind = 1 while ind < array.length if (array[ind]).capitalize < (array [min_ind]).capitalize min_ind = ind end ind += 1 end min_ind end puts dict_sort ['S','a','B']
true
890c3cf720d054fcdc8ad006d75a41755bd68c66
Ruby
drwrf/lang
/old/lib/lang/token.rb
UTF-8
1,862
3.15625
3
[]
no_license
class Lang::Token class << self def define(&block) class_eval(&block) end def token(name, start, capture: nil, quote: false, &block) cls = Class.new(self) cls.const_set('START', start) cls.const_set('CAPTURE', capture) cls.const_set('QUOTE', quote) const_set(name, cls) end end def parseable?(stream) match?(stream, start) end def parse(stream) if !parseable?(stream) raise RuntimeError end start = stream.location value = consume(stream) finish = stream.location Lang::Lexeme.new(value, self, start, finish) end private def consume(stream) chars = '' if start.is_a? ::String chars += advance(stream, start.length) elsif start.is_a? ::Array chars += advance(stream, start.find {|t| match?(stream, t) }.length) elsif start.is_a? ::Regexp chars += advance(stream, 1) else raise NotImplementedError end # Match everything until a match is made if capture chars += advance_until(stream, capture) # Match everything inside the delimiters elsif quote? quote = chars chars = advance_until(stream, chars) advance(stream, quote.length) end chars end def match?(stream, test) if test.is_a? ::String stream.peek(test.length) == test elsif test.is_a? ::Array !!(test.find {|t| match?(stream, t) }) else !!(stream.peek =~ test) end end def advance(stream, amount) stream.advance(amount) end def advance_until(stream, test) chars = '' loop do if stream.peek.nil? || match?(stream, test) break end chars += stream.advance end chars end def start self.class::START end def capture self.class::CAPTURE end def quote? self.class::QUOTE end end
true
fe1307ec4540d6fb5e71a7652f90c27e315c9bf0
Ruby
paddyjoneill/wk2_weekend_homework
/karaoke_bar.rb
UTF-8
1,990
3.625
4
[]
no_license
require 'pry' class KaraokeBar attr_reader :name, :rooms, :bars, :till, :entrance_fee def initialize(name, rooms, bars, initial_balance, entrance_fee) @name = name @rooms = rooms @bars = bars @till = initial_balance @entrance_fee = entrance_fee end def add_room(room) @rooms << room end def add_customer(room, customer) if customer.money >= @entrance_fee customer.remove_money(@entrance_fee) @till += @entrance_fee room.add_customer(customer) room.increase_total_spend(@entrance_fee) room.increase_customer_tab(customer, @entrance_fee) end end def remove_customer(room, customer) room.remove_customer(customer) end def add_song(room, song) room.add_song(song) end def increase_till(amount) @till += amount end def pay_entrance_fee(customer) if customer.money >= @entrance_fee customer.remove_money(@entrance_fee) @till += @entrance_fee end end def add_bar(bar) @bars << bar end def add_drinks(bar, drink, amount) bar.add_drink(drink, amount) end def stock_check(bar, drink) bar.stock[drink] end def remove_drink(bar, drink) bar.remove_drink(drink) end def sell_drink_to_customer(room, customer, bar, drink) return if !customer.has_enough_money(drink.price) return if bar.stock[drink] < 1 customer.remove_money(drink.price) bar.remove_drink(drink) @till += drink.price room.increase_total_spend(drink.price) room.increase_customer_tab(customer, drink.price) end def total_stock total_stock = 0 for bar in @bars # binding.pry for drink in bar.stock.keys total_stock += bar.stock[drink] end end return total_stock end def total_stock_value total_stock_value = 0 for bar in @bars for drink in bar.stock.keys total_stock_value += (bar.stock[drink] * drink.price) end end return total_stock_value end end
true
7404c70261d67a315656d86289cb3d9e02df235a
Ruby
lsegal/couchio
/lib/couchio/couch_open.rb
UTF-8
374
2.546875
3
[ "MIT" ]
permissive
module CouchOpen def open(name, mode = 'r', *perm, &block) if name.index("couch://") == 0 couch_io_class.new(name, mode, &block) else couch_orig_open(name, mode, *perm, &block) end end alias new open private def couch_io_class case self.to_s when 'File' CouchDocument when 'Dir' CouchDatabase end end end
true
97bb18ef882b5297249c264c7f9bec83431265f7
Ruby
extreem-engineer/extreme-engineer4
/fare.rb
UTF-8
150
2.84375
3
[]
no_license
class Fare attr_accessor :fare, :dept, :dest def initialize(fare,dept,dest) @fare = fare @dept = dept @dest = dest end end
true
ebd7c2a5f3eab884db3202d013f7bf3a69cb14cb
Ruby
soundasleep/adventofcode2016
/spec/advent_01_spec.rb
UTF-8
4,792
3.40625
3
[]
no_license
require "spec_helper" class Advent01 attr_reader :x, :y, :dx, :dy attr_reader :previous_visits, :visited_twice NORTH = [0, -1] SOUTH = [0, 1] WEST = [-1, 0] EAST = [1, 0] def initialize @x = 0 @y = 0 @dx, @dy = NORTH @previous_visits = {} end def call(input) input.split(", ").each do |step| step(step) end distance_from_zero end def location "(#{x},#{y})" end def step(input) case input[0] when "R" rotate_right! when "L" rotate_left! else fail "Unknown rotation for #{input}" end move_forwards!(input[1..9].to_i) end def rotate_left! @dx, @dy = case [dx, dy] when NORTH WEST when WEST SOUTH when SOUTH EAST when EAST NORTH else fail "I don't know how to rotate left from #{dx}, #{dy}" end end def rotate_right! @dx, @dy = case [dx, dy] when NORTH EAST when EAST SOUTH when SOUTH WEST when WEST NORTH else fail "I don't know how to rotate right from #{dx}, #{dy}" end end def move_forwards!(steps) steps.times do @x += dx @y += dy if previous_visits.has_key?(location) && @visited_twice.nil? @visited_twice = distance_from_zero end previous_visits[location] = distance_from_zero end end def distance_from_zero x.abs + y.abs end def to_s "[x=#{x}, y=#{y}, dx=#{dx}, dy=#{dy}, distance=#{distance_from_zero}, visited_twice=#{visited_twice}]" end end describe Advent01 do let(:north) { Advent01::NORTH } let(:south) { Advent01::SOUTH } let(:west) { Advent01::WEST } let(:east) { Advent01::EAST } describe "#call" do examples = { "R1" => 1, "R1, R1, R1, R1" => 0, "L1, L1, L1, L1" => 0, "R2" => 2, "L2" => 2, "R4" => 4, "L4" => 4, # provided data "R2, L3" => 5, "R2, R2, R2" => 2, "R5, L5, R5, R3" => 12, # actual input "L1, L3, L5, L3, R1, L4, L5, R1, R3, L5, R1, L3, L2, L3, R2, R2, L3, L3, R1, L2, R1, L3, L2, R4, R2, L5, R4, L5, R4, L2, R3, L2, R4, R1, L5, L4, R1, L2, R3, R1, R2, L4, R1, L2, R3, L2, L3, R5, L192, R4, L5, R4, L1, R4, L4, R2, L5, R45, L2, L5, R4, R5, L3, R5, R77, R2, R5, L5, R1, R4, L4, L4, R2, L4, L1, R191, R1, L1, L2, L2, L4, L3, R1, L3, R1, R5, R3, L1, L4, L2, L3, L1, L1, R5, L4, R1, L3, R1, L2, R1, R4, R5, L4, L2, R4, R5, L1, L2, R3, L4, R2, R2, R3, L2, L3, L5, R3, R1, L4, L3, R4, R2, R2, R2, R1, L4, R4, R1, R2, R1, L2, L2, R4, L1, L2, R3, L3, L5, L4, R4, L3, L1, L5, L3, L5, R5, L5, L4, L2, R1, L2, L4, L2, L4, L1, R4, R4, R5, R1, L4, R2, L4, L2, L4, R2, L4, L1, L2, R1, R4, R3, R2, R2, R5, L1, L2" => 299, } examples.each do |input, output| it "with #{input} returns #{output}" do subject = Advent01.new result = subject.call(input) expect(result).to eq(output), "#{subject}" end end end describe "#visited_twice" do examples = { "R8, R4, R4, R8" => 4, # actual input "L1, L3, L5, L3, R1, L4, L5, R1, R3, L5, R1, L3, L2, L3, R2, R2, L3, L3, R1, L2, R1, L3, L2, R4, R2, L5, R4, L5, R4, L2, R3, L2, R4, R1, L5, L4, R1, L2, R3, R1, R2, L4, R1, L2, R3, L2, L3, R5, L192, R4, L5, R4, L1, R4, L4, R2, L5, R45, L2, L5, R4, R5, L3, R5, R77, R2, R5, L5, R1, R4, L4, L4, R2, L4, L1, R191, R1, L1, L2, L2, L4, L3, R1, L3, R1, R5, R3, L1, L4, L2, L3, L1, L1, R5, L4, R1, L3, R1, L2, R1, R4, R5, L4, L2, R4, R5, L1, L2, R3, L4, R2, R2, R3, L2, L3, L5, R3, R1, L4, L3, R4, R2, R2, R2, R1, L4, R4, R1, R2, R1, L2, L2, R4, L1, L2, R3, L3, L5, L4, R4, L3, L1, L5, L3, L5, R5, L5, L4, L2, R1, L2, L4, L2, L4, L1, R4, R4, R5, R1, L4, R2, L4, L2, L4, R2, L4, L1, L2, R1, R4, R3, R2, R2, R5, L1, L2" => 181, } examples.each do |input, output| it "with #{input} returns #{output}" do subject = Advent01.new subject.call(input) expect(subject.visited_twice).to eq(output), "#{subject}" end end end describe "#rotate" do it "does rotation to the left" do x = Advent01.new expect([x.dx, x.dy]).to eq(north) x.rotate_left! expect([x.dx, x.dy]).to eq(west) x.rotate_left! expect([x.dx, x.dy]).to eq(south) x.rotate_left! expect([x.dx, x.dy]).to eq(east) x.rotate_left! expect([x.dx, x.dy]).to eq(north) end it "does rotation to the right" do x = Advent01.new expect([x.dx, x.dy]).to eq(north) x.rotate_right! expect([x.dx, x.dy]).to eq(east) x.rotate_right! expect([x.dx, x.dy]).to eq(south) x.rotate_right! expect([x.dx, x.dy]).to eq(west) x.rotate_right! expect([x.dx, x.dy]).to eq(north) end end end
true
a1731382621a7a28fdfbe56fffe1de1bde08aa87
Ruby
PewePro/alef-tng
/lib/tasks/data.rake
UTF-8
9,874
2.78125
3
[]
no_license
require 'rubygems' require 'nokogiri' require 'open-uri' require 'pandoc-ruby' require 'csv' namespace :alef do namespace :data do # import questions from ALEF docbook environment # run: # rake alef:data:import_xml['xml_dir'] task :import_xml, [:directory] => :environment do |t, args| directory = args.directory + "/**" files = Dir.glob(directory) files.each do |file| # open file @doc = Nokogiri::XML(File.open(file)) question = @doc.at('//alef:question') #question_type if question['type'] == "single-choice" question_type = "SingleChoiceQuestion" elsif question['type'] == "multi-choice" question_type = "MultiChoiceQuestion" elsif question['type'] == "answer-validator" question_type = "EvaluatorQuestion" end if question_type == "SingleChoiceQuestion" || question_type == "MultiChoiceQuestion" description = @doc.at('//alef:description') #question_text @converted_description = PandocRuby.new(description.content, :from => :docbook, :to => :markdown) #puts @converted_description.convert lo = LearningObject.create!( type: question_type, question_text: @converted_description.convert ) @doc.xpath('*//alef:choice').each do |node| if node['correct'] == "true" correct_answer = true else correct_answer = false end @converted_answer = PandocRuby.new(node.content, :from => :docbook, :to => :markdown) #puts @converted_answer.convert #puts "***" Answer.create!( learning_object_id: lo.id, answer_text: @converted_answer.convert, is_correct: correct_answer ) #puts node.content end #puts description.content + ' ; ' + question['type'] elsif question_type == "EvaluatorQuestion" description = @doc.at('//alef:description') #question_text @doc.xpath('*//alef:answer').each do |node| @converted_description = PandocRuby.new(description.content, :from => :docbook, :to => :markdown) #puts @converted_description.convert lo = LearningObject.create!( type: question_type, question_text: @converted_description.convert ) @converted_answer = PandocRuby.new(node.content, :from => :docbook, :to => :markdown) #puts @converted_answer.convert #puts "***" Answer.create!( learning_object_id: lo.id, answer_text: @converted_answer.convert ) #puts node.content end #puts description.content + ' ; ' + question['type'] end end end ## --------------------------------------------------------------------------------- ## CSV IMPORT ## --------------------------------------------------------------------------------- IMPORTED_QUESTION_TYPES = { 'single-choice' => 'SingleChoiceQuestion', 'multi-choice' => 'MultiChoiceQuestion', 'answer-validator' => 'EvaluatorQuestion', 'complement' => 'Complement' } def convert_format(source_string, is_answer = false) is_answer ? source_string.gsub(/<correct>|<\/correct>/,'') : source_string end def import_difficulty(difficulty_string, learning_object) difficulty_levels = { 'trivialne' => LearningObject::DIFFICULTY[:TRIVIAL], 'lahke' => LearningObject::DIFFICULTY[:EASY], 'stredne' => LearningObject::DIFFICULTY[:MEDIUM], 'tazke' => LearningObject::DIFFICULTY[:HARD], 'impossible' => LearningObject::DIFFICULTY[:IMPOSSIBLE] } difficulty = difficulty_levels[difficulty_string.andand.strip] unless difficulty puts "WARNING: '#{learning_object.external_reference}' - '#{learning_object.lo_id}' has unrecognized difficulty string: '#{difficulty_string.inspect}'" difficulty = LearningObject::DIFFICULTY[:UNKNOWN] end learning_object.update(difficulty: difficulty) end def import_concepts(concepts_string,learning_object) if concepts_string.nil? || concepts_string.empty? puts "WARNING: '#{learning_object.external_reference}' - '#{learning_object.lo_id}' has no concepts" concepts_string = Concept::DUMMY_CONCEPT_NAME end concept_names = concepts_string.split(',').map{|x| x.strip} concept_names.each do |concept_name| concept = Concept.find_or_create_by(name: concept_name) do |c| c.course = Course.first c.pseudo = (concept_name == Concept::DUMMY_CONCEPT_NAME) end learning_object.link_concept(concept) end learning_object.concepts.delete(learning_object.concepts.where.not(name: concept_names)) end def import_pictures(picture, pictures_dir, lo) picture = picture.split('/').last begin image = File.read(pictures_dir + '/' + picture) LearningObject.where(id: lo.id).update_all(image: image) rescue Errno::ENOENT => ex puts "IMAGE MISSING: #{picture}" raise end end # CSV structure # 0 1 2 3 4 # ID, Obrazok, Nazov, Kategoria, Do nultej verzie, # 510, resources/q-001pl.png, Hrany v diagrame prípadov použitia, funkcionalne_modely, y, # 5 6 7 8 # Otazka, Koncepty, Kapitola, Subkapitola, # "Akého typu...?", "UML, diagram prípadov použitia", 07 Funkcionálne modely, 07.01 Model a diagram prípadov použitia, # 9 10 11 # Typ otazky, Spravna odpoved, "Moznosti, ak boli k dispozicii", # single-choice, extend;, asociácia;<correct>extend</correct>;uses;dedenie;use;include;, # 12 13 # Obtiaznost (impossible/tazke/stredne/lahke/trivialne), XML # , questions/psi-op-q-006pl.xml def import_choice_questions(file, pictures_dir) CSV.read(file, :headers => true).each do |row| external_reference = row[0] picture = row[1] question_name = row[2] || '' zero_version = row[4] question_text = convert_format(row[5]) concept_names = row[6] question_type = IMPORTED_QUESTION_TYPES[row[9]] answers = row[11] difficulty_text = row[12] # import only tagged questions # next unless zero_version == 'y' next if question_type == 'Complement' lo = LearningObject.find_or_create_by(external_reference: external_reference) do |lo| lo.course = Course.first end lo.update( type: question_type, lo_id: question_name, question_text: question_text ) # TODO import answers when updating existing LO, not only upon first creation # ^NOTE: answer ID should be preserved whenever possible for logged relations if lo.answers.empty? answers.split(';').each do |answer| correct_answer = answer.include? '<correct>' answer_text = convert_format(answer, true) Answer.create!( learning_object_id: lo.id, answer_text: answer_text, is_correct: correct_answer ) end end import_difficulty(difficulty_text, lo) import_concepts(concept_names, lo) import_pictures(picture, pictures_dir, lo) if picture end end # CSV structure: # 0 1 2 3 4 5 6 # ID Otazka, ID odpoved, ID_Sypanie, Do nultej verzie, Vybrať (Y), Nazvova kategoria, Nazov (specificky), # 1072799564, 10, 836, y, Y, diagram, Určovanie typu diagramu, # 7 8 # Koncepty, Obtiaznost (impossible/tazke/stredne/lahke/trivialne), # "UML,štruktúrny diagram,diagram objektov", lahke, # 9 10 # Otazka, Image url, # Aký diagram..., http://alef.fiit.stuba.sk/learning_objects/resources/pic-psi-sg-q-0.png, # 11 # Odpoved, # Object diagram (Objektovy diagram) Patri do UML. def import_qalo_questions(file, pictures_dir) CSV.read(file, :headers => true).each do |row| external_reference = "#{row[0]}:#{row[1]}" zero_version = row[4] # using new selector question_name = row[6] || '' concept_names = row[7] difficulty_text = row[8] question_text = convert_format(row[9]) picture = row[10] answer_text = convert_format(row[11], true) question_type = 'EvaluatorQuestion' # import only tagged questions next unless zero_version.andand.upcase == 'Y' lo = LearningObject.find_or_create_by(external_reference: external_reference) do |lo| lo.course = Course.first end lo.update(type: question_type, lo_id: question_name, question_text: question_text) Answer.find_or_create_by(learning_object_id: lo.id).update(answer_text: answer_text) import_difficulty(difficulty_text, lo) import_concepts(concept_names, lo) import_pictures(picture, pictures_dir, lo) if picture end end # import questions from CSV files # run: # rake alef:data:import_csv["QALO.csv","choices.csv","img_dir"] task :import_csv, [:qalo_csv, :choice_csv, :img_dir] => :environment do |t, args| import_choice_questions(args.choice_csv, args.img_dir) import_qalo_questions(args.qalo_csv, args.img_dir) end end end
true
14db0cf4de75ed69c0da05be9060018fc31d2efb
Ruby
rails/rails
/actioncable/lib/action_cable/channel/broadcasting.rb
UTF-8
1,297
2.71875
3
[ "MIT", "Ruby" ]
permissive
# frozen_string_literal: true require "active_support/core_ext/object/to_param" module ActionCable module Channel module Broadcasting extend ActiveSupport::Concern included do delegate :broadcasting_for, :broadcast_to, to: :class end module ClassMethods # Broadcast a hash to a unique broadcasting for this <tt>model</tt> in this channel. def broadcast_to(model, message) ActionCable.server.broadcast(broadcasting_for(model), message) end # Returns a unique broadcasting identifier for this <tt>model</tt> in this channel: # # CommentsChannel.broadcasting_for("all") # => "comments:all" # # You can pass any object as a target (e.g. Active Record model), and it # would be serialized into a string under the hood. def broadcasting_for(model) serialize_broadcasting([ channel_name, model ]) end def serialize_broadcasting(object) # :nodoc: case when object.is_a?(Array) object.map { |m| serialize_broadcasting(m) }.join(":") when object.respond_to?(:to_gid_param) object.to_gid_param else object.to_param end end end end end end
true
31053a49775f3aad2c0da20b41a7f0aecfc4b37f
Ruby
willfowls/prepcourse
/ruby_books/intro_to_ruby/more_stuff/exercises/5.rb
UTF-8
408
3.359375
3
[]
no_license
# Why does the following code # Give us the error message below the code itself #def execute(block) # block.call # end # # execute { puts "Hello from inside the execute method!" } #block.rb1:in `execute': wrong number of arguments (0 for 1) (ArgumentError) #from test.rb:5:in `<main>' # I believe that it is displaying this error message because we don't have the & character before block on line 4
true
f5d330584893ffbc160d7782d5e27850ae123f3d
Ruby
drunkwater/leetcode
/hard/ruby/c0043_224_basic-calculator/00_leetcode_0043.rb
UTF-8
667
3.75
4
[]
no_license
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #224. Basic Calculator #Implement a basic calculator to evaluate a simple expression string. #The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces . #You may assume that the given expression is always valid. #Some examples: #"1 + 1" = 2 #" 2-1 + 2 " = 3 #"(1+(4+5+2)-3)+(6+8)" = 23 #Note: Do not use the eval built-in library function. ## @param {String} s ## @return {Integer} #def calculate(s) #end # Time Is Money
true
ced9fc160cbb78a8c7184c4ddb60a15704fbe057
Ruby
ishikota/PokerServer
/spec/poker_engine/deck_spec.rb
UTF-8
1,230
2.875
3
[]
no_license
require 'rails_helper' RSpec.describe Deck do let(:deck) { Deck.new } describe "#draw_card" do it "should return a card and remove it from deck" do card = deck.draw_card expect(card.to_s).to eq 'SK' expect(deck.size).to eq 51 end end describe "#draw_cards" do it "should return cards and remove them from deck" do cards = deck.draw_cards(3) expect(cards[2].to_s).to eq 'SJ' expect(deck.size).to eq 49 end end describe "restore" do before { deck.draw_cards(5) } it "should restore 52 cards to deck" do expect { deck.restore }.to change { deck.size }.to 52 end end describe "cheat mode" do let(:cheat_deck) { Deck.new(cheat=true, cheat_cards=cards) } let(:cards) { [Card.new(Card::CLUB, 2), Card.new(Card::SPADE, 3), Card.new(Card::CLUB, 4) ] } it "should draw passed card" do expect(cheat_deck.draw_cards(3)).to eq cards end describe "restore" do it "should restore cheat deck" do cheat_deck.draw_cards(3) expect { cheat_deck.restore }.to change { cheat_deck.size }.to cards.size expect(cheat_deck.draw_cards(3)).to eq cards end end end end
true
4f663f7686353ee298e3f07dd7f893f68f2d1ce0
Ruby
codonnell/railsicorn
/test/services/attacks_coercer_test.rb
UTF-8
1,764
2.71875
3
[]
no_license
require 'test_helper' class AttacksCoercerTest < ActiveSupport::TestCase def generic_attacks { attacks: { :"1" => { timestamp_started: 1000, timestamp_ended: 1050, attacker_id: 12, attacker_name: 'twiddles', attacker_faction: 13, attacker_factionname: 'twiddlers', defender_id: 14, defender_name: 'twoodled', defender_faction: 15, defender_factionname: 'twoodleds', result: 'Mug', respect_gain: 0 }, :"2" => { timestamp_started: 1001, timestamp_ended: 1051, attacker_id: "", attacker_name: nil, attacker_faction: "", attacker_factionname: nil, defender_id: 14, defender_name: 'twoodled', defender_faction: 15, defender_factionname: 'twoodleds', result: 'Hospitalize', respect_gain: 5.32 } } } end def coerced_attacks [ { torn_id: 1, timestamp_started: timestamp(1000), timestamp_ended: timestamp(1050), attacker_id: 12, defender_id: 14, result: 'Mug', respect_gain: 0 }, { torn_id: 2, timestamp_started: timestamp(1001), timestamp_ended: timestamp(1051), attacker_id: nil, defender_id: 14, result: 'Hospitalize', respect_gain: 5.32 } ] end def timestamp(secs) DateTime.parse(Time.at(secs).to_s) end test 'coerces valid attacks properly' do coerced = AttacksCoercer.new(generic_attacks).call assert_equal(Set.new(coerced_attacks), Set.new(coerced)) assert_instance_of(Array, coerced) assert_equal(coerced_attacks.size, coerced.size) end end
true
5cf0fb7269d0681b6f0e38da823b361f93503f36
Ruby
Davidslv/programming-exercises
/wegottickets-scrapper/scrapper.rb
UTF-8
1,632
3.078125
3
[]
no_license
#!/usr/bin/env ruby require 'nokogiri' require 'restclient' require 'json' require 'pry' class Scrapper attr_reader :page_number, :page, :acts, :listing_outers MAX_NUMBER_PAGES = 20 def initialize @page_number = 1 @acts = [] @outers = 10 process_page process_outers end def process_page current_page = "http://www.wegottickets.com/searchresults/page/#{@page_number}/all" @page = Nokogiri::HTML(RestClient.get(current_page)) ticket_listing = @page.css('.TicketListing') @listing_outers = ticket_listing.css('.ListingOuter') end def process_outers p "Processing outers... (#{@page_number}/#{MAX_NUMBER_PAGES})" listing_outers.each do |outer| @outers -= 1 next_page if @outers == 0 next if outer.css('.ListingAct h3').text =~ /comedy/i act = {} act[:name] = outer.css('.ListingAct h3').text act[:href] = outer.css('.ListingAct h3 a')[0]['href'] act[:city] = outer.css('.ListingAct blockquote .venuetown').text act[:venue] = outer.css('.ListingAct blockquote .venuename').text avoids_catched_text(outer) act[:date] = outer.css('.ListingAct blockquote p').text acts << act end end def next_page to_json if @page_number == MAX_NUMBER_PAGES @outers = 10 @page_number += 1 process_page process_outers end def to_json puts @acts.to_json exit 0 end private def avoids_catched_text(outer) 2.times { outer.css('.ListingAct blockquote p span')[0].unlink } outer.css('.ListingAct blockquote p i').unlink end end Scrapper.new.to_json
true
a7dd4bf4c60148a21e4b14a74356fe620b1b7fa6
Ruby
bwl21/vector2d
/lib/vector2d/fitting.rb
UTF-8
1,658
3.34375
3
[ "MIT" ]
permissive
# encoding: utf-8 class Vector2d module Fitting # Scales down the given vector unless it fits inside. # # vector = Vector2d(20, 20) # vector.contain(Vector2d(10, 10)) # => Vector2d(10,10) # vector.contain(Vector2d(40, 20)) # => Vector2d(20,10) # vector.contain(Vector2d(20, 40)) # => Vector2d(10,20) # def contain(other) v, _ = coerce(other) (v.x > x || v.y > y) ? other.fit(self) : other end # Scales the vector to fit inside another vector, retaining the aspect ratio. # # vector = Vector2d(20, 10) # vector.fit(Vector2d(10, 10)) # => Vector2d(10,5) # vector.fit(Vector2d(20, 20)) # => Vector2d(20,10) # vector.fit(Vector2d(40, 40)) # => Vector2d(40,20) # # Note: Either axis will be disregarded if zero or nil. This is a feature, not a bug. # def fit(other) v, _ = coerce(other) scale = v.to_f_vector / self self * ((scale.y == 0 || (scale.x > 0 && scale.x < scale.y)) ? scale.x : scale.y) end alias_method :constrain_both, :fit # Constrain/expand so that one of the coordinates fit within (the square implied by) another vector. # # constraint = Vector2d(5, 5) # Vector2d(20, 10).fit_either(constraint) # => Vector2d(10,5) # Vector2d(10, 20).fit_either(constraint) # => Vector2d(5,10) # def fit_either(other) v, _ = coerce(other) scale = v.to_f_vector / self if (scale.x > 0 && scale.y > 0) scale = (scale.x < scale.y) ? scale.y : scale.x self * scale else fit(v) end end alias_method :constrain_one, :fit_either end end
true
f9cf4c5cd4cc7513931f53d0dc8d9b40cc7c82c9
Ruby
ShahakBH/jazzino-master
/support/deployment/lib/scp.rb
UTF-8
1,777
2.5625
3
[]
no_license
module Yazino class SCP def self.start(hostname, params = {}, &block) ssh = Yazino::SCP.new(hostname, params) if block_given? yield ssh else ssh end end def initialize(hostname, params = {}) @username = ENV['USER'] @port = 22 @exit_on_error = true @hostname = hostname @username = params['username'] if params.has_key?('username') @port = params['port'] if params.has_key?('port') @key = params['key'] if params.has_key?('key') @args = params['args'] if params.has_key?('args') @exit_on_error = params['exit_on_error'] if params.has_key?('exit_on_error') if @key if @key !~ /^\// @key = "#{File.dirname(__FILE__)}/../config/#{@key}" end raise "Cannot find SSH key #{@key}" if !File.exists?(@key) %x(chmod 600 #{@key}) end end def upload_to(destination, filenames) dest_path = "#{@hostname}:#{destination}" dest_path = "#{@username}@#{dest_path}" if !@username.nil? exec_scp("#{filenames.join(' ')} #{dest_path}") end private def exec_scp(command) raise "Cannot execute empty command" if command.nil? || command.length == 0 scp_command = "scp -q -o UserKnownHostsFile=/dev/null -o BatchMode=yes -o StrictHostKeyChecking=no -o LogLevel=ERROR -c arcfour " scp_command = "#{scp_command}-i #{@key} " if !@key.nil? scp_command = "#{scp_command}-P #{@port} " if @port ssh_command = "#{ssh_command}#{@args} " if @args scp_command = "#{scp_command} #{command}" output = %x(#{scp_command} 2>&1) raise "Failed to copy: #{scp_command}: output was #{output}" if $?.exitstatus != 0 && @exit_on_error output end end end
true
9284885730a354f9f0dc907a47dcad3d81ab9a75
Ruby
J-Y/RubyQuiz
/ruby_quiz/quiz117_sols/solutions/Albert Ng/SimFrost2.rb
UTF-8
3,902
3.25
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby -w class SimFrost require 'RMagick' VACUUM=" " #Chris Shea reminded me of constants... VAPOR="+" ICE="*" ICECOLOR='blue' VAPORCOLOR='grey' VACUUMCOLOR='white' attr_reader :grid, :vapor def initialize (width=30,height=24, vapor_percent=30, showvapor=true) @x_size=width/2*2 #this should take care of those odd numbers @y_size=height/2*2 @vapor_percent=vapor_percent @offset=1 @image = Magick::ImageList.new @showvapor=showvapor create_grid end def create_grid @grid=Array.new(@x_size){Array.new(@y_size)} @bitmap = Array.new(@x_size){Array.new(@y_size,0)} @grid.each_with_index do |row, x| row.each_with_index do |square, y| if rand(100) < @vapor_percent @grid[x][y]= VAPOR @bitmap[x][y]=1 if @showvapor else @grid[x][y]= VACUUM end end end @grid[@x_size/2][@y_size/2]=ICE @bitmap[@x_size/2][@y_size/2]=1 end def check_neighborhoods #interesting bits shamelessly stolen from Dave Burt @offset ^= 1 (@offset...@x_size).step(2) do |x0| (@offset...@y_size).step(2) do |y0| x1=(x0+1) % @x_size y1=(y0+1) % @y_size neighborhood=[@grid[x0][y0], @grid[x0][y1], @grid[x1][y0], @grid[x1][y1]] if neighborhood.include?(VAPOR) if neighborhood.include?(ICE) #there's got to be a rubyer way of doing this... if @grid[x0][y0] == VAPOR #top left corner @grid[x0][y0] = ICE @bitmap[x0][y0] = 1 end if @grid[x0][y1] == VAPOR #one right @grid[x0][y1] = ICE @bitmap[x0][y1] end if @grid[x1][y0] == VAPOR #one down @grid[x1][y0] = ICE @bitmap[x1][y0] end if @grid[x1][y1] == VAPOR #right and down @grid[x1][y1] = ICE @bitmap[x1][y1] = 1 end elsif rand(2)==1 @grid[x0][y0], @grid[x0][y1], @grid[x1][y0], @grid[x1][y1] = @grid[x1][y0], @grid[x0][y0], @grid[x1][y1], @grid[x0][y1] if @showvapor @bitmap[x0][y0], @bitmap[x0][y1], @bitmap[x1][y0], @bitmap[x1][y1] = 1, 1, 1, 1 end else #It's the correct sequence, maybe... I think... @grid[x0][y0], @grid[x0][y1], @grid[x1][y0], @grid[x1][y1] = @grid[x0][y1], @grid[x1][y1], @grid[x0][y0], @grid[x1][y0] if @showvapor @bitmap[x0][y0], @bitmap[x0][y1], @bitmap[x1][y0], @bitmap[x1][y1] = 1, 1, 1, 1 end end end end end end def to_s @grid.transpose.collect{|row| row.join}.join("\n") end def generate_gif something = false if @image.empty? @image.new_image(@x_size, @y_size) else @image << @image.last.copy end frame = Magick::Draw.new @grid.each_with_index do | row, x | row.each_with_index do |square, y| if @bitmap[x][y] == 1 if square == ICE frame.fill(ICECOLOR).point(x,y) something = true elsif square == VAPOR frame.fill(VAPORCOLOR).point(x,y) something = true elsif square == VACUUM frame.fill(VACUUMCOLOR).point(x,y) something = true end @bitmap[x][y] =0 end end end frame.draw(@image) if something puts "On to next frame" end def create_animation @image.write("frost_#{Time.now.strftime("%H%M")}.gif") end end s=SimFrost.new(200,200,40) step = 0 puts "Sit back, this may take a while" while s.grid.flatten.include?(SimFrost::VAPOR) #flatten inspired by James Edward Gray puts "Step #{step}: creating frame" s.generate_gif s.check_neighborhoods step += 1 end s.create_animation puts "Done"
true
385e74830774562c897a7b17298ebe94c1ff13a2
Ruby
hiroshima-t1/Nomikai
/vendor/gems/ri_cal-0.8.7/lib/ri_cal/property_value/recurrence_rule/occurrence_incrementer/by_minute_incrementer.rb
UTF-8
813
2.546875
3
[ "MIT" ]
permissive
module RiCal class PropertyValue class RecurrenceRule < PropertyValue #- ©2009 Rick DeNatale, All rights reserved. Refer to the file README.txt for the license # class OccurrenceIncrementer # :nodoc: class ByMinuteIncrementer < ListIncrementer #:nodoc: def self.for_rrule(rrule) conditional_incrementer(rrule, :byminute, MinutelyIncrementer) end def advance_cycle(date_time) date_time.advance(:hours => 1).start_of_hour end def start_of_cycle(date_time) date_time.change(:min => 0) end def end_of_occurrence(date_time) date_time.end_of_minute end def varying_time_attribute :min end end end end end end
true
2541e7b598cb55e06c6aeaf652b578aca1e99e34
Ruby
QiruiSun/Assignment-Ruby-Fundamentals-Part-Two
/exercise7.rb
UTF-8
756
3.703125
4
[]
no_license
students = { :cohort1 => 34, :cohort2 => 42, :cohort3 => 22 } students.each {|key, value| puts "#{key} : #{value} students"} students[:cohort4] = 43 students.each { |key, value| puts "#{key}"} #what happens when you only put |key| in the {} students.each do |key, value| num = value * 1.05 puts "#{key} : #{num}" end students.delete(:cohort2) puts students # students.each do |key, value| # add = [value] # value.inject { |sum, n| sum + n} # end # need to find a way to convert the values in this hash to an new array! total_students = students.values.inject { |sum, n| sum + n } #=>99 |sum| is the accumulator here which equals to the previous sum+n!!! puts total_students students.values.each do |value| sum += value end puts sum
true
34394a71127e962ae5e8c822e26a79d88b75a84f
Ruby
brianburridge/mvc_sample
/team_view.rb
UTF-8
180
2.796875
3
[]
no_license
class TeamView def self.cheer(team) puts "Go #{team.team_name}!" end def self.announce_win(team) puts "The #{team.team_name} from #{team.home_town} wins!" end end
true
fbf27ac086d67bd76b3057fc18ce5656bcc794a6
Ruby
AbbottMichael/backend_mod_1_prework
/final_prep/annotations.rb
UTF-8
4,454
4.5
4
[]
no_license
# Add your annotations, line by line, to the code below using code comments. # Try to focus on using correct technical vocabulary. # Use the # to create a new comment # Build a Bear # declare a new function that takes 5 arguments def build_a_bear(name, age, fur, clothes, special_power) # declares the local variable <greeting> and assigns it to a string value with the function argument <name> interpolated. greeting = "Hey partner! My name is #{name} - will you be my friend?!" # declares the local variable <demographics> and sets it equal to an array with the funtion argument <name> in index position 0, and the function argument <age> in index position 1. demographics = [name, age] # declares the local variable <power_saying> and assigns it a string value with the function argument <special_power> interpolated. power_saying = "Did you know that I can #{special_power}?" # declares the local variable <built_bear> and assigns it to a hash value with six key/value pairs. built_bear = { # <'basic_info'> string key, assigned to the value of local variable <demographics> 'basic_info' => demographics, # <'clothes'> string key, assigned to the value of function argument <clothes> 'clothes' => clothes, # <'exterior'> string key, assigned to the value of function argument <fur> 'exterior' => fur, # <'cost'> string key, assigned to the float value <49.99>. 'cost' => 49.99, # <'saying'> string key, assigned to an array value with local variable <greeting> assigned to index 0, local variable <power_saying> assigned to index 1, and index 3 assigned to the string value "Goodnight my friend!" 'sayings' => [greeting, power_saying, "Goodnight my friend!"], # <'is_cuddly'> string key, assigned to the boolean value <true>. 'is_cuddly' => true, # denotes the end of the <built_bear> hash } # explicit return with the hash value built_bear return built_bear end # calls the <build_a_bear> function and passes values to it's arguments returning: # {"basic_info"=>["Fluffy", 4], # "clothes"=>["pants", "jorts", "tanktop"], # "exterior"=>"brown", # "cost"=>49.99, # "sayings"=> # ["Hey partner! My name is Fluffy - will you be my friend?!", # "Did you know that I can give you nightmares?", # "Goodnight my friend!"], # "is_cuddly"=>true} build_a_bear('Fluffy', 4, 'brown', ['pants', 'jorts', 'tanktop'], 'give you nightmares') # calls the <build_a_bear> function and passes values to it's arguments returning: # {"basic_info"=>["Sleepy", 2], # "clothes"=>["pajamas", "sleeping cap"], # "exterior"=>"purple", # "cost"=>49.99, # "sayings"=> # ["Hey partner! My name is Sleepy - will you be my friend?!", # "Did you know that I can sleeping in?", # "Goodnight my friend!"], # "is_cuddly"=>true} build_a_bear('Sleepy', 2, 'purple', ['pajamas', 'sleeping cap'], 'sleeping in') # FizzBuzz # declare a new function <fizzbuzz> that takes 3 arguments def fizzbuzz(num_1, num_2, range) # for...in loop executes through the range with <1> beginning and the function argument <range> ending. (1..range).each do |i| # if local variable <i> modulo, fuction argument <num_1> === 0 and <i> modulo function argument <num_2> === 0, returns <true> the code beneath executes. if i % num_1 === 0 && i % num_2 === 0 # prints the string 'fizzbuzz' to the terminal puts 'fizzbuzz' # if the if condition returned false, then the conditional statement: <i> modulo <num_1> === 0, is evaluated. If it returns <true> the code beneath executes. elsif i % num_1 === 0 # prints the string 'fizz' to the terminal if the conditional statement above returns <true>. puts 'fizz' # if and eslif above return <false>: the conditional statement: <i> modulo <num_2> === 0, is evaluated. If <true> then the code beneath executes. elsif i % num_2 === 0 # prints the string 'buzz' to the terminal if the conditional statement above returns <true>. puts 'buzz' # if none of the other conditional statements return <true> the code beneath <else> executes. else # prints the local variable <i> to the terminal. puts i # ends the if statement block end # ends the for...in loop end # ends the <fizzbuzz> function end # calls the <fizzbuzz> function and passes three arguments to it fizzbuzz(3, 5, 100) # calls the <fizzbuzz> function and passes three arguments to it fizzbuzz(5, 8, 400)
true
1b7eb0a95c837b455a69dc316d895986335af447
Ruby
fourmojo/siwapp
/app/models/invoice.rb
UTF-8
2,516
2.734375
3
[]
no_license
class Invoice < Common belongs_to :recurring_invoice has_many :payments, dependent: :delete_all accepts_nested_attributes_for :payments, :reject_if => :all_blank, :allow_destroy => true validates :customer_email, format: {with: /\A([\w+\-].?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i, message: "Only valid emails"}, allow_blank: true validates :serie, presence: true validates :number, numericality: { only_integer: true, allow_nil: true } before_save :set_status around_save :ensure_invoice_number, if: :needs_invoice_number CLOSED = 1 OPENED = 2 OVERDUE = 3 STATUS = {closed: CLOSED, opened: OPENED, overdue: OVERDUE} # Public: Get a string representation of this object # # Examples # # serie = Serie.new(name: "Sample Series", value: "SS").to_s # Invoice.new(serie: serie).to_s # # => "SS-(1)" # invoice.number = 10 # invoice.to_s # # => "SS-10" # # Returns a string. def to_s label = draft ? '[draft]' : number? ? number: "(#{serie.next_number})" "#{serie.value}-#{label}" end # Public: Returns the status of the invoice based on certain conditions. # # Returns a symbol. def get_status if draft :draft elsif closed || gross_amount <= paid_amount :closed elsif due_date and due_date > Date.today :opened else :overdue end end # Public: Returns the amount that has not been already paid. # # Returns a double. def unpaid_amount draft ? nil : gross_amount - paid_amount end # Public: Calculate totals for this invoice by iterating items and payments. # # Returns nothing. def set_amounts super self.paid_amount = 0 payments.each do |payment| self.paid_amount += payment.amount end end protected # Protected: Decide whether this invoice needs an invoice number. It's true # when the invoice is not a draft and has no invoice number. # # Returns a boolean. def needs_invoice_number !draft and number.nil? end # Protected: Sets the invoice number to the series next number and updates # the series by incrementing the next_number counter. # # Returns nothing. def ensure_invoice_number self.number = serie.next_number yield serie.update_attribute :next_number, number + 1 end # Protected: Update instance's status digit to reflect its status def set_status if !draft self.status = STATUS[get_status] end end end
true
293fe189344b163b75fb4b1cec404918f42ffd67
Ruby
hackhands/riot-rails
/test/active_record/validates_length_of_test.rb
UTF-8
1,484
2.84375
3
[ "MIT" ]
permissive
require 'teststrap' context "The validates_length_of assertion macro" do setup_test_context setup { topic.asserts("room") { Room.new } } should("fail when minimum length causes an error") do topic.validates_length_of(:name, (4..15)).run(Riot::Situation.new) end.equals([:fail, ":name should be able to be 4 characters", blah, blah]) should("fail when value less than minimum value does not cause an error") do topic.validates_length_of(:name, (6..15)).run(Riot::Situation.new) end.equals([:fail, ":name expected to be more than 5 characters", blah, blah]) should("fail when maximum length causes an error") do topic.validates_length_of(:name, (5..21)).run(Riot::Situation.new) end.equals([:fail, ":name should be able to be 21 characters", blah, blah]) should("fail when value greater than maximum value does not cause an error") do topic.validates_length_of(:name, (5..19)).run(Riot::Situation.new) end.equals([:fail, ":name expected to be less than 20 characters", blah, blah]) should("pass when only a value can only be within the specific range") do topic.validates_length_of(:name, (5..20)).run(Riot::Situation.new) end.equals([:pass, "validates length of :name is within 5..20"]) should("pass even when minimum value is zero") do topic.validates_length_of(:contents, (0..100)).run(Riot::Situation.new) end.equals([:pass, "validates length of :contents is within 0..100"]) end # The validates_length_of assertion macro
true
a616333f23857efa9e91dfdbc4cb94b913deeb47
Ruby
RubyProjectVu/LDB
/LDB_5lab/spec/models/budget_manager_spec.rb
UTF-8
1,879
2.546875
3
[]
no_license
# frozen_string_literal: true require_relative 'custom_matcher' require_relative '../rails_helper' describe BudgetManager do let :bm do described_class.new end it 'retrieves the state' do expect(bm.stater).to be true end it 'returns state after setting budget' do Project.create(name: 'test', budget: 3.5, id: 'testid') bm.stater(11) expect(bm.budgets_setter('testid', 87)).to eq 11 end it 'false when budget is too small' do id = Project.find_by(name: 'Projektas2').id # specific budget covers mutation 'find_by(nil)' expect(bm.can_deduct_more(35_000.11, id)).to be false end it 'false when state is false' do Project.create(name: 'test', manager: 'guy', status: 'Proposed', budget: 3.5, id: 'testid') bm.stater(false) expect(bm.can_deduct_more(3, 'testid')).to be false end it 'true when budget is bigger than deduction' do id = Project.find_by(name: 'Projektas2').id expect(bm.can_deduct_more(3, id)).to be true end it 'covers mutation \'>= -1\'' do id = Project.find_by(name: 'Projektas2').id expect(bm.can_deduct_more(5000.6, id)).to be false end it 'true when budget is equal to deduction' do id = Project.find_by(name: 'Projektas1').id expect(bm.can_deduct_more(35_000.11, id)).to be true end it 'budget is set correctly' do id = Project.find_by(name: 'Projektas2').id bm.budgets_setter(id, 87) expect(Project.find_by(id: id).budget).to eq 87 end it 'false when state is not true' do id = Project.find_by(name: 'Projektas2').id bm.stater(false) expect(bm.budgets_setter(id, 87)).to be false end it 'budget is also not changed' do id = Project.find_by(name: 'Projektas2').id bm.stater(false) bm.budgets_setter(id, 87) expect(Project.find_by(name: 'Projektas2').budget).not_to eq 87 end end
true
ea21b97bf3a598578b1e107c2d7f7232d66a94c1
Ruby
ZuhairS/Algorithms-and-Data-Structures
/Assortment/Count_triplet_sum_less_than_target.rb
UTF-8
423
3.625
4
[]
no_license
def count_triplets(arr, target) count = 0 arr.sort! (0...arr.length - 2).each do |idx| left_idx, right_idx = idx + 1, arr.length - 1 while left_idx < right_idx sum = arr[idx] + arr[left_idx] + arr[right_idx] if sum < target count += (right_idx - left_idx) left_idx += 1 else right_idx -= 1 end end end count end p count_triplets([5, 1, 3, 4, 7], 12)
true