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
ddf43b084e2f69862801f2fac7b50d9677672638
Ruby
eloudon/ruby-instance-variables-lab-online-web-ft-081219
/lib/dog.rb
UTF-8
251
3.921875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# @ symbol = instance variable. Removes the barrier of scope between methods inside a class. class Dog def name=(dog_name) @this_dogs_name = dog_name end def name @this_dogs_name end end lassie = Dog.new lassie.name = "Lassie" puts lassie.name
true
f72168247c23fb2fa873a8cb69c553c44945660e
Ruby
chris-groves/Gilded-Rose-Kata
/ruby/spec/daily_stock_check_spec.rb
UTF-8
3,958
3.09375
3
[ "MIT" ]
permissive
require "daily_stock_check" describe DailyStockCheck do describe "#update_item" do context "when there are no items" do it "returns an empty array" do items = [] expect(described_class.new(items).update_items).to eq [] end end context "when an invalid item is updated" do it "returns an error" do items = "string" expect{ described_class.new(items).update_items}.to raise_error "Items needs to be an array" end end context "Normal items" do it "does not change the name" do items = [Item.new(name:"Apples",sell_in: 0, quality: 0)] described_class.new(items).update_items expect(items[0].name).to eq "Apples" end it "reduces the sell in by 1" do items = [Item.new(name: "Apples", sell_in: 50, quality: 50)] described_class.new(items).update_items expect(items[0].sell_in).to eq 49 end it "reduces the quality in by 1" do items = [Item.new(name: "Apples", sell_in: 50, quality: 50)] described_class.new(items).update_items expect(items[0].sell_in).to eq 49 end it "does not reduce the quality below 0" do items = [Item.new(name: "Apples", sell_in: 10, quality: 0)] described_class.new(items).update_items expect(items[0].quality).to eq 0 end context "when sell by date has passed" do it "reduces the quality of an item by 2" do items = [Item.new(name: "Apples", sell_in: -1, quality: 50)] described_class.new(items).update_items expect(items[0].quality).to eq 48 end end end context "Aged Brie" do it "reduces the sell in by 1" do items = [Item.new(name: "Aged Brie", sell_in: 50, quality: 50)] described_class.new(items).update_items expect(items[0].sell_in).to eq 49 end it "increases the quality" do items = [Item.new(name: "Aged Brie", sell_in: 10, quality: 10)] described_class.new(items).update_items expect(items[0].quality).to eq 11 end it "does not increase the quality above 50" do items = [Item.new(name: "Aged Brie", sell_in: 10, quality: 50)] described_class.new(items).update_items expect(items[0].quality).to eq 50 end end context "Sulfuras, Hand of Ragnaros" do it "does not reduce the sell in" do items = [Item.new(name: "Sulfuras, Hand of Ragnaros", sell_in: 0, quality: 80)] described_class.new(items).update_items expect(items[0].sell_in).to eq 0 end it "does not change the quality" do items = [Item.new(name: "Sulfuras, Hand of Ragnaros", sell_in: 0, quality: 80)] described_class.new(items).update_items expect(items[0].quality).to eq 80 end end context "Backstage Passes" do it "increases the quality" do items = [Item.new(name: "Backstage passes to a TAFKAL80ETC concert", sell_in: 20, quality: 10)] described_class.new(items).update_items expect(items[0].quality).to eq 11 end it "increases the quality by 2 when sell in is between 10 and 6 inclusive" do items = [Item.new(name: "Backstage passes to a TAFKAL80ETC concert", sell_in: 10, quality: 10)] described_class.new(items).update_items expect(items[0].quality).to eq 12 end it "increases the quality by 3 when sell in is 5 or less" do items = [Item.new(name: "Backstage passes to a TAFKAL80ETC concert", sell_in: 5, quality: 10)] described_class.new(items).update_items expect(items[0].quality).to eq 13 end it "decreases the quality to 0 after the event" do items = [Item.new(name:"Backstage passes to a TAFKAL80ETC concert", sell_in: 0, quality: 10)] described_class.new(items).update_items expect(items[0].quality).to eq 0 end end end end
true
7490f98ae66005427c28dd359cfebad98e0fd051
Ruby
chongct/array-practice-1
/spec/pseudocode.rb
UTF-8
2,086
3.984375
4
[]
no_license
class String def dashes # normal cases # - self must be a string () # - all string must be a digit # - put dash respectively 1357 => 1357 # 0246 = 0-2-4-6 # edge # - if it's not a digit, don't add any dash (edge) #split the string into an Array #run an each loop for the Array #if element is last number in array don't add anything #else if even number add a dash behind the respective element # else don't add anything #end the each loop #join back the array into a string # [0,2,5,4,8,6] # [0-, 2, 5,...,6-] this cannot happen # input is a string # turn string into array # for every element in array, check if 0 || % 2 == 0, if true get_index, check check if 0 || % 2 == 0 # true, insert a '-' end end class Array def frequent # normal case # - it has to be an array # - [a, a, a, b] => 'a(3 times)' # - [x, a, a, b] => 'a(2 times)' # error case # - array cannot be empty # edge case # - two frequent items inside arr = [a, a, b, b] = 'there are two most freq items' # arr # uniq_arr # hash # find the highest one in the hash # Find all the unique element in the array #uniq # For each unique element, loop through and do a count # Find the element with the highest count # Return the element and its count end def remove_duplicate # normal case # - must be an array # - check if array items is either number or string # - ['abc', 'a', 'abc'] => ['abc', 'a'] # - ['a', 'b', 'c'] => ['a', 'b', 'c'] # error case # - cannot be empty # - nothing besides number and string for array item # edge case # input is an array # convert all into lowercase # hash this array, everything's value is 0 # run through array, for every element that appears value +1 # start: [a=>0,b=>0,c=>0,a=>0] # end: [a=>1,b=>1,c=>1,a=>2] # if value >1, remove item from array end end def union(arr1, arr2) end def mergeArray(arr1, arr2) end
true
185cae66d446066bbac03cd9ec23d213c509d58b
Ruby
ComaToastUK/pairing_challenges
/week1/array1.rb
UTF-8
89
3.34375
3
[]
no_license
array = [1, 2, 3, 4, 5] def plus_one(array) array.each { |n| n+=1 } return array end
true
10dc1d0cf6b158b51dcb2b5aa56e6273dc3919b2
Ruby
karmajunkie/rollcall
/db/fixtures/schools.rb
UTF-8
908
2.65625
3
[ "MIT" ]
permissive
schools=File.open(File.dirname(__FILE__) + '/schools.csv').read.split("\n").map{|row| row.strip.split(",")} @district = SchoolDistrict.find_or_create_by_name(:name => "Houston ISD") { |district| district.jurisdiction=Jurisdiction.find_or_create_by_name("Harris") } schools.each do |school| if school[0].nil? puts "Could not create a school for #{school[0]}; incomplete information" next end puts "seeding #{school[0]}" unless School.find_by_display_name(school[0]) School.find_or_create_by_display_name(:display_name => school[0]) {|s| s.district=@district # s.name=school[0] # s.region=school[1] # s.school_number = school[3] # s.display_name=school[0].strip.gsub(/(Elementary School$|Montessori$|Elementary$)/, "ES"). # gsub(/High School$/, "HS"). # gsub(/Middle School$/, "MS"). # gsub(/Early Childhood Education Center$/,"ECC").upcase } end
true
f8fd7f4fe33257d8559a10815e08fa709b0a811d
Ruby
hongtron/betting_game
/game
UTF-8
1,602
3.703125
4
[]
no_license
#!/usr/bin/env ruby class Game attr_reader :game_over def initialize(input) @starting_amount = input[0].to_i @baseline_bet = input[1].to_i @number_of_rounds = input[2].to_i @results = input[3].split(" ").map(&:to_i) @state = [] @current_round = 0 @game_over = false Round.baseline_bet = @baseline_bet end def play_round if @state.empty? @state << Round.new(@starting_amount, @baseline_bet, current_result) else previous_round = @state.last @state << previous_round.next_round(current_result) @game_over = broke? || finished? end @current_round += 1 end def current_result @results[@current_round] end def broke? @state.last.money <= 0 end def finished? @current_round >= @number_of_rounds end def output_result if broke? puts "BROKE" else puts @state.last.money end end end class Round class << self attr_accessor :baseline_bet end def initialize(money, bet, baseline_bet, result) @money = money @bet = bet @result = result end def win? @result == 1 end def next_round(next_round_result) Round.new(next_round_starting_money, next_round_bet, next_round_result) end def next_round_starting_money win? ? @money + @bet : @money - @bet end def next_round_bet win? ? [baseline_bet, next_round_starting_money].min : [2 * @bet, next_round_starting_money].min end end input_path = ARGV[0] input = File.readlines(input_path).map(&:chomp) g = Game.new(input) g.play_round until g.game_over g.output_result
true
a3502adaf795a9d33e8a0217da2e486fe975ebf1
Ruby
DuncanYe/note
/ruby_lesson/oop/Q4.rb
UTF-8
2,291
4
4
[]
no_license
class Hero attr_accessor :hp, :name @@heroes = [] def initialize(name, hp, ap, sp) @name = name @hp = hp @ap = ap @sp = sp @alive = true puts "你的英雄 #{@name}強勢登場!!" puts "生命力(HP) : #{@hp}" puts "攻擊力(AP) : #{@ap}" puts "體力(SP) : #{@sp}" puts "" end def is_alive? return @alive end def use_stamina @sp = @sp - 1 end def attack(enemy) if @sp > 0 use_stamina damage = rand(@ap/2..@ap) enemy.hp = enemy.hp - damage puts "#{@name} 普通攻擊! AP 剩下#{@sp}" puts "#{enemy.name} 受到 #{damage} 點傷害" puts "#{enemy.name} 剩下 #{enemy.hp} 點 HP" puts "" if enemy.hp < 1 enemy.die end else @sp = @sp + 1 puts "#{@name} 回復體力,跳過一回合,補了:#{@sp}SP" puts "" end end def die @alive = false puts "#{@name}被打倒了!" end end #====================================== class Monster attr_accessor :hp, :name def initialize(name, hp, ap, sp) @name = name @hp = hp @ap = ap @sp = sp @alive = true puts "遇到怪獸 #{@name} 了!" puts "生命力(HP):#{@hp}" puts "攻擊力(AP):#{@ap}" puts "體力(SP) : #{@sp}" puts "" end def is_alive? return @alive end def use_stamina @sp = @sp - 1 end def attack(enemy) if @sp > 0 use_stamina damage = rand (@ap/2..@ap) enemy.hp = enemy.hp - damage puts "#{@name} 攻擊! AP 剩下#{@sp}" puts "#{enemy.name} 受到 #{damage} 點傷害" puts "#{enemy.name} 剩下 #{enemy.hp} 點 HP" puts "" if enemy.hp < 1 enemy.die end else @sp = @sp + 1 puts "#{@name} 回復體力,跳過一回合,補了:#{@sp}SP" puts "" end end def die @alive = false puts "#{@name}被打倒了!" end end #================================== def fight(bright, dark) while bright.is_alive? && dark.is_alive? bright.attack(dark) if !dark.is_alive? break end dark.attack(bright) end end hero = Hero.new "Tim", 100, 30, 3 monster = Monster.new "Bigfoot", 100, 30, 2 fight(hero, monster)
true
981da95e5d12a78fb172dd039e3b2f8e04b4f06e
Ruby
brundage/packetfu
/lib/packetfu/pcap_packet.rb
UTF-8
1,421
2.890625
3
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
# -*- coding: binary -*- module PacketFu # PcapPacket defines how individual packets are stored in a libpcap-formatted # file. # # ==== Header Definition # # Timestamp :timestamp # Int32 :incl_len # Int32 :orig_len # String :data class PcapPacket < Struct.new(:endian, :timestamp, :incl_len, :orig_len, :data) include StructFu def initialize(args={}) set_endianness(args[:endian] ||= :little) init_fields(args) super(args[:endian], args[:timestamp], args[:incl_len], args[:orig_len], args[:data]) end # Called by initialize to set the initial fields. def init_fields(args={}) args[:timestamp] = Timestamp.new(:endian => args[:endian]).read(args[:timestamp]) args[:incl_len] = args[:incl_len].nil? ? @int32.new(args[:data].to_s.size) : @int32.new(args[:incl_len]) args[:orig_len] = @int32.new(args[:orig_len]) args[:data] = StructFu::String.new.read(args[:data]) end # Returns the object in string form. def to_s self.to_a[1,4].map {|x| x.to_s}.join end # Reads a string to populate the object. def read(str) return unless str force_binary(str) self[:timestamp].read str[0,8] self[:incl_len].read str[8,4] self[:orig_len].read str[12,4] self[:data].read str[16,self[:incl_len].to_i] self end end end
true
9a030e4399ef8231ae54c5a971e924da4a432815
Ruby
brianlamb/TokyoTechX-CS101
/kadai5/ango.rb
UTF-8
560
3.84375
4
[]
no_license
# # ango.rb # # 入力: 文字列 # # 出力: 入力した文字列をシーザー暗号(k 字シフト)で暗号化した文字列 def enc(k, m) code_a = 97 leng = m.length b = Array.new(leng, 0) a = m.unpack("C*") for i in 0..(leng-1) #  ここで a[i] を k シフトした値を b[i] に代入 sa = a[i] - code_a if 0 <= sa && sa <=25 sa = (sa + k) % 26 end b[i] = sa +code_a end c = b.pack("C*") return c end k = 3 hirabun = gets.chomp angobun = enc(k, hirabun) puts(angobun)
true
09b84cea590cd2be07b9fb20703c32e5ec7609bb
Ruby
tacklebox-webhooks/ruby
/lib/tacklebox/components/service.rb
UTF-8
418
2.734375
3
[ "MIT" ]
permissive
require_relative "../apis/service_api" class Service attr_accessor :api def initialize(config) self.api = ServiceApi.new(config) end def list self.api.list_services() end def create(serviceData) self.api.create_service(serviceData) end def get(service_id) self.api.get_service(service_id) end def delete(service_id) self.api.delete_service(service_id) end end
true
773aff857fb151c1c28ad317fe9cb93e2df896b4
Ruby
sonota88/practice-react
/server.rb
UTF-8
1,592
2.921875
3
[]
no_license
require "json" require "sinatra" require "sinatra/reloader" class Items @@items = [ { id: 1, name: "foo", note: "note 1"}, { id: 2, name: "bar", note: "note 2"} ] def self.get id @@items.find{|item| item[:id] == id } end def self.get_all @@items end def self.add item @@items << item end def self.update item i = @@items.index{|it| it[:id] == item[:id] } @@items[i] = item end def self.delete id @@items = @@items.reject{|it| it[:id] == id } end def self.max_id id = @@items[0][:id] @@items.each{|item| id = [item[:id], id].max } id end end def view_html name File.read "views/#{name}.html" end def _api content_type :json result = yield JSON.generate(result) end get "/items" do view_html("index") end get "/items/:id" do view_html("show") end get "/items/new" do view_html("new") end get "/items/:id/edit" do view_html("edit") end post "/items" do item = { id: Items.max_id + 1, name: params[:name], note: params[:note] } Items.add item redirect to("/items") end patch "/items/:id" do id = params[:id].to_i Items.update({ id: id, name: params[:name], note: params[:note] }) redirect to("/items/#{id}") end delete "/items/:id" do id = params[:id].to_i Items.delete(id) redirect to("/items") end get "/api/items" do _api do { items: Items.get_all } end end get "/api/items/:id" do _api do id = params[:id].to_i item = Items.get(id) { item: item } end end
true
f852c9e092bfb989c268824d84f8841ed14ce16a
Ruby
jgstern/ruby-challenges
/always_three_def.rb
UTF-8
147
3.390625
3
[]
no_license
def always_three print "Give me a number:" input = gets puts "final num is #{((((input.to_i + 5) * 2) - 4) / 2) - input.to_i}" end always_three
true
94ec329196fba0ddf7d9859b96e65aa5483d1a9d
Ruby
armaanv/fa15-hw1
/foobar.rb
UTF-8
276
3.21875
3
[]
no_license
class Foobar # Q4 CODE HERE def self.baz(array) sum = 0 array= array.map { |e| Integer(e) +2 } array = array.delete_if { |e| e > 10 } array = array.delete_if { |e| e % 2 != 0} array = array.uniq array.each {|e| sum+= e} return sum end end
true
f840fb4906527aff136ed422680a93df46222cb0
Ruby
ReyRizki/prinsip-bahasa-pemrograman
/ruby-oop/3.rb
UTF-8
390
3.609375
4
[]
no_license
class Product def initialize(name, brand, type, price, stock) @name = name @brand = brand @type = type @price = price @stock = stock end attr_accessor :name, :brand, :type, :price, :stock def to_s puts "#{@name} | #{@brand} | #{@type} | #{@price} | #{@stock}" end end product = Product.new("Mie", "Indomie", "Goreng", "Rp 2.500", 50) puts product.to_s
true
fbb4e4201f0b2641df7d342e3f6a0bdb3af84918
Ruby
kyohei-horikawa/sage_ruby
/Algebra.rb
UTF-8
393
3.140625
3
[]
no_license
require "./SageMath.rb" class Algebra < Sage def add(a, b) @command_list << "#{a}+#{b}" end def factor(f) @command_list << "factor(#{f})" end def expand(f) @command_list << "expand(#{f})" end end a = Algebra.new() input = "(y+1)**2" a.define_symbol("x,y,z") a.expand(input) output1 = a.exec_command p output1 a.factor(output1) output2 = a.exec_command p output2
true
c40f740c39d1ecd08be2878f14fa0bb19708e1e9
Ruby
jameschou93/Rally
/app/views/api/v1/groups/index.json.jbuilder
UTF-8
444
2.515625
3
[]
no_license
json.array! @groups.each do |group| json.id group.id json.name group.name json.bio group.bio json.private group.private? json.mygroup group.mygroup?(current_user) json.categories group.categories.each do |category| json.id category.id json.name category.name end json.members group.users.each do |user| json.id user.id json.first_name user.first_name json.last_name user.last_name json.username user.username json.email user.email end end
true
725b9c8ef6f05309836f94d139e38ea09d0d077a
Ruby
wvulibraries/aspace_reporting
/init.rb
UTF-8
700
2.765625
3
[]
no_license
#!/usr/bin/env ruby # gems require 'mysql2' require 'rubyXL' # require lib folder Dir['./lib/*.rb'].each {|file| require file } # set the root as a constant global root = File.dirname(__FILE__) # grabs the sql file you want to get form the database to put into the excel file sql_file = FileHelper.new("#{root}/sql/accessions_report.sql") sql = sql_file.get_file_contents.to_s # connect to db @db = Database.new sql_data = @db.query(sql).to_a # generate report report = AccessorReport.new report.excel_file = "#{root}/exports/report.xlsx" report.create_workbook report.sql_data = sql_data report.write_to_workbook report.write_headers report.save_workbook puts "Everything worked congrats!"
true
5026efec917405406d05977c9baa30f367171ae1
Ruby
aweshin/PriorityQueue
/priority_queue.rb
UTF-8
688
3.53125
4
[]
no_license
class PriorityQueue def initialize @n = 0 @heap = [] end def maxHeapify x l = 2*x r = 2*x+1 if l <= @n && @heap[l] > @heap[x] largest = l else largest = x end if r <= @n && @heap[r] > @heap[largest] largest = r end if largest != x @heap[x], @heap[largest] = @heap[largest], @heap[x] maxHeapify(largest) end end def extract key = @heap[1] @heap[1] = @heap[@n] @n -= 1 maxHeapify(1) key end def insert key @n += 1 @heap[@n] = key i = @n while i > 1 && @heap[i/2] < @heap[i] @heap[i], @heap[i/2] = @heap[i/2], @heap[i] i /= 2 end end end
true
1f2b40bad7e5213608b5f9463ca2de205fbf179c
Ruby
JonLavi/COFFEE
/models/console.rb
UTF-8
2,221
2.96875
3
[]
no_license
require('pry') require_relative('producer') require_relative('product') require_relative('blend') require_relative('origin') require_relative('roast') require_relative('type') Product.delete_all() Producer.delete_all() blend1 = Blend.new({'name' => 'Arabica'}) blend1.save() blend2 = Blend.new({'name' => 'Robusta'}) blend2.save() origin1 = Origin.new({'name' => 'Kenya'}) origin1.save() origin2 = Origin.new({'name' => 'Columbia'}) origin2.save() roast1 = Roast.new({'name' => 'Dark'}) roast1.save() roast2 = Roast.new({'name' => 'Medium'}) roast2.save() type1 = Type.new({'name' => 'Espresso'}) type1.save() type2 = Type.new({'name' => 'Filter'}) type2.save() producer1 = Producer.new({ 'name' => 'YummyCoffeeCo', 'address' => '123 Fake Street'}) producer1.save() producer2 = Producer.new({ 'name' => 'WiredBrew', 'address' => '456 Fake Street'}) producer2.save() product1 = Product.new({'name' => 'Colombian Supremo', 'producer_id' => producer1.id, 'origin' => origin2.id, 'roast' => roast2.id, 'blend' => blend2.id, 'type' => type2.id, 'weight' => 500, 'unit_cost' => 5, 'sell_price' => 6, 'units_in_stock' => 10, 'optimal_stock' => 20 }) product1.save() product2 = Product.new({'name' => 'Kickass Kenyan', 'producer_id' => producer2.id, 'origin' => origin1.id, 'roast' => roast1.id, 'blend' => blend1.id, 'type' => type1.id, 'weight' => 500, 'unit_cost' => 4, 'sell_price' => 5, 'units_in_stock' => 15, 'optimal_stock' => 30 }) product2.save() ##### Tested Methods: ##### # product1.name = "ColomboCoffee" # product1.blend = "Robusta" # product1.update() # producer1.name = "Hot Stuff Coffee" # producer1.address = "1 Elm Street" # producer1.update() # Producer.all() # Product.all() # StockItem.all() # Producer.find(22) # Product.find(22) # StockItem.find(7) # list_of_products =[product1, product2] # Product.total_stock_buy_value(list_of_products) # Product.total_stock_sell_value(list_of_products) # Product.total_stock_profit(list_of_products) # binding.pry # nil
true
67e859ed97e1c5934c608910c0a2f9b3086ce9e4
Ruby
adifsgaid/leetCodeExo
/allCounstruct.rb
UTF-8
911
3.234375
3
[]
no_license
def all_contruct(target, wordBank) return [[]] if target == '' result = [] wordBank.each do |word| if target.index(word) == 0 suffix = target.slice(word.length) suffixResult = all_contruct(suffix, wordBank) suffixWay = suffixResult.map { |e| [ word, *e] } result.push(*suffixWay) end end return result end all_contruct("purple",["purp","p","ur","le","purpl"]) # la mia risposta non funziona devo trovare il perche [ ["purp", "le"] ["p","ur", "p", "le"] ] def all_contruct( target, wordBank) nextPossibleWords = wordBank.select{|word| target.start_with? word} nextPossibleWords.each_with_object([]) do |word,result| rest = target.delete_prefix word if rest.empty? result << [word] else all_contruct(rest,wordBank).each {|contruct| result << [word] + contruct} end end end all_contruct("purple",["purp","p","ur","le","purpl"])
true
7548118ac0135fb4e3469158258d61bd4ef9916c
Ruby
boogity/ruby
/encrypt.incomplete.rb
UTF-8
1,779
3.921875
4
[]
no_license
#/Cryptologist Bruce Schneier designed the hand cipher "Solitaire" for Neal Stephenson's # book "Cryptonomicon". Created to be the first truly secure hand cipher, # Solitaire requires only a deck of cards for the encryption and decryption of messages. # # While it's true that Solitaire is easily completed by hand given ample time, # using a computer is much quicker and easier. Because of that, Solitaire conversion # routines are available in many languages, though I've not yet run across one in Ruby. # # This week's quiz is to write a Ruby script that does the encryption and decryption # of messages using the Solitaire cipher. class Encrypter def initialize(keystream) @keystream = keystream end def sanitize(s) s = s.upcase s = s.gsub(/[^A-Z]/, "") s = s + "X" * ((5 - s.size % 5) % 5) out = "" (s.size / 5).times {|i| out << s[i*5,5] << " "} return out end def mod(c) return c - 26 if c > 26 return c + 26 if c < 1 return c end def process(s, &combiner) s = sanitize(s) out = "" s.each_byte { |c| if c >= ?A and c <= ?Z key = @keystream.get res = combiner.call(c, key[0]) out << res.chr else out << c.chr end } return out end def encrypt(s) return process(s) {|c, key| 64 + mod(c + key - 128)} end def decrypt(s) return process(s) {|c, key| 64 + mod(c -key)} end end puts "What would you like to do?\n1.) Encrypt\n2.) Decrypt" input = gets.chomp if input == 1 then puts "Type your message for encryption." data = gets.chomp return Encrypter.encrypt(data) end
true
db2ece8bd56d38c6fc3e9db5f806419e99bcecc8
Ruby
ChikaKanu/Week_02-weekend-homework
/specs/rooms_spec.rb
UTF-8
2,177
3.046875
3
[]
no_license
require("minitest/autorun") require('minitest/rg') require_relative("../rooms.rb") require_relative("../bar") require_relative("../guests") require_relative("../songs") require_relative("../drinks") class RoomsTest < MiniTest::Test def setup @unoccupied_rooms = ["room_1", "room_2", "room_3", "room_4", "room_5"] @all_rooms = ["room_1", "room_2", "room_3", "room_4", "room_5"] @rooms = Rooms.new(@all_rooms, 50, 1200, @unoccupied_rooms) @song_1 = Songs.new("The moment", "Instrumental") @song_2 = Songs.new("Beetles", "Pop") @song_3 = Songs.new("Beautiful", "Rock") @bar = Bar.new("red_wine", 15, 40, 1800 ) @guest_1 = Guests.new("Kasel", 64, 650, "10 Buffery Street") @guest_2 = Guests.new("Koggy", 34, 1000, "2 Anan Street") @guest_3 = Guests.new("Ifunanya", 10, 100, "15 Bavelaw Close") end def test_all_free_room_names assert_equal(@unoccupied_rooms, @rooms.room_names) end def test_songs_count assert_equal(0, @rooms.songs_count) end def test_guest_age_ok__returns_true assert_equal(true, @rooms.guest_age_ok?(@guest_1)) end def test_guest_age_ok__returns_false assert_equal(false, @rooms.guest_age_ok?(@guest_3)) end def test_can_add_songs_to_rooms @rooms.add_songs(@song_1) assert_equal(1, @rooms.songs_count) end # def test_can_remove_songs_from_rooms # @rooms.remove_songs(@song_1) # assert_equal(0, @rooms.songs_count) # end # # def test_pay_room_rate # @rooms.pay_room_rate(@guest_1, 50) # assert_equal(600, @guest_1.wallet()) # assert_equal(1850, @bar.till()) # end # # def test_check_in_guest # @rooms.check_in_guest(@guest_1, @room_1) # assert_equal(4, @unoccupied_rooms.length()) # end # # def test_check_out_guest # @rooms.check_out_guest(@guest_1, @room_1) # assert_equal(5, @unoccupied_rooms.length()) # end # # def test_check_in_all_guest # @rooms.check_in_all_guest(@guest_1, @room_1) # assert_equal(4, @unoccupied_rooms.length()) # end # # def test_check_out_all_guest # @rooms.check_out_all_guest(@guest_1, @room_1) # assert_equal(5, @unoccupied_rooms.length()) # end end
true
980891d2d704a04de7d70a18a2d8c3da46003ccf
Ruby
rogergraves/meetingsurvey
/app/presenters/report_presenter.rb
UTF-8
2,864
2.625
3
[]
no_license
class ReportPresenter < BasePresenter presents :meeting_occurrence def yes_or_no_question_report(question) %Q( <ul class="list-group"> <li class="list-group-item"> <b>#{question[:question]}</b><br> <ul class="list-group"> #{question_report(answers_html(question, 'yes'), 'success')} #{question_report(answers_html(question, 'no'), 'danger')} </ul> </li> </ul> ).html_safe end def question_report(content, type) unless content.blank? %Q( <li class="list-group-item list-group-item-#{type}"> #{content} </li> ).html_safe end end def text_question_report(question) _answers = questions_and_answers[question[:question]] _answers_html = '' _answers.each do |_answer| _answers_html << "<p>#{mail_to _answer[:email]}<br>#{_answer[:answer]}</p>" end %Q( <p>#{question[:question]}</p> #{_answers_html} ).html_safe end def answers_html(question, answer) _answers = answers_for(question, answer) _answers_html = '' _answers.each do |_answer| _answers_html << "<p>#{mail_to _answer[:email]} #{" -- #{_answer[:why]}" unless _answer[:why].blank?}</p>" end unless _answers_html.blank? %Q( #{answer.capitalize } #{_answers_html} ).html_safe end end def answers_for(question, answer) questions_and_answers[question[:question]].select do |q| q[:answer] == answer end end # TODO: separate text for singular or plural users def refused_users_html emails = email_list(refused_users.map(&:email)) if refused_users.count == 0 nil else "#{emails} indicated that they were not present for the meeting.".html_safe end end def missed_users_html emails = email_list(missed_users.map(&:email)) if missed_users.count == 0 nil elsif missed_users.count == 1 "#{emails} has not yet responded to the survey invite.".html_safe else "#{emails} have not yet responded to the survey invite.".html_safe end end def summary meeting.summary end def meeting @meeting ||= meeting_occurrence.meeting end def all_participants @all_participants ||= meeting_occurrence.meeting.participants end def refused_users @refused_users ||= meeting_occurrence.refused_users end def missed_users meeting_occurrence.missed_users end def questions_and_answers @questions_and_answers ||= meeting_occurrence.questions_and_answers end def email_list(emails) if emails.count == 0 nil elsif emails.count == 1 "#{mail_to emails.first}".html_safe else result = emails.map { |email| mail_to email } "#{result[0...-1].join(', ')} and #{result.last}".html_safe end end end
true
1fdefc89d920f0ac737f21d14452b6f101b15ebb
Ruby
syu1/CS1632-Software-QA
/Project-3 Billcoin CryptoCoin Transaction Verifier/person.rb
UTF-8
317
3.703125
4
[]
no_license
class Person def initialize(name, coin_amount) @name = name @coin_amount = coin_amount end def get_name @name end def coin_amount @coin_amount end def add(add_amount) @coin_amount += add_amount end def subtract(subtract_amount) @coin_amount -= subtract_amount end end
true
8926e011fa8452c1488d000e1ddc89a619b8ff32
Ruby
revans/geodesy
/lib/geodesy/latitude.rb
UTF-8
195
2.84375
3
[ "MIT" ]
permissive
module Geodesy class Latitude using FloatExtension attr_reader :angle def initialize(lat) @angle = lat end def to_radians angle.to_radians end end end
true
041e7f59ee5983d9fadf15d8adbf39362fc1a208
Ruby
Derbeth/poeta
/poem_files.rb
UTF-8
1,319
2.8125
3
[ "MIT" ]
permissive
# -*- encoding: utf-8 -*- module Poeta class PoemFiles attr_reader :dictionary_file, :grammar_file, :sentences_file, :title_sentences_file attr_reader :dictionary_config_file, :general_config_file attr_writer :io def initialize(language,dictionary=nil) @io = File @language = language @default_dict = "default_#{language}" @dictionary = dictionary || @default_dict end def resolve! @dictionary_file = "#{DICT_DIR}/#@dictionary.dic" @sentences_file = first_existing("#{DICT_DIR}/#@dictionary.cfg", "#{DICT_DIR}/#@default_dict.cfg") @title_sentences_file = first_existing("#{DICT_DIR}/#@dictionary.titles.cfg", "#{DICT_DIR}/#@default_dict.titles.cfg", "titles.cfg") @grammar_file = "#{LANG_DIR}/#@language.aff" @general_config_file = "poetry.yml" @dictionary_config_file = "#{DICT_DIR}/#@dictionary.yml" [@dictionary_file, @sentences_file, @title_sentences_file, @grammar_file].each do |file| raise "#{file} does not exist" unless @io.exist?(file) end end private DICT_DIR = 'dictionaries' LANG_DIR = 'languages' # returns first of the given paths that exists, or the last one if none exists def first_existing(*paths) last_path = nil paths.each do |path| last_path = path break if @io.exist?(path) end last_path end end end
true
7390543e4064d75f319a38b809c1a70797d8e8e8
Ruby
rails/rails
/activejob/test/jobs/retry_job.rb
UTF-8
2,497
2.65625
3
[ "MIT", "Ruby" ]
permissive
# frozen_string_literal: true require_relative "../support/job_buffer" require "active_support/core_ext/integer/inflections" class DefaultsError < StandardError; end class DisabledJitterError < StandardError; end class ZeroJitterError < StandardError; end class FirstRetryableErrorOfTwo < StandardError; end class SecondRetryableErrorOfTwo < StandardError; end class LongWaitError < StandardError; end class ShortWaitTenAttemptsError < StandardError; end class ExponentialWaitTenAttemptsError < StandardError; end class CustomWaitTenAttemptsError < StandardError; end class CustomCatchError < StandardError; end class DiscardableError < StandardError; end class FirstDiscardableErrorOfTwo < StandardError; end class SecondDiscardableErrorOfTwo < StandardError; end class CustomDiscardableError < StandardError; end class UnlimitedRetryError < StandardError; end class RetryJob < ActiveJob::Base retry_on DefaultsError retry_on DisabledJitterError, jitter: nil retry_on ZeroJitterError, jitter: 0.0 retry_on FirstRetryableErrorOfTwo, SecondRetryableErrorOfTwo, attempts: 4 retry_on LongWaitError, wait: 1.hour, attempts: 10 retry_on ShortWaitTenAttemptsError, wait: 1.second, attempts: 10 retry_on ExponentialWaitTenAttemptsError, wait: :exponentially_longer, attempts: 10 retry_on CustomWaitTenAttemptsError, wait: ->(executions) { executions * 2 }, attempts: 10 retry_on(CustomCatchError) { |job, error| JobBuffer.add("Dealt with a job that failed to retry in a custom way after #{job.arguments.second} attempts. Message: #{error.message}") } retry_on(ActiveJob::DeserializationError) { |job, error| JobBuffer.add("Raised #{error.class} for the #{job.executions} time") } retry_on UnlimitedRetryError, attempts: :unlimited discard_on DiscardableError discard_on FirstDiscardableErrorOfTwo, SecondDiscardableErrorOfTwo discard_on(CustomDiscardableError) { |job, error| JobBuffer.add("Dealt with a job that was discarded in a custom way. Message: #{error.message}") } before_enqueue do |job| if job.arguments.include?(:log_scheduled_at) && job.scheduled_at JobBuffer.add("Next execution scheduled at #{job.scheduled_at}") end end def perform(raising, attempts, *) raising = raising.shift if raising.is_a?(Array) if raising && executions < attempts JobBuffer.add("Raised #{raising} for the #{executions.ordinalize} time") raise raising.constantize else JobBuffer.add("Successfully completed job") end end end
true
01c5b0f0335c22489222ec7cf1687e0c29f26c14
Ruby
patrodriguez108/maximum-subarray
/maximum_subarray.rb
UTF-8
306
3.921875
4
[]
no_license
# Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. def max_sub_array(nums) end example_one = [-2, 1, -3, 4, -1, 2, 1, -5, 4] max_sub_array(example_one) # Output: 6 # Explanation: [4,-1,2,1] has the largest sum = 6
true
49580f39ba351681cf3e0a581d2ba285825fdfbc
Ruby
tractorfeed/poligraph-api
/lib/Bill.rb
UTF-8
788
3.140625
3
[]
no_license
require 'pg' # HSW "finder" class. # mostly pseudocode, but probably would work... class Bill # This is a public, 'global' var attr_accessor :hostname # Put whatever you need here to initialize the DB conn. def initialize(hostname="localhost") # localhost is the default if there's no arg @hostname = hostname end # public method on the class def self.find(id=nil) response = Hash.new begin conn = PGconn.open(:dbname => 'test') res = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c') # build your result hash however makes you happy res.getvalue(0,0) # '1' res[0]['b'] # '2' response['big_spender'] = 'frank' rescue # bad things happened response = nil # convention end return response end end
true
0b69c9bd4e4695a004fb4984ec2b2b87a7c1e688
Ruby
pepijn/qantani
/lib/qantani.rb
UTF-8
1,733
2.546875
3
[ "MIT" ]
permissive
require 'httparty' require 'builder' require 'active_support/core_ext/hash' require 'qantani/response' require 'qantani/request' require 'qantani/bank' module Qantani API_ENDPOINT = 'https://www.qantanipayments.com/api/' DEFAULT_CURRENCY = 'EUR' REQUEST_SETTINGS = :merchant_id, :merchant_key SETTINGS = REQUEST_SETTINGS + [:merchant_secret] def self.config(settings) for setting in SETTINGS value = settings[setting.to_sym] raise ConfigError, "config setting '#{setting}' missing" if value.nil? class_variable_set '@@' + setting.to_s, value end end def self.merchant_id @@merchant_id end def self.merchant_key @@merchant_key end def self.merchant_secret @@merchant_secret end def self.banks request = Request.new action: "IDEAL.GETBANKS" request.response.banks.map { |b| Bank.new(b['Id'], b['Name']) } end def self.execute(amount: nil, bank_id: nil, description: nil, return_url: nil) request = Request.new action: "IDEAL.EXECUTE", parameters: { Amount: amount.to_s, Bank: bank_id, Currency: DEFAULT_CURRENCY, Description: description, Return: return_url } request.response end def self.check(transaction_id: nil, transaction_code: nil) request = Request.new action: "TRANSACTIONSTATUS", parameters: { TransactionCode: transaction_code, TransactionID: transaction_id } request.response end # The common base class for all exceptions raised by OmniKassa class QantaniError < StandardError end # Raised if something is wrong with the configuration parameters class ConfigError < QantaniError end end #require 'qantani/response'
true
a71af82932881370ae5e778608d0ba893a406131
Ruby
Andyarran/Animal_Shelter_Project
/models/animal.rb
UTF-8
2,126
3.34375
3
[]
no_license
require_relative( '../db/sql_runner' ) class Animal attr_reader( :id, :name, :admission_date, :type_id, :ready, :sex, :age, :description, :owner_id, :image) def initialize(options) @id = options['id'].to_i if options['id'] @name = options['name'] @admission_date = options['admission_date'] @type_id = options['type_id'].to_i @ready = options['ready'] @sex = options['sex'] @age = options['age'] @description = options['description'] @owner_id = options['owner_id'].to_i @image = options['image'] end def save() sql = " INSERT INTO animals (name, type_id, ready, sex, age, description, owner_id, image) VALUES ('#{@name}', #{@type_id}, '#{@ready}', '#{@sex}', '#{@age}', '#{@description}', #{@owner_id}, '#{@image}') RETURNING id; " animal_details = SqlRunner.run(sql).first @id = animal_details['id'].to_i end def delete() sql = " DELETE FROM animals WHERE id = #{id}; " SqlRunner.run(sql) end def update() sql = " UPDATE animals SET name = '#{@name}', type_id = #{@type_id}, ready = '#{@ready}', sex = '#{@sex}', age = '#{@age}', description = '#{@description}', owner_id = #{@owner_id} WHERE id = #{@id}; " SqlRunner.run(sql) end ########################### <- Class Functions Below -> ################################## def self.delete_all() sql = " DELETE FROM animals; " SqlRunner.run(sql) end def self.all sql = " SELECT * FROM animals; " animals_all = SqlRunner.run(sql) animals = animals_all.map { |animal| Animal.new(animal) } return animals end def self.find(id) sql = "SELECT * FROM animals WHERE id = #{id};" animal = SqlRunner.run(sql).first results = Animal.new(animal) return results end def self.find_by_type(id) sql = "SELECT * FROM animals WHERE type_id = #{id};" puts sql animals = SqlRunner.run(sql) result = animals.map { |animal| Animal.new(animal)} return result end end
true
edc651b7bd1a96179bfa45c9662501c4eb99d5be
Ruby
mirubenstein/say
/say.rb
UTF-8
1,567
3.453125
3
[]
no_license
class Say NUMBERS = { 1_000_000_000 => 'billion', 1_000_000 => 'million', 1000 => 'thousand', 100 => 'hundred', 90 => 'ninety', 80 => 'eighty', 70 => 'seventy', 60 => 'sixty', 50 => 'fifty', 40 => 'forty', 30 => 'thirty', 20 => 'twenty', 19 => 'nineteen', 18 => 'eighteen', 17 => 'seventeen', 16 => 'sixteen', 15 => 'fifteen', 14 => 'fourteen', 13 => 'thirteen', 12 => 'twelve', 11 => 'eleven', 10 => 'ten', 9 => 'nine', 8 => 'eight', 7 => 'seven', 6 => 'six', 5 => 'five', 4 => 'four', 3 => 'three', 2 => 'two', 1 => 'one', 0 => 'zero' }.freeze MIN = 0 MAX = 999_999_999_999 def initialize(number) @number = number @number_string = '' end def in_english raise ArgumentError unless @number.between? MIN, MAX return 'zero' if @number.zero? highest_number_less_than = NUMBERS.keys.find { |n| n <= @number } multiplier = @number / highest_number_less_than number_word highest_number_less_than, multiplier if @number.zero? @number_string.gsub /(\s|-)$/, '' else in_english end end private def number_word(number, multiplier) if multiplier > 0 && number > 99 @number -= number * multiplier @number_string << "#{Say.new(multiplier).in_english} " @number_string << "#{NUMBERS[number]} " else @number -= number @number_string << number_string(number) end end def number_string(number) if number.between? 20, 90 "#{NUMBERS[number]}-" else "#{NUMBERS[number]} " end end end module BookKeeping VERSION = 1 end
true
325f1480884dbc3479d49cf3b9338411b9df167b
Ruby
antoniablair/Story-Generator
/Storygenerator.rb
UTF-8
10,797
3.515625
4
[]
no_license
# Storygenerator: creates a story based on the genre the user chooses (using a madlib format) # Get user's story choice. def choosestory(username) storychoice = gets.chomp.downcase case storychoice when 'cop story', 'cop story', 'cop', 'cop' puts " You have chosen Cop Story." copstory(username) when 'rom com', 'rom-com', 'romance', 'rom', 'romcom' puts " You have chosen Rom-Com." romcom(username) when 'sci fi', 'sci-fi', 'sci', 'science fiction' puts " You have chosen Sci-Fi." scifi(username) else puts "Sorry, I don't understand! Would you like to hear a Rom-Com, Cop Story, or Sci-Fi?" choosestory(username) end end # runs after a story completes def afterStory(username) puts " Would you like to hear another story?" playagainyesorno = gets.chomp.downcase case playagainyesorno when 'yes', 'yes please', 'yup' puts "Great!" puts "Your choices are: Rom-Com, Cop Story, or Sci-Fi." choosestory(username) when 'no', 'nope', 'no way' puts " Okay, goodbye!" else puts "I don't know what you said! " afterStory(username) end end # Individual stories (madlib portion) def romcom(username) puts "Sweet!" puts " Okay, now a few questions for you." puts " Choose a pastry." romcomPastry = gets.chomp puts " Yum. Ok, now name a large city." romcomCity = gets.chomp.capitalize puts " What is your dream job? (i.e. hairstylist!)" romcomProfession1 = gets.chomp puts " On the flip side, what job would be THE worst? (i.e., telemarketer)" romcomProfession2 = gets.chomp puts " Who is your sassiest friend?" romcomFriend = gets.chomp.capitalize puts " Who is your favorite fashion designer?" romcomDesigner = gets.chomp.capitalize puts " Who do you think is a total hottie?" romcomCrush = gets.chomp.capitalize puts " Choose a breed of dog." romcomDog = gets.chomp puts " Name a tropical island." romcomDestination = gets.chomp.capitalize puts " Sweet. Here comes your story. PRESS ENTER TO CONTINUE." continue = gets.chomp puts" -------------- * ROM-COM STORY * ----------------- You're a quirky young #{romcomProfession1} with a great group of friends, a promising career, an adorable #{romcomDog} named Triscuit, and a beautiful apartment that overlooks downtown #{romcomCity}. On the surface, you seem to have it all..." continue = gets.chomp print " but your love life is a total mess!" continue = gets.chomp puts " Your bff, #{romcomFriend}, keeps trying to set you up on blind dates, but you always seem to find a silly excuse not to go." continue = gets.chomp puts " One day, while running late to a conference, you have a chance meeting with #{romcomCrush}... a particularly annoying #{romcomProfession2} who is quite possibly the most arrogant person you've ever met. You find out that this moron's company is next door to yours." continue = gets.chomp puts " You tell #{romcomCrush} that they are a total turd #{romcomPastry} and if they ever speak to you in public again, you will punch them in the face!" continue = gets.chomp puts " What a morning. When you finally get to work, you have a voicemail." continue = gets.chomp puts " You find out that your friend is being sent on location to work a private party for #{romcomDesigner} in #{romcomDestination}!" continue = gets.chomp puts " #{romcomFriend} has recieved a plus-one ticket to the show and kindly invites you to come, too. You deliberate on whether it's worth the price, but since you haven't left #{romcomCity} in God knows how long, you decide you will say yes." continue = gets.chomp puts " The day finally arrives for the trip!" continue = gets.chomp puts " To your shock, on the plane, who do you end up sitting next to but that ridiculous #{romcomProfession2}?! As it turns out, #{romcomCrush}'s sister happens to live in #{romcomDestination} and #{romcomCrush} is heading to the exact same hotel as yours for a family reunion... Can things possibly get any worse?!" continue = gets.chomp puts " A series of hilarious events are bound to ensue on this exotic, tropical paradise... -----------------------------------" continue = gets.chomp afterStory(username) end def scifi(username) puts " Sweet! Okay, now a few questions for you." puts " Who is your favorite philosopher?" scifiPhilosopher = gets.chomp.capitalize puts " Nice. Now, choose a farm animal." scifiAnimal = gets.chomp puts " What is your favorite color?" scifiColor = gets.chomp puts " Choose something you could buy at Radio Shack." scifiElectronic = gets.chomp puts " Name a very large city." scifiCity = gets.chomp.capitalize puts " Okay, choose a gem or precious metal." scifiMetal = gets.chomp.capitalize puts " Now pick a vehicle or transportation device." scifiTransport = gets.chomp.capitalize puts " Sweet. Here comes your story! PRESS ENTER TO CONTINUE." continue = gets.chomp puts "------------- * SCI-FI STORY * -------------- You live in the #{scifiMetal} district in downtown #{scifiCity}, working in production at the #{scifiElectronic} factory. You're a mysterious one, with a #{scifiColor} mohawk and a string of silver piercings scattered across your cheeks. No one knows you, and no one knows where you came from. You scarcely know yourself." continue = gets.chomp puts " Your name is #{username}, but you are not actually #{username}." continue = gets.chomp puts " You're a repository of #{username}'s experiences and emotions. Like a memory drive, but for real memories. A living, breathing backup system." continue = gets.chomp puts " ...A very expensive backup system." continue = gets.chomp puts " You choose to go by the name of #{scifiTransport}. After all, you are a vessel for cargo. A means of delivery from point A to point B. In this case, the delivery is memories." continue = gets.chomp puts "When the day finally comes that #{username}'s mind is injured or aged, that is when you will be called in to transfer your mind to theirs." continue = gets.chomp puts " On that day, you will leave the #{scifiMetal} district forever. #{scifiTransport}'s story will end, but #{username}'s story will continue unimpeded. It is what you were made to do." continue = gets.chomp puts "However, just like #{username}..." continue = gets.chomp print " You were never one for following the rules." continue = gets.chomp puts " You try to test the limits of your shared personality. You stray as far from your implanted memories as possible. You learn to enjoy the foods that #{username} never ate, frequent the areas that #{username} never liked, wear a cautiousness that #{username} never had." continue = gets.chomp puts "You wonder how similar you are, after all this time. It has been two years since your last memory update, after all. Are you still the exact same person? Two years is not enough for a life." continue = gets.chomp puts " You try to uncover the meaning of existence, studying #{scifiPhilosopher} and immersing yourself in philosophy. You wonder if the self is inherent, whether fate is pre-determined, and if we are truly the sum of our experiences." continue = gets.chomp puts " Escape is not an option. You've seen the examples, you know what would occur. And yet, all the signs are pointing to one, unignorable possibility." continue = gets.chomp puts " You must find the original #{username}... and you must convince them to help you. -----------------------------------" continue = gets.chomp afterStory(username) end def copstory(username) puts "Sweet! Okay, now a few questions for you. What is the most terrible city you can imagine?" copstoryLocation = gets.chomp.capitalize! puts " What is your favorite junk food?" copstorySnack = gets.chomp puts " What is your ex's name?" copstoryEx = gets.chomp.capitalize! puts " What is the most terrible vice you can imagine?" copstoryVice = gets.chomp puts " What is your weapon of choice?" copstoryWeapon = gets.chomp.downcase puts " What is the last thing you bought at the store?" copstoryGroceries = gets.chomp.downcase puts " Sweet. Here comes your story! PRESS ENTER TO CONTINUE." continue = gets.chomp puts "------------- * COP STORY * -------------- You always knew this day would come. 'I'm getting too old for this sh*t,' you mutter to yourself. You set down your #{copstorySnack} and look out at the window. 'This city needs you, #{username},' says Tony." continue = gets.chomp puts "'I'm retired now. I mean it,' You say. 'I can't be running around cleaning up every mess that you make." continue = gets.chomp "'It ain't worth it no more,' you continue, turning to look at your former partner. 'I got two kids, I got child support to pay, I'm tryin' to turn my life around. I'm out. It ain't worth it no more.' Tony turned his head in disgust. 'The cop I used to know wouldn't turn their back on a job until it was finished,' he said." continue = gets.chomp puts " 'Yeah?' you say bitterly.'Well the cop you knew no longer exists.' 'You really expect I believe that?' said Tony. 'Look at this city. #{copstoryLocation} is practically burning to the ground. Mobs are running the place... People fighting in the streets... We got a chief of police who only cares about getting his next hit of #{copstoryVice}. We're drowning out here.'" continue = gets.chomp puts " 'You got a lot of nerve coming here,' you say. 'You took away my badge. My #{copstoryWeapon}. My dignity.' 'Don't you turn your back on me!' said Tony. 'This department needs you.' His voice turned soft. '#{copstoryLocation} needs you." continue = gets.chomp puts " I don't think you know what you're asking, Tony,' you say. Tony is quiet. '#{username}, please... for old time's sake.' You turn back around to the window, look down at the streets below you. An old woman walks by pushing a cart full of #{copstoryGroceries}. You sigh." continue = gets.chomp puts" 'Alright,' you say, grimly. 'But I won't do it for you.' You pause, dramatically. 'I'll do it for #{copstoryEx}.' -----------------------------------" continue = gets.chomp afterStory(username) end # This runs when the program starts: puts "* * * * * * * * * * Welcome to Storygenerator! What is your name?" username = gets.chomp.capitalize while username.empty? puts "Wait, what was that? Please enter your name." username = gets.chomp.capitalize end puts " Hi there, #{username}! What kind of story would you like to hear today? Your choices are: Rom-Com, Cop Story, or Sci-Fi." choosestory(username) # initialize choosestory method
true
f8f4712cc900c15c6943847abe241ce6968fee50
Ruby
leonardbarreto/sgapp
/app/helpers/application_helper.rb
UTF-8
789
2.5625
3
[]
no_license
# encoding: utf-8 module ApplicationHelper def paginate_bootstrap(objeto) will_paginate(objeto, renderer: BootstrapPagination::Rails) end def timeFormat(hora) hora.strftime("%H:%M") end def dateFormat(data) data.strftime("%D/%M%/%Y") end #Contabilizar a quantidade de dias desde o último atendimento até o dia atual def diasCorridos(data) (Date.today.to_date-data.to_date).to_i end def total_pacientes Paciente.all.count end end #converter Fixnum (ou boolean) para string class Object def to_bs return 'SIM' if self == 1 return 'NÃO' if self == 0 return 'NÃO INFORMADO' if self.class==NilClass #return 'no' if [FalseClass, NilClass].include?(self.class) #return 'yes' if self.class == TrueClass self end end
true
db79571c5b408532140efa65fb4cfca22f2ba8a7
Ruby
KennethEhmsen/vyos-firewall-generator
/lib/vyos-generate-firewall.rb
UTF-8
5,316
2.546875
3
[]
no_license
require 'vyos-config' require 'titleize' class VyOSFirewallGenerator attr_accessor :input attr_accessor :config def initialize(input=nil) @config = VyOSConfig.new @input = input end def aliases input['aliases'] end def zones input['zones'] end def zone_names zones.keys end # Detect if an address is IPv4 or IPv6 def detect_ipvers(address) if address =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/ :ipv4 elsif address =~ /\h{0,4}::?\h{1,4}/i :ipv6 else nil end end # Return an array of addresses that match either IPv4 or IPv6 def select_ipvers(addresses, ipvers) addresses = [addresses] unless addresses.is_a?(Array) addresses.select {|addr| detect_ipvers(addr) == ipvers} end # Return an array of addresses from 1 or more aliases that match either IPv4 or IPv6 def resolve_alias(addresses, ipvers) addresses = [addresses] unless addresses.is_a?(Array) result = [] addresses.each do |address| if address =~ /^([\w\-]+)$/ if aliases[address] result += select_ipvers(aliases[address], ipvers) else raise "Alias is not defined: #{address}" end else result += select_ipvers(address, ipvers) end end result end def generate_default_action(name, ipvers, default_action) raise "default_action is not set for #{name}" if default_action.nil? name_dec = (ipvers == :ipv6 ? 'ipv6-name' : 'name') config.firewall.send(name_dec, name).default_action = default_action end def generate_global_stateful config.firewall.state_policy.established.action = :accept config.firewall.state_policy.related.action = :accept config.firewall.state_policy.invalid.action = :drop end # Convert ruby object into VyOS port string def port_string(input) if input port = if input.is_a?(Array) input.join(',') elsif input.is_a?(Range) "#{input.min}-#{input.max}" else input.to_s end yield(port) end end def generate_firewall_rules(name, ipvers, rules) return if rules.nil? or rules.empty? name_dec = (ipvers == :ipv6 ? 'ipv6-name' : 'name') rules.each_with_index do |rule, index| source_address = resolve_alias(rule['source-address'], ipvers) destination_address = resolve_alias(rule['destination-address'], ipvers) # Don't output rule, if it doens't apply to this IP version next if rule['source-address'] && source_address.empty? next if rule['destination-address'] && destination_address.empty? config_rule = config.firewall.send(name_dec, name).rule(index + 1) config_rule.description = rule['description'] if rule['description'] if !rule['action'] $stderr.puts "Warning: no action defined for rule" next end config_rule.action = rule['action'] if rule['protocol'] == 'ping' # Only allow ICMP ping requests if ipvers == :ipv4 config_rule.protocol = 'icmp' config_rule.icmp.type_name = 'echo-request' else config_rule.protocol = 'icmpv6' config_rule.icmpv6.type = 'echo-request' end elsif ipvers == :ipv6 && rule['protocol'] == 'icmp' config_rule.protocol = 'icmpv6' elsif rule['protocol'] config_rule.protocol = rule['protocol'] else config_rule.protocol = 'tcp' end config_rule.destination.address = destination_address unless destination_address.empty? port_string(rule['destination-port']) do |port| config_rule.destination.port = port end config_rule.source.address = source_address unless source_address.empty? port_string(rule['source-port']) do |port| config_rule.source.port = port end end end def generate zones.each_pair do |zone_name, zone_data| description = zone_data['description'] || "#{zone_name.to_s.titleize} Zone" config.zone_policy.zone(zone_name).description = description if zone_data['interfaces'].nil? || zone_data['interfaces'].empty? config.zone_policy.zone(zone_name).local_zone else zone_data['interfaces'].each do |interface| config.zone_policy.zone(zone_name).interface = interface end end zone_names.each do |from_zone| next if zone_name == from_zone key = "#{zone_name}-from-#{from_zone}" generate_default_action("#{key}-v4", :ipv4, input['default-actions'][key]) unless input['rules'].nil? generate_firewall_rules("#{key}-v4", :ipv4, input['rules'][key]) end generate_default_action("#{key}-v6", :ipv6, input['default-actions'][key]) unless input['rules'].nil? generate_firewall_rules("#{key}-v6", :ipv6, input['rules'][key]) end config.zone_policy.zone(zone_name).from(from_zone).firewall.name = "#{key}-v4" config.zone_policy.zone(zone_name).from(from_zone).firewall.ipv6_name = "#{key}-v6" end end generate_global_stateful end def commands generate config.commands end def commands_string commands.join("\n")+"\n" end def to_s generate config.to_s end end
true
8fc68639c8cfea9ed0b5a6bd39d1fc6568d15666
Ruby
adamkowalczyk/ruby-the-hard-way
/ex17c.rb
UTF-8
351
3.4375
3
[]
no_license
# david wicke's version. looking into it, I discovered that .write and .read close the file automatically. # so, my version passing a block to close the file was redundant File.open(ARGV[1], 'w').write(File.open(ARGV[0]).read) # interestingly, can't call .closed? to check state, as write and read return a string # p ARGV[0].closed? # p ARGV[1].closed?
true
835494d01b04f37ffc261338634a1eb9a920748e
Ruby
seb-faull/sinatra_to_do_app
/ToDoManager.rb
UTF-8
627
3.265625
3
[]
no_license
class ToDoManager @@todos = ["Buy some milk!", "Feed the cat"] #class variable def self.index @@todos.join(" | ") end def self.show (id) @@todos[id] end def self.create (new_todo) @@todos.push(new_todo) #@@todos << new_todo @@todos.join(" | ") end def self.delete (id) @@todos.delete_at(id) end def self.update (id, new_todo) @@todos[id] = new_todo @@todos.join(" | ") end end #Each resource (ie photos, todo, blog posts etc), needs the 7 RESTful routes. #RESTful routes allows us to do the 4 things of CRUD.
true
29c1c5ce850c306f3609029fc0615f542fe66a7b
Ruby
Hidayat-rivai/ruby_nilclass
/nilclass.rb
UTF-8
474
3.5
4
[]
no_license
def cari(nilai, daftar) hasil = nil daftar.each do |elemen| if elemen == nilai hasil = daftar.index(elemen) end end return hasil end if $0 == __FILE__ array = [100,200,300,400,500] index1 = cari(300,array) if index1 puts "300 ditemukan pada index ke-#{index1}" else puts "300 tidak ditemukan dalam array" end index2 = cari(99,array) if index2 puts "99 ditemukan pada index ke-#{index2}" else puts "99 tidak ditemukan dalam array" end end
true
90b9a05f678e0f71f4aebda558b58811fdb08ba1
Ruby
kna9/test
/Test/app/models/result_level2.rb
UTF-8
1,249
2.90625
3
[]
no_license
class ResultLevel2 < ResultClass attr_accessor :orders def initialize(data_struc) @orders = [] data_documents = data_struc.documents data_orders = data_struc.orders promotions = data_struc.promotions data_orders.each do |data_order| document = find_item_by_id(data_order.document_id, data_documents) processed_price = apply_promotion(data_order.promotion_id, promotions, document.price) @orders << { id: data_order.id, price: processed_price } end end private def apply_promotion(promotion_id, promotions, price) return price unless promotion_id promotion = find_item_by_id(promotion_id, promotions) new_price = is_percentage?(promotion) ? process_percentage_promotion(price, promotion) : process_fixed_promotion(price, promotion) end def is_percentage?(promotion) promotion.reduction != 0 if promotion && promotion.reduction end def process_percentage_promotion(price, promotion) new_price_or_zero(price - (price * promotion.reduction / 100)) end def process_fixed_promotion(price, promotion) new_price_or_zero(price - promotion.reduction_fixe) end def new_price_or_zero(new_price) new_price > 0 ? new_price : 0 end end
true
5960de1ad2c418bb3043ba734ae9c0de99df2028
Ruby
marciandmnd/rpncalculator
/test/unit/rpn_calculator/test_rpn_calculator.rb
UTF-8
1,314
2.921875
3
[ "MIT" ]
permissive
require_relative "#{LIB_PATH}/rpn_calculator/rpn_calculator" require 'minitest/autorun' class TestRPNCalculator < Minitest::Test def setup @rpn_calculator = RPNCalculator.new end def test_stack # initial stack stack = @rpn_calculator.stack assert_equal([], stack) # stack with operands expected = [1.0, 2.0, 3.0] @rpn_calculator.evaluate_expression('1 2 3') stack = @rpn_calculator.stack assert_equal(expected, stack) end def test_result # initial result result = @rpn_calculator.result assert_equal(0, result) # computed result @rpn_calculator.evaluate_expression('1 2 3 + -') result = @rpn_calculator.result assert_equal(-4, result) end def test_evaluate_expression # valid expression expression = '15 7 1 1 + - / 3 * 2 1 1 + + -' result = @rpn_calculator.evaluate_expression(expression) assert_equal(5, result) @rpn_calculator.clear_stack # invalid expression expression = '15 7 1 1 d + - / 3 * 2 1 1 + + - x' assert_raises InvalidExpressionError do @rpn_calculator.evaluate_expression(expression) end # operation not permitted @rpn_calculator.clear_stack assert_raises OperationNotPermittedError do @rpn_calculator.evaluate_expression('1 + +') end end end
true
d0232d2f1dd03c4ce2821c342c8d6e1e1d24bb33
Ruby
armi1401/Udemy-The-Complete-Beginners-Guide-to-Ruby
/grades.rb
UTF-8
340
3.5
4
[]
no_license
student_standing = {} @student_count = 0 until @student_count > 2 puts "Enter name of student: " student_name = gets.chomp puts "Enter grade for the student: " grade = gets.chomp.to_i student_standing[student_name] = grade @student_count += 1 end puts "" puts student_standing.sort_by {|student, grade| grade}
true
96fb5c718770a28f0649e461344c1a8cd8e81317
Ruby
zangzing/zz-chef-repo
/cookbooks/deploy-manager/libraries/photos_config.rb
UTF-8
3,865
2.703125
3
[]
no_license
# do custom environment setup for photos # determine relationship of machines and # store back into zz node, once configured # we output the zz node data as json which # can be used by the app to pull in custom # configuration - this data will hang under # zz{:photos_config] # class Chef::Recipe::PhotosConfig # figure out any custom data we # want to set up on the node def self.init(node) @@node = node zz_env = Chef::Recipe::ZZDeploy.env puts zz_env # see if we should host redis node[:zz][:app_config] = {} node[:zz][:app_config][:redis_host] = calc_redis_host node[:zz][:app_config][:redis_servers] = calc_redis_all node[:zz][:app_config][:redis_slaves] = calc_redis_slaves node[:zz][:app_config][:we_host_redis] = calc_we_host_redis node[:zz][:app_config][:we_host_redis_slave] = calc_we_host_redis_slave node[:zz][:app_config][:resque_cpus] = calc_resque_cpus node[:zz][:app_config][:we_host_resque_cpu] = calc_we_host_resque_cpu node[:zz][:app_config][:all_servers] = calc_all_servers node[:zz][:app_config][:util_servers] = calc_util_servers node[:zz][:app_config][:app_servers] = calc_app_servers node[:zz][:app_config][:we_host_app_server] = calc_we_host_app_server node[:zz][:app_config][:resque_workers] = calc_resque_workers node[:zz][:app_config][:we_host_resque_worker] = calc_we_host_resque_worker node[:zz][:app_config][:resque_scheduler] = calc_resque_scheduler node[:zz][:app_config][:we_host_resque_scheduler] = calc_we_host_resque_scheduler node[:zz][:app_config][:resque_worker_count] = zz_env.worker_count node[:zz][:app_config][:resque_cpu_worker_count] = zz_env.cpu_worker_count node[:zz][:app_config][:eventmachine_worker_count] = zz_env.eventmachine_worker_count end def self.node @@node end def self.zz node[:zz] end def self.config zz[:app_config] end def self.instances zz[:instances] end # match all roles given in the roles array of strings def self.find_matching(roles) hosts = [] instances.each_value do |instance| if roles.include?(instance[:role]) host = instance[:local_hostname] hosts << host end end hosts end # returns the first match as a single string def self.find_one_match(roles) hosts = find_matching(roles) hosts.length == 0 ? "" : hosts[0] end # determine which host runs redis def self.calc_redis_host find_one_match(['db','solo', 'local']) end # master and slaves def self.calc_redis_all find_matching(['db','db_slave','solo','local']) end def self.calc_redis_slaves find_matching(['db_slave']) end def self.calc_we_host_redis config[:redis_host] == zz[:local_hostname] end def self.calc_we_host_redis_slave config[:redis_slaves].include?(zz[:local_hostname]) end def self.calc_resque_cpus find_matching(['util','solo', 'local']) end def self.calc_we_host_resque_cpu config[:resque_cpus].include?(zz[:local_hostname]) end def self.calc_all_servers hosts = [] instances.each_value do |instance| host = instance[:local_hostname] hosts << host end hosts end def self.calc_util_servers find_matching(['util']) end def self.calc_app_servers find_matching(['app','app_master','solo', 'local']) end def self.calc_we_host_app_server config[:app_servers].include?(zz[:local_hostname]) end def self.calc_resque_workers find_matching(['app','app_master','solo', 'local']) end def self.calc_we_host_resque_worker config[:resque_workers].include?(zz[:local_hostname]) end def self.calc_resque_scheduler find_one_match(['app_master','solo', 'local']) end def self.calc_we_host_resque_scheduler config[:resque_scheduler] == zz[:local_hostname] end end
true
df104d0ff55a537e31ef90f7eabcae28225bb897
Ruby
gabrielecirulli/supernova
/lib/supernova/remote/fake/operating_system.rb
UTF-8
1,837
2.875
3
[ "MIT" ]
permissive
module Supernova module Remote module Fake # Manage operating system tasks like instlaling packages. # # @abstract Implement the methods in another remote to create # a working operating system module. module OperatingSystem # Creates a user with the given name and options. # # @abstract # @note Does nothing. # @param name [String, Symbol] the name of the user. # @param options [Hash] the options for the user. # @option options [Boolean] :system whether or not the user is # a system user. Defaults to +false+. # @option options [Boolean] :nologin whether or not the user # is able to log in. Defaults to +false+. # @option options [String] :password the user's password. # Defaults to nil. # @return [Boolean] whether or not the user creation was # successful. def create_user(name, options = {}) true end # Installs packages for the right operating system. # # @abstract # @note Does nothing. # @param packages [Hash{Symbol => Array<String>}] symbol is # the name of the OS, the array is the packages to install # for that OS. # @option packages [Array<String>] :ubuntu the packages to # install for debian-based OSs (Ubuntu, Debian, Mint). # @option packages [Array<String>] :red_hat the packages to # install for red hat-based OSs (RHEL, Fedora, CentOS). # @option packages [Array<String>] :arch the packages to # install for Arch. # @return [Boolean] whether or not package installation was # successful. def install_packages(packages) true end end end end end
true
7d6d5bf18bf5ed44c52976cd067dc82f5b1eb621
Ruby
jvanassche/davieswidgets
/app/models/order.rb
UTF-8
1,757
2.59375
3
[]
no_license
class Order < ActiveRecord::Base attr_accessible :CustomerID, :EmployeeID, :OrderDate, :PurchaseOrderNumber, :ShipDate, :ShippingMethodID, :SalesTaxRate has_many :order_details has_many :payments belongs_to :customer, :foreign_key => 'CustomerID' belongs_to :employee, :foreign_key => 'EmployeeID' belongs_to :shipping_method, :foreign_key => 'ShippingMethodID' validates_associated :customer, :employee validates :OrderDate, :SalesTaxRate, :presence => true validates :SalesTaxRate, :numericality => true validate :customer_id_exists def customer_id_exists if Customer.find_by_id(self.CustomerID).nil? errors.add(:base, "Invalid Customer Specified.") end end validate :employee_id_exists def employee_id_exists if Employee.find_by_id(self.EmployeeID).nil? errors.add(:base, "Invalid Employee Specified") end end validate :shipping_id_exists def shipping_id_exists if ShippingMethod.find_by_id(self.ShippingMethodID).nil? && self.ShippingMethodID != nil errors.add(:base, "Invalid Order Number") end end def order_total total = 0 OrderDetail.where("OrderID = ?", self.id).each do |i| total += i.FinalPrice end return total end def order_total_with_tax total = self.order_total + (self.order_total * (self.SalesTaxRate / 100)) return total end def payment_total payment_total = 0 Payment.where("OrderID = ?", self.id).each do |i| payment_total += i.PaymentAmount end return payment_total end def amount_owed return self.order_total_with_tax - self.payment_total end end
true
c0a4fb5ebbd42d00f51d1da92b77d02ef22bdb34
Ruby
wildfiler/mysqldump-processor
/lib/table_definition.rb
UTF-8
331
2.828125
3
[]
no_license
class TableDefinition attr_reader :name, :fields def initialize(name, fields) @name = name @fields = fields end def [](field) field_index(field) end private def field_index(field) fields_indexes[field.to_s] end def fields_indexes @fields_indexes ||= fields.each.with_index.to_h end end
true
775728069784fb425ec8577bc620b550cc90e80b
Ruby
lbvf50mobile/til
/20230626_Monday/20230626.rb
UTF-8
1,164
3.34375
3
[]
no_license
# Leetcode: 2462. Total Cost to Hire K Workers. # https://leetcode.com/problems/total-cost-to-hire-k-workers/ # = = = = = = = = = = = = = = # Thanks God, Jesus Christ! # = = = = = = = = = = = = = = # 2023.06.26 Daily Challenge. # @param {Integer[]} costs # @param {Integer} k # @param {Integer} candidates # @return {Integer} # TLE. def total_cost(costs, k, candidates) # Hint from: # https://leetcode.com/problems/total-cost-to-hire-k-workers/solution/ return costs.sum if k == costs.size return costs.sort[0...k].sum if 2*candidates >= costs.size ans = 0 i = candidates j = costs.size - 1 - candidates a = MinHeap.new(costs[0...candidates]) b = MinHeap.new(costs[-candidates..-1]) k.times do if i > j if a.empty? ans += b.pop elsif b.empty? ans += a.pop elsif a.min <= b.min ans += a.pop elsif b.min < a.min ans += b.pop else raise "Not enought space to fill k elements." end next end if a.min <= b.min ans += a.pop a.push(costs[i]) i += 1 else ans += b.pop b.push(costs[j]) j -= 1 end end return ans end
true
d8b84a0fbf720832e23ee309f0c167ea7db7bac0
Ruby
russellvaughan/russellator
/lib/qualifier.rb
UTF-8
3,652
2.5625
3
[]
no_license
require './lib/driver' class Qualifier attr_reader :qualification USER_SYSTEM = %w(sign\ in log\ in LOGIN log_in Login sign\ up register Sign\ In Sign\ Up Log\ in Sign\ in Log\ In signup) def initialize(website) @website = website @qualification = {} end def qualify @user_sites = Driver.new(@website).find_sites num = 0 p @user_sites while @user_sites == [] && num < 10 p "#{num += 1}" @user_sites = Driver.new(@website).find_sites p @user_sites end if num == 10 && @user_sites == [] @qualification['site']='no sites present' else qualify_user_sites end end def qualify_user_sites @user_sites.length.times do |num| @site = instance_variable_set("@site_#{num}", Hash.new) begin response = HTTParty.get(@user_sites[num]) rescue SocketError, Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Errno::ECONNREFUSED, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError, Errno::ETIMEDOUT, URI::InvalidURIError, OpenSSL::SSL::SSLError => error @site['url']=@user_sites[num] puts "Site does not load: #{error}" @site['site_status']=error @qualification["site_#{num}"]= @site puts @qualification end puts @user_sites[num] if response @site['url']=@user_sites[num] @site['site_status']=response.message qualify_page(@user_sites[num]) if response.headers['content-type'].include?('html') @qualification["site_#{@num}"]= @site puts @qualification end end @qualification end def qualify_page(website) @usersystem = false @goodfit = nil @badfit = nil page = HTTParty.get(website) @page = Nokogiri::HTML(page) login built_with analytics_scripts fit end def header @page.xpath('//head') end def body @page.xpath('//body') end def html @page.xpath('//html') end def login USER_SYSTEM.each do |x| x = (@page.search "[text()*='"+x+"']") if x.to_s.strip.length == 0 else @usersystem = x @goodfit = true end end if @usersystem @site['user_system']=true else @site['user_system']=false end end def analytics_scripts @analytics = [] string = html.to_s @analytics.push('GoSquared') if string.include?('_gs') @analytics.push('Segment') if string.include?('analytics.track' || 'analytics.identify') @analytics.push('Google Analytics') if string.include?('ga') @analytics.push('Google Tag Manager') if string.include?('gtm.start') @site['analytics'] = @analytics end def chat_scripts string = html.to_s print "Intercom is on this page\n" if string.include?('intercomSettings') @site['chat_scripts']='intercom' if string.include?('intercomSettings') end def built_with string = header.to_s.downcase if @usersystem && string.include?('wp-content') @site['built_with']='Wordpress' elsif string.include?('wp-content') @site['built_with']='Wordpress' @badfit = true end if string.include?('wix') @site['built_with']='Wix' @badfit = true end if string.include?('squarespace') @site['built_with']='SquareSpace' @badfit = true end if string.include?('rapidweaver') @site['built_with']='Rapidweaver' @badfit = true end if string.include?('tumblr') @site['built_with']='tumblr' @badfit = true end end def fit if @site['user_system']==true && @site['built_with'].nil? @site['fit']='People, Analytics and Chat' elsif @site['user_system']== true && @site['built_with'] == 'Wordpress' @site['fit']='People, Analytics and Chat' else @site['fit']='Analytics & Chat only' end end end
true
43f0bcf641505256c7e5f908f8e6ecd7c58e8a3d
Ruby
hasumin71/rensyu
/drill_20.rb
UTF-8
585
3.953125
4
[]
no_license
#以下のハッシュから値だけを取り出し、配列にしてください、ただ、hashクラスのvaluesメソッドは使用しないこと =begin values = [] attr.each do |key,value| #ハッシュattrのkeyとvalueを回して #なぜかvalueだけ回して、空の配列に回しても二次元配列になってしまう。なぜ? values << value #取り出したvalueをからの配列 end p values #pは配列のまま返す =end attr = {name: "田中", age: 27, height: 180, weight: 75} values = [] attr.each do |key, value| values << value end p values
true
dc4ac769bd1ff27fee124c5fdeaa14cc5a51370d
Ruby
ThundaHorse/ruby_practice_problems
/abbreviate.rb
UTF-8
587
4.59375
5
[]
no_license
# Write a function `abbreviate(sentence)` that takes in a sentence string and returns a new sentence where words longer than 4 characters have their vowels removed. Assume the sentence has all lowercase characters. # Feel free to use the array below in your solution: # You may need a helper function vowels = ['a', 'e', 'i', 'o', 'u'] def abbreviate(string) end # Examples: p abbreviate('bootcamp is fun') == 'btcmp is fun' p abbreviate('programming is fantastic') == 'prgrmmng is fntstc' p abbreviate('hello world') == 'hll wrld' p abbreviate('how are you') == 'how are you'
true
d92343b16882617e69a097169ecf6e17f9d4a27a
Ruby
ErikMelton/Full-Fill
/app/helpers/dashboard_helper.rb
UTF-8
1,931
2.640625
3
[]
no_license
module DashboardHelper def calcAllEvents @events = Event.where(person_id: @person.id) @person_grid = initialize_grid(@events, order: 'events.activity_when', order_direction: 'desc') @physical = nil @expressive = nil @creative = nil @abstract = nil @social = nil @physScore = 0 @expresScore = 0 @creatScore = 0 @abstractScore = 0 @socialScore = 0 @numOfActivityColumns = 4 calc_age_range input_events calc_scores getTopThreeEvents end def getTopThreeEvents @sortedEvents = @events.sort_by { |obj| obj.activity_hours }.reverse @topEvent = @sortedEvents[0]; @secondEvent = @sortedEvents[1]; end def input_events ageModeArray = [] @events.each do |event| ageModeArray.push(event.activity_when) end end def calc_age_range @ageArr = [] @birthYear = Date.strptime(@person.birth_date, "%m/%d/%Y").year.to_i @currentYear = Date.today.year.to_i @difference = @currentYear - @birthYear for i in 0..@difference do @ageArr[i] = i end end def calc_scores @events.each do |event| activity_spec = Activity.where(activity_spec_id: event.activity_id).first trait_spec = Trait.where(trait_spec_id: activity_spec.trait_id).first facet_spec = Facet.where(id: trait_spec.facet_id).first if(facet_spec.facettype == "physical") @physScore = @physScore + event.activity_hours end if(facet_spec.facettype == "expressive") @expresScore = @expresScore + event.activity_hours end if(facet_spec.facettype == "creative") @creatScore = @creatScore + event.activity_hours end if(facet_spec.facettype == "abstract") @abstractScore = @abstractScore + event.activity_hours end if(facet_spec.facettype == "social") @socialScore = @socialScore + event.activity_hours end end end end
true
6886398f98c981edb785a862b8aea8a706731b45
Ruby
jaxdid/rps-challenge
/spec/combat_spec.rb
UTF-8
1,272
2.53125
3
[]
no_license
require 'Combat' describe Combat do subject(:match) { described_class.new } it 'resolves Rock vs Rock' do expect(match.resolve('rock', 'rock')).to eq 'Rock ties with rock!' end it 'resolves Rock vs Paper' do expect(match.resolve('rock', 'paper')).to eq 'Rock loses to paper!' end it 'resolves Rock vs Scissors' do expect(match.resolve('rock', 'scissors')).to eq 'Rock beats scissors!' end it 'resolves Paper vs Rock' do expect(match.resolve('paper', 'rock')).to eq 'Paper beats rock!' end it 'resolves Paper vs Paper' do expect(match.resolve('paper', 'paper')).to eq 'Paper ties with paper!' end it 'resolves Paper vs Scissors' do expect(match.resolve('paper', 'scissors')).to eq 'Paper loses to scissors!' end it 'resolves Scissors vs Rock' do expect(match.resolve('scissors', 'rock')).to eq 'Scissors loses to rock!' end it 'resolves Scissors vs Paper' do expect(match.resolve('scissors', 'paper')).to eq 'Scissors beats paper!' end it 'resolves Scissors vs Scissors' do expect(match.resolve('scissors', 'scissors')).to eq 'Scissors ties with scissors!' end it 'stores the winning weapon' do match.resolve('rock', 'paper') expect(match.winning_weapon).to eq 'paper' end end
true
df982a6d45092b60062216ed71dfb33173e379e3
Ruby
makotz/CodeCore-Exercises
/4week/7JuneDay17/handytools2.0/app/models/question.rb
UTF-8
1,596
2.6875
3
[]
no_license
class Question < ActiveRecord::Base validates(:title, {presence: {message: "must be present!"}, uniqueness: true }) #by having the option: uniqueness: {scope: :title} it ensures that the hbody must be unique in combination with the title validates :body, presence: true, length: {minimum: 7}, uniqueness: {scope: :title} validates :view_count, numericality: {greater_than_or_equal_to: 0} validate :no_title_in_body # VALID_EMAIL_REGEX = /\A([\w+\-]\.?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i # validates :email, format: VALID_EMAIL_REGEX validate :no_monkey after_initialize :set_defaults before_save :cap_title, :squeeze scope :recent, lambda {|x| where("created_at > ?", 3.day.ago).limit(count) } scope :search, lambda {|word| where("title ILIKE ? OR body ILIKE ?", "%#{word}%", "%#{word}%")} def self.search(keyword) where("title ILIKE :word OR body ILIKE :word", {word: "%#{keyword}%"}) end def self.recent(count) where("created_at > ?", 3.day.ago).limit(count) end scope :created_after -> {|date| where "created_at > ?", date} private def squeeze self.title = title.squeeze(" ") self.body = body.squeeze(" ") end def cap_title self.title = title.capitalize end def set_defaults puts title self.view_count ||= 0 end def no_title_in_body if body.include?(title) errors.add(:body, "No title in body!") end end def no_monkey if title && title.downcase.include?("monkey") errors.add(:title, "No monkey please!") end end end
true
75f6924844d01ac96c02d4a714119bf28495a4be
Ruby
conversation/lita-datadog
/lib/lita/datadog.rb
UTF-8
1,505
2.6875
3
[ "MIT" ]
permissive
require "lita" require "lita/datadog_repository" module Lita module Handlers # Listens for `datadog_submit` events on the lita event bus, and sends the details # to datadog. Each event should have four attributes: # # * name (string) # * type (symbol) # * host (string) # * value (number) # # These directly map to the attributes expected by the datadog-metrics gem - check # its documentation for futher details. # class Datadog < Handler config :api_key config :app_key on :datadog_submit, :handle_datadog_submit def handle_datadog_submit(data) name = data.fetch(:name, nil) type = data.fetch(:type, nil) host = data.fetch(:host, nil) value = data.fetch(:value, nil) raise ArgumentError, "datadog_submit event must include key :name" unless name raise ArgumentError, "datadog_submit event must include key :type" unless type raise ArgumentError, "datadog_submit event must include key :host" unless host raise ArgumentError, "datadog_submit event must include key :value" unless value puts "datadog event. name=#{name} type=#{type} host=#{host} value=#{value}" datadog_repository.submit(name.to_s, value.to_s, type: type.to_s, host: host.to_s) end def datadog_repository @datadog_repository ||= DatadogRepository.new(config.api_key, config.app_key) end end Lita.register_handler(Datadog) end end
true
0b305eb4b875b5d08741e97fc62e18d7a4591bef
Ruby
ThriveTRM/class_profiler
/lib/class_profiler/benchmark.rb
UTF-8
1,652
3.140625
3
[ "MIT" ]
permissive
require "class_profiler" class ClassProfiler::Benchmark include Singleton def initialize(options = {}) @options = options @sum_hash = {} @active_labels = [] end def start(label, &block) append_active_label(label) value = nil time = ::Benchmark.measure { value = block.call }.real sum_hash[label] = {num: 0, sum: 0} if sum_hash[label].nil? sum_hash[label][:num] += 1 sum_hash[label][:sum] += time.round(5) remove_active_label(label) return value end def start_and_report(label = 'Total Time', &block) start(label, &block) report(label) end def report(total_label = nil) printf "######### Performance Report #########\n" if sum_hash[total_label] total_time = sum_hash[total_label][:sum].round(5) puts total_time sum_hash.sort_by{|label, values| values[:sum]}.to_h.each{|label, values| printf "%-150s %s (%s)\n", "#{label} (total time):", values[:sum].round(5), "#{((values[:sum]/ total_time) * 100).round(1)}%" printf "%-150s %s\n", "#{label} (number of calls):", values[:num] printf "%-150s %s\n\n", "#{label} (average time):", (values[:sum]/values[:num]).round(5) } end printf "\n######### (most time consuming method is at the bottom) #########" reset! end def reset! self.sum_hash = {} end def active? active_labels.any? end private attr_accessor :sum_hash, :options, :active_labels def append_active_label(label) active_labels << label end def remove_active_label(label) self.active_labels = active_labels.select{|i| i != label} end end
true
d80f1130c168fb7cbf6858f774c19f9024f8a0c9
Ruby
jordanwa1947/black_thursday
/test/customer_repository_test.rb
UTF-8
2,199
2.9375
3
[]
no_license
require 'simplecov' SimpleCov.start require 'minitest/autorun' require 'minitest/pride' require './lib/customer_repository' class CustomerRepositoryTest < Minitest::Test def test_it_exits cr = CustomerRepository.new("./data/customers.csv") assert_instance_of CustomerRepository, cr end def test_it_initalizes_an_array_of_customer_objects cr = CustomerRepository.new("./data/customers.csv") assert_instance_of Customer, cr.objects_array[534] assert_equal 1000, cr.all.count end def test_it_finds_by_id cr = CustomerRepository.new("./data/customers.csv") customer = cr.find_by_id(798) assert_instance_of Customer, customer assert_equal 798, customer.id end def test_it_finds_all_by_first_name cr = CustomerRepository.new("./data/customers.csv") actual = cr.find_all_by_first_name('oe') assert_equal 8, actual.count assert_instance_of Customer, actual[4] end def test_it_finds_all_by_last_name cr = CustomerRepository.new("./data/customers.csv") actual = cr.find_all_by_last_name('On') assert_equal 85, actual.count assert_instance_of Customer, actual[4] end def test_create_creates_a_new_customer cr = CustomerRepository.new("./data/customers.csv") cr.create ({:first_name => "Harry", :last_name => "Potter", :created_at => Time.now, :updated_at => Time.now}) new_customer = cr.all.last assert_equal 'Harry', new_customer.first_name assert_equal 'Potter', new_customer.last_name assert_instance_of Time, new_customer.created_at assert_instance_of Time, new_customer.updated_at end def test_that_update_updates_an_existing_customer cr = CustomerRepository.new("./data/customers.csv") old_customer = cr.find_by_id(1) assert_equal 'Joey', old_customer.first_name cr.update(1, {first_name: "Lily"}) new_customer = cr.find_by_id(1) assert_equal "Lily", new_customer.first_name end def test_it_deletes_a_given_customer cr = CustomerRepository.new("./data/customers.csv") assert_instance_of Customer, cr.find_by_id(54) cr.delete(54) assert_nil cr.find_by_id(54) end end
true
32a4bb251c839cf10df3c27613d379bb6168a393
Ruby
IcelandicGambit/veterinaryclinic
/test/customer_test.rb
UTF-8
1,060
3.328125
3
[]
no_license
# pry(main)> joel.outstanding_balance # # => 0 # # pry(main)> joel.charge(15) # # pry(main)> joel.charge(7) # # pry(main)> joel.outstanding_balance # # => 22 require 'minitest/autorun' require 'minitest/pride' require './lib/customer' require './lib/pet' class CustomerTest < Minitest::Test def setup @joel = Customer.new("Joel", 2) @samson = Pet.new({name: "Samson", type: :dog, age: 3}) @lucy = Pet.new({name: "Lucy", type: :cat, age: 12}) end def test_it_exists assert_instance_of Customer, @joel end def test_it_has_attributes assert_equal "Joel", @joel.name assert_equal 2, @joel.id assert_equal [], @joel.pets assert_equal 0, @joel.outstanding_balance end def test_you_can_adopt_pets assert_equal [], @joel.pets @joel.adopt(@samson) @joel.adopt(@lucy) assert_equal [@samson, @lucy], @joel.pets end def test_you_can_charge_customers assert_equal 0, @joel.outstanding_balance @joel.charge(15) @joel.charge(7) assert_equal 22, @joel.outstanding_balance end end
true
a790387c0ce85795f14e3b03315466f4b8ea7dc8
Ruby
CodeByLine/intro-to-tdd-rspec-and-learn-q-000
/current_age_for_birth_year.rb
UTF-8
196
2.890625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
#age_of_person = current_age_for_birth_year(1984) def current_age_for_birth_year(birth_year) 2015 - birth_year end #def current_age_for_birth_year(birth_year) # Time.now.year - birth_year #end
true
e95d8747a58444c7c45ec6096d90e580ffff2fee
Ruby
dhirabayashi/code_gen
/template/java.rb
UTF-8
1,156
3.390625
3
[]
no_license
def snake2camel(s) return s unless s.include?('_') array = s.split('_') array[0] + array[1..-1].map(&:capitalize).join end def delete_index(type) return type unless type.include?('[') type.split('[')[0] + '[]' end class String def upcase_first self[0].upcase + self[1..-1] end end def code_gen(app, hash) structure = <<-EOS public class %s { %s } EOS field = " private %s %s;\n" getter = <<-EOS public %s %s() { return %s; } EOS setter = <<-EOS public void set%s(%s %s) { this.%s = %s; } EOS field_hash = {} hash.each do |k, v| field_hash[snake2camel(k)] = delete_index(v) end field_list = [] accessor_list = [] field_hash.each do |name, type| field_list << field % [type, name] prefix = type == 'boolean' ? 'is' : 'get' accessor_list << getter % [type, prefix + name.upcase_first, name] accessor_list << setter % [name.upcase_first, type, name, name, name] end members = field_list + accessor_list code = structure % [app, members.join("\n")] filename = "#{app}.java" [filename, code] end
true
e3d804b56be662468d1bad6b908414cd0d67c3ce
Ruby
m4i/xrea-cron
/lib/cron/crontab/line.rb
UTF-8
680
2.78125
3
[]
no_license
require 'cron/crontab' require 'cron/crontab/date_field' module Cron module Crontab class Line class ParseError < Crontab::ParseError; end attr_reader :command def initialize(line) unless match = /^#{'(\S+)\s+' * 5}(\S.*)$/.match(line.strip) raise ParseError end fields = match.captures @date_fields = %w( Minute Hour Day Month DayOfWeek ).map do |klass| DateField.const_get(klass).new(fields.shift) end @command = fields.shift end def execute?(time) @date_fields.all? do |date_field| date_field.execute?(time) end end end end end
true
619b244a59b0caa4faa6f262fe86f2b67794113e
Ruby
jacoblockard99/models_in_place
/lib/models_in_place/middlewares/options_insert.rb
UTF-8
1,810
2.6875
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'middlegem' require 'deep_merge/rails_compat' module ModelsInPlace module Middlewares # {OptionsInsert} is a middleare class that can dynamically append options to a field's # options hash. This class is used internally for options scoping, but can also be used # directly if desired. # # This class is not to be confused with {OptionsInjector}, which ensures that an options # hash is always present in the field input. Note that {OptionsInsert} should *always* be # defined after {OptionInjector} as it relies upon the last argument being a hash. # # @author Jacob Lockard # @since 0.1.0 class OptionsInsert < Middlegem::Middleware # The options to append to the field's options hash. # @return [Hash] the options to insert. attr_reader :inserted_options # Creates a new instance of {OptionsInsert} with the given options to insert. # @param inserted_options [Hash] the options to append to the field's option hash. def initialize(inserted_options) @inserted_options = inserted_options super() end # Executes the {OptionsInsert} middleware by using the {deep_merge # https://github.com/danielsdeleo/deep_merge} gem to recursively merge the options in # {#inserted_options} with the current options hash. # @param mode [Symbol] the mode in which the field should be rendered. # @param args [Array] the input argments to transform. The final argument *must* be a hash. # @return [Array] the transformed arguments. def call(mode, *args) merge_options = { extend_existing_arrays: true } args[-1] = inserted_options.deep_dup.deeper_merge!(args.last, merge_options) [mode, *args] end end end end
true
e038d3e476fc5e55ab858e541ace246e11ecede9
Ruby
StrongMind/canvas_shim
/app/services/pipeline_service/api/publish.rb
UTF-8
1,623
2.53125
3
[ "MIT" ]
permissive
# The API calls Commands # # Class methods map to Commands # ie: PipelineService::API::Publish calls PipelineService::Commands::Publish module PipelineService module API class Publish attr_reader :object def initialize(object, args={}) if object.is_a? PipelineService::Models::Noun @object = object else @object = Models::Noun.new(object, alias: args[:alias]) end @changes = object.try(:changes) @command_class = args[:command_class] || Commands::Publish @queue = args[:queue] || Delayed::Job @client = args[:client] || PipelineClient end def call return if SettingsService.get_settings(object: :school, id: 1)['disable_pipeline'] if client == PipelineService::V2::Client perform else queue.enqueue(self, priority: 1000000) end end def perform retry_if_invalid unless object.valid? command.call end private attr_reader :jobs, :command_class, :queue, :changes, :client # If an object makes it here that is not valid, fetch it again and see if it is valid now. # Otherwise, raise an error to renqueue the command def retry_if_invalid @object = object.fetch return if object.valid? raise "#{object.name} noun with id=#{object.id} is invalid, validation errors: #{object.errors.full_messages}" end def command command_class.new( object: object, changes: changes, client: client ) end end end end
true
6c6b049a83e113b60d21ae6d0c77aba3edba652a
Ruby
vic/apricot
/lib/apricot/ast/send.rb
UTF-8
1,130
2.859375
3
[ "ISC" ]
permissive
module Apricot module AST # An auxiliary node for handling special send expression forms: # # (.method) # (Foo. ) # (Foo/bar ) # class Send < Identifier attr_reader :receiver attr_reader :message def initialize(line, receiver, message) rec_name = case receiver when Constant receiver.names.join('::') when Identifier receiver.name end if receiver.nil? # (.foo ) name = ".#{message}".to_sym elsif message == :new # (Foo. ) name = "#{rec_name}.".to_sym else # (Foo/bar ) name = "#{rec_name}/#{message}".to_sym end super(line, name) @receiver = receiver @message = message end def bytecode(g) if receiver.is_a?(Constant) && message receiver.bytecode(g) if message.to_s =~ /^[A-Z]/ g.find_const(message) else g.send message, 0 end else super(g) end end end end end
true
39aa18edeb34f71ecccbff0f6d5909dbc7f50b0e
Ruby
benburkert/schemr
/spec/lib/DOM/element_spec.rb
UTF-8
1,720
2.765625
3
[]
no_license
require File.dirname(__FILE__) + '/../../spec_helper' def new_element(*args) Schemr::DOM::Element.new(*args) end describe Schemr::DOM::Element, "'s new instances" do it "should expect the first argument of the constructor to to be the identifier" do new_element("name").identifier.should == "name" end it "should assign options as attributes in their string form" do new_element("name", :attr => :value).attributes.should == {"attr" => "value"} end end describe Schemr::DOM::Element, "by default" do it "should not have any attributes" do new_element("name").attributes.should be_empty end it "should not have any children" do new_element("name").children.should be_empty end end describe Schemr::DOM::Element do it "should respond to messages to attributes" do new_element("name", :attr => :value).attr.should == "value" end it "should add attributes if setter method does not exist" do element = new_element("identifier") element.name = "name" element.name.should == "name" end it "should add new attribute keys as symbols" do element = new_element("identifier") element["convert_to_sym"] = "value" element[:convert_to_sym].should == "value" end it "should add new attributes as nil if the key is not found" do element = new_element("identifier") element[:some_key] element.attributes.keys.should include("some_key") element[:some_key].should be_nil element.some_key.should be_nil end it "should still call method_missing if the method is not an attribute" do element = new_element("identifier") lambda { element.some_method_that_doesnt_exist }.should raise_error(NoMethodError) end end
true
f691b0e9c8dce02362df5c45bac717f2a97fe2e6
Ruby
ngovanhuong94/learn-ruby
/03_simon_says/simon_says.rb
UTF-8
502
4.09375
4
[]
no_license
#write your code here def echo(str) str end def shout(str) str.upcase end def repeat(str, num=2) result = [] num.times { result.push(str)} result.join(" ") end def start_of_word(str, num) str.slice(0, num) end def first_word(str) str.split(' ')[0] end def titleize(str) arr = str.split(' ') result = [] i = 0 arr.each do |item| if i == 0 || i == (arr.length - 1) || item.length > 4 result.push(item.capitalize) else result.push(item) end i += 1 end result.join(" ") end
true
171cd201680078f35a067e50b9426b11acd9190e
Ruby
nanachi772/Rails_programming
/Ruby/lib/redo2.rb
UTF-8
394
3.09375
3
[]
no_license
foods = ['ピーマン', 'トマト', 'セロリ', '人参', 'レタス'] count = 0 foods.each do |food| print "#{food}は好きですか? => " # わざといいえのみに解答をしぼる answer = 'いいえ' puts answer count += 1 # やり直しは二回までにする redo if answer != 'はい' && count < 2 # カウントをリセット count = 0 end
true
55e94bf2833f7ee171c63e98b51fc1cb963a101e
Ruby
volodymyr-mykhailyk/advent-of-code-2020
/lib/computing/structures/double_linked_list.rb
UTF-8
552
3.171875
3
[]
no_license
module Computing module Structures class DoubleLinkedList def initialize(first) @head = Node.new(first) @tail = @head end def append(item) node = Node.new(item) @tail.append(node) end class Node attr_reader :before, :after, :item def initialize(item) @item = item end def append(node) node.before = self node.after = @after @after.before = node @after = node end end end end end
true
3e10e89d6e93cdcdca3e4d59a846e730d91c32bc
Ruby
golybhe/hello-world
/db/seeds.rb
UTF-8
732
2.59375
3
[]
no_license
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) require 'imdb' search = Imdb::Search.new("woman") search.movies.each do |movie| Film.create(title: movie.title, plot: movie.plot, year: movie.year, poster: movie.poster) end # get '/' do # @movies=[] # erb :movies # end # def select movies # tmp_movies = [] # movies.each do |movie| # if movie.poster != "" # tmp_movies.push(movie) # end # end # tmp_movies # end
true
5ec1fe71fe4b65cc3440aee074b84a4869936b04
Ruby
kshmir/so-2011
/files/level_generator.rb
UTF-8
4,002
2.65625
3
[]
no_license
# Made by Cristian Pereyra - WTFPL # /* This program is free software. It comes without any warranty, to # * the extent permitted by applicable law. You can redistribute it # * and/or modify it under the terms of the Do What The Fuck You Want # * To Public License, Version 2, as published by Sam Hocevar. See # * http://sam.zoy.org/wtfpl/COPYING for more details. */ class Array def randomize! self.sort! { rand(100) - 50 } end end puts "Mode of use: ruby level_generator.rb NUMBER_OF_CITIES NUMBER_OF_MEDICINES NUMBER_OF_AIRLINES MAX_MED_AMOUNT ARC_PROBABILITY MAX_DISTANCE PLANES FOLDER_NAME" puts "Builds a folder with all the files to pass to the TP" # This medicines and cities are just taken from google, feel free to change em. meds = ["Adiro100", "Nolotil", "Efferalgan", "Gelocatil", "Augmentine", "VoltarenEmulgel", "Lexatn", "Paracetamol", "Orfidal", "Dianben", "Neobrufen", "Trankimazn", "Ventoln", "Almax", "Flumil", "Sintrom", "Termalgin", "Viscofresh", "Enantyum", "Cardyl"] cities = ["Abidjan","Ahmedabad","Alexandria","Ankara","Baghdad","Bangalore","Bangkok","Beijing","Berlin","Bogota","BuenosAires","Busan","Cairo","CapeTown","Chennai","Chongqing","Delhi","Dhaka","Dongguan","Durban","Guangzhou","Hanoi","HoChiMinhCity","HongKong","Hyderabad","Istanbul","Jaipur","Jakarta","Jeddah","Johannesburg","Kanpur","Karachi","Kinshasa","Kolkata","Lagos","Lahore","Lima","London","LosAngeles","Madrid","MexicoCity","Moscow","Mumbai","Nairobi","NewYorkCity","Pune","Pyongyang","RioDeJaneiro","Riyadh","SaintPetersburg","Santiago","Seoul","Shanghai","Shenyang","Shenzhen","Singapore","Surat","SaoPaulo","Tehran","Tianjin","Tokyo","Wuhan","Yangon","Yokohama"] if ARGV.count >= 7 n_cities = ARGV[0].to_i n_med = ARGV[1].to_i n_air = ARGV[2].to_i max_med = ARGV[3].to_i arc_prob = ARGV[4].to_f max_distance = ARGV[5].to_i n_planes = ARGV[6].to_i folder = ARGV[7] else n_cities = 50 n_med = 15 n_air = 10 max_med = 1000 arc_prob = 1 max_distance = 30 n_planes = 10 folder = "default" end relations = {} selected_meds = [] selected_cities = [] meds.randomize! cities.randomize! n_cities.times do break if cities.size == 0 selected_cities.push cities.pop end n_med.times do break if cities.size == 0 selected_meds.push meds.pop end Dir.mkdir folder unless test ?d, folder path = "#{folder}" map_name = "#{path}/mapa.txt" map_f = File.open(map_name, 'w') map_f.puts n_cities selected_cities.each do |city| map_f.puts map_f.puts city c = rand(n_med - 1) + 1 meds = selected_meds.clone.randomize! c.times do map_f.puts "#{meds.pop} #{rand(max_med - 10) / 10 * 10 + 10}" end end first = true selected_cities.each do |from| map_f.puts selected_cities.each do |to| if (rand() < arc_prob or first) and from != to if relations[from] == nil relations[from] = [] end unless relations[from].include? to or (not relations[to].nil? and relations[to].include? from) relations[from].push to map_f.puts "#{from} #{to} #{(rand(max_distance - 10) + 10) / 5 * 5}" end end end first = false end map_f.close airline_files = [] n_air.times do |i| air_name = "#{path}/aerolinea#{i}.txt" air_f = File.open(air_name, 'w') cities = selected_cities.clone.randomize! air_f.puts n_planes n_planes.times do meds = selected_meds.clone.randomize! air_f.puts air_f.puts cities.pop n_planes.times do air_f.puts "#{meds.pop} #{rand(max_med - 10) / 10 * 10 + 10}" end end air_f.close airline_files.push air_name end str = "./tp1 --method sockets --level files/#{map_name} --airline " airline_files.each do |air| str << " files/#{air}" end `echo #{str} | pbcopy`
true
4c6d5bb9ed164813aaf7f9bd7f5fef292b059e7b
Ruby
msrashid/intro-to-ruby-launch-school
/ch7_hashes/merge.rb
UTF-8
351
2.9375
3
[]
no_license
family = { uncles: ["bob", "joe", "steve"], sisters: ["jane", "jill", "beth"]} familyone = { brothers: ["frank","rob","david"], aunts: ["mary","sally","susan"]} puts family.merge(familyone) puts puts family puts puts familyone puts puts family.merge!(familyone) puts puts family puts puts familyone
true
15affe551e6faa2a99e0972f7296221d563f8407
Ruby
shibukk/qiita-advent_calendar-list
/scraping.rb
UTF-8
936
3
3
[]
no_license
require 'mechanize' class Scraping def initialize @agent = Mechanize.new @day = Time.now.day end def exec data = [] # めんどくさいのでハードコーディング 1.upto(24) do |i| page = @agent.get(url(i)) page.search('//td[@class="adventCalendarList_calendarTitle"]/a').each do |calendar| detail = page.link_with(:href => calendar[:href]).click detail.search('.adventCalendarItem').each do |item| entry = get_entry(item) next if entry.nil? data << { title: entry.text, url: entry[:href] } end end sleep 30 end return data end def url(num) "http://qiita.com/advent-calendar/2016/calendars?page=#{num}" end def get_entry(item) return nil if item.at('.adventCalendarItem_date').text !~ /^12 \/ #{@day}$/ return item.at('.adventCalendarItem_entry/a') end end
true
8f45c2b9fcc103734bd3668b7e6e760e10628f8d
Ruby
lucaminudel/TDDwithMockObjectsAndDesignPrinciples
/TDDMicroExercises/Ruby/unicode_file_to_html_text_converter/unicode_file_to_html_text_converter.rb
UTF-8
335
2.921875
3
[]
no_license
require 'cgi' class UnicodeFileToHtmTextConverter def initialize(file_path) @full_file_name_with_path = file_path end def convert_to_html text = File.open(@full_file_name_with_path).read html = '' text.each_line do |line| html += CGI::escapeHTML(line) html += '<br />' end html end end
true
7ae1d7b6f0f501d33baf0bd0907275fdf0bd63ef
Ruby
faisaln/number_puzzle
/spec/lib/print_number_spec.rb
UTF-8
6,906
3.59375
4
[]
no_license
require 'spec_helper' describe PrintNumber do include PrintNumber shared_examples "text for numbers" do it 'prints text for numbers' do for i in 0...numbers.length print(numbers[i]).should == text[i] end end end it 'does not accept numbers with 10 digits or more' do print(1000000000).should include "Numbers with more than nine digits are not supported\n" print(-1000000000).should include "Numbers with more than nine digits are not supported\n" end it 'should add Minus in front of negative numbers' do print(-1).should == 'Minus One' print('-100000000').should == 'Minus One Hundred Million' end it 'does not accept numbers with decimals' do print('1.01').should include "Only whole numbers are supported\n" end context 'non-numeric input' do it 'does not accept non-numeric input' do print('abc').should include "Non-numeric input is not supported\n" print('1abc').should include "Non-numeric input is not supported\n" print('abc1').should include "Non-numeric input is not supported\n" end end context 'single digits' do digit_text = %w[Zero One Two Three Four Five Six Seven Eight Nine] it 'print text for each digit' do for i in 0...digit_text.length print(i).should == digit_text[i] end end end context '2 digit numbers' do context 'tens' do tens_text = %w[Ten Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety] it 'prints text for tens' do for i in 1...tens_text.length print(i * 10).should == tens_text[i - 1] end end end context 'numbers from 11 to 19' do eleven_nineteen = %w[Eleven Twelve Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen] it 'prints text for numbers from 11 to 19' do (11..19).each do |i| print(i).should == eleven_nineteen[i - 10 - 1] end end end context 'numbers from 21 to 99 other than tens' do specify {print(21).should == 'Twenty One'} specify {print(34).should == 'Thirty Four'} specify {print(62).should == 'Sixty Two'} specify {print(77).should == 'Seventy Seven'} specify {print(99).should == 'Ninety Nine'} end end context '3 digit numbers' do context 'hundreds' do let(:text) {['One Hundred', 'Four Hundred', 'Seven Hundred']} let(:numbers) {[100, 400, 700]} it_behaves_like 'text for numbers' end context 'numbers other than hundreds' do let(:numbers) {[101, 221, 376, 999]} let(:text) {['One Hundred and One', 'Two Hundred and Twenty One', 'Three Hundred and Seventy Six', 'Nine Hundred and Ninety Nine']} it_behaves_like 'text for numbers' end end context 'thousands' do context 'ones' do context 'simple' do let(:numbers) {[1000, 4000, 7000]} let(:text) {['One Thousand', 'Four Thousand', 'Seven Thousand']} it_behaves_like 'text for numbers' end context 'complex' do let(:numbers) {[1701, 4357, 7011, 9001]} let(:text) {['One Thousand Seven Hundred and One', 'Four Thousand Three Hundred and Fifty Seven', 'Seven Thousand and Eleven', 'Nine Thousand and One']} it_behaves_like 'text for numbers' end end context 'tens' do context 'simple' do let(:numbers) {[10000, 40000, 70000]} let(:text) {['Ten Thousand', 'Forty Thousand', 'Seventy Thousand']} it_behaves_like 'text for numbers' end context 'complex' do let(:numbers) {[10010, 44567, 70003, 80798]} let(:text) {['Ten Thousand and Ten', 'Forty Four Thousand Five Hundred and Sixty Seven', 'Seventy Thousand and Three', 'Eighty Thousand Seven Hundred and Ninety Eight']} it_behaves_like 'text for numbers' end end context 'hundreds' do context 'simple' do let(:numbers) {[100000, 400000, 700000]} let(:text) {['One Hundred Thousand', 'Four Hundred Thousand', 'Seven Hundred Thousand']} it_behaves_like 'text for numbers' end context 'complex' do let(:numbers) {[101022, 489000, 700001, 899977]} let(:text) {['One Hundred and One Thousand and Twenty Two', 'Four Hundred and Eighty Nine Thousand', 'Seven Hundred Thousand and One', 'Eight Hundred and Ninety Nine Thousand Nine Hundred and Seventy Seven']} it_behaves_like 'text for numbers' end end end context 'millions' do context 'ones' do context 'simple' do let(:numbers) {[1000000, 4000000, 7000000]} let(:text) {['One Million', 'Four Million', 'Seven Million']} it_behaves_like 'text for numbers' end context 'complex' do let(:numbers) {[1701122, 4357778, 7011235, 9000009]} let(:text) {['One Million Seven Hundred and One Thousand One Hundred and Twenty Two', 'Four Million Three Hundred and Fifty Seven Thousand Seven Hundred and Seventy Eight', 'Seven Million Eleven Thousand Two Hundred and Thirty Five', 'Nine Million and Nine']} it_behaves_like 'text for numbers' end end context 'tens' do context 'simple' do let(:numbers) {[10000000, 40000000, 70000000]} let(:text) {['Ten Million', 'Forty Million', 'Seventy Million']} it_behaves_like 'text for numbers' end context 'complex' do let(:numbers) {[17011228, 43577789, 70112351, 90000007]} let(:text) {['Seventeen Million Eleven Thousand Two Hundred and Twenty Eight', 'Forty Three Million Five Hundred and Seventy Seven Thousand Seven Hundred and Eighty Nine', 'Seventy Million One Hundred and Twelve Thousand Three Hundred and Fifty One', 'Ninety Million and Seven']} it_behaves_like 'text for numbers' end end context 'hundreds' do context 'simple' do let(:numbers) {[100000000, 400000000, 700000000]} let(:text) {['One Hundred Million', 'Four Hundred Million', 'Seven Hundred Million']} it_behaves_like 'text for numbers' end context 'complex' do let(:numbers) {[170112281, 435777899, 701123515, 900000007]} let(:text) {['One Hundred and Seventy Million One Hundred and Twelve Thousand Two Hundred and Eighty One', 'Four Hundred and Thirty Five Million Seven Hundred and Seventy Seven Thousand Eight Hundred and Ninety Nine', 'Seven Hundred and One Million One Hundred and Twenty Three Thousand Five Hundred and Fifteen', 'Nine Hundred Million and Seven']} it_behaves_like 'text for numbers' end end end end
true
3630efd1143477be248e985b74037826a4976a30
Ruby
angusjfw/Boris_Bikes
/spec/feature_test/feature_test.rb
UTF-8
304
2.921875
3
[]
no_license
require '~/boris_bikes/lib/docking_station' station = DockingStation.new puts station.bikes.length 20.times { station.dock(Bike.new) } puts "adding bikes" puts station.bikes.length bike = station.release_bike puts "releasing one bike" puts station.bikes.length puts bike.working? puts "end of script"
true
92d70f244df56755676ba6f932225f06ff7fc037
Ruby
Eksentrysyti/phase_0_unit_2
/week_5/6_validate_credit_card/my_solution.rb
UTF-8
3,953
4.59375
5
[]
no_license
# U2.W5: Class Warfare, Validate a Credit Card Number # I worked on this challenge by myself. # 2. Pseudocode # Input: 16 digit credit card number # Output: true if valid card number, false if invalid card number # Steps: # => Create class CreditCard and initialize with single card number parameter # => Create method check_card with the following algorithm: # => Convert each digit into a string, then back into an integer and store into an array # => Double every odd element in the array, if result is greater than 10, then add digits together # => Add all digits in the array, then divide by 10 # => If result is 0, return true, otherwise return false # 3. Initial Solution # Don't forget to check on intialization for a card length # of exactly 16 digits =begin class CreditCard def initialize(card_num) @card_num = card_num if (card_num.to_s.length != 16) raise ArgumentError.new("Card length is not 16!") end end def check_card #convert the card number into an integer array (card_array) card_array = [] card_array = @card_num.to_s.split("").map {|n| n.to_i} #double the value of each odd index card_array.map!.with_index{|value,index| index % 2 == 0 ? value * 2 : value} #check each value of card_array and adds the digits together if greater than 0 card_array.map! {|num| if num > 9 (num/10).floor + num % 10 else num end } #add all digits in array together sum = 0 card_array.each{|value| sum += value} #check to see if the sum is divisible by 0 and returns true or false sum % 10 == 0 ? true : false end end =end # 4. Refactored Solution class CreditCard def initialize(card_num) @card_num = card_num #modified to a single line if statement to be a single line statement raise ArgumentError.new("Card length is not 16!") if (card_num.to_s.length != 16) end def check_card #removed redundant explicit card_array declaration card_array = @card_num.to_s.split("").map {|n| n.to_i} card_array.map!.with_index{|value,index| index % 2 == 0 ? value * 2 : value} #iterates through the array and adds each number to the sum (if it finds a double digit numb, it will add the digits together first) sum = 0 card_array.each {|num| num > 9 ? sum += ((num/10).floor + num % 10) : sum += num} sum % 10 == 0 ? true : false end end # 1. DRIVER TESTS GO BELOW THIS LINE # Create card for testing good_card = CreditCard.new(1234567890123456) # Test 1: Checks that one parameter was passed to new CreditCard object test_card p good_card.method(:initialize).arity == 1 ? "one parameter passed" : "wrong number of parameters passed" # Test 2: Checks that the card number has 16 digits begin bad_card = CreditCard.new(123456) rescue ArgumentError p "Card number is wrong length" end # Test 3: Checks that a bad card returns false bad_card_2 = CreditCard.new(4408041234567892) p bad_card_2.check_card == false ? "good, bad card caught" : "bad card wasn't caught!" # 5. Reflection # This challenge was more challenging that any of the others this week. I had to do extensive research on methods and refresh old ones to get this to work. Some examples of methods I'd never used or rarely used were .split and .with_index. Iterating through the array to double each even indexed element was tricky in that Ruby doesn't have a way to be specific on how to iterate the way that C language can increment a for loop by 2 (i.e. for(i=0; i<16; i+2)). I had to dig through similar questions people had on StackOverflow and eventually found the .with_index method. Once I passed each hurdle and created an initial solution that passed the tests, I went back and looked carefully at how I could refactor some code I knew looked ugly. The refactored code looks simpler and uses fewer lines, though some portions may still look gnarly (i.e. line 79). This is currently to the best of my ability until I can perhaps find some methods that would work.
true
c2661a3b45cffb1a67830d1457df35e75981190f
Ruby
DillonBarker/my_oystercard
/spec/journey_spec.rb
UTF-8
2,165
2.859375
3
[]
no_license
require 'journey.rb' require 'journey_log' require 'station.rb' describe Journey do let(:entry_station) { double(:entry_station) } let(:exit_station) { double(:exit_station) } let(:subject) {described_class.new(entry_station) } describe '#initialize' do it 'stores entry station' do journey = Journey.new(entry_station) expect(journey.entry_station).to eq entry_station end describe '#end_journey' it 'stores exit station' do journey = Journey.new(entry_station) journey.end_journey(exit_station) expect(journey.exit_station).to eq exit_station end end describe '#journey_complete?' do it 'is the journey complete, returns false' do journey = Journey.new(entry_station) expect(journey.journey_complete?).to be false end it 'is the journey complete, returns true' do journey = Journey.new(entry_station) journey.end_journey(exit_station) expect(journey.journey_complete?).to be true end end describe '#fare' do it 'returns penalty fare of 6, if no entry or exit' do journey = Journey.new(entry_station) expect(journey.fare).to eq Journey::PENALTY_FARE end it 'calculates fare of travel between zone 1 and zone 1' do update_zones(1,1) subject.end_journey(exit_station) expect(subject.fare).to eq Journey::MINIMUM_FARE end it 'calculates fare of travel between zone 1 and zone 1' do update_zones(1,2) subject.end_journey(exit_station) expect(subject.fare).to eq Journey::MINIMUM_FARE + 1 end it 'calculates fare of travel between zone 1 and zone 1' do update_zones(1,3) subject.end_journey(exit_station) expect(subject.fare).to eq Journey::MINIMUM_FARE + 2 end it 'calculates fare of travel between zone 1 and zone 1' do update_zones(2,5) subject.end_journey(exit_station) expect(subject.fare).to eq Journey::MINIMUM_FARE + 3 end def update_zones(entry_zone, exit_zone) allow(entry_station).to receive(:zone).and_return(entry_zone) allow(exit_station).to receive(:zone).and_return(exit_zone) end end end
true
3c2a694eb7c52bc85078344b85257b1857dfb77a
Ruby
mayank2707/thirdv
/lib/calculate_schedule.rb
UTF-8
3,101
3.1875
3
[]
no_license
class CalculateSchedule def initialize weight, user, exercise_type @weight = weight @user = user @exercise_type = exercise_type end [:week1, :week2, :week3, :week4].each do |week| define_method week.to_s do set1 = set1 week set2 = set2 week set3 = set3 week [set1, set2, set3] end end private def set1 week case week when :week1 return { expected: @weight * 65/100, actual: { weight: find_weight(week, :set1), rep: find_rep(week, :set1) } } when :week2 return { expected: @weight * 70/100, actual: { weight: find_weight(week, :set1), rep: find_rep(week, :set1) } } when :week3 return { expected: @weight * 75/100, actual: { weight: find_weight(week, :set1), rep: find_rep(week, :set1) } } when :week4 return { expected: @weight * 40/100, actual: { weight: find_weight(week, :set1), rep: find_rep(week, :set1) } } end end def set2 week case week when :week1 return { expected: @weight * 75/100, actual: { weight: find_weight(week, :set2), rep: find_rep(week, :set2) } } when :week2 return { expected: @weight * 80/100, actual: { weight: find_weight(week, :set2), rep: find_rep(week, :set2) } } when :week3 return { expected: @weight * 85/100, actual: { weight: find_weight(week, :set2), rep: find_rep(week, :set2) } } when :week4 return { expected: @weight * 50/100, actual: { weight: find_weight(week, :set2), rep: find_rep(week, :set2) } } end end def set3 week case week when :week1 return { expected: @weight * 85/100, actual: { weight: find_weight(week, :set3), rep: find_rep(week, :set3) } } when :week2 return { expected: @weight * 90/100, actual: { weight: find_weight(week, :set3), rep: find_rep(week, :set3) } } when :week3 return { expected: @weight * 95/100, actual: { weight: find_weight(week, :set3), rep: find_rep(week, :set3) } } when :week4 return { expected: @weight * 60/100, actual: { weight: find_weight(week, :set3), rep: find_rep(week, :set3) } } end end def find_weight week, set find_performance(week,set).try(:weight) || 0.0 end def find_rep week, set find_performance(week,set).try(:repetitions) || 0 end def find_performance week, set week_and_set = week.to_s + set.to_s exercise = @user.exercises.find_by_exercise_type @exercise_type exercise.performances.where(week_set: week_and_set).first if exercise end end
true
1f242df16785f485ba0673f071f781e0613eaea5
Ruby
scottberke/algorithms
/algorithms/sort/quick_sort.rb
UTF-8
667
3.53125
4
[]
no_license
def quick_sort(arr, start_index, end_index) if start_index < end_index partition_index = partition(arr, start_index, end_index) quick_sort(arr, start_index, partition_index - 1) quick_sort(arr, partition_index + 1, end_index) end arr end def partition(arr, start_index, end_index) partition_index = start_index partition_value = arr[end_index] start_index.upto(end_index - 1) do |index| if partition_value >= arr[index] arr[index], arr[partition_index] = arr[partition_index], arr[index] partition_index += 1 end end arr[end_index], arr[partition_index] = arr[partition_index], arr[end_index] partition_index end
true
b5c7f26e354b2435f8da78bdcaf19d4eec33ed9c
Ruby
retiman/project-euler
/solns/ruby/67.rb
UTF-8
451
3.046875
3
[ "CC0-1.0" ]
permissive
data = [] file = File.new('/data/67.txt') while (line = file.gets) data << line end file.close data = data.map(&:strip) .reject { |l| l == '' } .map { |l| l.split.map(&:to_i) } (data.length - 2).step(0, -1).each do |i| (0...data[i].length).each do |j| left = data[i + 1][j] right = data[i + 1][j + 1] data[i][j] += [left, right].max end end result = data[0][0] puts result raise Error unless result == 7273
true
59504e78d33d3a5289c75cadc5c9c0b6654b3df1
Ruby
hollyglot/code-exercises
/ruby-exercises/sketching_examples/static_pages/tree_builder.rb
UTF-8
1,062
2.796875
3
[]
no_license
module Domain module StaticPages class TreeBuilder def self.!(parent) instance = new parent instance.! end def initialize(parent) @parent = parent end def ! build end def parent @parent end def build tree_hash = parent.subtree.arrange(order: :position) # See: https://github.com/skyeagle/mongoid-ancestry#arrangement content_tree = {} content_tree = create_content_tree(tree_hash) content_tree end def create_content_tree(tree_hash) parent_hash = {} tree_hash.each do |parent, child_hash| parent_hash[parent.sluggable_field] = create_child_tree(child_hash) end parent_hash end def create_child_tree(child_hash) child_hash = {} child_hash.each do |key, value| if key == 'sluggable_field' child_hash[parent.sluggable_field] = create_child_tree(child_hash) end child_hash end end end end
true
af21b4b9bad5d49c3916b9dd73c066f3801b34ff
Ruby
RISCfuture/giffy
/lib/comic_sans.rb
UTF-8
3,778
2.890625
3
[]
no_license
require 'digest/md5' require 'tempfile' require 'addressable/template' # Interface for rendering strings to images in Comic Sans and uploading them to # AWS S3. # # @example # string= ComicSans.new("Hello, World!") # string.upload # puts string.url class ComicSans attr_reader :string def initialize(string) @string = string end # Renders the string to a temporary .pdf file intended for display as a # borderless image. # # @yield [path] A block to run with the rendered .pdf file before it is # deleted. # @yieldparam [String] path The path to the temporary .pdf file. def to_pdf_file Dir.mktmpdir(ident) do |output_directory| string = self.string pdf_path = File.join(output_directory, ident + '.pdf') Prawn::Document.generate(pdf_path) do font_families.update 'ComicSans' => {normal: Rails.root.join('vendor', 'assets', 'fonts', 'ComicSans.ttf').to_s} font('ComicSans') { text string } end yield pdf_path end end # Renders the string to a temporary .png file intended for display as a # borderless image. # # @yield [path] A block to run with the rendered .png file before it is # deleted. # @yieldparam [String] path The path to the temporary .png file. # @raise [ComicSans::PNGConversionFailed] If convert fails to complete. def to_png_file to_pdf_file do |pdf_path| Dir.mktmpdir(ident) do |output_directory| png_path = File.join(output_directory, ident + '.png') system convert, *CONVERT_OPTIONS, pdf_path, png_path raise PNGConversionFailed, self unless File.exist?(png_path) yield png_path File.unlink png_path end end end # Renders the equation as a borderless image and uploads it to AWS S3. # # @see #url def upload to_png_file do |png_path| File.open(png_path, 'rb') do |file| S3.put_object bucket: Giffy::Configuration.aws.bucket, key: key, body: file end S3.put_object_acl acl: 'public-read', bucket: Giffy::Configuration.aws.bucket, key: key end end # @private cattr_reader :url_template, default: Addressable::Template.new(Giffy::Configuration.aws.url_template) # @return [Addressable::URI] The URL to the uploaded string image on S3. This # URL will only be valid after {#upload} has been called. def url self.class.url_template.expand 'bucket' => Giffy::Configuration.aws.bucket, 'region' => Giffy::Configuration.aws.region, 'key' => key end private CONVERT_BINARIES = %w[convert].freeze CONVERT_OPTIONS = %w[-density 150 -quality 90 -trim].freeze private_constant :CONVERT_BINARIES, :CONVERT_OPTIONS def convert convert = CONVERT_BINARIES.detect { |b| system 'which', b } raise BinaryNotInstalled.new(self, 'convert') unless convert return convert end def ident Digest::MD5.hexdigest string end def key "images/#{ident}.png" end # @abstract # # Generic error class for all ComicSans errors. class Error < StandardError # @return [LaTeX] The LaTeX equation. attr_reader :latex # @private def initialize(msg, latex) super msg @latex = latex end end # Raised when convert fails to complete successfully. class PNGConversionFailed < Error # @private def initialize(latex) super "ImageMagick PNG conversion failed", latex end end # Raised when required binaries are not found. class BinaryNotInstalled < Error # @return [String] The binary that wasn't found. attr_reader :binary # @private def initialize(latex, binary) super "#{binary} not found", latex @binary = binary end end end
true
81b3700d6a3a8fb99e9ce550b33d4a7c9adb3988
Ruby
ricokareem/git-utils
/lib/git-utils/open.rb
UTF-8
1,226
2.734375
3
[ "MIT" ]
permissive
require 'git-utils/command' class Open < Command def parser OptionParser.new do |opts| opts.banner = "Usage: git open" opts.on_tail("-h", "--help", "this usage guide") do puts opts.to_s; exit 0 end end end # Returns the URL for the repository page. def page_url if service == 'stash' && protocol == 'ssh' pattern = /(.*)@([^:]*):?([^\/]*)\/([^\/]*)\/(.*)\.git/ replacement = 'https://\2/projects/\4/repos/\5/browse?at=' + current_branch elsif service == 'stash' && protocol == 'http' pattern = /(.*)@([^:\/]*)(:?[^\/]*)\/(.*)scm\/([^\/]*)\/(.*)\.git/ replacement = 'https://\2\3/\4projects/\5/repos/\6/browse?at=' + current_branch elsif protocol == 'ssh' pattern = /(.*)@(.*):(.*)\.git/ replacement = 'https://\2/\3/' elsif protocol == 'http' pattern = /https?\:\/\/(([^@]*)@)?(.*)\.git/ replacement = 'https://\3/' end origin_url.sub(pattern, replacement) end # Returns a command appropriate for executing at the command line def cmd c = ["open #{page_url}"] c << argument_string(unknown_options) unless unknown_options.empty? c.join("\n") end end
true
b0f316f76f2a734974ad8e9746d2ff9bbe556664
Ruby
q-m/nutriscore-ruby
/lib/nutriscore/common/range.rb
UTF-8
1,906
3.390625
3
[ "MIT" ]
permissive
module Nutriscore module Common # Range class that supports addition, substraction and comparison. # Assumes the objects that the range is composed of is a {{Numeric}}. # # Note that the end range is always included (+exclude_end+ is +false+). class Range < ::Range # Returns a {{Nutriscore::Common::Range}} object from a {{Numeric}} or {{Range}}. def self.wrap(a) if Numeric === a Range.new(a, a) elsif Range === a a elsif ::Range === a Range.new(a.first, a.last) else raise ArgumentError end end def +(a) if Numeric === a Range.new(min + a, max + a) elsif ::Range === a Range.new(min + a.min, max + a.max) else raise ArgumentError end end def -(a) if Numeric === a Range.new(min - a, max - a) elsif ::Range === a Range.new(min - a.max, max - a.min) else raise ArgumentError end end def *(a) if Numeric === a Range.new(min * a, max * a) elsif ::Range === a Range.new(min * a.min, max * a.max) else raise ArgumentError end end def /(a) if Numeric === a Range.new(min / a, max / a) elsif ::Range === a Range.new(min / a.max, max / a.min) else raise ArgumentError end end def ==(a) if Numeric === a single == a else super end end def to_s if min == max min.to_s else super end end def inspect to_s end # Returns single value if possible, +nil+ if there is a range of values. def single min if min == max end end end end
true
e8857d09dee8e7473dec6537ba0fa7887977e405
Ruby
idaolson/battleship
/lib/game_processor.rb
UTF-8
1,838
3.546875
4
[]
no_license
require './lib/board' require './lib/cell' require './lib/ship_generator' require './lib/shot_processor' require './lib/intelligent_computer' module GameProcessor include ShipGenerator include ShotProcessor extend self def game_loop loop do process_turns if winner puts display_boards puts winner break end end end def winner return "You won!" if player_win? return "I won!" if computer_win? end def player_win? @computer_ships.all? { |ship| ship.sunk? } end def computer_win? @player_ships.all? { |ship| ship.sunk? } end def process_turns puts display_boards player_result = process_player_shot computer_result = process_computer_shot @computer_brain.hit_ship(computer_result.last) puts display_results(player_result, computer_result) sunken_ship end def display_results(player_result, computer_result) [ "Your shot on #{player_result.first} was a #{player_result.last}.", "My shot on #{computer_result.first} was a #{computer_result.last}." ].join("\n") end def sunken_ship if computer_ship_sunk? puts "You sunk one of my ships!" end if player_ship_sunk? puts "I sunk one of your ships!" end end def player_ship_sunk? if @player_ships.any? { |ship| ship.sunk? } @player_ships.delete_if { |ship| ship.sunk? } @computer_brain.sunk_target true end end def computer_ship_sunk? if @computer_ships.any? { |ship| ship.sunk? } @computer_ships.delete_if { |ship| ship.sunk? } true end end def display_boards [ "=============COMPUTER BOARD=============", @computer_board.render, "==============PLAYER BOARD==============", @player_board.render(true) ].join("\n") end end
true
2aa07bb3e16dc05be4a3423a193db88151482ddd
Ruby
MicrohexHQ/sp_store
/lib/sp_store/mocks/ram_store.rb
UTF-8
1,402
2.890625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
# :nodoc: namespace module SpStore::Mocks # Memory-backed block store implementation. class RamStore # Creates a new block store with zeroed out blocks. # # Args: # block_size:: the application-desired block size, in bytes # block_count:: number of blocks; caller should make sure blocks fit in RAM def self.empty_store(block_size, block_count) empty_block = "\0" * block_size self.new :block_size => block_size, :block_count => block_count, :blocks => Array.new(block_count) { empty_block.dup } end # De-serializes a block store model from the hash produced by Attributes. def initialize(attributes) @block_size = attributes[:block_size] @blocks = attributes[:block_count] @block_data = attributes[:blocks].map(&:dup) end # Serializes this disk model to a Hash of primitives. def attributes { :block_size => @block_size, :block_count => @blocks, :blocks => @block_data.map(&:dup) } end attr_reader :blocks attr_reader :block_size # :nodoc def read_block_unchecked(block_id) @block_data[block_id].dup end private :read_block_unchecked # :nodoc def write_block_unchecked(block_id, data) @block_data[block_id] = data.dup end private :write_block_unchecked include SpStore::Storage::StoreCallChecker end # class SpStore::Mocks::RamStore end # namespace SpStore::Mocks
true
9ddf6dbd88d809f8b86082e672ccfbca5743665b
Ruby
bruceSz/learnToexcellent
/ruby/meta/blocks/ampersand.rb
UTF-8
275
3.828125
4
[]
no_license
def math(a,b) yield(a,b) end def teach_math(a,b,&operation) puts "let's do the math:" puts math(a,b,&operation) end teach_math(2,3) {|x,y| x*y} def my_method(&the_proc) the_proc end p = my_method{|name| "hello,#{name}!"} puts p.class puts p.call("bill")
true
33e239de5e7be9497052324464255ca6d73372e5
Ruby
taganaka/adventofcode
/day7/day7.rb
UTF-8
970
2.96875
3
[]
no_license
#!/usr/bin/env ruby require 'pp' opcodes = [] File.new(ARGV[0]).each_line do |line| opcodes << line.strip.scan(/(?:(?:(\S+) )?(.*) )?(\S+) -> (\S+)/im).flatten end points = {} loop do opcodes.each do |code| a, op, b, out = code case op when nil if b =~ /\d+/ points[out] = b.to_i else next if points[b].nil? points[out] = points[b] end next when 'RSHIFT' next if points[a].nil? points[out] = points[a] >> b.to_i when 'LSHIFT' next if points[a].nil? points[out] = points[a] << b.to_i when 'NOT' next if points[b].nil? points[out] = ~points[b] when 'OR' next if points[a].nil? || points[b].nil? points[out] = points[a] | points[b] when 'AND' next if points[a].nil? || points[b].nil? points[out] = points[a] & points[b] else fail("#{op} not supported") end end break unless points['a'].nil? end # end pp points
true
0d31cfa3a84648b776b10c887cf3762a90fd7181
Ruby
torqueforge/careerbuilder-2014-march
/bottles/lib/miracle.rb
UTF-8
1,373
3.234375
3
[]
no_license
require 'delegate' class Fixnum def to_bottle_number if Object.const_defined?("BottleNumber#{self}") Object.const_get("BottleNumber#{self}").new(self) else BottleNumber.new(self) end end def to_beer_bottle_number if Object.const_defined?("BeerSongNumber#{self}") Object.const_get("BeerSongNumber#{self}").new(self.to_bottle_number) else BeerSongNumber.new(self.to_bottle_number) end end end class BottleNumber < SimpleDelegator def to_s "#{how_many} #{container}" end def how_many __getobj__.to_s end def container 'bottles' end end class BottleNumber1 < BottleNumber def container 'bottle' end end class BottleNumber0 < BottleNumber def how_many 'no more' end end class BottleNumber6 < BottleNumber def how_many 1 end def container 'six-pack' end end class BeerSongNumber < SimpleDelegator def action "Take #{pronoun} down and pass it around" end def next pred.to_beer_bottle_number end private def pronoun 'one' end end class BeerSongNumber1 < BeerSongNumber private def pronoun 'it' end end class BeerSongNumber0 < BeerSongNumber def action "Go to the store and buy some more" end def pred 99 end end class BeerSongNumber6 < BeerSongNumber private def pronoun 'a beer' end end
true
f452a37693178cda9f63a76e54ca282f36c61fda
Ruby
fabn/zend-framework-deploy
/bin/zf-capify
UTF-8
3,096
2.53125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
#!/usr/bin/env ruby require 'optparse' require 'fileutils' CONFIG_DIR = 'application/configs' stages = [] OptionParser.new do |opts| opts.banner = "Usage: #{File.basename($0)} [path]" opts.on("-m [stage1,stage2]", "--multistage [stage1,stage2]", Array, "Uses multistage configuration") do |stges| stages = stges end opts.on("-h", "--help", "Displays this help info") do puts opts exit 0 end begin opts.parse!(ARGV) rescue OptionParser::ParseError => e warn e.message puts opts exit 1 end end if ARGV.empty? abort "Please specify the directory to capify, e.g. `#{File.basename($0)} .'" elsif !File.exists?(ARGV.first) abort "`#{ARGV.first}' does not exist." elsif !File.directory?(ARGV.first) abort "`#{ARGV.first}' is not a directory." elsif ARGV.length > 1 abort "Too many arguments; please specify only the directory to capify." end def unindent(string) indentation = string[/\A\s*/] string.strip.gsub(/^#{indentation}/, "") end files = { "Capfile" => unindent(<<-FILE), require 'rubygems' require 'zend-framework-deploy' load '#{CONFIG_DIR}/deploy' FILE "#{CONFIG_DIR}/deploy.rb" => 'set :application, "set your application name here" set :repository, "set your repository location here" set :deploy_to, "set path where to deploy application" set :zf_path, "set Zend Framework (remote) installation path here" set :scm, :subversion # Or: `accurev`, `bzr`, `cvs`, `darcs`, `git`, `mercurial`, `perforce`, `subversion` or `none` role :web, "your web-server goes here" # Your HTTP server, Apache/etc '} # multistage patch unless stages.empty? files["#{CONFIG_DIR}/deploy.rb"] << <<-MULTI # multistage setup, see https://boxpanel.bluebox.net/public/the_vault/index.php/Capistrano_Multi_Stage_Instructions set :default_stage, "#{stages.first}" set :stages, %w(#{stages.join(' ')}) require 'capistrano/ext/multistage' MULTI files.merge!( stages.inject({}) do |hash, file| hash["#{CONFIG_DIR}/deploy/" + file + '.rb'] = "# #{file} stage configuration goes here\n" hash end ) puts "Multistage configuration selected, remember to install capistrano-ext gem with '[sudo] gem install capistrano-ext'" end # hints to use other gems to improve capistrano experience files["#{CONFIG_DIR}/deploy.rb"] << <<-HINTS # gem install capistrano-tags to enable tag and branches deploying # require 'capistrano-tags' # gem install capistrano_colors to colorize capistano output # require 'capistrano_colors' HINTS base = ARGV.shift files.each do |file, content| file = File.join(base, file) if File.exists?(file) warn "[skip] '#{file}' already exists" elsif File.exists?(file.downcase) warn "[skip] '#{file.downcase}' exists, which could conflict with `#{file}'" else unless File.exists?(File.dirname(file)) puts "[add] making directory '#{File.dirname(file)}'" FileUtils.mkdir(File.dirname(file)) end puts "[add] writing '#{file}'" File.open(file, "w") { |f| f.write(content) } end end puts "[done] zf-capified!"
true
2d1250ef556cc8e86da79293cd54e8969251bc8a
Ruby
abandoned/fassbinder
/lib/fassbinder/book_builder.rb
UTF-8
691
2.671875
3
[ "WTFPL" ]
permissive
require 'kosher' require 'fassbinder/offer_builder' module Fassbinder class BookBuilder attr_reader :book def initialize @book = Kosher::Book.new @book.offers = [] end def add_offer(hash) builder = OfferBuilder.new builder.id = hash['OfferListing']['OfferListingId'] builder.venue = @book.venue builder.add_item(hash) builder.add_seller(hash['Merchant']) builder.add_shipping(hash) @book.offers << builder.offer end def asin=(asin) @book.asin = asin end def venue=(venue) @book.venue = venue end def offers_total=(count) @book.offers_total = count.to_i end end end
true
94f53658cd9f7c46d4e3e1c833450f6df3d1fbd3
Ruby
bradgreen3/enigma
/lib/key_generator.rb
UTF-8
281
3.171875
3
[]
no_license
class KeyGenerator attr_reader :numbers, :key def initialize @numbers = [0,1,2,3,4,5,6,7,8,9] @key = [] end def get_key 5.times { @key << @numbers.sample } end def give_key if @key.empty? self.get_key else @key.join end end end
true
cbeb80329bb9a24d5555a8a7311b1bd368e7ded1
Ruby
julik/otoku
/lib/otoku/timecode/.svn/text-base/test_timecode.rb.svn-base
UTF-8
4,007
3.125
3
[]
no_license
require 'test/unit' require 'rubygems' require 'timecode' # for Fixnum#hours require 'active_support' class TimecodeTest < Test::Unit::TestCase def test_basics five_seconds_of_pal = 5.seconds * 25 tc = Timecode.new(five_seconds_of_pal, 25) assert_equal 0, tc.hours assert_equal 0, tc.minutes assert_equal 5, tc.seconds assert_equal 0, tc.frames assert_equal five_seconds_of_pal, tc.total assert_equal "00:00:05:00", tc.to_s one_and_a_half_hour_of_hollywood = 90.minutes * 24 film_tc = Timecode.new(one_and_a_half_hour_of_hollywood, 24) assert_equal 1, film_tc.hours assert_equal 30, film_tc.minutes assert_equal 0, film_tc.seconds assert_equal 0, film_tc.frames assert_equal one_and_a_half_hour_of_hollywood, film_tc.total assert_equal "01:30:00:00", film_tc.to_s assert_equal "01:30:00:04", (film_tc + 4).to_s assert_equal "01:30:01:04", (film_tc + 28).to_s assert_raise(Timecode::WrongFramerate) do tc + film_tc end two_seconds_and_five_frames_of_pal = ((2.seconds * 25) + 5) pal_tc = Timecode.new(two_seconds_and_five_frames_of_pal, 25) assert_nothing_raised do added_tc = pal_tc + tc assert_equal "00:00:07:05", added_tc.to_s end end def test_parse simple_tc = "00:10:34:10" assert_nothing_raised do @tc = Timecode.parse(simple_tc) assert_equal simple_tc, @tc.to_s end bad_tc = "00:76:89:30" unknown_gobbledygook = "this is insane" assert_raise(Timecode::CannotParse) do tc = Timecode.parse(unknown_gobbledygook, 25) end assert_raise(Timecode::RangeError) do Timecode.parse(bad_tc, 25) end end def test_succ assert_equal Timecode.new(23), Timecode.new(22).succ end def test_zero assert Timecode.new(0).zero? assert !Timecode.new(1).zero? assert !Timecode.new(1000).zero? end def test_parse_from_numbers assert_equal Timecode.new(10), Timecode.parse("10") assert_equal Timecode.new(60), Timecode.parse("210") assert_equal "10:10:10:10", Timecode.parse("10101010").to_s end def test_parse_with_f assert_equal Timecode.new(60), Timecode.parse("60f") end def test_parse_s assert_equal Timecode.new(50), Timecode.parse("2s") end def test_parse_m assert_equal Timecode.new(25 * 60 * 3), Timecode.parse("3m") end def test_parse_h assert_equal Timecode.new(25 * 60 * 60 * 3), Timecode.parse("3h") end def test_parse_block assert_equal '01:00:00:04', Timecode.parse("1h 4f").to_s assert_equal '01:00:00:04', Timecode.parse("4f 1h").to_s assert_equal '01:00:01:04', Timecode.parse("29f 1h").to_s end def test_float_framerate tc = Timecode.new(25, 12.5) assert_equal "00:00:02:00", tc.to_s end def test_timecode_with_nil_gives_zero assert_equal Timecode.new(0), Timecode.new(nil) end def test_parse_fractional_tc fraction = "00:00:07.1" tc = Timecode.parse_with_fractional_seconds(fraction, 10) assert_equal "00:00:07:01", tc.to_s fraction = "00:00:07.5" tc = Timecode.parse_with_fractional_seconds(fraction, 10) assert_equal "00:00:07:05", tc.to_s fraction = "00:00:07.04" tc = Timecode.parse_with_fractional_seconds(fraction, 12.5) assert_equal "00:00:07:00", tc.to_s fraction = "00:00:07.16" tc = Timecode.parse_with_fractional_seconds(fraction, 12.5) assert_equal "00:00:07:02", tc.to_s end def test_parse_with_calculation tc = Timecode.parse_with_calculation("00:00:00:15 +2f") assert_equal Timecode.new(17), tc end def test_from_seconds fraction = 7.1 tc = Timecode.from_seconds(fraction, 10) assert_equal "00:00:07:01", tc.to_s fraction = 7.5 tc = Timecode.from_seconds(fraction, 10) assert_equal "00:00:07:05", tc.to_s fraction = 7.16 tc = Timecode.from_seconds(fraction, 12.5) assert_equal "00:00:07:02", tc.to_s end end
true
26f73d66798584be961cec7f25b94d49db3b07d2
Ruby
borcun/free
/ruby/hw/6/CharQueue.rb
UTF-8
587
4.25
4
[]
no_license
#!/usr/bin/ruby # CharQueue Class class CharQueue # constructor def initialize @str = String.new end # function that adds a character to end of string def add(chr) @str += chr end # function that adds a character to end of string def +(chr) @str += chr end def del @str.chop! end def - @str.chop! end # function that formats object def to_s @str end # function that prints object def << puts @str end end cqueue = CharQueue.new cqueue.add "x" cqueue.add "x" cqueue + "x" puts cqueue cqueue.del cqueue.- cqueue.<<
true
0f4eefa726999f6a2cf5b7ba376fcfd68878f1ba
Ruby
etsai/madlib
/tests/words_presenter_test.rb
UTF-8
551
2.53125
3
[]
no_license
require "minitest/autorun" require_relative "../app" class WordPresenterTest < MiniTest::Unit::TestCase def setup @story = Story.new :text => "This is a :word1 story." @sp = StoryPresenter.new @story @word = Word.new :url => "http://www.google.com/foo.mp3" @wp = StoryPresenter.new @word end def test_word_prompt_is_created assert @wp end def test_story_presenter_has_xml @word = Word.new :type => "Say a word." @wp = WordPresenter.new @word assert_equal "<Say>Say a word</Say>", @wp.prompt_xml end end
true
6b98d9a23292e11320f65ed11d46c48c416eacc6
Ruby
hock478/ruby-project-alt-guidelines-dc-web-030920
/lib/cli.rb
UTF-8
8,737
3.375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class CommandLineInterface def greet puts "Welcome to Spotify" puts "please enter a number to navigate" end def show_logo puts " /$$$$$$ /$$ /$$ /$$$$$$ /$$__ $$ | $$ |__/ /$$__ $$ | $$ \\__/ /$$$$$$ /$$$$$$ /$$$$$$ /$$| $$ \\__//$$ /$$ | $$$$$$ /$$__ $$ /$$__ $$|_ $$_/ | $$| $$$$ | $$ | $$ \\____ $$| $$ \\ $$| $$ \\ $$ | $$ | $$| $$_/ | $$ | $$ /$$ \\ $$| $$ | $$| $$ | $$ | $$ /$$| $$| $$ | $$ | $$ | $$$$$$/| $$$$$$$/| $$$$$$/ | $$$$/| $$| $$ | $$$$$$$ \\______/ | $$____/ \\______/ \\___/ |__/|__/ \\____ $$ | $$ /$$ | $$ | $$ | $$$$$$/ |__/ \\______/ " end def prompt(string,array) prompt = TTY::Prompt.new prompt.select(string,array) end def multiselect(string, array) prompt = TTY::Prompt.new prompt.multi_select(string,array) end def get_user_input gets.chomp end def welcome greet show_logo end # Exits program def exit_program puts "Goodbye!!!" end def display_menu menu_array = ["Artists","Songs", "Albums", "Genre", "Playlists","Create a Playlist", "Add to a Playlist" , "Delete a Playlist","Search song", "Search album", "To Exit"] user_choice = prompt("Select a menu item please: ", menu_array) return user_choice end #Searches for users input of a song def search_song puts "Enter the song name:" song = get_user_input.titleize song_instance = Song.find_by(name: song) while !song_instance do puts "Invalid, try again:" song = get_user_input.titleize song_instance = Song.find_by(name: song) end return song_instance.name end # Searches for users input of an album def search_album puts "Enter the album name:" album = get_user_input.titleize album_instance = Album.find_by(title: album) while !album_instance do puts "Invalid, try again:" album = get_user_input.titleize album_instance = Album.find_by(title: album) end var = album_instance.title end #plays a song , the argument is a string def play(song) # artist = Artist.find_by(id: song.artist_id) puts "Playing #{song}" end def play_by_artist(song) songg = Song.find_by(name: song) artist_id = songg.artist_id artist = Artist.find_by(id: artist_id).name puts "Playing #{song} - #{artist}" end # Returns a list of artists def view_all_artists list_of_artists = [] info_array = Artist.all.each{|artist| list_of_artists << artist.name}.sort prompt("Artists: ", list_of_artists.sort) end # Returns the songs of an Artist def view_artist_songs(artist) artist_name = artist artist_id = Artist.find_by(name: artist_name).id songs = Song.where(artist_id: artist_id).map{|song| song.name} puts "**************************" puts "**************************" prompt("#{artist_name}'s songs", songs) end # Returns a list of Albums def view_all_albums list_of_albums = [] info_array = Album.all.each{|album| list_of_albums << album.title}.sort prompt("Albums: ", list_of_albums.sort) end # Returns a list of songs by Album def view_album_songs(album) album_title = album album_id = Album.find_by(title: album_title).id songs = Song.where(album_id: album_id).map{|song| song.name} puts "**************************" puts "**************************" prompt("#{album_title}'s songs", songs) end # Returns a list of artists by the selected genre def artist_by_genre all_genres = Artist.all.map{|artist| artist.genre}.uniq.sort genre_name = prompt("Choose a genre: ", all_genres) artists = Artist.all.where(genre: genre_name).map{|artist| artist.name} puts "**************************" puts "For #{genre_name}" puts "**************************" prompt("Choose an Artist from #{genre_name}", artists) end # Returns all songs in database def display_all_songs all_songs = Song.all.map{|song| artist = Artist.find_by(id: song.artist_id) " #{song.name} - #{artist.name}" }.sort song_name = prompt("Choose a song: ", all_songs) end # Returns all Playlists in database def display_all_playlists all_playlists = Playlist.all.map{|playlist| playlist.name }.sort playlist_name = prompt("Choose a Playlist: ", all_playlists) end def view_playlist_songs(playlist) playlist_title = playlist playlist_id = Playlist.find_by(name: playlist_title).id playlist_songs_ids = PlaylistSong.where(playlist_id: playlist_id).map{|playsong| playsong.song_id} songs = playlist_songs_ids.map{|song_id| "#{Song.find_by(id: song_id).name} - #{Artist.find_by(id: Song.find_by(id: song_id).artist_id).name}"} puts "**************************" puts "**************************" prompt("#{playlist_title}'s songs", songs.uniq) end def create_playlist puts "Enter your new playlist title: " title_of_playlist = gets.chomp Playlist.create(name: title_of_playlist) end def find_playlist title = display_all_playlists Playlist.find_by(name: title) end # Prompt and let user select songs to add to playlist. Returns array of strings (songs) def select_songs_for_playlist songs = Song.all.map{|song| "#{song.name} - #{Artist.find_by(id: song.artist_id).name}"}.sort selections = multiselect("Select your songs", songs) while selections == [] do selections = multiselect("Please tap spacebar to select your songs", songs) end selections end def add_songs_to_playlist(playlist,songs_array) #returns all songs that matches the name songs_array.each do |song| artist = Artist.find_by(name: song.split(" - ")[1]) song_instance = Song.find_by(name: song.split(" - ")[0]) PlaylistSong.create(playlist_id: playlist.id, song_id: song_instance.id) end puts "**************************" puts "Added #{songs_array.count} songs to playlist #{playlist.name}" puts "**************************" end def delete_playlist find_playlist.destroy puts "Playlist has been deleted" end def run # menu_array = ["Artists","Songs", "Albums", "Genre", "Playlists","Create a Playlist", "Add to a Playlist" , "Delete a Playlist","Search song", "Search album", "To Exit"] input = "" while input choice = display_menu case choice when "Artists" # Displays all artists, and shows all songs by artist play(view_artist_songs(view_all_artists)) when "Albums" # Displays all albums and shows list of songs inside album play(view_album_songs(view_all_albums)) when "Genre" # Displays all genres, shows list of artists, shows all the songs of the artist play(view_artist_songs(artist_by_genre)) when "Songs" # Displays all songs in database play(display_all_songs) # play_by_artist(display_all_songs) when "Playlists" #view all playlists play(view_playlist_songs(display_all_playlists)) when "Create a Playlist" #create your playlist add_songs_to_playlist(create_playlist,select_songs_for_playlist) when "Search song" # Searches a song by name play_by_artist(search_song) when "Search album" play(view_album_songs(search_album)) when "Delete a Playlist" #delete playlist delete_playlist when "Add to a Playlist" add_songs_to_playlist(find_playlist,select_songs_for_playlist) when "To Exit" #EXIT exit_program break else display_menu end end end end
true
a8cfb0dad4f212b673e32fc2556767b78a41e41d
Ruby
patsul12/animal_shelter
/spec/animal_spec.rb
UTF-8
1,146
2.75
3
[ "MIT" ]
permissive
require 'rspec' require 'animal' require 'pg' DB = PG.connect({:dbname => 'animal_shelter_test'}) RSpec.configure do |config| config.after(:each) do DB.exec("DELETE FROM animals *;") end end describe Animal do describe '.all' do it 'starts off with no animals' do expect(Animal.all).to(eq([])) end end describe '#name' do it 'tells you its name' do test_animal = Animal.new({name: "spot", id: nil}) expect(test_animal.name).to(eq("spot")) end end describe '#id' do it 'sets its ID when you save it' do animal = Animal.new({name: "spot", id: nil}) animal.save expect(animal.id).to(be_an_instance_of(Fixnum)) end end describe '#save' do it 'lets you save animals to the database' do animal = Animal.new({name: "spot", id: nil}) animal.save expect(Animal.all).to(eq([animal])) end end describe("#==") do it("is the same list if it has the same name") do animal1 = Animal.new({:name => "Spot", :id => nil}) animal2 = Animal.new({:name => "Spot", :id => nil}) expect(animal1).to(eq(animal2)) end end end
true
7449cd3fcdeecf09cc524bdf33d585a423959cf7
Ruby
shsachdev/sinatra_todolist_project
/database_persistence.rb
UTF-8
2,259
2.890625
3
[]
no_license
require 'pg' require 'pry' class DatabasePersistence def initialize(logger) @db = if Sinatra::Base.production? PG.connect(ENV['DATABASE_URL']) else PG.connect(dbname: "todos") end @logger = logger end def disconnect @db.close end def query(statement, *params) @logger.info "#{statement}: #{params}" @db.exec_params(statement, params) end def find_list(id) sql = "SELECT * FROM lists WHERE id = $1" sql_todos = "SELECT id, name, completed FROM todo WHERE list_id = $1" result = query(sql, id) todo_result = query(sql_todos, id) tuple = result.first todos = get_todos(todo_result) {id: tuple["id"].to_i, name: tuple["name"], todos: todos} end def all_lists sql = "SELECT * FROM lists" result = query(sql) result.map do |tuple| list_id = tuple["id"].to_i sql_todos = "SELECT id, name, completed FROM todo WHERE list_id = $1" todo_result = query(sql_todos, list_id) todos = get_todos(todo_result) {id: list_id, name: tuple["name"], todos: todos} end end def create_new_list(list_name) sql = "INSERT INTO lists (name) VALUES ($1)" query(sql, list_name) end def delete_list(id) query("DELETE FROM todo WHERE list_id = $1", id) query("DELETE FROM lists WHERE id = $1", id) end def update_list_name(id, new_list_name) sql = "UPDATE lists SET name = $1 WHERE id = $2" query(sql, new_list_name, id) end def create_new_todo(list_id, new_todo_name) sql = "INSERT INTO todo (name, list_id) VALUES ($1, $2)" query(sql, new_todo_name, list_id) end def delete_todo_from_list(list_id, todo_id) query("DELETE FROM todo WHERE list_id = $1 AND id = $2", list_id, todo_id) end def update_todo_status(list_id, todo_id, is_completed) sql = "UPDATE todo SET completed = $1 WHERE list_id = $2 AND id = $3" query(sql, is_completed, list_id, todo_id) end def complete_all_todos(list_id) sql = "UPDATE todo SET completed = true WHERE list_id = $1" query(sql, list_id) end private def get_todos(result) result.map do |tuple| {id: tuple["id"].to_i, name: tuple["name"], completed: tuple["completed"] == "t"} end end end
true
b11a19ab77b249e34f25ccd709a96e740168bbb1
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/kindergarten-garden/3663c5d278e04da1929ff9152af0bcbd.rb
UTF-8
1,078
3.25
3
[]
no_license
class Garden attr_reader :plantings, :students def initialize(diagram, students=default_class) @plantings = parse_diagram(diagram) @students = parse_students(students).sort end private def parse_diagram(diagram) diagram.split("\n").map{ |row| row.chars } end def parse_students(students) students.map { |s| s.downcase.to_sym } end def student_garden_locations locations = {} students.each_with_index do |student, i| locations[student] = ((i * 2)..(i * 2 + 1)) end locations end def method_missing(student) my_locations = student_garden_locations[student] my_plants = plantings.map { |row| row[my_locations] } unabbreviate(my_plants) end def unabbreviate(plants) plants.flatten.map { |plant| abbreviations[plant] } end def abbreviations { "R" => :radishes, "C" => :clover, "G" => :grass, "V" => :violets } end def default_class [ :alice, :bob, :charlie, :david, :eve, :fred, :ginny, :harriet, :ileana, :joseph, :kincaid, :larry] end end
true
e5c7e9d6160ad2100b5fcca6757b999a066c8ac6
Ruby
carinah/Test
/whit_w2_d1/employee.rb
UTF-8
473
3.6875
4
[]
no_license
class Employee attr_accessor :name, :title @@employee_count = 0 def initialize(name, title) @name = name @title = title @@employee_count += 1 end def introduce() "Hi, my name is #{name}." end def self.count() @@employee_count #returns the employee_count class variable, #which ges incremented everytime employy_count is intatiated end def get_title() "Your title is #{@title}." end def self.resign() @@employee_count -= 1 end end
true
cfa7a4beabb2230887fceb5cdfd9ef5e003113f3
Ruby
kawanaka-s-ts/ruby_tutorial
/3-8.rb
UTF-8
616
3.984375
4
[]
no_license
#case式を使って、変数seasonが"春"の時は「アイス買っていこう」、"夏"の時は「かき氷買っていこう」、それ以外の時は「あんまん買っていこう」と表示 #変数seasonは"春"とする season = "春" case season when "春" puts "アイス買っていこう" when "夏" puts "かき氷買っていこう" else puts "あんまん買っていこう" end season = "春" case when season == "春" puts "アイス買っていこう" when season == "夏" puts "かき氷買っていこう" else puts "あんまん買っていこう" end
true
ec32793a485d6e97bd362ce1fdcfc2d7a212ab91
Ruby
theoreticaLee/Ruby-Warrior
/theoreticalee-beginner/player.rb
UTF-8
2,325
3.25
3
[]
no_license
require 'ap' class Player MAX_HEALTH = 20 SAFE_MID_HEALTH = 16 SAFE_MIN_HEALTH = 8 def initialize @previous_warrior_health = MAX_HEALTH end def play_turn(warrior) @warrior = warrior attacked = attacked? if enemy_visible? warrior.shoot!(enemy_direction) elsif walking_into_wall? @warrior.pivot!(:backward) elsif feel_captive? @warrior.rescue!(captive_direction) elsif captive_visible_afar? warrior.walk!(captive_direction) elsif safe?(attacked) && healthy? == false @warrior.rest! elsif retreat?(attacked) retreat! elsif @warrior.feel(:forward).empty? @warrior.walk! else @warrior.attack! end end def enemy_visible? enemy_direction != nil end def enemy_direction [:backward, :forward].each do |dir| shot_obstructed = false @warrior.look(dir).each do |x| shot_obstructed = true if x.captive? return dir if x.enemy? && shot_obstructed == false end end return nil end def retreat! @warrior.walk!(:backward) end def retreated? @warrior.feel(:backward).empty? == false end def retreat?(attacked) attacked == true && @warrior.health <= SAFE_MIN_HEALTH && retreated? == false end def healthy? @warrior.health == MAX_HEALTH end def safe? (attacked) directForwardSafe = @warrior.feel(:forward).empty? || @warrior.feel(:forward).wall? directBackwardSafe = @warrior.feel(:backward).empty? || @warrior.feel(:backward).wall? attacked == false && directForwardSafe && directForwardSafe end def attacked? feeling_worse = @previous_warrior_health > @warrior.health @previous_warrior_health = @warrior.health feeling_worse end def feel_captive? feel_captive_direction != nil end def feel_captive_direction [:forward, :backward, :left, :right].each do |dir| return dir if @warrior.feel(dir).captive? end return nil end def walking_into_wall? @warrior.feel(:forward).wall? end def captive_visible_afar? captive_direction != nil end def captive_direction [:backward, :forward].each do |dir| @warrior.look(dir).each do |x| return dir if x.captive? end end return nil end end
true