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 |
---|---|---|---|---|---|---|---|---|---|---|---|
b284fa9190a3330a2b5229ee3985680b56db0ade
|
Ruby
|
Youngv/shepherd
|
/school_student_course/school.rb
|
UTF-8
| 1,514 | 3.921875 | 4 |
[] |
no_license
|
#!usr/bin/ruby -w
class School
attr_writer :school,:address,:students,:courses
attr_reader :school,:address,:students,:courses
def initialize(school,address,students,courses)
@school = school
@address = address
@students = students
@courses = courses
end
def count
@students.length
end
end
class Student
attr_writer :name,:age,:courses
attr_reader :name,:age,:courses
def initialize(name,age,courses)
@name = name
@age = age
@courses = courses
end
def adult
if @age > 18
return @name
end
end
end
class Course
attr_writer :course, :students
attr_reader :course, :students
def initialize(course, students)
@course = course
@students = students
end
def count()
@students.length
end
def find(student)
if @students.include?(student)
return @course
end
end
end
school1 = School.new("Harvard","NO.28",["young", "victor", "peter"], ["English", "Math", "Chinese"])
z = school1.count()
puts "There are #{z} students in school."
x = school1.students()
puts "students are #{x.join(",")}"
y = school1.school
puts "school name is #{y}"
stu1 = Student.new("young", 20, ["English", "Math"])
stu2 = Student.new("victor", 20, ["Chinese", "Math"])
stu3 = Student.new("peter", 20, ["English", "Chinese"])
course1 = Course.new("Math",["young","victor"])
course2 = Course.new("English",["young","peter"])
course3 = Course.new("Math",["peter","victor"])
p = stu1.adult
puts "#{p}"
q = find('young')
puts "#{q}"
| true |
ae66c0ca22e97e39861c400fabdacfb16e73b817
|
Ruby
|
Enocruz/SWArchitectureClass
|
/Werewolves and Wanderer/main.rb
|
UTF-8
| 18,148 | 3.515625 | 4 |
[] |
no_license
|
# WEREWOLVES AND WARDERER
# Date: 23-Mar-2018
# Authors:
# A01374527 Luis Daniel Rivero Sosa
# A01374648 Mario Lagunes Nava
# A01375640 Brandon Alain Cruz Ruiz
# File: main.rb
# WEREWOLVES AND WANDERER
#
# COMMANDS:
# 1. I -> Opens the inventory
# 2. F -> Starts a fight
# 3. N -> Go to the north
# 4. S -> Go to the south
# 5. E -> Go to the east
# 6. W -> Go to the west
# 7. P -> Pick up a treasure in the curren room
# 8. U -> Go upstairs
# 9. D -> Go downstairs
# 10. T -> Shows the tally
require './map'
class Game
attr_accessor :name
# Initializes the initial values for the game
def initialize
@wealth = 75
@strength = 100
@tally = 0
@mk = 0
@food = 0
@monsters_killed = 0
@suit = 0
@light = 0
@axe = 0
@amulet = 0
@sword = 0
@map = Map.new
@name = ''
@score = 0
end
# Starts the game, calling the principal routine
def start
puts("WHAT IS YOUR NAME, EXPLORER")
@name = gets.chomp.upcase
main_routine
end
# Get the current score
def get_score
@score = 3 * @tally + 5 * @strength + 2 * @wealth + @food + 30 * @mk
@score
end
# Principal routine that handles all the events
def main_routine
loop do
if(@map.currentRoom != @map.previousRoom)
@strength -= 5
@tally += 1
end
if(@map.isGameWon)
@map.getWonMessage(@name)
puts("YOUR SCORE IS #{get_score}")
exit
end
puts("\n**********************************")
puts("")
if(@strength < 10)
puts("WARNING, YOUR STRENGTH IS RUNNING LOW")
end
if(@strength < 1)
puts("YOU HAVE DIED.........")
puts("YOUR SCORE IS #{get_score}")
exit
end
@tally += 1
puts("#{name.upcase}, YOUR STRENGTH IS #{@strength}")
if(@wealth > 0)
puts("YOU HAVE #{@wealth} GOLD")
end
if(@food > 0)
puts("YOUR PROVISIONS SACK HOLDS #{@food} UNITS OF FOOD")
end
if(@axe != 0 || @sword != 0 || @amulet != 0)
print("YOU ARE CARRIYING ")
if(@axe == 1)
print("AN AXE ")
end
if(@sword == 1)
print("A SWORD ")
end
if((@axe == 1 || @sword == 1) && @amulet == 1)
print("AND ")
end
if(@amulet == 1)
print("THE MAGIC AMULET")
end
end
if(@light == 0)
puts("IT IS TO DARK TO SEE ANYTHING")
else
puts("")
puts(@map.getRoomDescription)
end
treasureAndMonster = @map.getTreasuresAndMonsters
if(treasureAndMonster == 0)
puts("THE ROOM IS EMPTY")
elsif(treasureAndMonster > 9)
puts("THERE IS A TREASURE HERE WORTH OF #{treasureAndMonster}")
else
puts("DANGER...THERE IS A MONSTER HERE....")
if(treasureAndMonster == -1)
puts("IT IS A FEROCIOUS WEREWOLF")
puts("THE DANGER LEVEL IS 5")
elsif(treasureAndMonster == -2)
puts("IT IS A FANATICAL FLESHGORGER")
puts("THE DANGER LEVEL IS 10")
elsif(treasureAndMonster == -3)
puts("IT IS A MALOVENTY MALDEMER")
puts("THE DANGER LEVEL IS 15")
elsif(treasureAndMonster == -4)
puts("IT IS A DEVASTATINT ICE-DRAGON")
puts("THE DANGER LEVEL IS 20")
elsif(treasureAndMonster == -5)
puts("IT IS A HORRENDOUS HODGEPODGER")
puts("THE DANGER LEVEL IS 25")
else
puts("IT IS A GHASTLY GRUESOMENESS")
puts("THE DANGER LEVEL IS 30")
end
end
loop do
puts("WHAT DO YOU WANT TO DO")
move = get_movement
break if process_movement(move, treasureAndMonster)
sleep(2)
puts("\n**********************************\n")
end
end
end
#Returns true if a movement was performed otherwise returns false
def process_movement(move, treasureAndMonster)
flee = rand()
if(treasureAndMonster < 0 && move != "R" && move != "F")
puts("FIGHT OR RUN!")
return false
elsif(treasureAndMonster < 0 && move == "R" && flee > 0.7)
loop do
puts('WHICH WAY DO YOU WANT TO FLEE?')
move = get_movement
if(@map.isPossibleMove(move))
@map.move(move)
return true
else
puts(@map.getMoveError(move))
end
end
elsif(treasureAndMonster < 0 && move == "R" && flee < 0.7)
puts('NO YOU MUST STAND AND FIGHT')
sleep(2)
getToFight(treasureAndMonster)
return true
elsif(treasureAndMonster <0 && move == "F")
getToFight(treasureAndMonster)
return true
elsif(move == "Q")
puts("YOUR SCORE IS #{get_score}")
exit
elsif(move == "T")
puts("\n********************************\n")
puts("* YOUR TALLY AT PRESENT IS #{get_score} *")
puts("********************************\n")
sleep(3)
return true
elsif(move == "I")
inventory
@map.updatePreviousRoom
sleep(2)
return true
elsif(move == "C" && @food == 0)
puts("YOU HAVE NO FOOD")
elsif(move == "C")
eat_food
@map.updatePreviousRoom
sleep(2)
return true
elsif(move == "F" && treasureAndMonster >= 0)
puts("THERE IS NOTHING TO FIGTH HERE")
elsif(move == "P")
pick_up_treasure(treasureAndMonster)
@map.setEmptyRoom
sleep(2)
return true
elsif(move == "M" && @amulet == 1)
@map.teleport
sleep(2)
return true
else
if(@map.isPossibleMove(move))
@map.move(move)
return true
else
puts(@map.getMoveError(move))
return false
end
end
end
# Set the ferocity monster according to the parameter given
def getToFight(monsterNumber)
if(monsterNumber == -1)
ferocity = 5
elsif (monsterNumber == -2)
ferocity = 10
elsif (monsterNumber == -3)
ferocity = 15
elsif (monsterNumber == -4)
ferocity = 20
elsif (monsterNumber == -5)
ferocity = 25
elsif (monsterNumber == -6)
ferocity = 30
end
bePrepared(monsterNumber, ferocity)
end
# Adjust the ferocity of the monster according to the player stats
def bePrepared(monsterNumber, ferocity)
if(@suit == 1)
puts('YOUR ARMOR INCREASES YOUR CHANCE OF SUCCESS')
ferocity = 3 * (ferocity/4)
end
i=0;
while(i<=6)
puts('*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*')
i += 1
end
if(@axe == 0 && @sword == 0)
puts('YOU HAVE NO WEAPONS')
puts('YOU MUST FIGHT WITH BARE HANDS')
ferocity = ferocity + (ferocity/5)
battle(monsterNumber,ferocity)
elsif (@axe == 1 && @sword == 0)
puts('YOU HAVE ONLY AN AXE TO FIGHT WITH')
ferocity = 4 * (ferocity/5)
battle(monsterNumber,ferocity)
elsif (@axe == 0 && @sword == 1)
puts('YOU MUST FIGHT WITH YOUR SWORD')
ferocity = 3 * (ferocity/4)
battle(monsterNumber, ferocity)
elsif (@axe == 1 && @sword == 1)
loop do
puts("WHICH WEAPON?")
puts("1 - AXE")
puts("2 - SWORD")
weapon = get_action
if (weapon == 1)
ferocity = 4 * (ferocity/5)
battle(monsterNumber, ferocity)
break
elsif (weapon == 2)
ferocity = 3 * (ferocity/4)
battle(monsterNumber, ferocity)
break
end
end
end
end
# Starts the fight with the given monster
def battle(monsterNumber, ferocity)
if(monsterNumber == -1)
fight('Ferocious Werewolf',ferocity)
elsif (monsterNumber == -2)
fight('Fanatical Fleshgorger',ferocity)
elsif (monsterNumber == -3)
fight('Maloventy Maldemer',ferocity)
elsif (monsterNumber == -4)
fight('Devastating Ice Dragon',ferocity)
elsif (monsterNumber == -5)
fight('Horremdous Hodgepodger',ferocity)
elsif (monsterNumber == -6)
fight('Ghastly Gruesomeness',ferocity,axe)
end
end
# Simulates the fight
def fight(name, ferocity)
loop do
rndNumberFight = rand()
if(rndNumberFight > 0.5)
puts(name + ' ATTACKS')
else
puts('YOU ATTACK')
end
sleep(1)
puts("")
if(rndNumberFight > 0.5 && @light == 1)
puts('YOUR TORCH WAS KNOCKED FROM YOU')
@light = 0
sleep(1)
puts("")
end
if(rndNumberFight > 0.5 && @axe == 1)
puts('YOU DROP YOUR AXE IN THE HEAT OF BATTLE')
@axe = 0
ferocity = 5 * (ferocity/4)
sleep(1)
puts("")
end
if(rndNumberFight > 0.5 && @sword == 1)
puts('YOUR SWORD IS KNOCKED FROM YOUR HAND!!!')
@sword = 0
ferocity = 4 * (ferocity/3)
sleep(1)
puts("")
end
sleep(1)
puts("")
rndNumberFight = rand()
if(rndNumberFight > 0.5)
puts('YOU MANAGE TO WOUND IT')
sleep(1)
puts("")
ferocity = 5 * (ferocity/6)
if(rndNumberFight > 0.95)
puts('Aaaaargh')
puts('RIP! TEAR! RIP')
sleep(1)
puts("")
end
if(rndNumberFight > 0.9)
puts('YOU WANT TO RUN BUT YOU STAND YOUR GROUND')
puts('*&%%$#$% $%#!! @ #$$# #$@! #$ $#$')
sleep(1)
puts("")
end
if(rndNumberFight > 0.70)
puts('WILL THIS BE A BATTLE TO THE DEATH?')
puts('HIS EYES FLASH FEARFULLY')
puts('BLOOD DRIPS FROM HIS CLAWS')
puts('YOU SMELL THE SULPHUR ON HIS BREATH')
puts('HE STRIKES WILDLY, MADLY...........')
puts('YOU HAVE NEVER FOUGHT AN OPONENT LIKE THIS!!')
sleep(1)
puts("")
end
end
rndNumberFight = rand()
if(rndNumberFight > 0.5)
puts('THE MONSTER WOUNDS YOU!')
@strength -= 5
sleep(1)
puts("")
end
rndNumberFight = rand()
if(rndNumberFight > 0.35)
next
else
if(rndNumberFight*16 > ferocity)
puts('AND YOU MANAGED TO KILL THE ' + name)
@monsters_killed += 1
@map.setEmptyRoom
sleep(1)
puts("")
return
else
puts('THE ' + name + ' DEFEATED YOU')
@strength = @strength/2
@map.setEmptyRoom
@map.currentRoom = 6
sleep(1)
puts("")
return
end
end
break if @strength < 1
end
end
# Action to get the input (letters)
def get_movement
gets.chomp.upcase
end
# Action to get the input (numbers)
def get_action
gets.to_i
end
# Method to pick up a treasure in the map
def pick_up_treasure(treasure)
if treasure < 10
puts("THERE IS NO TREASURE TO PICK UP")
return
elsif @light == 1
@wealth += treasure
@map.setEmptyRoom
return
end
end
# Action perform to eat food
def eat_food
return if @food < 1
loop do
puts("YOU HAVE #{@food} UNITS OF FOOD")
puts("HOW MANY DO YOU WANT TO EAT")
food = get_action
if food <= @food
@food -= food
@strength += (food * 5)
break
end
end
end
# Action perform in the inventory to buy food
def buy_food
loop do
puts("\nHOW MANY UNITS OF FOOD")
food = get_action
if(food*2 > @wealth)
puts("YOU HAVEN'T GOT ENOUGH MONEY")
sleep(2)
next
else
puts("\nYOU BOUGTH #{food} UNITS OF FOOD")
@food += food
@wealth -= (food * 2)
sleep(2)
break
end
end
end
# Method that erases all your stats for cheating
def cheater
puts("YOU HAVE TRIED TO CHEAT ME!")
@wealth = 0
@suit = 0
@light = 0
@axe = 0
@amulet = 0
@sword = 0
@food /= 4
sleep(2)
end
# Main routine for the inventory
def inventory
puts("\n**********************************")
puts("\nPROVISIONS & INVENTORY")
loop do
if(@wealth == 0)
puts("\nYOU HAVE NO MONEY")
return
end
puts("\nYOU HAVE #{@wealth}")
if(@wealth >= 0.1)
puts("\nYOU CAN BUY ")
puts("\t 1 - FLAMING TORCH ($15)")
puts("\t 2 - AXE ($10)")
puts("\t 3 - SWORD ($20)")
puts("\t 4 - FOOD ($2 PER UNIT)")
puts("\t 5 - MAGIC AMULET ($30)")
puts("\t 6 - SUIT OF ARMOR ($50)")
puts("\t 0 - TO CONTINUE ADVENTURE")
if(@light == 1)
puts("YOU HAVE A TORCH")
end
if(@axe == 1)
puts("YOU HAVE AN AXE")
end
if(@sword == 1)
puts("YOU HAVE A SWORD")
end
if(@suit == 1)
puts("YOU HAVE A SUIT")
end
if(@amulet == 1)
puts("YOU HAVE AN AMULET")
end
puts("\nENTER NO. OF ITEM REQUIRED")
item = get_action
if(item == 0)
break
elsif(item == 1)
if(@light == 1)
puts("YOU ALREADY OWN A FLAMING TORCH")
sleep(2)
puts("-----------------------------------")
next
end
@wealth -= 15
@light = 1
elsif(item == 2)
if(@axe == 1)
puts("YOU ALREADY OWN AN AXE")
sleep(2)
puts("-----------------------------------")
next
end
@wealth -= 10
@axe = 1
elsif(item == 3)
if(@sword == 1)
puts("YOU ALREADY OWN A SWORD")
sleep(2)
puts("-----------------------------------")
next
end
@wealth -= 20
@sword = 1
elsif(item == 4)
if(@wealth > 1)
buy_food
else
cheater
break
end
elsif(item == 5)
if(@amulet == 1)
puts("YOU ALREADY OWN AN AMULET")
sleep(2)
puts("-----------------------------------")
next
end
@wealth -= 30
@amulet = 1
elsif(item == 6)
if(@suit == 1)
puts("YOU ALREADY OWN A SUIT")
sleep(2)
puts("-----------------------------------")
next
end
@wealth -= 50
@suit = 1
else
sleep(2)
puts("INVALID OPTION")
end
if(@wealth < 0)
cheater
sleep(2)
break
end
end
puts("-----------------------------------")
sleep(2)
end
end
end
| true |
626205ab3f312748598f05c7685a767abcb2f6c3
|
Ruby
|
greendog/clots
|
/spec/drop_spec.rb
|
UTF-8
| 1,434 | 2.671875 | 3 |
[] |
no_license
|
require File.dirname(__FILE__) + '/spec_helper'
class ChildModel
def parent
"parent"
end
def parent_id
15
end
def tags
["tag1", "tag2"]
end
def tag_ids
[1, 2]
end
end
describe "A Drop" do
context "which has associations" do
context "when belongs to an item" do
before(:all) do
class BaseDropWithBelongsTo
extend Clot::DropAssociation
def initialize
@source = ChildModel.new
end
belongs_to :parent
end
end
it "should delegate object calls to its source object" do
drop = BaseDropWithBelongsTo.new
drop.parent.should == "parent"
end
it "should delegate id calls to its source object" do
drop = BaseDropWithBelongsTo.new
drop.parent_id.should == 15
end
end
context "when has many of an item" do
before(:all) do
class BaseDropWithHasMany
extend Clot::DropAssociation
def initialize
@source = ChildModel.new
end
has_many :tags
end
end
it "should delegate object calls to its source object" do
drop = BaseDropWithHasMany.new
drop.tags.should == ["tag1", "tag2"]
end
it "should delegate id calls to its source object" do
drop = BaseDropWithHasMany.new
drop.tag_ids.should == [1, 2]
end
end
end
end
| true |
bdf7be463b65c30409046d4487b59bf16703f755
|
Ruby
|
procchio6/active-record-project
|
/lib/support/cli.rb
|
UTF-8
| 330 | 3.03125 | 3 |
[] |
no_license
|
class CLI
def initialize
puts "Hello and welcome to the Flatiron library!"
end
def get_user_info
while @user.nil?
puts "What is your name?"
name = gets.chomp.downcase
@user = User.find_by_name(name)
if @user.nil?
puts "User not found! Please try again."
end
end
end
end
| true |
850a3a2bfaa5fcafaab6d79ed704491f90683976
|
Ruby
|
ChaeOkay/CoreRuby
|
/4week/W4C1.rb
|
UTF-8
| 1,320 | 4.34375 | 4 |
[] |
no_license
|
=begin
Exercise1. Write a class called Dog, that has name as an instance variable and the following methods:
bark(), eat(), chase_cat()
I shall create the Dog object as follows:
d = Dog.new('Leo')
=end
class Dog
attr_accessor :name, :tricks
def initialize(name)
@name = name
@tricks = {}
end
def teach_trick(sym, &block)
@tricks[sym] = block.call
end
def method_missing(instance_id)
"#{@name} doesn't know how to #{instance_id}!"
end
end
d = Dog.new('Leo')
puts d.teach_trick(:dance) {"#{@name} is dancing!"}
puts d.dance
puts d.teach_trick(:poo) { "#{@name} is a smelly doggy!" }
puts d.poo
=begin
You can store the Proc in an instance variable that contains a hash of tricks. That might be one option.
Also, there are things that let you evaluate strings into code... not surprisingly, they have names such as eval, instance_eval, etc.
When you use a form of 'eval', it makes real methods, and so will utilize respond_to? method. With the tricks stored in a hash idea, you may use something like method missing and write your own responds_to? method to accommodate these things.
Many choices, which is perhaps part of the problem with solving this challenge, but it also means you can determine the best approach of the given situation.
I hope that helps.
=end
| true |
b876317afccdd5ad6efb96159cc7bf648342588a
|
Ruby
|
clarissa2448/kwk-pattern-lab
|
/pattern.rb
|
UTF-8
| 2,277 | 3.625 | 4 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class String
def black; "\e[30m#{self}\e[0m" end
def red; "\e[31m#{self}\e[0m" end
def green; "\e[32m#{self}\e[0m" end
def brown; "\e[33m#{self}\e[0m" end
def blue; "\e[34m#{self}\e[0m" end
def magenta; "\e[35m#{self}\e[0m" end
def cyan; "\e[36m#{self}\e[0m" end
def gray; "\e[37m#{self}\e[0m" end
def bg_black; "\e[40m#{self}\e[0m" end
def bg_red; "\e[41m#{self}\e[0m" end
def bg_green; "\e[42m#{self}\e[0m" end
def bg_brown; "\e[43m#{self}\e[0m" end
def bg_blue; "\e[44m#{self}\e[0m" end
def bg_magenta; "\e[45m#{self}\e[0m" end
def bg_cyan; "\e[46m#{self}\e[0m" end
def bg_gray; "\e[47m#{self}\e[0m" end
def bold; "\e[1m#{self}\e[22m" end
def italic; "\e[3m#{self}\e[23m" end
def underline; "\e[4m#{self}\e[24m" end
def blink; "\e[5m#{self}\e[25m" end
def reverse_color; "\e[7m#{self}\e[27m" end
end
def diamond(height)
#numStars = height * 2 + 1
count = 0
while count<(height + 1)
rowStars = count * 2 + 1
puts " " * (height-count) + "*"* rowStars + " " * (height-count)
count = count + 1
end
count2 = 1
while count2<height + 1
rowStars = (height - count2) * 2 + 1
puts " " * count2 + "*" * rowStars + " " * (count2)
count2 = count2 + 1
end
end
#diamond(2)
def diamond_chain(height, chain)
count = 0
while count < chain
diamond(height)
count = count + 1
end
end
def diamond_long(height,chain)
#count_chain = 0
#while count_chain < chain
count1 = 0
while count1<(height + 1)
rowStars = count1 * 2 + 1
puts (" " * (height-count1) + "*"* rowStars + " " * (height-count1)) * chain
count1 = count1 + 1
end
count2 = 1
while count2<height + 1
rowStars = (height - count2) * 2 + 1
puts (" " * count2 + "*" * rowStars + " " * (count2))*chain
count2 = count2 + 1
end
#count_chain = count_chain + 1
#end
#count_chain = count_chain + 1
end
puts "Enter height: ".red
height = gets.chomp.to_i
puts "Enter chain length:".green
chain = gets.chomp.to_i
diamond_long(height,chain)
| true |
c68e9d39b2f0409e8bbae96480f9ed092ce5e703
|
Ruby
|
eugenesavenko/hammer-gem
|
/functional.rb
|
UTF-8
| 2,173 | 2.75 | 3 |
[] |
no_license
|
require "tmpdir"
require "pathname"
require "fileutils"
require "open3"
include Open3
def compare_directories a, b
_compare_directories(a, b)
_compare_directories(b, a)
end
def _compare_directories a, b
a_files = Dir.glob(File.join(a, "**/*"))
b_files = Dir.glob(File.join(b, "**/*"))
a_files.each do |a_file_path|
relative_file_path = Pathname.new(a_file_path).relative_path_from(Pathname.new(a))
b_file_path = File.join(b, relative_file_path)
raise "File missing: #{a_file_path} wasn't compiled to Build folder" unless File.exist?(b_file_path)
if !File.directory? a_file_path
if !FileUtils.compare_file(b_file_path, a_file_path)
raise %Q{
Error in #{relative_file_path} (#{b_file_path} / #{a_file_path}):
Expected output: (#{b_file_path})
----
#{File.open(b_file_path, 'r:UTF-8').read}
----
Actual output: (File #{a_file_path})
----
#{File.open(a_file_path, 'r:UTF-8').read}
----
}
end
print "."
end
end
end
def run_functional_test(input_directory, reference_directory, optimized)
output_directory = Dir.mktmpdir('Build')
cache_directory = Dir.mktmpdir('cache')
args = ['/usr/bin/ruby', 'hammer_time.rb', cache_directory, input_directory, output_directory]
args << 'PRODUCTION' if optimized
Open3.popen3(*args) { |stdin, stdout, stderr, wait_thread| stdout.read }
return compare_directories(output_directory, reference_directory)
ensure
FileUtils.remove_entry output_directory
FileUtils.remove_entry cache_directory
end
@errors = []
@success = true
dirs = File.join('test', 'functional', '*')
Dir.glob(dirs).each do |directory|
input_directory = File.join(directory, 'input')
reference_directory = File.join(directory, 'output')
begin
# [true, false].each do |optimized|
test_result = run_functional_test(input_directory, reference_directory, false)
# end
rescue => message
print "F"
@errors << message
end
end
puts
if @errors.any?
@success = false
puts
puts "#{@errors.length} errors:"
@errors.uniq.each do |error|
print " "
puts error
end
puts
end
exit @success ? 0 : 1
| true |
1ccc0e016df3e251543fca91cef34d38504f2dd1
|
Ruby
|
traciechang/algorithm-problems
|
/unique_email_addresses.rb
|
UTF-8
| 685 | 3.375 | 3 |
[] |
no_license
|
# leetcode
def num_unique_emails(emails)
unique_emails = []
emails.each do |email|
temp_word = ""
on_domain = false
ignore = false
email.each_char do |char|
if char == "@"
on_domain = true
ignore = false
elsif ignore
next
elsif char == "." && !on_domain
next
elsif char == "+" && !on_domain
ignore = true
else
temp_word << char
end
end
unique_emails << temp_word if !unique_emails.include?(temp_word)
end
unique_emails.length
end
| true |
e5b8493cb925ba9813a3663328ba6e877a817e69
|
Ruby
|
jeffren716/W3D2
|
/SQL/question_like.rb
|
UTF-8
| 2,303 | 2.921875 | 3 |
[] |
no_license
|
require 'sqlite3'
require_relative 'template'
require_relative 'question'
require_relative 'reply'
require_relative 'question_follow'
require_relative 'user'
class QuestionLike
attr_reader :likes
def self.all
data = QuestionsDatabase.instance.execute("SELECT * FROM question_likes")
data.map { |datum| QuestionLike.new(datum) }
end
def initialize(options)
@likes = options['likes']
@question_id = options['question_id']
@user_id = options['user_id']
end
def self.likers_for_question_id(question_id)
users = QuestionsDatabase.instance.execute(<<-SQL, question_id)
SELECT
*
FROM
users
JOIN
question_likes ON (question_likes.user_id = users.id)
WHERE
question_likes.question_id = ?
SQL
users.map { |user| User.new(user) }
end
def self.num_likes_for_question_id(question_id)
likes = QuestionsDatabase.instance.execute(<<-SQL, question_id)
SELECT
COUNT(likes) AS num_likes
FROM
question_likes
WHERE
question_likes.question_id = ?
SQL
likes.first['num_likes']
end
def self.liked_questions_for_user_id(user_id)
questions = QuestionsDatabase.instance.execute(<<-SQL, user_id)
SELECT
*
FROM
questions
JOIN
question_likes ON (question_likes.question_id = questions.id)
WHERE
question_likes.user_id = ?
SQL
questions.map { |question| Question.new(question) }
end
def self.total_likes_for_user_id(user_id)
likes = QuestionsDatabase.instance.execute(<<-SQL, user_id)
SELECT
SUM(likes) as total_likes
FROM
question_likes
JOIN
questions ON question_likes.question_id = questions.id
WHERE
questions.author_id = ?
SQL
likes.first['total_likes']
end
def self.most_liked_question(n)
questions = QuestionsDatabase.instance.execute(<<-SQL)
SELECT
*
FROM
questions
JOIN
question_likes ON (question_likes.question_id = questions.id)
GROUP BY
question_id
ORDER BY
COUNT(*) DESC, question_id DESC
SQL
return nil unless questions.length > 0
questions.map! { |question| Question.new(question) }
questions.take(n)
end
end
| true |
9985ccd70e70dbeb2a70db564bc24711bac6de60
|
Ruby
|
jonfoster9999/never_ending_tape_cli
|
/lib/_task_runner.rb
|
UTF-8
| 1,691 | 2.75 | 3 |
[] |
no_license
|
require 'pry'
require 'active_support/core_ext/time/conversions'
class TaskRunner
attr_accessor :tasks_doc, :completed_tasks_doc, :path, :transfer_path
def initialize(path: nil, transfer_path: nil)
@path = path
@tasks = []
@transfer_path = transfer_path
end
def read_tasks
raw_tasks_doc = File.read(@path)
@tasks_doc = JSON.parse(raw_tasks_doc)
end
def read_completed_tasks
raw_completed_tasks_doc = File.read(@transfer_path)
@completed_tasks_doc = JSON.parse(raw_completed_tasks_doc)
end
def task_index_is_valid?(i)
tasks.each_index.to_a.include?(i)
end
def tasks
tasks_doc['tasks']
end
def completed_tasks
completed_tasks_doc['tasks']
end
def save_completed_tasks
File.open(@transfer_path, 'w') do |f|
f.write(JSON.pretty_generate(completed_tasks_doc))
end
end
def delete_task(i)
tasks.delete_at(i)
save
end
def edit_task(i, val)
tasks[i.to_i] = { info: val }
save
end
def save
File.open(@path, 'w') do |f|
f.write(JSON.pretty_generate(tasks_doc))
end
end
def add_task(task)
tasks << task
save
end
def completed_tasks_since(num_of_days)
read_completed_tasks
today = Date.today
completed_tasks.select do |date, task_arr|
task_date = Date.parse(date)
(today - task_date).to_i <= num_of_days
end.sort_by {|k, v| Date.parse(k) }
end
def mark_task_complete(i)
read_completed_tasks
read_tasks
completed_task = tasks.delete_at(i)
date = Date.today.strftime("%a, %d %b %Y")
completed_tasks[date] ||= []
completed_tasks[date] << completed_task
save
save_completed_tasks
end
end
| true |
342893ce8e81e6bacea5e6c5b79c1796876e6f15
|
Ruby
|
jaredm4/opsworks-scripts
|
/execute-instance-recipes.rb
|
UTF-8
| 3,181 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
require 'rubygems'
require 'json'
def usage
puts 'Usage: execute-instance-recipes.rb <layer-id> <recipes> [\'custom-json\']'
puts
puts 'Runs recipes on all online instances in a layer, and reports their success via shell status_code.'
puts
puts 'layer-id: The OpsWorks Layer ID where the instances are located.'
puts 'recipes: JSON array of recipes to run, in the format of: \'["cookbook::recipe"]\'. Wrap in single quotes.'
puts 'custom-json: Custom JSON to use for the deployment. Wrap in single quotes.'
exit 1
end
unless `which aws`
puts 'awscli not found!'
usage
end
args = ARGV.dup
# flag check
if args.include? '--single'
args.delete '--single'
SINGLE_INSTANCE = true
else
SINGLE_INSTANCE = false
end
if args.length < 2
usage
end
layer_id = args[0]
recipes = args[1]
custom_json = args[2].nil? ? '' : args[2]
# all instances in layer
instances_command = %|aws opsworks describe-instances --layer-id #{layer_id}|
instances = JSON.parse(`#{instances_command}`)['Instances']
if instances.empty?
puts "Failed to load instances."
puts "Command: #{instances_command}"
exit 1
end
# that are online
instances.delete_if {|x| x['Status'] != 'online' }
# pluck their ids
instance_ids = instances.collect {|x| x['InstanceId'] }
print 'Found online instances: '
p instance_ids
if SINGLE_INSTANCE
instance_ids = instance_ids.take 1
print 'As requested, will only run on a single instance: '
p instance_ids
end
# Find the Stack ID by validating the Layer
layer_command = %|aws opsworks describe-layers --layer-ids #{layer_id}|
layer = JSON.parse(`#{layer_command}`)['Layers'].first
if layer.nil?
puts "Layer '#{layer_id}' was not found!"
exit 1
end
stack_id = layer['StackId']
print 'Found layer with a Stack ID: '
p stack_id
puts 'Creating OpsWorks deployment.'
print 'Using recipes: '
p recipes
unless custom_json.empty?
print 'Using custom JSON: '
p custom_json
end
# kick off the publish recipe
publish_command = %|aws opsworks create-deployment --stack-id #{stack_id} --instance-ids #{instance_ids.join(' ')} --command='{"Name": "execute_recipes", "Args": {"recipes": #{recipes}}}'|
unless custom_json.empty?
publish_command += %| --custom-json='#{custom_json}'|
end
results = `#{publish_command}`
publish_id = JSON.parse(results)['DeploymentId']
if publish_id.empty?
puts "Failed to create publish recipe deploy."
puts "Command: #{publish_command}"
exit 1
end
print 'Deployment ID received: '
p publish_id
status_command = %|aws opsworks describe-deployments --deployment-ids #{publish_id}|
start_time = Time.now
max_time = start_time + 3600
while Time.now < max_time
# sleep first to give it time to run
sleep 5
print "(#{(Time.now - start_time).round} secs) Checking status... "
results = `#{status_command}`
unless results.empty?
status = JSON.parse(results)['Deployments'][0]['Status']
if status == 'successful'
puts "deployment was successful."
exit 0
elsif status == 'failed'
puts "deployment failed!"
exit 1
else
puts status
end
end
end
puts "Deployment '#{publish_id}' on instances #{instance_ids} took over an hour, giving up."
exit 1
| true |
f327b91aacd5a4740e4f45d3b3a7872f1ed1def5
|
Ruby
|
CaptConrado/SillyCode
|
/digiroot.rb
|
UTF-8
| 304 | 3.640625 | 4 |
[] |
no_license
|
# Challenge #122 [Easy] Sum Them Digits
# Answer: 10
num = 1073741824
def spliter challenge
challenge = challenge.to_s.split('')
fill = []
challenge.each do |i|
i_convert = i.to_i
fill.push(i_convert)
end
fill.inject(:+)
end
first_set = spliter num
answer = spliter first_set
puts answer
| true |
086de31f6bb11f9a1295a759a1bd028a7a045210
|
Ruby
|
sajithpremadasa/Bakery
|
/Bakery.rb
|
UTF-8
| 9,612 | 3.21875 | 3 |
[] |
no_license
|
#!/usr/bin/ruby
# ==================================
# Author: Sajith Premadasa
# Date : 01 Dec 2016
# ==================================
require 'minitest/autorun'
# ==================================
# Bakery class Implementation
# Represents a certain bakery
# Bakery sells different types of
# products in differnt pack sizes
# ==================================
class Bakery
attr_accessor :name
attr_accessor :location
attr_accessor :store
attr_accessor :order_manager
def initialize(name, location)
@name = name
@order_manager = OrderManager.new(self)
@store = Store.new
end
def submit_order(id, items)
@order_manager.submit_order(id, items)
end
end
# ==================================
# Store class Implementation
# Responsible of keeping products
# packages
# ==================================
class Store
attr_accessor :products
def initialize
@products = []
# ===================================================
# Sort packs by sizes (ascending) to arrange properly
# ===================================================
vs = add_product('Vegemite Scroll', 'VS5')
mb = add_product('Blueberry Muffin', 'MB11')
cf = add_product('Croissant', 'CF')
vs.add_package(3, 6.99)
vs.add_package(5, 8.99)
vs.packs.sort_by!(&:size)
mb.add_package(2, 9.95)
mb.add_package(5, 16.95)
mb.add_package(8, 24.95)
mb.packs.sort_by!(&:size)
cf.add_package(3, 5.95)
cf.add_package(5, 9.95)
cf.add_package(9, 16.99)
cf.packs.sort_by!(&:size)
end
def add_product(name, code)
product = Product.new(name, code)
@products << product
product
end
end
# ==================================
# OrderManager class Implementation
# Responsible of handling orders
# from the bakery reception
# It will keep track of orders
# ==================================
class OrderManager
attr_accessor :bakery
attr_accessor :orders
def initialize(bakery)
@orders = []
@bakery = bakery
end
def submit_order(id, items)
ord = @orders.select{|x| x.id == id}
if (ord.size > 0)
return "Order id already exists!"
end
if (items.size > 0 )
order = Order.new(id)
@orders << order
items.each do |item|
# identify each item
item.each do |code, qty|
if (qty.to_i <= 0)
return "Invalid order qty:#{qty} for #{code}"
end
products = bakery.store.products.select{|x| x.code == code}
if (products[0] == nil)
return "Invalid product code:#{code}!"
else
min_size = products[0].packs[0].size
if(qty.to_i < min_size)
return "Cannot service order as qty:#{qty} is less than the minimum sized pack:#{min_size}!"
end
order_item = OrderItem.new(products[0], qty)
order.add_item(order_item)
end
end
end
elsif
print "No items found!\n"
return nil
end
package_order(id)
end
def package_order(id)
order = @orders.select{|x| x.id == id}
if (order == nil)
print "Couldn't find the order!\n"
return nil
end
if (order.size != 1)
print "Invalid order size:#{order.size}\n";
return nil
end
prices = []
order[0].items.each do |item|
if (item.product != nil)
item.product.selected_packs = []
remain = item.product.allocate(item.qty.to_i);
if (remain.to_i != 0)
return "Requested qty:#{item.qty} cannot be serviced by existing pack sizes!"
end
price = item.product.calculate()
prices << price
# puts "#{item.qty} #{item.product.code} = $#{price}\n"
end
end
return prices
end
end
# ==================================
# Order class Implementation
# order can consist of combination
# of items
# ==================================
class Order
attr_accessor :id
attr_accessor :items
attr_accessor :selected_packs
def initialize(id)
@id = id
@items = []
# To store the final package arrangement
@selected_packs = []
end
def add_item(item)
@items << item
end
end
# ==================================
# OrderItem class Implementation
# order item consists of the product
# code and the quantity needed
# ==================================
class OrderItem
attr_accessor :code
attr_accessor :qty
attr_accessor :product
def initialize(product, qty)
@product = product
@qty = qty
end
end
# ==================================
# Product class Implementation
# Product has a unique code
# ==================================
class Product
attr_accessor :name
attr_accessor :code
attr_accessor :packs
attr_accessor :selected_packs
def initialize(name, code)
@name = name
@code = code
@packs = []
@selected_packs = []
end
def add_package(qty, price)
pack = Pack.new(self, qty, price)
@packs << pack
end
def allocate(qty)
remaining_qty = nil
# ==============================================
# packs are allocated in large packs first order
# to minimize the packaging space
# ==============================================
@packs.reverse_each do |pack|
remaining_qty = qty - pack.size
if remaining_qty > 0
ret_val = allocate(remaining_qty)
if ret_val == 0
@selected_packs << pack
remaining_qty = 0
break
end
elsif remaining_qty == 0
@selected_packs << pack
break
end
end
remaining_qty
end
def calculate
price = 0.0
@selected_packs.each do |pack|
price += pack.price.to_f
# print "#{pack.size} pack\n"
end
price.round(2)
end
end
# ==================================
# Pack class Implementation
# Pack contains number of products
# ==================================
class Pack
attr_accessor :size
attr_accessor :product
attr_accessor :price
def initialize (product, size, price)
@size = size.to_i
@price = price.to_f
@product = product
end
def add_product(product)
self.product = product
end
end
# ==================================
# Tests
# ==================================
class BakeryTest < Minitest::Test
def setup;
@bakery = Bakery.new('BillCap', 'Richmond')
end
def test_initial_setup
assert(@bakery != nil)
assert(@bakery.store.products.size == 3)
assert(@bakery.store.products[0].packs.size == 2)
assert(@bakery.store.products[1].packs.size == 3)
assert(@bakery.store.products[2].packs.size == 3)
assert(@bakery.store.products[0].packs[0].size == 3)
assert(@bakery.store.products[0].packs[1].size == 5)
assert(@bakery.store.products[0].packs[0].price == 6.99)
assert(@bakery.store.products[0].packs[1].price == 8.99)
assert(@bakery.store.products[1].packs[0].size == 2)
assert(@bakery.store.products[1].packs[1].size == 5)
assert(@bakery.store.products[1].packs[2].size == 8)
assert(@bakery.store.products[1].packs[0].price == 9.95)
assert(@bakery.store.products[1].packs[1].price == 16.95)
assert(@bakery.store.products[1].packs[2].price == 24.95)
assert(@bakery.store.products[2].packs[0].size == 3)
assert(@bakery.store.products[2].packs[1].size == 5)
assert(@bakery.store.products[2].packs[2].size == 9)
assert(@bakery.store.products[2].packs[0].price == 5.95)
assert(@bakery.store.products[2].packs[1].price == 9.95)
assert(@bakery.store.products[2].packs[2].price == 16.99)
assert(@bakery.store.products[0].code == 'VS5')
assert(@bakery.store.products[1].code == 'MB11')
assert(@bakery.store.products[2].code == 'CF')
end
def test_valid_order_should_be_success
@bakery.submit_order('order_1', [{'VS5' => '10'},{'MB11' => '14'}, {'CF' => '13'}])
# 2 * 5 packs from VS5
assert(@bakery.store.products[0].selected_packs.size == 2)
assert(@bakery.store.products[0].selected_packs[0].price == 8.99)
assert(@bakery.store.products[0].selected_packs[1].price == 8.99)
# 3 * 2 packs and 1 * 8 pack from MB11
assert(@bakery.store.products[1].selected_packs.size == 4)
assert(@bakery.store.products[1].selected_packs[0].price == 9.95)
assert(@bakery.store.products[1].selected_packs[1].price == 9.95)
assert(@bakery.store.products[1].selected_packs[2].price == 9.95)
assert(@bakery.store.products[1].selected_packs[3].price == 24.95)
# 1 * 3 pack and 2 * 5 pack
assert(@bakery.store.products[2].selected_packs.size == 3)
assert(@bakery.store.products[2].selected_packs[0].price == 5.95)
assert(@bakery.store.products[2].selected_packs[1].price == 9.95)
assert(@bakery.store.products[2].selected_packs[2].price == 9.95)
end
def test_wrong_product_id_returns_error
rc = @bakery.submit_order('order_2', [{'ABC' => '10'},{'MB11' => '14'}, {'CF' => '13'}])
assert(rc == "Invalid product code:ABC!")
end
def test_invalid_order_qty_returns_error
rc = @bakery.submit_order('order_3', [{'VS5' => '10'},{'MB11' => '14'}, {'CF' => '0'}])
assert(rc == "Invalid order qty:0 for CF")
end
def test_order_id_must_be_unique
rc = @bakery.submit_order('order_3', [{'VS5' => '10'},{'MB11' => '14'}, {'CF' => '0'}])
rc = @bakery.submit_order('order_3', [{'VS5' => '10'},{'MB11' => '14'}, {'CF' => '0'}])
assert(rc == "Order id already exists!")
end
def test_order_qty_must_be_greater_than_minimum_pack_size
rc = @bakery.submit_order('order_x', [{'VS5' => '2'}])
assert(rc == "Cannot service order as qty:2 is less than the minimum sized pack:3!")
end
def test_orders_with_unserviceable_order_qtys_must_be_rejected
rc = @bakery.submit_order('order_z', [{'VS5' => '4'}])
assert(rc == "Requested qty:4 cannot be serviced by existing pack sizes!")
end
def test_exact_qty_of_a_pack_size_should_be_serviced
@bakery.submit_order('order_z', [{'VS5' => '3'}])
# 1 * 3 pack from VS5
assert(@bakery.store.products[0].selected_packs.size == 1)
assert(@bakery.store.products[0].selected_packs[0].price == 6.99)
end
end
| true |
96b66014bed6ac47653c9569aeda862f53b36158
|
Ruby
|
doerte/LearningRuby
|
/8Ex2.rb
|
UTF-8
| 383 | 3.40625 | 3 |
[] |
no_license
|
title = [['Getting Started', 1],['Numbers', 9],['Letters', 13]]
puts 'Table of Contents'.center(50)
puts ''
chapterNum =1
title.each do |table|
tabtit = table[0]
tabpage = table[1]
beginning = 'Chapter ' + chapterNum.to_s + ': ' + tabtit.to_s
ending = 'page ' + tabpage.to_s
puts beginning.ljust(30) + ending.rjust(20)
chapterNum = chapterNum + 1
end
| true |
12c365946208efd45abe3950c41d9d68515dbb21
|
Ruby
|
ruby-stars/lessons
|
/Subjects/Classes-Objects/classes_attr.rb
|
UTF-8
| 392 | 3.734375 | 4 |
[] |
no_license
|
class Friend
attr_accessor :name, :age, :phone_number
def initialize(name, age, phone_number)
@name = name
@age = age
@phone_number = phone_number
end
def present
puts "Hi, my name is #{name}, I am #{age} years old and my phone number is #{phone_number}"
end
end
friend3 = Friend.new('Fernando', 26, 123_456_789)
friend3.present
friend3.age = 123
friend3.present
| true |
410fe26224d9fc24f1d6148f63ed9bed97a5a901
|
Ruby
|
victortyau/CodeEval
|
/Mixed Content/mixed_content.rb
|
UTF-8
| 845 | 3.296875 | 3 |
[] |
no_license
|
class Mix
def initialize
@lines = ""
open_file()
end
def open_file
file_name = ARGV[0]
if File.exist?(file_name)
@lines = IO.readlines(file_name);
end
end
def split_data
@lines.each do |line|
line.delete!("\n")
array = line.split(",")
string = ""
number = ""
array.each do |elem|
if elem =~ /\d/
number += elem + ","
else
string += elem + ","
end
end
number =number.chomp(',')
string = string.chomp(',')
if number.length > 0 && string.length == 0
puts number.gsub(/\s+/, "")
elsif number.length == 0 && string.length > 0
puts string.gsub(/\s+/, "")
else
puts string.gsub(/\s+/, "") + "|" +number.gsub(/\s+/, "")
end
end
end
end
m = Mix.new
m.split_data
| true |
f43b4eee08d2a2252d968e39c17a760573bd1a46
|
Ruby
|
lukepistolesi/CircularDependecyTest
|
/spec/unit/models/node_spec.rb
|
UTF-8
| 1,828 | 2.578125 | 3 |
[] |
no_license
|
require_relative '../../spec_helper'
require_relative '../../../circular_dep_app/models/node'
module CircularDepApp::Models
describe Node do
describe :initialize do
it 'sets the node name' do
node = Node.new 'My Name'
expect(node.name).to eql 'My Name'
end
it 'sets the outbound collection to empty' do
node = Node.new 'My Name'
expect(node.outbounds).to be_empty
end
it 'sets the inbound collection to empty' do
node = Node.new 'My Name'
expect(node.inbounds).to be_empty
end
end
describe :add_outbound do
let(:other_node) { 'Other' }
let(:node) { Node.new 'A Name' }
subject { node.add_outbound other_node }
it 'adds the given node to the list of the outbound nodes' do
subject
expect(node.outbounds).to eql Set.new([other_node])
end
it 'does nto add twice the same node' do
node.add_outbound other_node
subject
expect(node.outbounds).to eql Set.new([other_node])
end
it 'raises exception when no node provided' do
expect{node.add_outbound nil}.to raise_error 'No node provided'
end
end
describe :add_inbound do
let(:other_node) { 'Other' }
let(:node) { Node.new 'A Name' }
subject { node.add_inbound other_node }
it 'adds the given node to the list of the inbound nodes' do
subject
expect(node.inbounds).to eql Set.new([other_node])
end
it 'does nto add twice the same node' do
node.add_inbound other_node
subject
expect(node.inbounds).to eql Set.new([other_node])
end
it 'raises exception when no node provided' do
expect{node.add_inbound nil}.to raise_error 'No node provided'
end
end
end
end
| true |
2c5cd227049cb6afef9ba2eb915c513f2b7fb6a8
|
Ruby
|
kukareka/lemon_fresh
|
/app/word_counter.rb
|
UTF-8
| 1,259 | 2.9375 | 3 |
[] |
no_license
|
require 'influxdb'
require 'securerandom'
class WordCounter
INFLUX_DB_NAME = ENV['INFLUX_DB_NAME'] || 'word_count'
INFLUX_HOST = ENV['INFLUX_HOST'] || 'localhost'
INFLUX_PORT = ENV['INFLUX_PORT'] || 8086
def add(word)
# InfluxDB will overwrite points with same tags/timestamp, so need either to hack the tags or use Telegraf to
# aggregate the measurements of duplicated words. Hacking the tags for now but it is a bad choice for production.
#
# https://docs.influxdata.com/influxdb/v1.6/troubleshooting/frequently-asked-questions/#how-does-influxdb-handle-duplicate-points
influxdb.write_point 'words',
values: { value: 1 },
tags: { measurement_id: SecureRandom.hex, word: word.downcase }
end
def count(word)
influxdb.query('select count(*) from words where word=%{word}', params: { word: word }) do |_, _, (point)|
# Using `(point)` shortcut because we need only one aggregated point
return point['count_value']
end
return 0
end
def influxdb
# Need to check how connection pooling works in InfluxDB client, doing it simple for now
@influxdb ||= InfluxDB::Client.new INFLUX_DB_NAME, host: INFLUX_HOST, port: INFLUX_PORT
end
end
| true |
17ee4bef65f6cf8e4ba7b06d6d9d088a34bea5ba
|
Ruby
|
augustinevt/learn-how-to-program-clone
|
/app/models/lesson.rb
|
UTF-8
| 414 | 2.546875 | 3 |
[] |
no_license
|
class Lesson < ActiveRecord::Base
belongs_to :course
has_many :sections
def next
new_lesson = Lesson.find_by(number: self.number + 1, course_id: self.course_id)
if new_lesson
new_lesson
else
nil
end
end
def previous
new_lesson = Lesson.find_by(number: self.number - 1, course_id: self.course_id)
if new_lesson
new_lesson
else
nil
end
end
end
| true |
639da70bad5edbeb048db66810b298908005c27e
|
Ruby
|
alejandroclaro/katas
|
/ruby/roman-numerals/test_roman_numerals.rb
|
UTF-8
| 1,259 | 3.5 | 4 |
[] |
no_license
|
#
# Roman numerals code kata unit tests.
#
require_relative "roman_numerals"
require "test/unit"
class TestRomanNumerals < Test::Unit::TestCase
def test_to_roman_1
assert_equal("I", to_roman(1))
end
def test_to_roman_2
assert_equal("II", to_roman(2))
end
def test_roman_3
assert_equal("III", to_roman(3))
end
def test_roman_4
assert_equal("IV", to_roman(4))
end
def test_roman_5
assert_equal("V", to_roman(5))
end
def test_roman_9
assert_equal("IX", to_roman(9))
end
def test_roman_10
assert_equal("X", to_roman(10))
end
def test_roman_40
assert_equal("XL", to_roman(40))
end
def test_roman_50
assert_equal("L", to_roman(50))
end
def test_roman_90
assert_equal("XC", to_roman(90))
end
def test_roman_100
assert_equal("C", to_roman(100))
end
def test_roman_400
assert_equal("CD", to_roman(400))
end
def test_roman_500
assert_equal("D", to_roman(500))
end
def test_roman_900
assert_equal("CM", to_roman(900))
end
def test_roman_1000
assert_equal("M", to_roman(1000))
end
def test_roman_2378
assert_equal("MMCCCLXXVIII", to_roman(2378))
end
end
| true |
e4045dc21b6b5aff1791418979d9be7d87ae8324
|
Ruby
|
awebneck/crypto-demo
|
/block-encrypt-authenticate
|
UTF-8
| 550 | 2.8125 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
require 'openssl'
require 'base64'
message = ARGV[0]
cipher = OpenSSL::Cipher::AES128.new :CBC
cipher.encrypt
if ARGV[1]
key = cipher.key = Base64.strict_decode64(ARGV[1])
else
key = cipher.random_key
end
iv = cipher.random_iv
ciphertext = cipher.update(message) + cipher.final
hmac = OpenSSL::HMAC.new key, OpenSSL::Digest::SHA512.new
hmac << ciphertext
puts "Key: #{Base64.strict_encode64(key)}"
puts "IV: #{Base64.strict_encode64(iv)}"
puts "Ciphertext: #{Base64.strict_encode64(ciphertext)}"
puts "Tag: #{hmac.to_s}"
| true |
a1a2f0307fdf4eb90d6bd84472ca187584c2d361
|
Ruby
|
ltrainor1/ttt-10-current-player-v-000
|
/lib/current_player.rb
|
UTF-8
| 324 | 3.84375 | 4 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def turn_count(board)
turns = 0
board.each do |index|
if index == "X" || index == "O"
turns += 1
else
turns = turns
end
end
return turns
end
def current_player(board)
moves = turn_count(board)
remainder = moves % 2
if remainder == 0
return "X"
else
return "O"
end
end
| true |
274e012b635fff4e9bbdd697dce5ed1a5cf76880
|
Ruby
|
larry-cherry/phase-0-tracks
|
/ruby/iteration.rb
|
UTF-8
| 2,560 | 4.125 | 4 |
[] |
no_license
|
#create a method to convert fahrenheit to celcius and pass block into method
def f_to_c
puts "Please provide a temperature in Fahrenheit:"
fahrenheit = gets.chomp.to_i
celcius = ((fahrenheit - 32) * 5.0/9.0).round(2)
yield(fahrenheit, celcius)
end
f_to_c { |fahrenheit, celcius| puts "#{fahrenheit} converted to Celcius equals #{celcius} degrees." }
fruits = ["apples", "oranges", "grapes", "bananas", "pears"]
will_farrell_characters = {
talladega_nights: "Ricky Bobby",
elf: "Buddy",
semi_pro: "Jackie Moon",
anchorman: "Ron Burgundy"
}
puts "This is the array before we run .each"
p fruits
puts "This is the array after running .each on it"
fruits.each { |fruit| puts fruit }
puts "This is the array befor we run .map!"
p fruits
puts "This is the array after we run .map!"
fruits.map! { |fruit| puts fruit.chop}
puts "This is the hash before we run .each"
p will_farrell_characters
puts "This is the hash after we run .each"
will_farrell_characters.each { |movie, character| puts "Will Farrell plays #{character} in #{movie}"}
#Release 2: Use the Documentation
letters = ["a", "B", "c", "D", "e"]
numbers = {
1 => "one",
2 => "two",
3 => "three",
4 => "four",
5 => "five"
}
#A method that iterates through the items, deleting any that meet a certain
#condition (for example, deleting any numbers that are less than 5).
p letters.delete_if { |letter| letter.downcase == letter }
p numbers.delete_if { |digit, word| digit < 3}
#A method that filters a data structure for only items that do satisfy a certain
#condition (for example, keeping any numbers that are less than 5).
letters = ["a", "B", "c", "D", "e"]
numbers = {
1 => "one",
2 => "two",
3 => "three",
4 => "four",
5 => "five"
}
p letters.keep_if { |letter| letter.downcase == letter }
p numbers.keep_if { |digit, word| digit > 3}
#A different method that filters a data structure for only items
#satisfying a certain condition -- Ruby offers several options!
letters = ["a", "B", "c", "D", "e"]
numbers = {
1 => "one",
2 => "two",
3 => "three",
4 => "four",
5 => "five"
}
p letters.select { |letter| letter.downcase == letter }
p numbers.select { |digit, word| digit > 3}
#A method that will remove items from a data structure until the condition in the block
#evaluates to false, then stops (you may not find a perfectly working option for the hash, and that's okay).
p letters.drop_while { |letter| letter.downcase == letter }
p numbers.drop_while { |digit, word| word != "four"}
| true |
a95fefccd85f8a3e81891a2bd9328c97fc622b02
|
Ruby
|
LiamCusack/rails-engine
|
/spec/requests/api/v1/merchants_request_spec.rb
|
UTF-8
| 2,620 | 2.578125 | 3 |
[] |
no_license
|
require 'rails_helper'
require 'faker'
describe "Merchant API" do
describe "Merchant Index" do
it "sends a list of merchants" do
create_list(:merchant, 3)
get '/api/v1/merchants'
merchants = JSON.parse(response.body, symbolize_names: true)
expect(response).to be_successful
expect(merchants[:data].count).to eq(3)
merchants[:data].each do |merchant|
expect(merchant).to have_key(:id)
expect(merchant[:id].to_i).to be_an(Integer)
expect(merchant[:attributes]).to have_key(:name)
expect(merchant[:attributes][:name]).to be_an(String)
end
end
it "defaults to 20 merchants returned per page" do
create_list(:merchant, 30)
get '/api/v1/merchants'
merchants = JSON.parse(response.body, symbolize_names: true)
expect(response).to be_successful
expect(merchants[:data].count).to eq(20)
expect(merchants[:data].count).to_not eq(30)
end
it "allows you to choose the the number of results per page and the page number that are displayed" do
create_list(:merchant, 30)
get '/api/v1/merchants?per_page=10&page=2'
merchants = JSON.parse(response.body, symbolize_names: true)
expect(response).to be_successful
expect(merchants[:data].count).to eq(10)
expect(merchants[:data].last[:id].to_i - merchants[:data].first[:id].to_i).to eq(9)
end
it "returns page one if specified page number is less than 1" do
create_list(:merchant, 30)
get '/api/v1/merchants?per_page=10&page=2'
merchants = JSON.parse(response.body, symbolize_names: true)
expect(response).to be_successful
expect(merchants[:data].count).to eq(10)
expect(merchants[:data].last[:id].to_i - merchants[:data].first[:id].to_i).to eq(9)
end
end
describe "Merchant Show" do
it "can get one merchant by its id" do
id = create(:merchant).id
get "/api/v1/merchants/#{id}"
merchant = JSON.parse(response.body, symbolize_names: true)
expect(response).to be_successful
expect(merchant[:data]).to have_key(:id)
expect(merchant[:data][:id].to_i).to be_an(Integer)
expect(merchant[:data][:attributes]).to have_key(:name)
expect(merchant[:data][:attributes][:name]).to be_an(String)
end
it "returns 404 if a bad/nonexistant merchant id is queried" do
get "/api/v1/merchants/1000000"
expect(response.status).to eq(404)
end
it "returns 404 if a string id is queried" do
get "/api/v1/merchants/'1'"
expect(response.status).to eq(404)
end
end
end
| true |
926fc0e8901ef231106fa964b2e8b09a4d1a7241
|
Ruby
|
stephan-nordnes-eriksen/ruby_ship
|
/bin/shipyard/darwin_ruby/lib/ruby/gems/2.3.0/gems/minitest-5.8.3/test/minitest/test_minitest_mock.rb
|
UTF-8
| 10,511 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
require "minitest/autorun"
class TestMinitestMock < Minitest::Test
parallelize_me!
def setup
@mock = Minitest::Mock.new.expect(:foo, nil)
@mock.expect(:meaning_of_life, 42)
end
def test_create_stub_method
assert_nil @mock.foo
end
def test_allow_return_value_specification
assert_equal 42, @mock.meaning_of_life
end
def test_blow_up_if_not_called
@mock.foo
util_verify_bad "expected meaning_of_life() => 42"
end
def test_not_blow_up_if_everything_called
@mock.foo
@mock.meaning_of_life
assert @mock.verify
end
def test_allow_expectations_to_be_added_after_creation
@mock.expect(:bar, true)
assert @mock.bar
end
def test_not_verify_if_new_expected_method_is_not_called
@mock.foo
@mock.meaning_of_life
@mock.expect(:bar, true)
util_verify_bad "expected bar() => true"
end
def test_blow_up_on_wrong_number_of_arguments
@mock.foo
@mock.meaning_of_life
@mock.expect(:sum, 3, [1, 2])
e = assert_raises ArgumentError do
@mock.sum
end
assert_equal "mocked method :sum expects 2 arguments, got 0", e.message
end
def test_return_mock_does_not_raise
retval = Minitest::Mock.new
mock = Minitest::Mock.new
mock.expect(:foo, retval)
mock.foo
assert mock.verify
end
def test_mock_args_does_not_raise
skip "non-opaque use of ==" if maglev?
arg = Minitest::Mock.new
mock = Minitest::Mock.new
mock.expect(:foo, nil, [arg])
mock.foo(arg)
assert mock.verify
end
def test_set_expectation_on_special_methods
mock = Minitest::Mock.new
mock.expect :object_id, "received object_id"
assert_equal "received object_id", mock.object_id
mock.expect :respond_to_missing?, "received respond_to_missing?"
assert_equal "received respond_to_missing?", mock.respond_to_missing?
mock.expect :===, "received ==="
assert_equal "received ===", mock.===
mock.expect :inspect, "received inspect"
assert_equal "received inspect", mock.inspect
mock.expect :to_s, "received to_s"
assert_equal "received to_s", mock.to_s
mock.expect :public_send, "received public_send"
assert_equal "received public_send", mock.public_send
mock.expect :send, "received send"
assert_equal "received send", mock.send
assert mock.verify
end
def test_expectations_can_be_satisfied_via_send
@mock.send :foo
@mock.send :meaning_of_life
assert @mock.verify
end
def test_expectations_can_be_satisfied_via_public_send
skip "Doesn't run on 1.8" if RUBY_VERSION < "1.9"
@mock.public_send :foo
@mock.public_send :meaning_of_life
assert @mock.verify
end
def test_blow_up_on_wrong_arguments
@mock.foo
@mock.meaning_of_life
@mock.expect(:sum, 3, [1, 2])
e = assert_raises MockExpectationError do
@mock.sum(2, 4)
end
exp = "mocked method :sum called with unexpected arguments [2, 4]"
assert_equal exp, e.message
end
def test_expect_with_non_array_args
e = assert_raises ArgumentError do
@mock.expect :blah, 3, false
end
assert_equal "args must be an array", e.message
end
def test_respond_appropriately
assert @mock.respond_to?(:foo)
assert @mock.respond_to?(:foo, true)
assert @mock.respond_to?("foo")
assert [email protected]_to?(:bar)
end
def test_no_method_error_on_unexpected_methods
e = assert_raises NoMethodError do
@mock.bar
end
expected = "unmocked method :bar, expected one of [:foo, :meaning_of_life]"
assert_equal expected, e.message
end
def test_assign_per_mock_return_values
a = Minitest::Mock.new
b = Minitest::Mock.new
a.expect(:foo, :a)
b.expect(:foo, :b)
assert_equal :a, a.foo
assert_equal :b, b.foo
end
def test_do_not_create_stub_method_on_new_mocks
a = Minitest::Mock.new
a.expect(:foo, :a)
assert !Minitest::Mock.new.respond_to?(:foo)
end
def test_mock_is_a_blank_slate
@mock.expect :kind_of?, true, [Fixnum]
@mock.expect :==, true, [1]
assert @mock.kind_of?(Fixnum), "didn't mock :kind_of\?"
assert @mock == 1, "didn't mock :=="
end
def test_verify_allows_called_args_to_be_loosely_specified
mock = Minitest::Mock.new
mock.expect :loose_expectation, true, [Integer]
mock.loose_expectation 1
assert mock.verify
end
def test_verify_raises_with_strict_args
mock = Minitest::Mock.new
mock.expect :strict_expectation, true, [2]
e = assert_raises MockExpectationError do
mock.strict_expectation 1
end
exp = "mocked method :strict_expectation called with unexpected arguments [1]"
assert_equal exp, e.message
end
def test_method_missing_empty
mock = Minitest::Mock.new
mock.expect :a, nil
mock.a
e = assert_raises MockExpectationError do
mock.a
end
assert_equal "No more expects available for :a: []", e.message
end
def test_same_method_expects_are_verified_when_all_called
mock = Minitest::Mock.new
mock.expect :foo, nil, [:bar]
mock.expect :foo, nil, [:baz]
mock.foo :bar
mock.foo :baz
assert mock.verify
end
def test_same_method_expects_blow_up_when_not_all_called
mock = Minitest::Mock.new
mock.expect :foo, nil, [:bar]
mock.expect :foo, nil, [:baz]
mock.foo :bar
e = assert_raises(MockExpectationError) { mock.verify }
exp = "expected foo(:baz) => nil, got [foo(:bar) => nil]"
assert_equal exp, e.message
end
def test_same_method_expects_with_same_args_blow_up_when_not_all_called
mock = Minitest::Mock.new
mock.expect :foo, nil, [:bar]
mock.expect :foo, nil, [:bar]
mock.foo :bar
e = assert_raises(MockExpectationError) { mock.verify }
exp = "expected foo(:bar) => nil, got [foo(:bar) => nil]"
assert_equal exp, e.message
end
def test_verify_passes_when_mock_block_returns_true
mock = Minitest::Mock.new
mock.expect :foo, nil do
true
end
mock.foo
assert mock.verify
end
def test_mock_block_is_passed_function_params
arg1, arg2, arg3 = :bar, [1, 2, 3], { :a => "a" }
mock = Minitest::Mock.new
mock.expect :foo, nil do |a1, a2, a3|
a1 == arg1 && a2 == arg2 && a3 == arg3
end
mock.foo arg1, arg2, arg3
assert mock.verify
end
def test_mock_block_is_passed_function_block
mock = Minitest::Mock.new
block = proc { "bar" }
mock.expect :foo, nil do |arg, &blk|
arg == "foo" &&
blk == block
end
mock.foo "foo", &block
assert mock.verify
end
def test_verify_fails_when_mock_block_returns_false
mock = Minitest::Mock.new
mock.expect :foo, nil do
false
end
e = assert_raises(MockExpectationError) { mock.foo }
exp = "mocked method :foo failed block w/ []"
assert_equal exp, e.message
end
def test_mock_block_throws_if_args_passed
mock = Minitest::Mock.new
e = assert_raises(ArgumentError) do
mock.expect :foo, nil, [:a, :b, :c] do
true
end
end
exp = "args ignored when block given"
assert_equal exp, e.message
end
def test_mock_returns_retval_when_called_with_block
mock = Minitest::Mock.new
mock.expect(:foo, 32) do
true
end
rs = mock.foo
assert_equal rs, 32
end
def util_verify_bad exp
e = assert_raises MockExpectationError do
@mock.verify
end
assert_equal exp, e.message
end
def test_mock_called_via_send
mock = Minitest::Mock.new
mock.expect(:foo, true)
mock.send :foo
mock.verify
end
def test_mock_called_via___send__
mock = Minitest::Mock.new
mock.expect(:foo, true)
mock.__send__ :foo
mock.verify
end
def test_mock_called_via_send_with_args
mock = Minitest::Mock.new
mock.expect(:foo, true, [1, 2, 3])
mock.send(:foo, 1, 2, 3)
mock.verify
end
end
require "minitest/metametameta"
class TestMinitestStub < Minitest::Test
parallelize_me!
def setup
super
Minitest::Test.reset
@tc = Minitest::Test.new "fake tc"
@assertion_count = 1
end
def teardown
super
assert_equal @assertion_count, @tc.assertions
end
class Time
def self.now
24
end
end
def assert_stub val_or_callable
@assertion_count += 1
t = Time.now.to_i
Time.stub :now, val_or_callable do
@tc.assert_equal 42, Time.now
end
@tc.assert_operator Time.now.to_i, :>=, t
end
def test_stub_private_module_method
@assertion_count += 1
t0 = Time.now
self.stub :sleep, nil do
@tc.assert_nil sleep(10)
end
@tc.assert_operator Time.now - t0, :<=, 1
end
def test_stub_private_module_method_indirect
@assertion_count += 1
fail_clapper = Class.new do
def fail_clap
raise
:clap
end
end.new
fail_clapper.stub :raise, nil do |safe_clapper|
@tc.assert_equal :clap, safe_clapper.fail_clap # either form works
@tc.assert_equal :clap, fail_clapper.fail_clap # yay closures
end
end
def test_stub_public_module_method
Math.stub :log10, :stubbed do
@tc.assert_equal :stubbed, Math.log10(1000)
end
end
def test_stub_value
assert_stub 42
end
def test_stub_block
assert_stub lambda { 42 }
end
def test_stub_block_args
@assertion_count += 1
t = Time.now.to_i
Time.stub :now, lambda { |n| n * 2 } do
@tc.assert_equal 42, Time.now(21)
end
@tc.assert_operator Time.now.to_i, :>=, t
end
def test_stub_callable
obj = Object.new
def obj.call
42
end
assert_stub obj
end
def test_stub_yield_self
obj = "foo"
val = obj.stub :to_s, "bar" do |s|
s.to_s
end
@tc.assert_equal "bar", val
end
def test_dynamic_method
@assertion_count = 2
dynamic = Class.new do
def self.respond_to?(meth)
meth == :found
end
def self.method_missing(meth, *args, &block)
if meth == :found
false
else
super
end
end
end
val = dynamic.stub(:found, true) do |s|
s.found
end
@tc.assert_equal true, val
@tc.assert_equal false, dynamic.found
end
def test_mock_with_yield
mock = Minitest::Mock.new
mock.expect(:write, true) do
true
end
rs = nil
File.stub(:open, true, mock) do
File.open("foo.txt", "r") do |f|
rs = f.write
end
end
@tc.assert_equal true, rs
end
end
| true |
227036bf9b1fda09a03d787772e80d72725a80eb
|
Ruby
|
TinyGoat/freshrewards
|
/app/models/profile.rb
|
UTF-8
| 1,214 | 2.71875 | 3 |
[] |
no_license
|
class Profile
def initialize(customer)
@customer = customer
end
attr_reader :customer
delegate :id, to: :customer
def current_reward_progress
@customer.balance
end
def amount_remaining_for_current_reward
reward_threshold - current_reward_progress
end
def reward_threshold
@customer.reward_threshold
end
def rewards_count
@customer.rewards.size
end
def full_name
[@customer.first_name, @customer.last_name].join(' ')
end
def first_name
@customer.first_name
end
def street
@customer.street
end
def city_state_zip_code
[city_and_state, @customer.zip_code].join(' ')
end
def phone_number
[area_code, exchange, subscriber_number].join('-')
end
def email_address
@customer.email_address
end
def rewards
@customer.rewards.map { |date| date.strftime('%B %d, %Y') }
end
def member_status
@customer.gold_member? ? 'Gold' : 'Club'
end
private
def area_code
@customer.phone_number[0..2]
end
def exchange
@customer.phone_number[3..5]
end
def subscriber_number
@customer.phone_number[6..9]
end
def city_and_state
[@customer.city, @customer.state].join(', ')
end
end
| true |
7624c659d58e3664025ae597a9ffff96be504f6b
|
Ruby
|
aha-app/calculated_attributes
|
/spec/lib/calculated_attributes_spec.rb
|
UTF-8
| 4,650 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
require 'spec_helper'
def model_scoped(klass)
if klass.respond_to? :scoped
klass.scoped
else
klass.all
end
end
describe 'calculated_attributes' do
it 'includes calculated attributes' do
expect(model_scoped(Post).calculated(:comments_count).first.comments_count).to eq(1)
end
it 'includes parametric calculated attributes' do
expect(model_scoped(Post).calculated(comments_by_user: [User.where(username: 'unused').first])
.first.comments_by_user).to eq(0)
expect(model_scoped(Post).calculated(comments_by_user: [User.where(username: 'test').first])
.first.comments_by_user).to eq(1)
end
it 'includes multiple calculated attributes' do
post = model_scoped(Post).calculated(:comments_count, :comments_two).first
expect(post.comments_count).to eq(1)
expect(post.comments_two).to eq(1)
end
it 'includes chained calculated attributes' do
post = model_scoped(Post).calculated(:comments_count).calculated(:comments_two).first
expect(post.comments_count).to eq(1)
expect(post.comments_two).to eq(1)
end
it 'nests with where query' do
expect(Post.where(id: 1).calculated(:comments_count).first.comments_count).to eq(1)
end
it 'nests with order query' do
expect(Post.order('id DESC').calculated(:comments_count).first.id).to eq(Post.count)
end
it 'allows access via model instance method' do
expect(Post.first.calculated(:comments_count).comments_count).to eq(1)
end
it 'allows access via model instance method with parameters' do
expect(Post.first.calculated(comments_by_user: [User.where(username: 'test').first]).comments_by_user).to eq(1)
end
it 'allows anonymous access via model instance method' do
expect(Post.first.comments_count).to eq(1)
end
it 'allows access via model instance method with parameters' do
expect(Post.first.comments_by_user(User.where(username: 'test').first)).to eq(1)
end
it 'allows anonymous access via model instance method with STI and lambda on base class' do
expect(Tutorial.first.comments_count).to eq(1)
end
it 'allows anonymous access via model instance method with STI and lambda on subclass' do
expect(Article.first.sub_comments).to eq(1)
end
it 'does not allow anonymous access for nonexisting calculated block' do
expect { Post.first.some_attr }.to raise_error(NoMethodError)
end
it 'does not allow anonymous access for nonexisting calculated block with STI' do
expect { Tutorial.first.some_attr }.to raise_error(NoMethodError)
end
it 'allows access to multiple calculated attributes via model instance method' do
post = Post.first.calculated(:comments_count, :comments_two)
expect(post.comments_count).to eq(1)
expect(post.comments_two).to eq(1)
end
it 'allows attributes to be defined using AREL' do
expect(model_scoped(Post).calculated(:comments_arel).first.comments_arel).to eq(1)
end
it 'allows attributes to be defined using class that responds to to_sql' do
expect(model_scoped(Post).calculated(:comments_to_sql).first.comments_to_sql).to eq(1)
end
it 'maintains previous scope' do
expect(Post.where(text: 'First post!').calculated(:comments_count).first.comments_count).to eq(1)
expect(Post.where("posts.text = 'First post!'").calculated(:comments_count).first.comments_count).to eq(1)
end
it 'maintains subsequent scope' do
expect(model_scoped(Post).calculated(:comments_count).where(text: 'First post!').first.comments_count).to eq(1)
expect(model_scoped(Post).calculated(:comments_count).where("posts.text = 'First post!'").first.comments_count).to eq(1)
end
it 'includes calculated attributes with STI and lambda on base class' do
expect(model_scoped(Tutorial).calculated(:comments_count).first.comments_count).to eq(1)
end
it 'includes calculated attributes with STI and lambda on subclass' do
expect(model_scoped(Article).calculated(:sub_comments).first.sub_comments).to eq(1)
end
context 'when joining models' do
it 'includes calculated attributes' do
expect(model_scoped(Post).joins(:comments).calculated(:comments_count).first.comments_count).to eq(1)
end
context 'when conditions are specified on the joined table' do
it 'includes calculated models' do
scope = model_scoped(Post).joins(:comments)
expect(scope.first.comments_count).to eq(1)
end
end
end
context 'when eager loading models' do
it 'includes calculated attributes' do
scope = model_scoped(Post).includes(:comments).references(:comments)
expect(scope.first.comments_count).to eq(1)
end
end
end
| true |
c8778afcc93829d3ed521515e1746341555ba2e3
|
Ruby
|
KalebGz/Flatiron
|
/code/module-2/Because-project/app/models/reply.rb
|
UTF-8
| 1,187 | 2.5625 | 3 |
[] |
no_license
|
class Reply < ApplicationRecord
belongs_to :comment
belongs_to :post
belongs_to :user
validates :content, presence: true, if: :because?, unless: -> { content.include?('?')}
validates :content, length: { minimum: 250, message: "A post must contain at least 250 characters, or include a question mark." }, unless: -> { content.include?('?')}
def because?
self.content.include?('because') || self.content.include?('reason') || self.content.include?('why') || self.content.include?("Because") || self.content.include?("Reason") || self.content.include?('Why')
end
def reply_age
days = DateTime.now.mjd - created_at.to_date.mjd
year = days/365
months = days/30
weeks = days/7
remaining_days = days%365
if days/365 > 1
return "#{year.to_i} years old"
elsif days/30 > 1
return "#{moths.to_i} months old"
elsif days/7 > 1
return "#{weeks.to_i} weeks old"
else
return "#{days} days old"
end
end
def user_name
self.user.name
end
def user_image
self.user.image
end
end
| true |
41e835fe591f41305bdd4a6609029d5cdedda4ec
|
Ruby
|
wasabigeek/aoc2020
|
/day2/day2.rb
|
UTF-8
| 1,574 | 3.296875 | 3 |
[] |
no_license
|
require_relative '../helpers'
class PartOne
include FileHelpers
INPUT_REGEX = /(\d+)-(\d+) ([a-z]): ([a-z]+)/
def check_passwords_in_file(path)
passwords = readlines_from_file(path)
valid_passwords = passwords.reduce(0) do |count, password|
count += 1 if check_password(password)
count
end
end
# Could do this in one pass through the string - but this is at least a bit more readable
# Also, it's not _really_ a password that is input, but I'll leave the naming decision for another day
def check_password(input)
_, min_str, max_str, letter, password = input.match(INPUT_REGEX).to_a
min, max = min_str.to_i, max_str.to_i
matches = password.split('').reduce(0) do |count, char|
count += 1 if char == letter
count
end
matches <= max && matches >= min
end
end
class PartTwo
include FileHelpers
INPUT_REGEX = /(\d+)-(\d+) ([a-z]): ([a-z]+)/
def check_passwords_in_file(path)
passwords = readlines_from_file(path)
valid_passwords = passwords.reduce(0) do |count, password|
count += 1 if check_password(password)
count
end
end
def check_password(input)
# resisting the desire to abstract a Policy for now
_, first_index_str, second_index_str, letter, password = input.match(INPUT_REGEX).to_a
first_index, second_index = first_index_str.to_i - 1, second_index_str.to_i - 1
[
password[first_index],
password[second_index]
].count { |char| char == letter } == 1
end
end
# puts PartOne.new.check_passwords_in_file('day2/input.txt')
| true |
f80c16444952052c36078d9cc0fe2141087b336a
|
Ruby
|
tuenti/sensu-community-plugins
|
/plugins/etcd/etcd-metrics.rb
|
UTF-8
| 1,868 | 2.515625 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
#! /usr/bin/env ruby
#
# etcd-metrics
#
# DESCRIPTION:
# This plugin pulls stats out of an etcd node
#
# OUTPUT:
# metric data
#
# PLATFORMS:
# Linux
#
# DEPENDENCIES:
# gem: sensu-plugin
# gem: etcd
# gem: socket
#
# USAGE:
# #YELLOW
#
# NOTES:
#
# LICENSE:
# Copyright (c) 2014, Sean Clerkin
# Released under the same terms as Sensu (the MIT license); see LICENSE
# for details.
#
require 'rubygems' if RUBY_VERSION < '1.9.0'
require 'sensu-plugin/metric/cli'
require 'etcd'
require 'socket'
class EtcdMetrics < Sensu::Plugin::Metric::CLI::Graphite
option :scheme,
description: 'Metric naming scheme',
short: '-s SCHEME',
long: '--scheme SCHEME',
default: "#{Socket.gethostname}.etcd"
option :etcd_host,
description: 'Etcd host, defaults to localhost',
short: '-h HOST',
long: '--host HOST',
default: 'localhost'
option :etcd_port,
description: 'Etcd port, defaults to 4001',
short: '-p PORT',
long: '--port PORT',
default: '4001'
option :leader_stats,
description: 'Show leader stats',
short: '-l',
long: '--leader-stats',
boolean: true,
default: false
def run
client = Etcd.client(host: config[:etcd_host], port: config[:etcd_port])
client.stats(:self).each do |k, v|
output([config[:scheme], 'self', k].join('.'), v) if v.is_a? Integer
end
client.stats(:store).each do |k, v|
output([config[:scheme], 'store', k].join('.'), v)
end
if config[:leader_stats]
client.stats(:leader)['followers'].each do |follower, fv|
fv.each do |metric, mv|
mv.each do |submetric, sv|
output([config[:scheme], 'leader', follower, metric, submetric].join('.'), sv)
end
end
end
end
ok
end
end
| true |
b469b5b8b3a9c2b31a9eaf368d74e1094b2e0bf8
|
Ruby
|
bankair/rt
|
/features/step_definitions/materials.rb
|
UTF-8
| 2,781 | 2.515625 | 3 |
[] |
no_license
|
require 'material'
Given("m ← material") do
@m = Material.new
end
Then("m.color = color {int}, {int}, {int}") do |int, int2, int3|
expect(@m.color).to eq(Color.new(int, int2, int3))
end
Then("m.ambient = {float}") do |float|
expect(@m.ambient).to eq(float)
end
Then("m.diffuse = {float}") do |float|
expect(@m.diffuse).to eq(float)
end
Then("m.specular = {float}") do |float|
expect(@m.specular).to eq(float)
end
Then("m.shininess = {float}") do |float|
expect(@m.shininess).to eq(float)
end
Given("eyev ← vector {float}, {float}, {float}") do |float, float2, float3|
@eyev = Tuple.vector(float, float2, float3)
end
Given("normalv ← vector {float}, {float}, {float}") do |float, float2, float3|
@normalv = Tuple.vector(float, float2, float3)
end
Given("light ← point_light point {int}, {int}, {int}, color {int}, {int}, {int}") do |int, int2, int3, int4, int5, int6|
@light = Light::Point.new(
Tuple.point(int, int2, int3),
Color.new(int4, int5, int6)
)
end
When("result ← lighting m, light, position, eyev, normalv") do
@result = @m.lighting(Sphere.new, @light, @position, @eyev, @normalv, false)
end
Then("result = color {float}, {float}, {float}") do |float, float2, float3|
expect(@result.red).to be_within(0.001).of(float)
expect(@result.green).to be_within(0.001).of(float2)
expect(@result.blue).to be_within(0.001).of(float3)
end
Given("in_shadow ← true") do
@in_shadow = true
end
When("result ← lighting m, light, position, eyev, normalv, in_shadow") do
@result = @m.lighting(Sphere.new, @light, @position, @eyev, @normalv, @in_shadow)
end
Given("m.pattern ← stripe_pattern color {int}, {int}, {int}, color {int}, {int}, {int}") do |int, int2, int3, int4, int5, int6|
@m.pattern = Pattern::Stripe.new(
Color.new(int, int2, int3),
Color.new(int4, int5, int6)
)
end
Given("m.ambient ← {float}") do |float|
@m.ambient = float
end
Given("m.diffuse ← {float}") do |float|
@m.diffuse = float
end
Given("m.specular ← {float}") do |float|
@m.specular = float
end
Given("light ← point_light point {float}, {float}, {float}, color {float}, {float}, {float}") do |float, float2, float3, float4, float5, float6|
@light = Light::Point.new(Tuple.point(float, float2, float3), Color.new(float4, float5, float6))
end
When("c{int} ← lighting m, light, point {float}, {float}, {float}, eyev, normalv, false") do |int, float, float2, float3|
(@c ||= {})[int] = @m.lighting(Sphere.new, @light, Tuple.point(float, float2, float3), @eyev, @normalv, false)
end
Then("c{int} = color {float}, {float}, {float}") do |int, float, float2, float3|
expect(@c[int]).to eq(Color.new(float, float2, float3))
end
Then("m.reflective = {float}") do |float|
expect(@m.reflective).to eq(float)
end
| true |
d1cc4539cca5bb603e60cf192dfd80c34b120c6d
|
Ruby
|
yesnik/pricing_rules
|
/lib/pricing_rule/free_item.rb
|
UTF-8
| 464 | 3.09375 | 3 |
[] |
no_license
|
module PricingRule
class FreeItem
attr_reader :product, :free_item_num
def initialize(product, free_item_num)
@product = product
@free_item_num = free_item_num
end
def price(items)
count = rule_items(items).size
free_items_count = count / free_item_num
(count - free_items_count) * product.price
end
def rule_items(items)
Array(items).select { |item| item.code.eql? product.code }
end
end
end
| true |
e7650de3bd087e7b845b372ad582df298f9df41b
|
Ruby
|
chmohit4/blogger
|
/app/controllers/blogs_controller.rb
|
UTF-8
| 1,918 | 2.5625 | 3 |
[] |
no_license
|
class BlogsController < ApplicationController
before_filter :authenticate_user!, :except => [:index, :show]
#before_filter :load_blog, :only => [:show, :edit, :update, :destroy]
before_filter :load_blog, :except => [:index, :new, :create]
def index
@blogs = Blog.all
end
def new
@blog = Blog.new
end
def create
#1. create an instance of the Blog
#2. Set the values of the attributes of the blog from the data sent to the server from /blogs/new form
#3. Request parameters available through the keyword params and params is a Hash
blog_values = params[:blog]
@blog = Blog.new(blog_values)
if @blog.save
flash[:notice] = "Hurray! Your blog with title #{@blog.title} is created"
redirect_to blogs_path #, :notice => "Hurray! Your blog with title #{@blog.title} is created!"
else
render :new # render the view corresponding to the new action in this controller
end
end
def show
#1. ID of the blog record to be fetched from the DB and shown in this page
# URL: /blogs/1, then params[:id] #=> 1
# URL: /blogs/21, then params[:id] #=> 21
end
def edit
#1. URL : /blogs/:id/edit
#2. /blogs/5/edit #=> params[:id] => 5
end
def update
# /blogs/4 with POST or PUT HTTP method
#1. ID the blog record to be updated
#2. The form data (Title, Summary, Keywords, Published)
if @blog.update_attributes(params[:blog])
redirect_to @blog, :notice => "Hurray! Your blog entry is updated!"
else
render :edit
end
end
def destroy
#1 URL : /blogs/4 with DELETE HTTP method
#2 ID of the blog to be deleted is passed as the request parameter
#@blog = Blog.find(params[:id])
if @blog.destroy
redirect_to blogs_path, :notice => "Hurray! Your blog entry is deleted!"
else
redirect_to blogs_path, :notice => "Hurray! Your blog entry could not be deleted!"
end
end
private
def load_blog
@blog = Blog.find(params[:id])
end
end
| true |
0823b05f7fd20f5c3437bf4388e08bbbd545e4c5
|
Ruby
|
jekyll/jekyll
|
/benchmark/conditional_liquid.rb
|
UTF-8
| 3,769 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
# frozen_string_literal: true
require "liquid"
require "benchmark/ips"
# Test if processing content string without any Liquid constructs, via Liquid,
# is slower than checking whether constructs exist ( using `String#include?` )
# and return-ing the "plaintext" content string as is..
#
# Ref: https://github.com/jekyll/jekyll/pull/6735
# Sample contents
WITHOUT_LIQUID = <<-TEXT.freeze
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor libero at
pharetra tempus. Etiam bibendum magna et metus fermentum, eu cursus lorem
mattis. Curabitur vel dui et lacus rutrum suscipit et eget neque.
Nullam luctus fermentum est id blandit. Phasellus consectetur ullamcorper
ligula, at finibus eros laoreet id. Etiam sit amet est in libero efficitur
tristique. Ut nec magna augue. Quisque ut fringilla lacus, ac dictum enim.
Aliquam vel ornare mauris. Suspendisse ornare diam tempor nulla facilisis
aliquet. Sed ultrices placerat ultricies.
TEXT
WITH_LIQUID = <<-LIQUID.freeze
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor libero at
pharetra tempus. {{ author }} et metus fermentum, eu cursus lorem
mattis. Curabitur vel dui et lacus rutrum suscipit et eget neque.
Nullam luctus fermentum est id blandit. Phasellus consectetur ullamcorper
ligula, {% if author == "Jane Doe" %} at finibus eros laoreet id. {% else %}
Etiam sit amet est in libero efficitur.{% endif %}
tristique. Ut nec magna augue. Quisque ut fringilla lacus, ac dictum enim.
Aliquam vel ornare mauris. Suspendisse ornare diam tempor nulla facilisis
aliquet. Sed ultrices placerat ultricies.
LIQUID
WITH_JUST_LIQUID_VAR = <<-LIQUID.freeze
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor libero at
pharetra tempus. et metus fermentum, eu cursus lorem, ac dictum enim.
mattis. Curabitur vel dui et lacus rutrum suscipit et {{ title }} neque.
Nullam luctus fermentum est id blandit. Phasellus consectetur ullamcorper
ligula, at finibus eros laoreet id. Etiam sit amet est in libero efficitur.
tristique. Ut nec magna augue. {{ author }} Quisque ut fringilla lacus
Aliquam vel ornare mauris. Suspendisse ornare diam tempor nulla facilisis
aliquet. Sed ultrices placerat ultricies.
LIQUID
SUITE = {
:"plain text" => WITHOUT_LIQUID,
:"tags n vars" => WITH_LIQUID,
:"just vars" => WITH_JUST_LIQUID_VAR,
}.freeze
# Mimic how Jekyll's LiquidRenderer would process a non-static file, with
# some dummy payload
def always_liquid(content)
Liquid::Template.error_mode = :warn
Liquid::Template.parse(content, :line_numbers => true).render(
"author" => "John Doe",
"title" => "FooBar"
)
end
# Mimic how the proposed change would first execute a couple of checks and
# proceed to process with Liquid if necessary
def conditional_liquid(content)
return content if content.nil? || content.empty?
return content unless content.include?("{%") || content.include?("{{")
always_liquid(content)
end
# Test https://github.com/jekyll/jekyll/pull/6735#discussion_r165499868
# ------------------------------------------------------------------------
def check_with_regex(content)
!content.to_s.match?(%r!{[{%]!)
end
def check_with_builtin(content)
content.include?("{%") || content.include?("{{")
end
SUITE.each do |key, text|
Benchmark.ips do |x|
x.report("regex-check - #{key}") { check_with_regex(text) }
x.report("builtin-check - #{key}") { check_with_builtin(text) }
x.compare!
end
end
# ------------------------------------------------------------------------
# Let's roll!
SUITE.each do |key, text|
Benchmark.ips do |x|
x.report("always thru liquid - #{key}") { always_liquid(text) }
x.report("conditional liquid - #{key}") { conditional_liquid(text) }
x.compare!
end
end
| true |
dbd9c9fa3d2bc7299c71c703acedc733095a68f2
|
Ruby
|
scpike/rails-units
|
/lib/rails_units/unit.rb
|
UTF-8
| 42,912 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
require 'date'
if RUBY_VERSION < "1.9"
require 'parsedate'
require 'rational'
end
# = Ruby Units
#
# Copyright 2006-2011 by Kevin C. Olbrich, Ph.D.
#
# See http://rubyforge.org/ruby-units/
#
# http://www.sciwerks.org
#
# mailto://[email protected]
#
# See README for detailed usage instructions and examples
#
# ==Unit Definition Format
#
# '<name>' => [%w{prefered_name synonyms}, conversion_to_base, :classification, %w{<base> <units> <in> <numerator>} , %w{<base> <units> <in> <denominator>} ],
#
# Prefixes (e.g., a :prefix classification) get special handling
# Note: The accuracy of unit conversions depends on the precision of the conversion factor.
# If you have more accurate estimates for particular conversion factors, please send them
# to me and I will incorporate them into the next release. It is also incumbent on the end-user
# to ensure that the accuracy of any conversions is sufficient for their intended application.
#
# While there are a large number of unit specified in the base package,
# there are also a large number of units that are not included.
# This package covers nearly all SI, Imperial, and units commonly used
# in the United States. If your favorite units are not listed here, send me an email
#
# To add / override a unit definition, add a code block like this..
#
# class Unit < Numeric
# @@USER_DEFINITIONS = {
# <name>' => [%w{prefered_name synonyms}, conversion_to_base, :classification, %w{<base> <units> <in> <numerator>} , %w{<base> <units> <in> <denominator>} ]
# }
# end
# Unit.setup
class Unit < Numeric
# pre-generate hashes from unit definitions for performance.
VERSION = Unit::Version::STRING
@@USER_DEFINITIONS = {}
@@PREFIX_VALUES = {}
@@PREFIX_MAP = {}
@@UNIT_MAP = {}
@@UNIT_VALUES = {}
@@OUTPUT_MAP = {}
@@BASE_UNITS = ['<meter>','<kilogram>','<second>','<mole>', '<farad>', '<ampere>','<radian>','<kelvin>','<temp-K>','<byte>','<dollar>','<candela>','<each>','<steradian>','<decibel>']
UNITY = '<1>'
UNITY_ARRAY= [UNITY]
FEET_INCH_REGEX = /(\d+)\s*(?:'|ft|feet)\s*(\d+)\s*(?:"|in|inches)/
TIME_REGEX = /(\d+)*:(\d+)*:*(\d+)*[:,]*(\d+)*/
LBS_OZ_REGEX = /(\d+)\s*(?:#|lbs|pounds|pound-mass)+[\s,]*(\d+)\s*(?:oz|ounces)/
SCI_NUMBER = %r{([+-]?\d*[.]?\d+(?:[Ee][+-]?)?\d*)}
RATIONAL_NUMBER = /([+-]?\d+)\/(\d+)/
COMPLEX_NUMBER = /#{SCI_NUMBER}?#{SCI_NUMBER}i\b/
NUMBER_REGEX = /#{SCI_NUMBER}*\s*(.+)?/
UNIT_STRING_REGEX = /#{SCI_NUMBER}*\s*([^\/]*)\/*(.+)*/
TOP_REGEX = /([^ \*]+)(?:\^|\*\*)([\d-]+)/
BOTTOM_REGEX = /([^* ]+)(?:\^|\*\*)(\d+)/
UNCERTAIN_REGEX = /#{SCI_NUMBER}\s*\+\/-\s*#{SCI_NUMBER}\s(.+)/
COMPLEX_REGEX = /#{COMPLEX_NUMBER}\s?(.+)?/
RATIONAL_REGEX = /#{RATIONAL_NUMBER}\s?(.+)?/
KELVIN = ['<kelvin>']
FAHRENHEIT = ['<fahrenheit>']
RANKINE = ['<rankine>']
CELSIUS = ['<celsius>']
TEMP_REGEX = /(?:temp|deg)[CFRK]/
SIGNATURE_VECTOR = [:length, :time, :temperature, :mass, :current, :substance, :luminosity, :currency, :memory, :angle, :capacitance]
@@KINDS = {
-312058=>:resistance,
-312038=>:inductance,
-152040=>:magnetism,
-152038=>:magnetism,
-152058=>:potential,
-39=>:acceleration,
-38=>:radiation,
-20=>:frequency,
-19=>:speed,
-18=>:viscosity,
0=>:unitless,
1=>:length,
2=>:area,
3=>:volume,
20=>:time,
400=>:temperature,
7942=>:power,
7959=>:pressure,
7962=>:energy,
7979=>:viscosity,
7961=>:force,
7997=>:mass_concentration,
8000=>:mass,
159999=>:magnetism,
160000=>:current,
160020=>:charge,
312058=>:resistance,
3199980=>:activity,
3199997=>:molar_concentration,
3200000=>:substance,
63999998=>:illuminance,
64000000=>:luminous_power,
1280000000=>:currency,
25600000000=>:memory,
511999999980=>:angular_velocity,
512000000000=>:angle,
10240000000000=>:capacitance,
}
@@cached_units = {}
@@base_unit_cache = {}
def self.setup
@@ALL_UNIT_DEFINITIONS = UNIT_DEFINITIONS.merge!(@@USER_DEFINITIONS)
for unit in (@@ALL_UNIT_DEFINITIONS) do
key, value = unit
if value[2] == :prefix then
@@PREFIX_VALUES[key]=value[1]
for name in value[0] do
@@PREFIX_MAP[name]=key
end
else
@@UNIT_VALUES[key]={}
@@UNIT_VALUES[key][:scalar]=value[1]
@@UNIT_VALUES[key][:numerator]=value[3] if value[3]
@@UNIT_VALUES[key][:denominator]=value[4] if value[4]
for name in value[0] do
@@UNIT_MAP[name]=key
end
end
@@OUTPUT_MAP[key]=value[0][0]
end
@@PREFIX_REGEX = @@PREFIX_MAP.keys.sort_by {|prefix| [prefix.length, prefix]}.reverse.join('|')
@@UNIT_REGEX = @@UNIT_MAP.keys.sort_by {|unit_name| [unit_name.length, unit]}.reverse.join('|')
@@UNIT_MATCH_REGEX = /(#{@@PREFIX_REGEX})*?(#{@@UNIT_REGEX})\b/
Unit.new(1)
end
include Comparable
attr_accessor :scalar, :numerator, :denominator, :signature, :base_scalar, :base_numerator, :base_denominator, :output, :unit_name
def to_yaml_properties
%w{@scalar @numerator @denominator @signature @base_scalar}
end
# needed to make complex units play nice -- otherwise not detected as a complex_generic
def kind_of?(klass)
self.scalar.kind_of?(klass)
end
def copy(from)
@scalar = from.scalar
@numerator = from.numerator
@denominator = from.denominator
@is_base = from.is_base?
@signature = from.signature
@base_scalar = from.base_scalar
@unit_name = from.unit_name rescue nil
end
# basically a copy of the basic to_yaml. Needed because otherwise it ends up coercing the object to a string
# before YAML'izing it.
if RUBY_VERSION < "1.9"
def to_yaml( opts = {} )
YAML::quick_emit( object_id, opts ) do |out|
out.map( taguri, to_yaml_style ) do |map|
for m in to_yaml_properties do
map.add( m[1..-1], instance_variable_get( m ) )
end
end
end
end
end
# Create a new Unit object. Can be initialized using a String, a Hash, an Array, Time, DateTime
# Valid formats include:
# "5.6 kg*m/s^2"
# "5.6 kg*m*s^-2"
# "5.6 kilogram*meter*second^-2"
# "2.2 kPa"
# "37 degC"
# "1" -- creates a unitless constant with value 1
# "GPa" -- creates a unit with scalar 1 with units 'GPa'
# 6'4" -- recognized as 6 feet + 4 inches
# 8 lbs 8 oz -- recognized as 8 lbs + 8 ounces
#
def initialize(*options)
@scalar = nil
@base_scalar = nil
@unit_name = nil
@signature = nil
@output = {}
if options.size == 2
# options[0] is the scalar
# options[1] is a unit string
begin
cached = @@cached_units[options[1]] * options[0]
copy(cached)
rescue
initialize("#{options[0]} #{(options[1].units rescue options[1])}")
end
return
end
if options.size == 3
options[1] = options[1].join if options[1].kind_of?(Array)
options[2] = options[2].join if options[2].kind_of?(Array)
begin
cached = @@cached_units["#{options[1]}/#{options[2]}"] * options[0]
copy(cached)
rescue
initialize("#{options[0]} #{options[1]}/#{options[2]}")
end
return
end
case options[0]
when Hash
@scalar = options[0][:scalar] || 1
@numerator = options[0][:numerator] || UNITY_ARRAY
@denominator = options[0][:denominator] || UNITY_ARRAY
@signature = options[0][:signature]
when Array
initialize(*options[0])
return
when Numeric
@scalar = options[0]
@numerator = @denominator = UNITY_ARRAY
when Time
@scalar = options[0].to_f
@numerator = ['<second>']
@denominator = UNITY_ARRAY
when DateTime, Date
@scalar = options[0].ajd
@numerator = ['<day>']
@denominator = UNITY_ARRAY
when /^\s*$/
raise ArgumentError, "No Unit Specified"
when String
parse(options[0])
else
raise ArgumentError, "Invalid Unit Format"
end
self.update_base_scalar
raise ArgumentError, "Temperatures must not be less than absolute zero" if self.is_temperature? && self.base_scalar < 0
unary_unit = self.units || ""
if options.first.instance_of?(String)
opt_scalar, opt_units = Unit.parse_into_numbers_and_units(options[0])
unless @@cached_units.keys.include?(opt_units) || (opt_units =~ /(#{TEMP_REGEX})|(pounds|lbs[ ,]\d+ ounces|oz)|('\d+")|(ft|feet[ ,]\d+ in|inch|inches)|%|(#{TIME_REGEX})|i\s?(.+)?|±|\+\/-/)
@@cached_units[opt_units] = (self.scalar == 1 ? self : opt_units.unit) if opt_units && !opt_units.empty?
end
end
unless @@cached_units.keys.include?(unary_unit) || (unary_unit =~ /#{TEMP_REGEX}/) then
@@cached_units[unary_unit] = (self.scalar == 1 ? self : unary_unit.unit)
end
[@scalar, @numerator, @denominator, @base_scalar, @signature, @is_base].each {|x| x.freeze}
self
end
def kind
return @@KINDS[self.signature]
end
def self.cached
return @@cached_units
end
def self.clear_cache
@@cached_units = {}
@@base_unit_cache = {}
Unit.new(1)
end
def self.base_unit_cache
return @@base_unit_cache
end
#
# parse strings like "1 minute in seconds"
#
def self.parse(input)
first, second = input.scan(/(.+)\s(?:in|to|as)\s(.+)/i).first
second.nil? ? first.unit : first.unit.to(second)
end
def to_unit
self
end
alias :unit :to_unit
# Returns 'true' if the Unit is represented in base units
def is_base?
return @is_base if defined? @is_base
return @is_base=true if self.degree? && self.numerator.size == 1 && self.denominator == UNITY_ARRAY && self.units =~ /(?:deg|temp)K/
n = @numerator + @denominator
for x in n.compact do
return @is_base=false unless x == UNITY || (@@BASE_UNITS.include?((x)))
end
return @is_base = true
end
alias :base? :is_base?
# convert to base SI units
# results of the conversion are cached so subsequent calls to this will be fast
def to_base
return self if self.is_base?
if self.units =~ /\A(?:temp|deg)[CRF]\Z/
if RUBY_VERSION < "1.9"
@signature = @@KINDS.index(:temperature)
else
#:nocov:
@signature = @@KINDS.key(:temperature)
#:nocov:
end
base = case
when self.is_temperature?
self.to('tempK')
when self.is_degree?
self.to('degK')
end
return base
end
cached = ((@@base_unit_cache[self.units] * self.scalar) rescue nil)
return cached if cached
num = []
den = []
q = 1
for unit in @numerator.compact do
if @@PREFIX_VALUES[unit]
q *= @@PREFIX_VALUES[unit]
else
q *= @@UNIT_VALUES[unit][:scalar] if @@UNIT_VALUES[unit]
num << @@UNIT_VALUES[unit][:numerator] if @@UNIT_VALUES[unit] && @@UNIT_VALUES[unit][:numerator]
den << @@UNIT_VALUES[unit][:denominator] if @@UNIT_VALUES[unit] && @@UNIT_VALUES[unit][:denominator]
end
end
for unit in @denominator.compact do
if @@PREFIX_VALUES[unit]
q /= @@PREFIX_VALUES[unit]
else
q /= @@UNIT_VALUES[unit][:scalar] if @@UNIT_VALUES[unit]
den << @@UNIT_VALUES[unit][:numerator] if @@UNIT_VALUES[unit] && @@UNIT_VALUES[unit][:numerator]
num << @@UNIT_VALUES[unit][:denominator] if @@UNIT_VALUES[unit] && @@UNIT_VALUES[unit][:denominator]
end
end
num = num.flatten.compact
den = den.flatten.compact
num = UNITY_ARRAY if num.empty?
base= Unit.new(Unit.eliminate_terms(q,num,den))
@@base_unit_cache[self.units]=base
return base * @scalar
end
alias :base :to_base
# Generate human readable output.
# If the name of a unit is passed, the unit will first be converted to the target unit before output.
# some named conversions are available
#
# :ft - outputs in feet and inches (e.g., 6'4")
# :lbs - outputs in pounds and ounces (e.g, 8 lbs, 8 oz)
#
# You can also pass a standard format string (i.e., '%0.2f')
# or a strftime format string.
#
# output is cached so subsequent calls for the same format will be fast
#
def to_s(target_units=nil)
out = @output[target_units]
if out
return out
else
case target_units
when :ft
inches = self.to("in").scalar.to_int
out = "#{(inches / 12).truncate}\'#{(inches % 12).round}\""
when :lbs
ounces = self.to("oz").scalar.to_int
out = "#{(ounces / 16).truncate} lbs, #{(ounces % 16).round} oz"
when String
out = case target_units
when /(%[\-+\.\w#]+)\s*(.+)*/ #format string like '%0.2f in'
begin
if $2 #unit specified, need to convert
self.to($2).to_s($1)
else
"#{$1 % @scalar} #{$2 || self.units}".strip
end
rescue
(DateTime.new(0) + self).strftime(target_units)
end
when /(\S+)/ #unit only 'mm' or '1/mm'
"#{self.to($1).to_s}"
else
raise "unhandled case"
end
else
out = case @scalar
when Rational
"#{@scalar} #{self.units}"
else
"#{'%g' % @scalar} #{self.units}"
end.strip
end
@output[target_units] = out
return out
end
end
# Normally pretty prints the unit, but if you really want to see the guts of it, pass ':dump'
def inspect(option=nil)
return super() if option == :dump
self.to_s
end
# true if unit is a 'temperature', false if a 'degree' or anything else
def is_temperature?
self.is_degree? && (!(self.units =~ /temp[CFRK]/).nil?)
end
alias :temperature? :is_temperature?
# true if a degree unit or equivalent.
def is_degree?
self.kind == :temperature
end
alias :degree? :is_degree?
# returns the 'degree' unit associated with a temperature unit
# '100 tempC'.unit.temperature_scale #=> 'degC'
def temperature_scale
return nil unless self.is_temperature?
self.units =~ /temp([CFRK])/
"deg#{$1}"
end
# returns true if no associated units
# false, even if the units are "unitless" like 'radians, each, etc'
def unitless?
(@numerator == UNITY_ARRAY && @denominator == UNITY_ARRAY)
end
# Compare two Unit objects. Throws an exception if they are not of compatible types.
# Comparisons are done based on the value of the unit in base SI units.
def <=>(other)
case
when !self.base_scalar.respond_to?(:<=>)
raise NoMethodError, "undefined method `<=>' for #{self.base_scalar.inspect}"
when !self.is_temperature? && other.zero?
return self.base_scalar <=> 0
when other.instance_of?(Unit)
raise ArgumentError, "Incompatible Units (#{self.units} !~ #{other.units})" unless self =~ other
return self.base_scalar <=> other.base_scalar
else
x,y = coerce(other)
return x <=> y
end
end
# Compare Units for equality
# this is necessary mostly for Complex units. Complex units do not have a <=> operator
# so we define this one here so that we can properly check complex units for equality.
# Units of incompatible types are not equal, except when they are both zero and neither is a temperature
# Equality checks can be tricky since round off errors may make essentially equivalent units
# appear to be different.
def ==(other)
case
when other.respond_to?(:zero?) && other.zero?
return self.zero?
when other.instance_of?(Unit)
return false unless self =~ other
return self.base_scalar == other.base_scalar
else
x,y = coerce(other)
return x == y
end
end
# check to see if units are compatible, but not the scalar part
# this check is done by comparing signatures for performance reasons
# if passed a string, it will create a unit object with the string and then do the comparison
# this permits a syntax like:
# unit =~ "mm"
# if you want to do a regexp on the unit string do this ...
# unit.units =~ /regexp/
def =~(other)
case other
when Unit
self.signature == other.signature
else
x,y = coerce(other)
x =~ y
end
end
alias :compatible? :=~
alias :compatible_with? :=~
# Compare two units. Returns true if quantities and units match
#
# Unit("100 cm") === Unit("100 cm") # => true
# Unit("100 cm") === Unit("1 m") # => false
def ===(other)
case other
when Unit
(self.scalar == other.scalar) && (self.units == other.units)
else
x,y = coerce(other)
x === y
end
end
alias :same? :===
alias :same_as? :===
# Add two units together. Result is same units as receiver and scalar and base_scalar are updated appropriately
# throws an exception if the units are not compatible.
# It is possible to add Time objects to units of time
def +(other)
case other
when Unit
case
when self.zero?
other.dup
when self =~ other
raise ArgumentError, "Cannot add two temperatures" if ([self, other].all? {|x| x.is_temperature?})
if [self, other].any? {|x| x.is_temperature?}
if self.is_temperature?
Unit.new(:scalar => (self.scalar + other.to(self.temperature_scale).scalar), :numerator => @numerator, :denominator=>@denominator, :signature => @signature)
else
Unit.new(:scalar => (other.scalar + self.to(other.temperature_scale).scalar), :numerator => other.numerator, :denominator=>other.denominator, :signature => other.signature)
end
else
@q ||= ((@@cached_units[self.units].scalar / @@cached_units[self.units].base_scalar) rescue (self.units.unit.to_base.scalar))
Unit.new(:scalar=>(self.base_scalar + other.base_scalar)*@q, :numerator=>@numerator, :denominator=>@denominator, :signature => @signature)
end
else
raise ArgumentError, "Incompatible Units ('#{self}' not compatible with '#{other}')"
end
when Date, Time
raise ArgumentError, "Date and Time objects represent fixed points in time and cannot be added to a Unit"
else
x,y = coerce(other)
y + x
end
end
# Subtract two units. Result is same units as receiver and scalar and base_scalar are updated appropriately
# throws an exception if the units are not compatible.
def -(other)
case other
when Unit
case
when self.zero?
-other.dup
when self =~ other
case
when [self, other].all? {|x| x.is_temperature?}
Unit.new(:scalar => (self.base_scalar - other.base_scalar), :numerator => KELVIN, :denominator => UNITY_ARRAY, :signature => @signature).to(self.temperature_scale)
when self.is_temperature?
Unit.new(:scalar => (self.base_scalar - other.base_scalar), :numerator => ['<temp-K>'], :denominator => UNITY_ARRAY, :signature => @signature).to(self)
when other.is_temperature?
raise ArgumentError, "Cannot subtract a temperature from a differential degree unit"
else
@q ||= ((@@cached_units[self.units].scalar / @@cached_units[self.units].base_scalar) rescue (self.units.unit.scalar/self.units.unit.to_base.scalar))
Unit.new(:scalar=>(self.base_scalar - other.base_scalar)*@q, :numerator=>@numerator, :denominator=>@denominator, :signature=>@signature)
end
else
raise ArgumentError, "Incompatible Units ('#{self}' not compatible with '#{other}')"
end
when Time
raise ArgumentError, "Date and Time objects represent fixed points in time and cannot be subtracted from to a Unit, which can only represent time spans"
else
x,y = coerce(other)
y-x
end
end
# Multiply two units.
def *(other)
case other
when Unit
raise ArgumentError, "Cannot multiply by temperatures" if [other,self].any? {|x| x.is_temperature?}
opts = Unit.eliminate_terms(@scalar*other.scalar, @numerator + other.numerator ,@denominator + other.denominator)
opts.merge!(:signature => @signature + other.signature)
Unit.new(opts)
when Numeric
Unit.new(:scalar=>@scalar*other, :numerator=>@numerator, :denominator=>@denominator, :signature => @signature)
else
x,y = coerce(other)
x * y
end
end
# Divide two units.
# Throws an exception if divisor is 0
def /(other)
case other
when Unit
raise ZeroDivisionError if other.zero?
raise ArgumentError, "Cannot divide with temperatures" if [other,self].any? {|x| x.is_temperature?}
opts = Unit.eliminate_terms(@scalar/other.scalar, @numerator + other.denominator ,@denominator + other.numerator)
opts.merge!(:signature=> @signature - other.signature)
Unit.new(opts)
when Numeric
raise ZeroDivisionError if other.zero?
Unit.new(:scalar=>@scalar/other, :numerator=>@numerator, :denominator=>@denominator, :signature => @signature)
else
x,y = coerce(other)
y / x
end
end
# divide two units and return quotient and remainder
# when both units are in the same units we just use divmod on the raw scalars
# otherwise we use the scalar of the base unit which will be a float
def divmod(other)
raise ArgumentError, "Incompatible Units" unless self =~ other
if self.units == other.units
return self.scalar.divmod(other.scalar)
else
return self.to_base.scalar.divmod(other.to_base.scalar)
end
end
# perform a modulo on a unit, will raise an exception if the units are not compatible
def %(other)
self.divmod(other).last
end
# Exponentiate. Only takes integer powers.
# Note that anything raised to the power of 0 results in a Unit object with a scalar of 1, and no units.
# Throws an exception if exponent is not an integer.
# Ideally this routine should accept a float for the exponent
# It should then convert the float to a rational and raise the unit by the numerator and root it by the denominator
# but, sadly, floats can't be converted to rationals.
#
# For now, if a rational is passed in, it will be used, otherwise we are stuck with integers and certain floats < 1
def **(other)
raise ArgumentError, "Cannot raise a temperature to a power" if self.is_temperature?
if other.kind_of?(Numeric)
return self.inverse if other == -1
return self if other == 1
return 1 if other.zero?
end
case other
when Rational
self.power(other.numerator).root(other.denominator)
when Integer
self.power(other)
when Float
return self**(other.to_i) if other == other.to_i
valid = (1..9).map {|x| 1/x}
raise ArgumentError, "Not a n-th root (1..9), use 1/n" unless valid.include? other.abs
self.root((1/other).to_int)
when Complex
raise ArgumentError, "exponentiation of complex numbers is not yet supported."
else
raise ArgumentError, "Invalid Exponent"
end
end
# returns the unit raised to the n-th power. Integers only
def power(n)
raise ArgumentError, "Cannot raise a temperature to a power" if self.is_temperature?
raise ArgumentError, "Exponent must an Integer" unless n.kind_of?(Integer)
return self.inverse if n == -1
return 1 if n.zero?
return self if n == 1
if n > 0 then
(1..(n-1).to_i).inject(self) {|product, x| product * self}
else
(1..-(n-1).to_i).inject(self) {|product, x| product / self}
end
end
# Calculates the n-th root of a unit, where n = (1..9)
# if n < 0, returns 1/unit^(1/n)
def root(n)
raise ArgumentError, "Cannot take the root of a temperature" if self.is_temperature?
raise ArgumentError, "Exponent must an Integer" unless n.kind_of?(Integer)
raise ArgumentError, "0th root undefined" if n.zero?
return self if n == 1
return self.root(n.abs).inverse if n < 0
vec = self.unit_signature_vector
vec=vec.map {|x| x % n}
raise ArgumentError, "Illegal root" unless vec.max == 0
num = @numerator.dup
den = @denominator.dup
for item in @numerator.uniq do
x = num.find_all {|i| i==item}.size
r = ((x/n)*(n-1)).to_int
r.times {|y| num.delete_at(num.index(item))}
end
for item in @denominator.uniq do
x = den.find_all {|i| i==item}.size
r = ((x/n)*(n-1)).to_int
r.times {|y| den.delete_at(den.index(item))}
end
q = @scalar < 0 ? (-1)**Rational(1,n) * (@scalar.abs)**Rational(1,n) : @scalar**Rational(1,n)
Unit.new(:scalar=>q,:numerator=>num,:denominator=>den)
end
# returns inverse of Unit (1/unit)
def inverse
Unit("1") / self
end
# convert to a specified unit string or to the same units as another Unit
#
# unit >> "kg" will covert to kilograms
# unit1 >> unit2 converts to same units as unit2 object
#
# To convert a Unit object to match another Unit object, use:
# unit1 >>= unit2
# Throws an exception if the requested target units are incompatible with current Unit.
#
# Special handling for temperature conversions is supported. If the Unit object is converted
# from one temperature unit to another, the proper temperature offsets will be used.
# Supports Kelvin, Celsius, fahrenheit, and Rankine scales.
#
# Note that if temperature is part of a compound unit, the temperature will be treated as a differential
# and the units will be scaled appropriately.
def to(other)
return self if other.nil?
return self if TrueClass === other
return self if FalseClass === other
if (Unit === other && other.is_temperature?) || (String === other && other =~ /temp[CFRK]/)
raise ArgumentError, "Receiver is not a temperature unit" unless self.degree?
start_unit = self.units
target_unit = other.units rescue other
unless @base_scalar
@base_scalar = case start_unit
when 'tempC'
@scalar + 273.15
when 'tempK'
@scalar
when 'tempF'
(@scalar+459.67)*Rational(5,9)
when 'tempR'
@scalar*Rational(5,9)
end
end
q= case target_unit
when 'tempC'
@base_scalar - 273.15
when 'tempK'
@base_scalar
when 'tempF'
@base_scalar * Rational(9,5) - 459.67
when 'tempR'
@base_scalar * Rational(9,5)
end
Unit.new("#{q} #{target_unit}")
else
case other
when Unit
return self if other.units == self.units
target = other
when String
target = Unit.new(other)
else
raise ArgumentError, "Unknown target units"
end
raise ArgumentError, "Incompatible Units" unless self =~ target
_numerator1 = @numerator.map {|x| @@PREFIX_VALUES[x] ? @@PREFIX_VALUES[x] : x}.map {|i| i.kind_of?(Numeric) ? i : @@UNIT_VALUES[i][:scalar] }.compact
_denominator1 = @denominator.map {|x| @@PREFIX_VALUES[x] ? @@PREFIX_VALUES[x] : x}.map {|i| i.kind_of?(Numeric) ? i : @@UNIT_VALUES[i][:scalar] }.compact
_numerator2 = target.numerator.map {|x| @@PREFIX_VALUES[x] ? @@PREFIX_VALUES[x] : x}.map {|x| x.kind_of?(Numeric) ? x : @@UNIT_VALUES[x][:scalar] }.compact
_denominator2 = target.denominator.map {|x| @@PREFIX_VALUES[x] ? @@PREFIX_VALUES[x] : x}.map {|x| x.kind_of?(Numeric) ? x : @@UNIT_VALUES[x][:scalar] }.compact
# eliminate common terms
(_numerator1 & _denominator2).each do |common|
_numerator1.delete(common)
_denominator2.delete(common)
end
(_numerator2 & _denominator1).each do |common|
_numerator1.delete(common)
_denominator2.delete(common)
end
q = @scalar * ( (_numerator1 + _denominator2).inject(1) {|product,n| product*n} ) /
( (_numerator2 + _denominator1).inject(1) {|product,n| product*n} )
Unit.new(:scalar=>q, :numerator=>target.numerator, :denominator=>target.denominator, :signature => target.signature)
end
end
alias :>> :to
alias :convert_to :to
# converts the unit back to a float if it is unitless. Otherwise raises an exception
def to_f
return @scalar.to_f if self.unitless?
raise RuntimeError, "Cannot convert '#{self.to_s}' to Float unless unitless. Use Unit#scalar"
end
# converts the unit back to a complex if it is unitless. Otherwise raises an exception
def to_c
return Complex(@scalar) if self.unitless?
raise RuntimeError, "Cannot convert '#{self.to_s}' to Complex unless unitless. Use Unit#scalar"
end
# if unitless, returns an int, otherwise raises an error
def to_i
return @scalar.to_int if self.unitless?
raise RuntimeError, "Cannot convert '#{self.to_s}' to Integer unless unitless. Use Unit#scalar"
end
alias :to_int :to_i
# if unitless, returns a Rational, otherwise raises an error
def to_r
return @scalar.to_r if self.unitless?
raise RuntimeError, "Cannot convert '#{self.to_s}' to Rational unless unitless. Use Unit#scalar"
end
# returns the 'unit' part of the Unit object without the scalar
def units
return "" if @numerator == UNITY_ARRAY && @denominator == UNITY_ARRAY
return @unit_name unless @unit_name.nil?
output_n = []
output_d =[]
num = @numerator.clone.compact
den = @denominator.clone.compact
if @numerator == UNITY_ARRAY
output_n << "1"
else
num.each_with_index do |token,index|
if token && @@PREFIX_VALUES[token] then
output_n << "#{@@OUTPUT_MAP[token]}#{@@OUTPUT_MAP[num[index+1]]}"
num[index+1]=nil
else
output_n << "#{@@OUTPUT_MAP[token]}" if token
end
end
end
if @denominator == UNITY_ARRAY
output_d = ['1']
else
den.each_with_index do |token,index|
if token && @@PREFIX_VALUES[token] then
output_d << "#{@@OUTPUT_MAP[token]}#{@@OUTPUT_MAP[den[index+1]]}"
den[index+1]=nil
else
output_d << "#{@@OUTPUT_MAP[token]}" if token
end
end
end
on = output_n.reject {|x| x.empty?}.map {|x| [x, output_n.find_all {|z| z==x}.size]}.uniq.map {|x| ("#{x[0]}".strip+ (x[1] > 1 ? "^#{x[1]}" : ''))}
od = output_d.reject {|x| x.empty?}.map {|x| [x, output_d.find_all {|z| z==x}.size]}.uniq.map {|x| ("#{x[0]}".strip+ (x[1] > 1 ? "^#{x[1]}" : ''))}
out = "#{on.join('*')}#{od == ['1'] ? '': '/'+od.join('*')}".strip
@unit_name = out unless self.kind == :temperature
return out
end
# negates the scalar of the Unit
def -@
return -@scalar if self.unitless?
self.dup * -1
end
def abs
return @scalar.abs if self.unitless?
Unit.new(@scalar.abs, @numerator, @denominator)
end
def ceil
return @scalar.ceil if self.unitless?
Unit.new(@scalar.ceil, @numerator, @denominator)
end
def floor
return @scalar.floor if self.unitless?
Unit.new(@scalar.floor, @numerator, @denominator)
end
def round
return @scalar.round if self.unitless?
Unit.new(@scalar.round, @numerator, @denominator)
end
def truncate
return @scalar.truncate if self.unitless?
Unit.new(@scalar.truncate, @numerator, @denominator)
end
# returns next unit in a range. '1 mm'.unit.succ #=> '2 mm'.unit
# only works when the scalar is an integer
def succ
raise ArgumentError, "Non Integer Scalar" unless @scalar == @scalar.to_i
Unit.new(@scalar.to_i.succ, @numerator, @denominator)
end
alias :next :succ
# returns next unit in a range. '1 mm'.unit.succ #=> '2 mm'.unit
# only works when the scalar is an integer
def pred
raise ArgumentError, "Non Integer Scalar" unless @scalar == @scalar.to_i
Unit.new(@scalar.to_i.pred, @numerator, @denominator)
end
# Tries to make a Time object from current unit. Assumes the current unit hold the duration in seconds from the epoch.
def to_time
Time.at(self)
end
alias :time :to_time
# convert a duration to a DateTime. This will work so long as the duration is the duration from the zero date
# defined by DateTime
def to_datetime
DateTime.new!(self.to('d').scalar)
end
def to_date
Date.new0(self.to('d').scalar)
end
# true if scalar is zero
def zero?
return self.base_scalar.zero?
end
# '5 min'.unit.ago
def ago
self.before
end
# '5 min'.before(time)
def before(time_point = ::Time.now)
raise ArgumentError, "Must specify a Time" unless time_point
if String === time_point
time_point.time - self rescue time_point.datetime - self
else
time_point - self rescue time_point.to_datetime - self
end
end
alias :before_now :before
# 'min'.since(time)
def since(time_point = ::Time.now)
case time_point
when Time
(Time.now - time_point).unit('s').to(self)
when DateTime, Date
(DateTime.now - time_point).unit('d').to(self)
when String
(DateTime.now - time_point.to_datetime(:context=>:past)).unit('d').to(self)
else
raise ArgumentError, "Must specify a Time, DateTime, or String"
end
end
# 'min'.until(time)
def until(time_point = ::Time.now)
case time_point
when Time
(time_point - Time.now).unit('s').to(self)
when DateTime, Date
(time_point - DateTime.now).unit('d').to(self)
when String
(time_point.to_datetime(:context=>:future) - DateTime.now).unit('d').to(self)
else
raise ArgumentError, "Must specify a Time, DateTime, or String"
end
end
# '5 min'.from(time)
def from(time_point = ::Time.now)
raise ArgumentError, "Must specify a Time" unless time_point
if String === time_point
time_point.time + self rescue time_point.datetime + self
else
time_point + self rescue time_point.to_datetime + self
end
end
alias :after :from
alias :from_now :from
# automatically coerce objects to units when possible
# if an object defines a 'to_unit' method, it will be coerced using that method
def coerce(other)
if other.respond_to? :to_unit
return [other.to_unit, self]
end
case other
when Unit
[other, self]
else
[Unit.new(other), self]
end
end
# Protected and Private Functions that should only be called from this class
protected
def update_base_scalar
return @base_scalar unless @base_scalar.nil?
if self.is_base?
@base_scalar = @scalar
@signature = unit_signature
else
base = self.to_base
@base_scalar = base.scalar
@signature = base.signature
end
end
# calculates the unit signature vector used by unit_signature
def unit_signature_vector
return self.to_base.unit_signature_vector unless self.is_base?
vector = Array.new(SIGNATURE_VECTOR.size,0)
for element in @numerator
if r=@@ALL_UNIT_DEFINITIONS[element]
n = SIGNATURE_VECTOR.index(r[2])
vector[n] = vector[n] + 1 if n
end
end
for element in @denominator
if r=@@ALL_UNIT_DEFINITIONS[element]
n = SIGNATURE_VECTOR.index(r[2])
vector[n] = vector[n] - 1 if n
end
end
raise ArgumentError, "Power out of range (-20 < net power of a unit < 20)" if vector.any? {|x| x.abs >=20}
vector
end
private
def initialize_copy(other)
@numerator = other.numerator.dup
@denominator = other.denominator.dup
end
# calculates the unit signature id for use in comparing compatible units and simplification
# the signature is based on a simple classification of units and is based on the following publication
#
# Novak, G.S., Jr. "Conversion of units of measurement", IEEE Transactions on Software Engineering,
# 21(8), Aug 1995, pp.651-661
# doi://10.1109/32.403789
# http://ieeexplore.ieee.org/Xplore/login.jsp?url=/iel1/32/9079/00403789.pdf?isnumber=9079&prod=JNL&arnumber=403789&arSt=651&ared=661&arAuthor=Novak%2C+G.S.%2C+Jr.
#
def unit_signature
return @signature unless @signature.nil?
vector = unit_signature_vector
vector.each_with_index {|item,index| vector[index] = item * 20**index}
@signature=vector.inject(0) {|sum,n| sum+n}
end
def self.eliminate_terms(q, n, d)
num = n.dup
den = d.dup
num.delete_if {|v| v == UNITY}
den.delete_if {|v| v == UNITY}
combined = Hash.new(0)
i = 0
loop do
break if i > num.size
if @@PREFIX_VALUES.has_key? num[i]
k = [num[i],num[i+1]]
i += 2
else
k = num[i]
i += 1
end
combined[k] += 1 unless k.nil? || k == UNITY
end
j = 0
loop do
break if j > den.size
if @@PREFIX_VALUES.has_key? den[j]
k = [den[j],den[j+1]]
j += 2
else
k = den[j]
j += 1
end
combined[k] -= 1 unless k.nil? || k == UNITY
end
num = []
den = []
for key, value in combined do
case
when value > 0
value.times {num << key}
when value < 0
value.abs.times {den << key}
end
end
num = UNITY_ARRAY if num.empty?
den = UNITY_ARRAY if den.empty?
{:scalar=>q, :numerator=>num.flatten.compact, :denominator=>den.flatten.compact}
end
# parse a string into a unit object.
# Typical formats like :
# "5.6 kg*m/s^2"
# "5.6 kg*m*s^-2"
# "5.6 kilogram*meter*second^-2"
# "2.2 kPa"
# "37 degC"
# "1" -- creates a unitless constant with value 1
# "GPa" -- creates a unit with scalar 1 with units 'GPa'
# 6'4" -- recognized as 6 feet + 4 inches
# 8 lbs 8 oz -- recognized as 8 lbs + 8 ounces
def parse(passed_unit_string="0")
unit_string = passed_unit_string.dup
if unit_string =~ /\$\s*(#{NUMBER_REGEX})/
unit_string = "#{$1} USD"
end
unit_string.gsub!(/%/,'percent')
unit_string.gsub!(/'/,'feet')
unit_string.gsub!(/"/,'inch')
unit_string.gsub!(/#/,'pound')
#:nocov:
if defined?(Uncertain) && unit_string =~ /(\+\/-|±)/
value, uncertainty, unit_s = unit_string.scan(UNCERTAIN_REGEX)[0]
result = unit_s.unit * Uncertain.new(value.to_f,uncertainty.to_f)
copy(result)
return
end
#:nocov:
if defined?(Complex) && unit_string =~ COMPLEX_NUMBER
real, imaginary, unit_s = unit_string.scan(COMPLEX_REGEX)[0]
result = Unit(unit_s || '1') * Complex(real.to_f,imaginary.to_f)
copy(result)
return
end
if defined?(Rational) && unit_string =~ RATIONAL_NUMBER
numerator, denominator, unit_s = unit_string.scan(RATIONAL_REGEX)[0]
result = Unit(unit_s || '1') * Rational(numerator.to_i,denominator.to_i)
copy(result)
return
end
unit_string =~ NUMBER_REGEX
unit = @@cached_units[$2]
mult = ($1.empty? ? 1.0 : $1.to_f) rescue 1.0
mult = mult.to_int if (mult.to_int == mult)
if unit
copy(unit)
@scalar *= mult
@base_scalar *= mult
return self
end
unit_string.gsub!(/<(#{@@UNIT_REGEX})><(#{@@UNIT_REGEX})>/, '\1*\2')
unit_string.gsub!(/[<>]/,"")
if unit_string =~ /:/
hours, minutes, seconds, microseconds = unit_string.scan(TIME_REGEX)[0]
raise ArgumentError, "Invalid Duration" if [hours, minutes, seconds, microseconds].all? {|x| x.nil?}
result = "#{hours || 0} h".unit +
"#{minutes || 0} minutes".unit +
"#{seconds || 0} seconds".unit +
"#{microseconds || 0} usec".unit
copy(result)
return
end
# Special processing for unusual unit strings
# feet -- 6'5"
feet, inches = unit_string.scan(FEET_INCH_REGEX)[0]
if (feet && inches)
result = Unit.new("#{feet} ft") + Unit.new("#{inches} inches")
copy(result)
return
end
# weight -- 8 lbs 12 oz
pounds, oz = unit_string.scan(LBS_OZ_REGEX)[0]
if (pounds && oz)
result = Unit.new("#{pounds} lbs") + Unit.new("#{oz} oz")
copy(result)
return
end
raise( ArgumentError, "'#{passed_unit_string}' Unit not recognized") if unit_string.count('/') > 1
raise( ArgumentError, "'#{passed_unit_string}' Unit not recognized") if unit_string.scan(/\s[02-9]/).size > 0
@scalar, top, bottom = unit_string.scan(UNIT_STRING_REGEX)[0] #parse the string into parts
top.scan(TOP_REGEX).each do |item|
n = item[1].to_i
x = "#{item[0]} "
case
when n>=0
top.gsub!(/#{item[0]}(\^|\*\*)#{n}/) {|s| x * n}
when n<0
bottom = "#{bottom} #{x * -n}"; top.gsub!(/#{item[0]}(\^|\*\*)#{n}/,"")
end
end
bottom.gsub!(BOTTOM_REGEX) {|s| "#{$1} " * $2.to_i} if bottom
@scalar = @scalar.to_f unless @scalar.nil? || @scalar.empty?
@scalar = 1 unless @scalar.kind_of? Numeric
@scalar = @scalar.to_int if (@scalar.to_int == @scalar)
@numerator ||= UNITY_ARRAY
@denominator ||= UNITY_ARRAY
@numerator = top.scan(@@UNIT_MATCH_REGEX).delete_if {|x| x.empty?}.compact if top
@denominator = bottom.scan(@@UNIT_MATCH_REGEX).delete_if {|x| x.empty?}.compact if bottom
us = "#{(top || '' + bottom || '')}".to_s.gsub(@@UNIT_MATCH_REGEX,'').gsub(/[\d\*, "'_^\/\$]/,'')
raise( ArgumentError, "'#{passed_unit_string}' Unit not recognized") unless us.empty?
@numerator = @numerator.map do |item|
@@PREFIX_MAP[item[0]] ? [@@PREFIX_MAP[item[0]], @@UNIT_MAP[item[1]]] : [@@UNIT_MAP[item[1]]]
end.flatten.compact.delete_if {|x| x.empty?}
@denominator = @denominator.map do |item|
@@PREFIX_MAP[item[0]] ? [@@PREFIX_MAP[item[0]], @@UNIT_MAP[item[1]]] : [@@UNIT_MAP[item[1]]]
end.flatten.compact.delete_if {|x| x.empty?}
@numerator = UNITY_ARRAY if @numerator.empty?
@denominator = UNITY_ARRAY if @denominator.empty?
self
end
private
# parse a string consisting of a number and a unit string
def self.parse_into_numbers_and_units(string)
# scientific notation.... 123.234E22, -123.456e-10
sci = %r{[+-]?\d*[.]?\d+(?:[Ee][+-]?)?\d*}
# rational numbers.... -1/3, 1/5, 20/100
rational = %r{[+-]?\d+\/\d+}
# complex numbers... -1.2+3i, +1.2-3.3i
complex = %r{#{sci}{2,2}i}
anynumber = %r{(?:(#{complex}|#{rational}|#{sci})\b)?\s?([\D].*)?}
num, unit = string.scan(anynumber).first
[case num
when NilClass
1
when complex
if num.respond_to?(:to_c)
num.to_c
else
Complex(*num.scan(/(#{sci})(#{sci})i/).flatten.map {|n| n.to_i})
end
when rational
Rational(*num.split("/").map {|x| x.to_i})
else
num.to_f
end, unit.to_s.strip]
end
end
Unit.setup
| true |
efa4c5dcbbb5199b1025e2b39c5e358364a8daac
|
Ruby
|
Iscaraca/Iai-ruby
|
/deck_of_cards.rb
|
UTF-8
| 336 | 3.65625 | 4 |
[] |
no_license
|
# Suits: C, D, S, H
# Numbers 1 to 10
# Pictures J, Q, K
# Jokers 2
deck_of_cards = ["Joker", "Joker"]
suits = ["C", "D", "S", "H"]
values = ("1".."10").to_a
values.append("J", "Q", "K")
suits.each do |suit|
values.each do |value|
deck_of_cards.append(value + suit)
end
end
print deck_of_cards.shuffle
| true |
3da3165ca4172a3e85939d13bff9f465df714962
|
Ruby
|
nasnick/scripts
|
/ruby/wordpress_not_touched_for_3_months.rb
|
UTF-8
| 871 | 2.65625 | 3 |
[] |
no_license
|
wp_content = []
wp_includes = []
wp_admin = []
a = File.open('/Users/nickschofield/Desktop/wordpress/wp-content') do |a|
a.each_line do |line_a|
wp_content << line_a
end
end
b = File.open('/Users/nickschofield/Desktop/wordpress/wp-includes') do |b|
b.each_line do |line_b|
wp_includes << line_b
end
end
c = File.open('/Users/nickschofield/Desktop/wordpress/wp-admin') do |c|
c.each_line do |line_c|
wp_admin << line_c
end
end
all_sites = []
d = File.open('/Users/nickschofield/Desktop/wordpress/all_sites') do |d|
d.each_line do |line_d|
all_sites << line_d
end
end
array = []
for i in all_sites
if wp_content.include?(i)
if wp_includes.include?(i)
if wp_admin.include?(i)
array << i
end
end
end
end
File.open("/Users/nickschofield/Desktop/wordpress/unique", "w+") do |f|
array.each { |element| f.puts(element) }
end
| true |
f37be847d70aa7f5b524657d1d531bf1460ddf24
|
Ruby
|
durerSV/ruby
|
/lesson7/route.rb
|
UTF-8
| 840 | 3.6875 | 4 |
[] |
no_license
|
class Route
attr_reader :stations, :name
def initialize(from, to)
@stations = [from, to]
@name = "#{from.name}-#{to.name}"
validate!
end
def add_station (station)
@stations.insert(-2, station)
end
def delete_station(station)
@stations.delete(station)
end
def print_route
@stations.each_with_index{|station, index| puts "#{index} - #{station} "}
end
def station(number)
@stations[number]
end
private
def validate!
raise "Выберите существующую станцию" if @stations[0] == nil || @stations.last == nil
raise "Станция должна являтся объектом класса Station" if @stations[0].class != Station|| @stations.last.class != Station
raise "Имя не может быть пустым" if @name == nil
end
end
| true |
963e69ac46a4a2c4eb2cc26b254918032035cf87
|
Ruby
|
kealanmcd/Ruby
|
/Week 6/Assignment: OOPsie Project/children.rb
|
UTF-8
| 1,828 | 3.1875 | 3 |
[] |
no_license
|
require './parent.rb'
require './modules.rb'
class Wizard < LifeForm
include BaseWizardSpells
attr_reader :wizard_type
@@acceptable_items[:cloak] = 1
def initialize(name, age, height, wizard_type)
super(name, age, height)
self.wizard_type=(wizard_type)
end
def speak
puts "I am a #{wizard_type} wizards. I'm very powerful"
end
def wizard_type=(wizard_type)
raise "Must not be blank" if wizard_type.empty?
@wizard_type = wizard_type
end
def cast_spell
puts "#{@name} cast a magic spell"
end
def teleport
puts "#{@name} teleported out of the area"
end
end
class Knight < LifeForm
include KnightAbilities
attr_reader :knight_type
@@acceptable_items[:great_sword] = 1
def initialize(name, age, height, knight_type)
super(name, age, height)
self.knight_type=(knight_type) # templar, hospistaller, teutonic
end
def move
puts "Slowly moves *clunk, *clunk"
end
def knight_type=(knight_type)
raise "Must not be blank" if knight_type.empty?
@knight_type = knight_type
end
def attack
puts "Attacks enemy"
end
def defence_stance
puts "changes to a d defence stance"
end
end
class Archer < LifeForm
include ArcherAbilities
attr_reader :archer_type
@@acceptable_items[:short_bow] = 2
def initialize(name, age, height, archer_type)
super(name, age, height)
self.archer_type=(archer_type)
end
def move
puts "moves swiftly light stepped"
end
def archer_type=(archer_type)
raise "Must not be blank" if archer_type.empty?
@archer_type = archer_type
end
def draw_bow
if @satchel[:short_bow]
puts "#{@name} draws their bow"
else
puts "#{@name} does not have a bow in their satchel"
end
end
def sneak
puts "#{@name} lightly tip toes"
end
end
| true |
6f696820278acc884333203d6b90f156cb8b503d
|
Ruby
|
ritabc/library-system
|
/lib/Patron.rb
|
UTF-8
| 640 | 3.109375 | 3 |
[
"MIT"
] |
permissive
|
class Patron
attr_reader(:name, :id)
def initialize(attributes)
@name = attributes.fetch(:name)
@id = attributes.fetch(:id)
end
def ==(another_thing)
self.name().==(another_thing.name())
end
def save
result = DB.exec("INSERT INTO patrons (name) VALUES ('#{@name}') RETURNING id;")
@id = result.first.fetch('id').to_i
end
def self.all
returned_patrons = DB.exec("SELECT * FROM patrons;")
patrons = []
returned_patrons.each do |patron|
name = patron.fetch('name')
id = patron.fetch('id')
patrons.push(Patron.new({:name => name, :id => id}))
end
patrons
end
end
| true |
a773254098bfccccaab11175a5ff415c37b06686
|
Ruby
|
JAtherton1072/Julie_Atherton_PDA
|
/Static_and_Dynamic_Task_A/specs/card_game_spec.rb
|
UTF-8
| 674 | 3.125 | 3 |
[] |
no_license
|
require('minitest/autorun')
require('minitest/rg')
require_relative('../card_game')
require_relative('../card')
class TestCardGame < Minitest::Test
def setup
@card1 = Card.new("Hearts", 1)
@card2 = Card.new("Spades", 8)
@card3 = Card.new("Clubs", 5)
@card4 = Card.new("Diamond", 3)
@cards = [@card1, @card2, @card3, @card4]
@card_game = CardGame.new
end
def test_check_for_ace
assert_equal(true, @card_game.check_for_ace(@card1))
end
def test_highest_card
assert_equal(8, @card_game.highest_card(@card1, @card2))
end
def test_cards_total
assert_equal("You have a total of 17", @card_game.cards_total(@cards))
end
end
| true |
c92db39d19f03c8356f91e77997758dece636385
|
Ruby
|
aki1502/pypret
|
/pypret.rb
|
UTF-8
| 39,735 | 2.765625 | 3 |
[] |
no_license
|
=begin
所属: 総合人間学部3回生
氏名:
学生番号:
概要: Pythonの翻訳機
操作法: ruby pypret.rb [Pythonの文法で書かれたプレーンテキスト]
動機: 似た課題を提出しそこねたため。
アピールポイント: 手間が掛かっている。
自己評価: 99点
改良すべき点: 下記のとおり機能に制限があるため、本物に寄せたい。
注意点: import文,raise文,try文,class文,yield文,async文,with文,
global文,nonlocal文には対応していません。
複素数に対応していません。
tuple,set,frozensetに対応していません。
"""hoge""", '''fuga'''に対応していません。
関数以外の属性参照、書き込みに対応していません。
イテレータとそうでないものをごっちゃにしています。
pythonの文としてエラーが生じる場合には対応していません。
classmethodに対応していません。
キーワード引数、デフォルト引数に対応していません。
組み込み関数ではascii,breakpoint,bytearray,bytes,
callable,classmethod,compile,complex,delattr,dir,eval,
exec,format,frozenset,getattr,globals,hasattr,help,id,
isinstance,issubclass,iter,locals,
memoryview,next,object,open,property,repr,set,setattr,
slice,staticmethod,super,tuple,type,varsには対応していません。
複数の記法に対応した関数ではそのうち一つしか使用できません。
組み込み定数ではNotImplementedと...(Ellipsis)には対応していません。
インデントは4字固定です。
その他バグ、実装漏れはいくらでもあると思われます、予めご了承下さい。
=end
require "securerandom"
filename = ARGV.shift
NullValues = [0, 0.0, [], {}, "", false, nil]
DefaultKey = lambda {|x| x}
BuiltinFunctions = {
abs: lambda {|x| x.abs()},
all: lambda {|x| (x.map() {|y| !NullValues.include?(y)}).all?()},
any: lambda {|x| (x.map() {|y| !NullValues.include?(y)}).any?()},
bin: lambda {|x| Pystr.new(x>=0 ? "0b"+x.to_s(2) : "-0b"+-x.to_s(2))},
bool: lambda {|x=false| !NullValues.include?(x)},
chr: lambda {|x| Pystr.new(x.chr())},
dict: lambda {|**kwargs| kwargs},
divmod: lambda {|x, a| x.divmod(a)},
enumerate: lambda {|x, start:0| (start...start+x.length()).zip(x)},
filter: lambda {|func, iter| iter.find_all() {|x| func.call(x)}},
float: lambda {|x=0.0| x.to_f()},
hash: lambda {|x| x.hash()},
hex: lambda {|x| Pystr.new(x>=0 ? "0x"+x.to_s(16) : "-0x"+-x.to_s(16))},
input: lambda {|x=""| print(x); Pystr.new(gets().chomp())},
int: lambda {|x=0| x.to_i()},
len: lambda {|x| x.length()},
list: lambda {|x=[]| x.to_a()},
map: lambda {|func, *iters| iters.transpose().map() {|x| func.call(*x)}},
max: lambda {|*x, key:DefaultKey, default:nil| x = x[0] if x[0].is_a?(Array); (default ? x+[default] : x).max_by(&key)},
min: lambda {|*x, key:DefaultKey, default:nil| x = x[0] if x[0].is_a?(Array); (default ? x+[default] : x).min_by(&key)},
oct: lambda {|x| Pystr.new(x>=0 ? "0o"+x.to_s(8) : "-0o"+-x.to_s(8))},
ord: lambda {|x| x.ord()},
pow: lambda {|base, exp, mod=nil| base.pow(exp, modulo=mod)},
print: lambda {|*o| print(o.map(&:to_s).join(" ")+"\n")},
range: lambda {|*s| (case s.length() when 1; 0...s[0] when 2; s[0]...s[1] else (s[0]...s[1]).step(s[2]) end).to_a()},
reversed: lambda {|x| x.reverse()},
round: lambda {|x| x.round()},
sorted: lambda {|x| x.sort()},
str: lambda {|x=""| Pystr.new(x)},
sum: lambda {|*x, init:0| x.sum(init)},
zip: lambda {|*x| l = x.map(&:length).min(); (x.map() {|y| y.take(l)}).transpose()},
}
BuiltinConstants = {
False: false,
True: true,
None: nil,
}
$gd = BuiltinFunctions.merge(BuiltinConstants)
$gd[:Integer] = {
as_integer_ratio: lambda {[where($address)[$name], 1]},
bit_length: lambda {|x| where($address)[$name].bit_length()},
from_bytes: nil, # 使えません
to_bytes: nil, # 使えません
}
$gd[:Float] = {
as_integer_ratio: lambda {f = where($address)[$name]; [f.numerator(), f.denominator()]},
fromhex: nil, # 使えません
hex: lambda {x=where($address)[$name]; x>=0 ? "0x"+x.to_s(16) : "-0x"+-x.to_s(16)},
is_integer: lambda {f = where($address)[$name]; f == f.to_i()},
}
$gd[:Array] = {
append: lambda {|x| where($address)[$name] <<= x},
clear: lambda {where($address)[$name] = []},
copy: lambda {where($address)[$name].clone()},
count: lambda {|x| where($address)[$name].count(x)},
extend: lambda {|t| where($address)[$name] += t},
index: lambda {|x| i = where($address)[$name].index()},
insert: lambda {|i, x| where($address)[$name][i, 0] = [x]},
pop: lambda {|i=-1| w = where($address); n = w[$name]; a = n.slice!(i); w[$name] = n; a},
remove: lambda {|x| w = where($address); n = w[$name]; i = n.index(x); n.slice!(i); w[$name] = n},
reverse: lambda {w = where($address); w[$name] = w[$name].reverse()},
sort: lambda {|x=DefaultKey| w = where($address); w[$name] = w[$name].sort_by(&x).to_a()},
}
$gd[:Pystr] = {
capitalize: lambda {Pystr.new(where($address)[$name].to_s().capitalize())},
casefold: lambda {Pystr.new(where($address)[$name].to_s().downcase(:fold))},
center: lambda {|width, fillchar=" "| Pystr.new(where($address)[$name].to_s().center(width, fillchar.to_s()))},
count: lambda {|sub| where($address)[$name].to_s().scan(sub.to_s()).length()},
encode: nil, # 使えません
endswith: lambda {|suffix| where($address)[$name].to_s().end_with?(suffix.to_s())},
expandtabs: nil, # 使えません
find: lambda {|sub| where($address)[$name].to_s().index(sub.to_s())},
format: nil, # 使えません
format_map: nil, # 使えません
index: lambda {|sub| a = where($address)[$name].to_s().index(sub.to_s()) ? a : (raise ValueError.new("inappropriate value"))},
isalnum: lambda {where($address)[$name].to_s().match?(/^\w+$/)},
isalpha: lambda {where($address)[$name].to_s().match?(/^[A-Za-z]+$/)},
isascii: lambda {where($address)[$name].to_s().ascii_only?()},
isdecimal: lambda {where($address)[$name].to_s().match?(/^\d+$/)},
isdigit: nil, # 使えません
isidentidier: lambda {where($address)[$name].to_s().match?(/^[A-Za-z_][\w]*$/)},
islower: lambda {where($address)[$name].to_s().match?(/^[a-z]+$/)},
isprintable: nil, # 使えません
isspace: lambda {where($address)[$name].to_s().match?(/^\s+$/)},
istitle: lambda {(where($address)[$name].to_s().split().map() {|w| w.match?(/^[A-Z]/)}).all?},
isupper: lambda {where($address)[$name].to_s().match?(/^[A-Z]+$/)},
join: lambda {|iterable| iterable.join(where($address)[$name])},
ljust: lambda {|width, padding=" "| Pystr.new(where($address)[$name].to_s().ljust(width, padding.to_s()))},
lower: lambda {Pystr.new(where($address)[$name].to_s().downcase())},
lstrip: lambda {Pystr.new(where($address)[$name].to_s().lstrip())},
maketrans: nil, # 使えません
partition: lambda {|sep| where($address)[$name].to_s().partition(sep.to_s()).map() {|s| Pystr.new(s)}},
replace: lambda {|old, new| Pystr.new(where($address)[$name].to_s().gsub(old.to_s(), new.to_s()))},
rfind: lambda {|sub| where($address)[$name].to_s().rindex(sub.to_s())},
rindex: lambda {|sub| a = where($address)[$name].to_s().rindex(sub.to_s()) ? a : (raise ValueError.new("inappropriate value"))},
rjust: lambda {|width, padding=" "| Pystr.new(where($address)[$name].to_s().rjust(width, padding.to_s()))},
rpartition: lambda {|sep| where($address)[$name].to_s().rpartition(sep.to_s()).map() {|s| Pystr.new(s)}},
rsplit: nil, # 使えません
rstrip: lambda {Pystr.new(where($address)[$name].to_s().rstrip())},
split: lambda {|sep=" ", maxsplit=0| where($address)[$name].to_s().split(sep.to_s(), maxsplit).map() {|x| Pystr.new(x)}},
splitlines: lambda {|keepends=false| where($address)[$name].to_s().split(/[\n\r\v\f\x1c\x1d\x1e]/).map() {|x| Pystr.new(x)}},
startswith: lambda {|prefix| where($address)[$name].to_s().start_with?(prefix)},
strip: lambda {Pystr.new(where($address)[$name].to_s().strip())},
swapcase: lambda {Pystr.new(where($address)[$name].to_s().swapcase())},
title: nil, # 使えません
translate: nil, # 使えません
upper: lambda {Pystr.new(where($address)[$name].to_s().upcase())},
zfill: nil # 使えません
}
$gd[:Hash] = {
clear: lambda {where($address)[$name] = {}},
copy: lambda {where($address)[$name].clone()},
fromkeys: nil, # 使えません
get: lambda {|key, default=nil| x = where($address)[$name][key] ? x : default},
items: lambda {where($address)[$name].each()},
keys: lambda {where($address)[$name].each_key()},
pop: lambda {|key, default=nil|w = where($address); h = w[$name]; v = h.delete(key); w[name] = h; v ? v : default},
popitem: lambda {w = where($address); h = w[$name]; v = h.shift(); w[name] = h; v},
setdefault: lambda {|key, default=nil| h = where($address)[$name]; (v = h[key]) ? v : (h[key] = default)},
update: lambda {|other| w = where($address); w[$name] = w[$name].merge(other)},
values: lambda {where($address)[$name].each_value()},
}
$address = []
$name = "".to_sym()
$args = {}
$return = false
$break = false
$continue = false
$answer = nil
class Integer
def to_string()
to_s()
end
end
class Float
def div(other)
super(other).to_f()
end
def to_string()
to_s()
end
end
class Array
def to_s()
"[#{map(&:to_string).join(", ")}]"
end
def foldr(m = nil, &o)
reverse().inject(m) {|m, i| m ? o[i, m] : i}
end
def to_string()
to_s()
end
end
class Hash
def each()
each_key()
end
def to_s()
"{#{(to_a().map() {|k, v| "#{k.to_string()}: #{v.to_string()}"}).join(", ")}}"
end
def to_string()
to_s()
end
end
class String
# カッコ外にstrが含まれているか判定する
def include_outside?(str)
honest = gsub(
/(?=(?:(?:([\"\'`])(?:(?:(?!\1)[^\\\n])|(?:\\[^\n])|(?:\1\1))*?\1)(?:(?:(?!\1)[^\\\n])|(?:\\[^\n])|(?:\1\1))*?)+\n?$)(?:\1(?:(?:(?!\1)[^\\\n])|(?:\\[^\n])|(?:\1\1))*?(?:\1))/,
"_"
) # "", '' とその内部にマッチする
while honest =~ /[\(\{\[]/
honest.gsub!(/\([^\(\)\{\}\[\]]*?\)/, "_")
honest.gsub!(/\{[^\(\)\{\}\[\]]*?\}/, "_")
honest.gsub!(/\[[^\(\)\{\}\[\]]*?\]/, "_") # (), {}, []とその内部にマッチする
end
honest.include?(str)
end
# 詰まった書き方の文字列にゆとりを与える
def spacia()
gsub(
/([\)\]\}\d])([^\.\{\}\[\]\(\) \n,\d])/,
'\1 \2',
).gsub(
/(\W(?:False|else|pass|None|break|in|True|is|return|and|continue|for|lambda|def|while|assert|del|not|elif|if|or))([\(\{\[])/,
'\1 \2',
)
end
end
class NilClass
def to_string()
"None"
end
def to_s()
"None"
end
end
class TrueClass
def to_string()
"True"
end
def to_s()
"True"
end
def to_i()
1
end
end
class FalseClass
def to_string()
"False"
end
def to_s()
"False"
end
def to_i()
0
end
end
# lambda式の中身、関数を文字列の形で保持する。
class Pylamb
def initialize(argstr, funcstr)
@argstrs = argstr.split(",").map(&:strip).find_all() {|s| s!=""}
@funcstr = funcstr
@key = ("(lambda)"+SecureRandom.alphanumeric()).to_sym()
end
def call(*args)
if i = @argstrs.index() {|a| a.include?("*")}
args = args[0...i] + [args[i..-1]]
end
argsyms = (@argstrs.map() {|s| s.delete_prefix("*")}).map(&:to_sym)
ary = [argsyms, args].transpose()
ld = Hash[*ary.flatten(1)]
where($address)[@key] = ld
$address << @key
r = read_expression(@funcstr)
$address.pop()
r
end
end
# 関数定義の中身、関数を文字列の形で保持する。
class Pyfunc
def initialize(funcname, argstr, funcstr)
@argstrs = argstr.split(",").map(&:strip).find_all() {|s| s!=""}
@funcstr = funcstr
@key = "(#{funcname})".to_sym()
end
def call(*args)
if i = @argstrs.index() {|a| a.include?("*")}
args = args[0...i] + [args[i..-1]]
end
argsyms = (@argstrs.map() {|s| s.delete_prefix("*")}).map(&:to_sym)
ary = [argsyms, args].transpose()
ld = Hash[*ary.flatten(1)]
where($address)[@key] = ld
$address << @key
read_suite(@funcstr)
$address.pop()
if $return
$return = false
return $answer
end
nil
end
end
# 内包表記の中身、式を文字列の形で保持する。
class Pycomp
def initialize(compstr)
@compstr = compstr
@key = ("(comprehension)"+SecureRandom.alphanumeric()).to_sym()
end
def call()
where($address)[@key] = {}
$address << @key
/^(.+?) (for .+? in .+)$/ =~ @compstr[1..-2]
if @compstr[0] == "["
r = l_recursion($1, $2, "True")
else
r = d_recursion($1, $2, "True")
end
$address.pop()
r
end
def l_recursion(head, rest, cond)
case rest
when /^for (.+?) in (.+?)( (?:if|for) .+)?$/
multiple = $1.include_outside?(",")
argstrs = $1.split(",").map(&:strip).find_all() {|s| s!=""}
argsyms = argstrs.map(&:to_sym)
rest = $3 ? $3.strip() : ""
arr = []
read_expression($2).each() do |args|
args = [args] unless multiple
argsyms.zip(args) do |k, v|
where($address)[k] = v
end
arr += l_recursion(head, rest, cond)
end
arr
when /^if (.+?)( (?:if|for) .+)?$/
rest = $2 ? $2.strip() : ""
l_recursion(head, rest, "#{cond} and #{$1}")
else
read_expression("bool(#{cond})") ? [read_expression(head)] : []
end
end
def d_recursion(head, rest, cond)
case rest
when /^for (.+?) in (.+?)( (?:if|for) .+)?$/
multiple = $1.include_outside?(",")
argstrs = $1.split(",").map(&:strip).find_all() {|s| s!=""}
argsyms = argstrs.map(&:to_sym)
rest = $3 ? $3.strip() : ""
hash = {}
read_expression($2).each() do |args|
args = [args] unless multiple
argsyms.zip(args) do |k, v|
where($address)[k] = v
end
hash.merge!(d_recursion(head, rest, cond))
end
hash
when /^if (.+?)( (?:if|for) .+)?$/
rest = $2 ? $2.strip() : ""
d_recursion(head, rest, "#{cond} and #{$1}")
else
/(.+?):(.+)/ =~ head
hash = {}
hash[read_expression($1)] = read_expression($2) if read_expression("bool(#{cond})")
hash
end
end
end
# pythonにおける挙動を模した文字列、ほとんどchars。
class Pystr < Array
def initialize(str)
self.replace(str.to_s().chars())
end
def [](index)
Pystr.new(self.to_s()[index])
end
def +(other)
Pystr.new((to_a()+other.to_a()).join())
end
def *(other)
Pystr.new((to_a()*other).join())
end
def include?(ps)
sl = length()
pl = ps.length()
0.upto(sl-pl) do |i|
return true if slice(i, pl) == ps
end
false
end
def to_s()
join()
end
def to_string()
"'#{self}'"
end
def to_i()
to_s().to_i()
end
def to_sym()
to_s().to_sym()
end
freeze
end
# エラー二種
class AssertionError < StandardError
end
class ValueError < StandardError
end
# ファイルを一行ずつ読み込んで文(statement)に分ける。
def read_file(file)
stmt = ""
bracket_level = 0
while line = file.gets()
line.sub!(/#.*$/, "") # コメントを外す
indent = count_indent(line)
ls = line.spacia().split(";")
ls.each_with_index() do |l, i|
l = " "*indent+l.strip()+"\n" if i > 0
bracket_level += bracket(l)
if l.strip() == ""
nil
elsif /^(.+?)\\$/ =~ l
stmt += $1
flag = true
elsif bracket_level > 0
stmt += l.chomp()
flag = true
elsif /^ .+?/ =~ l
stmt += l
flag = false
elsif /^else\s*:/ =~ l
stmt += l
flag = false
elsif /^elif\s*.+:/ =~ l
stmt += l
flag = false
elsif flag
read_statement(stmt+l)
stmt = ""
flag = false
else
read_statement(stmt)
stmt = l
end
end
end
read_statement(stmt)
raise SyntaxError.new("using return/break/continue inappropriately") if $return || $break || $continue
end
# 文の塊を読み解く。文(statement)に分ける。
def read_suite(suite)
stmt = ""
flag = false
bracket_level = 0
suite.split("\n").each() do |line|
line += "\n"
line.sub!(/#.*$/, "")
line.delete_prefix!(" "*4)
indent = count_indent(line)
ls = line.spacia().split(";")
ls.each_with_index() do |l, i|
l = " "*indent+l.strip()+"\n" if i > 0
bracket_level += bracket(l)
if l.strip() == ""
nil
elsif /^(.+)\\$/ =~ l
stmt += $1
flag = true
elsif bracket_level > 0
stmt += l.chomp()
flag = true
elsif /^ / =~ l
stmt += l
flag = false
elsif /^else\s/ =~ l
stmt += l
flag = false
elsif /^elif\s/ =~ l
stmt += l
flag = false
elsif flag
read_statement(stmt+l)
stmt = ""
flag = false
else
read_statement(stmt)
stmt = l
end
end
end
read_statement(stmt)
end
# 文を読み解く。
def read_statement(stmt)
return nil if $return || $break || $continue
stmt.strip!()
/^(.+?)\s+(.*)$/ =~ stmt+" "
case $1
when "assert"
if read_expression("bool(#{$2})")
nil
else
raise AssertionError.new("assertion failed: #{$2.strip()}")
end
when "pass"
nil
when "del"
dol2 = $2.split(",").map() {|x| x.strip().to_sym()}
dol2.each() do |k|
where($address)[k] = nil
end
when "return"
$answer = read_expression($2)
$return = true
when "break"
$break = true
when "continue"
$continue = true
when "if"
flag = false
suite = ""
stmt.split("\n").each() do |line|
case line
when /^if(.+):(.*?)$/ # if lst[:2]==[1,2]:lst[:2]=[2,1] みたいな例に対応できない。
dol2 = $2
if read_expression("bool(#{$1})")
if /^\s*$/ =~ dol2
flag = true
else
return read_statement(dol2)
end
end
when /^elif(.+):(.*?)$/
return read_suite(suite) if flag
flag = false
dol2 = $2
if read_expression("bool(#{$1})")
if /^\s*$/ =~ dol2
flag = true
else
return read_statement(dol2)
end
end
when /^else\s*?:(.*)$/
return read_suite(suite) if flag
flag = false
dol2 = $1
if /^\s*$/ =~ dol2
flag = true
else
return read_statement(dol2)
end
else
suite += line+"\n" if flag
end
end
read_suite(suite) if flag
when "while"
flag = false
expr = ""
suite = ""
stmt.split("\n").each() do |line|
case line
when /^while\s+(.+):(.*?)$/
flag = true
expr = "bool(#{$1})"
suite = " #{$2.strip()}\n"
when /^else\s*?:(.*)$/
while read_expression(expr)
$continue = false
read_suite(suite)
end
flag = false
suite = " #{$1.strip()}\n"
else
suite += line+"\n"
end
end
if flag
while read_expression(expr)
$continue = false
read_suite(suite)
end
else
read_suite(suite)
end
$break = false
when "for"
flag = false
argsyms = []
iterable = []
suite = ""
multiple = false
stmt.split("\n").each() do |line|
case line
when /^for (.+?) in (.+):(.*?)$/
flag = true
argstrs = $1.split(",").map(&:strip).find_all() {|s| s!=""}
argsyms = argstrs.map(&:to_sym)
iterable = read_expression($2)
suite = " #{$3.strip()}\n"
multiple = $1.include_outside?(",")
when /^else\s*?:(.*?)$/
iterable.each() do |args|
$continue = false
args = [args] unless multiple
argsyms.zip(args) do |k, v|
where($address)[k] = v
end
read_suite(suite)
end
flag = false
suite = " #{$1.strip()}\n"
else
suite += line+"\n"
end
end
if flag
iterable.each() do |args|
$continue = false
args = [args] unless multiple
argsyms.zip(args) do |k, v|
where($address)[k] = v
end
read_suite(suite)
end
else
read_suite(suite)
end
$break = false
when "def"
funcname = ""
argstr = ""
suite = ""
stmt.split("\n").each() do |line|
case line
when /^def\s+([A-Za-z_][\w]*)\((.*)\)\s*:(.*)$/
funcname = $1
argstr = $2
suite = " #{$3.lstrip()}\n"
else
suite += line+"\n"
end
end
d = where($address)[:"@"] || []
where($address)[:"@"] = nil
where($address)[funcname.to_sym()] = d.foldr(Pyfunc.new(funcname, argstr, suite), &:call)
else
w = where($address)
case stmt
when /^@(.+)$/ # decorator
w = where($address)
w[:"@"] = (w[:"@"] ? w[:"@"] : []) + [read_expression($1)]
when /^(.+?)(\*\*=|\/\/=|>>=|<<=)(.+)$/ # 累算代入文(3字のもの)
augop = $2
ser, val = $1.strip(), read_expression($3)
h, k = assignment_hash_and_key(ser)
case augop
when "**="
h[k] **= val
when "//="
h[k] /= val
when ">>="
h[k] >>= val
when "<<="
h[k] <<= val
end
when /^(.+?)(\+=|\-=|\*=|\/=|%=|&=|\^=|\|=)(.+)$/ # 累算代入文(2字のもの)
augop = $2
ser, val = $1.strip(), read_expression($3)
h, k = assignment_hash_and_key(ser)
case augop
when "+="
h[k] += val
when "-="
h[k] -= val
when "*="
h[k] *= val
when "/="
h[k] /= val.to_f()
when "%="
h[k] %= val
when "&="
h[k] &= val
when "^="
h[k] ^= val
when "|="
h[k] |= val
end
else
if stmt.include_outside?("=") # 代入文
serval = stmt.split("=").map(&:strip)
unite = []
serval.each_with_index() do |ser, i|
unite << i if ser == ""
end
unite.reverse().each() do |i|
serval[i-1..i+1] = "#{serval[i-1]}==#{serval[i+1]}"
end
unite = []
serval.each_with_index() do |ser, i|
unite << i if ser.end_with?("!", ">", "<")
end
unite.reverse().each() do |i|
serval[i..i+1] = "#{serval[i]}=#{serval[i+1]}"
end
val = read_expression(serval[-1].include_outside?(",") ? "[#{serval[-1]}]" : serval[-1])
serval[0..-2].each() do |x|
if x =~ /^(.+)\[(.+?)\]$/
read_expression($1)[read_expression($2)] = val
elsif x.include_outside?(",")
argstrs = x.split(",").map(&:strip).find_all() {|k| k!=""}
if i = argstrs.index() {|a| a.include?("*")}
l = val.length()-argstrs.length()+1
va = val[0...i] + [val[i, l]] + val[i+l..-1] # func(0, 1, 2) -> def(*arg)
else
va = val
end
argsyms = (argstrs.map() {|s| s.delete_prefix("*")}).map(&:to_sym)
argsyms.zip(va) do |k, v|
case k
when /^(.+)\[(.+?)\]$/
read_expression($1)[read_expression($2)] = v
else
where($address)[k] = v
end
end
else
where($address)[x.to_sym()] = val
end
end
else #式文
read_expression(stmt)
end
end
end
nil
end
# '', "", (), [], {}を主に内側から先に評価し、dictに格納していく。
def rename_quotes(expr)
return nil if expr == nil
# 文字列リテラルを先に評価し、dictに格納する。
expr.gsub!(
/(?=(?:(?:([\"\'`])(?:(?:(?!\1)[^\\\n])|(?:\\[^\n])|(?:\1\1))*?\1)(?:(?:(?!\1)[^\\\n])|(?:\\[^\n])|(?:\1\1))*?)+\n?$)(?:\1(?:(?:(?!\1)[^\\\n])|(?:\\[^\n])|(?:\1\1))*?(?:\1))/
) do |matched|
key = "quote$"+SecureRandom.alphanumeric()
where($address)[key.to_sym()] = read_atom(matched)
key
end
expr.sub!(/lambda (.+?):(.+)/) do #lambda
key = "lambda$"+SecureRandom.alphanumeric()
where($address)[key.to_sym()] = Pylamb.new($1, $2)
key
end if expr.include_outside?("lambda ")
expr.sub!(/^(.+) if (.+?) else (.+?)$/) do # if_else
key = "condop$"+SecureRandom.alphanumeric()
where($address)[key.to_sym()] = read_expression("bool(#{$2})") ? read_expression($1) : read_expression($3)
key
end if expr.include_outside?(" if ")
expr.sub!(/^(.+) or (.+?)$/) do # or
key = "or$"+SecureRandom.alphanumeric()
where($address)[key.to_sym()] = read_expression("bool(#{$1})") ? read_expression($1) : read_expression($2)
key
end if expr.include_outside?(" or ")
expr.sub!(/^(.+) and (.+?)$/) do # and
key = "and$"+SecureRandom.alphanumeric()
where($address)[key.to_sym()] = read_expression("bool(#{$1})") ? read_expression($2) : read_expression($1)
key
end if expr.include_outside?(" and ")
# (), [], {}を先に評価し、dictに格納していく。
while /[\(\[\{]/ =~ expr
expr = rename_brackets(expr)
expr = rename_braces(expr)
expr = rename_parentheses(expr)
end
expr
end
def rename_parentheses(expr)
while /\([^\(\)\[\]\{\}]*?\)/ =~ expr
while /[A-Za-z_$][\w\.$]*\([^\(\)\[\]\{\}]*?\)/ =~ expr
while /([A-Za-z_$][\w\.$]*)\.([A-Za-z_$][\w$]*?)\(([^\(\)\[\]\{\}]*?)\)/ =~ expr
# method_callを先に評価し、dictに格納する。
expr.gsub!(/([A-Za-z_$][\w\.$]*)\.([A-Za-z_$][\w$]*?)\(([^\(\)\[\]\{\}]*?)\)/) do
key = "method$"+SecureRandom.alphanumeric()
argstrs = $3.split(",").find_all() {|x| x!=""}
args = []
kwargs = {}
argstrs.each() do |x|
if x.include_outside?("=")
if x[x.index("=")+1] == "="
args << read_expression(x)
else
k, v = x.split("=", 2)
kwargs[Pystr.new(k.strip())] = read_expression(v)
end
elsif x.strip().start_with?("*")
read_expression(x).each() do |v|
args << v
end
else
args << read_expression(x)
end
end
args << kwargs unless kwargs.empty?()
m = $gd[read_expression($1).class()::name.to_sym()][$2.strip().to_sym()]
$name = $1.to_sym()
where($address)[key.to_sym()] = m.call(*args)
key
end
end
# function_callを先に評価し、dictに格納する。
expr.sub!(/([A-Za-z_$][\w_$]*)\(([^\(\)\[\]\{\}]*?)\)/) do
key = "function$"+SecureRandom.alphanumeric()
funcname = $1
argstrs = $2.split(",").find_all() {|x| x!=""}
args = []
kwargs = {}
argstrs.each() do |x|
if x.include_outside?("=")
if x[x.index("=")+1] =~ /\=/
args << read_expression(x)
elsif x[x.index("=")-1] =~ /!|>|</
args << read_expression(x)
else
k, v = x.split("=", 2)
kwargs[Pystr.new(k.strip())] = read_expression(v)
end
elsif x.strip().start_with?("*")
read_expression(x[1..-1]).each() do |v|
args << v
end
else
args << read_expression(x)
end
end
args << kwargs unless kwargs.empty?()
where($address)[key.to_sym()] = read_atom(funcname).call(*args)
key
end
end
# ()内を先に評価し、dictに格納する。
expr.sub!(/\(([^\(\)\[\]\{\}]+?)\)/) do
key = "parentheses$"+SecureRandom.alphanumeric()
where($address)[key.to_sym()] = read_expression($1)
key
end
end
expr
end
def rename_brackets(expr)
while /\[[^\[\]\{\}]*?\]/ =~ expr
while /[a-zA-Z_$][\w\._$]*\[[^\[\]\{\}]+?\]/ =~ expr || /\[[^\[\]]+? for [^\[\]]+\]/ =~ expr
while /\[[^\[\]]+? for [^\[\]]+\]/ =~ expr
# リスト内包表記を先に評価し、dictに格納する。
expr.gsub!(/\[[^\[\]]+? for [^\[\]]+\]/) do |matched|
key = "list_comprehension$"+SecureRandom.alphanumeric()
where($address)[key.to_sym()] = Pycomp.new(matched)
key+"()"
end
end
# x[index]を先に評価し、dictに格納する。
expr.gsub!(/([A-Za-z_$][\w\._$]*)\[([^\[\]\{\}]+?)\]/) do
key = "index$"+SecureRandom.alphanumeric()
dol1 = read_atom($1)
where($address)[key.to_sym()] =
case $2
when /^(.*?)\:(.*?)\:(.*?)$/
dol2 = read_expression($1) || 0
dol3 = (read_expression($2) || 0)-1
dol4 = read_expression($3) || 1
dol1[dol2..dol3].each_slice(dol4).map(&:first)
when /^(.*?)\:(.*?)$/
dol2 = read_expression($1) || 0
dol3 = (read_expression($2) || 0)-1
dol1[dol2..dol3]
when /^(.+?)$/
dol1[read_expression($1)]
else
raise expr
end
key
end
end
# [expressions...](list)を先に評価し、dictに格納する。
expr.gsub!(/\[([^\[\]\{\}]*?)\]/) do
key = "list$"+SecureRandom.alphanumeric()
dol1 = rename_parentheses($1)
where($address)[key.to_sym()] = dol1.split(",").map() {|x| read_expression(x)}
key
end
end
expr
end
def rename_braces(expr)
while /\{([^\{\}]*?)\}/ =~ expr
while /\{[^\{\}]+? for [^\{\}]+\}/ =~ expr
# dict内包表記を先に評価し、dictに格納する。
expr.gsub!(/\{[^\{\}]+? for [^\{\}]+\}/) do |matched|
key = "dict_comprehension$"+SecureRandom.alphanumeric()
where($address)[key.to_sym()] = Pycomp.new(matched)
key+"()"
end
end
# {key: value...}(dict)を先に評価し、dictに格納する。
expr.gsub!(/\{([^\(\)\[\]\{\}]*?)\}/) do
key = "dict$"+SecureRandom.alphanumeric()
d = {}
$1.split(",").map() do |kv|
k, v = kv.split(":").map() {|x| read_expression(x)}
d[k] = v
end
where($address)[key.to_sym()] = d
key
end
end
expr
end
# 式を読み解く。
def read_expression(expr)
return false if $break
return nil if expr == nil
expr = rename_quotes(expr.strip())
case expr
when /^not (.+?)$/ # not
!read_expression("bool(#{$1})")
when /^(.+)(\sin\s|\sis\s|<|>|!=|==)(.+?)$/ # 所属や同一性のテストを含む比較
dol1, dol3 = $1, $3
case $2.strip()
when "in"
case dol1.strip()
when /\Wnot$/
!read_expression(dol3).include?(read_expression(dol1[0..-4]))
else
read_expression(dol3).include?(read_expression(dol1))
end
when "is"
case dol3.strip()
when /^not\W/
!read_expression(dol1).equal?(read_expression(dol3[3..-1]))
else
read_expression(dol1).equal?(read_expression(dol3))
end
when "<"
if dol3[0] != "="
read_expression(dol1) < read_expression(dol3)
else
read_expression(dol1) <= read_expression(dol3[1..-1])
end
when ">"
if dol3[0] != "="
read_expression(dol1) > read_expression(dol3)
else
read_expression(dol1) >= read_expression(dol3[1..-1])
end
when "!="
read_expression(dol1) != read_expression(dol3)
when "=="
read_expression(dol1) == read_expression(dol3)
else
raise expr
end
when /^(.+)\|(.+?)$/ # |
read_expression($1) | read_expression($2)
when /^(.+)\^(.+?)$/ # ^
read_expression($1) ^ read_expression($2)
when /^(.+)&(.+?)$/ # &
read_expression($1) & read_expression($2)
when /^(.+)[(<<)(>>)](.+?)$/ # <<, >>
case $2
when "<<"
read_expression($1) << read_expression($3)
when ">>"
read_expression($1) >> read_expression($3)
else
raise expr
end
when /^(.+)(\+|\-)(.+?)$/ # add, sub
case $2
when "+"
read_expression($1) + read_expression($3)
when "-"
read_expression($1) - read_expression($3)
else
raise expr
end
when /^(.*[^\*\/%])(\*|\/|\/\/|%)([^\*\/%].*?)$/ # mul, div, mod
case $2
when "*"
read_expression($1) * read_expression($3)
when "/"
read_expression($1) / read_expression($3).to_f()
when "//"
read_expression($1).div(read_expression($3))
when "%"
read_expression($1) % read_expression($3)
else
raise expr
end
when /^(\+|\-|~)(.+)$/ # add, sub
case $1
when "+"
+read_expression($2)
when "-"
-read_expression($2)
when "~"
~read_expression($2)
else
raise expr
end
when /^(.+?)\*\*(.+)$/ # exp
read_expression($1) ** read_expression($2)
when /^\s*$/ # blank
nil
else
read_atom(expr)
end
end
# アトムと属性参照を読み解く。
def read_atom(atom)
return nil if atom == nil
atom = atom.strip()
case atom
# literal
when /^"(.*?)"$/
Pystr.new($1)
when /^'(.*?)'$/
Pystr.new($1)
when /^([\d]+?)$/
$1.to_i()
when /^([\d\.]+?)$/
$1.to_f()
# attribute
when /^(.+)\.(.+?)$/
dol1 = read_expression($1)
what($address, dol1.class()::name.to_sym())[$2.to_sym()]
# identifier
else
what($address, atom.to_sym())
end
end
# global_dict(変数全体のハッシュ)のaddressに示された番地の中身(主に局所変数のハッシュ)を呼び出す。
def where(address)
address.inject($gd, &:[])
end
# global_dict(変数全体のハッシュ)のaddressに示された番地のから参照できる中身を呼び出す。
def what(address, key)
address.length().downto(0) do |i|
v = where(address[0...i])[key]
return v if v
end
where([])[key]
end
def bracket(line)
l = line.gsub(
/(?=(?:(?:([\"\'`])(?:(?:(?!\1)[^\\\n])|(?:\\[^\n])|(?:\1\1))*?\1)(?:(?:(?!\1)[^\\\n])|(?:\\[^\n])|(?:\1\1))*?)+\n?$)(?:\1(?:(?:(?!\1)[^\\\n])|(?:\\[^\n])|(?:\1\1))*?(?:\1))/,
"_"
)
l.count("([{")-l.count(")]}")
end
def assignment_hash_and_key(ser)
case ser
when /^(.+)\[(.+?)\]$/
return read_expression($1), read_expression($2)
else
return where($address), ser.to_sym()
end
end
def count_indent(line)
c = 0
l = line.chars()
while l.shift() == " "
c += 1
end
c
end
File.open(filename, "r") do |fin|
read_file(fin)
end
| true |
d0e713cf63d8796ddc1f2f0cbfe5ad0886984da7
|
Ruby
|
xdkernelx/phase-0-tracks
|
/ruby/client.rb
|
UTF-8
| 2,981 | 3.359375 | 3 |
[] |
no_license
|
#Nestor Alvarez
#DBC, Bobolinks
#5.3, 20160808, 17:17 PDT
class Client
# Initializes Client object with keyword arguments
# Params:
# +args+:: arguments match parameters, have default values
def initialize(first_name: "", last_name: "", age: 0, children: 0,\
decor_theme: "", vip_member: false, budget: 0)
@first_name = first_name
@last_name = last_name
@age = age
@children = children
@decor_theme = decor_theme
@vip_member = vip_member
@budget = budget
end
# Initializes Client object with keyword arguments
# Params:
# +args+:: arguments match parameters, have default values
# Using self contained methods prevents resetting object values
def update(first_name: "", last_name: "", age: 0, children: 0,\
decor_theme: "", vip_member: nil, budget: 0)
change_first_name(first_name)
change_last_name(last_name)
change_age(age)
change_children(children)
change_decor(decor_theme)
if(!vip_member.nil?)
@vip_member = vip_member
end
change_budget(budget)
end
#Mutator Methods
def change_name(first_name, last_name = "")
@first_name = first_name
@last_name = last_name if !last_name.empty?
return nil
end
def change_last_name(last_name)
@last_name = last_name if !last_name.empty?
return nil
end
def change_first_name(first_name)
@first_name = first_name if !first_name.empty?
return nil
end
def change_age(age)
@age = age if age > 0
return nil
end
def change_children(num)
@children = num if num >= 0
end
def change_decor(str)
@decor_theme = str if !str.empty?
return nil
end
def change_vip
@vip_member = !@vip_member
return nil
end
def change_budget(num)
@budget = num if num >= 0
return nil
end
#Accessor Methods
def get_last_name
return @last_name
end
def get_first_name
return @first_name
end
def get_age
return @age
end
def get_children
return @children
end
def get_decor
return @decor_theme
end
def vip?
return @vip_member
end
def get_budget
return @budget
end
# Returns a hash using the object's instance variables (coverted to symbols)
# instance_variables returns an Arrays, .each iterates through the array values
def get_hash
hash = {}
instance_variables.each {|var| hash[var.to_s.delete("@").to_sym] = instance_variable_get(var) }
hash
end
# Prints readable output
def print_client
puts("\n*****VIP Member*****") if @vip_member
puts("Your client's name is: #{@first_name} #{@last_name if !@last_name.empty?}")
puts("Your client's age is: #{@age}")
puts("Your client has #{@children} children.")
puts("Your client's decoration theme: #{@decor_theme}")
puts("Your client's budget is: #{@budget}")
end
end
| true |
2e01db67a6dd99d2ca6fb5ef1a48719bea06b5e7
|
Ruby
|
youngorchen/ruby-codesnippet
|
/scripts/nodes-man/test_ip.rb
|
UTF-8
| 943 | 2.734375 | 3 |
[] |
no_license
|
ip_list=%w(
172.16.0.85
172.16.0.86
172.16.0.87
172.16.0.88
172.16.0.89
172.16.0.90
172.16.0.91
172.16.0.92
172.16.0.93
172.16.0.94
172.16.0.95
172.16.0.96
172.16.0.97
172.16.0.98
172.16.0.99
172.16.0.100
172.16.0.101
172.16.0.102
172.16.0.103
172.16.0.104
172.16.0.105
172.16.0.106
172.16.0.107
172.16.0.108
172.16.0.109
172.16.0.110
172.16.0.111
172.16.0.112
172.16.0.113
172.16.0.114
)
TIMES=1
def pingable?(addr)
cmd = "ping -c #{TIMES} #{addr} 2>&1"
#puts cmd
output = `#{cmd}`
#puts output
res = true
res = false if output.include? "100% packet loss"
res = false if output.include? "unknown host"
res
end
#puts "Shizam!" if pingable? "google1.com"
def ping_result(ip)
res = "."
res = "X" unless pingable? ip
puts "test #{ip}" + "."*20 + res
end
while true
ip_list.each do |ip|
ping_result(ip)
end
sleep 10
end
| true |
010a3c4500cf85f2f2876126f5162135460fb83c
|
Ruby
|
cheezenaan/procon
|
/atcoder/abc115/b.rb
|
UTF-8
| 109 | 2.703125 | 3 |
[] |
no_license
|
# frozen_string_literal: true
n = gets.to_i
ps = n.times.map { gets.to_i }
puts ps.inject(:+) - ps.max / 2
| true |
8b0341d5586e51355f60fea8b82ca961869f825f
|
Ruby
|
gadgetguy82/codeclan_caraoke_hw
|
/room.rb
|
UTF-8
| 1,122 | 3.421875 | 3 |
[] |
no_license
|
require_relative('./bar_tab')
class Room
attr_reader :number, :guests, :songs
def initialize(number, capacity)
@number = number
@guests = []
@songs = []
@capacity = capacity
@bar_tab = BarTab.new
end
def check_in(guest)
if @guests.length < @capacity
@guests << guest
else
return "Room #{@number} is full, #{guest.name} cannot be checked in."
end
end
def check_out(guest)
if @guests.include?(guest)
@guests.delete(guest)
else
return "#{guest.name} is not in room #{@number}"
end
end
def add_song(song)
if song.is_a?(Array)
@songs += song
else
@songs << song
end
end
def get_tab
return @bar_tab.tab
end
def get_total_cash_of_guests
@guests.reduce(0) {|total, guest| total + guest.wallet}
end
def add_to_bar_tab(amount)
if get_total_cash_of_guests >= get_tab + amount
@bar_tab.add_to_bar_tab(amount)
else
return "Service refused, you don't have enough cash to cover it."
end
end
def settle_tab(till)
till.add_sale(get_tab)
@bar_tab.clear_tab
end
end
| true |
4b4867c532c99594c991203088ed726e987bc18e
|
Ruby
|
JoinJanay-JS/my-each-online-web-pt-090819
|
/my_each.rb
|
UTF-8
| 131 | 3.28125 | 3 |
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
require "pry"
def my_each(array) # put argument(s) here
i = 0
while i < array.length
yield(array[i])
i = i + 1
end
end
end
| true |
9949ef17b06de8e088e1d44b9853181e7a68698e
|
Ruby
|
Fernandocgomez/crypto-trading-app-api
|
/app/models/user.rb
|
UTF-8
| 2,031 | 2.578125 | 3 |
[] |
no_license
|
class User < ApplicationRecord
# DB relationships
has_secure_password
has_one :portafolio
# Global validations
validates :username, :email, :password, :first_name, :last_name, presence: true
validates :password_confirmation, presence: true, on: :create
validates :email, :username, uniqueness: true
# First_name & Last_name
validates :first_name, :last_name, format: { with: /\A[a-zA-Z]+\z/,
message: "only allows letters" }
# username validation
validates :username, format: { with: /\A[a-zA-Z0-9]+\z/,
message: "only allows letters and numbers" }
validates :username, length: { minimum: 8 }
validates :username, length: { maximum: 15 }
# email validation
validates :email, presence: true, 'valid_email_2/email': true
validates :email, 'valid_email_2/email': { mx: true }
validates :email, 'valid_email_2/email': { disposable: true }
validates :email, 'valid_email_2/email': { disposable_domain: true }
validates :email, 'valid_email_2/email': { disallow_subaddressing: true }
validates :email, 'valid_email_2/email': { message: "is not a valid email" }
validates :email, confirmation: true
validates :email_confirmation, presence: true, on: :create
# password validation
def password_requirements_are_met
rules = {
" must contain at least one lowercase letter" => /[a-z]+/,
" must contain at least one uppercase letter" => /[A-Z]+/,
" must contain at least one digit (0-9)" => /\d+/,
" must contain at least one special character (!,@,#,$,%,^,&,*,+,-,=)" => /[^A-Za-z0-9]+/
}
rules.each do |message, regex|
errors.add( :password, message ) unless password.match( regex )
end
end
validate :password_requirements_are_met
validates :password, format: { without: /\s/, message: "No spaces allowed" }
validates :password, length: { minimum: 8 }
validates :password, length: { maximum: 20 }
end
| true |
2581fc4637f4650525db2cb5daf883d5d588c1e5
|
Ruby
|
codyruby/cursus_thp_bis
|
/week4/the_gossip_project/lib/gossip.rb
|
UTF-8
| 715 | 2.796875 | 3 |
[] |
no_license
|
class Gossip
attr_accessor :author, :content
def initialize(author, content)
@author = author
@content = content
end
def save
CSV.open("./lib/db/gossip.csv", "ab") do |csv|
csv << [@author, @content]
end
end
def self.all
all_gossips = []
CSV.read("./lib/db/gossip.csv").each do |csv_line|
all_gossips << Gossip.new(csv_line[0], csv_line[1])
end
return all_gossips
end
# def find(id)
# gossips_choices = []
# CSV.read("./lib/db/gossip.csv").each do |csv|
# all_gossips << Gossip.new(csv[id])
# end
# return gossips_choices
# end
end
| true |
0750121637328aaa407462a090e90d104b2679c2
|
Ruby
|
stefanosu/ruby-objects-belong-to-lab-dumbo-web-051319
|
/lib/song.rb
|
UTF-8
| 126 | 2.71875 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require_relative "artist.rb"
class Song
attr_accessor :title, :artist
def initialize()
@title = title
end
end
| true |
e91894ae9def35b6e5f267473bb6e6f16846ac55
|
Ruby
|
MrSnickers/FIS
|
/todos/todo14/triangle_class.rb
|
UTF-8
| 615 | 3.421875 | 3 |
[] |
no_license
|
### CLASS TRIANGLE
class Triangle
exception :TriangleError
attr_reader :side1, :side2, :side3, :kind
def initialize(a, b, c)
@kind
@side1 = a
@side2 = b
@side3 = c
self.assign_kind
end
def assign_kind
if side1 == side2
if side1 == side3
@kind = :equilateral
else
@kind = :isosceles
end
elsif side2 == side3 || side1 == side3
@kind = :isosceles
else
@kind = :scalene
end
end
def side_check(a,b,c)
raise TriangleError, "This triangle does not have allowable dimentions" if a == 0 || b == 0 || c == 0
end
end
| true |
e672805e83a682d961581dbb4d834cf724395c00
|
Ruby
|
KrisHolley/hello_world
|
/numbers_minedminds.rb
|
UTF-8
| 206 | 2.84375 | 3 |
[] |
no_license
|
count = 1
until count == 101
if count %3 == 0 &&
count %5 == 0
puts"mined minds"
elsif
count %3 == 0
puts"mined"
elsif
count %5 == 0
puts"minds"
else
puts count
end
count = count+1
end
| true |
6382e6b6f8f963b1ee2fb4dc117303f86ef0c080
|
Ruby
|
tmknom/tech-news
|
/lib/tasks/command/sidekiq.rake
|
UTF-8
| 3,746 | 2.59375 | 3 |
[] |
no_license
|
namespace :command do
namespace :sidekiq do
require 'sidekiq/api'
require 'awesome_print'
# SidekiqのAPIドキュメント
# https://github.com/mperham/sidekiq/wiki/API
desc 'Sidekiqのジョブ一覧を表示'
task :show_all do
queues, scheduled_set, retry_set, dead_set = [], [], [], []
queue_names.each { |queue_name| Sidekiq::Queue.new(queue_name).each { |job| queues << create_pretty_job(job) } }
Sidekiq::ScheduledSet.new.each { |job| scheduled_set << create_pretty_job(job) }
Sidekiq::RetrySet.new.each { |job| retry_set << create_pretty_job(job) }
Sidekiq::DeadSet.new.each { |job| dead_set << create_pretty_job(job) }
show(queues.sort, scheduled_set.sort, retry_set.sort, dead_set.sort)
end
desc 'Sidekiqのジョブ一覧を詳細表示'
task :show_verbose_all do
queues, scheduled_set, retry_set, dead_set = [], [], [], []
queue_names.each { |queue_name| Sidekiq::Queue.new(queue_name).each { |job| queues << create_verbose_job(job) } }
Sidekiq::ScheduledSet.new.each { |job| scheduled_set << create_verbose_job(job) }
Sidekiq::RetrySet.new.each { |job| retry_set << create_verbose_job(job) }
Sidekiq::DeadSet.new.each { |job| dead_set << create_verbose_job(job) }
show(queues, scheduled_set, retry_set, dead_set)
end
desc 'Sidekiqのステータスを表示'
task :show_status do
ap JSON.parse(Sidekiq::Stats.new.to_json)['stats']
end
desc 'Sidekiqのジョブを全てクリア'
task :clear_all do
queues = 0
queue_names.each { |queue_name|
result = Sidekiq::Queue.new(queue_name).clear
queues += result[0]
}
scheduled_set = Sidekiq::ScheduledSet.new.clear
retry_set = Sidekiq::RetrySet.new.clear
dead_set = Sidekiq::DeadSet.new.clear
cleared ={}
cleared.store(:queue, queues) unless queues == 0
cleared.store(:scheduled, scheduled_set) unless scheduled_set == 0
cleared.store(:retry, retry_set) unless retry_set == 0
cleared.store(:dead, dead_set) unless dead_set == 0
result = {cleared: cleared}
ap result unless cleared.empty?
ap 'job is empty!' if cleared.empty?
end
private
def queue_names
queue_names = []
Sidekiq::Queue.all.each { |queue| queue_names << queue.name }
queue_names
end
def show(queues, scheduled_set, retry_set, dead_set)
jobs = create_jobs(queues, scheduled_set, retry_set, dead_set)
ap jobs unless jobs.empty?
ap 'job is empty!' if jobs.empty?
end
def create_jobs(queues, scheduled_set, retry_set, dead_set)
result ={}
result.store(:queue, queues) unless queues.empty?
result.store(:scheduled, scheduled_set) unless scheduled_set.empty?
result.store(:retry, retry_set) unless retry_set.empty?
result.store(:dead, dead_set) unless dead_set.empty?
result
end
def create_pretty_job(job)
job_class = job.args[0]['job_class']
arguments = job.args[0]['arguments'].join(',')
queue = job.queue
created_at = format_time(job.created_at)
"#{created_at} #{queue} #{job_class}#perform(#{arguments})"
end
def create_verbose_job(job)
{
class: job.args[0]['job_class'],
arguments: job.args[0]['arguments'].size == 1 ? job.args[0]['arguments'][0] : job.args[0]['arguments'],
queue: job.queue,
created_at: format_time(job.created_at),
enqueued_at: format_time(job.enqueued_at),
jid: job.jid,
job_id: job.args[0]['job_id']
}
end
def format_time(time)
time.in_time_zone('Tokyo').strftime('%Y/%m/%d %H:%M:%S')
end
end
end
| true |
c9dbcb793d2a652e2046222eb9b02ef0e57d2a61
|
Ruby
|
TransformCore/trade-tariff-backend
|
/app/services/meursing_measure_component_resolver_service.rb
|
UTF-8
| 1,545 | 2.59375 | 3 |
[
"LicenseRef-scancode-proprietary-license",
"MIT"
] |
permissive
|
class MeursingMeasureComponentResolverService
def initialize(root_measure, meursing_measures)
@root_measure = root_measure
@meursing_measures = meursing_measures
end
def call
# Iterate root measure components and replace placeholder meursing components with meursing measure answer components
root_measure.measure_components.map do |root_measure_component|
if root_measure_component.meursing?
meursing_component_for(root_measure_component)
else
root_measure_component
end
end
end
private
attr_reader :root_measure, :meursing_measures
def meursing_component_for(root_measure_component)
applicable_measures = meursing_measures.select do |meursing_measure|
meursing_measure.measure_type_id == root_measure_component.duty_expression.meursing_measure_type_id
end
# Occasionally we get multiple meursing measures that apply to multiple geographical areas based on the contained geographical area logic. We should aim to retrieve the most specific answer if possible
most_specific_measure = applicable_measures.find do |meursing_measure|
meursing_measure.geographical_area_id == root_measure.geographical_area_id
end
applicable_measure = most_specific_measure.presence || applicable_measures.first
return nil unless applicable_measure
# Meursing measures only ever have a single component
component = applicable_measure.measure_components.first
Api::V2::Measures::MeursingMeasureComponentPresenter.new(component)
end
end
| true |
bc1d84090d6ca6513b27a9b37f9400af3ca7d1b8
|
Ruby
|
prurph/algo-practice
|
/merge_sort.rb
|
UTF-8
| 1,404 | 4 | 4 |
[] |
no_license
|
# merge sort: O(n*log n) average and maximum; quicksort usually faster in prac
# not in-place, there are stable implementations but this is not
# recursive: base case return array if length <= 1
# otherwise divide array into left, right halves, call merge(left, right)
# merge merges arrays by checking if left or right empty, otherwise comparing
# left.first and right.first, then returning the smaller + merge(left, right)
# with the first removed with left.drop(1) or right.drop(1)
class Array
def merge_sort
if self.length <= 1 then self
else
mid = self.length / 2
left = self[0..mid - 1].merge_sort
right = self[mid..-1].merge_sort
left.merge(right)
end
end
def merge(right)
if empty?
right
elsif right.empty?
self
elsif self.first < right.first
[self.first] + (self.drop(1)).merge(right)
else
[right.first] + merge(right.drop(1))
end
end
end
# Non instance method version:
# def merge_sort(arr)
# if arr.length <= 1
# arr
# else
# mid = arr.length / 2
# left = arr[0..mid - 1]
# right = arr[mid..-1]
# merge(left, right)
# end
# end
# def merge(left, right)
# if left.empty?
# right
# elsif right.empty?
# left
# elsif left.first < right.first
# [left.first] + merge(left.drop(1), right)
# else
# [right.first] + merge(left, right.drop(1))
# end
# end
| true |
30157929353bcd1483e7af9db154cec5cd01299a
|
Ruby
|
drakontis/hackerrank
|
/tutorial/cracking_the_code_interview/ransome_note.rb
|
UTF-8
| 754 | 3.5625 | 4 |
[
"MIT"
] |
permissive
|
# https://www.hackerrank.com/challenges/ctci-ransom-note/problem
#!/bin/ruby
def check_words_availability(magazine, ransom)
all_words_available = true
ransom.each do |ransom_element|
magazine.each_with_index do |magazine_element, magazine_index|
if ransom_element != magazine_element
all_words_available = false
else
magazine.delete_at(magazine_index)
all_words_available = true
break
end
end
break unless all_words_available
end
all_words_available
end
m,n = gets.strip.split(' ')
m = m.to_i
n = n.to_i
magazine = gets.strip
magazine = magazine.split(' ').sort
ransom = gets.strip
ransom = ransom.split(' ').sort
puts check_words_availability(magazine, ransom) ? 'Yes' : 'No'
| true |
ed0580c6de46ea7000d1733e6e1f6dd2561dee93
|
Ruby
|
geckods/CodeChef
|
/February19/chefing.rb
|
UTF-8
| 288 | 2.796875 | 3 |
[] |
no_license
|
require 'set'
if File.exists?("input")
$stdin = File.open("input")
$stdout = File.open("output","w")
end
t = gets.to_i
t.times do
n = gets.to_i
myset = gets.chomp.each_char.to_a
(n-1).times do
set = gets.chomp.each_char.to_a
myset = myset&set
end
puts myset.uniq.size
end
| true |
476a48d3fe63e47783f444682b017e165ea26304
|
Ruby
|
bdarfler/CodeKata
|
/ruby/02/KataTwo.rb
|
UTF-8
| 1,815 | 3.59375 | 4 |
[] |
no_license
|
class KataTwo
def self.chop_iterative(target, list)
first = 0
last = list.size - 1
while first <= last do
mid = (first + last) / 2
if list[mid] < target
first = mid + 1
elsif list[mid] > target
last = mid - 1
else
return mid
end
end
return -1
end
def self.chop_recursive(target, list)
return recursive_helper(target, list, 0, list.size - 1)
end
def self.recursive_helper(target, list, first, last)
return -1 if first > last
mid = first + (last - first) / 2
if list[mid] < target
recursive_helper(target, list, mid + 1, last)
elsif list[mid] > target :
recursive_helper(target, list, first, mid - 1)
else
mid
end
end
def self.slice_recursive(target, list)
slice_recursive_helper(target, list, 0)
end
def self.slice_recursive_helper(target, list, offset)
return -1 unless list.any?
mid = list.size / 2
if list[mid] < target
slice_recursive_helper(target, list[mid+1, list.size], mid + 1)
elsif list[mid] > target
slice_recursive_helper(target, list[0, mid], offset)
else
offset + mid
end
end
def self.slice_iterative(target, list)
offset = 0
while list.any? do
mid = list.size / 2
if list[mid] < target
offset = mid + 1
list = list[mid + 1, list.size]
elsif list[mid] > target
list = list[0, mid]
else
return offset + mid
end
end
return -1
end
def self.chop(target, list)
return -1 unless list.any?
mid = list.size / 2
if list[mid] < target
ret = chop(target, list[mid + 1, list.size])
ret == -1 ? ret : mid + 1 + ret
elsif list[mid] > target
chop(target, list[0, mid])
else
mid
end
end
end
| true |
eec013b0a21111b305a61fd6be94a6c3e2c1916f
|
Ruby
|
wangjohn/eager_db
|
/lib/eager_db/prediction/probability_calculator.rb
|
UTF-8
| 2,389 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
module EagerDB
module Prediction
class ProbabilityCalculator
attr_reader :time_threshold, :probability_storage
def initialize(logs, time_threshold)
@logs = logs
@time_threshold = time_threshold
@probability_storage = Hash.new { |h,statement| h[statement] = MarkovProbabilityStorage.new(statement) }
@processed = false
end
def process
grouped_logs = @logs.group_by { |log| log.user }
grouped_logs.each do |user, user_logs|
process_user_logs(user_logs)
end
@processed = true
end
def likely_transitions(probability_threshold = 0.8)
process unless @processed
transitions = Hash.new { |h,k| h[k] = [] }
probability_storage.each do |match, markov_storage|
markov_storage.probabilities.select do |preload, probability|
if probability > probability_threshold
transitions[match] << preload
end
end
end
transitions
end
private
def process_user_logs(user_logs)
rolling_group = []
index = 1
current_log = user_logs[0]
while index < user_logs.length or !rolling_group.empty?
if index < user_logs.length
log = user_logs[index]
if log.processed_at > current_log.processed_at + time_threshold
current_log = make_transitions(current_log, rolling_group)
end
rolling_group << log
index += 1
else
current_log = make_transitions(current_log, rolling_group)
end
end
end
def make_transitions(current_log, rolling_group)
current_storage = probability_storage[current_log.non_binded_sql]
current_storage.increment_total_occurrences
verified_transitions = rolling_group.take_while do |log|
(log.processed_at - current_log.processed_at) <= time_threshold
end
unique_logs = verified_transitions.uniq do |log|
log.non_binded_sql
end
unique_logs.each do |log|
current_storage.add_transition(
log.processed_at - current_log.processed_at,
log.non_binded_sql)
end
rolling_group.shift
end
end
end
end
| true |
61550c84b69e2bf6565bb603afb041115f340a69
|
Ruby
|
ninjudd/rupture
|
/lib/rupture/reader.rb
|
UTF-8
| 2,116 | 3.328125 | 3 |
[
"MIT"
] |
permissive
|
require 'set'
module Rupture
class Reader
def initialize(input)
@input = input
@buffer = []
end
def ungetc(*chars)
@buffer.concat(chars)
@space = false
chars.last
end
def getc
while c = (@buffer.shift || @input.getc.chr)
if c =~ /[\s,;]/
next if @space
@space = true
@input.gets if c == ';'
return ' '
else
@space = false
return c
end
end
end
def peekc
unget(getc)
end
def read
case c = getc
when '(' then read_list
when '[' then read_list(Array, ']')
when '{' then read_map
when '"' then read_string
when ':' then read_keyword
when ' ' then read
when /\d/ then ungetc(c); read_number
when /\w/ then ungetc(c); read_symbol
when '-'
case c = getc
when /\d/ then ungetc(c); -read_number
else ungetc('-', c); read_symbol
end
when '#'
case c = getc
when '{' then read_list(Set, '}')
end
end
end
def read_list(klass = List, terminator = ')')
list = klass.new
while c = getc
return list if c == terminator
ungetc(c)
list << read
end
end
def read_map
map = {}
while c = getc
return map if c == '}'
ungetc(c)
list[read] = read
end
end
def read_string
string = ''
while c = getc
return string if c == '"'
string << c
end
end
def read_while(pattern, token = '')
while c = getc
if c !~ pattern
ungetc(c)
return token
end
token << c
end
end
def read_symbol(prefix = '@')
read_while(/[^\s{}\[\]()]/, prefix).to_sym
end
def read_keyword
read_symbol('')
end
def read_number
number = read_while(/[-\d]/)
if (c = getc) == '.'
read_while(/\d/, number << '.').to_f
else
ungetc(c)
number.to_i
end
end
end
end
| true |
8c38d0681cd141d6120e233285dffc56871dbfa0
|
Ruby
|
audy/phylograph
|
/lib/cluster.rb
|
UTF-8
| 1,502 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
# A SIMPLE INTERFACE FOR CDHIT
class Cluster
def self.compute_clusters(similarity, filename)
output = "#{filename}_out"
# Compute clusters
run_cdhit filename, output, similarity
# Parse CDHIT Output
parse_cdhit output
# Return results
end
def self.run_cdhit(input, output, similarity)
res = system "./lib/cd-hit-est \
-i #{input} \
-o #{output} \
-c 0.#{similarity} \
-T 0 \
> /dev/null"
unless res
$stderr.puts "cdhit failed"
quit -1
end
end
def self.parse_cdhit(output)
clusters = Hash.new
clusters[:counts] = Hash.new 0
clusters[:reps] = Hash.new
# Number of sequences per cluster
handle = File.open "#{output}.clstr"
i, c = 0, 0
handle.each do |line|
if line[0] == '>'
if c > 0
clusters[:counts][i] = c
c = 0
i += 1
end
else
c += 1
end
line.split(/\t/)
clusters[:counts][i] += 1
end
# Representative for each cluster
# They're in order of cluster number
handle = File.open "#{output}"
cluster = -1
handle.each_with_index do |line|
if line[0] == '>'
cluster += 1
else
clusters[:reps][cluster] = line[0..-2]
end
end
# Make sure they have the same keys
raise "Something went wrong with CD-HIT parsing" \
unless (clusters[:counts].keys - clusters[:reps].keys) == []
clusters
end
end
| true |
9e5b295c69d45a231ec2b8315f3207e8d1c1d084
|
Ruby
|
sebaquevedo/desafiolatam
|
/mayorque.rb
|
UTF-8
| 183 | 3.546875 | 4 |
[
"MIT"
] |
permissive
|
#fixnums
puts " ingrese dos numeros"
numero1=gets.chomp.to_i
numero2=gets.chomp.to_i
if numero1 > numero2
puts "el primer numero es mayor"
else puts "el segundo numero es mayor"
end
| true |
08674258dc6106a238ca158cb9bc4cc9754b5fe3
|
Ruby
|
vitorkaio/controle-estoque-ruby
|
/outros/learn/arrays_loops.rb
|
UTF-8
| 879 | 4.34375 | 4 |
[] |
no_license
|
# Array com 10 primeiros números.
lista = Array(0..10)
puts "***** For ****"
for cont in lista
puts "Número: #{cont}"
end
# Entrar com dados em uma array.
=begin
l = Array.new()
for cont in 0..3
print "Entre com uma string: "
l.push(gets())
end
for cont in l
puts "Dado: #{cont}"
end
=end
puts "***** While ****"
# loop com while.
i = 0
while i < 3
puts i
i += 1
end
puts "***** Do while ****"
# Do while
x = 0
begin
puts x
x += 1
end while x < 3
puts "***** Each ****"
lis = [10, 20, 1, 30, 5, 0, 3]
lis.each do |valor|
puts valor
end
puts "***** Times ****"
5.times do |cont|
puts cont
end
puts "***** loop Infinito ****"
cont = 0
loop do
puts cont
cont += 1
break if cont == 20
end
puts "***** Array push sugar ****"
lis << 13
puts lis
# next -> Próxima interação do loop.
# redo -> Volta o loop mais interno.
# break -> Sai do loop.
| true |
d729c9abb3d44d19cb888b37729489e69199f7b3
|
Ruby
|
wmleidy/advent-of-code-ruby
|
/problems/9-minimum-distance.rb
|
UTF-8
| 1,424 | 4.1875 | 4 |
[] |
no_license
|
# --- Day 9: All in a Single Night ---
##### A Version of The Traveling Salesman Problem #####
# Every year, Santa manages to deliver all of his presents in a single night.
# This year, however, he has some new locations to visit; his elves have provided him the distances between every pair of locations. He can start and end at any two (different) locations he wants, but he must visit each location exactly once. What is the shortest distance he can travel to achieve this?
# For example, given the following distances:
# London to Dublin = 464
# London to Belfast = 518
# Dublin to Belfast = 141
# The possible routes are therefore:
# Dublin -> London -> Belfast = 982
# London -> Dublin -> Belfast = 605
# London -> Belfast -> Dublin = 659
# Dublin -> Belfast -> London = 659
# Belfast -> Dublin -> London = 605
# Belfast -> London -> Dublin = 982
# The shortest of these is London -> Dublin -> Belfast = 605, and so the answer is 605 in this example.
# What is the distance of the shortest route?
# --- Part Two ---
# The next year, just to show off, Santa decides to take the route with the longest distance instead.
# He can still start and end at any two (different) locations he wants, and he still must visit each location exactly once.
# For example, given the distances above, the longest route would be 982 via (for example) Dublin -> London -> Belfast.
# What is the distance of the longest route?
| true |
c2a33d06ffb2d91fcac8bada02c50ebf3061c141
|
Ruby
|
exp-ndrew/triangle_classifier
|
/lib/Triangle.rb
|
UTF-8
| 534 | 3.765625 | 4 |
[] |
no_license
|
class Triangle
def initialize side1, side2, side3
@side1 = side1.to_i
@side2 = side2.to_i
@side3 = side3.to_i
end
def side1
@side1
end
def side2
@side2
end
def side3
@side3
end
def classify
tri_arr = []
tri_arr << @side1
tri_arr << @side2
tri_arr << @side3
tri_arr.sort!
if (@side1 == @side2) && (@side2 == @side3)
"equilateral"
elsif (tri_arr[0] == tri_arr[1] || tri_arr[1] == tri_arr[2])
"isosceles"
else
"scalene"
end
end
end
| true |
204fc567be77e935c3f7a485e9978a1042865a35
|
Ruby
|
plkujaw/boris-bikes
|
/spec/dockingstation_spec.rb
|
UTF-8
| 1,413 | 2.875 | 3 |
[] |
no_license
|
require "dockingstation"
describe DockingStation do
it "responds to 'release_bike'" do
expect(subject).to respond_to(:release_bike)
# expect{DockingStation.new.release_bike}.not_to raise_error
end
it "releases working bike" do
bike = Bike.new
expect(bike).to be_working
end
it "responds to 'dock(bike)' with 1 argument" do
expect(subject).to respond_to(:dock).with(1).argument
# expect(DockingStation.new).to respond_to.(:dock).with(1).argument
end
it "docks released bike" do
bike = Bike.new
expect(subject.dock(bike)).to eq [bike]
# expect(DockingStation.new).to respond_to(:bike)
end
it "raises an error when docking station has no space for a new bike" do
# bike = Bike.new
# subject.dock(bike)
# bike = Bike.new
docking_station = DockingStation.new
DockingStation::DEFAULT_CAPACITY.times { docking_station.dock Bike.new}
expect{docking_station.dock(Bike.new)}.to raise_error "Docking station full"
end
describe '#release_bike' do
it 'releases a bike' do
bike = Bike.new
docking_station = DockingStation.new
docking_station.dock(bike)
# we want to release the bike we docked
expect(docking_station.release_bike).to eq bike
end
it "raises an error when there are no bikes available" do
expect { subject.release_bike }.to raise_error "No bikes available"
end
end
end
| true |
da9e98e643097a8013c0f4305184b1fce9e7c85b
|
Ruby
|
oneiros/canned_meat
|
/lib/canned_meat/template_renderer.rb
|
UTF-8
| 615 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
module CannedMeat
class TemplateRenderer
def initialize(template, markdown)
@template = template
@markdown = markdown
end
def render_html
html = render_markdown(::Redcarpet::Render::HTML)
VariableReplacer.new(content: html)
.replace @template.html
end
def render_text
text = render_markdown(Redcarpet::TextRenderer)
VariableReplacer.new(content: text)
.replace @template.text
end
private
def render_markdown(renderer_class)
::Redcarpet::Markdown.new(
renderer_class
).render(@markdown)
end
end
end
| true |
f888e8af9862a641ea37b01304a3a9b823a47273
|
Ruby
|
DavidBarriga-Gomez/market_1908
|
/lib/market.rb
|
UTF-8
| 1,364 | 3.375 | 3 |
[] |
no_license
|
class Market
attr_reader :name, :vendors
def initialize(name)
@name = name
@vendors = []
end
def add_vendor(vendor)
@vendors.push vendor
end
def vendor_names
@vendors.map do |vendor|
vendor.name
end
end
def vendors_that_sell(food_item)
@vendors.find_all do |vendor|
vendor.inventory[food_item] != 0
end
end
def sorted_item_list
food_array = []
@vendors.each do |vendor|
vendor.inventory.find_all do |item|
food_array.push item[0]
end
end
food_array.sort.uniq
end
def total_inventory
food_hash = Hash.new(0)
@vendors.each do |vendor|
vendor.inventory.each do |item|
food_hash[item[0]] += item[1]
end
end
food_hash
end
def sell(food_item, quantity)
if total_inventory[food_item] < quantity
false
else total_inventory[food_item] >= quantity
# total_inventory[food_item] - quantity && true
# @vendors.each do |vendor|
# vendor.inventory[food_item] - quantity
vendors_that_sell(food_item).each do |vendor|
vendor.inventory[food_item] - quantity
# if quantity >= vendor.inventory[food_item]
# binding.pry
# quantity -= vendor.inventory[food_item]
# until vendor.inventory[food_item] == 0
# end
# end
end
end
end
end
| true |
3d4c04cfbd0e6112d534432a6d71cb0f23545d5c
|
Ruby
|
AdrienTchinda/scrapping
|
/lib/bourse.rb
|
UTF-8
| 513 | 2.8125 | 3 |
[] |
no_license
|
require "nokogiri"
require "open-uri"
page = Nokogiri::HTML(open("https://coinmarketcap.com/all/views/all/"))
all_prices_links = page.xpath('//a[@class="price"]')
arrayprices = []
i = 0
all_symbols_links = page.xpath('//td[@class="text-left col-symbol"]')
arraysymbol = []
all_symbols_links.each do |symbol_link|
arraysymbol << symbol_link.text
end
all_prices_links.each do |price_link|
arrayprices << price_link.text
end
tableau = Hash[arraysymbol.zip arrayprices]
print tableau
| true |
5b03afb847017057f9e75dfd32e212356be17240
|
Ruby
|
bucknermr/algorithms
|
/interview_cake/stock_price/stock_price.rb
|
UTF-8
| 1,447 | 4.03125 | 4 |
[] |
no_license
|
def get_max_profit(stock_prices)
raise "Need at least 2 stock prices" if stock_prices.length < 2
min = stock_prices.first
best_profit = -1/0.0
stock_prices.drop(1).each do |price|
profit = price - min
best_profit = profit if profit > best_profit
min = price if price < min
end
best_profit
end
# tests
def run_tests
desc = 'price goes up then down'
actual = get_max_profit([1, 5, 3, 2])
expected = 4
assert_equal(actual, expected, desc)
desc = 'price goes down then up'
actual = get_max_profit([7, 2, 8, 9])
expected = 7
assert_equal(actual, expected, desc)
desc = 'price goes up all day'
actual = get_max_profit([1, 6, 7, 9])
expected = 8
assert_equal(actual, expected, desc)
desc = 'price goes down all day'
actual = get_max_profit([9, 7, 4, 1])
expected = -2
assert_equal(actual, expected, desc)
desc = 'price stays the same all day'
actual = get_max_profit([1, 1, 1, 1])
expected = 0
assert_equal(actual, expected, desc)
desc = 'one price raises error'
assert_raises(desc) {
get_max_profit([1])
}
desc = 'empty array raises error'
assert_raises(desc) {
get_max_profit([])
}
end
def assert_equal(a, b, desc)
if a == b
puts "#{desc} ... PASS"
else
puts "#{desc} ... FAIL: #{a} != #{b}"
end
end
def assert_raises(desc)
begin
yield
puts "#{desc} ... FAIL"
rescue
puts "#{desc} ... PASS"
end
end
run_tests()
| true |
3a247b18897d05c616ac48f3f1f4073dfdbdd269
|
Ruby
|
arbonap/interview-practice
|
/stringcompression.rb
|
UTF-8
| 873 | 4.125 | 4 |
[] |
no_license
|
#Implement a method to perform basic string compression
#usign the counts of repeated characters.
# For example, the string 'aabcccccaaa' would
#become 'a2b1c5a3'. If the "compressed" string
# would not become smaller than the original string, your
# method should return the original string.
#Assume string has only uppercase and lowercase letters (a-z).
def string_compression(txt)
output = {}
txt.each_char do |char|
if output.include? char
output[char] += 1
else
output[char] = 1
end
end
string_keys = output.keys
string_values = output.values
compressed = string_keys.zip(string_values).flatten.join
if compressed.length > txt.length
return txt
else
return compressed
end
end
puts string_compression("aabcccccaa") #should return a4b1c5
puts string_compression("abcdefghijklmno") #should return abcdefghijklmno
| true |
dba869a3f34eda75573b85209def4edaf16f9962
|
Ruby
|
Hives/makers-process-reviews
|
/03-checkout/lib/checkout.rb
|
UTF-8
| 401 | 3.453125 | 3 |
[] |
no_license
|
def checkout(basket)
return -1 if basket.is_a?(Integer)
return -1 if basket != basket.upcase
a_count = basket.count("A")
b_count = basket.count("B")
c_count = basket.count("C")
d_count = basket.count("D")
price = 50 * a_count
discount = (a_count/3) * 20
price += 30 * b_count
discount += (b_count/2) * 15
price += 20 * c_count
price += 15 * d_count
price - discount
end
| true |
e8c6ef6f673a598d1aa1cfca84370a349cff9a94
|
Ruby
|
zombiecalypse/SinatraStory
|
/iteration06/app/models/user.rb
|
UTF-8
| 1,432 | 3.0625 | 3 |
[] |
no_license
|
require 'rubygems'
require 'bcrypt'
module Models
class User
attr_reader :name, :password_hash, :password_salt
@@users = {}
def initialize(name, password)
# Promise me to never store a password in clear text in your
# database!
# BCrypt is good *because* it is slow, making it hard to crack
# by brute force.
pw_salt = BCrypt::Engine.generate_salt
pw_hash = BCrypt::Engine.hash_secret(password, pw_salt)
@name = name
@password_hash = pw_hash
@password_salt = pw_salt
@texts = {}
end
def texts
@texts.values
end
def add_text( title, text )
new_text = Text.new(title, text, self)
@texts[new_text.id] = new_text
new_text.save
new_text
end
def remove_text( id )
@texts.delete(id)
throw "something weird happened" if @texts[id]
end
def save
raise "Duplicated user" if @@users.has_key? name and @@users[name] != self
@@users[name] = self
end
def self.available? name
not @@users.has_key? name
end
def self.by_name name
@@users[name]
end
def self.login name, password
user = @@users[name]
return false if user.nil?
user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
end
def self.all
@@users.values
end
def self.reset
@@users = {}
end
end
end
| true |
da7f3e2a78604da648b45784c8335b3b7d09a133
|
Ruby
|
schacon/cucumber
|
/lib/cucumber/ast/feature.rb
|
UTF-8
| 2,430 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
module Cucumber
module Ast
# Represents the root node of a parsed feature.
class Feature #:nodoc:
attr_accessor :file, :language
attr_writer :features
attr_reader :name
def initialize(background, comment, tags, name, feature_elements)
@background, @comment, @tags, @name, @feature_elements = background, comment, tags, name.strip, feature_elements
background.feature = self if background
@feature_elements.each do |feature_element|
feature_element.feature = self
end
end
def accept(visitor)
return if $cucumber_interrupted
visitor.visit_comment(@comment) unless @comment.empty?
visitor.visit_tags(@tags)
visitor.visit_feature_name(@name)
visitor.visit_background(@background) if @background
@feature_elements.each do |feature_element|
visitor.visit_feature_element(feature_element)
end
end
def source_tag_names
@tags.tag_names
end
def accept_hook?(hook)
@tags.accept_hook?(hook)
end
def next_feature_element(feature_element, &proc)
index = @feature_elements.index(feature_element)
next_one = @feature_elements[index+1]
proc.call(next_one) if next_one
end
def backtrace_line(step_name, line)
"#{file_colon_line(line)}:in `#{step_name}'"
end
def file_colon_line(line)
"#{@file}:#{line}"
end
def tag_count(tag)
if @tags.respond_to?(:count)
@tags.count(tag) # 1.9
else
@tags.select{|t| t == tag}.length # 1.8
end
end
def feature_and_children_tag_count(tag)
children_tag_count = @feature_elements.inject(0){|count, feature_element| count += feature_element.tag_count(tag)}
children_tag_count + tag_count(tag)
end
def short_name
first_line = name.split(/\n/)[0]
if first_line =~ /#{language.keywords('feature', true)}:(.*)/
$1.strip
else
first_line
end
end
def to_sexp
sexp = [:feature, @file, @name]
comment = @comment.to_sexp
sexp += [comment] if comment
tags = @tags.to_sexp
sexp += tags if tags.any?
sexp += [@background.to_sexp] if @background
sexp += @feature_elements.map{|fe| fe.to_sexp}
sexp
end
end
end
end
| true |
614d8bb68024d1ac8e0b9889071be56f8c4683a6
|
Ruby
|
steve-lynx/DuckQuack
|
/examples/test11.rb
|
UTF-8
| 587 | 2.53125 | 3 |
[
"Apache-2.0"
] |
permissive
|
#-*- ruby -*-
# Supporto per database sqlite
DB = app.database_connect
DB.create_table!(:contatti) {
String :nome
String :cognome
String :telefono
}
DB[:contatti].insert(
nome: "Massimo",
cognome: "Ghisalberti",
telefono: "1234567890")
DB[:contatti].insert(
nome: "Stefano",
cognome: "Penge",
telefono: "0000000000000")
DB[:contatti].insert(
nome: "Anacleto",
cognome: "Mitraglia",
telefono: "0000000000000")
risultato = DB[:contatti].where(nome: "Massimo").first
stampa("il numero di telefono è: " + risultato[:telefono])
app.database_disconnect
| true |
4ce213a33f9953288a0252ed62ba31665bdf0f3e
|
Ruby
|
WitoldSlawko/Ruby_Files_Tamer
|
/lib/rft/mutation.rb
|
UTF-8
| 2,801 | 3.140625 | 3 |
[
"MIT"
] |
permissive
|
module Mutation
def self.create(to_create)
File.open(to_create, "w");
end
def self.overwrite_text(to_overwrite)
puts "Write text to " + to_write + ' :'
new_text = STDIN.gets.chomp
File.open(to_write, "w").syswrite(new_text)
end
def self.append_text(to_write)
puts "Append text to " + to_write + ' :'
new_text = STDIN.gets.chomp
File.open(to_write, "a+") do |line|
line.puts "\n" + "Following text was added at: " +Time.now.inspect + " \n"+ new_text + "\n"
end
end
def self.end_of_line(to_add, end_line)
arr_lines = IO.readlines(to_add)
arr_lines.collect! do |ending|
ending += end_line + "\n"
end
#puts arr_lines
end_file = File.new(to_add, "w+")
for ender in 0...arr_lines.length
end_file.syswrite(arr_lines[ender])
end
end
def self.clear_text(to_clear)
File.open(to_clear, "w").syswrite('')
end
def self.rename(from, to)
File.rename(from, to)
end
def self.replace(to_rep, with_word)
if to_rep.is_a? String
arr_lines = IO.readlines(to_rep)
arr_lines.each do |replacer|
replacer.gsub!(/#{ARGV[2]}/, with_word )
end
rep_file = File.new(to_rep, "w");
for rep in 0...arr_lines.length do
rep_file.syswrite(arr_lines[rep])
end
elsif to_rep.is_a? Array
to_rep.each do |replacement|
arr_lines = IO.readlines(replacement)
arr_lines.each do |replacer|
replacer.gsub!(/#{ARGV[2]}/, with_word )
end
rep_file = File.new(replacement, "w");
for rep in 0...arr_lines.length do
rep_file.syswrite(arr_lines[rep])
end
end
end
end
def self.copy(to_copy, new_name)
arr_lines = IO.readlines(to_copy)
rep_file = File.new(new_name, "w");
for rep in 0...arr_lines.length do
rep_file.syswrite(arr_lines[rep])
end
end
def self.remove(to_file, to_remove)
if to_file.is_a? String
arr_lines = IO.readlines(to_file)
arr_lines.each do |remover|
remover.gsub!(/#{to_remove}/, '' )
end
rep_file = File.new(to_file, "w");
for rep in 0...arr_lines.length do
rep_file.syswrite(arr_lines[rep])
end
elsif to_remove.is_a? Array
to_remove.each do |removement|
arr_lines = IO.readlines(removement)
arr_lines.each do |remover|
remover.gsub!(/#{to_remove}/, '' )
end
rep_file = File.new(removement, "w");
for rep in 0...arr_lines.length do
rep_file.syswrite(arr_lines[rep])
end
end
end
end
def self.del(to_delete)
if to_delete.is_a? String
File.delete(to_delete)
elsif to_delete.is_a? Array
to_delete.each do |to_del|
File.delete(to_del)
end
end
end
end
| true |
04a4d1139673474fcc2eeafe6de06d3dd926037f
|
Ruby
|
Thorsson/open-weather
|
/app/models/weather.rb
|
UTF-8
| 1,333 | 2.8125 | 3 |
[] |
no_license
|
class Weather < ActiveRecord::Base
validates :description, :temperature, :speed, :data, :lat, :lon, presence: true
TIME_RANGE = 15.minutes
LOCATION_PRECISION = 2
def self.current_weather location
location = optimize_location(location)
if (report = latest_weather(location))
report
else
update_weather_for(location)
end
end
def self.update_weather_for(location)
data = OpenWeatherApi.get_weather(location)
content = {}
content[:description] = data['weather'].first['description'] if data['weather'].first['description']
content[:temperature] = data['main']['temp'].to_f if data['main']['temp']
content[:speed] = data['wind']['speed'].to_f if data['wind']['speed']
content[:data] = data
content[:lat] = location['lat']
content[:lon] = location['lon']
Weather.create!(content)
end
def self.latest_weather location
where(lat: location['lat'], lon: location['lon'], created_at: (TIME_RANGE.ago)..Time.now).first
end
def self.optimize_location location
location['lat'] = location['lat'].to_f.round(LOCATION_PRECISION) if location['lat']
location['lon'] = location['lon'].to_f.round(LOCATION_PRECISION) if location['lon']
location
end
def as_json(options = {})
super(:only => [:description, :temperature, :speed])
end
end
| true |
ae6979bb73e6ff83a56fcf4bc7117c2de024f3ad
|
Ruby
|
SanaNasar/ruby_inheritance
|
/inheritance.rb
|
UTF-8
| 478 | 4.09375 | 4 |
[] |
no_license
|
class Box
def initialize(w, h)
@width = w
@height = h
end
def get_area
@width * @height
end
end
class BigBox < Box
def print_area
@area = @width * @height
end
end
# 1.) How would I create a box? How could I create a BigBox?
# 1.) How would I print the area of the BigBox?
b1 = Box.new(4, 6) # Creating a box
puts b1.get_area # printing the area of box
b2 = BigBox.new(4, 5)# Creating a BigBox
puts b2.print_area # printing the area of BigBox
| true |
4da61343d1463ef95118c5336d84431cba89ab25
|
Ruby
|
benwbrum/antique_date
|
/lib/antique_date/documentary_date.rb
|
UTF-8
| 720 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
module AntiqueDate
class DocumentaryDate
@regime = nil
@verbatim = nil
# # proleptic Gregorian
# def to_gregorian
#
# end
#
# produces a YYYY-MM-DD string resembling ISO-8601 containing a version of the date on the document with year normalized to a January 1 New Year's Day.
# No proleptization is done, so "February 11, 1731/2" becomes '1732-02-11' rather than '1732-02-22'
# For missing values, a mid-point is selected, so that 'July 1800' yields '1800-06-31' and
def to_searchable
end
# produces a YYYY-MM_DD string similar to that produced by to_searchable, except that
def to_sortable(alphabetic=true)
end
end
end
| true |
1f53c87203c27eee253b7420c1e7ec1c4f4f7a92
|
Ruby
|
nybblr/dotfiles
|
/bin/mlv_batch
|
UTF-8
| 381 | 2.625 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
videos = ARGV.map do |path|
if File.directory?(path)
Dir[File.join(path, "*.MLV")]
else
path
end
end.flatten
videos.each do |video|
directory = video.chomp(File.extname(video))
Dir.mkdir(directory)
puts "Extracting #{video}..."
# puts "mlv_dump --dng -o \"#{directory}\" \"#{video}\""
`mlv_dump --dng -o "#{directory}/" "#{video}"`
end
| true |
0b1de178dbab393cbf5ca7101187b8d6f8f49c40
|
Ruby
|
urimaro/progate_ruby
|
/ruby_v/11_index.rb
|
UTF-8
| 87 | 3.15625 | 3 |
[] |
no_license
|
require "date"
birthday = Date.new(1974, 12, 13)
puts birthday
puts birthday.sunday?
| true |
df6ccdf444cf046249d9620f4ab7e2c720e04550
|
Ruby
|
caporta/oo-data-normalization-001
|
/lib/song.rb
|
UTF-8
| 265 | 2.984375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'pry'
class Song
attr_accessor :artist, :title
def initialize() end
def slugify
slug = @title.gsub(" ", "_").downcase
file = Tempfile.new([slug, ".txt"], "tmp")
file.write("#{self.artist.name} - #{self.title}")
file.close
end
end
| true |
e0ac94c9da6558d518e314cb1092d8e3de556e22
|
Ruby
|
enspirit/wlang
|
/spec/unit/scope/test_null_scope.rb
|
UTF-8
| 815 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
require 'spec_helper'
module WLang
class Scope
describe NullScope do
let(:scope){ NullScope.new }
it 'throws on fetch' do
lambda{ scope.fetch(:who) }.should throw_symbol(:fail)
end
it 'throws on fetch even on `self`' do
lambda{ scope.fetch(:self) }.should throw_symbol(:fail)
end
it 'returns pushed scope on push' do
pushed = ObjectScope.new(12)
scope.push(pushed).should eq(pushed)
end
it 'coerces pushed scope on push' do
scope.push(12).should be_a(ObjectScope)
end
it 'returns nil on pop' do
scope.pop.should be_nil
end
it 'returns an empty array of subjects' do
scope.subjects.should eq([])
end
end # describe NullScope
end # class Scope
end # module WLang
| true |
4bd6a6822e6ce489afc974f2de096fede9c9d076
|
Ruby
|
Victor-Arruda/Gerenciador-de-Matriculas
|
/app/models/student.rb
|
UTF-8
| 464 | 2.71875 | 3 |
[] |
no_license
|
class Student < ActiveRecord::Base
has_many :enrollments
validates_uniqueness_of :cpf
validates_presence_of :cpf, :rg, :birth_date, :name, :phone
validate :check_cpf
def check_cpf
require 'cpf_cnpj'
errors.add(:cpf, 'Esse CPF não é válido!') unless CPF.valid? self.cpf
end
def bissextile_year
year = self.birth_date.year
if(year % 4 == 0 and year % 100 != 0 or year % 400 == 0)
true
else
false
end
end
end
| true |
e2f952b943db3bc791e85675b8d204c0919f162d
|
Ruby
|
BCI-AR/RubyNeuroServer
|
/command_handler.rb
|
UTF-8
| 2,278 | 3.171875 | 3 |
[] |
no_license
|
require 'optparse'
class CommandHandler
def initialize(client)
@client = client
end
def help_message
{
hello: "Healthcheck",
close: "Close client connection",
role: "Displays client role [CONTROLLER, EEG, DISPLAY]",
control: "Starts a CONTROLLER client, that can send commands to another clients",
eeg: "Starts an EEG client",
display: "Starts a DISPLAY client",
status: "Shows status of connected clients",
"go N" => "Go command for controllers. go 0 activates a go trial in EEG device 0",
"nogo N" => "No Go command for controllers",
setheader: "EEG command to set EDFHeaders",
"setcheader CH" => "EEG command to set EDFChannelHeaders for channel CH",
"getheader N" => "Display command to print all headers for EEG #N",
watch: "Display command to enable data frames receipt",
unwatch: "Display command to disable data frames receipt",
"! P CC M1 M2.."=>
%{Data frame for each CC channels having P packet_size, with its Mi measures.
M1, M2, M3, ... refers to the P * CC measures in each channel.
It's broadcasted for all display clients that are in watch state.}
}.collect { |k,v|
"#{k}: #{v}"
}.join "\n"
end
def parse(command)
puts "handling #{command}"
args = command.split " "
n = args.count
case args[0]
when "help"
@client.send_message help_message
when "hello"
@client.hello
when "close"
@client.close
when "role"
@client.role
when "control"
@client.control
when "eeg"
@client.eeg
when "display"
@client.display
when "status"
@client.status
when "go"
@client.go args[1]
when "nogo"
@client.go args[1], "nogo"
when "watch"
@client.watch true
when "unwatch"
@client.watch false
when "setheader"
@client.set_header args[1..n]
when "setcheader"
@client.set_channel_header args[1], args[2..n]
when "getheader"
@client.get_header args[1]
when "!"
@client.data_frame args[1], args[2], args[3..n]
end
end
end
| true |
46932c0640dfa85abe1d9dccdfd7e194671cd93f
|
Ruby
|
shioimm/til
|
/practices/exercism/ruby/2019/luhn.rb
|
UTF-8
| 736 | 3.71875 | 4 |
[] |
no_license
|
# Luhn from https://exercism.io
class Luhn
def self.valid?(string)
new(string).valid?
end
def initialize(string)
@string = string
end
def valid?
return false if numbers.length <= 1
return false if string.match? /[^\d\s]/
(checksum % 10).zero?
end
private
attr_reader :string
def numbers
string.scan(/\d/).map(&:to_i)
end
def double(n)
doubled = n * 2
doubled > 9 ? doubled - 9 : doubled
end
def checksum
numbers.reverse_each
.with_index
.sum { |num, index| index.odd? ? double(num) : num }
end
end
# Array#sum
# https://docs.ruby-lang.org/ja/2.6.0/method/Array/i/sum.html
# ブロックを渡すことができる
| true |
13df071994bebf5865f18b8524ebea303de7ea9c
|
Ruby
|
learn-co-curriculum/roman-numerals
|
/spec/roman_numerals_spec.rb
|
UTF-8
| 1,372 | 3.03125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
describe Integer, '#to_roman' do
it 'converts 1 to I' do
expect(1.to_roman).to eq('I')
end
it 'converts 2 to II' do
expect(2.to_roman).to eq('II')
end
it 'converts 3 to III' do
expect(3.to_roman).to eq('III')
end
it 'converts 4 to IV' do
expect(4.to_roman).to eq('IV')
end
it 'converts 5 to V' do
expect(5.to_roman).to eq('V')
end
it 'converts 6 to VI' do
expect(6.to_roman).to eq('VI')
end
it 'converts 9 to IX' do
expect(9.to_roman).to eq('IX')
end
it 'converts 27 XXVII' do
expect(27.to_roman).to eq('XXVII')
end
it 'converts 48 to XLVIII' do
expect(48.to_roman).to eq('XLVIII')
end
it 'converts 59 to LIX' do
expect(59.to_roman).to eq('LIX')
end
it 'converts 93 to XCIII' do
expect(93.to_roman).to eq('XCIII')
end
it 'converts 141 to CXLI' do
expect(141.to_roman).to eq('CXLI')
end
it 'converts 163 to CLXIII' do
expect(163.to_roman).to eq('CLXIII')
end
it 'converts 402 to CDII' do
expect(402.to_roman).to eq('CDII')
end
it 'converts 575 TO DLXXV' do
expect(575.to_roman).to eq('DLXXV')
end
it 'converts 911 to CMXI' do
expect(911.to_roman).to eq('CMXI')
end
it 'converts 1024 to MXXIV' do
expect(1024.to_roman).to eq('MXXIV')
end
it 'converts 3000 to MMM' do
expect(3000.to_roman).to eq('MMM')
end
end
| true |
cda071cf5f6f5a04fc871d5c4858fed721bbb687
|
Ruby
|
Krolmir/ruby-exercises
|
/rb101_rb109_small_problems/easy_8/fizz_buzz.rb
|
UTF-8
| 965 | 4.5 | 4 |
[] |
no_license
|
# Write a method that takes two arguments: the first is the starting number,
# and the second is the ending number. Print out all numbers between the two
# numbers, except if a number is divisible by 3, print "Fizz", if a number is
# divisible by 5, print "Buzz", and finally if a number is divisible by 3 and
# 5, print "FizzBuzz".
def fizzbuzz(num1, num2)
str = []
num1.upto(num2) do |num|
str << if (num % 3).zero? && (num % 5).zero?
'FizzBuzz'
elsif (jnum % 3).zero?
'Fizz'
elsif (num % 5).zero?
'Buzz'
else
num.to_s
end
# case variable
# when "FizzBuzz"
# str += "FizzBuzz"
# when "Fizz"
# str += "Fizz"
# when "Buzz"
# str += "Buzz"
# else
# str += num.to_s
# end
# str += ', '
end
p str.join(', ')
end
fizzbuzz(1, 15)
# -> 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz
| true |
7e4e25f588e3b7ca859741699400600a4a737421
|
Ruby
|
mwagner19446/wdi_work
|
/w02/d04/Etan/gladiator/lib/gladiator.rb
|
UTF-8
| 559 | 3.21875 | 3 |
[] |
no_license
|
class Gladiator
def initialize(name, weapon)
@name = name
@weapon = weapon
end
def name
return @name
end
def weapon
return @weapon
end
end
class Arena
def initialize(name)
@name = name.capitalize
@gladiators = []
end
def name
return @name
end
def gladiators
return @gladiators
end
def add_gladiators(gladiator1, gladiator2)
self.gladiators().push(gladiator1, gladiator2)
if @gladiators.count > 2
return false
else
return gladiators
end
end
def fight
end
end
| true |
5013c26ec7428dd5b046443aaa3521789506b4ac
|
Ruby
|
niklas/ilhan-cci
|
/lib/annual.rb
|
UTF-8
| 576 | 2.9375 | 3 |
[] |
no_license
|
class Annual < Crunch
def unpack
list = []
csv = File.read 'db/annual.txt'
csv.lines.each do |line|
datum, op, cl, hi, lo = line.split
if op && cl && hi && lo && datum =~ /(\d\d)\.(\d\d)\.(\d{4})/
epoch = Time.new($3.to_i, $2.to_i, $1.to_i).to_i
list << Pupple.new(
epoch,
german_num(cl),
german_num(op),
german_num(hi),
german_num(lo),
nil
)
end
end
list.sort_by(&:epoch)
end
def german_num(s)
s.gsub('.','').sub(',','.').to_f
end
end
| true |
5af40a9d0f1496375b97f3359492693666e188b6
|
Ruby
|
jasonkwong11/flatiron-bnb-methods-v-000
|
/app/models/city.rb
|
UTF-8
| 539 | 2.6875 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class City < ActiveRecord::Base
has_many :neighborhoods
has_many :listings, :through => :neighborhoods
def city_openings(date1, date2)
self.listings.find_all{|listing| listing.available?(date1, date2)}
end
def total_reservations
self.listings.inject(0) {|sum, listing| sum + listing.reservations.count}
end
def self.highest_ratio_res_to_listings
City.all.max_by {|city| city.total_reservations/city.listings.count}
end
def self.most_res
City.all.max_by {|city| city.total_reservations}
end
end
| true |
89be28380aaf0d4942819960848fb5c67186bc40
|
Ruby
|
jlangley3/programming-univbasics-4-finding-the-maximum-value-in-an-array-lab-wdc01-seng-ft-042020
|
/lib/finding_the_max_value.rb
|
UTF-8
| 178 | 3.234375 | 3 |
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
def find_max_value(array)
count = 0
max_value = -1
while count < array.length do
if max_value < array[count]
max_value = array[count]
end
count += 1
end
max_value
end
| true |
87db6db79cedad99df2aaabc9e33796a33347778
|
Ruby
|
IanVaughan/random-ruby
|
/dn_query.rb
|
UTF-8
| 1,307 | 2.65625 | 3 |
[] |
no_license
|
require 'sequel'
require 'mysql2'
require 'yaml'
DB = Sequel.connect('mysql2://[email protected]:3306/death_star_development')
def show_tables_sql
"SHOW TABLES"
end
def get_fields_sql table
"SELECT DISTINCT(c.column_name) FROM INFORMATION_SCHEMA.COLUMNS c WHERE c.table_name = '#{table}';"
end
def get_count_sql table, field
"SELECT * FROM #{table} WHERE #{field} IS NOT NULL"
end
IGNORE_FIELDS = ['id', 'created_at', 'updated_at', 'created_on']
results = {}
if true
query_result = DB.fetch(show_tables_sql).all
tables = query_result.map { |f| f[:Tables_in_death_star_development] }
else
tables = ['memberships', 'accounts']
end
table_count = tables.count
tables.each_with_index do |table, i|
query_result = DB.fetch(get_fields_sql(table)).all
fields = query_result.map { |f| f[:column_name] }
print "=> #{i+1}/#{table_count} #{table} has #{fields.count} fields"
field_results = {}
fields.each do |field|
next if IGNORE_FIELDS.include? field
query = get_count_sql(table, field)
begin
field_results[field.to_sym] = DB.fetch(query).count
rescue Sequel::DatabaseError
field_results[field.to_sym] = -1
end
print "."
end
results[table.to_sym] = field_results
puts
end
File.open("results.yml", "w") do |file|
file.write results.to_yaml
end
| true |
b477128abceab973996e0f402c18b998765a4830
|
Ruby
|
felipegruoso/dojos
|
/07_checkbook/checkbook_spec.rb
|
UTF-8
| 916 | 3.296875 | 3 |
[] |
no_license
|
require 'rspec'
require_relative 'checkbook'
RSpec.describe 'Checkbook' do
context 'units' do
it { expect(Checkbook.convert(1)).to eq('um real') }
it { expect(Checkbook.convert(9)).to eq('nove reais') }
end
context 'tens' do
it { expect(Checkbook.convert(10)).to eq('dez reais') }
it { expect(Checkbook.convert(20)).to eq('vinte reais') }
it { expect(Checkbook.convert(17)).to eq('dezessete reais') }
it { expect(Checkbook.convert(25)).to eq('vinte e cinco reais') }
it { expect(Checkbook.convert(99)).to eq('noventa e nove reais') }
end
context 'hundreds' do
it { expect(Checkbook.convert(100)).to eq('cem reais') }
it { expect(Checkbook.convert(215)).to eq('duzentos e quinze reais') }
end
context 'cents' do
it { expect(Checkbook.convert(0.01)).to eq('um centavo') }
it { expect(Checkbook.convert(0.99)).to eq('noventa e nove centavos') }
end
end
| true |
7bd2f15a3851d6e3f71d8401299b88417c188d90
|
Ruby
|
boaromayo/pagr
|
/scripts/window/Window_Escape.rb
|
UTF-8
| 2,034 | 2.765625 | 3 |
[] |
no_license
|
class Window_Escape < Window_Base
# --------------------------------
def initialize
super(440, 256, 192, 64)
self.contents = Bitmap.new(width - 32, height - 32)
self.opacity = 0
self.z = 5000
refresh
end
# --------------------------------
def refresh
if $scene.is_a?(Scene_Battle)
@escape_progress = $scene.escape_progress
if @escape_progress > 10000
@escape_progress = 10000
end
if @escape_progress == 0
self.contents.clear
self.visible = false
return
else
self.visible = true
self.contents.clear
c = Color.new(0, 0, 0, 64)
self.contents.fill_rect(0, 0, width - 32, height - 32, c)
end
self.contents.font.name = "Arial"
self.contents.font.size = 16
self.contents.draw_text(8, 4, 200, 16, "Escape")
if @escape_progress == -1
self.contents.font.size = 10
self.contents.draw_text(8, 20, 200, 10, "Cannot Escape", 1)
end
draw_escape_bar(8, 20, 144)
end
end
# --------------------------------
def draw_escape_bar(x, y, length)
self.contents.fill_rect(x, y, length, 3, Color.new(0, 0, 0, 128))
gradient_red_start = 255
gradient_red_end = 255
gradient_green_start = 144
gradient_green_end = 0
gradient_blue_start = 74
gradient_blue_end = 0
draw_bar_percent = @escape_progress / 100
for x_coord in 1..length
current_percent_done = x_coord * 100 / length
difference = gradient_red_end - gradient_red_start
red = gradient_red_start + difference * x_coord / length
difference = gradient_green_end - gradient_green_start
green = gradient_green_start + difference * x_coord / length
difference = gradient_blue_end - gradient_blue_start
blue = gradient_blue_start + difference * x_coord / length
if current_percent_done <= draw_bar_percent
rect = Rect.new(x + x_coord-1, y, 1, 3)
self.contents.fill_rect(rect, Color.new(red, green, blue, 255))
end
end
end
# --------------------------------
end
| true |
c0d16ea6c47eefd855a0d25e8db519dbbd724544
|
Ruby
|
csmartinez/Ruby-Dictionary
|
/lib/dictionary.rb
|
UTF-8
| 774 | 2.953125 | 3 |
[
"MIT"
] |
permissive
|
class Dictionary
@@dictionaries = []
define_method(:initialize) do |name|
@name = name
@terms = []
@id = @@dictionaries.length().+(1)
end
define_method(:name) do
@name
end
define_method(:terms) do
@terms
end
define_method(:id) do
@id
end
define_singleton_method(:all) do
@@dictionaries
end
define_method(:save) do
@@dictionaries.push(self)
end
define_singleton_method(:clear) do
@@dictionaries = []
end
define_singleton_method(:find) do |id|
found_dictionary = nil
@@dictionaries.each() do |dictionary|
if dictionary.id().eql?(id)
found_dictionary = dictionary
end
end
found_dictionary
end
define_method(:add_term) do |term|
@terms.push(term)
end
end
| true |
4de63fa28b6a5b61b363e979ffaa98e46ea4bab8
|
Ruby
|
ViaMarcus/ruby_exercises
|
/my_group.rb
|
UTF-8
| 461 | 3.8125 | 4 |
[] |
no_license
|
my_group = Array.new
person_1 = {name:"Leah",age:1,gender:"female"}
person_2 = {name:"Simba",age:13,gender:"male"}
person_3 = {name:"Mufasa",age:53,gender:"male"}
my_group.push person_1
my_group.push person_2
my_group.push person_3
my_group.each do |entry|
if entry[:gender] == "male"
puts "#{entry[:name]} is #{entry[:age]} years old and is a lion"
else
puts "#{entry[:name]} is #{entry[:age]} years old and is not a lion"
end #end if
end #end do each
| true |
47b14f76588c2365a2b54662e26fc55fcfcc60d0
|
Ruby
|
tabasano/wavseq
|
/sequence-record.rb
|
UTF-8
| 1,218 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
tmp="seq-byseqrec.txt"
tmp=ARGV.shift
adjustlevel=ARGV.shift
adjustpercent=ARGV.shift
def hint
puts "usage: #{$0} outputfile (adjust-level adjust-percent)"
puts " make sequence data by series of enter keys. first 3 enters are for making minimum unit span only."
puts " adjust-parameters for quantize"
puts " 'q' = quit ( recording end. )"
end
(hint;exit) if ! tmp
ti=[]
while 1
print"#{ti.size}>"
k=gets
break if k=~/^q/
ti<<Time.now.to_f
end
class Array
def unit
@unit=(self[2]-self[0])/2/480.round(5)
end
def seq unit=@unit
start=self[3]
r=[]
(size-3).times{|i|
r<<((self[i+3]-start)/unit).round(0)
}
r
end
def span
r=[0.0]
(self.size-1).times{|i|
r<<(self[i+1]-self[i]).round(3)
}
r
end
def adjust level, rate
level=(level*4.8).to_i
mid=level/2.0
self.map{|i|
a,b=i/level,i%level
a+=1 if b>mid
(i*(100-rate)+a*level*rate)/100
}
end
end
unit=ti.unit
p ti,ti.unit,seq=ti.seq,seq.span
adjustpercent=adjustpercent ? adjustpercent.to_i : 100
if adjustlevel
seq=seq.adjust(adjustlevel.to_i, adjustpercent)
puts "adjust."
p seq,seq.span
end
open(tmp,"w"){|f|f.puts "# unit=#{unit}",seq*","}
| true |
f4d916421c761208d81bae3fbad8f58399324018
|
Ruby
|
markprzepiora/crave
|
/lib/crave/serializers/direnv_serializer.rb
|
UTF-8
| 1,102 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
require 'crave'
module Crave::Serializers::DirenvSerializer
def self.serialize_many(dependencies)
dependencies.map do |dependency|
serialize(dependency)
end.join("\n") +
"\n" +
"# Finally, add the .bin directory to the path\n" +
"PATH_add .bin\n"
end
def self.serialize(satisfied_dependency)
env_string = satisfied_dependency.env.map do |key, value|
"export #{key}=#{bash_quote(value)}\n"
end.join
paths_string = satisfied_dependency.prepend_paths.map do |path|
"PATH_add #{bash_quote(path)}\n"
end.join
commands_string = satisfied_dependency.commands.map do |cmd|
link_path = ".bin/#{cmd.name}"
"ln -sf #{bash_quote(cmd.path)} #{bash_quote(link_path)}\n"
end.join
"# #{satisfied_dependency.name}\n" +
env_string +
paths_string +
"mkdir -p .bin\n" +
commands_string
end
def self.bash_quote(string)
'"' +
string.
gsub('$', '\$').
gsub('"', '\"').
gsub('`', '\`').
gsub('\\', '\\\\').
gsub('!', '\!') +
'"'
end
private_class_method :bash_quote
end
| true |
890b7e789748cf5e9d023cc1cfb588fa1d88c6cf
|
Ruby
|
festinalent3/boris_bikes
|
/spec/van_spec.rb
|
UTF-8
| 1,224 | 2.5625 | 3 |
[] |
no_license
|
require 'bike_container'
require 'van'
describe Van do
let(:working_bike) { double(:working_bike, working: true) }
let(:broken_bike) { double(:broken_bike, working: false) }
let(:garage) { double(:garage) }
let(:ds) { double(:ds) }
it 'takes broken bikes from the docking station' do
allow(ds).to receive(:bikes).and_return([broken_bike, working_bike, broken_bike])
subject.take_broken_bikes(ds)
expect(subject.bikes).to eq([broken_bike, broken_bike])
end
it 'delivers (broken) bikes to garage' do
allow(garage).to receive(:dock).with([broken_bike, broken_bike]).and_return([broken_bike, broken_bike])
subject.bikes = [broken_bike, broken_bike]
subject.deliver(garage)
expect(subject.bikes).to eq([])
end
it 'collects working bikes from a garage' do
allow(garage).to receive(:bikes).and_return([working_bike, working_bike, working_bike])
subject.collect_working_bikes(garage)
expect(subject.bikes).to eq [working_bike, working_bike, working_bike]
end
it 'returns bikes to a docking_station' do
subject.bikes = [working_bike, working_bike]
allow(ds).to receive(:dock).with(working_bike).and_return([working_bike])
subject.return_bikes(ds)
expect(subject.bikes).to eq([])
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.