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 |
---|---|---|---|---|---|---|---|---|---|---|---|
8a6c2662a5032eb70a1e3fbb829f0a8cc535c496
|
Ruby
|
jem/non-haml
|
/gem/lib/non-haml/colorizer.rb
|
UTF-8
| 381 | 3.34375 | 3 |
[] |
no_license
|
module Color
COLORS = {clear: 0, red: 31, green: 32, yellow: 33, blue: 34, gray: 30, grey: 30}
def self.method_missing(color_name, *args)
if args.first.is_a? String
color(color_name) + args.first + color(:clear)
else
color(color_name) + args.first.inspect + color(:clear)
end
end
def self.color(color)
"\e[#{COLORS[color.to_sym]}m"
end
end
| true |
a41326847396da114fa4a7ef0552b61f577b9203
|
Ruby
|
angiemalaika/ruby-objects-has-many-through-lab-dc-web-career-040119
|
/lib/genre.rb
|
UTF-8
| 566 | 3.03125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'pry'
class Genre
attr_reader :name
@@all = []
def initialize(name)
@name= name
@@all << self
end
def songs
Song.all.select do |song|
song.genre == self
#self.Songeach do
#iterates through all songs
#finds the song that belongs genre
end
end
def artists
self.songs.map do |song_object|
song_object.artist
#genre.artist
# song.artist
#iterates over genre collection of songs
#collect the artist
end
# binding.pry
end
def self.all
@@all
end
end
| true |
51dafe1bba15a271880626b0578712c3c91653b7
|
Ruby
|
justGrasse/phase-0-tracks
|
/databases/daily_todo/daily_todo.rb
|
UTF-8
| 5,852 | 3.25 | 3 |
[] |
no_license
|
# Justin's Daily To-Do List
# DOMAIN LOGIC (+ ORM w/SQLite3)
# require gems
require 'sqlite3'
require 'faker'
# create SQLite3 database
db = SQLite3::Database.new("todo.db")
db.results_as_hash = true
# create SQL command for activity table
create_activities_cmd = <<-SQL
CREATE TABLE IF NOT EXISTS activities(
id INTEGER PRIMARY KEY,
name VARCHAR(255)
)
SQL
# create SQL command for todo table
create_todo_cmd = <<-SQL
CREATE TABLE IF NOT EXISTS todo(
id INTEGER PRIMARY KEY,
activity_id INT,
done BOOLEAN,
FOREIGN KEY (activity_id) REFERENCES activities(id)
)
SQL
# create SQL command for time log table
create_log_cmd = <<-SQL
CREATE TABLE IF NOT EXISTS log(
id INTEGER PRIMARY KEY,
day INT,
time INT
)
SQL
# create todo list tables
db.execute(create_activities_cmd)
db.execute(create_todo_cmd)
db.execute(create_log_cmd)
# create check-in that logs your time
def check_in(db)
currentArr = Time.new.to_s.split(' ')
dayArr = currentArr[0].split('-').join('').to_i
timeArr = currentArr[1].split(':').join('').to_i
db.execute("INSERT INTO log (day, time)
VALUES (?, ?)", [dayArr, timeArr])
log = db.execute("SELECT * FROM log")
# Return true if its the first check-in of the day
log.length==1 || !log[-1]['day'] == log[-2]['day']
end
# create method to add activities
def add_activity(db, name)
db.execute("INSERT INTO activities (name) VALUES (?)", [name])
end
# create method to delete activities
def delete_activity(db, act_id)
db.execute("DELETE FROM activities WHERE id=?", [act_id])
end
# create method to add activities to the todo list
def add_todo(db, act_id)
db.execute("INSERT INTO todo (activity_id, done) VALUES (?,'false')", [act_id])
end
# create method to delete activities from the todo list
def delete_todo(db, act_id)
db.execute("DELETE FROM todo WHERE activity_id=?", [act_id])
end
# create method to complete activity
def complete_activity(db, act_id)
db.execute("UPDATE todo SET done='true' WHERE activity_id = ?", [act_id])
end
# *** PRETTY PRINT METHODS ***
# create method to print unfinished activities
def print_todo_list(db)
todo_list = db.execute("SELECT * FROM todo JOIN activities
ON activities.id = todo.activity_id AND todo.done='false'")
today = Time.new.strftime("%B %d, %Y")
puts "\nYour daily To-Do List for #{today}:"
puts '*~'*20+'*'
todo_list.each { |act| puts act['name'] }
end
# create method to print detailed todo_list
def print_full(db)
print_todo_list(db)
todo_list = db.execute("SELECT * FROM todo JOIN activities
ON activities.id = todo.activity_id AND todo.done='true'")
todo_list.each { |act| puts "#{act['name']} - COMPLETE" }
end
# create method to print activities
def print_activities(db)
todo_list = db.execute("SELECT * FROM activities")
puts "\nHere are the available activities:"
puts '*~'*20+'*'
# is_included = to show if the activity is in the todolist
todo_list.each { |act| puts "#{act['id']} - #{act['name']}" }
end
# create method to print unfinished activities with id's
def print_unfinished(db)
todo_list = db.execute("SELECT * FROM todo JOIN activities
ON activities.id = todo.activity_id AND todo.done='false'")
puts "\nUnfinished Activities for Today:"
puts '*~'*20+'*'
puts "ALL ACTIVITIES HAVE BEEN COMPLETED" if todo_list.empty?
todo_list.each { |act| puts "#{act['id']} - #{act['name']}" }
end
# create method to print items in the todo list with id's
def print_todo_ids(db)
todo_list = db.execute("SELECT * FROM todo JOIN activities
ON activities.id = todo.activity_id")
puts "\nActivities in Your To-Do List:"
puts '*~'*20+'*'
puts "NO ACTIVITIES FOUND" if todo_list.empty?
todo_list.each { |act| puts "#{act['id']} - #{act['name']}" }
end
# create method to print activities NOT on the todo list
def print_unused(db)
act_list = db.execute("SELECT * FROM activities")
todo_list = db.execute("SELECT activity_id FROM todo")
puts "\nActivities Available (i.e. Not Being Used):"
puts '*~'*20+'*'
act_list.each { |act|
exists = false
todo_list.each{ |todo_act|
exists = true if act["id"] == todo_act["activity_id"]
}
puts "#{act['id']} - #{act['name']}" if !exists
}
end
# create method to print a menu (return choice)
def print_menu(db)
puts "\nDaily To-Do List Menu"
puts '*~'*20+'*'
puts "Choose 1, 2, 3, or 4:"
puts '1 - Add/Delete an activity to the activities list'
puts '2 - Add/Delete an activity from the to-do list'
puts '3 - Mark an activity as complete'
puts '4 - Exit'
choice = gets.chomp
until ['1','2','3','4'].index(choice)
puts 'Please choose either 1, 2, 3, or 4'
choice = gets.chomp
end
choice
end
# create method to add/delete activities
def add_delete
puts "Would you like to ADD or DELETE? (or EXIT)"
add_delete = gets.chomp.upcase
until ["ADD","DELETE","EXIT"].index(add_delete)
puts "Please select ADD, DELETE, or EXIT"
add_delete = gets.chomp.upcase
end
add_delete
end
# create method to wipe table clean (always double checks!)
def delete_table(db)
puts ('Are you sure you want to wipe the table? (y/n)')
if gets.chomp == 'y'
db.execute("DELETE FROM todo")
db.execute("DELETE FROM log")
end
end
# DRIVER CODE
# Test check-in method
# check_in(db)
# Set a default list of activities/todo list:
# db.execute("DELETE FROM todo")
# db.execute("DELETE FROM activities")
# add_activity(db, "Read a Chapter")
# add_activity(db, "20 Push Ups")
# add_activity(db, "15 Ab Rolls")
# add_activity(db, "CodeWars Challenge")
# add_activity(db, "Water Plants")
# add_activity(db, "Run a Mile")
# add_todo(db,1)
# add_todo(db,2)
# add_todo(db,3)
# add_todo(db,4)
# complete_activity(db,2)
# complete_activity(db,4)
# Clean up the check-in log
# db.execute("DELETE FROM log")
# Print today's to-do list:
# print_todo_list(db)
# print_full(db)
# print_unfinished(db)
# print_unused(db)
# print_todo_ids(db)
| true |
b6021efc2bc1c7686563c11c76a059675dfe3445
|
Ruby
|
automation551/ramf_rails
|
/installer/install_helper.rb
|
UTF-8
| 1,429 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
require 'fileutils'
module RAMF
module InstallHelper
def file_in_app(*args)
File.join(args.unshift(RAILS_ROOT))
end
def file_in_installer(*args)
File.join(args.unshift(File.dirname(__FILE__)))
end
def create_file_unless_exists!(path_under_rails, template=nil, verbose = true)
template ||= file_in_installer(File.basename(path_under_rails))
print("Creating file: #{path_under_rails}.....") if verbose
if !File.exist?(file = file_in_app(path_under_rails))
FileUtils.mkdir_p(File.dirname(file))
FileUtils.copy_file(template, file, false)
print("[OK]\n") if verbose
else
print("[Exists]\n") if verbose
end
end
def remove_file!(path_under_rails,remove_dir = true, verbose = true)
print("Removing file: #{path_under_rails}.....") if verbose
if File.exist?(file = file_in_app(path_under_rails))
FileUtils.rm(file)
print("[OK]\n") if verbose
remove_dir_if_empty!(File.dirname(file), verbose) if remove_dir
else
print("[Doesn't Exist]\n") if verbose
end
end
def remove_dir_if_empty!(dir, verbose)
print("Removing directory: #{dir}......") if verbose
if Dir[File.join(dir,"*")].empty?
FileUtils.rm_r(dir)
print("[OK]\n") if verbose
else
print("[Non Empty]\n") if verbose
end
end
end
end
| true |
35c692bc691019f8ba4eb6e21fd7d6c3255fa87a
|
Ruby
|
qiushuizy/captcha_server
|
/captcha/get_img.rb
|
UTF-8
| 224 | 2.5625 | 3 |
[] |
no_license
|
require 'memcached'
$cache = Memcached.new("localhost:11211")
i = 10000
until i == 0 do
key = $cache.get(i.to_s, false)
value = $cache.get(key, false)
puts "#{i}, #{key}, #{value.length}"
i = i - 1;
end
| true |
a37977f96fab487774aef616327b9cede591a5fe
|
Ruby
|
nana4gonta/gdd2011jp
|
/ruby/puzzle/gdd_puzzle.rb
|
UTF-8
| 6,890 | 3.015625 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
require 'digest/md5'
class Ctrl
def initialize(left, right, up, down)
@@left = left.to_i
@@right = right.to_i
@@up = up.to_i
@@down = down.to_i
end
def reduce(str)
str.split('').each do |c|
case c
when 'L'
@@left -= 1
when 'R'
@@right -= 1
when 'U'
@@up -= 1
when 'D'
@@down -= 1
end
end
end
def rest
[@@left, @@right, @@up, @@down]
end
end
class Puzzle
FORE = :fore
BACK = :back
def initialize(adjacent, goal, width, height, board)
@width = width.to_i
@height = height.to_i
@open = []
@closed = {}
@start = nil
@goal = nil
@adjacent = adjacent
@state = 0
@table = table_new(@width * @height)
b = board_new(board.split(''), 0, '', FORE)
@open << b
@start = b
b = board_new(goal, 0, '', BACK)
@open << b
@goal = b
end
def board_new(ary, depth, ctrl, dir)
board = Board.new(ary, depth, ctrl, dir)
board.calc_eval_func(@width, @height)
board.calc_invert_dist(@width, @height)
return board
end
def table_new(size)
table = {}
i = 1
j = 1
(size).times do |n|
if n < ((@height - 2) * @width)
if n % @width < @width - 2
table[n] = n + 1
elsif n % @width == @width -2
table[n] = n + 2
else
table[n] = 0
end
else
if n < @width * @height - 4
if n % 2 == 0
table[n] = [(@height -2) * @width, i]
i += 1
else
table[n] = [(@height - 1) * @width, j]
j += 1
end
end
end
end
return table
end
def insert(board)
@open << board
end
def sort
i = 0
#if @state < @height - 2
# @open = @open.sort_by{|b| [b.id > b.ef ? b.id : b.ef, b.dir, i += 1]}
#else
@open = @open.sort_by{|b| b.id > b.ef ? b.id : b.ef}
#end
end
def solve
limit = @open[0].id > @open[0].ef ? @open[0].id : @open[0].ef
limit += 2
threads = []
while true
self.sort
a = @open.shift
if a.nil?
a = @start
@state = 0
@closed.clear
end
depth = a.ctrl.size
space = a.cell.index('0')
dir = a.dir
while @table[@state] == 0
@state += 1
end
st = @table[@state]
if a.dir == FORE
if @state < (@height - 2) * @width
if a.cell[0, st] == @goal.cell[0, st]
@state += 1
@open.delete_if{|b| b.cell[0, st] != @goal.cell[0, st]}
end
elsif @state >= (@height - 2) * @width
if a.cell[st[0], st[1]] == @goal.cell[st[0], st[1]]
@state += 1
@open.delete_if{|b| b.cell[st[0], st[1]] != @goal.cell[st[0], st[1]]}
end
end
end
@adjacent[space].each do |i|
if a.dir == FORE and @state < (@height - 2) * @width
if i < @state
next
end
end
cell = a.cell.dup
cell = cell.swap(i, space)
if i > space
if i == space + 1
ctrl = 'R'
ctrl = 'L' if a.dir == BACK
else
ctrl = 'D'
ctrl = 'U' if a.dir == BACK
end
else
if i == space - 1
ctrl = 'L'
ctrl = 'R' if a.dir == BACK
else
ctrl = 'U'
ctrl = 'D' if a.dir == BACK
end
end
safe = true
case a.ctrl[-1]
when 'U'
safe = false if ctrl == 'D'
when 'D'
safe = false if ctrl == 'U'
when 'L'
safe = false if ctrl == 'R'
when 'R'
safe = false if ctrl == 'L'
end
if @closed.key?(cell)
c = @closed[cell]
if dir != c.dir
if dir == FORE
return a.ctrl + c.ctrl
else
return c.ctrl + a.ctrl
end
end
else
b = board_new(cell, depth + 1, a.ctrl + ctrl, dir)
low = (b.id > b.ef) ? b.id : b.ef
if limit + 2 >= low and safe
insert(b)
end
@closed[b.cell] = b
end
end
@closed[a.cell] = a
low = (a.id > a.ef) ? a.id : a.ef
limit = depth + low + 10
end
end
def print(cell)
@height.times do |i|
p cell[i * @width, @width]
end
puts
end
class Board
def initialize(ary, depth = 0, ctrl = '', dir)
@cell = ary
@ef = 0
@id = 0
@depth = depth
@ctrl = ctrl
@dir = dir
end
attr_accessor :cell, :ef, :ctrl, :depth, :hash, :id, :dir
def calc_eval_func(width, height)
sum = 0
copy = @cell.dup
copy.each_index do |i|
if copy[i] =~ /[A-Z]/
copy[i] = copy[i].ord - 55
elsif copy[i] =~ /=/
copy[i] = i + 1
else
copy[i] = copy[i].to_i
end
# $B2#$N%R%e!<%j%9%F%#%C%/4X?tCM(B
sum += ( (copy[i] - 1) % width - i % width ).abs
# $B=D$N%R%e!<%j%9%F%#%C%/4X?tCM(B
if copy[i] == 0
now = i / width
sum += height - now - 1
else
sum += ( ((copy[i] - 1) / width).abs - i / width ).abs
end
end
@ef = sum
end
def calc_invert_dist(width, height)
id = 0
tmp = []
cell = @cell.dup
cell.each_index do |i|
if cell[i] == '='
cell[i] = (i + 1).to_s
elsif cell[i] == '0'
cell[i] = (width * height).to_s
end
end
cell.each_index do |i|
tmp << cell[i, cell.size].count{|n| cell[i] > n}
end
id += tmp.reduce(:+) / width + tmp.reduce(:+) % width
tmp.clear
t_cell = []
height.times do |i|
t_cell << cell[i * width, width]
end
t_cell = t_cell.transpose.flatten
t_cell.each_index do |i|
tmp << t_cell[i, t_cell.size].count{|n| t_cell[i] > n}
end
id += tmp.reduce(:+) / height + tmp.reduce(:+) % height
@id = id
end
end
end
class Array
def swap(p1, p2)
tmp = self[p1]
self[p1] = self[p2]
self[p2] = tmp
return self
end
end
adjacent = []
open(ARGV[0]) do |f|
while l = f.gets
eval l
end
end
goal = []
open(ARGV[1]) do |f|
while l = f.gets
eval l
end
end
file = ARGV[2]
open(file) do |f|
l = f.gets
ctrl = Ctrl.new(*(l.split(' ')))
t = f.gets.to_i
t.times do |n|
l = f.gets.chomp.split(',')
if ctrl.rest.all?{|n| n > 0}
if l[0].to_i < 5 and l[1].to_i < 5
puzzle = Puzzle.new(adjacent[n], goal[n], *l)
result = puzzle.solve
puts result
ctrl.reduce(result)
else
print "\n"
end
else
print "\n"
end
end
end
| true |
2a14f6c38814d5354d1f601d9a390e9171a609c3
|
Ruby
|
philcrissman/advent
|
/08/solution.rb
|
UTF-8
| 868 | 2.96875 | 3 |
[] |
no_license
|
def reset
@instructions = File.read("./input.txt").split("\n")
@vars = []
@vals = []
end
def run_instructions(instr = @instructions)
instr.each do |instruction|
instruction = instruction.split(" ")
unless @vars.include?("@#{instruction[0]}")
instance_variable_set(:"@#{instruction[0]}", 0)
@vars << "@#{instruction[0]}"
end
unless @vars.include?("@#{instruction[4]}")
instance_variable_set(:"@#{instruction[4]}", 0)
@vars << "@#{instruction[4]}"
end
instruction[0] = "@#{instruction[0]}"
instruction[4] = "@#{instruction[4]}"
instruction[1] = "+=" if instruction[1] == "inc"
instruction[1] = "-=" if instruction[1] == "dec"
line = instruction.join(" ")
eval(line)
@vals << instance_variable_get(:"#{instruction[0]}")
@vals << instance_variable_get(:"#{instruction[4]}")
end
end
| true |
29ce0f9326f81307a61485207168a832c5e0ecd9
|
Ruby
|
AntoineMassoni/planet-invader
|
/app/models/booking.rb
|
UTF-8
| 994 | 2.59375 | 3 |
[] |
no_license
|
class Booking < ApplicationRecord
belongs_to :user
belongs_to :planet
validates :check_in, :check_out, :travelers, presence: true
validates :travelers, numericality: true
# def check_out_after_check_in
# errors.add(:check_out, "must be after the start date") if check_in > check_out
# end
# # def parse_date(year, month, day)
# # Date.parse("#{year}-#{month}-#{day}")
# # end
# def validate_each
# bookings = self.garage.bookings
# bookings = bookings.map do |rental|
# (rental.check_in..rental.check_out).to_a
# end
# bookings.flatten
# rental_array_date = (self.check_in..self.check_out).to_a
# # Rental.where("check_in >= ? AND check_out <= ?", record.check_in, record.check_out)
# # bookings = Rental.where(["garage_id =?", record.garage_id])
# # date_ranges = bookings.map { |r| r.check_in..r.check_out }
# errors.add(:check_in, "not available") if bookings.flatten - rental_array_date != bookings.flatten
# end
end
| true |
53fd529789dfbba25d061734fa7e9a34b770f878
|
Ruby
|
heath3conk/phase-0
|
/week-5/gps2_2.rb
|
UTF-8
| 5,173 | 4.40625 | 4 |
[
"MIT"
] |
permissive
|
# Method to create a list
# input:
# String of items separated by spaces (example: "carrots apples cereal pizza")
# steps:
# Create a new array, splitting the given string of items into elements of the array
# Iterate over the elements of the array, putting them into a hash
# - key - item name
# - value - set default quantity of 1
# output:
# Hash = {item: quantity}
def create_list(items="")
initial_list = items.split
grocery_list = Hash.new
initial_list.each { |item| grocery_list[item] = 1 }
return grocery_list
end
# Method to add an item to a list
# input:
# List, item name and optional quantity
# steps:
# Add the item provided to the list
# If no quantity is provided in the arguments, assume the quantity is 1
# output:
# Hash = {item: quantity}
def add_item(list, item, quantity = 1)
list [item] = quantity
return list
end
# Method to remove an item from the list
# input:
# List and item to be removed
# steps:
# Remove item from hash
# output:
# Updated Hash = {item: quantity}
def remove_item(list, item_to_remove)
list.reject! { |item, quantity| item == item_to_remove }
return list
end
# Method to update the quantity of an item
# input:
# Item name and quantity
# steps:
# Overwrite the existing quantity for a given item with the new quantity provided
# output:
# Hash = {item: quantity}
def update_item(list, item_to_update, new_quantity)
list[item_to_update] = new_quantity
return list
end
# Method to print a list and make it look pretty
# input:
# List of items and quantities (in a hash)
# steps:
# Print all of the items and quantities on the list
# output:
# Items and quantities
def print_list(list)
list.each_pair{ |item, quantity| puts "#{item}: #{quantity}" }
end
test_list = create_list()
add_item(test_list,"Lemonade", 2)
add_item(test_list,"Tomatoes", 3)
add_item(test_list,"Onions", 1)
add_item(test_list,"Ice Cream", 4)
remove_item(test_list,"Lemonade")
update_item(test_list,"Ice Cream", 1)
print_list(test_list)
=begin
What did you learn about pseudocode from working on this challenge?
My pair and I did all the pseudocode first and then started coding. This challenge was indeed
challenging in that kept wanting to make our methods do more than they were supposed to do.
So our initial pseudocode included a lot more for each method than the code ultimately
contained. I've gone back and changed the pseudocode to reflect reality but this was a good
exercise in keeping things simple!
What are the tradeoffs of using Arrays and Hashes for this challenge?
It's a question of what you are trying to do at any given point in time. We knew that the end
result was going to be a hash because we wanted two pieces of information for everything: an
item name and a quantity, basically a poster child for a hash. Then, for each interim step we
had to consider how we needed to access the data.
For example, we couldn't find any simple way to transfrom a space-separated string directly
into a hash so we put it into an array first and then filled in the hash from that array. Just
about all the other methods were going to act on that hash.
What does a method return?
Whatever I tell it to! (*evil laugh*) Actually, I think that is pretty much true. The
default method return is whatever the last line in the method (before "end") does, but if
I include an explicit "return" statement, that statement could be anything.
What kind of things can you pass into methods as arguments?
Anything I want. Multiples of anything I want. In this challenge, we passed strings, integers,
hashes... In the reading so far I haven't seen anything about a limitation on this.
How can you pass information between methods?
I've only done this three times so far so I can really only say how WE did it in this specific
challenge (and hope that this experience is applicable elsewhere). We used one variable,
"test_list" to do almost everything we needed to do here. When we initialized that variable,
we set it equal to the return value of our "create_list()" method. When we then used test_list
as an argument elsewhere, as in the "add_item" method, that add_item method got the current contents
of the variable...whether it was the first time calling add_item or the third time.
I may not be explaining this well, but I'm thinking of this challenge as building a box (the gps2_2.rb
file itself) that holds all the various methods in their individual boxes and also contains this
variable. We can change the variable by putting into a particular method's box and then we can take
it and feed it to another box. We can do that in any order we want and as many times as we want.
What concepts were solidified in this challenge, and what concepts are still confusing?
The hardest thing at the beginning was keeping each method focused on JUST what the instructions said
about it and not making it more complicated.
I think the biggest thing I'm taking away from this one is how to hold that variable separate from the
method(s)...scope, I guess. I won't say I've got it down completely, but it is becoming clearer.
=end
| true |
6cd4c543ba4bce3f726748cd4112ddd82177afd1
|
Ruby
|
sarahrudy/battleship
|
/spec/cell_spec.rb
|
UTF-8
| 1,618 | 3.25 | 3 |
[] |
no_license
|
require 'rspec'
require './lib/ship'
require './lib/cell'
describe Cell do
it 'exists' do
cell = Cell.new("B4")
expect(cell).to be_instance_of(Cell)
end
it 'has attributes' do
cell = Cell.new("B4")
expect(cell.coordinate).to eq("B4")
end
it 'has a ship' do
cell = Cell.new("B4")
expect(cell.ship).to eq(nil)
end
it 'has an empty cell' do
cell = Cell.new("B4")
expect(cell.empty?).to eq(true)
end
it 'places a ship' do
cell = Cell.new("B4")
cruiser = Ship.new("Cruiser", 3)
submarine = Ship.new("Submarine", 2)
cell.place_ship(cruiser)
expect(cell.ship).to eq(cruiser)
expect(cell.empty?).to eq(false)
cell.place_ship(submarine)
expect(cell.ship).to eq(cruiser)
end
it 'is fired upon' do
cell = Cell.new("B4")
cruiser = Ship.new("Cruiser", 3)
cell.place_ship(cruiser)
expect(cell.fired_upon?).to eq(false) # brand new cell, no action yet
cell.fire_upon
expect(cell.ship.health).to eq(2)
expect(cell.fired_upon?).to eq(true)
end
it 'renders correct symbols' do
cell_1 = Cell.new("B4")
cell_2 = Cell.new("C3")
cruiser = Ship.new("Cruiser", 3)
expect(cell_1.render).to eq(".")
cell_1.fire_upon
expect(cell_1.render).to eq("M")
cell_2.place_ship(cruiser)
expect(cell_2.render).to eq(".")
expect(cell_2.render(true)).to eq("S")
cell_2.fire_upon
expect(cell_2.render).to eq("H")
expect(cruiser.sunk?).to eq(false)
cruiser.hit
cruiser.hit
expect(cruiser.sunk?).to eq(true)
expect(cell_2.render).to eq("X")
end
end
| true |
8d7c68a4eee442a0047d2b93645d429b8eec1a98
|
Ruby
|
warmer/quick_tools
|
/http_client.rb
|
UTF-8
| 1,666 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
require 'net/http'
require 'net/https'
require 'uri'
# This provides helper methods for common HTTP actions and is based on a
# several implementations of this basic functionality written over the years.
#
# Intended usage: simple HTTP library in a single, portable file, that
# abstracts the basic HTTP functionality found in Ruby's standard library
#
# Usage notes: the client will supply basic auth credentials for all requests
# if initialized with a username and password. The client does NOT support
# more advanced functionality like protocol determination (HTTP vs HTTPS),
# cookie management, etc.
class HttpClient
def initialize(base_url, username = nil, password = nil)
@base_url = base_url
@username = username
@password = password
end
def get(path, headers = {})
request(Net::HTTP::Get, path, headers)
end
def post(path, body = "", headers = {})
request(Net::HTTP::Post, path, headers, body)
end
def put(path, body = "", headers = {})
request(Net::HTTP::Put, path, headers, body)
end
def delete(path, headers = {})
request(Net::HTTP::Delete, path, headers)
end
private
def request(type, path, headers, body = nil)
uri = URI.parse("#{@base_url}#{path}")
http = Net::HTTP.new(uri.host, uri.port)
if uri.scheme == 'https'
http.use_ssl
# uncomment if connecting to untrusted endpoint
#http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
request = type.new(uri.request_uri)
request.basic_auth @username, @password unless @username.nil?
headers.keys.each { |k| request[k] = headers[k] }
request.body = body if body
http.request(request)
end
end
| true |
1356558f00a03e10189821dc432b23f2dadf9c7d
|
Ruby
|
pav3ls/learn-to-code-with-ruby-lang
|
/Section-5-Methods_and_Conditionals_I/71_the_respond_to_method.rb
|
UTF-8
| 88 | 2.765625 | 3 |
[] |
no_license
|
num = 1000
p num.respond_to?("length")
if num.respond_to?("next")
p num.next
end
| true |
b9e550943c4ef2f8dd7ec0fabbc09b3fc5be484f
|
Ruby
|
juggernault/reportportal_sample_project
|
/features/support/helpers/wait_helper.rb
|
UTF-8
| 1,296 | 3.046875 | 3 |
[] |
no_license
|
require 'capybara/dsl'
module Zpg
module WaitHelper
include Capybara::DSL
# wait for ajax request to complete
def wait_for_ajax
counter = 0
while page.execute_script("return $.active").to_i > 0
counter += 1
sleep(0.1)
raise "AJAX request took longer than 20 seconds." if counter >= 400
end
end
# dynamicly wait for the page to load
# usage: Zpg.wait_for(page_has_loaded)
def wait_for_dom_has_loaded
Capybara.default_max_wait_time = 40
Timeout.timeout(Capybara.default_max_wait_time) do
loop until page_has_loaded?
end
end
# @return [page status]
def page_has_loaded?
return page.evaluate_script('document.readyState;') == 'complete'
end
## used when we just want to continue and make it visible in the code
# this is an alternative of python pass statement (continue , brake , pass)
# is just there is no need to log a message as this tells that
# boolean statements that we check are how we expect
# eg : if a && b
# Zpg.pass
# we check if a and b are true so I replace to say assert_true(a) and assert_true(b)
# else
# raise "Some message #{a} and #{b}"
# end
def pass
end
end
end
| true |
af338de5a0318f3522db0554e57d34e9530cfff7
|
Ruby
|
natalvz/oo-cash-register-v-000
|
/lib/cash_register.rb
|
UTF-8
| 744 | 3.359375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'pry'
class CashRegister
attr_accessor :total, :discount, :descuento, :items, :last_transaction
def initialize(dis=nil)
@total = 0
@discount = dis
@items = []
end
def add_item(item, price, quantity=1)
self.total += (price*quantity)
quantity.times do
@items << item
end
self.last_transaction = (price*quantity)
end
def apply_discount
if @discount == nil
return "There is no discount to apply."
else
@descuento = (@discount*@total)/100
@total -= @descuento
return "After the discount, the total comes to $#{total}."
end
end
def items
@items
end
def void_last_transaction
self.total -= last_transaction
end
end
| true |
606a81235f3eba059f4cf2362b8c917cada321e9
|
Ruby
|
glenc/rpoint
|
/lib/rpoint/interop/webs.rb
|
UTF-8
| 2,503 | 2.59375 | 3 |
[] |
no_license
|
module RPoint
module Interop
##
# Interop methods for working with webs
class Webs
##
# Gets a web by its URL
def self.get_web(url)
return url if url.is_a? SPWeb
return url.RootWeb if url.is_a? SPSite
# to get the web, first we'll open the site collection,
# then we'll try to open the web with whatever remains
# in the web URL
# open the site collection
site = Sites.get_site(url)
# TODO - extract this into some other helper method
# if we get a different host name back as the site URL,
# use the new host for our web URL
site_uri = Uri.new(site.Url)
web_uri = Uri.new(url)
if web_uri.Host.to_s.downcase != site_uri.Host.to_s.downcase
web_uri = Uri.new("#{site_uri.GetLeftPart(UriPartial.Authority)}#{web_uri.PathAndQuery}")
end
# get the relative uri
relative_url = site_uri.MakeRelative(web_uri)
return site.OpenWeb(relative_url)
end
##
# Create a new web beneath the parent web specified and
# returns the result
def self.create_web(parent, name, template, options = {})
# merge options with defaults
options = {
:language => 1033, # language id for the new site
:description => '', # description for the new site
:unique_permissions => false, # if true, new site will have unique permissions
:convert_if_exists => false, # will convert existing folder if exists
:url => nil # override the url which will be auto-calculated from the name
}.merge(options)
# figure out URL for new web
new_web_url = self.determine_new_url(parent, name, options)
# create new web
parent.Webs.Add(
new_web_url,
name,
options[:description],
options[:language],
template.id,
options[:unique_permissions],
options[:convert_if_exists])
end
private
##
# Determine the URL for a new site based on the new name and options
# provided
def self.determine_new_url(parent_web, new_name, options = {})
url_explicitly_set = options.has_key?(:url) && !options[:url].nil?
url_explicitly_set ? options[:url] : new_name.url_friendly
end
end
end
end
| true |
bc3f7b93f5c06d5c09c3304f99068358f9b92ae5
|
Ruby
|
openware/peatio-core
|
/lib/peatio/ranger/connection.rb
|
UTF-8
| 3,093 | 2.53125 | 3 |
[] |
no_license
|
module Peatio::Ranger
class Connection
attr_reader :socket, :user, :authorized, :streams, :logger, :id
def initialize(router, socket, logger)
@id = SecureRandom.hex(10)
@router = router
@socket = socket
@logger = logger
@user = nil
@authorized = false
@streams = {}
end
def inspect
if authorized
"<Connection id=#{id} user=#{user}>"
else
"<Connection id=#{id}>"
end
end
def send_raw(payload)
if user
logger.debug { "sending to user #{user.inspect} payload: #{payload}" }
else
logger.debug { "sending to anonymous payload: #{payload}" }
end
@socket.send(payload)
end
def send(method, data)
payload = JSON.dump(method => data)
send_raw(payload)
end
def authenticate(authenticator, jwt)
payload = {}
authorized = false
begin
payload = authenticator.authenticate!(jwt)
authorized = true
rescue Peatio::Auth::Error => e
logger.warn e.message
end
[authorized, payload]
end
def subscribe(subscribed_streams)
raise "Streams must be an array of strings" unless subscribed_streams.is_a?(Array)
subscribed_streams.each do |stream|
stream = stream.to_s
next if stream.empty?
unless @streams[stream]
@streams[stream] = true
@router.on_subscribe(self, stream)
end
end
send(:success, message: "subscribed", streams: streams.keys)
end
def unsubscribe(unsubscribed_streams)
raise "Streams must be an array of strings" unless unsubscribed_streams.is_a?(Array)
unsubscribed_streams.each do |stream|
stream = stream.to_s
next if stream.empty?
if @streams[stream]
@streams.delete(stream)
@router.on_unsubscribe(self, stream)
end
end
send(:success, message: "unsubscribed", streams: streams.keys)
end
def handle(msg)
return if msg.to_s.empty?
if msg =~ /^ping/
send_raw("pong")
return
end
data = JSON.parse(msg)
case data["event"]
when "subscribe"
subscribe(data["streams"])
when "unsubscribe"
unsubscribe(data["streams"])
end
rescue JSON::ParserError => e
logger.debug { "#{e}, msg: `#{msg}`" }
end
def handshake(authenticator, hs)
query = URI.decode_www_form(hs.query_string)
subscribe(query.map {|item| item.last if item.first == "stream" })
logger.debug "WebSocket connection openned"
headers = hs.headers_downcased
return unless headers.key?("authorization")
authorized, payload = authenticate(authenticator, headers["authorization"])
if !authorized
logger.debug "Authentication failed for UID:#{payload[:uid]}"
raise EM::WebSocket::HandshakeError, "Authorization failed"
else
@user = payload[:uid]
@authorized = true
logger.debug "User #{@user} authenticated #{@streams}"
end
end
end
end
| true |
f53280cc36642e22375c662d22d7a2e63118d09b
|
Ruby
|
takagotch/rails1
|
/super/binary/InstantRails-1.7-win/InstantRails/rails_apps/typo-2.6.0/script/process/reaper
|
UTF-8
| 4,392 | 2.9375 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/local/bin/ruby
require 'optparse'
require 'net/http'
require 'uri'
def nudge(url, iterations)
print "Nudging #{url}: "
iterations.times { Net::HTTP.get_response(URI.parse(url)); print "."; STDOUT.flush }
puts
end
if RUBY_PLATFORM =~ /mswin32/ then abort("Reaper is only for Unix") end
class ProgramProcess
class << self
def process_keywords(action, *keywords)
processes = keywords.collect { |keyword| find_by_keyword(keyword) }.flatten
if processes.empty?
puts "Couldn't find any process matching: #{keywords.join(" or ")}"
else
processes.each do |process|
puts "#{action.capitalize}ing #{process}"
process.send(action)
end
end
end
def find_by_keyword(keyword)
process_lines_with_keyword(keyword).split("\n").collect { |line|
next if line.include?("inq") || line.include?("ps ax") || line.include?("grep")
pid, *command = line.split
new(pid, command.join(" "))
}.compact
end
private
def process_lines_with_keyword(keyword)
`ps ax -o 'pid command' | grep #{keyword}`
end
end
def initialize(pid, command)
@pid, @command = pid, command
end
def find
end
def reload
`kill -s HUP #{@pid}`
end
def graceful
`kill -s TERM #{@pid}`
end
def kill
`kill -9 #{@pid}`
end
def usr1
`kill -s USR1 #{@pid}`
end
def to_s
"[#{@pid}] #{@command}"
end
end
OPTIONS = {
:action => "graceful",
:dispatcher => File.expand_path(File.dirname(__FILE__) + '/../../public/dispatch.fcgi'),
:spinner => File.expand_path(File.dirname(__FILE__) + '/spinner'),
:toggle_spin => true,
:iterations => 10,
:nudge => false
}
ARGV.options do |opts|
opts.banner = "Usage: reaper [options]"
opts.separator ""
opts.on <<-EOF
Description:
The reaper is used to reload, gracefully exit, and forcefully exit FCGI processes
running a Rails Dispatcher. This is commonly done when a new version of the application
is available, so the existing processes can be updated to use the latest code.
The reaper actions are:
* reload : Only reloads the application, but not the framework (like the development environment)
* graceful: Marks all of the processes for exit after the next request
* kill : Forcefully exists all processes regardless of whether they're currently serving a request
Graceful exist is the most common and default action. But since the processes won't exist until after
their next request, it's often necessary to ensure that such a request occurs right after they've been
marked. That's what nudging is for.
A nudge is simply a request to a URL where the dispatcher is serving. You should perform one nudge per
FCGI process you have running if they're setup in a round-robin. Be sure to do one nudge per FCGI process
across all your servers. So three servers with 10 processes each should nudge 30 times to be sure all processes
are restarted.
Examples:
reaper -a reload
reaper -n http://www.example.com -i 10 # gracefully exit, nudge 10 times
EOF
opts.on(" Options:")
opts.on("-a", "--action=name", "reload|graceful|kill (default: #{OPTIONS[:action]})", String) { |OPTIONS[:action]| }
opts.on("-d", "--dispatcher=path", "default: #{OPTIONS[:dispatcher]}", String) { |OPTIONS[:dispatcher]| }
opts.on("-s", "--spinner=path", "default: #{OPTIONS[:spinner]}", String) { |OPTIONS[:spinner]| }
opts.on("-t", "--toggle-spin", "Whether to send a USR1 to the spinner before and after the reaping (default: true)") { |OPTIONS[:toggle_spin]| }
opts.on("-n", "--nudge=url", "Should point to URL that's handled by the FCGI process", String) { |OPTIONS[:nudge]| }
opts.on("-i", "--iterations=number", "One nudge per FCGI process running (default: #{OPTIONS[:iterations]})", Integer) { |OPTIONS[:iterations]| }
opts.separator ""
opts.on("-h", "--help", "Show this help message.") { puts opts; exit }
opts.parse!
end
ProgramProcess.process_keywords("usr1", OPTIONS[:spinner]) if OPTIONS[:toggle_spin]
ProgramProcess.process_keywords(OPTIONS[:action], OPTIONS[:dispatcher])
nudge(OPTIONS[:nudge], OPTIONS[:iterations]) if OPTIONS[:nudge]
ProgramProcess.process_keywords("usr1", OPTIONS[:spinner]) if OPTIONS[:toggle_spin]
| true |
e55190131ec9004dff8d17b85f938cb0c01f7fe1
|
Ruby
|
teoucsb82/pokemongodb
|
/lib/pokemongodb/pokemon/beedrill.rb
|
UTF-8
| 1,243 | 2.75 | 3 |
[] |
no_license
|
class Pokemongodb
class Pokemon
class Beedrill < Pokemon
def self.id
15
end
def self.base_attack
144
end
def self.base_defense
130
end
def self.base_stamina
130
end
def self.buddy_candy_distance
1
end
def self.capture_rate
0.1
end
def self.cp_gain
21
end
def self.description
"Beedrill is extremely territorial. No one should ever approach its nest—this is for their own safety. If angered, they will attack in a furious swarm."
end
def self.flee_rate
0.06
end
def self.height
1.0
end
def self.max_cp
1439.96
end
def self.moves
[
Pokemongodb::Move::BugBite,
Pokemongodb::Move::PoisonJab,
Pokemongodb::Move::AerialAce,
Pokemongodb::Move::SludgeBomb,
Pokemongodb::Move::XScissor
]
end
def self.name
"beedrill"
end
def self.types
[
Pokemongodb::Type::Bug,
Pokemongodb::Type::Poison
]
end
def self.weight
29.5
end
end
end
end
| true |
d0e845b369bfeacfec9e88ccf568dcbf9f16505f
|
Ruby
|
JohnMarkLudwick/ruby-objects-has-many-lab-v-000
|
/lib/post.rb
|
UTF-8
| 785 | 3.09375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Post
attr_accessor :title, :author
@@all = []
def initialize(title)
@title = title
@@all << self
end
def author_name
if self.author
self.author.name
else
nil
end
end
end
# class Post
# attr_accessor :name
# @@all = 0
# def initialize(title)
# @title = title
# end
# def add_posts(post)
# self.posts << post
# posts.title = self
# @@song_count +=1
# end
# def add_song_by_name(name)
# song = Song.new(name)
# self.posts << posts
# posts.author = self
# @@post_count +=1
# end
# def title
# end
# def author
# end
# def author_name
# end
# def posts
# @posts
# end
# def self.post_count
# @@post_count
# end
# end
| true |
3783706767961946cabe9782b97432f8f59b35da
|
Ruby
|
Sheena-Marie/ruby-projects
|
/analyser.rb
|
UTF-8
| 1,317 | 4.96875 | 5 |
[] |
no_license
|
# Setting up the methods
def multiply(first_number, second_number)
first_number.to_f * second_number.to_f
end
def divide(first_number, second_number)
first_number.to_f / second_number.to_f
end
def subtract(first_number, second_number)
second_number.to_f - first_number.to_f
end
def mod(first_number, second_number)
first_number.to_f % second_number.to_f
end
# The actual human interaction stuff
puts "What do you want to do? 1) Multiply 2) divide 3) subtract 4) find remainder?"
prompt = gets.chomp.to_i
puts "Enter in your first number:"
first_number = gets.chomp
puts "Enter in your second number:"
second_number = gets.chomp
# If/Else statements
if prompt == 1
puts "You have chosen to multiply #{first_number} with #{second_number}"
result = multiply(first_number, second_number)
elsif prompt == 2
puts "You have chosen to divide #{first_number} with #{second_number}"
result = divide(first_number, second_number)
elsif prompt == 3
puts "You have chosen to subtract #{second_number} with #{first_number}"
result = subtract(first_number, second_number)
elsif prompt == 4
puts "You have chosen to find the remainder from #{first_number} and #{second_number}"
result = mod(first_number, second_number)
else
puts "You have made an invalid choice"
end
puts "The result is #{result}"
| true |
f3ea68ebaa8714c99e7ab8bdb02cae8285ed2ff5
|
Ruby
|
merrua/ruby
|
/ex10_cat.rb
|
UTF-8
| 357 | 3.5 | 4 |
[] |
no_license
|
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
fat_cat = <<MY_HEREDOC
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
MY_HEREDOC
puts tabby_cat
puts persian_cat
puts backslash_cat
puts fat_cat
poppy_cat = "This string has a quote: \". As you can see, it is escaped"
puts poppy_cat
| true |
29e9000c94dd600d33f8e5bb17bbdc19566b432d
|
Ruby
|
jgt17/Minesweeper
|
/game_resources/positions/position.rb
|
UTF-8
| 376 | 3.046875 | 3 |
[] |
no_license
|
# frozen_string_literal: true
# basic position
# extended to map coordinates in different minefield topologies to the corresponding index in the underlying array
class Position
attr_reader :true_position
def initialize(index)
@true_position = index
end
def ==(other)
other.is_a?(Position) && @true_position == other.true_position
end
alias eql? ==
end
| true |
bbdc8590208e885c02434e55ab651d7a584b39ee
|
Ruby
|
georgeu2000/volt
|
/lib/volt/extra_core/hash.rb
|
UTF-8
| 160 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
class Hash
def deep_cur
new_hash = {}
each_pair do |key, value|
new_hash[key.deep_cur] = value.deep_cur
end
return new_hash
end
end
| true |
3434e80bca72a9bb26ce72d94d0b3190b790e5b5
|
Ruby
|
tanphan313/leet_works
|
/problems/array/palindrome_number.rb
|
UTF-8
| 550 | 3.875 | 4 |
[] |
no_license
|
<<-Doc
Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not.
Input: x = 121
Output: true
solve it without converting the integer to string
Doc
# @param {Integer} x
# @return {Boolean}
def is_palindrome x
return false if x < 0
original_x = x.dup
reverted_number = 0
while x > 0
reverted_number = reverted_number * 10 + (x % 10)
x = x / 10
end
reverted_number == original_x
end
p is_palindrome 121
| true |
e5fc60a2e17afa36256bce7ea75194f11f3202ca
|
Ruby
|
champagnepappi/ruby
|
/sum2.rb
|
UTF-8
| 120 | 3.375 | 3 |
[] |
no_license
|
def get_sum(numbers)
sum = 0
numbers.map do |e|
passengers = e[1] - e[0]
sum += passengers
end
sum
end
| true |
2ea157a91a174073e3c8374af8eed780644726c7
|
Ruby
|
weilihmen/simple-twitter
|
/lib/tasks/dev.rake
|
UTF-8
| 2,452 | 2.53125 | 3 |
[] |
no_license
|
namespace :dev do
# 請先執行 rails dev:fake_user,可以產生 20 個資料完整的 User 紀錄
# 其他測試用的假資料請依需要自行撰寫
task fake_user: :environment do
User.destroy_all
20.times do |i|
name = FFaker::Name::first_name
file = File.open("#{Rails.root}/public/avatar/user#{i+1}.jpg")
user = User.new(
name: name,
email: "#{name}@example.co",
password: "12345678",
introduction: FFaker::Lorem::sentence(30),
avatar: file
)
user.save!
puts user.name
end
end
task uniname_user_20: :environment do
url = "https://uinames.com/api/?ext®ion=england"
20.times do
response = RestClient.get(url)
data = JSON.parse(response.body)
user = User.create(
name: data["name"],
email: data["email"],
password: "password",
avatar: data["photo"],
introduction: FFaker::Lorem::sentence(30)
)
puts "created user #{user.name}"
end
puts "now you have #{User.count} users data"
end
task fake_tweets_200: :environment do
200.times do |i|
Tweet.create(
description: FFaker::Tweet::body,
user: User.all.sample
)
end
puts "create random 200 fake tweets"
end
task fake_replies_200: :environment do
200.times do |i|
Reply.create(
comment: FFaker::Lorem.sentence(50),
tweet: Tweet.all.sample,
user: User.all.sample
)
end
puts "create random 200 fake replies"
end
task fake_likes_100: :environment do
100.times do |i|
Like.create(
user: User.all.sample,
tweet: Tweet.all.sample
)
end
puts "create random 100 fake likes"
end
task fake_follows_100: :environment do
100.times do |i|
Followship.create(
user: User.all.sample,
following: User.all.sample
)
end
puts "create random 100 fake follows"
end
task fake_all: :environment do
Rake::Task["dev:uniname_user_20"].execute
Rake::Task["dev:fake_tweets_200"].execute
Rake::Task["dev:fake_replies_200"].execute
Rake::Task["dev:fake_likes_100"].execute
Rake::Task["dev:fake_follows_100"].execute
puts "finish"
end
task update_followers_count: :environment do
User.all.each do |u|
u.followers_count!
end
puts "update all users followers_count"
end
end
| true |
b87335e09154dd476c179f9f003ac825a13ce5c3
|
Ruby
|
sirramongabriel/lunch_panoply
|
/app/models/company.rb
|
UTF-8
| 1,463 | 2.8125 | 3 |
[] |
no_license
|
class Company < ActiveRecord::Base
attr_accessible :address, :city, :name, :phone, :state, :zip, :employee_id
validates_presence_of :name, :address, :city, :state, :zip, :phone
validates_length_of :state, is: 2, too_long: 'please enter a two character state abbreviation',
too_short: 'please enter a two character state abreviation'
validates_length_of :zip, within: 5..9, too_long: 'please enter no more than 9 characters',
too_short: 'please enter at least 5 characters'
validates_length_of :phone, is: 10, too_long: 'please enter no more than 10 digits',
too_short: 'please enter a 10 digit number'
belongs_to :employee
# def Company.total
# end
# def Company.by_name
# Company.all.order(name: :asc)
# end
def Company.by_newest_first
Company.all.order(created_at: :desc)
end
def Company.by_oldest_first
Company.all.order(created_at: :asc)
end
def Company.by_city
Company.all.order(city: :asc)
end
def Company.by_state
Company.all.order(state: :asc)
end
def Company.first_favorite_venue
end
def Company.second_favorite_venue
end
def Company.third_favorite_venue
end
def Company.first_favorite_menu_item
end
def Company.second_favorite_menu_item
end
def Company.third_favorite_menu_item
end
end
class InvalidCompany < Company
attr_accessible :name, :address, :city, :state, :zip, :phone
has_many :employees
end
| true |
a67ed5dd56f2580b5d1993dddc7ab4c296bc7b0b
|
Ruby
|
uk-gov-mirror/ministryofjustice.specialist-publisher
|
/bin/republish_withdrawn_document
|
UTF-8
| 957 | 2.578125 | 3 |
[
"MIT",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
#!/usr/bin/env ruby
require File.expand_path("../../config/environment", __FILE__)
require "specialist_publisher"
def republish_withdrawn_edition(edition)
# Change the state to published
edition.update_attribute(:state, "published")
# Get the services for the right document type
services = SpecialistPublisher.document_services(edition.document_type)
# Republish the document to other GOV.UK systems
services.republish(edition.document_id).call
end
unless ARGV.any?
$stderr.puts "usage: #{File.basename(__FILE__)} document_id ..."
exit(1)
end
ARGV.each do |document_id|
edition = SpecialistDocumentEdition
.where(document_id: document_id)
.order_by(:version_number)
.last
if edition.nil?
$stderr.puts "SKIPPING #{document_id}; could not find document"
elsif !edition.archived?
$stderr.puts "SKIPPING #{document_id}; latest edition is not withdrawn"
else
republish_withdrawn_edition(edition)
end
end
| true |
6bf8919b5cfb04d89e1ca17e9bd73f2767a014ff
|
Ruby
|
yoshitsugu/host_summary_parser
|
/lib/host_summary_parser.rb
|
UTF-8
| 722 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
require "host_summary_parser/version"
class HostSummaryParser
def self.parse(string)
parsed = ""
string.split("\n").each do |line|
line.gsub!(/\(.+\)/,"")
if line =~ /^(\s*)(\S+)\s*=\s*([\{\[])\s*$/
parsed << "#{$1}:#{$2} => #{$3}\n"
elsif line =~ /^(\s*)(\S+)\s*=\s*(.*),\s*$/
s = $1; l = $2; r = $3
# insert double quotation
if r =~ /^".*?"$/
parsed << "#{s}:#{l} => #{r},\n"
else
parsed << "#{s}:#{l} => \"#{r}\",\n"
end
else
parsed << line + "\n"
end
parsed.gsub!(/"<unset>"/,"nil")
end
begin
eval(parsed)
rescue
raise "cannot parse \"#{string.to_s}\""
end
end
end
| true |
10514f41f4923b5b41c9b0c19f5928e9caa11177
|
Ruby
|
cesareferrari/programming-foundations
|
/exercises/101-109_small_problems/easy4/previous3/10_convert_number.rb
|
UTF-8
| 492 | 3.8125 | 4 |
[] |
no_license
|
def integer_to_string(integer)
digits = []
loop do
integer, digit = integer.divmod(10)
digits << digit
break if integer == 0
end
digits.reverse.join
end
def signed_integer_to_string(integer)
return '0' if integer == 0
return integer_to_string(integer.abs).prepend('-') if integer < 0
integer_to_string(integer).prepend('+')
end
puts signed_integer_to_string(4321) == '+4321'
puts signed_integer_to_string(-123) == '-123'
puts signed_integer_to_string(0) == '0'
| true |
b1168ba3f7e3fdf5e3591c0731b0c2ef6a289a9a
|
Ruby
|
mindreframer/datastructures-algorithms-stuff
|
/github.com/mindreframer/source-data-structures-and-algorithms-with-oop/ruby/pgm14_08.txt
|
UTF-8
| 456 | 3.15625 | 3 |
[] |
no_license
|
#
# This file contains the Ruby code from Program 14.8 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Ruby"
# by Bruno R. Preiss.
#
# Copyright (c) 2004 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus8/programs/pgm14_08.txt
#
def mergeSort(array, i, n)
if n > 1
mergeSort(array, i, n / 2)
mergeSort(array, i + n / 2, n - n / 2)
merge(array, i, n / 2, n - n / 2)
end
end
| true |
49ef618815607d695e59dc793935daebeef69075
|
Ruby
|
locomotivecms/custom_fields
|
/lib/custom_fields/types/date_time.rb
|
UTF-8
| 3,181 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
module CustomFields
module Types
module DateTime
module Field; end
module Target
extend ActiveSupport::Concern
module ClassMethods
# Adds a date_time field
#
# @param [ Class ] klass The class to modify
# @param [ Hash ] rule It contains the name of the field and if it is required or not
#
def apply_date_time_custom_field(klass, rule)
name = rule['name']
klass.field name, type: ::DateTime, localize: rule['localized'] || false
# other methods
klass.send(:define_method, :"formatted_#{name}") { _get_formatted_date_time(name) }
klass.send(:define_method, :"formatted_#{name}=") { |value| _set_formatted_date_time(name, value) }
return unless rule['required']
klass.validates_presence_of name, :"formatted_#{name}"
end
# Build a hash storing the formatted value for
# a date_time custom field of an instance.
#
# @param [ Object ] instance An instance of the class enhanced by the custom_fields
# @param [ String ] name The name of the date_time custom field
#
# @return [ Hash ] field name => formatted date_time
#
def date_time_attribute_get(instance, name)
if value = instance.send(:"formatted_#{name}")
{ name => value, "formatted_#{name}" => value }
else
{}
end
end
# Set the value for the instance and the date_time field specified by
# the 2 params.
#
# @param [ Object ] instance An instance of the class enhanced by the custom_fields
# @param [ String ] name The name of the date_time custom field
# @param [ Hash ] attributes The attributes used to fetch the values
#
def date_time_attribute_set(instance, name, attributes)
return unless attributes.key?(name) || attributes.key?("formatted_#{name}")
value = attributes[name] || attributes["formatted_#{name}"]
instance.send(:"formatted_#{name}=", value)
end
end
protected
def _set_formatted_date_time(name, value)
if value.is_a?(::String) && !value.blank?
date_time = ::DateTime._strptime(value, _formatted_date_time_format)
if date_time
value = ::Time.zone.local(date_time[:year], date_time[:mon], date_time[:mday], date_time[:hour], date_time[:min], date_time[:sec] || 0) # , date_time[:zone] || "")
else
value = begin
::Time.zone.parse(value)
rescue StandardError
nil
end
end
end
send(:"#{name}=", value)
end
def _get_formatted_date_time(name)
send(name.to_sym).strftime(_formatted_date_time_format)
rescue StandardError
nil
end
def _formatted_date_time_format
I18n.t('time.formats.default')
end
end
end
end
end
| true |
48f46732b23810ff4b0349ecd2bc97f359d3cb7b
|
Ruby
|
arthurnn/memcached-manager
|
/lib/extensions/memcached_inspector.rb
|
UTF-8
| 1,413 | 2.53125 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
module Sinatra
module MemcachedInspector
def memcached_inspect options
host = options[:host]
port = options[:port]
key = options[:key]
inspect = inspector host, port
# Filter by key if defined
if !key.nil?
inspect = inspect.select{|pair| pair[:key] == key }.first
end
inspect
end
private
def inspector host, port
# Looks horrible, got it from a gist... yet, it works.
keys = []
cache_dump_limit = 9_000 # It's over...
localhost = Net::Telnet::new("Host" => host, "Port" => port, "Timeout" => 3)
slab_ids = []
localhost.cmd("String" => "stats items", "Match" => /^END/) do |c|
matches = c.scan(/STAT items:(\d+):/)
slab_ids = matches.flatten.uniq
end
slab_ids.each do |slab_id|
localhost.cmd("String" => "stats cachedump #{slab_id} #{cache_dump_limit}", "Match" => /^END/) do |c|
matches = c.scan(/^ITEM (.+?) \[(\d+) b; (\d+) s\]$/).each do |key_data|
(cache_key, bytes, expires_time) = key_data
humanized_expires_time = Time.at(expires_time.to_i).to_s
expired = false
expired = true if Time.at(expires_time.to_i) < Time.now
keys << { key: cache_key, bytes: bytes, expires_at: humanized_expires_time, expired: expired }
end
end
end
keys
end
end
end
| true |
d69152de30414b19cd4a3b979e14de12912aeea6
|
Ruby
|
lbt/sourcify
|
/spec/proc/to_sexp_within_irb_spec.rb
|
UTF-8
| 3,886 | 2.640625 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
require File.join(File.expand_path(File.dirname(__FILE__)), 'spec_helper')
describe "Proc#to_sexp within IRB" do
class << self
def irb_eval(string)
irb_exec(string)[-1]
end
def equal_to(expected)
lambda {|found| found == expected }
end
end
should 'handle non var' do
expected = s(:iter, s(:call, nil, :proc, s(:arglist)), nil, s(:call, nil, :x, s(:arglist)))
irb_eval('lambda { x }.to_sexp').should.be equal_to(expected)
end
should 'handle local var' do
expected = s(:iter, s(:call, nil, :proc, s(:arglist)), nil, s(:lvar, :x))
irb_eval(%Q(
x = 'lx'
lambda { x }.to_sexp
)).should.be equal_to(expected)
end
should 'handle class_eval scoped local var' do
expected =
s(:iter,
s(:call, nil, :proc, s(:arglist)),
nil,
s(:iter,
s(:call, s(:const, :Object), :class_eval, s(:arglist)),
s(:lasgn, :x),
s(:lasgn, :y, s(:lvar, :x))))
irb_eval(%Q(
x = 1
lambda { Object.class_eval {|x| y = x } }.to_sexp
)).should.be equal_to(expected)
end
should 'handle instance_eval scoped local var' do
expected =
s(:iter,
s(:call, nil, :proc, s(:arglist)),
nil,
s(:iter,
s(:call, s(:str, "aa"), :instance_eval, s(:arglist)),
s(:lasgn, :x),
s(:lasgn, :y, s(:lvar, :x))))
irb_eval(%Q(
x = 1
lambda { 'aa'.instance_eval {|x| y = x } }.to_sexp
)).should.be equal_to(expected)
end
should 'handle define_method scoped local var' do
expected =
s(:iter,
s(:call, nil, :proc, s(:arglist)),
nil,
s(:iter,
s(:call,
s(:const, :Object),
:send,
s(:arglist, s(:lit, :define_method), s(:lit, :aa))),
s(:lasgn, :x),
s(:lasgn, :y, s(:lvar, :x))))
irb_eval(%Q(
x = 1
lambda { Object.send(:define_method, :aa) {|x| y = x } }.to_sexp
)).should.be equal_to(expected)
end
should 'not handle class scoped local var (simple)' do
expected =
s(:iter,
s(:call, nil, :proc, s(:arglist)),
nil,
s(:class, :AA, nil, s(:scope, s(:lasgn, :y, s(:call, nil, :x, s(:arglist))))))
irb_eval(%Q(
x = 1
lambda { class AA ; y = x ; end }.to_sexp
)).should.be equal_to(expected)
end
should 'not handle class scoped local var (w inheritance)' do
expected =
s(:iter,
s(:call, nil, :proc, s(:arglist)),
nil,
s(:class,
:AA,
s(:const, :Object),
s(:scope, s(:lasgn, :y, s(:call, nil, :x, s(:arglist))))))
irb_eval(%Q(
x = 1
lambda { class AA < Object; y = x ; end }.to_sexp
)).should.be equal_to(expected)
end
should 'not handle class scoped local var (w singleton)' do
expected =
s(:iter,
s(:call, nil, :proc, s(:arglist)),
nil,
s(:sclass,
s(:str, "AA"),
s(:scope, s(:lasgn, :y, s(:call, nil, :x, s(:arglist))))))
irb_eval(%Q(
x = 1
lambda { class << 'AA'; y = x ; end }.to_sexp
)).should.be equal_to(expected)
end
should 'not handle module scoped local var' do
expected =
s(:iter,
s(:call, nil, :proc, s(:arglist)),
nil,
s(:module, :AA, s(:scope, s(:lasgn, :y, s(:call, nil, :x, s(:arglist))))))
irb_eval(%Q(
x = 1
lambda { module AA ; y = x ; end }.to_sexp
)).should.be equal_to(expected)
end
should 'not handle method scoped local var' do
expected =
s(:iter,
s(:call, nil, :proc, s(:arglist)),
nil,
s(:defn,
:aa,
s(:args),
s(:scope, s(:block, s(:lasgn, :y, s(:call, nil, :x, s(:arglist)))))))
irb_eval(%Q(
x = 1
lambda { def aa ; y = x ; end }.to_sexp
)).should.be equal_to(expected)
end
end
| true |
03158df3308550d3278de2c4b381b3f0dac11e0b
|
Ruby
|
lonelyelk/advent-of-code
|
/2020/23/test.rb
|
UTF-8
| 240 | 2.53125 | 3 |
[] |
no_license
|
require_relative "lib"
require "test/unit/assertions"
include Test::Unit::Assertions
input = "389125467"
assert_equal "92658374", crab_game(input, 10), "Wrong result"
assert_equal 149245887792, crab_game2(input, 10000000), "Wrong result"
| true |
d6c5fdd73acfcb3f10a379b443299e4e9a617be7
|
Ruby
|
alexkorich/library_korich
|
/lib/library_korich/book.rb
|
UTF-8
| 335 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
module LibraryKorich
class Book
attr_reader :title, :author
def initialize(title, author)
if author.class==Author
@title=title
@author=author
else
raise "Author is not valid!"
end
end
def count(c)
@count=c
end
def to_s
"#{self.title.to_s}, #{self.author.name}"
end
end
end
| true |
24b5af8bbaebd257ccbaefdc07fc42fdf69baa51
|
Ruby
|
Riyan-Bryant/CIT383
|
/create_user_records2.rb
|
UTF-8
| 1,939 | 3.703125 | 4 |
[] |
no_license
|
#!/usr/bin/ruby
# Program 01
# Riyan Bryant
# CIT 383-003 Fall 2017
# 9/13/2017
#Initializing variabls and creates empty arrays for the user response to be stored in.
employee_id = []
first_name = []
last_name = []
dep_num = []
sup_name = []
linux_id = []
temp_pass = []
cont_prog = 'Y'
# A loop that gathers the users response until the last question is answered with anything other than yes or Y.
while cont_prog == 'Y' || cont_prog == 'yes'
puts "Enter the user's employee id:"
employee_id = gets.chomp.to_i
puts "Enter the user's first name:"
first_name = gets.chomp
puts "Enter the user's last name:"
last_name = gets.chomp
puts "Enter the user's department number:"
dep_num = gets.chomp
puts "Enter the user's supervisor (full name):"
sup_name = gets.chomp
puts "Enter the user's linux id:"
linux_id = gets.chomp
puts "Enter the user's temporary password:"
temp_pass = gets.chomp
puts "Would you like to create another record? (Type yes or Y to continue):"
cont_prog = gets.chomp
end
# Creates a hash to store the user's responses where the employee id is the key.
user_info = Hash.new
user_info = Hash.new
user_info[employee_id] = []
user_info[employee_id] << first_name
user_info[employee_id] << last_name
user_info[employee_id] << dep_num
user_info[employee_id] << sup_name
user_info[employee_id] << linux_id
user_info[employee_id] << temp_pass
# Once the user exits the program, generate a records report.
if cont_prog != 'Y' || cont_prog != 'yes'
puts "Summary"
puts "========================="
puts "Name: " + first_name.to_s + " " + last_name.to_s
puts "Employee ID: " + employee_id.to_s
puts "Department: " + dep_num
puts "Supervisor: " + sup_name
puts "Username: " + linux_id
puts "Password: " + temp_pass
end
| true |
1c58e6096dd0728e570a0ab273494943d4003356
|
Ruby
|
beckyrussoniello/multi-city-indeed-search
|
/spec/requests/search_spec.rb
|
UTF-8
| 2,537 | 2.609375 | 3 |
[] |
no_license
|
require 'spec_helper'
describe "job search" do
it "performs a search with multiple locations" do
visit root_url
expect {
fill_in "search_query", with: "phlebotomy"
fill_in "location_name", with: "new york chicago" #CITIES.sample(10) #rand(1..10))
click_button "Search"
}.to change(Search, :count).by(1)
page.should have_content "What:"
page.should have_content "Where:"
page.should_not have_css ".flash-notice"
page.should have_css "#results"
page.should have_css ".result"
page.should have_css ".job-title"
end
it "can do consecutive searches without user hitting back button" do
visit root_url
3.times do
expect {
fill_in "search_query", with: %w(staff associate cashier sales manager assistant).sample
fill_in "location_name", with: CITIES.sample(rand(2..10))
click_button "Search"
}.to change(Search, :count).by(1)
page.should_not have_css ".flash-notice"
page.should have_css "#results"
end
end
it "tells the user if there are no results to display" do
@query = "dslkfjjklsdjf"
@locs = "shell wy, greybull wy"
visit root_url
expect {
fill_in "search_query", with: @query
fill_in "location_name", with: @locs
click_button "Search"
}.to change(Search, :count).by(1)
page.should have_css "#search"
page.should have_content "Your search did not match any jobs."
end
it "displays appropriate error message if location list is empty" do
visit root_url
expect {
fill_in "search_query", with: "jquery"
fill_in "location_name", with: ""
click_button "Search"
}.to_not change(Search, :count)
page.should have_css "#search"
page.should have_content "Please type one or more locations, separated by commas."
end
it "displays appropriate error message if location list is too long" do
visit root_url
expect {
fill_in "search_query", with: "staff"
fill_in "location_name", with: CITIES.sample(rand(12..20))
click_button "Search"
}.to change(Search, :count).by(1)
page.should have_css "#results"
page.should have_content "FYI, we only process"
end
it "displays appropriate error message if query is empty" do
visit root_url
expect {
fill_in "search_query", with: ""
fill_in "location_name", with: CITIES.sample(rand(2..10))
click_button "Search"
}.to_not change(Search, :count)
page.should have_content "Please type a search keyword."
end
end
| true |
4ed86706fe48430105e8afa422cd8b92c2f09076
|
Ruby
|
ZempTime/ConsciousSpendingPlan
|
/app/models/paycheck.rb
|
UTF-8
| 553 | 2.546875 | 3 |
[] |
no_license
|
class Paycheck < ActiveRecord::Base
has_many :disbursments
has_many :accounts, through: :disbursments
after_save :create_disbursements
validates :total_amount, presence: true
def create_disbursements
#TODO: Create our disbursements for this paycheck based upon accounts
# Iterate through each account
# Create disbursement with amount = paycheck.amount * account.percentage
Account.all.each do |account|
disbursments.create(account_id: account.id, amount: total_amount * account.percentage / 100.0)
end
end
end
| true |
9e23eeea297cdfcb848a4fa9b5988af093d30b35
|
Ruby
|
roykim79/tdd_ruby_card_game_war
|
/lib/card_deck.rb
|
UTF-8
| 455 | 3.328125 | 3 |
[] |
no_license
|
require_relative './playing_card'
class CardDeck
def initialize
@cards_left = []
ranks = %w[A K Q J 10 9 8 7 6 5 4 3 2]
suits = %w[Spades Hearts Clubs Diamonds]
ranks.each do |rank|
suits.each do |suit|
@cards_left.push(PlayingCard.new({rank: rank, suit: suit}))
end
end
end
def cards_left
@cards_left.length
end
def shuffle
@cards_left.shuffle!
end
def deal
@cards_left.pop
end
end
| true |
8949118cd790f8c47bdb63c41f161b1194982384
|
Ruby
|
Eden-Eltume/100
|
/Introduction_to_Programming_with_Ruby/2_The_Basics4/ex4.rb
|
UTF-8
| 55 | 2.859375 | 3 |
[] |
no_license
|
movies = [2018, 2008, 2014]
movies.each{|el| puts el}
| true |
a2a0a2611d3ed4730e48951ab284f96b750a5ade
|
Ruby
|
doremidom/mastermind
|
/mastermind.rb
|
UTF-8
| 4,660 | 3.21875 | 3 |
[] |
no_license
|
require 'sinatra'
require 'sinatra/reloader' if development?
class Mastermind
attr_accessor :computer_output, :guess_feedback, :code, :game_over
def initialize(gametype, code, saved_code=nil)
@colors = ['r','g','y','b','o','v']
@game_over = false
@tried_codes = []
if gametype == 1
@code = code.split('')
@computer_output =[]
computer_guess
elsif gametype == 2
if saved_code
@code = saved_code
else
@code = code_generator
end
@guess = code.split('')
@guess_feedback = []
check_guess(@guess)
end
end
def code_generator(colors=@colors)
code = []
4.times do |x|
random = rand((colors.length))
code.push(colors[random])
end
code
end
def play
until @game_over
guess
end
end
def guess
puts "Enter a guess for a code"
guess = gets.chomp.split('')
feedback = check_guess(guess)
end
def computer_guess(guess_code = code_generator, known ={}, close =[], wrong=[])
@computer_output.push("guessing #{guess_code}")
if guess_code == @code
@game_over = true
@computer_output.push("Computer won!")
else
@tried_codes.push(guess_code)
guess_code.each_with_index do |color, index|
diagnosis = feedback(color,index)
if diagnosis == "match"
@computer_output.push("found a match")
if known[color]
known[color].push(index)
else
known[color] = [index]
end
elsif diagnosis == "partial match"
@computer_output.push("found a partial match")
close.push(color) unless close.include?(color)
else
@computer_output.push("color not found, removing from possibilities")
wrong.push(color)
end
end
@computer_output.push("trying new guess")
computer_new_guess(known, close, wrong)
end
end
def computer_new_guess(known={}, close=[], wrong=[])
new_colors = @colors
wrong.each do |color|
if new_colors.include?(color)
new_colors.delete(color)
#@computer_output.push("deleted #{color}")
end
end
new_guess = []
if !close.empty?
@computer_output.push("making a new code that includes #{close}")
until close.all? { |e| new_guess.include?(e) } && !@tried_codes.include?(new_guess)
#@computer_output.push("close is #{close[0]}")
new_guess = code_generator(new_colors)
unless known.empty?
known.each_pair do |color, pos|
pos.each do |ind|
new_guess[ind] = color
end
end
end
end
#close = []
else
@computer_output.push("making a new code")
new_guess = code_generator(new_colors)
unless known.empty?
known.each_pair do |color, pos|
pos.each do |ind|
new_guess[ind] = color
end
end
end
end
#@computer_output.push("new guess is #{new_guess}")
computer_guess(new_guess, known, close, wrong)
end
def check_guess(guess)
if guess == @code
@game_over = true
@guess_feedback.push("You won!")
else
guess.each_with_index do |color, index|
response = feedback(color,index)
hint(response)
end
end
end
def feedback(color, index)
if @code.include?(color)
if color == @code[index]
"match"
else
"partial match"
end
else
"not found"
end
end
def hint(guess_response)
if guess_response == "match"
@guess_feedback.push("This color is in the right position.")
elsif guess_response == "partial match"
@guess_feedback.push("This color is in the wrong position.")
else
@guess_feedback.push("This color was not found in the code.")
end
end
end
enable :sessions
get '/' do
#checking for the presence of either type of game parameter
if !params['code-guess'].nil? || !params['user-code'].nil?
game_started = true
if !params['code-guess'].nil?
code_guess = params['code-guess']
game_type = "user"
if !session[:game_code].nil?
@saved_code = session[:game_code]
game = Mastermind.new(2, code_guess, @saved_code)
if game.game_over
session[:game_code] = nil
game_over = true
end
else
game = Mastermind.new(2, code_guess)
session[:game_code] = game.code
session[:game] = game
end
guess_feedback = game.guess_feedback
else
game_type = "computer"
user_code = params['user-code']
game = Mastermind.new(1, user_code)
computer_output = game.computer_output
end
else
game_started = false
game_type = nil
computer_output = nil
guess_feedback = nil
code_guess = nil
code = nil
game_over = false
end
erb :index , :locals => {:game_started => game_started, :game_type => game_type, :computer_output => computer_output, :guess_feedback => guess_feedback, :code_guess => code_guess, :saved_code => @saved_code, :game_over => game_over}
end
| true |
aad6a79cd7c888b449db3ae019c14023195673a6
|
Ruby
|
magdalenamandat/homework-hashes
|
/loops.rb
|
UTF-8
| 1,109 | 4.125 | 4 |
[] |
no_license
|
# counter = 0
# my_number = 5
#
# while (counter < my_number)
# p "counter is #{counter}"
# counter += 1
# end
# my_number = 5
# p "What number am I thinking of?"
# value = gets.chomp().to_i()
#
# while (value != my_number)
# break if (value == 0)
# if (value > my_number)
# p "too high!"
# else
# p "too low"
# end
# p "nope! try again..."
# value = gets.chomp().to_i()
# end
#
# p "yes! well done!"
# numbers = [1, 2, 3, 4, 5]
#
# total = 0
#
# for number in numbers
# total = total + number
# # p number * 2
# end
#
# p total
# chickens = ["Margaret", "Hetty", "Henrietta", "Audrey", "Mabel"]
#
# for chicken in chickens
# p chicken
# end
chicken_hashes = [
{name: "Margaret", age: 2, eggs: 0},
{name: "Hetty", age: 1, eggs: 2},
{name: "Henrietta", age: 3, eggs: 1},
{name: "Audrey", age: 2, eggs: 0},
{name: "Mabel", age: 5, eggs: 1}
]
total_eggs = 0
for chicken in chicken_hashes
if chicken[:eggs] > 0
p "Wooo! #{chicken[:name]} has eggs!"
end
total_eggs += chicken[:eggs]
chicken[:eggs] = 0
# p "#{chicken[:name]} is #{chicken[:age]}"
p total_eggs
end
| true |
999d838e4316018c18119df2fa8117ff4cf427a8
|
Ruby
|
albertbahia/wdi_june_2014
|
/w04/d03/hoa_newton/movie_trailer/app/models/omdb.rb
|
UTF-8
| 610 | 2.875 | 3 |
[] |
no_license
|
class OMDB
def self.search(term)
search_url = URI.escape("http://omdbapi.com/?s=#{term}")
api_response = HTTParty.get(search_url) #string
results = JSON.parse(api_response)["Search"]
results_array = results.map do |movie|
movie["imdbID"]
end
movie_info_array = results_array.map do |imdbid|
movie = JSON.parse(HTTParty.get("http://www.omdbapi.com/?i=#{imdbid}"))
movie_info = {
"Title" => movie["Title"],
"Year" => movie["Year"],
"Actors" => movie["Actors"],
"Plot" => movie["Plot"],
"Poster" => movie["Poster"]
}
end
end
end
#we want OMDB.search("True Grit")
| true |
a04553b0935df7aff90af5585407bf1832596459
|
Ruby
|
kathrynmbrown/epicodus
|
/address-book-ruby-master 3/address_book_main.rb
|
UTF-8
| 1,717 | 3.78125 | 4 |
[] |
no_license
|
require './lib/contact'
require './lib/phone'
require './lib/email'
require './lib/address'
# @contact = []
def main
puts "Press 'a' to add a contact or 'l' to view list of contacts"
puts "Press 'x' to exit"
main_choice = gets.chomp
case main_choice
when 'a'
add_contact
when 'l'
view_contacts
when 'x'
exit
end
main
end
def add_contact
puts "What is contact's name?"
user_name = gets.chomp
Contact.create(user_name)
puts "Name added!\n\n"
main
end
def list_contact
Contact.contacts.each_with_index do |name, index|
puts (index+1).to_s + ": " + name.name
end
end
def view_contacts
select_contact
end
def select_contact
puts "Which contact would you like to edit or view? Select the number."
list_contact
user_input = gets.chomp.to_i
contact_menu(Contact.contacts[user_input-1])
end
def contact_menu(contact)
puts "Press 'a' to add information for your contact"
puts "Press 'v' to see contacts information"
puts "Press 'x' to exit"
main_choice = gets.chomp
case main_choice
when 'a'
add_info(contact)
when 'v'
info_list(contact)
when 'x'
exit
end
end
def add_info(contact)
puts "Phone Number: "
user_phone = gets.chomp
puts "Number added! How about their email address? \n\n"
puts "Email Address: "
user_email = gets.chomp
puts "Number added! How about their physical address? \n\n"
puts "Address: "
user_address = gets.chomp
puts "Address added! Thanks so much! \n\n"
contact.add_info(user_phone, user_email, user_address)
puts "Contact updated! \n\n"
main
end
def info_list(contact)
contact.info_list.each_with_index do |info, index|
puts (index+1).to_s + ": " + info + "\n"
end
end
main
| true |
2e173f58aba9d6203246b390da202f38dc6c9cf0
|
Ruby
|
ysei/polite_programmer_presentation
|
/src/botwars/lib/botwars/basic_robot.rb
|
UTF-8
| 649 | 2.890625 | 3 |
[] |
no_license
|
class Robot
# Informs the robot that the game is starting. The
# control_unit is provided for getting sensor data and
# issuing commands.
def start_game(name, color, controller)
end
# Informs the robot that it has collided with an object
# and how much damage the collision caused.
def collision(damage)
end
# Called every virtual clock tick. The robot is allowed
# to do some procesing every clock tick.
def tick
end
# Informs the robot that it has died. The robot should
# not perform any further actions on its controller.
def dead
end
# Informs the robot that the game is over.
def end_game
end
end
| true |
b49d9dadf8b56aa0f20c231f19539ed9c859c690
|
Ruby
|
raohmaru/romtools
|
/move_roms/move_roms.rb
|
UTF-8
| 3,010 | 3.1875 | 3 |
[
"MIT"
] |
permissive
|
require 'fileutils'
# Options
working_dir = '.'
output_dir = ''
romlist = false
inc_clones = false
dry_run = false
copy = false
# Variables
rom_count = 0
rom_total = 0
roms_found = {}
missing = []
# Const
RX_EXT_ZIP = /\.zip$/
HELP = <<eof
Move ROMs 1.0
-------------
Moves zipped ROMs files from the target dir to the specified output directory, given a ROM list generated by roms_filter.rb or arcade_roms_filter.rb.
Usage:
ruby move_roms.rb [romlist] -t [romddir] [-o [outputdir] -c -d]
Arguments:
romlist Source file with the ROMs
-t, --target Directory with the zipped ROMs
-o, --output Output directory were to move the ROMs found at romlist
-c, --clones Include clones
-d, --dryrun Dry run mode (no file is moved)
-cp, --copy Copy the ROMs to the output directory instead of moving them
-h, --help Display this help
eof
unless ARGV.empty?
ARGV.each_with_index { |item, i|
if item == "-t" || item == "--target"
working_dir = ARGV[i+1]
elsif item == "-o" || item == "--output"
output_dir = ARGV[i+1]
elsif item == "-c" || item == "--clones"
inc_clones = true
elsif item == "-d" || item == "--dryrun"
dry_run = true
elsif item == "-cp" || item == "--copy"
copy = true
elsif item == "-h" || item == "--help"
puts HELP
exit
else
if !romlist && File.exists?(item) && !File.directory?(item)
romlist = item
end
end
}
else
puts HELP
exit
end
if !romlist
puts "ERROR: romlist file not found. Type `ruby move_roms.rb -h` for help."
exit
end
if !File.directory?(working_dir)
puts "ERROR: Target directory does not exists. Type `ruby move_roms.rb -h` for help."
exit
end
if output_dir == ''
output_dir = File.join(working_dir, 'moved')
end
unless File.directory? output_dir
Dir.mkdir output_dir
end
puts "Running in dry-run mode"
File.open(romlist, "rt") do |f|
f.each_line do |line|
roms = []
rom = line.rstrip
if inc_clones
Dir.chdir(working_dir) do
Dir.glob(rom+"*.zip") do |r|
next if roms_found[r]
roms.push r
roms_found[r] = true
end
end
end
rom += '.zip' unless RX_EXT_ZIP =~ rom
roms.push rom
roms.each do |r|
rom_total += 1
romfile = File.join(working_dir, r)
if File.exists? romfile
rom_count += 1
unless dry_run
args = [romfile, File.join(output_dir, r)]
if copy
puts "Copying #{r}..."
FileUtils.cp(*args)
else
puts "Moving #{r}..."
FileUtils.mv(*args)
end
end
else
puts "ROM not found: #{r}"
missing.push(rom)
end
end
end
puts "\nMoved #{rom_count}/#{rom_total} ROMs to the directory #{output_dir}/"
if missing.length > 0
puts "#{missing.length} ROM(s) not found: " + missing.join(", ")
end
end
# File is closed automatically at end of block, no need to close it
| true |
08d92d337bb3b2cd034cddc010e58d6490c89aeb
|
Ruby
|
JulianNicholls/Advent-of-Code-Ruby
|
/day-12/day-12_2.rb
|
UTF-8
| 616 | 3.25 | 3 |
[
"MIT"
] |
permissive
|
require 'json'
require 'pp'
input = JSON.parse(File.read 'input.txt')
def trim(hash)
hash.delete_if { |k, v| v.is_a?(Hash) && v.values.include?('red') }
hash.keys.each do |key|
val = hash[key]
if val.is_a? Hash
trim(val)
elsif val.is_a? Array
trim_array(val)
end
end
end
def trim_array(array)
array.delete_if { |item| item.is_a?(Hash) && item.values.include?('red') }
array.each do |item|
if item.is_a? Hash
trim(item)
elsif item.is_a? Array
trim_array(item)
end
end
end
trim(input)
pp input
puts input.to_s.scan(/-*\d+/).map(&:to_i).reduce(:+)
| true |
e4a3cd93f1d80b5fddc108a435d11c1a7232c75c
|
Ruby
|
pathbox/A-bit-of-ruby-code
|
/csv_big/csv_foreach.rb
|
UTF-8
| 302 | 2.84375 | 3 |
[] |
no_license
|
require_relative './print_helper'
require 'csv'
print_memory_usage do
print_time_spent do
sum = 0
CSV.foreach('data.csv', headers: true) do |row|
sum += row['id'].to_i
end
puts "Sum: #{sum}"
end
end
# ruby csv_foreach.rb
# Sum: 500000500000
# Time: 13.63
# Memory: 1.8 MB
| true |
903d8d0b2ab4c55ca1bb7a2ea37a307ac9dab92f
|
Ruby
|
matthope/pupistry
|
/exe/pupistry
|
UTF-8
| 11,784 | 2.65625 | 3 |
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env ruby
# Lancher for Pupistry CLI
require 'rubygems'
require 'thor'
require 'logger'
require 'fileutils'
require 'pupistry'
# Ensure all output is real time - this is a long running process with
# continual output, we want it to sync ASAP
STDOUT.sync = true
# Logging - STDOUT only
$logger = Logger.new(STDOUT)
# Thor is a toolkit for producing command line applications, see http://whatisthor.com/
class CLI < Thor
class_option :verbose, type: :boolean
class_option :config, type: :string
## Agent Commands
desc 'apply', 'Apply the latest Puppet artifact'
method_option :noop, type: :boolean, desc: 'No changes mode (note: does change checked out artifact, but no Puppet changes)'
method_option :force, type: :boolean, desc: 'Ignore existing versions, re-apply every time'
method_option :minimal, type: :boolean, desc: "Don't run Puppet unless the artifact has changed"
method_option :daemon, type: :boolean, desc: 'Run as a system daemon'
method_option :environment, type: :string, desc: 'Specifiy which environment to deploy (default: master)'
def apply
# Thor seems to force class options to be defined repeatedly? :-/
if options[:verbose]
$logger.level = Logger::DEBUG
else
$logger.level = Logger::INFO
end
if options[:config]
Pupistry::Config.load(options[:config])
else
Pupistry::Config.find_and_load
end
# Muppet Check
$logger.warn 'A daemon running in noop will do nothing except log what changes it could apply' if options[:noop] and options[:daemon]
$logger.warn 'A daemon running with force will be very wasteful of system resources! NOT RECOMMENDED.' if options[:force] and options[:daemon]
if options[:daemon]
# Run as a daemon service
Pupistry::Agent.daemon options
else
# Single-run Agent Execution
Pupistry::Agent.apply options
end
end
## Workstation Commands
desc 'build', 'Build a new archive file'
def build
# Thor seems to force class options to be defined repeatedly? :-/
if options[:verbose]
$logger.level = Logger::DEBUG
else
$logger.level = Logger::INFO
end
if options[:config]
Pupistry::Config.load(options[:config])
else
Pupistry::Config.find_and_load
end
begin
# Fetch the latest data with r10k
artifact = Pupistry::Artifact.new
artifact.fetch_r10k
artifact.hieracrypt_encrypt
artifact.build_artifact
puts '--'
puts 'Tip: Run pupistry diff to see what changed since the last artifact version'
rescue StandardError => e
$logger.fatal 'An unexpected error occured when trying to generate the new artifact file'
raise e
end
end
desc 'diff', 'Show what has changed between now and the current live artifact'
def diff
# Thor seems to force class options to be defined repeatedly? :-/
if options[:verbose]
$logger.level = Logger::DEBUG
else
$logger.level = Logger::INFO
end
if options[:config]
Pupistry::Config.load(options[:config])
else
Pupistry::Config.find_and_load
end
# Fetch the latest artifact
artifact_upstream = Pupistry::Artifact.new
artifact_upstream.checksum = artifact_upstream.fetch_latest
unless artifact_upstream.checksum
$logger.error 'There is no upstream artifact to compare to.'
exit 0
end
artifact_upstream.fetch_artifact
# Fetch the current artifact
artifact_current = Pupistry::Artifact.new
artifact_current.checksum = artifact_current.fetch_current
unless artifact_current.checksum
$logger.error 'There is no current artifact to compare to, run "pupistry build" first to generate one with current changes'
exit 0
end
artifact_current.fetch_artifact
# Are they the same version?
$logger.info 'Current version and upstream version are the same, no diff' if artifact_current.checksum == artifact_upstream.checksum
# Unpack the archives
artifact_current.unpack
artifact_upstream.unpack
# Diff the contents. This is actually bit of a pain, there's no native way
# of diffing an entire directory and a lot of the gems out there that promise
# to do diffing a) can't handle dirs and b) generally exec out to native diff
# anyway. :-(
#
# So given this, we might as well go native and just rely on the system
# diff command to do the job.
#
# TODO: We need smarts here to handle git branching, so a branch doens't
# produce a new mega diff, we want only the real changes to be
# easily visible, or the diff function loses value to people.
# Pull requests welcome :-) xoxo
Dir.chdir("#{$config['general']['app_cache']}/artifacts/") do
unless system "diff -Nuar --exclude hieracrypt unpacked.#{artifact_upstream.checksum} unpacked.#{artifact_current.checksum}"
end
end
# Cleanup
artifact_current.clean_unpack
artifact_upstream.clean_unpack
puts '--'
puts 'Tip: Run pupistry push to GPG sign & upload if happy to go live'
end
desc 'push', 'Sign & Upload a new artifact version'
def push
# Thor seems to force class options to be defined repeatedly? :-/
if options[:verbose]
$logger.level = Logger::DEBUG
else
$logger.level = Logger::INFO
end
if options[:config]
Pupistry::Config.load(options[:config])
else
Pupistry::Config.find_and_load
end
# Push the artifact to S3
artifact = Pupistry::Artifact.new
artifact.push_artifact
end
desc 'bootstrap', 'Generate a user-data bootstrap script for a node'
method_option :template, type: :string, desc: 'The template you want to generate'
method_option :base64, type: :boolean, desc: 'Output in base64 format'
method_option :environment, type: :string, desc: 'Environment to run puppet in'
def bootstrap
# Thor seems to force class options to be defined repeatedly? :-/
if options[:verbose]
$logger.level = Logger::DEBUG
else
$logger.level = Logger::INFO
end
if options[:config]
Pupistry::Config.load(options[:config])
else
Pupistry::Config.find_and_load
end
if options[:template]
$logger.debug "Generating bootstrap template #{options[:template]}"
environment = options[:environment] || 'master'
templates = Pupistry::Bootstrap.new
templates.build options[:template], environment
if options[:base64]
templates.output_base64
else
templates.output_plain
end
else
templates = Pupistry::Bootstrap.new
templates.list
puts '--'
puts 'Tip: Run `pupistry bootstrap --template example` to generate a specific template'
end
end
desc 'packer', 'Generate a packer template for a particular provider with OS bootstrap script included'
method_option :template, type: :string, desc: 'The template you want to generate'
method_option :file, type: :string, desc: 'File to write the generated packer template into'
def packer
# Thor seems to force class options to be defined repeatedly? :-/
if options[:verbose]
$logger.level = Logger::DEBUG
else
$logger.level = Logger::INFO
end
if options[:config]
Pupistry::Config.load(options[:config])
else
Pupistry::Config.find_and_load
end
if options[:template]
$logger.info "Generating packer template #{options[:template]}"
templates = Pupistry::Packer.new
templates.build options[:template]
if options[:file]
templates.output_file options[:file]
else
templates.output_plain
end
else
templates = Pupistry::Packer.new
templates.list
puts '--'
puts 'Tip: Run `pupistry packer --template example` to generate a specific template'
end
end
## Hieracrypt Feature
desc 'hieracrypt', 'Manage the encryption of Hiera data to securely restrict access from nodes'
method_option :generate, type: :boolean, desc: 'Generate an export of public cert and facts for Hieracrypt usage.'
def hieracrypt
# Thor seems to force class options to be defined repeatedly? :-/
if options[:verbose]
$logger.level = Logger::DEBUG
else
$logger.level = Logger::INFO
end
if options[:config]
Pupistry::Config.load(options[:config])
else
Pupistry::Config.find_and_load
end
# TODO
if options[:generate]
Pupistry::HieraCrypt.generate_nodedata
else
puts "Run `pupistry hieracrypt --generate` on each node to get back a data file to be saved into puppetcode"
end
end
## Other Commands
desc 'setup', 'Write a template configuration file'
method_option :force, type: :boolean, desc: 'Replace an existing config file'
def setup
# Thor seems to force class options to be defined repeatedly? :-/
if options[:verbose]
$logger.level = Logger::DEBUG
else
$logger.level = Logger::INFO
end
# Generally we should put the Pupistry configuration into the home dir, a
# developer who wants it elsewhere will be capable of figuring out how to
# install themselves.
config_dest = '~/.pupistry/settings.yaml'
# If the HOME environmental hasn't been set, dump the config into CWD.
unless ENV['HOME']
config_dest = "#{Dir.pwd}/settings.yaml"
$logger.warn "HOME is not set, so writing configuration file into #{config_dest}"
end
config_dest = File.expand_path config_dest
# Make sure the directory exists
FileUtils.mkdir_p(File.dirname(config_dest)) unless Dir.exist?(File.dirname(config_dest))
# Does a local template exist?
if File.exist?("#{Dir.pwd}/settings.example.yaml")
config_source = "#{Dir.pwd}/settings.example.yaml"
else
# Check for GEM installed location
begin
config_source = Gem::Specification.find_by_name('pupistry').gem_dir
config_source = "#{config_source}/settings.example.yaml"
rescue Gem::LoadError
# Yeah I dunno what you're doing...
$logger.error 'Unable to find settings.example.yaml, seems we are not running as a Gem nor in the CWD of the app source'
exit 0
end
end
unless File.exist?(config_source)
$logger.error "Template configuration should exist in #{config_source} but no file found/readable!"
exit 0
end
# Prevent Overwrite
if File.exist?(config_dest)
if options[:force]
$logger.warn "Overwriting #{config_dest}..."
else
$logger.error "Configuration file #{config_dest} already exists, if you wish to replace it please call with --force"
exit 0
end
end
# Copy the template configuration file to destination
begin
FileUtils.cp config_source, config_dest
$logger.info "Successfully installed configuration file into #{config_dest}"
rescue StandardError => e
$logger.error "An unexpected error occured when copying #{config_source} to #{config_dest}"
raise e
end
# TODO: This is where I'd like to do things more cleverly. Currently we
# just tell the user to edit the configuration file, but would be really
# cool to write a setup wizard that helps them complete the configuration
# file and validates the input (eg AWS keys).
if ENV['EDITOR']
$logger.info "Now open the config file with `#{ENV['EDITOR']} #{config_dest}` and set your configuration values before running Pupistry."
else
$logger.info "You now need to edit #{config_dest} with your configuration values before running Pupistry."
end
end
end
CLI.start(ARGV)
# vim:shiftwidth=2:tabstop=2:softtabstop=2:expandtab:smartindent
| true |
0a49ee5669d190625debc760816d27fffa4eb05b
|
Ruby
|
piaoyehong1107/sql-table-relations-crowdfunding-join-table-lab-hou01-seng-ft-071320
|
/lib/sql_queries.rb
|
UTF-8
| 1,838 | 3.1875 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Write your sql queries in this file in the appropriate method like the example below:
#
# def select_category_from_projects
# "SELECT category FROM projects;"
# end
# Make sure each ruby method returns a string containing a valid SQL statement.
def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title
"SELECT projects.title, SUM(pledges.amount) FROM pledges INNER JOIN projects ON pledges.project_id=projects.id GROUP BY pledges.project_id ORDER BY projects.title"
end
def selects_the_user_name_age_and_pledge_amount_for_all_pledges_alphabetized_by_name
"SELECT users.name, users.age, SUM(pledges.amount) FROM pledges INNER JOIN users ON pledges.user_id=users.id GROUP BY pledges.user_id ORDER BY users.name"
end
def selects_the_titles_and_amount_over_goal_of_all_projects_that_have_met_their_funding_goal
"SELECT projects.title, SUM(pledges.amount)-projects.funding_goal FROM pledges INNER JOIN projects ON pledges.project_id=projects.id GROUP BY pledges.project_id HAVING projects.funding_goal<=SUM(pledges.amount)"
end
def selects_user_names_and_amounts_of_all_pledges_grouped_by_name_then_orders_them_by_the_summed_amount
"SELECT users.name , SUM(pledges.amount) FROM pledges INNER JOIN users ON pledges.user_id=users.id GROUP BY users.name ORDER BY SUM(pledges.amount)"
end
def selects_the_category_names_and_pledge_amounts_of_all_pledges_in_the_music_category
"SELECT projects.category, pledges.amount FROM projects LEFT OUTER JOIN pledges ON projects.id=pledges.project_id WHERE projects.category='music'ORDER BY pledges.id"
end
def selects_the_category_name_and_the_sum_total_of_the_all_its_pledges_for_the_books_category
"SELECT projects.category, SUM(pledges.amount) FROM pledges INNER JOIN projects ON pledges.project_id=projects.id WHERE projects.category='books'"
end
| true |
1803bbf34e4c4741d03980491374f1b55cccafd1
|
Ruby
|
jbhannah/agate
|
/spec/agate/cli_spec.rb
|
UTF-8
| 2,110 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
# -*- coding: utf-8 -*-
require "spec_helper"
require "agate/cli"
RSpec.describe Agate::CLI do
let(:cli) { File.join(File.expand_path(File.dirname(__FILE__)), "..", "..", "bin", "agate") }
let(:text) { "勉【べん】強【きょう】します" }
context "with help option" do
it "shows the help message and exits" do
stub_const("Agate::CLI::ARGV", ["-h"])
text = <<-eos
Usage: agate [options] text-to-convert
Options:
-d, --delimiters DELIMITERS Specify custom delimiters for ruby text (default: 【】)
-f, --formatter FORMAT Specify a formatter to use (default/fallback: plain text)
-h, --help Show this message
-v, --version Show version
eos
expect do
begin
load cli
rescue SystemExit
end
end.to output(text).to_stdout
end
end
context "with version option" do
it "shows the version and exits" do
version = ["1", "2", "3"]
stub_const("Agate::CLI::ARGV", ["-v"])
stub_const("Agate::VERSION", version)
expect do
begin
load cli
rescue SystemExit
end
end.to output(version.join('.') + "\n").to_stdout
end
end
context "with defaults" do
it "parses delimited text and echoes it back" do
stub_const("Agate::CLI::ARGV", [text])
expect { load cli }.to output(text + "\n").to_stdout
end
end
context "with custom delimiters" do
let(:text) { "勉(べん)強(きょう)します" }
it "parses delimited text and echoes it back" do
stub_const("Agate::CLI::ARGV", ["-d", "\"()\"", text])
expect { load cli }.to output(text + "\n").to_stdout
end
end
context "with formatter" do
let(:formatted_text) { "<ruby>勉<rp>【</rp><rt>べん</rt><rp>】</rp></ruby><ruby>強<rp>【</rp><rt>きょう</rt><rp>】</rp></ruby>します" }
it "parses delimited text and echoes it back" do
stub_const("Agate::CLI::ARGV", ["-f", "html", text])
expect { load cli }.to output(formatted_text + "\n").to_stdout
end
end
end
| true |
2d8e6549627135848cf99b04f5fb9d530cfe682f
|
Ruby
|
jean-baptiste-blanc/project-euler
|
/problem3.rb
|
UTF-8
| 158 | 2.765625 | 3 |
[] |
no_license
|
# search for the prime numbers
require 'prime'
primes =Prime.prime_division (600851475143)
primes.each {|prime,division| puts "Next prime factor #{prime}"}
| true |
0f249f4a75c57c7bb39454d844bbd7beaba99fff
|
Ruby
|
theouty/ruby-project-alt-guidelines
|
/lib/new_event_app.rb
|
UTF-8
| 3,259 | 3.5 | 4 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class NewEventApp
attr_reader :user
def run
welcome
login_and_signup
create_event
event_search
update_event
delete
bye
end
def welcome
puts "Welcome to the Events application!"
end
def login_and_signup
puts "Type your name"
username = gets.chomp
puts "Type your city"
city = gets.chomp
@user = User.find_or_create_by({name: username, current_city: city})
end
def create_event
puts "Do you want to a create an event you heard about? Type 'yes' if yes. Type anything else otherwise."
response = gets.chomp
if response == "yes"
puts "What is the name of the event?"
eventname = gets.chomp
puts "What is the type of the event?"
eventkind = gets.chomp
puts "What is the date of the event in 8 digits (mmddyyyy)?"
eventdate = gets.chomp
puts "What is an average age you would give to attendees"
eventage = gets.chomp
Event.create({name: eventname, event_type: eventkind, date_digits: eventdate, avg_age_attendees: eventage})
end
end
def event_search
puts "Do you want to see all of events. Type 'all' if you do. If not type 'no'."
answer = gets.chomp
if answer == "all"
Event.all.each do |event|
puts "Event name: #{event.name}, Event Type: #{event.event_type}, Event Date: #{event.date_digits}, Average Attendee Age: #{event.avg_age_attendees}"
end
else
end
end
def update_event
puts "Do you want to update event. If yes, type 'yes'. If not, type anything else."
answer = gets.chomp
if answer == "yes"
puts "Type the name of the event you want to change"
name_to_change = gets.chomp
event = Event.find_by_name("#{name_to_change}")
puts "Event name: #{event.name}, Event Type: #{event.event_type}, Event Date: #{event.date_digits}, Average Attendee Age: #{event.avg_age_attendees}
Type the attribute you want to update('name', 'event type', 'date', 'average age'), also note dates are recorded as 8 digit integers:"
information = gets.chomp
puts "Type the updated value you want for that attribute"
specific = gets.chomp
if information == "name"
event.update(name: specific)
elsif information == "event type"
event.update(event_type: specific)
elsif information == "date"
event.update(date_digits: specific)
elsif information == "average age"
event.update(avg_age_attendees: specific)
end
end
end
def delete
puts "If you think an event is lame, tell me the name. I will delete the event from our list. If you like all the events type 'no'"
hate = gets.chomp
Event.where(:name => hate).destroy_all
end
def bye
puts "Thank you for using our app! Hope you find something fun to do!"
end
end
| true |
168e598d38bb13f961646ec20d58bfec25c247c4
|
Ruby
|
thiagocanto/bowling
|
/spec/player_spec.rb
|
UTF-8
| 1,152 | 3.1875 | 3 |
[] |
no_license
|
require_relative '../src/models/player'
require_relative '../src/rules/ten_pin_rules'
RSpec.describe Player do
context 'having correct values' do
player = Player.new 'Steve', %w[8 2 7 3 3 4 10 2 8 10 10 8 0 10 8 2 9]
it 'should calculate round scores' do
expect(player.scores(TenPinRules)).to eq [17, 30, 37, 57, 77, 105, 123, 131, 151, 170]
end
it 'should calculate total score' do
expect(player.final_score(TenPinRules)).to eq 170
end
end
context 'having a perfect game' do
it 'should get max score' do
player = Player.new 'Awesome bowler', %w[10 10 10 10 10 10 10 10 10 10 10 10]
expect(player.final_score(TenPinRules)).to eq 300
end
end
context 'having a lame game' do
it 'should get minimum score' do
player = Player.new 'Lame bowler', %w[0 0 0 0 0 0 0 0 0 0 0]
expect(player.final_score(TenPinRules)).to eq 0
end
end
# couldn't make it work :(
# context 'having negative value on chance' do
# it 'should not create the player' do
# expect(Player.new('John', %w[-8 5])).to raise StandardError "Player score can't have negatives"
# end
# end
end
| true |
a16e167a2c2c796671a7633062cb2cdd317d05a7
|
Ruby
|
taylortreece/pick-a-key
|
/lib/pick_a_key/cli.rb
|
UTF-8
| 5,826 | 3.734375 | 4 |
[
"MIT"
] |
permissive
|
require './lib/pick_a_key'
require 'pp'
class PickAKey::CLI
def start
puts "Welcome to your basic music theory coordinator!"
puts
puts "If you want to check out a key, choose from the list below by typing the key as you see it listed."
puts
puts "Pick a key:"
puts
puts "Major:"
puts PickAKey::Scraper.all_scale_names[0]
puts
puts "Minor:"
puts PickAKey::Scraper.all_scale_names[1]
PickAKey::Scraper.key_information_creator
puts
puts PickAKey::CLI.current_key_information
PickAKey::CLI.menu
PickAKey::CLI.commands
end
def self.current_key=(key)
@current_key=key
end
def self.current_key
@current_key
end
def self.menu
puts "________________________________________"
puts
puts "What would you like to do?\n"
puts "____________________________________________________________________________"
puts "To find this key's relative Major/minor, type 'Major' or 'minor" # Done.
puts "To find this key's relative fifth, type 'fifth'" #Done.
puts "To generate a random chord progression in this key, type 'chord'" #Done.
puts "To get a random song generated in this key, type 'song'" #Done.
puts "To look up a new key, type 'new' to review and choose from the list of keys." #Done.
puts "To see all keys at once, type 'all'" #Done.
puts "To exit, type 'exit'" #Done.
end
def self.commands
user_input=gets.strip
#relative keys
if user_input.downcase.include?("m") || user_input.include?("fi")
PickAKey::CLI.relative_key_selector(user_input)
#chord progression
elsif user_input.downcase.include?("ch")
PickAKey::CLI.generate_chord_progression
#song creation
elsif user_input.include?("so")
PickAKey::CLI.song_output
#new key
elsif user_input.include?("ne")
PickAKey::CLI.new.start
#all keys
elsif user_input.include?("al")
PickAKey::CLI.list_all_keys
#exit
elsif user_input.include?("ex")
puts "See you soon."
end
end
#INFORMATION OUTPUT METHODS
def self.current_key_information
puts
puts "Key:"
puts @current_key.name
puts
puts "notes:"
puts @current_key.notes
puts
puts "chords:"
puts @current_key.chords
puts
puts "Popular Chord Progressions:"
pp @current_key.popular_chord_progressions
puts
puts "relative_fifth:"
puts @current_key.relative_fifth
puts
if @current_key.relative_minor.include?("Major")
puts "relative Major:"
else
puts "relative minor:"
end
puts @current_key.relative_minor
end
def self.popular_chord_progressions_pp
@current_key.popular_chord_progressions.each_pair do |k, v|
puts k
pp v
binding.pry
end
end
#COMMAND METHODS
#"To find this key's relative Major/minor, type 'Major' or 'minor" # Done.
#"To find this key's relative fifth, type 'fifth'" #Done.
def self.relative_key_selector(user_input)
if user_input.downcase.include?("m")
switch="a"
PickAKey::CLI.relative_key(switch)
elsif user_input.include?("fi")
switch="b"
PickAKey::CLI.relative_key(switch)
end
end
def self.relative_key(switch)
if PickAKey::CLI.current_key != nil
PickAKey::Scraper.key_information_creator(switch)
puts PickAKey::CLI.current_key_information
PickAKey::CLI.menu
PickAKey::CLI.commands
else
puts
puts "**You are not currently viewing an individual key. Please choose a valid selection**"
PickAKey::CLI.menu
PickAKey::CLI.commands
end
end
#"To generate a random chord progression in this key, type 'chord'" #Done.
def self.chord_progression(user_input=nil)
@progression = []
i=0
if user_input == nil then user_input=4 end
if @current_key.type.include?("ajor")
while i < user_input
@progression << @current_key.chords[rand(6)]
i += 1
end
else
while i < user_input
@progression << @current_key.chords.delete_if {|a| a.include?("dim")}[rand(6)]
i += 1
end
end
@progression
end
def self.generate_chord_progression
puts
puts "Enter the number of chords you would like your progression to be (e.g. 4)"
user_input=gets.chomp.to_i
puts "Random #{user_input} chord progression written in #{PickAKey::CLI.current_key.name}"
puts
puts PickAKey::CLI.chord_progression(user_input)
PickAKey::CLI.menu
PickAKey::CLI.commands
end
#"To get a random song generated in this key, type 'song'" #Done.
def self.song_creation
verse = PickAKey::CLI.chord_progression
puts
puts "Intro:"
puts intro = verse
puts ""
puts "1st Verse (insert lyrics):"
puts verse
puts ""
puts "1st Chorus (insert chorus lyrics):"
puts chorus = PickAKey::CLI.chord_progression
puts ""
puts "2nd Verse (insert lyrics):"
puts verse
puts ""
puts "2nd Chorus (repeat chorus lyrics):"
puts chorus
puts ""
puts "Bridge (insert lyrics):"
puts bridge = PickAKey::CLI.chord_progression
puts ""
puts "3rd Chorus (repeat chorus lyrics):"
puts chorus
puts ""
puts "Outro:"
puts chorus
puts ""
puts "End. Don't tell people I'm giving out free songs..."
end
def self.song_output
puts
puts "Generating your masterpiece in #{@current_key.name}."
PickAKey::CLI.song_creation
PickAKey::CLI.menu
PickAKey::CLI.commands
end
#"To see all keys at once, type 'all'" #Done.
def self.list_all_keys
puts
puts "loading..."
puts
pp PickAKey::Scraper.create_hash_for_keys
PickAKey::CLI.menu
PickAKey::CLI.commands
end
end
| true |
9daf71787202e97d89d516845164adf0c35eb268
|
Ruby
|
saghourkhalil/day-6
|
/04_simon_says/simon_says.rb
|
UTF-8
| 696 | 3.953125 | 4 |
[] |
no_license
|
#write your code here
def echo say
return p "#{say}"
end
def shout say
return p "#{say.upcase}"
end
def repeat(string, nb = 2)
([string] * nb).join(" ")
end
def start_of_word string, nb
i = 0
char = ""
while i < nb
char << string[i]
i += 1
end
return char
end
def first_word mots
i = 0
char = ""
while mots[i] != " "
char << mots[i]
i += 1
end
return char
end
def titleize mots
mots_array = mots.downcase.split(" ")
mots_array[0] = mots_array[0].capitalize
i=0
mots_array.each do |a|
if (a != "the" && a != "and")
mots_array[i] = a.capitalize
end
i+=1
end
return mots_array.join(" ")
end
| true |
bee1051a59c62a4aaaf4ec1756bd812b8bd8d513
|
Ruby
|
janefoster72/config
|
/lib/config/private_data.rb
|
UTF-8
| 1,374 | 2.734375 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
module Config
# This class manages everything that's not checked into the project
# repository.
class PrivateData
def initialize(path)
@path = Pathname.new(path)
end
# Manage a secret.
#
# name - Symbol name of the secret.
#
# Returns a Config::Core::File.
def secret(name)
Config::Core::File.new(@path + "secret-#{name}")
end
# Manage an SSH private key.
#
# name - Symbol name of the key.
#
# Returns a Config::Core::File.
def ssh_key(name)
Config::Core::File.new(@path + "ssh-key-#{name}")
end
# Manage the signature for an SSH known host.
#
# host - String name of the host.
#
# Returns a Config::Core::File.
def ssh_host_signature(host)
Config::Core::File.new(@path + "ssh-host-#{host}")
end
# Get the stored accumulation.
#
# Returns a Config::Core::Accumulation or nil.
def accumulation
data = accumulation_file.read
Config::Core::Accumulation.from_string(data) if data
end
# Store the accumulation.
#
# accumulation - Config::Core::Accumulation.
#
# Returns nothing.
def accumulation=(accumulation)
accumulation_file.write(accumulation.serialize)
end
protected
def accumulation_file
Config::Core::File.new(@path + "accumulation.marshall")
end
end
end
| true |
2ea24a65a6d1e443d7aaad4a6d1614cbff8f5059
|
Ruby
|
Kumassy/MCDotArtMaker
|
/lib/mc_dot_art_maker/extern_lib_extension.rb
|
UTF-8
| 1,180 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
#
# Add some features to extern gem.
#
module Magick
class Image
def get_color_rgb_at(x, y)
pixel = self.pixel_color(x,y)
r = pixel.red / 257
g = pixel.green / 257
b = pixel.blue / 257
::Color::RGB.new(r, g, b)
end
end
end
module Color
class RGB
# Add to check equality
def ==(other)
@r == other.r && @g == other.g && @b == other.b
end
# Add to use this object for hash key
def eql?(other)
@r.eql?(other.r) && @g.eql?(other.g) && @b.eql?(other.b)
end
def hash
code = 17
code = 37*code + @r.hash
code = 37*code + @g.hash
code = 37*code + @b.hash
code
end
end
end
# Add to rewrite NBT files
module NBTUtils
module Tag
class ByteArray
def payload=(new_value)
@payload = ::BinData::String.new(new_value)
end
end
end
end
module NBTUtils
module Tag
class Int
def payload=(new_value)
@payload = ::BinData::Int32be.new(new_value)
end
end
end
end
module NBTUtils
module Tag
class Short
def payload=(new_value)
@payload = ::BinData::Int16be.new(new_value)
end
end
end
end
| true |
4cecea2bc912a4a526344631894a2a74640769c3
|
Ruby
|
jhartwell/ironruby
|
/Tests/Experiments/CF/Return/Errors.rb
|
UTF-8
| 79 | 2.9375 | 3 |
[] |
no_license
|
def foo
$p = Proc.new { return }
end
def y
yield
end
foo
y &$p
| true |
f74e3119c6d38ce97445ed26418cd4cd109390c6
|
Ruby
|
cupofjoy/the-bachelor-todo-prework
|
/lib/bachelor.rb
|
UTF-8
| 1,238 | 3.703125 | 4 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def get_first_name_of_season_winner(data, season)
# code here
data.each do |season_num, people|
if season_num == season
people.each do |person|
if person["status"] == "Winner"
return person["name"].split(' ')[0]
end
end
end
end
end
def get_contestant_name(data, occupation)
# code here
data.each do |season, people|
people.each do |person|
if person["occupation"] == occupation
return person["name"]
end
end
end
end
def count_contestants_by_hometown(data, hometown)
# code here
count = 0
data.each do |season, people|
people.each do |person|
if person["hometown"] == hometown
count += 1
end
end
end
count
end
def get_occupation(data, hometown)
# code here
data.each do |season, people|
people.each do |person|
if person["hometown"] == hometown
return person["occupation"]
end
end
end
end
def get_average_age_for_season(data, season)
# code here
age = 0
count = 0
data.each do |season_num, people|
if season_num == season
people.each do |person|
age += person["age"].to_i
count += 1
end
end
end
age = (age/count.to_f).round
end
| true |
c20fab9337920d56d480598e6942244a57381a1a
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/grade-school/279f97b411dc4da2a6a73f84ab6484c2.rb
|
UTF-8
| 331 | 3.421875 | 3 |
[] |
no_license
|
class School
attr_accessor :school
def initialize
@school = {}
end
def add(name, grade)
school[grade] ||= []
school[grade] << name
end
def to_hash
Hash[school.sort do |a, b|
a[-1].sort!
a.first <=> b.first
end]
end
def grade(num)
school[num] ? school[num].sort : []
end
end
| true |
5b371a609f27af608858cf5e705490d8c9010845
|
Ruby
|
clee1996/Big_O_and_anagrams
|
/two_sum.rb
|
UTF-8
| 644 | 4 | 4 |
[] |
no_license
|
# def bad_two_sum?(arr, target)
# arr.each_with_index do |ele, i|
# arr.each_with_index do |ele2, i2|
# if ele + ele2 == target && i2 > i
# return true
# end
# end
# end
# false
# end
def okay_two_sum?(arr, target)
# arr.sort.bsearch(target)
# arr.combination(2).any? { |el,el2| return true if el + el2 == target }
sorted = arr.sort
(0...sorted.lentgh-1).each do |i|
if arr[i] + arr[i+1] == target
return true
end
end
end
arr = [7,1,9,6,2,3,10] #[1,2,3,6,7,9,10]
p okay_two_sum?(arr, 6)
p okay_two_sum?(arr, 11)
| true |
58ebdee91c1535e30d59cac4af102895d50ec28b
|
Ruby
|
department-of-veterans-affairs/caseflow-efolder
|
/app/services/image_converter_service.rb
|
UTF-8
| 1,799 | 2.703125 | 3 |
[] |
no_license
|
# Converts images to PDFs
class ImageConverterService
class ImageConverterError < StandardError; end
include ActiveModel::Model
attr_accessor :image, :record
def process
# If we do not handle converting this mime_type, don't do any processing.
return image if self.class.converted_mime_type(record.mime_type) == record.mime_type
converted_image = convert
record.update_attributes!(conversion_status: :conversion_success)
converted_image
rescue ImageConverterError
record.update_attributes!(conversion_status: :conversion_failed)
image
end
# If the converter converts this mime_type then this returns the converted type
# otherwise it just returns the original type.
def self.converted_mime_type(mime_type)
if FeatureToggle.enabled?(:convert_tiff_images)
return "application/pdf" if mime_type == "image/tiff"
end
mime_type
end
private
EXCEPTIONS = [Errno::ECONNREFUSED, HTTPClient::ReceiveTimeoutError].freeze
# :nocov:
def convert_tiff_to_pdf
url = "http://localhost:5000/tiff-convert"
clnt = HTTPClient.new
response = nil
MetricsService.record("Image Magick: Convert tiff to pdf",
service: :image_magick,
name: "image_magick_convert_tiff_to_pdf") do
Tempfile.open(["tiff_to_convert", ".tiff"]) do |file|
file.binmode
file.write(image)
file.rewind
body = { "file" => file }
response = clnt.post(url, body)
end
raise ImageConverterError if response.status != 200
end
response.body
rescue *EXCEPTIONS
raise ImageConverterError
end
# :nocov:
def convert
case record.mime_type
when "image/tiff"
convert_tiff_to_pdf
else
image
end
end
end
| true |
c7dc02d296a1edf3db318b28c1718b4fe1233d50
|
Ruby
|
acelizondo1/connect_four
|
/lib/game_board.rb
|
UTF-8
| 2,145 | 3.734375 | 4 |
[] |
no_license
|
class GameBoard
attr_reader :board
def initialize
@board = Array.new(7){ Array.new(6) }
end
def make_move(column, player)
unless column > @board.length || column < 0
for row in 0..5
if @board[column-1][row] == nil
@board[column-1][row] = player
return @board[column-1][row]
end
end
end
false
end
def check_winner(player)
if vertical_winner?(player) || horizontal_winner?(player) || diagonal_winner?(player)
true
else
false
end
end
def display_board
puts "| 1 | 2 | 3 | 4 | 5 | 6 | 7 |"
for row in 5.downto(0)
row_string = "|"
for column in [email protected]
if @board[column][row] == nil
cell = "*"
else
cell = @board[column][row]
end
row_string += " #{cell} |"
end
puts row_string
end
end
def is_tie?
for column in 0..6
for row in 0..5
return false if @board[column][row] == nil
end
end
true
end
private
def vertical_winner?(player)
for column in 0..6
count = 0
for row in 0..5
@board[column][row] == player ? count += 1 : count = 0
return true if count >= 4
end
end
false
end
def horizontal_winner?(player)
for col in 0..3
for cell in 0..5
if @board[col][cell] == player
count = 1
for i in 1..3
@board[col+i][cell] == player ? count += 1 : break
end
return true if count >= 4
end
end
end
false
end
def diagonal_winner?(player)
for col in 0..3
for cell in 0..5
if @board[col][cell] == player
count = 1
if @board[col+1][cell+1] == player
for i in 1..3
@board[col+i][cell+i] ==player ? count += 1 : break
end
elsif cell > 0 && @board[col+1][cell-1] == player
for i in 1..3
@board[col+i][cell-i] ==player ? count += 1 : break
end
end
return true if count >= 4
end
end
end
false
end
end
| true |
6e8c6f6e823f5be62f59d4ecee817f883aaa4757
|
Ruby
|
ACMCMU/BoredPrototype
|
/vendor/bundle/ruby/1.9.1/gems/shoulda-matchers-2.4.0/lib/shoulda/matchers/active_model/comparison_matcher.rb
|
UTF-8
| 1,418 | 2.609375 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
module Shoulda # :nodoc:
module Matchers
module ActiveModel # :nodoc:
# Examples:
# it { should validate_numericality_of(:attr).
# is_greater_than(6).
# less_than(20)...(and so on) }
class ComparisonMatcher < ValidationMatcher
def initialize(value, operator)
@value = value
@operator = operator
@message = nil
end
def for(attribute)
@attribute = attribute
self
end
def matches?(subject)
@subject = subject
disallows_value_of(value_to_compare, @message)
end
def allowed_types
'integer'
end
def with_message(message)
@message = message
end
private
def value_to_compare
case @operator
when :> then [@value, @value - 1].sample
when :>= then @value - 1
when :== then @value + 1
when :< then [@value, @value + 1].sample
when :<= then @value + 1
end
end
def expectation
case @operator
when :> then "greater than"
when :>= then "greater than or equal to"
when :== then "equal to"
when :< then "less than"
when :<= then "less than or equal to"
end
end
end
end
end
end
| true |
df2fe8527a3308e8d44ecf176ce2c29a98ffdffa
|
Ruby
|
luizeof/mp3file
|
/lib/mp3file/mp3_file.rb
|
UTF-8
| 9,316 | 2.515625 | 3 |
[] |
no_license
|
module Mp3file
class InvalidMP3FileError < Mp3fileError; end
class MP3File
attr_reader(:file, :file_size, :audio_size)
attr_reader(:first_header_offset, :first_header)
attr_reader(:xing_header_offset, :xing_header)
attr_reader(:vbri_header_offset, :vbri_header)
attr_reader(:mpeg_version, :layer, :bitrate, :samplerate, :mode)
attr_reader(:num_frames, :total_samples, :length)
attr_accessor(:id3v1_tag, :id3v2_tag, :extra_id3v2_tags)
def initialize(file_path, options = {})
file_path = Pathname.new(file_path).expand_path if file_path.is_a?(String)
load_file(file_path, options)
end
def vbr?
@vbr
end
def id3v1tag?
!@id3v1_tag.nil?
end
def id3v2tag?
!@id3v2_tag.nil?
end
def title
value_from_tags(:title)
end
def artist
value_from_tags(:artist)
end
def album
value_from_tags(:album)
end
def track
value_from_tags(:track)
end
def year
value_from_tags(:year)
end
def comment
value_from_tags(:comment)
end
def genre
value_from_tags(:genre)
end
def each_header
file = File.open(@file.path, "rb")
offset = @first_header_offset
file.seek(offset, IO::SEEK_SET)
while !file.eof?
header = MP3Header.new(file)
yield offset, header
offset = offset + header.frame_size
file.seek(offset, IO::SEEK_SET)
end
file.close
end
private
def value_from_tags(v1_field)
if @id3v1_tag
@id3v1_tag.send(v1_field)
else
nil
end
end
def load_file(file_path, options = {})
scan_all_headers = %w{ t true 1 }.include?(options[:scan_all_headers].to_s)
@file = file_path.open('rb')
@file.seek(0, IO::SEEK_END)
@file_size = @file.tell
# Try to read an ID3v1 tag.
@id3v1_tag = nil
begin
@file.seek(-128, IO::SEEK_END)
@id3v1_tag = ID3v1Tag.parse(@file)
rescue Mp3file::InvalidID3v1TagError
@id3v1_tag = nil
ensure
@file.seek(0, IO::SEEK_SET)
end
# Try to detect an ID3v2 header.
@id3v2_tag = nil
begin
@id3v2_tag = ID3v2::Tag.new(@file)
rescue ID3v2::InvalidID3v2TagError # => e
# $stderr.puts "Error parsing ID3v2 tag: %s\n\t%s" %
# [ e.message, e.backtrace.join("\n\t") ]
@id3v2_tag = nil
@file.seek(0, IO::SEEK_SET)
end
# Skip past the ID3v2 header if it's present.
if @id3v2_tag
@file.seek(@id3v2_tag.size, IO::SEEK_SET)
end
# Count how many bytes we had to skip while searching for a
# frame.
@skipped_bytes = 0
# Some files have more than one ID3v2 tag. If we can't find an
# MP3 header in the next 4k, try reading another ID3v2 tag and
# repeat.
@extra_id3v2_tags = []
begin
# Try to find the first two MP3 headers.
loop do
@first_header_offset, @first_header = get_next_header(@file)
@file.seek(@first_header_offset + @first_header.frame_size, IO::SEEK_SET)
second_header_offset = @file.tell - 4
second_header =
begin
MP3Header.new(@file)
rescue InvalidMP3HeaderError
nil
end
# Pretend we didn't read the second header.
@file.seek(@first_header_offset + 4)
if second_header && @first_header.same_header?(second_header)
break
end
end
rescue InvalidMP3FileError
if @id3v2_tag
end_of_tags = @id3v2_tag.size + @extra_id3v2_tags.map(&:last).map(&:size).reduce(:+).to_i
@file.seek(end_of_tags, IO::SEEK_SET)
tag = nil
begin
tag = ID3v2::Tag.new(@file)
rescue ID3v2::InvalidID3v2TagError
tag = nil
@file.seek(end_of_tags, IO::SEEK_SET)
end
if tag
@extra_id3v2_tags << [ end_of_tags, tag ]
# Start the counter of skipped bytes over again, since we're
# starting the search for the first header over again.
@skipped_bytes = 0
retry
else
raise
end
else
raise
end
end
@mpeg_version = @first_header.version
@layer = @first_header.layer
@bitrate = @first_header.bitrate / 1000
@samplerate = @first_header.samplerate
@mode = @first_header.mode
@audio_size = @file_size
if @id3v1_tag
@audio_size -= 128
end
if @id3v2_tag
@audio_size -= @id3v2_tag.size
end
# If it's VBR, there should be an Xing header after the
# side_bytes.
@xing_header = nil
@file.seek(@first_header.side_bytes, IO::SEEK_CUR)
begin
@xing_header = XingHeader.new(@file)
rescue InvalidXingHeaderError
@file.seek(@first_header_offset + 4, IO::SEEK_CUR)
end
if scan_all_headers
# Loop through all the frame headers, to check for VBR / CBR (as
# a Xing header can show up in either case).
frame_headers = [ @first_header ]
last_header_offset = @first_header_offset
loop do
file.seek(last_header_offset + frame_headers.last.frame_size)
last_header_offset, header = get_next_header(file)
if header.nil?
break
else
frame_headers << header
end
end
uniq_brs = frame_headers.map { |h| h.bitrate }.uniq
@vbr = uniq_brs.size > 1
if uniq_brs.size == 1
@bitrate = uniq_brs.first / 1000
end
@num_frames = frame_headers.size
else
# Use the presence and name of the Xing header to make the VBR
# / CBR call. Assume that Xing headers, when present in a CBR
# file, are called "Info".
@vbr = !@xing_header.nil? && @xing_header.name == "Xing"
end
# puts "@num_frames (1) = #{@num_frames.inspect}"
# puts "@bitrate (1) = #{@bitrate.inspect}"
# puts "@vbr = #{@vbr.inspect}"
# puts "@xing_header.frames = #{@xing_header && @xing_header.frames.inspect}"
# puts "@xing_header.bytes = #{@xing_header && @xing_header.bytes.inspect}"
# puts "@audio_size = #{@audio_size.inspect}"
# puts "@first_header size = #{@first_header.frame_size.inspect}"
# Find the number of frames, in this order:
# 1. The frame count from the Xing (or Info) header.
# 2. The number of frames we actually counted by scanning the
# whole file, which we might not have done.
# 3. Assume it's CBR and divide the file size by the frame size.
@num_frames =
(@xing_header && @xing_header.frames) ||
@num_frames ||
(@audio_size / @first_header.frame_size)
# puts "@num_frames (2) = #{@num_frames.inspect}"
# Figure out the total samples and the time duration.
@total_samples = @num_frames * @first_header.samples
@length = @total_samples.to_f / @samplerate.to_f
# puts "@total_samples = #{@total_samples.inspect}"
# puts "@length = #{@length.inspect}"
# If the file looks like it's a VBR file, do an averate bitrate
# calculation, either using the Xing header's idea of the file
# size or the one we found.
if @vbr
@bitrate = ((@xing_header && @xing_header.bytes) || @audio_size) / @length.to_f * 8 / 1000
end
# puts "@bitrate (2) = #{@bitrate.inspect}"
@file.close
end
def get_next_header(file, offset = nil)
if offset && offset != file.tell
file.seek(offset, IO::SEEK_SET)
end
header = nil
initial_header_offset = file.tell
header_offset = file.tell
while header.nil?
begin
header = MP3Header.new(file)
header_offset = file.tell - 4
rescue InvalidMP3HeaderError
header_offset += 1
if header_offset - initial_header_offset > 4096
raise InvalidMP3FileError, "Could not find a valid MP3 header in the first 4096 bytes."
else
file.seek(header_offset, IO::SEEK_SET)
retry
end
rescue EOFError
break
end
# byte = file.readbyte
# while byte != 0xFF
# byte = file.readbyte
# end
# header_bytes = [ byte ] + file.read(3).bytes.to_a
# if header_bytes[1] & 0xE0 != 0xE0
# file.seek(-3, IO::SEEK_CUR)
# else
# header = MP3Header.new(header_bytes)
# if !header.valid?
# header = nil
# file.seek(-3, IO::SEEK_CUR)
# else
# header_offset = file.tell - 4
# end
# end
end
@skipped_bytes += header_offset - initial_header_offset
if @skipped_bytes > 2048
raise InvalidMP3FileError, "Had to skip > 2048 bytes in between headers."
end
# if initial_header_offset != header_offset
# puts "Had to skip past #{header_offset - initial_header_offset} to find the next header. header_offset = #{header_offset} header = #{header.inspect}"
# end
[ header_offset, header ]
end
end
end
| true |
204d10e84995bcb0274afe732ccec2aeafcf940b
|
Ruby
|
rdavid1099/poke-api-v2
|
/spec/unit/poke_api/pokemon/pokemon_type_spec.rb
|
UTF-8
| 531 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
RSpec.describe PokeApi::Pokemon::PokemonType do
describe '#initialize' do
it 'creates a basic PokemonType object from raw json data' do
raw_data = {
slot: 2,
type: {
name: "flying",
url: "https://pokeapi.co/api/v2/type/3/"
}
}
poke_type = PokeApi::Pokemon::PokemonType.new(raw_data)
expect(poke_type.class).to eq(PokeApi::Pokemon::PokemonType)
expect(poke_type.slot).to eq(2)
expect(poke_type.type.class).to eq(PokeApi::Type)
end
end
end
| true |
36dde17dc975c9605df4239c050f89646fdf13e8
|
Ruby
|
shadabahmed/leetcode-problems
|
/1047-remove-all-adjacent-duplicates-in-string.rb
|
UTF-8
| 253 | 3.578125 | 4 |
[] |
no_license
|
# @param {String} s
# @return {String}
def remove_duplicates(s)
stack = []
s.each_char do |c|
if stack.last == c
stack.pop while c == stack.last
else
stack.push(c)
end
end
stack.join
end
p remove_duplicates "abbaca"
| true |
b2236c5135ab512446a2f72c0e77476f38624efd
|
Ruby
|
libgit2/docurium
|
/lib/docurium/cparser.rb
|
UTF-8
| 13,503 | 2.78125 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
class Docurium
class CParser
# Remove common prefix of all lines in comment.
# Otherwise tries to preserve formatting in case it is relevant.
def cleanup_comment(comment)
return "" unless comment
lines = 0
prefixed = 0
shortest = nil
compacted = comment.sub(/^\n+/,"").sub(/\n\s*$/, "\n")
compacted.split(/\n/).each do |line|
lines += 1
if line =~ /^\s*\*\s*$/ || line =~ /^\s*$/
# don't count length of blank lines or lines with just a " * " on
# them towards shortest common prefix
prefixed += 1
shortest = line if shortest.nil?
elsif line =~ /^(\s*\*\s*)/
prefixed += 1
shortest = $1 if shortest.nil? || shortest.length > $1.length
end
end
if shortest =~ /\s$/
shortest = Regexp.quote(shortest.chop) + "[ \t]"
elsif shortest
shortest = Regexp.quote(shortest)
end
if lines == prefixed && !shortest.nil? && shortest.length > 0
if shortest =~ /\*/
return comment.gsub(/^#{shortest}/, "").gsub(/^\s*\*\s*\n/, "\n")
else
return comment.gsub(/^#{shortest}/, "")
end
else
return comment
end
end
# Find the shortest common prefix of an array of strings
def shortest_common_prefix(arr)
arr.inject do |pfx,str|
pfx = pfx.chop while pfx != str[0...pfx.length]; pfx
end
end
# Match #define A(B) or #define A
# and convert a series of simple #defines into an enum
def detect_define(d)
if d[:body] =~ /\A\#\s*define\s+((\w+)\([^\)]+\))/
d[:type] = :macro
d[:decl] = $1.strip
d[:name] = $2
d[:tdef] = nil
elsif d[:body] =~ /\A\#\s*define\s+(\w+)/
names = []
d[:body].scan(/\#\s*define\s+(\w+)/) { |m| names << m[0].to_s }
d[:tdef] = nil
names.uniq!
if names.length == 1
d[:type] = :define
d[:decl] = names[0]
d[:name] = names[0]
elsif names.length > 1
d[:type] = :enum
d[:decl] = names
d[:name] = shortest_common_prefix(names)
d[:name].sub!(/_*$/, '')
end
end
end
# Take a multi-line #define and join into a simple definition
def join_define(text)
text = text.split("\n\n", 2).first || ""
# Ruby 1.8 does not support negative lookbehind regex so let's
# get the joined macro definition a slightly more awkward way
text.split(/\s*\n\s*/).inject("\\") do |val, line|
(val[-1] == ?\\) ? val = val.chop.strip + " " + line : val
end.strip.gsub(/^\s*\\*\s*/, '')
end
# Process #define A(B) macros
def parse_macro(d)
if d[:body] =~ /define\s+#{Regexp.quote(d[:name])}\([^\)]*\)[ \t]*(.*)/m
d[:value] = join_define($1)
end
d[:comments] = d[:rawComments].strip
end
# Process #define A ... macros
def parse_define(d)
if d[:body] =~ /define\s+#{Regexp.quote(d[:name])}[ \t]*(.*)/
d[:value] = join_define($1)
end
d[:comments] = d[:rawComments].strip
end
# Match enum {} (and possibly a typedef thereof)
def detect_enum(d)
if d[:body] =~ /\A(typedef)?\s*enum\s*\{([^\}]+)\}\s*([^;]+)?;/i
typedef, values, name = $1, $2, $3
d[:type] = :enum
d[:decl] = values.strip.split(/\s*,\s*/).map do |v|
v.split(/\s*=\s*/)[0].strip
end
if typedef.nil?
d[:name] = shortest_common_prefix(d[:decl])
d[:name].sub!(/_*$/, '')
# Using the common prefix for grouping enum values is a little
# overly aggressive in some cases. If we ended up with too short
# a prefix or a prefix which is too generic, then skip it.
d[:name] = nil unless d[:name].scan('_').length > 1
else
d[:name] = name
end
d[:tdef] = typedef
end
end
# Process enum definitions
def parse_enum(d)
if d[:decl].respond_to? :map
d[:block] = d[:decl].map { |v| v.strip }.join("\n")
else
d[:block] = d[:decl]
end
d[:comments] = d[:rawComments].strip
end
# Match struct {} (and typedef thereof) or opaque struct typedef
def detect_struct(d)
if d[:body] =~ /\A(typedef)?\s*struct\s*(\w+)?\s*\{([^\}]+)\}\s*([^;]+)?/i
typedef, name1, fields, name2 = $1, $2, $3, $4
d[:type] = :struct
d[:name] = typedef.nil? ? name1 : name2;
d[:tdef] = typedef
d[:decl] = fields.strip.split(/\s*\;\s*/).map do |x|
x.strip.gsub(/\s+/, " ").gsub(/\(\s+/,"(")
end
elsif d[:body] =~ /\A(typedef)\s+struct\s+\w+\s+(\w+)/
d[:type] = :struct
d[:decl] = ""
d[:name] = $2
d[:tdef] = $1
end
end
# Process struct definition
def parse_struct(d)
if d[:decl].respond_to? :map
d[:block] = d[:decl].map { |v| v.strip }.join("\n")
else
d[:block] = d[:decl]
end
d[:comments] = d[:rawComments].strip
end
# Match other typedefs, checking explicitly for function pointers
# but otherwise just trying to extract a name as simply as possible.
def detect_typedef(d)
if d[:body] =~ /\Atypedef\s+([^;]+);/
d[:decl] = $1.strip
if d[:decl] =~ /\S+\s+\(\*([^\)]+)\)\(/
d[:type] = :fnptr
d[:name] = $1
else
d[:type] = :typedef
d[:name] = d[:decl].split(/\s+/).last
end
end
end
# Process typedef definition
def parse_typedef(d)
d[:comments] = d[:rawComments].strip
end
# Process function pointer typedef definition
def parse_fnptr(d)
d[:comments] = d[:rawComments].strip
end
# Match function prototypes or inline function declarations
def detect_function(d)
if d[:body] =~ /[;\{]/
d[:type] = :file
d[:decl] = ""
proto = d[:body].split(/[;\{]/, 2).first.strip
if proto[-1] == ?)
(proto.length - 1).downto(0) do |p|
tail = proto[p .. -1]
if tail.count(")") == tail.count("(")
if proto[0..p] =~ /(\w+)\(\z/
d[:name] = $1
d[:type] = :function
d[:decl] = proto
end
break
end
end
end
end
end
# Process function prototype and comments
def parse_function(d)
d[:args] = []
rval, argline = d[:decl].split(/\s*#{Regexp.quote(d[:name])}\(\s*/, 2)
# clean up rval if it is like "extern static int" or "GIT_EXTERN(int)"
while rval =~ /[A-Za-z0-9_]+\(([^\)]+)\)$/i
rval = $1
end
rval.gsub!(/extern|static/, '')
rval.strip!
d[:return] = { :type => rval }
# we removed the opening parenthesis, which this is expecting
argline = '(' + argline
# clean up argline
argline = argline.slice(1..-2) while argline[0] == ?( && argline[-1] == ?)
d[:argline] = argline.strip
d[:args] = []
left = 0
# parse argline
(0 .. argline.length).each do |i|
next unless argline[i] == ?, || argline.length == i
s = argline.slice(left .. i)
next unless s.count("(") == s.count(")")
s.chop! if argline[i] == ?,
s.strip!
if s =~ /\(\s*\*\s*(\w+)\s*\)\s*\(/
argname = $1
d[:args] << {
:name => argname,
:type => s.sub(/\s*#{Regexp.quote(argname)}\s*/, '').strip
}
elsif s =~ /\W(\w+)$/
argname = $1
d[:args] << {
:name => argname,
:type => s[0 ... - argname.length].strip,
}
else
# argline is probably something like "(void)"
end
left = i + 1
end
# parse comments
if d[:rawComments] =~ /\@(param|return)/i
d[:args].each do |arg|
param_comment = /\@param\s+#{Regexp.quote(arg[:name])}/.match(d[:rawComments])
if param_comment
after = param_comment.post_match
end_comment = after.index(/(?:@param|@return|\Z)/)
arg[:comment] = after[0 ... end_comment].strip.gsub(/\s+/, ' ')
end
end
return_comment = /\@return\s+/.match(d[:rawComments])
if return_comment
after = return_comment.post_match
d[:return][:comment] = after[0 ... after.index(/(?:@param|\Z)/)].strip.gsub(/\s+/, ' ')
end
else
# support for TomDoc params
end
# add in inline parameter comments
if d[:inlines] # array of [param line]/[comment] pairs
d[:inlines].each do |inl|
d[:args].find do |arg|
if inl[0] =~ /\b#{Regexp.quote(arg[:name])}$/
arg[:comment] += "\n#{inl[1]}"
end
end
end
end
# generate function signature
d[:sig] = d[:args].map { |a| a[:type].to_s }.join('::')
# pull off function description
if d[:rawComments] =~ /^\s*(public|internal|deprecated):/i
# support for TomDoc description
else
desc, comments = d[:rawComments].split("\n\n", 2)
d[:description] = desc.strip
d[:comments] = comments || ""
params_start = d[:comments].index(/\s?\@(?:param|return)/)
d[:comments] = d[:comments].slice(0, params_start) if params_start
end
end
# Match otherwise unrecognized commented blocks
def detect_catchall(d)
d[:type] = :file
d[:decl] = ""
end
# Process comment blocks that are only associated with the whole file.
def parse_file(d)
m = []
d[:brief] = m[1] if m = /@brief (.*?)$/.match(d[:rawComments])
d[:defgroup] = m[1] if m = /@defgroup (.*?)$/.match(d[:rawComments])
d[:ingroup] = m[1] if m = /@ingroup (.*?)$/.match(d[:rawComments])
comments = d[:rawComments].gsub(/^@.*$/, '').strip + "\n"
if d[:comments]
d[:comments] = d[:comments].strip + "\n\n" + comments
else
d[:comments] = comments
end
end
# Array of detectors to execute in order
DETECTORS = %w(define enum struct typedef function catchall)
# Given a commented chunk of file, try to parse it.
def parse_declaration_block(d)
# skip uncommented declarations
return unless d[:rawComments].length > 0
# remove inline comments in declaration
while comment = d[:body].index("/*") do
end_comment = d[:body].index("*/", comment)
d[:body].slice!(comment, end_comment - comment + 2)
end
# if there are multiple #ifdef'ed declarations, we'll just
# strip out the #if/#ifdef and use the first one
d[:body].sub!(/[^\n]+\n/, '') if d[:body] =~ /\A\#\s*if/
# try detectors until one assigns a :type to the declaration
# it's going to be one of:
# - :define -> #defines + convert a series of simple ones to :enum
# - :enum -> (typedef)? enum { ... };
# - :struct -> (typedef)? struct { ... };
# - :fnptr -> typedef x (*fn)(...);
# - :typedef -> typedef x y; (not enum, struct, fnptr)
# - :function -> rval something(like this);
# - :file -> everything else goes to "file" scope
DETECTORS.find { |p| method("detect_#{p}").call(d); d.has_key?(:type) }
# if we detected something, call a parser for that type of thing
method("parse_#{d[:type]}").call(d) if d[:type]
end
# Parse a chunk of text as a header file
def parse_text(filename, content)
# break into comments and non-comments with line numbers
content = "/** */" + content if content[0..2] != "/**"
recs = []
lineno = 1
openblock = false
content.split(/\/\*\*/).each do |chunk|
c, b = chunk.split(/[ \t]*\*\//, 2)
next unless c || b
lineno += c.scan("\n").length if c
# special handling for /**< ... */ inline comments or
# for /** ... */ inside an open block
if openblock || c[0] == ?<
c = c.sub(/^</, '').strip
so_far = recs[-1][:body]
last_line = so_far[ so_far.rindex("\n")+1 .. -1 ].strip.chomp(",").chomp(";")
if last_line.empty? && b =~ /^([^;]+)\;/ # apply to this line instead
last_line = $1.strip.chomp(",").chomp(";")
end
if !last_line.empty?
recs[-1][:inlines] ||= []
recs[-1][:inlines] << [ last_line, c ]
if b
recs[-1][:body] += b
lineno += b.scan("\n").length
openblock = false if b =~ /\}/
end
next
end
end
# make comment have a uniform " *" prefix if needed
if c !~ /\A[ \t]*\n/ && c =~ /^(\s*\*)/
c = $1 + c
end
# check for unterminated { brace (to handle inline comments later)
openblock = true if b =~ /\{[^\}]+\Z/
recs << {
:file => filename,
:line => lineno + (b.start_with?("\n") ? 1 : 0),
:body => b,
:rawComments => cleanup_comment(c),
}
lineno += b.scan("\n").length if b
end
# try parsers on each chunk of commented header
recs.each do |r|
r[:body].strip!
r[:rawComments].strip!
r[:lineto] = r[:line] + r[:body].scan("\n").length
parse_declaration_block(r)
end
recs
end
end
end
| true |
f16747934a29f6c3db203b5eb5cad5e9bd44f70a
|
Ruby
|
amirahaile/CenturyLink-Crime
|
/app/helpers/maps_helper.rb
|
UTF-8
| 359 | 2.53125 | 3 |
[] |
no_license
|
module MapsHelper
def format_link(event_type)
sanitized_str = event_type.downcase.delete(",").delete("-").gsub("/", " ")
words = sanitized_str.split(" ")
link = ""
words.each_with_index do |word, index|
if (index == (words.length - 1))
link += word
else
link += (word + "-")
end
end
link
end
end
| true |
09e82df7b86ce58dbfa71ac4f99346ee81e18ca5
|
Ruby
|
rootulp/exercism
|
/ruby/exercises/say/say.rb
|
UTF-8
| 1,896 | 3.984375 | 4 |
[
"MIT"
] |
permissive
|
# Say
class Say
UNITS = {
1 => 'thousand',
2 => 'million',
3 => 'billion'
}.freeze
TENS = {
90 => 'ninety',
80 => 'eighty',
70 => 'seventy',
60 => 'sixty',
50 => 'fifty',
40 => 'forty',
30 => 'thirty',
20 => 'twenty'
}.freeze
NUMS = {
19 => 'nineteen',
17 => 'seventeen',
16 => 'sixteen',
15 => 'fifteen',
14 => 'fourteen',
13 => 'thirteen',
12 => 'twelve',
11 => 'eleven',
10 => 'ten',
9 => 'nine',
8 => 'eight',
7 => 'seven',
6 => 'six',
5 => 'five',
4 => 'four',
3 => 'three',
2 => 'two',
1 => 'one'
}.freeze
ACCEPTED_RANGE = 0...1_000_000_000_000
attr_reader :number
def initialize(number)
raise ArgumentError unless ACCEPTED_RANGE.include?(number)
@number = number
end
def in_english
number_to_words(number)
end
private
def number_to_words(number)
return 'zero' if number.zero?
result = ''
chunkify(number).each_with_index do |chunk, index|
val = chunk_for(chunk)
units = UNITS[index]
result.prepend("#{val} #{units} ") if val
end
result.strip
end
def chunkify(number)
chunks = []
while number > 0
number, chunk = number.divmod(1000)
chunks << chunk
end
chunks
end
def chunk_for(number)
return NUMS[number] if number < 20
general_case(number)
end
def general_case(number)
hundreds_digit, leftover_digits = number.divmod(100)
tens_digit, ones_digit = leftover_digits.divmod(10)
hundreds = NUMS[hundreds_digit] || false
tens = TENS[tens_digit * 10] || false
ones = NUMS[ones_digit] || false
format(hundreds, tens, ones)
end
def format(hundreds, tens, ones)
result = ''
result += "#{hundreds} hundred " if hundreds
result += tens.to_s if tens
result += "-#{ones}" if ones
result.strip
end
end
| true |
511685d4b256f6f9e55e84cb2dd2d7f8b077a34b
|
Ruby
|
dapmas/Ruby_MarsRover
|
/spec/grid_spec.rb
|
UTF-8
| 1,061 | 3.109375 | 3 |
[] |
no_license
|
require File.expand_path('../../lib/grid', __FILE__)
describe Grid, "behaviour" do
let (:input) { "5 5\n1 2 N\nLMLMLMLMM 3 3 E MMRMMRMRRM" }
before :each do
@grid = Grid.new input
end
it "initializes_correctly" do
expect(@grid).not_to be_nil
#@grid.should_not be_nil
end
it "sets up the grid map" do
expect(@grid.cell_x).to eq(5)
expect(@grid.cell_y).to eq(5)
#@grid.cell_x.should eq(5)
#@grid.cell_y.should eq(5)
end
it "sets the rovers to their initial state" do
expect(@grid.rovers.count).to eq(2)
#@grid.rovers.count.should eq(2)
expect(@grid.rovers[0].rover).to eq(x: 1, y: 2, dir: 'N')
expect(@grid.rovers[1].rover).to eq(x: 3, y: 3, dir: 'E')
end
it "move the rovers according to the instruction" do
@grid.move_rovers
expect(@grid.rovers[0].rover).to eq(x: 1, y: 3, dir: 'N')
expect(@grid.rovers[1].rover).to eq(x: 5, y: 1, dir: 'E')
end
it "prints out the final position of the rover" do
@grid.move_rovers
expect(@grid.to_s).to eq("1 3 N\n5 1 E")
end
end
| true |
58c2a4d2460488afa3e6950f8d6f591d09f0d83a
|
Ruby
|
rewinfrey/RubyTTT
|
/spec/ttt/ai_medium_spec.rb
|
UTF-8
| 1,809 | 2.84375 | 3 |
[] |
no_license
|
require 'spec_helper'
module TTT
describe AIMedium do
let(:ai) { AIMedium.new(side: "o") }
let(:board) { ThreeByThree.new }
describe "#minimax" do
it "blocks a potential fork win" do
#situation: x to move
# o | | x
# -----------------
# | o | block
# -----------------
# | | x
board[] = ['o', ' ', 'x', ' ', 'o', ' ', ' ', ' ', 'x']
ai.move(board: board)
ai.minimax.should == 5
end
it "takes a winning move when one is immediately avaialable" do
#situation: o to move
# o | o | win
# ---------------
# x | x |
# ---------------
# | |
board[] = ['o', 'o', ' ', 'x', 'x', ' ', ' ', ' ', ' ']
ai.move(board: board)
ai.minimax.should == 2
end
it "blocks an opponnent's winning move when one is found" do
#situation: o to move
# x | x | block
# ---------------
# o | |
# ---------------
# o | |
board[] = ['x', 'x', ' ', 'o', ' ', ' ', 'o', ' ', ' ']
ai.move(board: board)
ai.minimax.should == 2
end
it "returns 0 when it's a draw" do
board[] = ['x', 'o', 'o', 'o', 'x', 'x', 'o', 'x', 'o']
ai.move(board: board).should == 0
end
end
describe "#set_max_ply" do
it "returns 3 when number of available moves > 15" do
ai.set_max_ply(16).should == 3
end
it "returns 5 when number of available moves > 5 && < 15" do
ai.set_max_ply(14).should == 5
end
it "returns 7 when the number of available moves < 5" do
ai.set_max_ply(3).should == 7
end
end
end
end
| true |
f8e3438572a2e85893e1b43c01b7ee1ddc9b8ed1
|
Ruby
|
mapcloud/mdTranslator
|
/lib/adiwg/mdtranslator/readers/mdJson/modules/module_timeInterval.rb
|
UTF-8
| 2,895 | 2.546875 | 3 |
[
"Unlicense"
] |
permissive
|
# unpack time interval
# Reader - ADIwg JSON to internal data structure
# History:
# Stan Smith 2016-10-14 original script
module ADIWG
module Mdtranslator
module Readers
module MdJson
module TimeInterval
def self.unpack(hTimeInt, responseObj)
# return nil object if input is empty
if hTimeInt.empty?
responseObj[:readerExecutionMessages] << 'Time Interval object is empty'
responseObj[:readerExecutionPass] = false
return nil
end
# instance classes needed in script
intMetadataClass = InternalMetadata.new
intTime = intMetadataClass.newTimeInterval
# time interval - interval (required)
if hTimeInt.has_key?('interval')
interval = hTimeInt['interval']
if interval != ''
if interval.is_a?(Integer) || interval.is_a?(Float)
intTime[:interval] = hTimeInt['interval']
else
responseObj[:readerExecutionMessages] << 'Time Interval attribute interval is not a number'
responseObj[:readerExecutionPass] = false
return nil
end
end
end
if intTime[:interval].nil? || intTime[:interval] == ''
responseObj[:readerExecutionMessages] << 'Time Interval attribute interval is missing'
responseObj[:readerExecutionPass] = false
return nil
end
# time interval - units (required) {enum}
if hTimeInt.has_key?('units')
units = hTimeInt['units']
unless units.nil?
if %w{year month day hour minute second}.one? {|word| word == units}
intTime[:units] = hTimeInt['units']
end
end
end
if intTime[:units].nil? || intTime[:units] == ''
responseObj[:readerExecutionMessages] << 'Time Interval attribute units is missing or invalid'
responseObj[:readerExecutionPass] = false
return nil
end
return intTime
end
end
end
end
end
end
| true |
5846a88b3518929fffd63096bb89f8c7deb2fdef
|
Ruby
|
aflatune/trackablaze-gem
|
/trackers/klout.rb
|
UTF-8
| 976 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
require 'klout'
module Trackablaze
class Klout < Tracker
def get_metrics(tracker_items)
@klout_client = Kloutbg.new("zxz2p64gv3caabbqmvzaub9p")
tracker_items.collect {|tracker_item| get_metrics_single(tracker_item)}
end
def get_metrics_single(tracker_item)
metrics = {}
if (tracker_item.params["username"].nil? || tracker_item.params["username"].empty?)
add_error(metrics, "No username supplied", "username")
return metrics
end
response = nil
begin
response = @klout_client.show(tracker_item.params["username"])
rescue
end
if (response.nil? || response['status'] == 404)
add_error(metrics, "Invalid username supplied", "username")
return metrics
end
s = response['users'][0]['score']
tracker_item.metrics.each do |metric|
metrics[metric] = s[metric]
end
metrics
end
end
end
| true |
ac8f8b5f63e17c0348e9a1e6e3a754d4e19e847d
|
Ruby
|
abdul10a10/research-worker-aws
|
/app/services/transaction_service.rb
|
UTF-8
| 3,151 | 2.515625 | 3 |
[] |
no_license
|
class TransactionService
def self.total_monthly_transaction
total_transaction = 0
indian_transactions = 0
uae_transactions = 0
other_country_transactions = 0
total_payment = 0
total_indian_payment = 0
total_uae_payment = 0
total_other_country_payment = 0
end_time = Time.now.utc
start_time = Time.now.beginning_of_month
monthly_transaction = Array.new
monthly_payment = Array.new
monthly_indian_payment = Array.new
monthly_uae_payment = Array.new
monthly_other_country_payment = Array.new
payment_array = Array.new
i=0
loop do
paid_studies = Study.where(created_at: start_time..end_time, is_paid: "1").order(id: :desc)
paid_amount = 0
transaction_count = 0
indian_payment = 0
uae_payment = 0
other_country_payment = 0
paid_studies.each do |study|
transaction = study.transactions.where(payment_type: "Study Payment").first
if transaction.present?
paid_amount += transaction.try(:amount)
transaction_count +=1
if study.user.country == "India"
indian_transactions += 1
indian_payment += transaction.try(:amount)
total_indian_payment += transaction.try(:amount)
elsif study.user.country == "United Arab Emirates" || study.user.country == "UAE"
uae_transactions += 1
uae_payment += transaction.try(:amount)
total_uae_payment += transaction.try(:amount)
else
other_country_transactions += 1
total_other_country_payment += transaction.try(:amount)
end
end
end
total_payment += paid_amount
monthly_payment.push(sprintf('%.2f', paid_amount))
monthly_indian_payment.push(sprintf('%.2f',indian_payment))
monthly_uae_payment.push(sprintf('%.2f',uae_payment))
monthly_other_country_payment.push(sprintf('%.2f',other_country_payment))
monthly_transaction.push(transaction_count)
total_transaction += transaction_count
end_time = start_time
start_time = start_time-1.month
i += 1
if i == 12
break
end
end
data = { total_transaction: total_transaction,
monthly_transaction: monthly_transaction.reverse,
indian_transactions: indian_transactions,
uae_transactions: uae_transactions,
other_country_transactions: other_country_transactions,
monthly_payment: monthly_payment.reverse,
monthly_uae_payment: monthly_uae_payment.reverse,
monthly_other_country_payment: monthly_other_country_payment.reverse,
monthly_indian_payment: monthly_indian_payment.reverse,
total_indian_payment: sprintf('%.2f',total_indian_payment),
total_uae_payment: sprintf('%.2f',total_uae_payment),
total_other_country_payment: sprintf('%.2f',total_other_country_payment),
total_payment: sprintf('%.2f', total_payment),
payment_array: payment_array.push(sprintf('%.2f',total_indian_payment),sprintf('%.2f',total_uae_payment),sprintf('%.2f',total_other_country_payment))
}
end
end
| true |
83823049147f54cd4012eff10c2587460d57249c
|
Ruby
|
jgmorse/greensub
|
/bin/restrict_items.rb
|
UTF-8
| 1,868 | 2.78125 | 3 |
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
# frozen_string_literal: true
require 'slop'
require_relative '../lib/product'
require_relative '../lib/subscriber'
require_relative '../lib/component'
begin
opts = Slop.parse strict: true do |opt|
opt.string '-p', '--product', 'product id'
opt.string '-i', '--id', 'external id of component (i.e. its id on the host service)'
opt.string '-s', '--sales_id', 'sales id of component (i.e. the id when selling access, e.g. ISBN)'
opt.string '-f', '--file', 'csv or tab delimeted file of components: $id, $sales_id'
opt.bool '-r', '--remove', 'Remove components from product'
opt.bool '-t', '--testing'
opt.bool '-d', '--delete', 'Delete component from host (unrestricts item)'
opt.bool '-h', '--help' do
puts opts
end
end
rescue Slop::Error => e
puts e
puts 'Try -h or --help'
exit
end
ENV['GREENSUB_TEST'] = opts[:testing] ? '1' : '0'
product = Product.new(opts[:product])
unless product.hosted?
puts "Product #{opts[:product]} does not have a host, quitting...."
exit!(0)
end
rows = []
if opts[:file] && (opts[:id] || opts[:sales_id])
puts "Either define one component with -e [-s], or multiple with -f"
puts opts
elsif opts[:file]
puts "got a file"
File.foreach(opts[:file]) { |l| rows.push l.chomp }
elsif opts[:id]
rows.push "#{opts[:id]},#{opts[:sales_id]}"
else
puts "No id defined, so can't restrict component"
end
rows.each do |r|
fields = r.split(/[,\s]+/) # handle both tabs and commas
id = fields[0].tr_s('"', '').tr_s("''", '').strip
sales_id = fields[1].tr_s('"', '').tr_s("''", '').strip
component = Component.new(id, sales_id, product)
begin
if opts[:remove]
product.remove(component)
elsif opts[:delete]
component.remove_from_host
else
product.add(component)
end
rescue StandardError => e
STDERR.puts e.message
end
end
| true |
c34dc4c8d0d9e114f4592b9993b27a6f79226b6d
|
Ruby
|
jaxxstorm/sensu-plugins-coinbase
|
/bin/check-coinbase-price.rb
|
UTF-8
| 2,252 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
#
require 'coinbase/exchange'
require 'sensu-plugin/check/cli'
require 'pp'
class CheckCoinbasePrice < Sensu::Plugin::Check::CLI
option :api_key,
short: '-k API_KEY',
long: '--api-key API_KEY',
description: 'gdax API key',
required: true
option :api_secret,
short: '-s API_SECRET',
long: '--api-secret API_SECRET',
description: 'gdax API secret',
required: true
option :api_pass,
short: '-p API_PASS',
long: '--api-pass API_PASS',
description: 'gdax API pass',
required: true
option :product,
short: '-P PRODUCT',
long: '--product PRODUCT',
description: 'gdax product',
default: 'BTC-GBP'
option :low_price,
short: '-l LOW_PRICE',
long: '--low-price LOW_PRICE',
description: 'The value we should alert on if the price drops below',
proc: proc(&:to_i),
required: true
option :high_price,
short: '-h HIGH_PRICE',
long: '--high-price HIGH_PRICE',
description: 'The value we should alert on if the price goes above',
proc: proc(&:to_i),
required: true
def run
rest_api = Coinbase::Exchange::Client.new(config[:api_key], config[:api_secret], config[:api_pass])
response = rest_api.last_trade(product_id: config[:product])
case config[:product]
when 'BTC-GBP'
currency = '£'
coin = 'bitcoin'
when 'BTC-USD'
currency = '$'
coin = 'bitcoin'
when 'BTC-EUR'
currency = '€'
coin = 'bitcoin'
when 'ETH-GBP'
currency = '£'
coin = 'ethereum'
when 'ETH-USD'
currency = '$'
coin = 'ethereum'
when 'ETH-EUR'
currency = '€'
coin = 'ethereum'
end
if response.bid > config[:low_price] && response.bid < config[:high_price]
ok "Current #{coin} price is #{currency}#{response.price.truncate(2).to_s('F')}"
else
critical "Current #{coin} price is #{currency}#{response.price.truncate(2).to_s('F')}"
end
end
end
| true |
3c010d6f4dbd3f162fb1992ee40617cf82c0631c
|
Ruby
|
DDuongNguyen/oo-cash-register-dumbo-web-051319
|
/app.rb
|
UTF-8
| 672 | 3.3125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'pry'
require 'rest-client'
require 'json'
#
# i tell this app a theme it gives me list of books
# terminal should ask to enter a name
puts "tell me a book theme"
# get in put from user
input = gets.chomp
url= "https://www.googleapis.com/books/v1/volumes?q=#{input}"
response = RestClient.get url
#
response_hash = JSON.parse(response.body)
books = response_hash['items']
# show title
books.each do |book_hash|
puts ''
puts 'Title'
puts book_hash['volumeInfo']['title']
# show author
puts ''
puts 'Author'
puts book_hash['volumeInfo']['authors']
# show description
puts ''
puts 'Description'
puts book_hash['volumeInfo']['description']
puts '🐈' * 20
end
| true |
b724e62754a064b3483f0cfdf0349bbfc86a932d
|
Ruby
|
mjamesv19/Assignment3
|
/accounts.rb
|
UTF-8
| 883 | 3.328125 | 3 |
[] |
no_license
|
# Create account
# add founds
# remove founds
# trasfer founds
# Time to reach goal
class Account
attr_accessor :name
attr_accessor :funds
attr_accessor :goal
attr_accessor :income_hash
attr_accessor :expense_hash
# variables
def initialize(name, funds)
# income_hash = {}
# expense_hash = {}
@name = name
@funds = funds.to_i
@goal = goal
@income_hash = {}
@expense_hash = {}
end
methods
#display accounts
def income_list(name, amount)
@income_hash << { name => amount}
end
def add_income(amount)
@funds+=amount.to_i
end
def deduct_expense(amount)
@funds-=amount.to_i
end
def to_s
name = @name
funds = @funds
goal = @goal
return "#{name} #{funds} #{goal}"
end
end
| true |
6c9448e397b104dd98dd0a8a3cecb338d40b086f
|
Ruby
|
DausdasKreuz/ironhack-week1-ruby
|
/day_4-single_responsibility/login_solution.rb
|
UTF-8
| 1,037 | 3.703125 | 4 |
[] |
no_license
|
User.new.login
Text.new.get_text
class User
def login
user_data = UserData.get_data
while !Autenticator.autenticate(username,password)
puts "Incorrect name or password"
user_data = UserData.get_data
end
end
end
class UserData
def self.get_data
puts "Please, insert your username"
username = gets.chomp
puts "Please, insert your password"
password = gets.chomp
user_data = {username: username, password: password}
end
end
class Autenticator
def self.autenticate(username, password)
if username == "dani" && password == "secret"
true
else
false
end
end
end
class Text
def get_text
puts "Tipe in some text"
text = gets.chomp
end
end
class Menu
def show_menu
end
end
class TextCounter
def self.count_words(text)
text.split(" ").length
end
def self.count_letters(text)
text.split("").length
end
end
class TextModifier
def self.text_reverser(text)
text.reverse
end
def self.text_upper(text)
text.upcase
end
def self.text_downer(text)
text.downcase
end
end
| true |
74f90a6ac1791ed8047173ffb7d116f69bf05189
|
Ruby
|
billma/bill_algorithms
|
/lib/dijkstra.rb
|
UTF-8
| 1,632 | 3.0625 | 3 |
[] |
no_license
|
class String
def is_correct_format?
return false unless
self[0] =~ /[a-zA-Z]/ and
self[1] =~ /[a-zA-Z]/ and
self[0] != self[1] and
self[2..(self.length-1)] =~ /[0-9]/
return true
end
end
class Dijkstra
attr_accessor :vertices, :edges
def initialize
@vertices = {}
@edges = {}
end
def set_graph arry
return false if arry.nil? || arry.empty?
arry.each {|a|
return false unless a.is_correct_format?
s1,s2,s3=a[0],a[1],a[0..1]
@vertices[s1]={'path'=> nil} if @vertices[s1].nil?
add_child s1, s2
@vertices[s2]={'path'=> nil} if @vertices[s2].nil?
add_child s2, s1
@edges[s3]=a[2..(a.length-1)].to_i
@edges[s3.reverse]=a[2..(a.length-1)].to_i
}
end
def shortest_path start, finish
return 0 if @vertices.empty? || @edges.empty?
v = Marshal.load( Marshal.dump(@vertices) )
e = Marshal.load( Marshal.dump(@edges) )
queue = [start]
v[start]['path'] = 0
until queue.empty?
cur_node = queue.shift
v[cur_node]['children'].each {|child|
child_path = v[child]['path']
parent_path = v[cur_node]['path']
edge = e["#{cur_node+child}"]
if child_path.nil? || parent_path + edge < child_path
v[child]['path'] = parent_path + edge
queue << child
end
}
end
return v[finish]['path']
end
private
def add_child parent, child
if @vertices[parent]['children'].nil?
@vertices[parent]['children'] = [child]
else
@vertices[parent]['children'] << child
end
end
end
| true |
f04ca39acce0ddc40f1fbd1061b41380b7cf8a19
|
Ruby
|
kristjan/code_eval
|
/fibonacci_series/fibonacci_series.rb
|
UTF-8
| 171 | 3.546875 | 4 |
[] |
no_license
|
#!/usr/bin/env ruby
def fibonacci(n)
a, b = [1, 1]
a, b = b, a + b while (n -= 1) > 0
a
end
File.readlines(ARGV[0]).each do |line|
puts fibonacci(line.to_i)
end
| true |
fd2e45ebe9d89676b8d300fa4e3b9c1e4058c4e9
|
Ruby
|
hunglethanh9/leetcode
|
/283. Move Zeroes/Move Zeroes.rb
|
UTF-8
| 266 | 3.296875 | 3 |
[] |
no_license
|
# @param {Integer[]} nums
# @return {Void} Do not return anything, modify nums in-place instead.
def move_zeroes(nums)
temp = 0
nums.each_with_index{|n,i| n == 0 ? temp += 1: nums[i-temp] = n}
(nums.size - temp).upto(nums.size-1){|i| nums[i] = 0}
end
| true |
4bd2555ea16672d8e3e3f76f18a84821972a7d0a
|
Ruby
|
dianamora/cli_project
|
/lib/cli.rb
|
UTF-8
| 2,824 | 3.265625 | 3 |
[
"MIT"
] |
permissive
|
#this is what communicates with the user, controller
require 'pry'
class Cli
def start
puts "
This is a galaxy of wondrous aliens, bizarre monsters, strange Droids,
powerful weapons, great heroes, and terrible villains. It is a
galaxy of fantastic worlds, magical devices, vast
fleets, awesome machi-nery, terrible
conflict, and unending hope. . .
. . . . . . . .
. .. . . . .
. . T h i s i s t h e g a l a x y o f . . . .
. . . . .
. . . . . .
S T A R W A R S
"
puts "Welcome Padawan"
puts "To view Star Wars character, enter 'characters'"
puts "To leave, enter 'exit'"
menu
end
def menu
input = gets.strip.downcase
if input == "characters"
Api.create_characters
character_list
menu2
elsif input == "exit"
goodbye
else
invalid_entry
menu
end
end
def menu2
puts "Would you like to see another character? y or n"
input = gets.strip.downcase
if input == "y"
character_list
menu2
elsif input == "n"
goodbye
else
invalid_entry
end
end
def character_list
Characters.all.each_with_index do |character, index|
puts "#{index + 1}. #{character.name}"
end
puts ""
puts ""
puts "which character would you like to learn about? Enter Name:"
input = gets.strip.downcase
character_selection(input)
end
def character_selection(character)
person = Characters.find_by_name(character)
input = character.to_i
if person == nil && !(1...10).include?(input)
invalid_entry
elsif person == nil && (1...10).include?(input)
person = Characters.all[input -1]
# binding.pry
end
person.update_character #ideally, would incorporate a 'check' to see if info is already there (if someone asks for Luke twice)
puts "Name: #{person.name}"
puts "Gender: #{person.gender}"
puts "Birth Year: #{person.birth_year}"
end
def goodbye
puts "May the force be with you"
end
def invalid_entry
puts "invalid entry, try again"
end
end
# input = gets.chomp
# index = input_to_index(input)
| true |
61017a06c7deca32a7db65986ca97e271886babe
|
Ruby
|
secretartist272/CLI_Dinosaur
|
/lib/cli_dinosaur/dinosaur.rb
|
UTF-8
| 786 | 3.53125 | 4 |
[
"MIT"
] |
permissive
|
require 'pry'
class CliDinosaur::Dinosaur
attr_accessor :name, :description
@@all = []
def initialize(attr_hash)
attr_hash.each do |key, value|
self.send("#{key.downcase}=", value) if self.respond_to?("#{key.downcase}=")
end
save
end
def save
@@all << self
end
def self.all
@@all
end
def self.find_by_name(name)
# search through all the dinos...
# if there is a dino whose name matches the incoming argument, return that instance of Dinosaur
# if there are no matches, return nil
# ideally, the search would be case-insensitive
@@all.find do |dinosaur|
dinosaur.name.downcase == name.downcase
end
end
end
| true |
342e7e9fbd256e82289c70444b89de9b35cfa9f8
|
Ruby
|
usman-tahir/rubyeuler
|
/factors.rb
|
UTF-8
| 155 | 3.4375 | 3 |
[] |
no_license
|
# find factors of an int
def factors(n)
fctrs = []
(1...n).each do |factor|
fctrs << factor if n % factor == 0
end
fctrs
end
p factors(120)
| true |
4a2ab8e6a649e0692abc3c931f1f8b5eae10a056
|
Ruby
|
amyanne/crud-with-validations-lab-online-web-sp-000
|
/app/models/song.rb
|
UTF-8
| 584 | 2.609375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Song < ApplicationRecord
validates :title, presence: true, uniqueness: true
validates :released, inclusion: {in: [true, false]}
validates :release_year, numericality: { only_integer: true, less_than_or_equal_to: Time.now.year}, length: {in: 1..4, message: "please enter a 4 (or less) digit year"}, if: :released?
validates :artist_name, presence: true #, format: { with: /\A[a-zA-Z\-]+\z/, message: "only allows letters" }
#validates :genre, format: { with: /\A[a-zA-Z\-\w]+\z/, message: "only allows letters" }
def released?
self.released
end
end
| true |
d42b35ee4e4b7f6b83cbe31ecf0914e4c9d6f2a2
|
Ruby
|
glenngillen/s3backup-manager
|
/bin/s3restore
|
UTF-8
| 2,483 | 2.734375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
require 'optparse'
begin
require 's3backup-manager'
rescue LoadError
require "#{File.dirname(__FILE__)}/../lib/s3backup-manager"
end
options = {}
optparse = OptionParser.new do|opts|
opts.banner = "Usage: s3restore.rb [options] backup_file destination"
options[:adapter] = "postgres"
opts.on('--adapter ADAPTER', 'Type of database to backup. To be used with "--type database"' ) do |a|
unless ["mysql","postgres"].include?(a)
puts 'Only "mysql" and "postgres" are valid values for --adapter'
exit(1)
end
options[:adapter] = a
end
opts.on('--bucket BUCKET', 'AmazonS3 bucket you wish to store the backup in' ) do |b|
options[:bucket] = b
end
opts.on('--timestamp TIMESTAMP', 'Timestamp of file/database you want to restore' ) do |t|
options[:timestamp] = t
end
options[:type] = "file"
opts.on('--type TYPE', String, 'Type of backup. Valid options are "file" and "database". Defaults to "file"' ) do |t|
unless ["file","database"].include?(t.downcase)
puts 'Only "file" and "database" are valid values for --type'
exit(1)
end
options[:type] = t.downcase
options[:type_provided] = true
end
opts.on('--username USER', 'User to connect to the database as' ) do |u|
options[:username] = u
end
opts.on('-h', '--help', 'Display this screen') do
puts opts
exit
end
opts.on('-l', '--list', 'List all available buckets, or backed up files/databases if provided with --type') do
options[:list] = true
end
end
optparse.parse!
if options[:list] && !options[:type_provided]
S3BackupManager::Bucket.find_all.each do |bucket|
puts bucket
end
exit
end
def setup_backup_adapter(options)
if options[:bucket]
eval("S3BackupManager::#{options[:type].capitalize}Backup").new(options)
else
puts "You need to specify a valid bucket for retrieval"
exit(1)
end
end
backup_adapter = setup_backup_adapter(options)
if options[:list] && options[:bucket]
backup_adapter.files.each do |file|
puts "#{file.key.sub(%r{^filesystem/},"")} (%0.2f KB)" % (file.size.to_f/1024)
end
exit
end
source = ARGV[0]
destination = ARGV[1]
puts "Restoring #{source}..."
if options[:type] == "database"
backup_adapter.restore(source, options[:timestamp])
else
if ARGV.size != 2
puts "Please specify the source and destination files"
exit(1)
end
backup_adapter.restore(source, options[:timestamp], destination)
end
| true |
e5aca0d835beef9137c476527b4c06aa979103b0
|
Ruby
|
zafinar/ruby-advanced-class-methods-lab-web-022018
|
/lib/song.rb
|
UTF-8
| 1,060 | 3.25 | 3 |
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
require 'pry'
class Song
attr_accessor :name, :artist_name
def initialize
end
@@all = []
def self.all
@@all
end
def save
self.class.all << self
end
def self.create
@@all << Song.new
@@all.last
end
def self.new_by_name(title)
song = Song.new
song.name = title
song
end
def self.create_by_name(title)
@@all << Song.new_by_name(title)
@@all.last
end
def self.find_by_name(title)
Song.all.find {|song| song.name == title}
end
def self.find_or_create_by_name(title)
!!Song.find_by_name(title)? Song.find_by_name(title) : Song.create_by_name(title)
end
def self.alphabetical
Song.all.sort_by{|song| song.name}
end
def self.new_from_filename(file)
file = file.split(".")
file[0] = file[0].split(" - ").flatten
song = Song.new
song.artist_name = file[0][0]
song.name = file[0][1]
song
end
def self.create_from_filename(file)
@@all << Song.new_from_filename(file)
@@all.last
end
def self.destroy_all
@@all = []
end
end
| true |
6a337c1772c1e81e0020ead8516414bf3f16a445
|
Ruby
|
marciopocebon/flipdotwars
|
/lib/movie.rb
|
UTF-8
| 498 | 3.265625 | 3 |
[] |
no_license
|
class Movie
LINES_PER_FRAME = 13 # Do not include the separator line in this number
attr_reader :frames
def initialize(path)
@frames = []
read_frames_from(path)
end
private
def read_frames_from(path)
File.readlines(path).map(&:chomp).each_slice(LINES_PER_FRAME + 1) do |lines|
frame = lines[1..LINES_PER_FRAME].map{ |line| line.ljust(67) }
repeat_count = lines[0].to_i
repeat_count.times do
@frames << frame
end
end
end
end
| true |
3c4c466d22df230c025e4e81bed2f7c7ec6269f0
|
Ruby
|
tdg5/adaptive_polling
|
/lib/adaptive_polling/governor.rb
|
UTF-8
| 1,427 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
require "redis"
module AdaptivePolling
class Governor
COEFFICIENT_SUFFIX = ":co".freeze
LOCK_SUFFIX = ":lock".freeze
BASE_NAMESPACE = "rb:ap:".freeze
attr_reader :correction_algorithm, :id, :redis_client
def initialize(id, correction_algorithm, opts = {})
@id = id
@correction_algorithm = correction_algorithm
@redis_client = opts[:redis_client] || build_default_redis_client
end
def calculate_interval_in_ms
interval = correction_algorithm.call(correction_coefficient).to_i
interval > 0 ? interval : 1
end
def correction_coefficient
redis_client.get(correction_coefficient_key).to_f
end
def correction_coefficient_key
namespace.concat(COEFFICIENT_SUFFIX)
end
def decrement_correction_coefficient
redis_client.decr(correction_coefficient_key)
end
def increment_correction_coefficient
redis_client.incr(correction_coefficient_key)
end
def lock_key
namespace.concat(LOCK_SUFFIX)
end
def namespace
BASE_NAMESPACE + id
end
def try_lock
raise ArgumentError, "block required" unless block_given?
ttl_ms = calculate_interval_in_ms
success = redis_client.set(lock_key, true, :nx => true, :px => ttl_ms)
return false if !success
yield(self)
true
end
private
def build_default_redis_client
Redis.new
end
end
end
| true |
f5869ad7e084ef21a1b77f101fb9c09ca8ebda9e
|
Ruby
|
vilelajonas/launch_school
|
/exercises/ruby_basics/methods/3.rb
|
UTF-8
| 287 | 4.5625 | 5 |
[] |
no_license
|
# Using the following code, write a method called car that takes two arguments
# and prints a string containing the values of both arguments.
# car('Toyota', 'Corolla')
# Expected output:
# Toyota Corolla
def car(brand, model)
brand + ' ' + model
end
puts car('Toyota', 'Corolla')
| true |
696d0e5c728854cbbe8e144a6dd37eada400e317
|
Ruby
|
nyx-a/stim
|
/src/job.rb
|
UTF-8
| 2,862 | 2.96875 | 3 |
[
"MIT"
] |
permissive
|
require_relative 'b.dhms.rb'
require_relative 'command.rb'
require_relative 'history.rb'
require_relative 'pendulum.rb'
class Job
@@mtx = { } # { ? => Mutex }
def self.dispense_mutex token
if token.nil?
nil
else
token = token.to_s
@@mtx.fetch(token){ @@mtx[token] = Mutex.new }
end
end
def self.capture= o
@@capture = o
end
def self.log= o
@@log = o
end
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
attr_reader :name # Name
attr_reader :interval # Numeric
attr_reader :mutex # Mutex
attr_reader :command # Command
def name= *o
@name = Name.new(*o)
end
def interval= o
@interval = case o
when nil then nil
when String then B.dhms2sec o
when Numeric then o
else
raise TypeError, "#{o}(#{o.class})"
end
end
def mutex= token
@mutex = self.class.dispense_mutex token
end
def initialize(
name:,
interval: nil,
mutex: nil,
directory: nil,
command:,
option: nil
)
self.interval = interval
self.mutex = mutex
self.name = name
@command = Command.new(
directory: directory,
command: command,
option: option,
)
@history = History.new @@capture + @name + '.yaml'
@pendulum = Pendulum.new @interval, self
@pendulum.start
@@log.i "#{@name} started"
end
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def synchronize &b
@mutex ? @mutex.synchronize(&b) : b.call
end
def call
name = @name.to_s
r = synchronize do
@command.run @@capture, name do |r|
@@log.i "START #{name} (#{r.pid})"
end
end
@@log.send(
(r.status==0 ? :i : :e),
"END #{name} (#{r.pid}) #{B.sec2dhms r.time_spent}"
)
@history.push r
return nil
end
def execute
case
when @pendulum.dead?
self.call
@pendulum.reset
@@log.i "#{@name} executed only once"
when @pendulum.sleeping?
@pendulum.stop
@pendulum.start 0
@@log.i "#{@name} executed immediately and the cycle was reset"
else
@@log.i "#{@name} now #{@pendulum.state}"
end
end
def pause
if @pendulum.pause
@@log.i "#{@name} going to pause (#{remaining_time})"
else
@@log.i "#{@name} already pausing"
end
end
def resume
if @pendulum.start
@@log.i "#{@name} Resumed (#{remaining_time})"
else
@@log.i "#{@name} already starting"
end
end
def terminate
@pendulum.stop
@pendulum.join
@history.save
@@log.i "#{@name} terminated"
end
def state
@pendulum.state
end
def remaining_time
rt = @pendulum.remaining_time
if rt
Time.at(rt, in:'UTC').strftime("%k:%M:%S")
end
end
end
| true |
e8b02e6ec2095db446bbf2b5add069409d01d419
|
Ruby
|
kamaradclimber/Dotfiles
|
/gnothi_form.rb
|
UTF-8
| 2,967 | 2.8125 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
require 'net/http'
require 'uri'
require 'json'
require 'highline'
def get_tokens(login, password)
uri = URI.parse('https://api.gnothiai.com/auth/login')
request = Net::HTTP::Post.new(uri)
request.body = URI.encode_www_form(username: login, password: password)
req_options = {
use_ssl: uri.scheme == 'https'
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
raise "Impossible to get a token. Code was #{response.code}. Body #{response.body}" unless response.code.to_i == 200
JSON.parse(response.body)
end
def get_fields(tokens)
uri = URI.parse('https://api.gnothiai.com/fields')
request = Net::HTTP::Get.new(uri)
req_options = {
use_ssl: uri.scheme == 'https'
}
request['Authorization'] = "Bearer #{tokens['access_token']}"
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
raise "Impossible to list fields from gnothi. Code was #{response.code}" unless response.code.to_i == 200
JSON.parse(response.body)
end
def ask_value(service)
cli = HighLine.new
case service['type']
when 'fivestar'
cli.ask("How would you rate your #{service['name']} ? (1-5) ", Integer) { |q| q.in = 1..5 }
when 'number'
cli.ask("What is your #{service['name']} ? ", Float)
when 'check'
cli.agree("Is '#{service['name']}' true? (y/n)") ? 1 : 0
else
raise "Unknown field type #{service['type']}, need to be implemented"
end
end
def send_value(service, value, tokens)
uri = URI.parse("https://api.gnothiai.com/field-entries/#{service['id']}")
request = Net::HTTP::Post.new(uri)
request['Content-Type'] = "application/json"
request['Authorization'] = "Bearer #{tokens['access_token']}"
request.body = {value: value}.to_json
req_options = {
use_ssl: uri.scheme == 'https'
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
raise "Impossible to send value for #{service['name']}. Code was #{response.code}. Body #{response.body}" unless response.code.to_i == 200
JSON.parse(response.body)
end
raise 'You must set GNOTHIAI_USERNAME' unless ENV.key?('GNOTHIAI_USERNAME')
raise 'You must set GNOTHIAI_PASSWORD' unless ENV.key?('GNOTHIAI_PASSWORD')
tokens = get_tokens(ENV['GNOTHIAI_USERNAME'], ENV['GNOTHIAI_PASSWORD'])
raise 'Failed to get access_token from gnothi' unless tokens.key?('access_token')
fields = get_fields(tokens)
puts "Found #{fields.size} fields for the following services:"
fields.values.group_by { |f| f['service'] }.each do |service_name, service_fields|
puts "- #{service_name || '<none>'}: #{service_fields.size} fields (#{service_fields.sample(3).map { |s| s['name'] }})"
end
puts ''
puts "Will now ask to fill all those fields"
puts ''
fields.values.select { |f| f['service'].nil? }.each do |service|
value = ask_value(service)
send_value(service, value, tokens)
end
| true |
183ca8d20ac2a53a20b3a8e943a6cb1bac116022
|
Ruby
|
kgoettling/intro_to_programming
|
/ch7_hashes/ex3_loop_keys_values.rb
|
UTF-8
| 601 | 4.5625 | 5 |
[] |
no_license
|
# Write a program that loops through a hash and prints all the keys.
# Then write a program that prints all the values. Finally, write
# a program that prints both.
my_hash = {key1: "value1",
key2: "value2",
key3: "value3",
key4: "value4",
key5: "value5",
key6: "value6"}
# Print all keys
puts 'Here comes the keys: '
my_hash.each {|key, value| puts key}
# Print all values
puts 'Here comes the values: '
my_hash.each {|key, value| puts value}
# Print both
puts 'Here comes both: '
my_hash.each {|key, value| puts key.to_s + ": " + value}
| true |
d564158e3e1eec7d126092c97e4acc2583a4a2d5
|
Ruby
|
ashtony42/midi_printer
|
/helpers/methods.rb
|
UTF-8
| 759 | 2.671875 | 3 |
[] |
no_license
|
def show_midi_info sequence
print "the file has #{sequence.tracks.count} tracks\n"
sequence.tracks.count.times do |track_index|
sequence.tracks[track_index].events.each do |event|
if event.respond_to? "program"
print "track #{track_index} has instrument of #{GM_PATCH_NAMES[event.program]}\n"
end
end
end
end
def get_midi_note_coordinates sequence
note_hash = {}
sequence.tracks.each do |track|
track.events.each do |event|
if event.class == MIDI::NoteOn
note_letter = MIDI::Utils.note_to_s(event.note)
note_hash[note_letter] ||= []
note_hash[note_letter].push((event.time_from_start)..(event.off.time_from_start))
end
end
end
return note_hash
end
| true |
642bd0705bf015939fd16b5f3d2eae4e7f9d4836
|
Ruby
|
pbinkley/If_I_Should_Die_Tonight
|
/newspapers/lib/tasks/ingest.rake
|
UTF-8
| 2,242 | 2.5625 | 3 |
[] |
no_license
|
INGEST_REPORTS_LOCATION = Rails.root.join('tmp/ingest_reports')
INDEX_OFFSET = 1
# adapted from https://github.com/ualbertalib/jupiter/blob/integration_postmigration/lib/tasks/batch_ingest.rake
namespace :ingest do
desc 'Ingest newspapers.com item list from csv file'
task :ingest_csv, [:csv_path] => :environment do |_t, args|
require 'csv'
require 'fileutils'
require 'byebug'
log 'START: Batch ingest started...'
csv_path = args.csv_path
if csv_path.blank?
log 'ERROR: CSV path must be present. Please specify a valid csv_path as an argument'
exit 1
end
full_csv_path = File.expand_path(csv_path)
csv_directory = File.dirname(full_csv_path)
if File.exist?(full_csv_path)
successful_ingested_items = []
CSV.foreach(full_csv_path,
headers: true,
header_converters: :symbol,
converters: :all).with_index(INDEX_OFFSET) do |item_data, index|
item = item_ingest(item_data, index, csv_directory)
successful_ingested_items << item
end
log 'FINISH: Batch ingest completed!'
else
log "ERROR: Could not open file at `#{full_csv_path}`. Does the csv file exist at this location?"
exit 1
end
end
end
def log(message)
puts "[#{Time.current.strftime('%F %T')}] #{message}"
end
def item_ingest(item_data, index, csv_directory)
log "ITEM #{index}: Starting ingest of an item..."
item = Item.new.tap do |i|
i.filename = item_data[:filename]
i.publication = item_data[:publication]
i.location = item_data[:location]
i.date = item_data[:date]
i.page = item_data[:page]
i.url = item_data[:url]
i.category_id = 1
i.save!
end
log "ITEM #{index}: Starting ingest of file for item..."
item.thumbnail.attach(
io: File.open("#{csv_directory}/../thumbnails/#{item_data[:filename]}.jpg"),
filename: 'thumbnail.jpg'
)
sleep(1)
item
rescue StandardError => e
log 'ERROR: Ingest of item failed! The following error occured:'
log "EXCEPTION: #{e.message}"
log 'WARNING: Please be careful with rerunning batch ingest! Duplication of items may happen '\
'if previous items were successfully deposited.'
exit 1
end
| true |
dc7219fdeb8b263496eb716be56574a35cfff405
|
Ruby
|
alekscp/exercism
|
/ruby/bob/bob.rb
|
UTF-8
| 556 | 3.109375 | 3 |
[] |
no_license
|
module Bob
ANSWERS = {
'question' => 'Sure.',
'yell' => 'Whoa, chill out!',
'without_saying_anything' => 'Fine. Be that way!',
'anything_else' => 'Whatever.'
}
def self.hey(remark)
if remark.scan(/[A-Z]/).count > remark.scan(/[a-z]/).count
ANSWERS['yell']
elsif remark.scan(/[^\n\s\t]/).last =~ /[\.\!\w]$/
ANSWERS['anything_else']
elsif remark.scan(/[^\n\s\t]/).last =~ /\?$/
ANSWERS['question']
else
ANSWERS['without_saying_anything']
end
end
end
module BookKeeping; VERSION = 1; end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.