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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
5a81184f961e974af2d690d2ebb12d5dd76c5560 | Ruby | mondrian/tubform-rsig | /vendor/plugins/i18n_localize_core/lib/i18n_localize_core/string_extensions.rb | UTF-8 | 580 | 2.703125 | 3 | [
"MIT"
] | permissive | class String
def as_delocalized_number
result = self.clone
result.gsub!(I18n.thousand_separator, '_') if I18n.thousand_separator
result.gsub!(I18n.decimal_separator, '.') if I18n.decimal_separator
result
end
alias original_to_f to_f
def to_f(localize = nil)
localize = I18n.localize_core if localize.nil?
(localize ? as_delocalized_number : self).original_to_f
end
alias original_to_i to_i
def to_i(localize = nil)
localize = I18n.localize_core if localize.nil?
(localize ? as_delocalized_number : self).original_to_i
end
end
| true |
f3513748a8ef6712385a3695a95704e2f2b21ddb | Ruby | BearerPipelineTest/girl_friday | /test/test_error_handler.rb | UTF-8 | 1,340 | 2.703125 | 3 | [
"MIT"
] | permissive | require 'helper'
class TestErrorHandler < MiniTest::Unit::TestCase
Stderr = GirlFriday::ErrorHandler::Stderr
Airbrake = GirlFriday::ErrorHandler::Airbrake
class FakeStderr
include Faker
def flush
"WOOSH!"
end
alias_method :puts, :count
alias_method :write, :count
end
class FakeAirbrake
include Faker
alias_method :notify_or_ignore, :count
end
class FakeError
def backtrace
%w(
We're no strangers to love
You know the rules and so do I
A full commitment's what I'm thinking of
You wouldn't get this from any other guy
I just wanna tell you how I'm feeling
Gotta make you understand
)
end
end
def handler
GirlFriday::ErrorHandler
end
def test_default
assert_equal [Stderr], handler.default
Object.const_set("Airbrake","super cool error catcher")
assert_equal [Stderr,Airbrake], handler.default
Object.send(:remove_const,:Airbrake)
end
def test_stderr
$stderr = FakeStderr.new
Stderr.new.handle(FakeError.new)
assert_equal 2, $stderr.number_of_calls
end
def test_airbrake
airbrake = FakeAirbrake.new
Object.const_set("Airbrake", airbrake)
Airbrake.new.handle(FakeError.new)
assert_equal 1, airbrake.number_of_calls
Object.send(:remove_const,:Airbrake)
end
end
| true |
7e8ba671a8736b8992e6d83a89887d88a144e476 | Ruby | sullycodes/parks | /lib/parks.rb | UTF-8 | 467 | 3.234375 | 3 | [
"MIT"
] | permissive | require_relative '../config/environment'
class Park
attr_accessor :name, :url, :address, :phone, :overview, :activities
@@all = []
def initialize(name = nil, url = nil)
@name = name
@url = url
@@all << self
end
def self.all
@@all
end
def add_park_attributes(park_url)
hash = Scraper.scrape_park_page(park_url)
@overview = hash[:overview]
@activities = hash[:activities]
@address = hash[:address]
@phone = hash[:phone]
end
end #Park | true |
8f8b0a3e5569fdb00a91edd5833e5d2b6cb3436c | Ruby | runcoderun/cogent_times | /spec/controllers/crud_controller_spec.rb | UTF-8 | 3,977 | 2.515625 | 3 | [] | no_license | require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
def model(clazz, attributes=nil, &attribute_block)
define_method(:model_class) {return clazz}
attr_accessor :valid_model_attributes
attr_accessor :valid_parameters
define_method(:initialize_attributes) do
object_attributes = attributes || attribute_block.call
self.valid_model_attributes = as_attributes(object_attributes)
self.valid_parameters = as_parameters(object_attributes)
end
end
class Class
def is_relationship?(name)
return !!self.relationships[name]
end
def is_date_property?(name)
self.properties.each do |property|
if property.name == name
return property.type == Date
end
end
return false
end
def related_class(relationship_name)
return self.relationships[relationship_name].parent_model_name.constantize
end
end
shared_examples_for 'any crud controller' do
integrate_views
before(:each) do
initialize_attributes
end
def as_attributes(object_attributes)
parameters = object_attributes.clone
parameters.each do |key, value|
if model_class.is_relationship?(key)
parameters[:"#{key}_id"] = value.id
parameters.delete(key)
end
end
return parameters
end
def as_parameters(attributes)
parameters = attributes.clone
parameters.each do |key, value|
if model_class.is_date_property?(key)
parameters["#{key}(1i)"] = value.year.to_s
parameters["#{key}(2i)"] = value.month.to_s
parameters["#{key}(3i)"] = value.day.to_s
parameters.delete(key)
end
if model_class.is_relationship?(key)
parameters[key] = value.id
end
end
return parameters
end
def collection_sym
model_class.to_s.pluralize.underscore.to_sym
end
def instance_sym
model_class.to_s.underscore.to_sym
end
def clear_instances
instances.destroy! # rely on database constraints
end
def leave_one_instance
clear_instances
make_new_instance
end
def instances
model_class.all
end
def instance
model_class.first
end
def make_new_instance
model_class.make
end
def cache_new_instance
@instance = make_new_instance
end
def cached_instance
@instance || cache_new_instance
end
def should_render(template)
response.should render_template(template)
end
def collection_var
assigns[collection_sym]
end
def instance_var
assigns[instance_sym]
end
def check_index_displayed
response.should redirect_to("http://test.host/#{collection_sym.to_s}")
end
def check_instance_count(count)
instances.should have(count).records
end
def check_instance_attributes
instance.attributes.should == valid_model_attributes.merge(:id => instance.id)
end
it "should retrieve all instances for index" do
leave_one_instance
get :index
should_render("index")
collection_var.should have(1).record
end
it "should retrieve one instance for show" do
leave_one_instance
get :show, :id => instance.id
should_render("show")
instance_var.should == instance
end
it "should destroy one instance" do
leave_one_instance
delete :destroy, :id => instance.id
check_index_displayed
check_instance_count(0)
end
it "should display new instance" do
cache_new_instance
stub(model_class).new {cached_instance}
put :new
should_render("new")
instance_var.should == cached_instance
end
it "should create new instance" do
clear_instances
post :create, instance_sym => valid_parameters
check_index_displayed
check_instance_count(1)
check_instance_attributes
end
it "should update instance" do
leave_one_instance
put :update, :id => instance.id, instance_sym => valid_parameters
check_index_displayed
check_instance_count(1)
check_instance_attributes
end
end | true |
cddf2d3ce7bd2ebd5918f8eca9b0a7f0ae485e63 | Ruby | clondono/FriendSplitter | /test/models/event_test.rb | UTF-8 | 10,174 | 2.96875 | 3 | [] | no_license | # Author: Lucy
require 'test_helper'
class EventTest < ActiveSupport::TestCase
# Event should not save if there is no amount field
test "Validate amount presence" do
event = Event.new
event.title = "Title"
event.description = "Description"
assert !event.save, "Event should not save if there is no amount field"
end
# Event should not save if there is no title field
test "Validate title presence" do
event = Event.new
event.description = "Description"
event.amount = 3.00
assert !event.save, "Event should not save if there is no title field"
end
# Event should not save if there is no description field
test "Validate description presence" do
event = Event.new
event.title = "title"
event.amount = 4
assert !event.save, "Event should not save if there is no description field"
end
# isPending should return true for event with pending column true
test "isPending returns true for pending event" do
event = events(:one)
assert event.isPending?, "isPending should return true for event with pending column true"
end
# isPending should return false for event with pending column false
test "isPending returns false for nonpending event" do
event = events(:two)
assert !event.isPending?, "isPending should return false for event with pending column false"
end
# confirmed? should return true if all the event's contributions
# were confirmed ie nonpending
test "confirmed? returns true if all contributions nonpending" do
event = events(:four)
assert event.confirmed?, "confirmed? should return true if all contributions connected to event are nonpending"
end
# confirmed? should return false if at least one of the event's contributions
# are not confirmed ie pending
test "confirmed? returns false if not all contributions nonpending" do
event = events(:five)
assert !event.confirmed?, "confirmed? should return false if some contribution connected to the event is pending"
end
# confirm! should set the event's pending column to false
test "confirm! sets pending to false" do
event = events(:five)
event.confirm!
assert !event.pending, "confirm! should set the event's pending column to false"
end
# validContributions? should return true if the amount and paid contributions
# in params hash add up to the total amount of an event cost when dealing with
# integers only
test "validContributions? true if contributions sum to event amount integers only" do
params = {"0"=>{"email"=>"one@one.com", "amount"=>"3", "paid"=>"2"}, "1"=>{"email"=>"two@two.com", "amount"=>"1", "paid"=>"2"}}
assert Event.validContributions?(params, 4), "validContributions? should be true if contributions sum to event amount"
end
# validContributions? should return true if the amount and paid contributions
# in params hash add up to the total amount of an event cost when dealing with
# decimal numbers
test "validContributions? true if contributions sum to event amount integer decimal" do
params = {"0"=>{"email"=>"one@one.com", "amount"=>"1.5", "paid"=>"2"}, "1"=>{"email"=>"two@two.com", "amount"=>"0.5", "paid"=>"0"}}
assert Event.validContributions?(params, 2), "validContributions? should be true if contributions sum to event amount"
end
# validContributions? should return true if the amount and paid contributions
# in params hash add up to the total amount of an event cost
test "validContributions? true if contributions sum to event amount 2" do
params = {"0"=>{"email"=>"lucy@lucy.com", "amount"=>"1.5", "paid"=>"2"}, "1"=>{"email"=>"cake@cake.com", "amount"=>"0.5", "paid"=>"0"}, "2" => {"email" => "pie@pie.com", "amount" => "2", "paid"=> "2"} }
assert Event.validContributions?(params, 4), "three users involved: validContributions? should be true if contributions sum to event amount"
end
# validContributions? should return false if the amounts of contributions in
# hash do not add up to total amount of event cost
test "validContributions? false if amount does not sum to event total" do
params = {"0"=>{"email"=>"lucy@lucy.com", "amount"=>"1.5", "paid"=>"2"}, "1"=>{"email"=>"cake@cake.com", "amount"=>"0.5", "paid"=>"0"}, "2" => {"email" => "pie@pie.com", "amount" => "2", "paid"=> "2"} }
assert !Event.validContributions?(params, 3), "three users involved: validContributions? should be false if amount does not sum to event total"
end
# validContributions? should return false if the "paid" values of
# contributions in hash do not add up to total amount of event cost
test "validContributions? false if paid does not sum to event total" do
params = {"0"=>{"email"=>"lucy@lucy.com", "amount"=>"1.5", "paid"=>"1"}, "1"=>{"email"=>"cake@cake.com", "amount"=>"0.5", "paid"=>"0"}, "2" => {"email" => "pie@pie.com", "amount" => "2", "paid"=> "2"} }
assert !Event.validContributions?(params, 4), "three users involved: validContributions? should be false if paid values do not sum to event total"
end
# createContributions should create Contributions objects
# given a set of contribution attributes
test "createContributions creates Contribution objects" do
params = {"0"=>{"email"=>"one@one.com", "amount"=>"1.5", "paid"=>"2"}, "1"=>{"email"=>"two@two.com", "amount"=>"0.5", "paid"=>"0"}}
event = events(:six)
contribution1 = Contribution.find_by(event_id: 6, user_id: 1)
contribution2 = Contribution.find_by(event_id: 6, user_id: 2)
assert_nil contribution1, "contribution from user 1 and event 6 doesn't exist yet"
assert_nil contribution2, "contribution from user 2 and event 6 doesn't exist yet"
event.createContributions(params)
contribution1 = Contribution.find_by(event_id: 6, user_id: 1)
contribution2 = Contribution.find_by(event_id: 6, user_id: 2)
assert_not_nil contribution1, "contribution from user 1 and event 6 shoud exist after createContributions"
assert_not_nil contribution2, "contribution from user 2 and event 6 shoud exist after createContributions"
end
# createContributions should create Contributions objects with the proper values,
# given a set of contribution attributes
test "createContributions creates Contribution objects with correct values" do
params = {"0"=>{"email"=>"one@one.com", "amount"=>"1.5", "paid"=>"2"}, "1"=>{"email"=>"two@two.com", "amount"=>"0.5", "paid"=>"0"}}
event = events(:six)
event.createContributions(params)
contribution1 = Contribution.find_by(event_id: 6, user_id: 1)
contribution2 = Contribution.find_by(event_id: 6, user_id: 2)
assert_not_nil contribution1, "contribution from user 1 and event 6 shoud exist after createContributions"
assert_not_nil contribution2, "contribution from user 2 and event 6 shoud exist after createContributions"
assert contribution1.amount==1.50, "contribution from user 1 amount is $1.50"
assert contribution1.paid==2, "contribution from user 1 paid is $2"
assert contribution2.amount==0.50, "contribution from user 1 amount is $0.50"
assert contribution2.paid==0, "contribution from user 1 paid is $0"
end
# Check that createDebts creates Debts such that each indebted User's debts
# are increased by their deficit from the event...and conversely, that each
# person who paid over their share is owed money that sum up to the surplus
test "createDebts create satisfactory debts for two participants" do
event = events(:four)
user5 = users(:five)
user6 = users(:six)
event.createDebts
d1 = Debt.find_by(owner_id: 6, indebted_id: 5)
assert_not_nil d1, "debt should not exist between users 5 and 6"
assert d1.amount == 2, "user 6 should owe money to user 5 after createDebts is called on event 4"
end
# Check that createDebts creates Debts such that each indebted User's debts
# are increased by their deficit from the event...and conversely, that each
# person who paid over their share is owed money that sum up to the surplus
test "createDebts create satisfactory debts for three participants" do
event = events(:five)
user4 = users(:four)
user5 = users(:five)
user6 = users(:six)
event.createDebts
d1 = Debt.find_by(owner_id: 4, indebted_id: 5)
d2 = Debt.find_by(owner_id: 4, indebted_id: 6)
assert_not_nil d1, "debt should now exist between users 4 and 5"
assert_not_nil d2, "debt should now exist between users 4 and 6"
assert (d1.amount+d2.amount) == 2, "total money owed by 4 should equal their deficit in the event, which is 3"
assert d1.amount == 1, "user 5 is owed $1 after overpaying for this event"
assert d2.amount == 1, "user 6 is owed $1 after overpaying for this event"
end
# Check that createDebts creates no debts when everyone pays their share
test "createDebts should not create debts when all users pay share" do
event = events(:six)
user4 = users(:four)
user5 = users(:five)
user6 = users(:six)
event.createDebts
d1 = Debt.find_by(owner_id: 4, indebted_id: 5)
d2 = Debt.find_by(owner_id: 4, indebted_id: 6)
assert_nil d1, "debt should not exist between users 4 and 5"
assert_nil d2, "debt should not exist between users 4 and 6"
d1 = Debt.find_by(owner_id: 5, indebted_id: 4)
d2 = Debt.find_by(owner_id: 5, indebted_id: 6)
assert_nil d1, "debt should not exist between users 5 and 4"
assert_nil d2, "debt should not exist between users 5 and 6"
d1 = Debt.find_by(owner_id: 6, indebted_id: 4)
d2 = Debt.find_by(owner_id: 6, indebted_id: 5)
assert_nil d1, "debt should not exist between users 6 and 4"
assert_nil d2, "debt should not exist between users 6 and 5"
end
end
| true |
8eb82b474cd66a94bf05a296b1e2d8a06a56edbd | Ruby | Jablooo/Restaurant | /restaurant2.rb | UTF-8 | 5,117 | 4 | 4 | [] | no_license | class Pasta
# - How do we describe it
def initialize(name, ingredients, price)
@name = name
@ingredients = ingredients
@price = price
end
attr_accessor :name, :ingredients, :price
# - What does it do
def show_pasta_ingredients
@name.each do |pastaType|
puts "- #{pastaType.ingredients}"
end
end
end
spagBol = Pasta.new("Spaghetti Bolognese", ["tomato", "beef", "parmesan"], 10)
carbonara = Pasta.new("Spaghetti Carbonara", ["cream", "egg", "bacon", "parmesan"], 12)
napolitana = Pasta.new("Ravioli Napolitana", ["tomato", "parmesan"], 8)
pesto = Pasta.new("Penne Pesto", ["pesto", "brocolli"], 7)
class Pizza
# - How do we describe it
def initialize(name, ingredients, price)
@name = name
@ingredients = ingredients
@price = price
end
attr_accessor :name, :ingredients, :price
# - What does it do
def show_pizza_ingredients
@name.each do |pizzaType|
puts "- #{pizzaType.ingredients}"
end
end
end
fourCheese = Pizza.new("Four Cheeses", ["tomato", "gorgonzola", "mozzarella", "cheddar", "goats cheese"], 12)
margarita = Pizza.new("Margarita", ["tomato", "mozzarella"], 8)
diavola = Pizza.new("Diavola", ["salami", "chilli"], 7)
class Menu
# - How do we describe it
def initialize(name, items)
@name = name
@items = items
end
def show_items
@items.each do |x|
puts "#{x.name}- #{x.ingredients}............$#{x.price}"
end
end
attr_accessor :name, :item
end
pastaMenu = Menu.new("Pastas", [spagBol, carbonara, napolitana, pesto])
pizzaMenu = Menu.new("Pizzas", [fourCheese, margarita, diavola])
class Order
def initialize(items)
@items = items
end
def order_push
newOrder = [
]
while runner = 2
puts "What would you like to order?"
gap
puts " [1] Pasta"
puts " [2] Pizza"
puts " [3] Check Order"
puts " [4] Place Order"
gap
answerOrder = gets.chomp.to_i
if answerOrder == 1
puts "[1] Spaghetti Bolognese"
puts "[2] Spaghetti Carbonara"
puts "[3] Ravioli Napolitana"
puts "[4] Penne Pesto"
puts "[5] Back to order menu"
selection = gets.chomp.to_i
if selection == 1
newOrder.push("Spaghetti Bolognese")
puts "Spaghetti Bolognese has been added to your order"
gap
runner = 2
elsif selection == 2
newOrder.push("Spaghetti Carbonara")
puts "Spaghetti Carbonara has been added to your order"
gap
runner = 2
elsif selection == 3
newOrder.push("Ravioli Napolitana")
puts "Ravioli Napolitana has been added to your order"
gap
runner = 2
elsif selection == 4
newOrder.push("Penne Pesto")
puts "Penne Pesto has been added to your order"
gap
runner = 2
elsif selection == 5
runner = 3
else
valid_option(gap)
runner = 1
end
elsif answerOrder == 2
puts "[1] Four Cheeses"
puts "[2] Margarita"
puts "[3] Diavola"
puts "[4] Back to order menu"
selection = gets.chomp.to_i
if selection == 1
newOrder.push("Four Cheeses")
puts "Four Cheeses has been added to your order"
gap
runner = 2
elsif selection == 2
newOrder.push("Margarita")
puts "Margarita has been added to your order"
gap
runner = 2
elsif selection == 3
newOrder.push("Diavola")
puts "Diavola has been added to your order"
gap
runner = 2
elsif selection == 4
runner = 3
else
valid_option(gap)
runner = 1
end
elsif answerOrder == 3
puts newOrder
runner = 1
elsif answerOrder == 4
puts "Your order has been placed"
sleep(2)
abort
else
valid_option(gap)
end
end
end
def total_cost
cost = 0
@items.each do |order|
cost = cost + items.price
end
end
attr_accessor :items
end
def gap
puts
puts
end
def valid_option(gap)
gap
puts "please select valid option"
end
runner = 0
while runner == 0
gap
puts " Welcome to Jominoes online ordering"
puts " What would you like today"
gap
puts " [1] Pastas"
puts " [2] Pizzas"
puts " [3] Order"
puts " [4] Exit"
gap
menuAnswer = gets.chomp.to_i
if menuAnswer == 1
gap
puts " Pastas"
pastaMenu.show_items
gap
puts " press return to go back to main menu"
gets.chomp
runner = 0
elsif menuAnswer == 2
gap
puts " Pizzas"
pizzaMenu.show_items
gap
puts " press return to go back to main menu"
gets.chomp
runner = 0
elsif menuAnswer == 3
newOrder = Order.new([])
newOrder.order_push
runner = 1
elsif menuAnswer == 4
abort
else
valid_option(gap)
gap
end
end
| true |
7c95562a2b2ef0a6ecbe9d90ec838ffc9ec039e8 | Ruby | Hansen-Nick/RB101 | /101-109_practice_problems/easy_3/counting.rb | UTF-8 | 135 | 3.84375 | 4 | [] | no_license | print "Please write a word or multiple words: "
words = gets.chomp
puts "There are #{words.delete(' ').length} characters in #{words}." | true |
f13ccec0868906e6851e7bd37265a06a978ee1d9 | Ruby | Dwire/deli_counter_flatiron | /customer_view.rb | UTF-8 | 653 | 3.375 | 3 | [] | no_license |
module CustomerView
def line_view(current_line)
puts current_line.length > 0 ? "\nThe line is currently: #{current_line.join(" ")}" : "\nThe line is currently empty."
end
def take_a_number_view(name)
puts @deli_line.length == 1 ? "Welcome #{name}, you are first in line." : "Welcome #{name}, you are number #{@deli_line.length} in line."
end
def now_serving_view
puts "Now serving #{@deli_line[0]}" if @deli_line.length > 0
end
def day_overview
puts "REPORT: On #{@date} #{@deli_name} served #{@total_customers} customers. The busiest time of day was #{@busiest_hour} with #{@longest_line} people in line."
end
end
| true |
c7e36795f11822fb3aa4edefd395f87bf4c1be14 | Ruby | shristigautam/vector-space-model | /data/reuters21578/remove_nils.rb | UTF-8 | 696 | 2.703125 | 3 | [] | no_license | require 'fileutils'
i = 0
Dir.new("adapted_docs").select{|name| name != "." and name != ".."}.each do |name|
if File.size("adapted_docs/#{name}") <= 10
i = i + 1
puts name
FileUtils.rm "adapted_docs/#{name }"
end
end
puts "#{i} files removed"
missing = {}
Dir.new("adapted_topics").select{|name| name != "." and name != ".."}.each do |name|
open "adapted_topics/#{name}", "r" do |file|
open "tmp", "w" do |tmp|
while (line = file.gets)
if File.exist? "adapted_docs/#{line.strip}"
tmp.puts line.strip
else
missing[line.strip] = true
puts line.strip
end
end
end
end
FileUtils.cp "tmp", "ad/#{name}"
end
puts "#{missing.length} files dereferenced"
| true |
20c431614cad5c7cac4fd9d2ab16bd617104b730 | Ruby | lermannen/advent_of_code_2015 | /day6a.rb | UTF-8 | 10,546 | 3.109375 | 3 | [] | no_license | def handle_input(line, grid)
coords = line.match(/(\d+),(\d+) through (\d+),(\d+)/)
.captures.map(&:to_i)
case
when line.start_with?("turn on") then turn_on(coords, grid)
when line.start_with?("turn off") then turn_off(coords, grid)
when line.start_with?("toggle") then toggle(coords, grid)
end
end
def turn_on(coords, grid)
(coords[0]..coords[2]).each do |row|
(coords[1]..coords[3]).each do |col|
grid[row][col] = 1
end
end
grid
end
def turn_off(coords, grid)
(coords[0]..coords[2]).each do |row|
(coords[1]..coords[3]).each do |col|
grid[row][col] = 0
end
end
grid
end
def toggle(coords, grid)
(coords[0]..coords[2]).each do |row|
(coords[1]..coords[3]).each do |col|
grid[row][col] = (grid[row][col] + 1) % 2
end
end
grid
end
grid = []
(0..999).each do |x|
grid[x] = Array.new(1000) { 0 }
end
data = DATA.read.strip
data.each_line do |line|
handle_input(line, grid)
end
p grid.reduce(0) { |sum, n| sum + n.reduce(:+) }
__END__
turn on 489,959 through 759,964
turn off 820,516 through 871,914
turn off 427,423 through 929,502
turn on 774,14 through 977,877
turn on 410,146 through 864,337
turn on 931,331 through 939,812
turn off 756,53 through 923,339
turn off 313,787 through 545,979
turn off 12,823 through 102,934
toggle 756,965 through 812,992
turn off 743,684 through 789,958
toggle 120,314 through 745,489
toggle 692,845 through 866,994
turn off 587,176 through 850,273
turn off 674,321 through 793,388
toggle 749,672 through 973,965
turn on 943,30 through 990,907
turn on 296,50 through 729,664
turn on 212,957 through 490,987
toggle 171,31 through 688,88
turn off 991,989 through 994,998
turn off 913,943 through 958,953
turn off 278,258 through 367,386
toggle 275,796 through 493,971
turn off 70,873 through 798,923
toggle 258,985 through 663,998
turn on 601,259 through 831,486
turn off 914,94 through 941,102
turn off 558,161 through 994,647
turn on 119,662 through 760,838
toggle 378,775 through 526,852
turn off 384,670 through 674,972
turn off 249,41 through 270,936
turn on 614,742 through 769,780
turn on 427,70 through 575,441
turn on 410,478 through 985,753
turn off 619,46 through 931,342
turn on 284,55 through 768,922
turn off 40,592 through 728,685
turn on 825,291 through 956,950
turn on 147,843 through 592,909
turn off 218,675 through 972,911
toggle 249,291 through 350,960
turn off 556,80 through 967,675
toggle 609,148 through 968,279
toggle 217,605 through 961,862
toggle 407,177 through 548,910
toggle 400,936 through 599,938
turn off 721,101 through 925,455
turn on 268,631 through 735,814
toggle 549,969 through 612,991
toggle 553,268 through 689,432
turn off 817,668 through 889,897
toggle 801,544 through 858,556
toggle 615,729 through 832,951
turn off 427,477 through 958,948
turn on 164,49 through 852,946
turn on 542,449 through 774,776
turn off 923,196 through 980,446
toggle 90,310 through 718,846
turn off 657,215 through 744,252
turn off 800,239 through 811,712
turn on 502,90 through 619,760
toggle 649,512 through 862,844
turn off 334,903 through 823,935
turn off 630,233 through 839,445
turn on 713,67 through 839,865
turn on 932,50 through 982,411
turn off 480,729 through 984,910
turn on 100,219 through 796,395
turn on 758,108 through 850,950
turn off 427,276 through 439,938
turn on 178,284 through 670,536
toggle 540,27 through 625,102
turn off 906,722 through 936,948
toggle 345,418 through 859,627
toggle 175,775 through 580,781
toggle 863,28 through 929,735
turn off 824,858 through 905,973
toggle 752,312 through 863,425
turn on 985,716 through 988,852
turn off 68,504 through 763,745
toggle 76,209 through 810,720
turn off 657,607 through 676,664
toggle 596,869 through 896,921
turn off 915,411 through 968,945
turn off 368,39 through 902,986
turn on 11,549 through 393,597
turn off 842,893 through 976,911
toggle 274,106 through 581,329
toggle 406,403 through 780,950
toggle 408,988 through 500,994
toggle 217,73 through 826,951
turn on 917,872 through 961,911
toggle 394,34 through 510,572
toggle 424,603 through 583,626
toggle 106,159 through 755,738
turn off 244,610 through 472,709
turn on 350,265 through 884,690
turn on 688,184 through 928,280
toggle 279,443 through 720,797
turn off 615,493 through 888,610
toggle 118,413 through 736,632
turn on 798,782 through 829,813
turn off 250,934 through 442,972
turn on 68,503 through 400,949
toggle 297,482 through 313,871
toggle 710,3 through 839,859
turn on 125,300 through 546,888
toggle 482,39 through 584,159
turn off 536,89 through 765,962
turn on 530,518 through 843,676
turn on 994,467 through 994,676
turn on 623,628 through 744,927
toggle 704,912 through 837,983
turn on 154,364 through 517,412
toggle 344,409 through 780,524
turn off 578,740 through 725,879
turn on 251,933 through 632,957
turn on 827,705 through 971,789
toggle 191,282 through 470,929
toggle 324,525 through 446,867
toggle 534,343 through 874,971
toggle 550,650 through 633,980
toggle 837,404 through 881,915
toggle 338,881 through 845,905
turn on 469,462 through 750,696
turn on 741,703 through 892,870
turn off 570,215 through 733,562
turn on 445,576 through 870,775
turn on 466,747 through 554,878
turn off 820,453 through 868,712
turn off 892,706 through 938,792
turn off 300,238 through 894,746
turn off 306,44 through 457,444
turn off 912,569 through 967,963
toggle 109,756 through 297,867
turn on 37,546 through 41,951
turn on 321,637 through 790,910
toggle 66,50 through 579,301
toggle 933,221 through 933,791
turn on 486,676 through 878,797
turn on 417,231 through 556,317
toggle 904,468 through 981,873
turn on 417,675 through 749,712
turn on 692,371 through 821,842
toggle 324,73 through 830,543
turn on 912,490 through 977,757
turn off 634,872 through 902,949
toggle 266,779 through 870,798
turn on 772,982 through 990,996
turn off 607,46 through 798,559
turn on 295,602 through 963,987
turn on 657,86 through 944,742
turn off 334,639 through 456,821
turn off 997,667 through 997,670
turn off 725,832 through 951,945
turn off 30,120 through 952,984
turn on 860,965 through 917,976
toggle 471,997 through 840,998
turn off 319,307 through 928,504
toggle 823,631 through 940,908
toggle 969,984 through 981,993
turn off 691,319 through 865,954
toggle 911,926 through 938,929
turn on 953,937 through 968,991
toggle 914,643 through 975,840
turn on 266,982 through 436,996
turn off 101,896 through 321,932
turn off 193,852 through 751,885
turn off 576,532 through 863,684
turn on 761,456 through 940,783
turn on 20,290 through 398,933
turn off 435,335 through 644,652
turn on 830,569 through 905,770
turn off 630,517 through 905,654
turn on 664,53 through 886,976
toggle 275,416 through 408,719
turn on 370,621 through 515,793
turn on 483,373 through 654,749
turn on 656,786 through 847,928
turn off 532,752 through 945,974
toggle 301,150 through 880,792
turn off 951,488 through 958,952
turn on 207,729 through 882,828
toggle 694,532 through 973,961
toggle 676,639 through 891,802
turn off 653,6 through 905,519
toggle 391,109 through 418,312
turn on 877,423 through 957,932
turn on 340,145 through 563,522
turn off 978,467 through 988,895
turn off 396,418 through 420,885
turn off 31,308 through 816,316
turn on 107,675 through 758,824
turn on 61,82 through 789,876
turn on 750,743 through 754,760
toggle 88,733 through 736,968
turn off 754,349 through 849,897
toggle 157,50 through 975,781
turn off 230,231 through 865,842
turn off 516,317 through 630,329
turn off 697,820 through 829,903
turn on 218,250 through 271,732
toggle 56,167 through 404,431
toggle 626,891 through 680,927
toggle 370,207 through 791,514
toggle 860,74 through 949,888
turn on 416,527 through 616,541
turn off 745,449 through 786,908
turn on 485,554 through 689,689
turn on 586,62 through 693,141
toggle 506,759 through 768,829
turn on 473,109 through 929,166
turn on 760,617 through 773,789
toggle 595,683 through 618,789
turn off 210,775 through 825,972
toggle 12,426 through 179,982
turn on 774,539 through 778,786
turn on 102,498 through 121,807
turn off 706,897 through 834,965
turn off 678,529 through 824,627
turn on 7,765 through 615,870
turn off 730,872 through 974,943
turn off 595,626 through 836,711
turn off 215,424 through 841,959
toggle 341,780 through 861,813
toggle 507,503 through 568,822
turn on 252,603 through 349,655
toggle 93,521 through 154,834
turn on 565,682 through 951,954
turn on 544,318 through 703,418
toggle 756,953 through 891,964
turn on 531,123 through 856,991
turn on 148,315 through 776,559
turn off 925,835 through 963,971
turn on 895,944 through 967,964
turn off 102,527 through 650,747
toggle 626,105 through 738,720
turn off 160,75 through 384,922
toggle 813,724 through 903,941
turn on 207,107 through 982,849
toggle 750,505 through 961,697
toggle 105,410 through 885,819
turn on 226,104 through 298,283
turn off 224,604 through 508,762
turn on 477,368 through 523,506
turn off 477,901 through 627,936
turn off 887,131 through 889,670
turn on 896,994 through 938,999
toggle 401,580 through 493,728
toggle 987,184 through 991,205
turn on 821,643 through 882,674
toggle 784,940 through 968,959
turn off 251,293 through 274,632
turn off 339,840 through 341,844
turn off 675,351 through 675,836
toggle 918,857 through 944,886
toggle 70,253 through 918,736
turn off 612,604 through 772,680
turn off 277,40 through 828,348
toggle 692,139 through 698,880
toggle 124,446 through 883,453
toggle 969,932 through 990,945
toggle 855,692 through 993,693
toggle 722,472 through 887,899
toggle 978,149 through 985,442
toggle 837,540 through 916,889
turn off 612,2 through 835,82
toggle 560,767 through 878,856
turn on 461,734 through 524,991
toggle 206,824 through 976,912
turn on 826,610 through 879,892
turn on 577,699 through 956,933
turn off 9,250 through 50,529
turn off 77,657 through 817,677
turn on 68,419 through 86,426
turn on 991,720 through 992,784
turn on 668,20 through 935,470
turn off 133,418 through 613,458
turn off 487,286 through 540,328
toggle 247,874 through 840,955
toggle 301,808 through 754,970
turn off 34,194 through 578,203
turn off 451,49 through 492,921
turn on 907,256 through 912,737
turn off 479,305 through 702,587
turn on 545,583 through 732,749
toggle 11,16 through 725,868
turn on 965,343 through 986,908
turn on 674,953 through 820,965
toggle 398,147 through 504,583
turn off 778,194 through 898,298
turn on 179,140 through 350,852
turn off 241,118 through 530,832
turn off 41,447 through 932,737
turn off 820,663 through 832,982
turn on 550,460 through 964,782
turn on 31,760 through 655,892
toggle 628,958 through 811,992
| true |
aa75ea288c34a84319eaa388bbb22cbb913453ee | Ruby | takuan517/aoj_ruby | /ITP1/ITP1_2_B.rb | UTF-8 | 135 | 3.25 | 3 | [] | no_license | a = gets
b = a.split
if b[0].to_i < b[1].to_i && b[1].to_i < b[2].to_i && b[0].to_i < b[2].to_i
puts "Yes"
else
puts "No"
end
| true |
4e01c4c09bacd08a4368afe593a0c0815f8e6203 | Ruby | georgebixby/BEWD_NYC_6_Homework | /__george_bixby/midterm/play.rb | UTF-8 | 322 | 3.1875 | 3 | [] | no_license | require 'json'
require 'rest-client'
require 'pry'
require './word_counter'
require './times_headline'
@year = 0
while @year <= 1900 || @year >= 2013 do
puts "Please enter a date between 1900 and 2013"
year = gets
@year = year.to_i
end
t = TimesHeadline.new(@year)
w = WordCounter.new(t.headlines)
w.count_words
| true |
d7c14979c9b82decf79d215b91755ed59950add5 | Ruby | stujo/pokemonit | /pokemonit.rb | UTF-8 | 1,472 | 2.9375 | 3 | [] | no_license | require 'dotenv'
Dotenv.load
require 'sinatra'
require 'httparty'
def load_data(filename)
File.readlines(filename).inject({}) do |hash, line|
matches = /^(\d+)\s+([^\s]+)/.match(line)
hash[matches[1].to_i] = matches[2]
hash
end
end
$names = load_data('./data.txt')
$filter = [
1,2,3,5,6,9,24,26,27,28,29,30,31,32,33,34,
37,38,39,40,43,44,45,46,47,48,49,50,51,52,
53,56,57,58,59,63,64,65,66,67,68,69,70,71,
74,75,76,77,78,79,80,83,84,85,86,87,88,89,
90,91
]
$exclude = [118,119]
def is_wanted?(pokemon)
return false if $exclude.include?(pokemon["pokemonId"])
return (pokemon["pokemonId"] >= 100) || ($filter.include?(pokemon["pokemonId"]))
end
def get_pokemon(lat,lng)
response = HTTParty.get("https://pokevision.com/map/data/#{lat}/#{lng}")
response.body
end
post '/pokemon' do
p params
@location = {lat: "", lng: ""}
if params[:lat] && params[:lng]
@location = {lat: (params[:lat]).to_f, lng: (params[:lng]).to_f}
raw = get_pokemon(@location[:lat],@location[:lng])
data = JSON.parse(raw)
@pokemon = data["pokemon"].select { |pokemon|
is_wanted?(pokemon)
}.map{ |pokemon|
pokemon["name"] = $names[pokemon["pokemonId"]]
pokemon["image_url"] = "http://pokedream.com/pokedex/images/blackwhite/front/#{pokemon["pokemonId"].to_s.rjust(3, "0")}.png"
pokemon
}
else
@pokemon = []
end
content_type :json
@pokemon.to_json
end
get '/' do
erb :index
end
| true |
52b7e6e97a7b60833ff1c7e83fc07a519692f397 | Ruby | cwrydberg/ninjabear | /bear.rb | UTF-8 | 334 | 3.21875 | 3 | [] | no_license | require_relative 'fighter'
#links from the fighter.rb file in the ninjabeargame folder
class Bear < Fighter
def attack(enemy)
puts "Rawwr!!"
enemy.lose_health(self.power)
end
end
# bear = Bear.new("Bear", 100, 12)
# ninja = Fighter.new("Ninja", 100, 10)
# # ninja.attack(bear)
# # p bear
# # bear.attack(ninja)
# # p ninja
| true |
cce116ed42d99e3139648c6caf62de059e2367a3 | Ruby | utensils/barcoded | /docker-assets/usr/local/bin/edit-unicorn-config.rb | UTF-8 | 2,099 | 3 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
# This script is used to read a unicorn configuration file into memory
# Update values based on ENV variables and write it back to disk.
CONFIG_FILE = '/usr/local/etc/barcoded/unicorn.rb'
ENV_CONFIG_OPTIONS = {
'UNICORN_WORKERS' => 'worker_processes',
'UNICORN_TIMEOUT' => 'timeout',
'UNICORN_BACKLOG' => 'backlog'
}
def print_header(string)
puts '=' * 80
puts string
puts '=' * 80
end
def parse_env_variables
options = {}
ENV_CONFIG_OPTIONS.each do |env_variable,option|
if ENV[env_variable]
puts "#{option} value: #{ENV[env_variable]}"
options[option] = ENV[env_variable]
else
puts "Could not find #{ENV[env_variable]}"
end
end
return options
end
def read_config_file(input_file)
contents = []
file = nil
begin
file = File.open(input_file).each_line{|line| contents.push(line)}
rescue => e
puts e.message
return nil
ensure
file.close unless file.nil?
end
return contents
end
def write_config_file(contents,output_file)
file = nil
begin
file = File.open(output_file,'w')
contents.each {|line| file.puts line}
rescue => e
puts e.message
return false
ensure
file.close unless file.nil?
end
return true
end
def update_config_options(contents,options)
new_contents = []
regex = /^(\w+)\s+\S.*$/
contents.map! do |line|
match = line.match(regex)
match.nil? ? option = nil : option = match[1]
if option
new_contents.push("#{option} #{options[option]}") if options.has_key?(option)
else
new_contents.push(line)
end
end
return new_contents
end
# Update the configuration
print_header 'Updating Unicorn configuration'
config_options = parse_env_variables
if (config_contents = read_config_file(CONFIG_FILE))
new_contents = update_config_options(config_contents,config_options)
if (write_config_file(new_contents,CONFIG_FILE))
print_header 'Configuration updated!'
else
print_header 'Problem updating config'
exit 1
end
else
print_header 'Problem reading config'
exit 1
end
| true |
2d1f7cc2092ee1f628362badfbcc2ad42addaddf | Ruby | danpariente/trading_risk_calculator | /risk_calculator.rb | UTF-8 | 550 | 3.3125 | 3 | [] | no_license | class RiskCalculator
ATR_RATIO = 1.5
RISK_PERCENTAGE = 0.02
private_constant :ATR_RATIO, :RISK_PERCENTAGE
attr_writer :atr_ratio, :risk_percentage
def initialize(balance:, atr:)
@balance = balance
@atr = atr
end
def pip_value
(risk / (atr_ratio * atr)).round(2)
end
def risk
balance * risk_percentage
end
def pips
atr_ratio * atr
end
private
attr_reader :atr, :balance
def atr_ratio
@atr_ratio ||= ATR_RATIO
end
def risk_percentage
@risk_percentage ||= RISK_PERCENTAGE
end
end
| true |
4ce53a4fb2999426d814ce001ec4d211d64f29f0 | Ruby | AamuLumi/UniSoc | /main.rb | UTF-8 | 1,391 | 2.796875 | 3 | [] | no_license | $: << "."
require 'timeout'
require 'lib/uniSocPrinter'
require 'lib/twitterDebug'
# executeCommand
# -> Execute la commande spécifiée
# PARAMS :
# command : la commande à exécuter
# RETURN : No
def executeCommand(command)
commands = command.downcase.split(" ")
case commands[0] # Correspond à la première commande : st (showTwitter), h (help)
when "twitter", "t"
case commands[1]
when "ratelimit", "rl"
TwitterAPI::TwitterDebug.ShowRateLimit
when "timeline", "t"
UniSoc::UniSocPrinter.PrintTwitterTimeline
when "user", "u"
UniSoc::UniSocPrinter.PrintTwitterUser commands[2]
when "mention", "m"
UniSoc::UniSocPrinter.PrintTwitterMentionTimeline
end
when "help", "h"
UniSoc::UniSocPrinter.PrintHelp
when "q"
exit(0)
end
end
tmpKeyboard = ""
# On initialise UniSocPrinter
UniSoc::UniSocPrinter.Init("unknown")
begin
begin
puts "[INFO] Rafraîchissement de la timeline"
# On affiche les données de Twitter
UniSoc::UniSocPrinter.PrintTwitterDatas
# Permet de rentrer des commandes et d'obtenir un rafraîchissement toutes les 60 secondes
status = Timeout::timeout(60) {
while true
print "> "
tmpKeyboard = gets.chomp
executeCommand(tmpKeyboard)
end
}
# Quand on dépasse les 60 secondes, on supprime le caractère d'entrée au clavier
rescue Timeout::Error
print "\r"
end
end while true
| true |
2f2f5b20a15e50c928d6a01cc035f33624fa4435 | Ruby | nickborbe/bootcamp | /week_2/thursday/web_blog/app.rb | UTF-8 | 1,923 | 3.203125 | 3 | [] | no_license | require "sinatra"
require "sinatra/reloader"
require 'date'
require_relative('lib/blog.rb')
require_relative('lib/post.rb')
require_relative('lib/comment.rb')
my_blog = Blog.new
post0 = Post.new("Downtown Chickens", Date.new(2016, 1, 1), "I saw feral chickens under the metro rail station", "Nick Borbe")
post1 = Post.new("How to Gain 5 Pounds in One Day", Date.new(2016, 2, 1), "Eat pizza. Duh.", "Nick Borbe")
post2 = Post.new("How to Come out of a Breakup Looking Like a Loser", Date.new(2016, 1, 16), "Call her crying! Everyday!", "Nick Borbe")
post3 = Post.new("Why I Don't Shower Daily", Date.new(2016, 1, 21), "I'm just counterculture like that", "Nick Borbe")
comment1 = Comment.new("This is a title", Date.today, "This whole blog sucks why am I reading this?", "James Capra")
sponsored_post = SponsoredPost.new("Buy some stuff", Date.new(2016, 1, 14), "Buy this new sweet thing. You need it.", "The Evil Advertising Companies")
my_blog.add_post(post0)
my_blog.add_post(post1)
my_blog.add_post(post2)
my_blog.add_post(post3)
my_blog.add_post(sponsored_post)
my_blog.add_comment(comment1)
get "/" do
@comments = my_blog.show_comments
@posts = my_blog.latest_posts
erb :home
end
get "/post_details/:number" do
@posts = my_blog.latest_posts
@number = params[:number].to_i
@the_post = @posts[@number - 1]
erb :post_details
end
get "/create_new_post" do
erb :create_new_post
end
get "/create_new_comment" do
erb :create_new_comment
end
post "/new_post" do
title = params[:title]
contents = params[:contents]
author = params[:author]
x = 4
new_post = Post.new(title, Date.today, contents, author)
my_blog.add_post(new_post)
redirect "/"
end
post "/new_comment" do
title = params[:title]
contents = params[:contents]
author = params[:author]
x = 4
new_comment = Comment.new(title, Date.today, contents, author)
my_blog.add_comment(new_comment)
redirect "/"
end
| true |
8ad63f894b8fc312dbab752c2c0e537318b268d7 | Ruby | Srkiscool/phase2_s19 | /test/models/customer_test.rb | UTF-8 | 2,754 | 2.703125 | 3 | [] | no_license | require 'test_helper'
class CustomerTest < ActiveSupport::TestCase
#Relationships
# --------------------------
should have_many(:orders)
should have_many(:addresses)
#Validation macros...
should validate_presence_of(:first_name)
should validate_presence_of(:last_name)
#validate phone number
should allow_value("4122683259").for(:phone)
should allow_value("412-268-3259").for(:phone)
should allow_value("412.268.3259").for(:phone)
should allow_value("(412) 268-3259").for(:phone)
should_not allow_value("2683259").for(:phone)
should_not allow_value("4122683259x224").for(:phone)
should_not allow_value("800-EAT-FOOD").for(:phone)
should_not allow_value("412/268/3259").for(:phone)
should_not allow_value("412-2683-259").for(:phone)
# Validating email...
should allow_value("fred@fred.com").for(:email)
should allow_value("fred@andrew.cmu.edu").for(:email)
should allow_value("my_fred@fred.org").for(:email)
should allow_value("fred123@fred.gov").for(:email)
should allow_value("my.fred@fred.net").for(:email)
should_not allow_value("fred").for(:email)
should_not allow_value("fred@fred,com").for(:email)
should_not allow_value("fred@fred.uk").for(:email)
should_not allow_value("my fred@fred.com").for(:email)
should_not allow_value("fred@fred.con").for(:email)
context "Given context" do
# create the objects I want with factories
setup do
create_customers
end
# and provide a teardown method as well
teardown do
destroy_customers
end
# test the scope 'active'
should "shows that there are two active Customers" do
assert_equal 2, Customer.active.size
assert_equal ["Aob", "Sruthi"], Customer.active.alphabetical. map{|o| o.first_name}
#assert_equal ["Alex", "Mark"], Address.active.map{|o| o.first_name}.sort
end
# test the scope 'inactive'
should "shows that there is one inactive owners" do
assert_equal 1, Customer.inactive.size
assert_equal ["Bob"], Customer.inactive.map{|o| o.first_name}.sort
end
# test the scope 'alphabetical'
should "shows that there are three owners in in alphabetical order" do
assert_equal ["Aob", "Bob", "Sruthi"], Customer.alphabetical.map{|o| o.first_name}
end
#tests the method 'name' works
should "show that the name method works" do
assert_equal "Kalva, Sruthi", @sruthi.name
end
# test the method 'proper_name' works
should "shows that proper_name method works" do
assert_equal "Sruthi Kalva", @sruthi.proper_name
end
# test the callback is working 'reformat_phone'
should "shows that Sruthi's phone is stripped of non-digits" do
assert_equal "7032336783", @sruthi.phone
end
# test "the truth" do
# assert true
# end
end
end | true |
67803cd0d28c9dacb5612628e02a28509f2e0c96 | Ruby | paradigmshift/course1 | /lesson2/oop_blackjack.rb | UTF-8 | 3,946 | 3.8125 | 4 | [] | no_license | class Card
attr_accessor :rank, :suit
def initialize(rank, suit)
self.rank = rank
self.suit = suit
end
def to_s
"#{rank} of #{suit}"
end
end
class Deck
attr_accessor :cards
def initialize(number_of_decks=1)
self.cards = []
number_of_decks.times do
["Hearts", "Diamonds", "Spades", "Clubs"].each do |suit|
['2', '3', '4', '5', '6', '7', '8', '9', '10',
'Jack', 'Queen', 'King', 'Ace'].each { |rank| cards << Card.new(rank, suit) }
end
end
cards.shuffle!
end
def deal_card
cards.pop
end
end
class Player
attr_accessor :name, :hand, :score
def initialize(name)
self.name = name
self.hand = []
self.score = 0
end
def hit(deck)
hand << deck.deal_card
end
def show_hand
str = ""
if hand.length > 2
hand[0, hand.length - 1].each { |card| str << "#{card}, " }
str << "and #{hand.last}"
else
str << "#{hand.first} and #{hand.last}"
end
end
def get_name
puts "Please enter your name: "
self.name = gets.chomp
end
end
class BlackJack
def initialize
@player = Player.new("some random guy")
@dealer = Player.new("Dealer")
@deck = Deck.new(4)
end
def initial_deal
system "clear"
@player.hand = []
@dealer.hand = []
2.times do
@player.hit(@deck)
@dealer.hit(@deck)
end
@current_player = @player
end
def current_player_turn
if @current_player == @player
system "clear"
puts "#{@dealer.name}: #{@dealer.score} #{@player.name}: #{@player.score}"
puts "Your cards are #{@player.show_hand}, with a total value of #{calculate_value(@player.hand)}.\n
#{@dealer.name} has #{@dealer.hand.last}. (H)it or (s)tay?: "
hit_or_stay = gets.chomp.downcase
@player.hit(@deck) if hit_or_stay == 'h'
@current_player = @dealer if hit_or_stay == 's'
else
@dealer.hit(@deck)
end
end
def calculate_value(hand)
total = 0
hand.map do |card|
if card.rank.to_i == 0 && card.rank != 'Ace'
total += 10
else
total += card.rank.to_i
end
end
hand.select { |card| card.rank == 'Ace' }.count.times do # check for Aces and ajust accordingly
total + 11 <= 21 ? total += 11 : total += 1
end
total
end
def blackjack?(player)
calculate_value(player.hand) == 21
end
def bust?(player)
calculate_value(player.hand) > 21
end
def compare_hands
str = "#{@player.name}'s hand is #{@player.show_hand}, with a value of #{calculate_value(@player.hand)}.\n
#{@dealer.name}'s hand is #{@dealer.show_hand}, with a value of #{calculate_value(@dealer.hand)}.\n"
if calculate_value(@player.hand) > calculate_value(@dealer.hand)
str << "#{@player.name} wins!"
@player.score += 1
else
str << "#{@dealer.name} wins!"
@dealer.score += 1
end
str
end
def other_player(player)
case player
when @dealer
@player
else
@dealer
end
end
def current_player_turn_over?
bust?(@current_player) ||
blackjack?(@current_player) ||
calculate_value(@dealer.hand) > 17 && @current_player == @dealer
end
def run
@player.get_name
begin
initial_deal
case
when blackjack?(@player)
true
when blackjack?(@dealer)
@current_player = @dealer
else
current_player_turn until current_player_turn_over?
end
case
when blackjack?(@current_player)
message = "#{@current_player.name} hit blackjack!\n"
@current_player.score += 1
when bust?(@current_player)
message = "#{@current_player.name} busted!"
other_player(@current_player).score += 1
else
message = compare_hands
end
puts message
puts "Play again?: "
play_again = gets.chomp.downcase
end until play_again == 'n'
end
end
BlackJack.new.run
| true |
4c09541de22cd97a2c7144dbb72ec0d5a9771b91 | Ruby | wesenu/rrobots | /bots/SpaceInvader.rb | UTF-8 | 7,095 | 2.9375 | 3 | [] | no_license | require 'rrobots/robot.rb'
class Sector
attr_accessor :name
attr_accessor :range
attr_accessor :enemies
attr_accessor :closest_enemy
attr_accessor :gun_direction
def initialize(sector_range, sector_name)
@name = sector_name
@range = sector_range
@fire_to = range.first
@gun_direction = 1
@enemies = false
end
def fire_next
@fire_ret = @fire_to
if @fire_to == range.last
@gun_direction = -1
elsif @fire_to == range.first
@gun_direction = 1
end
@fire_to = @fire_to + @gun_direction
@fire_ret
end
end
class SpaceInvader
include Robot
def puts(*args)
# be quiet!!!
end
def initialize
@action_queue = [
:head_down
]
@next_actions_queue = []
@current_phase = 0
@due_north = 90
@due_east = 0
@due_west = 180
@due_south = 270
@roam_accel = 1
@sectors = [
Sector.new(0..29, "alpha"),
Sector.new(30..59, "bravo"),
Sector.new(60..89, "charlie"),
Sector.new(90..119, "delta"),
Sector.new(120..149, "echo"),
Sector.new(150..179, "foxtrot"),
Sector.new(180..209, "foxtrot"),
Sector.new(210..239, "foxtrot"),
Sector.new(240..269, "foxtrot"),
Sector.new(270..309, "foxtrot"),
Sector.new(310..360, "foxtrot")
]
@gun_in_position = false
@scan_sector_idx = 0
@target_sector = nil
@fire_counter = 0
end
def tick events
while !@action_queue.empty?
case @action_queue.pop
when :head_down
head_down(events)
when :travel_down
travel_down(events)
when :position
position(events)
when :aim
aim(events)
when :roam
roam(events)
when :radar_to_sector
radar_to_sector
when :check_enemies
check_enemies
when :unleash_heck
unleash_heck
else
say "I'm lost!"
end
end
#dump_scan
#dump_sectors
@action_queue = @next_actions_queue
@next_actions_queue = []
end
def head_down(events)
say "Heading for solid ground..."
if heading == @due_south
say "Ready to head out!"
@next_actions_queue << :travel_down
elsif heading < @due_south
say "Turning left..."
turn (@due_south - heading >= 10) ? 10 : @due_south - heading
@next_actions_queue << :head_down
else
say "Turning right..."
d = @due_south - heading
turn (d <= -10) ? -10 : d
@next_actions_queue << :head_down
end
end
def travel_down(events)
# check to see if we've reahed the bottom
if y < battlefield_height - size
say "Underway..."
accelerate(1)
@next_actions_queue << :travel_down
elsif speed == 0
@next_actions_queue << :position
else
stop
@next_actions_queue << :travel_down
end
end
def position(events)
say "Positioning..."
if heading == @due_west
@next_actions_queue << :roam
else
turn (heading - @due_west >= 10) ? -10 : @due_west - heading
@next_actions_queue << :position
end
end
def aim(events)
if gun_heading == @target_sector.range.first
@next_actions_queue << :unleash_heck
else
t = @target_sector.range.first - gun_heading
turn_gun(t)
@next_actions_queue << :aim
end
end
def unleash_heck
# puts "Firing at heading #{gun_heading}"
fire(0.3)
turn_gun(@target_sector.fire_next - gun_heading)
@fire_counter += 1
if @fire_counter < 40
@next_actions_queue << :unleash_heck
else
@fire_counter = 0
@next_actions_queue << :roam
end
end
def roam(events)
if speed < 8
accelerate(1)
else
# check to see if we need to turn around
if x < 300 && heading != @due_east
t = (heading - @due_east) * -1
puts "Turning east heading= #{heading} turning=#{t}"
turn(t)
elsif x > (battlefield_width - 300) && heading != @due_west
if heading == 0
t = -10
else
t = (@due_west - heading)
end
puts "Turning west heading= #{heading} turning=#{t}"
turn(t)
end
end
# if x >= battlefield_width - size - 300
# @roam_accel = 1
# elsif x <= size + 300
# @roam_accel = -1
# end
#
# if speed <= 5 && @roam_accel == 1
# accelerate(@roam_accel)
# elsif speed >= -5 && @roam_accel == -1
# accelerate(@roam_accel)
# end
@next_actions_queue << :radar_to_sector
end
def scan(events)
if radar_heading < 120 && radar_heading > 60
turn_radar(radar_heading - 120)
else
turn_radar(60)
end
@next_actions_queue << :scan
end
def radar_to_sector
if radar_heading == @sectors[@scan_sector_idx].range.first
scan_sweep = @sectors[@scan_sector_idx].range.last - @sectors[@scan_sector_idx].range.first
turn_radar(scan_sweep)
@next_actions_queue << :check_enemies
else
distance_from_sector = @sectors[@scan_sector_idx].range.first - radar_heading
turn_radar distance_from_sector > 60 ? 60 : distance_from_sector
@next_actions_queue << :roam
end
end
def check_enemies
if !events['robot_scanned'].empty?
closest = 99999
for distance in events['robot_scanned'].flatten.sort
if distance < closest
closest = distance
end
end
@sectors[@scan_sector_idx].enemies = true
@sectors[@scan_sector_idx].closest_enemy = closest
else
# clear the sector
@sectors[@scan_sector_idx].enemies = false
@sectors[@scan_sector_idx].closest_enemy = 0
end
advance_scan_sector
if @scan_sector_idx == 0
set_target_sector
if @target_sector == nil
@next_actions_queue << :radar_to_sector
else
@next_actions_queue << :aim
end
else
@next_actions_queue << :radar_to_sector
end
end
def advance_scan_sector
if @scan_sector_idx < @sectors.size - 1
@scan_sector_idx += 1
else
@scan_sector_idx = 0
end
end
def set_target_sector
@target_sector = nil
@sectors.each { | sector |
if sector.enemies == true
if @target_sector == nil
@target_sector = sector
else
if @target_sector.closest_enemy > sector.closest_enemy
@target_sector = sector
end
end
end
}
end
def dump_scan
#puts "Dumping Scan:"
#puts events
#distance = events['robot_scanned'].flatten.min
for distance in events['robot_scanned'].flatten.sort
puts "SpaceInvader scanned distance = #{distance}"
end
# if event = events['robot_scanned'].pop
# puts "got something"
# dist = event.first
# puts "distance = #{dist}"
# else
# #puts "got nothing"
# end
end
def dump_sectors
puts "Sectors:"
@sectors.each_with_index { | sector, i |
puts "Sector #{i} enemies #{sector.enemies} closest #{sector.closest_enemy}"
}
end
end
| true |
230767b61eeea38878ab199718e819d232bf4042 | Ruby | gnufied/representable | /test/json_test.rb | UTF-8 | 3,792 | 2.796875 | 3 | [
"MIT"
] | permissive | require 'test_helper'
require 'representable/json'
module JsonTest
class APITest < MiniTest::Spec
Json = Representable::JSON
Def = Representable::Definition
describe "Xml module" do
describe "#binding_for_definition" do
it "returns ObjectBinding" do
assert_kind_of Json::ObjectBinding, Json.binding_for_definition(Def.new(:band, :as => Hash))
end
it "returns TextBinding" do
assert_kind_of Json::TextBinding, Json.binding_for_definition(Def.new(:band))
end
end
end
end
class PropertyTest < MiniTest::Spec
describe "property :name" do
class Band
include Representable::JSON
representable_property :name
end
it "#from_json creates correct accessors" do
band = Band.from_json({:band => {:name => "Bombshell Rocks"}}.to_json)
assert_equal "Bombshell Rocks", band.name
end
it "#to_json serializes correctly" do
band = Band.new
band.name = "Cigar"
assert_equal "{\"band\"=>{\"name\"=>\"Cigar\"}}", band.to_json.to_s
end
end
describe "property :name, :as => []" do
class CD
include Representable::JSON
representable_property :songs, :as => []
end
it "#from_json creates correct accessors" do
cd = CD.from_json({:cd => {:songs => ["Out in the cold", "Microphone"]}}.to_json)
assert_equal ["Out in the cold", "Microphone"], cd.songs
end
it "#to_json serializes correctly" do
cd = CD.new
cd.songs = ["Out in the cold", "Microphone"]
assert_equal "{\"cd\"=>{\"songs\"=>[\"Out in the cold\", \"Microphone\"]}}", cd.to_json.to_s
end
end
end
class TypedPropertyTest < MiniTest::Spec
describe ":as => Item" do
class Label
include Representable::JSON
representable_property :name
end
class Album
include Representable::JSON
representable_property :label, :as => Label
end
it "#from_json creates one Item instance" do
album = Album.from_json({:album => {:label => "Fat Wreck"}}.to_json)
assert_equal "Bad Religion", album.label.name
end
describe "#to_json" do
it "serializes" do
label = Label.new; label.name = "Fat Wreck"
album = Album.new; album.label = label
assert_equal "{\"album\"=>{\"label\"=>{\"name\"=>\"Fat Wreck\"}}}", album.to_json.to_s
end
end
end
end
class CollectionTest < MiniTest::Spec
describe ":as => [Band]" do
class Band
include Representable::JSON
representable_property :name
def initialize(name="")
self.name = name
end
end
class Compilation
include Representable::JSON
representable_property :bands, :as => [Band]
end
describe "#from_json" do
it "pushes collection items to array" do
cd = Compilation.from_json({:compilation => {:bands => [
{:name => "Cobra Skulls"},
{:name => "Diesel Boy"}]}}.to_json)
assert_equal ["Cobra Skulls", "Diesel Boy"], cd.bands.map(&:name).sort
end
it "collections can be empty" do
cd = Compilation.from_json({:compilation => {}}.to_json)
assert_equal [], cd.bands
end
end
it "responds to #to_json" do
cd = Compilation.new
cd.bands = [Band.new("Diesel Boy"), Band.new("Bad Religion")]
assert_equal "{\"compilation\"=>{\"bands\"=>[{\"name\"=>\"Diesel Boy\"}, {\"name\"=>\"Bad Religion\"}]}}", cd.to_json.to_s
end
end
end
end
| true |
08da21bf9a37a6c7ce62140363293986847be2bd | Ruby | faheemmughal/bitmap_editor | /lib/bitmap_editor/image.rb | UTF-8 | 2,354 | 3.359375 | 3 | [] | no_license | # frozen_string_literal: true
module BitmapEditor
class Image
MIN_COLUMNS = MIN_ROWS = 1
MAX_COLUMNS = MAX_ROWS = 250
attr_accessor :number_of_rows, :number_of_columns, :bitmap
def initialize(columns, rows)
# we are going to store the image in zero based arrays
# and do translation on fly
self.number_of_columns = columns
self.number_of_rows = rows
self.bitmap = generate_white_bitmap
end
def draw_horizontal(x1, x2, y, colour)
x1, x2 = [x1, x2].sort
unless valid_coordinate?(x1, y) && valid_coordinate?(x2, y)
log_coordinates_out_of_bound([x1, y], [x2, y])
return
end
(x1..x2).each do |x|
bitmap[x - 1][y - 1] = colour
end
end
def draw_vertical(x, y1, y2, colour)
y1, y2 = [y1, y2].sort
unless valid_coordinate?(x, y1) && valid_coordinate?(x, y2)
log_coordinates_out_of_bound([x, y1], [x, y2])
return
end
(y1..y2).each do |y|
bitmap[x - 1][y - 1] = colour
end
end
def clear
self.bitmap = generate_white_bitmap
end
def colour(x, y, colour)
unless valid_coordinate?(x, y)
Log.instance.error "Coordinate (#{x}, #{y}) are out of bounds for \
image of with max coordinates \
(#{number_of_columns}, #{number_of_rows})"
.squeeze(' ')
return
end
bitmap[x - 1][y - 1] = colour
end
def pixel_at(x, y)
bitmap[x - 1][y - 1]
end
def to_s
output = +''
# O(n^2) time
(1..number_of_rows).each do |y|
(1..number_of_columns).each do |x|
output << pixel_at(x, y)
end
output << "\n"
end
output
end
private
def generate_white_bitmap
Array.new(number_of_columns) do
Array.new(number_of_rows, 'O')
end
end
def valid_coordinate?(x, y)
x.between?(MIN_COLUMNS, number_of_columns) &&
y.between?(MIN_ROWS, number_of_rows)
end
def log_coordinates_out_of_bound(coordinate1, coordinate2)
Log.instance.error "Coordinate (#{coordinate1[0]}, #{coordinate1[1]}) or \
(#{coordinate2[0]}, #{coordinate2[1]}) are out of bounds for image of \
with max coordinates (#{number_of_columns}, #{number_of_rows})"
.squeeze(' ')
end
end
end
| true |
b6af0e4a8bf5d5a50479a60122c4f7e05f7116b2 | Ruby | navya7744/Coding_Assignment | /features/libraries/locator.rb | UTF-8 | 4,854 | 2.671875 | 3 | [] | no_license | # frozen_string_literal: true
module Libraries
class Locator
attr_accessor :how, :what, :options
def initialize(
how,
what,
options = {
'hidden' => false,
'ajax_load' => false
}
)
@how = how
@what = what
@options = options
end
# #Highlight the element##
def highlight(driver = $focus_driver)
element = driver.find_element(self)
attr = element.attribute('backgroundColor')
driver.execute_script "arguments[0].style.backgroundColor = 'red';", element
driver.execute_script 'arguments[0].style.backgroundColor = arguments[1];', element, attr
driver.execute_script "arguments[0].style.backgroundColor = 'red';", element
driver.execute_script 'arguments[0].style.backgroundColor = arguments[1];', element, attr
end
##################################################
# Methods inherited and overriden from Selenium #
##################################################
# #Custom Click method with exception handling##
def click(driver = $focus_driver)
driver.find_element(self).click
puts "Clicked - #{how} => #{what}"
rescue Exception => e
puts "Not clicked at - #{how} => #{what}"
puts e.message
end
# #Get Text of an element##
def text(driver = $focus_driver)
driver.find_element(self).text
end
# #Get texts of similar elements##
def texts(driver = $focus_driver)
elements_text = []
driver.find_elements(self).each do |element|
elements_text.push(element.text)
end
elements_text
end
# #Get particular attribute value of an element##
def attribute(name, driver = $focus_driver)
driver.find_element(self).attribute(name)
end
# #Get CSS values of an element##
def css_value(prop, driver = $focus_driver)
driver.find_element(self).css_value(prop)
end
# #Verify Element displayed or not##
def displayed?(driver = $focus_driver)
driver.find_element(self).displayed?
end
# #Verify Element enabled or not##
def enabled?(driver = $focus_driver)
driver.find_element(self).enabled?
end
# #Verify Element enabled or not, if not enabled then wait and retry##
def is_enabled_with_wait?(timeout = $conf['implicit_wait'], driver = $focus_driver)
index = 0
while driver.find_element(self).enabled? == false
break if index == timeout
index += 1
end
end
# #Verify Element displayed or not##
def selected?(driver = $focus_driver)
driver.find_element(self).selected?
end
# #Get the element location after scrolling into element's view##
def location_once_scrolled_into_view(driver = $focus_driver)
driver.find_element(self).location_once_scrolled_into_view
end
def is_present?(driver = $focus_driver)
driver.driver.manage.timeouts.implicit_wait = 0
begin
driver.driver.find_element(how, what).displayed?
rescue Exception => e
driver.driver.manage.timeouts.implicit_wait = $conf['implicit_wait']
false
ensure
driver.driver.manage.timeouts.implicit_wait = $conf['implicit_wait']
end
end
def is_not_present?(driver = $focus_driver)
!is_present?(driver)
end
def is_present_with_wait?(timeout = $conf['implicit_wait'], driver = $focus_driver)
Wait.wait_for_element(self, timeout, driver)
is_present?(driver)
end
def is_not_present_with_wait?(timeout = $conf['implicit_wait'], driver = $focus_driver)
Wait.wait_for_element_hide(self, timeout, driver)
!is_present?(driver)
end
def click_if_present(driver = $focus_driver)
click(driver) if is_present?(driver)
end
def scroll_to_locator(_driver = $focus_driver)
$focus_driver.scroll_to_locator(self)
end
def click_if_present_with_wait(timeout = $conf['implicit_wait'], driver = $focus_driver)
click(driver) if is_present_with_wait?(timeout, driver)
end
def to_s
"How ===> #{@how}\nWhat ===> #{@what}\nOptions ===> #{@options}"
end
def move_and_click(driver = $focus_driver)
element = driver.find_element(self)
driver.action.move_to(element).click.perform
end
def get_element(driver = $focus_driver)
driver.find_element(self)
end
##############################
# Text box methods
##############################
def clear(driver = $focus_driver)
driver.find_element(self).clear
end
def send_keys(*args)
$focus_driver.find_element(self).send_keys(*args)
end
def clear_and_send_keys(*args)
clear($focus_driver)
send_keys(*args)
end
def get_value(driver = $focus_driver)
driver.find_element(self).attribute('value')
end
end
end
| true |
90dd1ba153bf89208274187102c677c0ab9db5a7 | Ruby | javifc/forecast | /app/services/forecast_service.rb | UTF-8 | 970 | 3.046875 | 3 | [] | no_license | require 'net/http'
class ForecastService
@base_url_find_by_city = "http://api.openweathermap.org/data/2.5/forecast/daily?"
def self.find_by_city(city, days=16, format="json", units="metric")
return {success: false, error: "A city has to be provided" } if city.blank?
url = @base_url_find_by_city + "q=#{city}&cnt=#{days}&units=#{units}&mode=#{format}&appid=#{ENV['OPEN_WEATHER_API_KEY']}"
response = Net::HTTP.get(URI.parse(url))
forecasts = []
return {success: false, error: "Unexpected error, no response returned" } unless response
data = JSON.parse(response).with_indifferent_access
return {success: false, error: "#{data[:cod]} - #{data[:message]}" } unless data[:cod] == "200"
data[:list].each do |item|
item[:units] = units
item[:city] = data[:city]
forecast = Forecast.new(item)
forecasts << forecast if forecast.valid?
end
city = City.new(data[:city])
{success: true, forecasts: forecasts, city: city}
end
end | true |
e34d73b5f78d4e23560a65011a25e3a902a28a4a | Ruby | yanovitchsky/karibu | /lib/karibu/request.rb | UTF-8 | 1,322 | 2.75 | 3 | [
"MIT"
] | permissive | # @author yanovitchsky
module Karibu
class Request
attr_accessor :uniq_id, :resource, :method, :params
def initialize(packet)
@packet = packet
end
def decode
@msg = MessagePack.unpack(@packet, :symbolize_keys => true, :encoding => Encoding::UTF_8)
check_msg()
[:type=, :uniq_id=, :resource=, :method=, :params=].each_with_index do |meth, index|
self.send(meth, @msg[index])
end
self
end
# def encode
# @msg = MessagePack.pack(@packet)
# end
def type=(type);end
def to_s
"[:id => #{uniq_id}, :resource => #{resource}, :method => #{method_called}, :params => #{params.join(',')}]"
end
private
def check_msg
raise BadRequestError if @msg.size != 5
check_type
check_id
check_resource
check_method
check_params
end
def check_type
raise BadRequestError unless (@msg[0].is_a?(Integer) && @msg[0] == 0)
end
def check_id
raise BadRequestError unless @msg[1].is_a? String
end
def check_resource
raise BadRequestError unless @msg[2].is_a? String
end
def check_method
raise BadRequestError unless @msg[3].is_a? ::String
end
def check_params
raise BadRequestError unless @msg[4].is_a? ::Array
end
end
end
| true |
48a0ded6d663ea32916c3414f38fe8d7c5533113 | Ruby | ryu2129/paiza | /Brank/4-1.rb | UTF-8 | 190 | 3.703125 | 4 | [] | no_license | #3文字列がスペース区切りで2つ入力されるので、スペースで分割し、2行で出力してください。(同じ問題多いな・・・)
N = gets.split(' ')
puts N | true |
3ca92024d1d1461d7d6c50c3408b80288c118550 | Ruby | dclechok/ruby-class-variables-and-class-methods-lab-online-web-ft-090919 | /lib/song.rb | UTF-8 | 1,061 | 3.640625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Song
attr_accessor :name, :artist, :genre
@@count = 0
@@genres = []
@@artists = []
def initialize(song_name, artist, genre)
@@count += 1
@@genres << genre
@@artists << artist
@name = song_name
@artist = artist
@genre = genre
end
def self.count()
@@count
end
def self.genres()
@@genres.uniq
end
def self.artists()
@@artists.uniq
end
def self.genre_count()
histogram = {}
count = 0
@@genres.each do |index|
if(histogram.has_key?(index))
#if key exists, add 1 to the count value
histogram[index] += 1
else
#create new key and value
histogram[index] = 1
end
end
histogram
end
def self.artist_count
artist_histogram = {}
count = 0
@@artists.each do |index|
if(artist_histogram.has_key?(index))
#if key exists, add 1 to the count value
artist_histogram[index] += 1
else
#create new key and value
artist_histogram[index] = 1
end
end
artist_histogram
end
end
| true |
e0c8a0ee1855a81144386b8ed41311e7bdcc0c19 | Ruby | Whelpley/phase-0 | /week-5/die-class/my_solution.rb | UTF-8 | 2,339 | 4.25 | 4 | [
"MIT"
] | permissive | # Die Class 1: Numeric
# I worked on this challenge [by myself!]
# I spent [1.5] hours on this challenge.
# 0. Pseudocode
=begin
# Input:
# Output:
-Depends on the methods being called.
Initialize: takes the # of sides, return the new Die object
Sides: takes no arguments, returns the # of sides
Roll: takes no arguments, returns a random integer between 1 and the # of sides
# Steps:
-I just jumped into the code for this one; each method was very simple
=end
# 1. Initial Solution
class Die
def initialize(sides)
unless (sides >= 1) && (sides.is_a? Integer)
raise ArgumentError.new("Only integers of 1 or higher are allowed")
end
@num_sides = sides
end
def sides
@num_sides
end
def roll
rand(1..@num_sides)
end
end
# 3. Refactored Solution
# see above, nothing to refactor down
# 4. Reflection
=begin
What is an ArgumentError and why would you use one?
-This is a special clause you can throw into a method that will shut down the method's operations and return an error message under a specified condition. They are useful to place in the initialize method of a class to filter out inapproriate starting arguments.
What new Ruby methods did you implement? What challenges and successes did you have in implementing them?
-Rand was new for me, and the challenge there was learning to specify the range of the method (eg rand{1..6)) to exclude 0 from the range of results, which would have happened with rand(0)
What is a Ruby class?
(Oh boy, this is one of those things that I feel that I get, but it's still hard to explain in words. Here goes:)
-A class is an object, but it is also a tent under which other objects are instances of & share available methods.
Why would you use a Ruby class?
-They are useful when you anticipate the creation of multiple objects sharing certain attributes. When any new object in a class is created, it comes with a set of pre-loaded methods available to it.
What is the difference between a local variable and an instance variable?
Where can an instance variable be used?
While a local variable is available within the scope of where it is defined, an instance variable may be defined within a class, and then later referenced outside of the class definition, as long as it is used in an object that is a member of that class.
=end
| true |
461e46c1cf7237e0ef9b72d39e3a67b09a0d4851 | Ruby | lsethi-xoriant/interviewcake | /solutions/ruby/stockPrices.rb | UTF-8 | 681 | 3.984375 | 4 | [] | no_license | =begin
Solution
We walk through the array from beginning to end, keeping track of:
our min_price so far
our max_profit so far
For each time, we check to see if:
we have a new min_price, or
buying at the current min_price and selling at the current_price would give a new max_profit.
So we have:
=end
min_price = stockPricesYesterday[0]
max_profit = 0 q
for time in range(len(stockPricesYesterday)):
current_price = stockPricesYesterday[time]
min_price = min(min_price, current_price)
max_profit = max(max_profit, current_price - min_price)
return max_profit
=begin
Complexity
O(n) time (we're only looping through the array once) and O(1) space.
=end | true |
dc747a997e42183aa12624c854e0859076788921 | Ruby | giraffi/giraffi | /lib/giraffi/client/triggers.rb | UTF-8 | 3,904 | 2.734375 | 3 | [
"MIT"
] | permissive | module Giraffi
class Client
# Defines methods related to the triggers
module Triggers
# Returns the desired trigger
#
# @requires_apikey Yes
# @param options [Hash] The request params to retrieve the desired triggers
# @return [HTTParty::Response]
def find_triggers(options={})
self.class.get("/triggers.json?apikey=#{apikey}", :query => options)
end
# Returns the desired trigger
#
# @requires_apikey Yes
# @param id [String] The numerical ID of the desired trigger
# @return [HTTParty::Response]
def find_trigger(id)
self.class.get("/triggers/#{id}.json?apikey=#{apikey}")
end
# Returns all axions related to the desired trigger
#
# @requires_apikey Yes
# @param args [Array] A set of params to retrieve axions related to the trigger
# @option args [String] The numerical ID of the related trigger
# @option args [String] The kind of axion [problem, recovery] to retrieve
# @return [HTTParty::Response]
def find_axions_by_trigger(*args)
raise ArgumentError.new('The method `find_axions_by_trigger` requires at least a trigger id.') if args.size.zero?
if args.size == 1
self.class.get("/triggers/#{args[0]}/axions.json?apikey=#{apikey}")
else
self.class.get("/triggers/#{args[0]}/axions.json?apikey=#{apikey}", :query => {:axionkind => args[-1]})
end
end
# Executes all axions related to the desired trigger
#
# @requires_apikey Yes
# @param id [String] The numerical ID of the desired trigger
# @return [HTTParty::Response]
def execute_axions_by_trigger(id)
self.class.post("/triggers/#{id}/axions/execute.json?apikey=#{apikey}")
end
# Updates the desired trigger
#
# @requires_apikey Yes
# @param id [String] The numerical ID of the desired trigger
# @param options [Hash] A set of attributes to update the trigger
# @return [HTTParty::Response]
def update_trigger(id, options={})
self.class.put("/triggers/#{id}.json?apikey=#{apikey}", :query => {:trigger => options}, :body => {})
end
# Updates the axion related to the desired trigger
#
# @requires_apikey Yes
# @param args [Array] A set of parmas to update the axion related to the trigger
# @option args [String] The numerical ID of the related trigger
# @option args [String] The numerical ID of the desired axion
# @option args [String] The kind of axion [problem, recovery] to update
# @return [HTTParty::Response]
def update_axion_of_trigger(*args)
raise ArgumentError.new('The method `update_axion_by_trigger` requires 3 argments (trigger-id, axion-id and axion-kind)') if args.size != 3
self.class.put("/triggers/#{args[0]}/axions/#{args[1]}.json?apikey=#{apikey}", :query => { :axionkind => args[-1] }, :body => {})
end
# Deletes the trigger
#
# @requires_apikey Yes
# @param id [String] The numerical ID of the desired trigger
# @return [HTTParty::Response]
def destroy_trigger(id)
self.class.delete("/triggers/#{id}.json?apikey=#{apikey}")
end
# Removes an axion from the trigger
#
# @requires_apikey Yes
# @param args [Array] A set of parmas to remove an axion from the trigger
# @option args [String] The numerical ID of the related trigger
# @option args [String] The numerical ID of the axion to remove
# @return [HTTParty::Response]
def remove_axion_from_trigger(*args)
raise ArgumentError.new('The method `remove_axion_from_trigger` requires 2 arguments (trigger-id and axion-id)') if args.size != 2
self.class.delete("/triggers/#{args[0]}/axions/#{args[-1]}.json?apikey=#{apikey}")
end
end
end
end
| true |
6a73c1c6c5ecb5cb415cdc91b67861bf35c7738e | Ruby | alu0100902341/P12_LPP | /lib/gema/cocinero.rb | UTF-8 | 960 | 3.421875 | 3 | [
"MIT"
] | permissive | class Cocinero
attr_accessor :experiencia, :contador, :edad
def initialize
@edad = 36
@experiencia = "pinche"
@contador = 0
end
def uno_mas
if @edad < 50
@edad = @edad + 1
if @edad == 44
@experiencia = "cocinero"
end
if @edad >= 44
@contador = @contador + 1
end
else
@experiencia = "jubilado"
end
end
def degustar_uno
if @experiencia == "cocinero"
if @contador == 0
puts "Sorry, no dishes to taste"
else
@contador = @contador - 1
puts "The dish is delicious"
end
elsif @experiencia == "pinche"
puts "Sorry, no dishes to taste"
elsif @experiencia == "jubilado"
puts "Sorry, the Chef is retired"
end
end
end
@cocinero = Cocinero.new
@t1 = Thread.new do
for i in 0..17
@cocinero.uno_mas
sleep(rand(0.1))
end
end
@t2 = Thread.new do
for i in 0..17
@cocinero.degustar_uno
sleep(rand(0.1))
end
end
@t2.join
@t1.join
| true |
0bd7ead59654a3bca2b7da4b172619b0e37f3aae | Ruby | gardengeek/remarkable | /remarkable/lib/remarkable/dsl/assertions.rb | UTF-8 | 6,423 | 3.453125 | 3 | [
"MIT"
] | permissive | module Remarkable
module DSL
module Assertions
protected
# It sets the arguments your matcher receives on initialization.
#
# arguments :name, :range
#
# Which is roughly the same as:
#
# def initialize(name, range, options = {})
# @name = name
# @range = range
# @options = options
# end
#
# But most of the time your matchers iterates through a collection,
# such as a collection of attributes in the case below:
#
# @product.should validate_presence_of(:title, :name)
#
# validate_presence_of is a matcher declared as:
#
# class ValidatePresenceOfMatcher < Remarkable::Base
# arguments :collection => :attributes, :as => :attribute
# end
#
# In this case, Remarkable provides an API that enables you to easily
# assert each item of the collection. Let's check more examples:
#
# should allow_values_for(:email, "jose@valim.com", "carlos@brando.com")
#
# Is declared as:
#
# arguments :attribute, :collection => :good_values, :as => :good_value
#
# And this is the same as:
#
# class AllowValuesForMatcher < Remarkable::Base
# def initialize(attribute, *good_values)
# @attribute = attribute
# @options = default_options.merge(good_values.extract_options!)
# @good_values = good_values
# end
# end
#
# Now, the collection is @good_values. In each assertion method we will
# have a @good_value variable (in singular) instantiated with the value
# to assert.
#
# Finally, if your matcher deals with blocks, you can also set them as
# option:
#
# arguments :name, :block => :builder
#
# It will be available under the instance variable @builder.
#
def arguments(*names)
options = names.extract_options!
args = names.dup
@matcher_arguments[:names] = names
if collection = options.delete(:collection)
@matcher_arguments[:collection] = collection
if options[:as]
@matcher_arguments[:as] = options.delete(:as)
else
raise ArgumentError, 'You gave me :collection as option but have not give me :as as well'
end
args << "*#{collection}"
get_options = "#{collection}.extract_options!"
set_collection = "@#{collection} = #{collection}"
else
args << 'options={}'
get_options = 'options'
set_collection = ''
end
if block = options.delete(:block)
@matcher_arguments[:block] = block
args << "&#{block}"
names << block
end
assignments = names.map do |name|
"@#{name} = #{name}"
end.join("\n ")
class_eval <<-END, __FILE__, __LINE__
def initialize(#{args.join(',')})
#{assignments}
@options = default_options.merge(#{get_options})
#{set_collection}
run_after_initialize_callbacks
end
END
end
# Call it to declare your collection assertions. Every method given will
# iterate through the whole collection given in <tt>:arguments</tt>.
#
# For example, validate_presence_of can be written as:
#
# class ValidatePresenceOfMatcher < Remarkable::Base
# arguments :collection => :attributes, :as => :attribute
# collection_assertions :allow_nil?
#
# protected
# def allow_nil?
# # matcher logic
# end
# end
#
# Then we call it as:
#
# should validate_presence_of(:email, :password)
#
# For each attribute given, it will call the method :allow_nil which
# contains the matcher logic. As stated in <tt>arguments</tt>, those
# attributes will be available under the instance variable @argument
# and the matcher subject is available under the instance variable
# @subject.
#
# If a block is given, it will create a method with the name given.
# So we could write the same class as above just as:
#
# class ValidatePresenceOfMatcher < Remarkable::Base
# arguments :collection => :attributes
#
# collection_assertion :allow_nil? do
# # matcher logic
# end
# end
#
# Those methods should return true if it pass or false if it fails. When
# it fails, it will use I18n API to find the proper failure message:
#
# expectations:
# allow_nil: allowed the value to be nil
# allow_blank: allowed the value to be blank
#
# Or you can set the message in the instance variable @expectation in the
# assertion method if you don't want to rely on I18n API.
#
# As you might have noticed from the examples above, this method is also
# aliased as <tt>collection_assertion</tt>.
#
def collection_assertions(*methods, &block)
define_method methods.last, &block if block_given?
@matcher_collection_assertions += methods
end
alias :collection_assertion :collection_assertions
# In contrast to <tt>collection_assertions</tt>, the methods given here
# are called just once. In other words, it does not iterate through the
# collection given in arguments.
#
# It also accepts blocks and is aliased as assertion.
#
def assertions(*methods, &block)
define_method methods.last, &block if block_given?
@matcher_single_assertions += methods
end
alias :assertion :assertions
# Class method that accepts a block or a hash to set matcher's default options.
#
def default_options(hash = {}, &block)
if block_given?
define_method :default_options, &block
else
class_eval "def default_options; #{hash.inspect}; end"
end
end
end
end
end
| true |
dd62dd27b2fb13cfff01fefa8414ed61fb251e40 | Ruby | cielavenir/procon | /atcoder/codefestival/tyama_atcodercodefestival2015qualaC.rb | UTF-8 | 145 | 2.703125 | 3 | [
"0BSD"
] | permissive | #!/usr/bin/ruby
N,T=gets.split.map &:to_i
s=0
A=N.times.map{a,b=gets.split.map &:to_i;s+=a;b-a}.sort
p s>T ? (1..N).find{|i|(s+=A[i-1])<=T}||-1:0 | true |
0da038425b1f33cda9ee7756fd3c842fd876d272 | Ruby | qbahers/google-code-jam | /2013/qualification-round/tic-tac-toe-tomek/tic-tac-toe-tomek.rb | UTF-8 | 2,847 | 3.296875 | 3 | [] | no_license | class Problem
def check_rows(board, output)
board.each do |row|
if (row.first == "X" || row.first == "O")
symbol = row.first
else
symbol = row[1]
end
count = row.count(symbol)
t_symbol = row.include?("T")
if ((symbol == "X" || symbol == "O") &&
(count == 4 || (count == 3 && t_symbol)))
output.write("#{symbol} won")
return true
end
end
false
end
def check_first_diagonal(board, output)
if (board.first.first == "X" || board.first.first == "O")
symbol = board.first.first
else
symbol = board[1][1]
end
count = 0
t_symbol = false
board.each_with_index do |row, i|
if row[i] == symbol
count += 1
elsif row[i] == "T"
t_symbol = true
end
end
if ((symbol == "X" || symbol == "O") &&
(count == 4 || (count == 3 && t_symbol)))
output.write("#{symbol} won")
return true
end
false
end
def check_second_diagonal(board, output)
if (board.first.last == "X" || board.first.last == "O")
symbol = board.first.last
else
symbol = board[1][2]
end
count = 0
t_symbol = false
board.each_with_index do |row, i|
if row[3 - i] == symbol
count += 1
elsif row[3 - i] == "T"
t_symbol = true
end
end
if ((symbol == "X" || symbol == "O") &&
(count == 4 || (count == 3 && t_symbol)))
output.write("#{symbol} won")
return true
end
false
end
def solve(dataset)
File.open(dataset, 'r') do |input|
File.open(dataset.sub(/\.in/, '.out'), 'w') do |output|
#
nb_test_cases = input.readline.chomp.to_i
nb_test_cases.times do |index|
board = []
4.times do
line = input.readline.chomp
row = line.split(//)
board << row
end
empty_line = input.readline.chomp
output.write("Case ##{index + 1}: ")
transpose = board.transpose
someone_won = (check_rows(board, output) ||
check_rows(transpose, output) ||
check_first_diagonal(board, output) ||
check_second_diagonal(board, output))
unless someone_won
draw = true
board.each do |row|
if row.include?(".")
output.write("Game has not completed")
draw = false
break
end
end
output.write("Draw") if draw
end
output.write("\n")
end
#
end
end
end
end
problem = Problem.new
problem.solve('sample.in')
problem.solve('A-small-practice.in')
problem.solve('A-large-practice.in')
| true |
b548a2a5e7a28f6d7fabddb0296f2f9c34b481ee | Ruby | braydon322/sql-crowdfunding-lab-v-000 | /lib/sql_queries.rb | UTF-8 | 1,634 | 2.65625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive |
def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_name
"SELECT projects.title, SUM(pledges.amount) FROM projects INNER JOIN pledges ON projects.id = pledges.project_id GROUP BY projects.id ORDER BY projects.title ASC;"
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 users INNER JOIN pledges ON users.id = pledges.user_id GROUP BY users.name ORDER BY users.name ASC;"
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) AS amount_over FROM projects INNER JOIN pledges ON projects.id = pledges.project_id GROUP BY projects.title HAVING amount_over >= 0;"
end
def selects_user_names_and_amounts_of_all_pledges_grouped_by_name_then_orders_them_by_the_amount_and_users_name
"SELECT users.name, SUM(pledges.amount) AS sum_of_pledges FROM users INNER JOIN pledges ON users.id = pledges.user_id GROUP BY users.name ORDER BY sum_of_pledges ASC;"
end
def selects_the_category_names_and_pledge_amounts_of_all_pledges_in_the_music_category
"SELECT projects.category, SUM(pledges.amount) FROM projects INNER JOIN pledges ON projects.id = pledges.project_id GROUP BY pledges.id HAVING projects.category == 'music';"
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 projects INNER JOIN pledges ON projects.id = pledges.project_id GROUP BY projects.category HAVING projects.category == 'books';"
end
| true |
0af084c554f42d721a4aef8727364657ae2ea656 | Ruby | AlfredoVillalobos/Desafio-latam | /Desafio-latam/clases online/hola.rb/primera-clase-ruby/entrada.rb | UTF-8 | 69 | 3.15625 | 3 | [] | no_license | numero = -1
numero = gets.chomp.to_i while numero < 0 || numero > 36 | true |
8592858e1fa261bc4d411ff8f85f2d8fa31f9613 | Ruby | rowlandjl/ruby-collaborating-objects-lab-cb-000 | /lib/song.rb | UTF-8 | 509 | 3.03125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Song
attr_accessor :name, :artist
@@all = []
def self.all
@@all
end
def initialize(name)
@name = name
self.class.all << self
end
def self.new_by_filename(name)
parse = name.split(" - ")
artist = Artist.find_or_create_by_name(parse[0])
song = Song.new(parse[1])
artist.add_song(song)
song.artist = artist
song
end
def artist_name=(name)
artist = Artist.find_or_create_by_name(name)
self.artist = artist
end
end | true |
5f8557bbf4af391c70e5aefca8ae63837ae90797 | Ruby | lainventoria/aaww | /lib/aaww/transaction.rb | UTF-8 | 2,096 | 2.578125 | 3 | [
"MIT"
] | permissive | module Aaww
class Transaction
include ActiveModel::Model
extend Forwardable
attr_accessor :key, :token, :file, :email, :value, :job_id, :link,
:ssl_link, :status, :progress
def_delegators :status, :ok?, :error?
# Creates a single unique token for this transaction
# Returns Token
# GET /api3/api_create_partner_token?api_key={key}
def create_token
response = Aaww.get '/api3/api_create_partner_token', query: { api_key: key }
self.status = Status.new response['status']
self.token = response['data']['token']
response
end
# Uploads a 3D object associated with a specific token and purchase order information
# Returns token_link and ssl_token_link
# POST /api3/api_upload_partner_stl?api_key={key}&receiver_email={email}&print_value={value}&token=&partner_job_id={job_id}
def upload(file, email, value, job_id = nil)
self.file = file
self.email = email
self.value = value
self.job_id = job_id unless job_id.nil?
upload!
end
def upload!
create_token if token.nil?
response = Aaww.post '/api3/api_upload_partner_stl', query: upload_query
self.status = Status.new response['status']
self.link = response['data']['token_link']
self.ssl_link = response['data']['ssl_token_link']
response
end
def upload_query
{ api_key: key,
receiver_email: email,
print_value: value,
token: token,
partner_job_id: job_id,
stl_file: file }.reject { |_, value| value.nil? }
end
# Returns a detailed print status for a specific token
# Returns Print Status
# GET /api3/api_get_partner_print_status?api_key={key}&token={token}"
# TODO enforce 15 seconds API restriction
def check_print_status!
if token
response = Aaww.get '/api3/api_get_partner_print_status', query: { api_key: key, token: token }
self.status = Status.new response['status']
self.progress = Progress.new response['data']
response
end
end
end
end
| true |
9b9f7f03141bc6a6c57f7871152047fa8fdc5cef | Ruby | dibdas/tic-tac-toe | /lib/player.rb | UTF-8 | 161 | 3.125 | 3 | [] | no_license | class Player
attr_reader :name, :symbol
attr_accessor :moves
def initialize(name, symbol)
@name = name
@symbol = symbol
@moves = []
end
end
| true |
51244061c826b7522c8942e3d4bd1e25f6e7e877 | Ruby | kennethjohnbalgos/wiser_trails | /lib/wiser_trails/common.rb | UTF-8 | 10,388 | 2.703125 | 3 | [
"MIT"
] | permissive | module WiserTrails
# Happens when creating custom activities without either action or a key.
class NoKeyProvided < Exception; end
# Used to smartly transform value from metadata to data.
# Accepts Symbols, which it will send against context.
# Accepts Procs, which it will execute with controller and context.
# @since 0.4.0
def self.resolve_value(context, thing)
case thing
when Symbol
context.__send__(thing)
when Proc
thing.call(WiserTrails.get_controller, context)
else
thing
end
end
# Common methods shared across the gem.
module Common
extend ActiveSupport::Concern
included do
include Trackable
class_attribute :activity_owner_global, :activity_account_global, :activity_skip_fields_global,
:activity_new_value_global, :activity_hooks, :activity_custom_fields_global,
:activity_force_fields_global
set_wiser_trails_class_defaults
end
# @!group Global options
# @!attribute activity_owner_global
# Global version of activity owner
# @see #activity_owner
# @return [Model]
# @!attribute activity_account_global
# Global version of activity recipient
# @see #activity_account
# @return [Model]
# @!attribute activity_new_value_global
# Global version of activity parameters
# @see #activity_new_value
# @return [Hash<Symbol, Object>]
# @!attribute activity_hooks
# @return [Hash<Symbol, Proc>]
# Hooks/functions that will be used to decide *if* the activity should get
# created.
#
# The supported keys are:
# * :create
# * :update
# * :destroy
# @!endgroup
# @!group Instance options
# Set or get parameters that will be passed to {Activity} when saving
#
# == Usage:
#
# @article.activity_new_value = {:article_title => @article.title}
# @article.save
#
# This way you can pass strings that should remain constant, even when model attributes
# change after creating this {Activity}.
# @return [Hash<Symbol, Object>]
attr_accessor :activity_new_value
@activity_new_value = {}
attr_accessor :activity_owner
@activity_owner = nil
attr_accessor :activity_account
@activity_account = nil
attr_accessor :activity_key
@activity_key = nil
attr_accessor :activity_custom_fields
@activity_custom_fields = {}
attr_accessor :activity_skip_fields_global
@activity_skip_fields_global = {}
attr_accessor :activity_force_fields_global
@activity_force_fields_global = {}
# @!visibility private
@@activity_hooks = {}
# @!endgroup
# Provides some global methods for every model class.
module ClassMethods
#
# @since 1.0.0
# @api private
def set_wiser_trails_class_defaults
self.activity_owner_global = nil
self.activity_account_global = nil
self.activity_new_value_global = {}
self.activity_hooks = {}
self.activity_custom_fields_global = {}
self.activity_skip_fields_global = {}
self.activity_force_fields_global = {}
end
def get_hook(key)
key = key.to_sym
if self.activity_hooks.has_key?(key) and self.activity_hooks[key].is_a? Proc
self.activity_hooks[key]
else
nil
end
end
end
#
# Returns true if WiserTrails is enabled
# globally and for this class.
# @return [Boolean]
# @api private
# @since 0.5.0
def wiser_trails_enabled?
WiserTrails.enabled?
end
#
# Shortcut for {ClassMethods#get_hook}
# @param (see ClassMethods#get_hook)
# @return (see ClassMethods#get_hook)
# @since (see ClassMethods#get_hook)
# @api (see ClassMethods#get_hook)
def get_hook(key)
self.class.get_hook(key)
end
# Calls hook safely.
# If a hook for given action exists, calls it with model (self) and
# controller (if available, see {StoreController})
# @param key (see #get_hook)
# @return [Boolean] if hook exists, it's decision, if there's no hook, true
# @since 0.4.0
# @api private
def call_hook_safe(key)
hook = self.get_hook(key)
if hook
# provides hook with model and controller
hook.call(self, WiserTrails.get_controller)
else
true
end
end
# Directly creates activity record in the database, based on supplied options.
#
# It's meant for creating custom activities while *preserving* *all*
# *configuration* defined before. If you fire up the simplest of options:
#
# current_user.create_activity(:avatar_changed)
#
# It will still gather data from any procs or symbols you passed as params
# to {Tracked::ClassMethods#tracked}. It will ask the hooks you defined
# whether to really save this activity.
#
# But you can also overwrite instance and global settings with your options:
#
# @article.activity :owner => proc {|controller| controller.current_user }
# @article.create_activity(:commented_on, :owner => @user)
#
# And it's smart! It won't execute your proc, since you've chosen to
# overwrite instance parameter _:owner_ with @user.
#
# [:key]
# The key will be generated from either:
# * the first parameter you pass that is not a hash (*action*)
# * the _:action_ option in the options hash (*action*)
# * the _:key_ option in the options hash (it has to be a full key,
# including model name)
# When you pass an *action* (first two options above), they will be
# added to parameterized model name:
#
# Given Article model and instance: @article,
#
# @article.create_activity :commented_on
# @article.activities.last.key # => "article.commented_on"
#
# For other parameters, see {Tracked#activity}, and "Instance options"
# accessors at {Tracked}, information on hooks is available at
# {Tracked::ClassMethods#tracked}.
# @see #prepare_settings
# @return [Model, nil] If created successfully, new activity
# @since 0.4.0
# @api public
# @overload create_activity(action, options = {})
# @param [Symbol,String] action Name of the action
# @param [Hash] options Options with quality higher than instance options
# set in {Tracked#activity}
# @option options [Activist] :owner Owner
# @option options [Activist] :recipient Recipient
# @option options [Hash] :params Parameters, see
# {WiserTrails.resolve_value}
# @overload create_activity(options = {})
# @param [Hash] options Options with quality higher than instance options
# set in {Tracked#activity}
# @option options [Symbol,String] :action Name of the action
# @option options [String] :key Full key
# @option options [Activist] :owner Owner
# @option options [Activist] :recipient Recipient
# @option options [Hash] :params Parameters, see
# {WiserTrails.resolve_value}
def create_activity(*args)
return unless self.wiser_trails_enabled?
options = prepare_settings(*args)
if call_hook_safe(options[:key].split('.').last)
reset_activity_instance_options
return WiserTrails::Adapter.create_activity(self, options)
end
nil
end
# Prepares settings used during creation of Activity record.
# params passed directly to tracked model have priority over
# settings specified in tracked() method
#
# @see #create_activity
# @return [Hash] Settings with preserved options that were passed
# @api private
# @overload prepare_settings(action, options = {})
# @see #create_activity
# @overload prepare_settings(options = {})
# @see #create_activity
def prepare_settings(*args)
# key
all_options = args.extract_options!
options = {
key: all_options.delete(:key),
action: all_options.delete(:action)
}
action = (args.first || options[:action]).try(:to_s)
options[:key] = extract_key(action, options)
raise NoKeyProvided, "No key provided for #{self.class.name}" unless options[:key]
options.delete(:action)
# user responsible for the activity
options[:owner] = WiserTrails.resolve_value(self,
(all_options.has_key?(:owner) ? all_options[:owner] : (
self.activity_owner || self.class.activity_owner_global
)
)
)
# recipient of the activity
options[:account] = WiserTrails.resolve_value(self,
(all_options.has_key?(:account) ? all_options[:account] : (
self.activity_account || self.class.activity_account_global
)
)
)
changes = Hash.new
self.changed_attributes.each do |attr, val|
changes[attr.to_sym] = val if attr != "updated_at"
end
options[:old_value] = changes.stringify_keys
options.delete(:params)
customs = self.class.activity_custom_fields_global.clone
customs.merge!(self.activity_custom_fields) if self.activity_custom_fields
customs.merge!(all_options)
customs.each do |k, v|
customs[k] = WiserTrails.resolve_value(self, v)
end.merge options
end
# Helper method to serialize class name into relevant key
# @return [String] the resulted key
# @param [Symbol] or [String] the name of the operation to be done on class
# @param [Hash] options to be used on key generation, defaults to {}
def extract_key(action, options = {})
(options[:key] || self.activity_key ||
((self.class.name.underscore.gsub('/', '_') + "." + action.to_s) if action)
).try(:to_s)
end
# Resets all instance options on the object
# triggered by a successful #create_activity, should not be
# called from any other place, or from application code.
# @private
def reset_activity_instance_options
@activity_old_value = {}
@activity_new_value = {}
@activity_key = nil
@activity_owner = nil
@activity_account = nil
@activity_custom_fields = {}
@activity_skip_fields_global = {}
@activity_force_fields_global = {}
end
end
end
| true |
a9c9164c3643820d259e535cb27010dc002caa4d | Ruby | garyeh/projects | /chess/knight.rb | UTF-8 | 163 | 2.671875 | 3 | [] | no_license | require_relative 'stepping_piece'
class Knight < Piece
include SteppingPiece
def initialize(position, board, color)
super
@symbol = "∑"
end
end
| true |
782e211ccf6b48a20f48cf557532b701bb0fe7e3 | Ruby | sagar601/nekoshop-master | /test/factories/order_item_factory_test.rb | UTF-8 | 929 | 2.53125 | 3 | [] | no_license | require 'test_helper'
describe OrderItemFactory do
it 'transforms a collection o CartItems into equivalent OrderItems' do
cart_items = [
Monkey.imitate(CartItem.new,
name: 'item1',
variations: [],
quantity: 1,
base_price: Money.new(99),
options_cost: Money.new(150),
virtual_cat_id: 11
),
Monkey.imitate(CartItem.new,
name: 'item2',
variations: [ 'var1', 'var2' ],
quantity: 5,
base_price: Money.new(50),
options_cost: Money.new(199),
virtual_cat_id: 22
),
]
order_items = OrderItemFactory.new.from_cart_items cart_items
order_items.zip(cart_items).each do |order_item, cart_item|
%i(name variations quantity base_price options_cost virtual_cat_id).map do |attr|
order_item.send(attr) == cart_item.send(attr)
end
.reduce(:&).must_equal true
end
end
end | true |
b518d61d721782ab78af38810f92856274b65c60 | Ruby | fritzvl/protobuf | /lib/protobuf/rpc/servers/socket/server.rb | UTF-8 | 3,249 | 2.53125 | 3 | [] | no_license | require 'protobuf/rpc/server'
require 'protobuf/rpc/servers/socket/worker'
module Protobuf
module Rpc
module Socket
class Server
include ::Protobuf::Rpc::Server
include ::Protobuf::Logger::LogMethods
def self.cleanup?
# every 10 connections run a cleanup routine after closing the response
@threads.size > (@thread_threshold - 1) && (@threads.size % @thread_threshold) == 0
end
def self.cleanup_threads
log_debug { "[#{log_signature}] Thread cleanup - #{@threads.size} - start" }
@threads = @threads.select do |t|
if t[:thread].alive?
true
else
t[:thread].join
@working.delete(t[:socket])
false
end
end
log_debug { "[#{log_signature}] Thread cleanup - #{@threads.size} - complete" }
end
def self.log_signature
@log_signature ||= "server-#{self}"
end
def self.new_worker(socket)
Thread.new(socket) do |sock|
::Protobuf::Rpc::Socket::Worker.new(sock) do |s|
s.close
end
end
end
def self.run(opts = {})
log_debug { "[#{log_signature}] Run" }
host = opts.fetch(:host, "127.0.0.1")
port = opts.fetch(:port, 9399)
backlog = opts.fetch(:backlog, 100)
thread_threshold = opts.fetch(:thread_threshold, 100)
auto_collect_timeout = opts.fetch(:auto_collect_timeout, 20)
@threads = []
@thread_threshold = thread_threshold
@server = ::TCPServer.new(host, port)
@server.listen(backlog)
@working = []
@listen_fds = [@server]
@running = true
while running?
log_debug { "[#{log_signature}] Waiting for connections" }
if ready_cnxns = IO.select(@listen_fds, [], [], auto_collect_timeout)
cnxns = ready_cnxns.first
cnxns.each do |client|
case
when !running? then
# no-op
when client == @server then
log_debug { "[#{log_signature}] Accepted new connection" }
client, sockaddr = @server.accept
@listen_fds << client
else
if !@working.include?(client)
@working << @listen_fds.delete(client)
log_debug { "[#{log_signature}] Working" }
@threads << { :thread => new_worker(client), :socket => client }
cleanup_threads if cleanup?
end
end
end
else
# Run a cleanup if select times out while waiting
cleanup_threads if @threads.size > 1
end
end
rescue Errno::EADDRINUSE
raise
rescue
# Closing the server causes the loop to raise an exception here
raise if running?
end
def self.running?
@running
end
def self.stop
@running = false
@server.close if @server
end
end
end
end
end
| true |
51023463d1a1b27f97700d0b3fec06321fea65da | Ruby | ariera/i19 | /lib/i19/key.rb | UTF-8 | 2,191 | 2.640625 | 3 | [
"MIT"
] | permissive | module I19
class Key
class SourceOcurrence
attr_accessor :src_path, :pos, :line_num, :line_pos, :line
def initialize(args)
@src_path = args[:src_path]
@pos = args[:pos]
@line_num = args[:line_num]
@line_pos = args[:line_pos]
@line = args[:line]
end
def short_path
src_path.split("/").last + ":#{line_num}"
end
def long_path
"#{src_path}:#{line_num}"
end
end
class InconsistentDefaults < StandardError
def initialize(key, defaults, source_occurrences)
@key, @defaults, @source_occurrences = key, defaults, source_occurrences
end
def to_str
"\n
Inconsistent Defaults for:
'#{@key}'
Defaults:
[#{@defaults.join(",")}]
Source Files:
#{@source_occurrences.map(&:long_path).join("\n\t ")}
"
end
end
extend ActiveModel::Naming
include ActiveModel::Validations
validate :key_can_not_be_interpolated
attr_accessor :key, :default, :source_occurrences
alias_method :value, :default
def initialize(args)
@key = args[:key]
@source_occurrences = Array(args[:source_occurrences]).map{|sc| SourceOcurrence.new(sc)}
@defaults = Array(args[:defaults]).compact.uniq
raise InconsistentDefaults.new(@key, @defaults, @source_occurrences) if @defaults.length > 1
@default = clean_default(@defaults.first)
end
def to_row
[key, default, source_occurrences.map(&:short_path)]
end
def to_log
{"#{key}" => default, "source_occurrences" => source_occurrences.map(&:short_path)}.to_s
%{#{key} => #{default}\n\t#{source_occurrences.map(&:long_path).join("\n\t")}}
end
private
def key_can_not_be_interpolated
if key.match(%r[#\{.*?\}])
errors.add(:key, "'#{key}' looks like a interpolated string. Sorry, no support for that yet")
end
end
def clean_default(str)
return str if str.blank?
str[0] = '' if ["'", '"'].include?(str[0])
str[-1] = '' if ["'", '"'].include?(str[-1])
str.force_encoding("UTF-8")
str
end
end
end
| true |
d9549af7358eb3a7e6afd44d7e3072005b26d7b3 | Ruby | nomatteus/adventofcode | /2019/day11/day11.rb | UTF-8 | 3,183 | 3.921875 | 4 | [] | no_license | require 'matrix'
require 'set'
require 'pry'
# Day 9 Intcode works as-is for this problem, so use that
require_relative '../day09/intcode_day9'
input = IO.read('input')
program = Intcode::Helpers.parse_program(input)
class PaintingRobot
attr_reader :painted_panels
# Color values
BLACK = 0
WHITE = 1
# Output codes
OUTPUT_LEFT = 0
OUTPUT_RIGHT = 1
# Direction vectors
UP = Vector[0, 1]
DOWN = Vector[0, -1]
LEFT = Vector[-1, 0]
RIGHT = Vector[1, 0]
def initialize(program:, starting_color:)
@program = program
@robot = Intcode::Computer.new(program: program, debug: false)
# Store panel as a hash where key is a Vector and value is current color
# All panels start as black, so set that as default.
@panel_grid = Hash.new(BLACK)
@current_location = Vector[0, 0]
@current_direction = UP
# Set initial color
@panel_grid[@current_location] = starting_color
# Track all panels that have been painted at least once
@painted_panels = Set.new
end
def run!
while !@robot.terminated? do
panel_color = @panel_grid[@current_location]
# Input: 0 if over black panel, 1 if over white panel
@robot.add_input(panel_color)
# Output 1: First, it will output a value indicating the color to paint the
# panel the robot is over: 0 means to paint the panel black, and 1 means to
# paint the panel white.
new_color = @robot.run
break if new_color.nil? # program has terminated
@panel_grid[@current_location] = new_color
@painted_panels << @current_location
# Output 2: Second, it will output a value indicating the direction the robot
# should turn: 0 means it should turn left 90 degrees, and 1 means it should turn right 90 degrees.
direction = @robot.run
if direction == OUTPUT_LEFT
# Turn left 90 degress
@current_direction = case @current_direction
when UP then LEFT
when LEFT then DOWN
when DOWN then RIGHT
when RIGHT then UP
end
else
# Turn right 90 degrees
@current_direction = case @current_direction
when UP then RIGHT
when RIGHT then DOWN
when DOWN then LEFT
when LEFT then UP
end
end
# Move forward one space
@current_location += @current_direction
end
end
# Output grid of panels
def to_s
# Calculate boundaries
left = @painted_panels.map { |panel| panel[0] }.min
right = @painted_panels.map { |panel| panel[0] }.max
top = @painted_panels.map { |panel| panel[1] }.max
bottom = @painted_panels.map { |panel| panel[1] }.min
top.downto(bottom).map do |col|
left.upto(right).map do |row|
@panel_grid[Vector[row, col]] == WHITE ? '⬜' : '⬛'
end.join
end.join("\n")
end
end
part1_robot = PaintingRobot.new(program: program, starting_color: PaintingRobot::BLACK)
part1_robot.run!
# Part 1: 2226
puts "Part 1: #{part1_robot.painted_panels.size} painted panels."
# Part 2: HBGLZKLF
puts "Part 2:"
part2_robot = PaintingRobot.new(program: program, starting_color: PaintingRobot::WHITE)
part2_robot.run!
puts part2_robot
| true |
df3170a965515e46d17017d936ebfb9a497c437b | Ruby | plato721/ruby-exercism | /allergies/allergies/allergies_test.rb | UTF-8 | 991 | 3.03125 | 3 | [] | no_license | require 'minitest/autorun'
require 'minitest/pride'
require './allergies.rb'
class AllergiesTest < Minitest::Test
def setup
@all = ["cats", "pollen", "chocolate", "tomatoes", "strawberries", "shellfish",
"peanuts", "eggs"]
@tester = Allergies.new(255)
end
def test_255_returns_all_allergies
tester = Allergies.new(255)
assert_equal tester.allergies_for, @all
end
def test_34_returns_choco_and_peanuts
tester = Allergies.new(34)
assert tester.allergies_for.include?("chocolate")
assert tester.allergies_for.include?("peanuts")
end
def test_3_eggs_and_peanuts
tester = Allergies.new(3)
assert tester.allergies_for.include?("eggs")
assert tester.allergies_for.include?("peanuts")
end
def test_128_returns_cat
assert @tester.allergies_for(128).include?("cats")
end
def test_224_returns_cats_pol_choco
expected = ["cats", "pollen", "chocolate"]
assert_equal @tester.allergies_for(224), expected
end
end | true |
0c820b0e3080dad4d01d800ac419c70af21b172c | Ruby | ga-dc/wdi5 | /w02/d01_object_oriented_programming/04_inheritance/time_traveler.rb | UTF-8 | 245 | 2.703125 | 3 | [] | no_license | class TimeTraveler < Car
def initialize color, max_speed
super
@can_time_travel = true
end
def visit_past
puts "the year is 1900"
end
def drive speed
super
puts "a blazing trail of fire was left behind"
end
end
| true |
c42b28e12cb34917fa4dbc6191aab7bab9e38f08 | Ruby | ahawkins/chassis-example | /vendor/cache/chassis-fca0c675c66b/lib/chassis/dirty_session.rb | UTF-8 | 2,229 | 2.96875 | 3 | [
"MIT"
] | permissive | require 'set'
module Chassis
class DirtySession < Proxy
def initialize(*args)
super
@original_values = { }
@new_values = { }
end
def clean?
new_values.empty?
end
def dirty?
!clean?
end
def original_values
@original_values
end
def new_values
@new_values
end
def changes
Set.new original_values.keys
end
def reset!
original_values.clear
new_values.clear
end
def method_missing(name, *args, &block)
raise MissingObject, name unless __getobj__
if writer_method?(name)
handle_writer_method name, *args, &block
elsif changed_method?(name)
handle_changed_method name
elsif original_method?(name)
handle_original_method name
else
__getobj__.send name, *args, &block
end
end
def respond_to_missing?(name, include_private = false)
if changed_method?(name) || original_method?(name)
__getobj__.respond_to? reader_method(name)
else
super
end
end
private
def handle_writer_method(name, *args, &block)
method_key = reader_method name
original_value = __getobj__.send method_key
new_value = __getobj__.send name, *args, &block
if new_value != original_value
original_values[method_key] = original_value unless original_values.key? method_key
new_values[method_key] = new_value
end
new_value
end
def writer_method?(name)
name =~ /=$/
end
def reader_method(name)
method_name = name.to_s
if writer_method? method_name
method_name.match(/(.+)=$/)[1].to_sym
elsif changed_method? method_name
method_name.match(/(.+)_changed\?$/)[1].to_sym
elsif original_method? method_name
method_name.match(/original_(.+)$/)[1].to_sym
end
end
def original_method?(name)
name =~ /original_.+$/
end
def changed_method?(name)
name =~ /_changed\?$/
end
def handle_changed_method(name)
original_values.key? reader_method(name)
end
def handle_original_method(name)
original_values[reader_method(name)]
end
end
end
| true |
af6a3741e3fed48b849dfeb349a3514877299b35 | Ruby | KnightsofRen/knights_chess | /spec/models/rook_spec.rb | UTF-8 | 1,214 | 2.796875 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe Rook, type: :model do
describe 'valid_move?' do
it 'should return true if valid, false if invalid' do
game = FactoryGirl.create(:game)
game.pieces.delete_all
# rook is at (4, 4), other pieces at (2, 4) and (4, 2)
rook = FactoryGirl.create(:rook, game_id: game.id)
FactoryGirl.create(:piece, x_coordinate: 2, y_coordinate: 4, game_id: game.id)
FactoryGirl.create(:piece, x_coordinate: 4, y_coordinate: 2, game_id: game.id)
test = 0
(-1..8).each do |y|
(-1..8).each do |x|
test += 1 if rook.valid_move?(x, y) == true # => 8
end
end
expect(test).to eq(8)
expect(rook.valid_move?(4, 4)).to eq false # destination same as current position
expect(rook.valid_move?(-3, 4)).to eq false # off board
expect(rook.valid_move?(6, 6)).to eq false # diagonal
expect(rook.valid_move?(3, 2)).to eq false # not horizontal or vertical
expect(rook.valid_move?(1, 4)).to eq false # obstructed (horizontal)
expect(rook.valid_move?(4, 1)).to eq false # obstructed (vertical)
expect(rook.valid_move?(4, 6)).to eq true # valid
end
end
end
| true |
370e445d62632e86375c81a0ba6871d9ce3573b6 | Ruby | dariathompson/oystercard | /lib/oystercard.rb | UTF-8 | 612 | 3.515625 | 4 | [] | no_license | # frozen_string_literal: true
class Oystercard
attr_reader :balance
attr_accessor :state
LIMIT = 90
MIN_BAL = 1
def initialize(balance = 0, state = false)
@balance = balance
@state = state
end
def top_up(value)
@balance += value
raise "You exceeded the limit of #{LIMIT}£" if limit?
@balance
end
def deduct(value)
@balance -= value
end
def in_journey?
@state
end
def touch_in
raise 'Not Enough Balance' if @balance < MIN_BAL
@state = true
end
def touch_out
@state = false
end
private
def limit?
@balance >= LIMIT
end
end
| true |
d311300645fbd6748bb8d0ef3dd9b0a05f5405f8 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/gigasecond/05cf48b01cd046478d4037982d435443.rb | UTF-8 | 124 | 2.8125 | 3 | [] | no_license | class Gigasecond
GIGASECOND = 10**9
class << self
def from(date)
(date.to_time + GIGASECOND).to_date
end
end
end
| true |
463097ea78a09a65d50547aa247ddc2117f8f82d | Ruby | cominvent/elasticrawl | /lib/elasticrawl/job_step.rb | UTF-8 | 1,560 | 2.765625 | 3 | [
"MIT"
] | permissive | module Elasticrawl
# Represents an Elastic MapReduce job flow step. For a parse job this will
# process a single Common Crawl segment. For a combine job a single step
# will aggregate the results of multiple parse jobs.
class JobStep < ActiveRecord::Base
belongs_to :job
belongs_to :crawl_segment
# Returns a custom jar step that is configured with the jar location,
# class name and input and output paths.
#
# For parse jobs optionally specifies the maximum # of Common Crawl
# data files to process before the job exits.
def job_flow_step(job_config)
jar = job_config['jar']
max_files = self.job.max_files
step_args = []
step_args[0] = job_config['class']
step_args[1] = self.input_paths
step_args[2] = self.output_path
# All arguments must be strings.
step_args[3] = max_files.to_s if max_files.present?
step = Elasticity::CustomJarStep.new(jar)
step.name = set_step_name
step.arguments = step_args
step
end
private
# Sets the Elastic MapReduce job flow step name based on the type of job it
# belongs to.
def set_step_name
case self.job.type
when 'Elasticrawl::ParseJob'
if self.crawl_segment.present?
max_files = self.job.max_files || 'all'
"#{self.crawl_segment.segment_desc} Parsing: #{max_files}"
end
when 'Elasticrawl::CombineJob'
paths = self.input_paths.split(',')
"Combining #{paths.count} jobs"
end
end
end
end
| true |
9e63080738d515138a50e38c268837715d03d657 | Ruby | caelum/ruby_on_br_forum | /vendor/rails/activerecord/test/defaults_test.rb | UTF-8 | 1,140 | 2.640625 | 3 | [
"BSD-3-Clause",
"MIT"
] | permissive | require 'abstract_unit'
require 'fixtures/default'
require 'fixtures/entrant'
class DefaultTest < Test::Unit::TestCase
def test_nil_defaults_for_not_null_columns
column_defaults =
if current_adapter?(:MysqlAdapter)
{ 'id' => nil, 'name' => '', 'course_id' => nil }
else
{ 'id' => nil, 'name' => nil, 'course_id' => nil }
end
column_defaults.each do |name, default|
column = Entrant.columns_hash[name]
assert !column.null, "#{name} column should be NOT NULL"
assert_equal default, column.default, "#{name} column should be DEFAULT #{default.inspect}"
end
end
if current_adapter?(:PostgreSQLAdapter, :SQLServerAdapter, :FirebirdAdapter, :OpenBaseAdapter)
def test_default_integers
default = Default.new
assert_instance_of Fixnum, default.positive_integer
assert_equal 1, default.positive_integer
assert_instance_of Fixnum, default.negative_integer
assert_equal -1, default.negative_integer
assert_instance_of BigDecimal, default.decimal_number
assert_equal BigDecimal.new("2.78"), default.decimal_number
end
end
end
| true |
bbe72ba3c0e7f5f641f36f90df5ccbf25006c66d | Ruby | warmwaffles/skeleton | /lib/skeleton/item.rb | UTF-8 | 3,543 | 2.84375 | 3 | [
"MIT"
] | permissive | require 'skeleton/model'
module Skeleton
class Item < Model
attr_accessor :type, :format, :title, :description, :default, :multiple_of,
:maximum, :exclusive_maximum, :minimum, :exclusive_minimum,
:max_length, :min_length, :pattern, :max_items, :min_items,
:unique_items, :max_properties, :min_properties, :items
attr_writer :enum
attr_presence :exclusive_maximum, :exclusive_minimum, :unique_items, :items
def enum
@enum ||= []
end
def enum?
!enum.empty?
end
def array?
@type == 'array'
end
def string?
@type == 'string'
end
def number?
@type == 'number'
end
def integer?
@type == 'integer'
end
def boolean?
@type == 'boolean'
end
def file?
@type == 'file'
end
def to_h
hash = {}
hash[:type] = type if type?
hash[:format] = format if format?
hash[:items] = items.to_hash if items?
hash[:title] = title if title?
hash[:description] = description if description?
hash[:default] = default if default?
hash[:multiple_of] = multiple_of if multiple_of?
hash[:maximum] = maximum if maximum?
hash[:exclusive_maximum] = exclusive_maximum if exclusive_maximum?
hash[:minimum] = minimum if minimum?
hash[:exclusive_minimum] = exclusive_minimum if exclusive_minimum?
hash[:max_length] = max_length if max_length?
hash[:min_length] = min_length if min_length?
hash[:pattern] = pattern if pattern?
hash[:max_items] = max_items if max_items?
hash[:min_items] = min_items if min_items?
hash[:unique_items] = unique_items if unique_items?
hash[:max_properties] = max_properties if max_properties?
hash[:min_properties] = min_properties if min_properties?
hash[:enum] = enum if enum?
hash
end
def to_swagger_hash
hash = {}
hash[:type] = type if type?
hash[:format] = format if format?
hash[:items] = items.to_swagger_hash if items?
hash[:title] = title if title?
hash[:description] = description if description?
hash[:default] = default if default?
hash[:multipleOf] = multiple_of if multiple_of?
hash[:maximum] = maximum if maximum?
hash[:exclusiveMaximum] = exclusive_maximum if exclusive_maximum?
hash[:minimum] = minimum if minimum?
hash[:exclusiveMinimum] = exclusive_minimum if exclusive_minimum?
hash[:maxLength] = max_length if max_length?
hash[:minLength] = min_length if min_length?
hash[:pattern] = pattern if pattern?
hash[:maxItems] = max_items if max_items?
hash[:minItems] = min_items if min_items?
hash[:uniqueItems] = unique_items if unique_items?
hash[:maxProperties] = max_properties if max_properties?
hash[:minProperties] = min_properties if min_properties?
hash[:enum] = enum if enum?
hash
end
end
end
| true |
4b0006c1bb451be824d6251755503f36f852e0dc | Ruby | nigel-lowry/the_ray_tracer_challenge | /lib/point_light.rb | UTF-8 | 266 | 3.3125 | 3 | [] | no_license | class PointLight
attr_reader :position, :intensity
def initialize position, intensity
@position, @intensity = position, intensity
end
def ==(other)
self.class == other.class and @position == other.position and @intensity = other.intensity
end
end | true |
a1a4ecd0a67fd6280543cbdc4d1494d694417837 | Ruby | jonareyes/Destripando-twiter | /destripando_twitter.rb | UTF-8 | 2,135 | 3.25 | 3 | [] | no_license | require 'nokogiri'
class TwitterScrapper
def initialize(url)
@url = Nokogiri::HTML(File.open(url))
end
def extract_username
user = @url.search(".ProfileHeaderCard-name > a")
user.first.inner_text
end
def extract_tweets
tweets = @url.search(".ProfileNav-value")
tweets.first.inner_text
end
def extract_followings
followings = @url.search(".ProfileNav-value")
followings[1].inner_text
end
def extract_followers
followers = @url.search(".ProfileNav-value")
followers[2].inner_text
end
def extract_likes
likes = @url.search(".ProfileNav-value")
likes[3].inner_text
end
def show_date_and_tweet
result = []
dates = []
tweets = []
tweets_stream = @url.search("#stream-items-id").xpath("//li")
tweets_stream.each do |tweet_content|
dates << tweet_content.search(".js-short-timestamp").inner_text
tweets << tweet_content.search(".tweet-text").inner_text
end
result << dates.reject!(&:empty?)
result << tweets.reject!(&:empty?)
result
end
def interfaz
puts "Username: #{extract_username}"
puts ""
puts "-----------------------------------------------------------------------------------------"
puts ""
puts "Stats:"
puts "Tweets: #{extract_tweets} followings: #{extract_followings}"
puts "followers: #{extract_followers} likes: #{extract_likes}"
puts ""
puts "-----------------------------------------------------------------------------------------"
puts ""
puts "Tweets:"
show_date_and_tweet[0].each_with_index do |date, index|
puts date
puts show_date_and_tweet[1][index]
end
puts ""
end
end
display = TwitterScrapper.new('twitter_account.html')
display.interfaz
display.extract_username
display.extract_tweets
display.extract_followings
display.extract_followers
display.extract_likes
display.show_date_and_tweet
# values = {tweets: stats[0].inner_text, followings: stats[1].inner_text, followers: stats[2].inner_text, likes: stats[3].inner_text}
# stats = stats[0].inner_text, stats[1].inner_text, stats[2].inner_text, stats[3].inner_text
| true |
0c9bc469477179fb1c25aec101386ab6eadc7331 | Ruby | Lee-oh/engine-honeypot-ruby | /bin/executer.rb | UTF-8 | 330 | 2.84375 | 3 | [] | no_license | port_1 = ARGV[0]
port_2 = ARGV[1]
port_3 = ARGV[2]
threads = []
if port_1
threads << Thread.new {system("start main.rb #{port_1}")}
end
if port_2
threads << Thread.new {system("start main.rb #{port_2}")}
end
if port_3
threads << Thread.new {system("start main.rb #{port_3}")}
end
threads.each { |thr| thr.join }
| true |
9712e46fcc0288017e8fc3244ebf802abd51566c | Ruby | ECOtterstrom/Ruby_Basics | /12_hashes/ex_129.rb | UTF-8 | 180 | 3.140625 | 3 | [] | no_license | # 12_hashes exercise 9
vehicles = {
car: { type: 'sedan', color: 'blue', year: '2003' },
truck: { type: 'pickup', color: 'red', year: '1998' }
}
puts vehicles | true |
674b2e2d0f530f4257e7c67e8e9de3b00b77d0d1 | Ruby | KalyanAkella/graphs | /spec/topological_sort_spec.rb | UTF-8 | 731 | 2.71875 | 3 | [] | no_license |
require 'graph'
require 'topological_sort'
describe 'topological sort on a graph' do
before(:all) do
@graph = Graph.create %w(shorts pants belt shirt tie jacket socks shoes watch)
shorts, pants, belt, shirt, tie, jacket, socks, shoes, watch = @graph.vertices
@graph.edges(shorts, pants, shoes)
@graph.edges(pants, belt, shoes)
@graph.edge(belt, jacket)
@graph.edges(shirt, belt, tie)
@graph.edge(tie, jacket)
@graph.edge(socks, shoes)
end
it "should list vertices in the correct order" do
shorts, pants, belt, shirt, tie, jacket, socks, shoes, watch = @graph.vertices
expect(topological_sort(@graph)).to eq([watch, socks, shirt, tie, shorts, pants, shoes, belt, jacket])
end
end
| true |
3c3b666df93c8873d8951a593d23a495b1abf006 | Ruby | northofnormal/ruby_fundementals | /Data/Happy_Numbers.rb | UTF-8 | 129 | 2.8125 | 3 | [] | no_license | def happy_number?(a)
10.times do
a = a.to_s.chars.map { |x| x.to_i ** 2 }.inject(:+)
return true if a == 1
end
false
end
| true |
2cf6301aaf888a7244a39f336f802a94339a60ba | Ruby | digideskio/icast | /app/models/xiph/directory.rb | UTF-8 | 293 | 2.578125 | 3 | [] | no_license | require 'nokogiri'
require 'open-uri'
class Xiph::Directory
attr_reader :path, :xml
def initialize(path)
@path = path
@xml = Nokogiri::XML(open(path))
end
def each
xml.xpath('//directory/entry').each do |xml_node|
yield Xiph::Entry.new(xml_node)
end
end
end
| true |
11094a6821ef687afab47fa113e60827836d3980 | Ruby | bradx3/fundation | /app/models/deposit_template.rb | UTF-8 | 1,323 | 2.59375 | 3 | [] | no_license | class DepositTemplate < ActiveRecord::Base
validates_presence_of :name
validates_uniqueness_of :name, :scope => :user_id
belongs_to :user
validates_presence_of :user
has_many :deposit_template_fund_percentages, :order => "id asc", :dependent => :destroy
accepts_nested_attributes_for :deposit_template_fund_percentages
validate :percentages_add_up
def init_all_fund_percentages
funds = user.family.funds.active
percentages = self.deposit_template_fund_percentages
set_funds = percentages.map { |d| d.fund }
(funds - set_funds).each do |acc|
percentages.build(:percentage => 0, :fund => acc)
end
end
def allocated_percentage
deposit_template_fund_percentages.inject(0) do |total, dtfp|
total += dtfp.percentage
end
end
# Applies the given deposit to use this templates percentages
def apply(deposit)
deposit.fund_transactions.each do |ft|
template_value = deposit_template_fund_percentages.detect { |dtfp| dtfp.fund == ft.fund }
if template_value
ft.percentage = template_value.percentage
end
end
end
private
def percentages_add_up
allocated = allocated_percentage
if allocated > 0 and allocated != 100.0
errors.add(:base, "All money must be allocated in a deposit template")
end
end
end
| true |
0e37104fcbd97924857476229f83204955e7be43 | Ruby | Edward-Phillips/Bookmark_manager | /lib/bookmark.rb | UTF-8 | 1,013 | 3.015625 | 3 | [] | no_license | require 'pg'
require 'uri'
class Bookmark
attr_reader :name, :address, :id
def initialize(who: "nobody", where: "nowhere", id:)
@id = id
@name = who
@address = where
end
def self.all
self.connect
rs = @con.exec "SELECT * FROM bookmarks"
rs.map { |row| Bookmark.new(where: row['url'], who: row['title'], id: row['id'])}
end
def self.create(url:, title:)
if self.good_url?(url)
self.connect
@con.exec("INSERT INTO bookmarks (url, title) VALUES('#{url}','#{title}')")
end
end
def self.connect
if ENV['RACK_ENV'] == 'test'
@con = PG.connect :dbname => 'bookmark_manager_test', :user => 'edwardphillips'
else
@con = PG.connect :dbname => 'bookmark_manager', :user => 'edwardphillips'
end
end
def self.good_url?(url)
uri = URI.parse(url)
uri.is_a?(URI::HTTP) && !uri.host.nil?
rescue URI::InvalidURIError
false
end
def self.delete(id)
self.connect
@con.exec("DELETE FROM bookmarks WHERE id = '#{id}'")
end
end | true |
e75570de3ea004cc9ff50733037b3d0acde7fb3a | Ruby | growth-nirvana/events-ruby | /spec/helpers/runscope_client.rb | UTF-8 | 978 | 2.640625 | 3 | [
"MIT"
] | permissive | require 'faraday'
require 'pmap'
class RunscopeClient
def initialize(api_token)
headers = { 'Authorization' => "Bearer #{api_token}" }
@conn = Faraday.new('https://api.runscope.com', headers: headers)
end
def requests(bucket_key)
with_retries(3) do
response = @conn.get("/buckets/#{bucket_key}/messages", count: 10)
raise "Runscope error. #{response.body}" unless response.status == 200
message_uuids = JSON.parse(response.body)['data'].map { |message|
message.fetch('uuid')
}
message_uuids.pmap { |uuid|
response = @conn.get("/buckets/#{bucket_key}/messages/#{uuid}")
raise "Runscope error. #{response.body}" unless response.status == 200
JSON.parse(response.body).fetch('data').fetch('request')
}
end
end
private
def with_retries(max_retries)
retries ||= 0
yield
rescue StandardError => e
retries += 1
retry if retries < max_retries
raise e
end
end
| true |
6520101130131ff88f0db7eae4e09d029d3e7509 | Ruby | felipeclopes/pontueme | /app/models/coupon.rb | UTF-8 | 413 | 2.578125 | 3 | [] | no_license | class Coupon < ActiveRecord::Base
belongs_to :benefit
belongs_to :user
belongs_to :card
def self.generate_code
code = ''
while code.blank? or Coupon.find_by_code(code)
code = String.random_alphanumeric(8)
end
code
end
private
def String.random_alphanumeric(size=16)
chars = ('a'..'z').to_a + ('A'..'Z').to_a
(0...size).collect { chars[Kernel.rand(chars.length)] }.join
end
end
| true |
b1591aa30b49936891913519fe37f37dc0e4fc30 | Ruby | topdan/memory_record | /test/crud_test.rb | UTF-8 | 2,422 | 2.6875 | 3 | [] | no_license | require 'helper'
class CrudTest < Test::Unit::TestCase
include ClassHelper
define_classes %(
class Post < MemoryRecord::Base
attribute.integer :id, auto: true
attribute.string :title
attribute.integer :comments_count
end
)
test 'only create when saved' do
@post = Post.new(title: 'foo')
assert_equal 0, Post.count
@post.save
assert_equal 1, Post.count
end
test 'only update when saved' do
@post = Post.create!(title: 'foo')
@post.title = 'hi'
assert_equal 'foo', Post.first.title
@post.save
assert_equal 'hi', Post.first.title
end
test 'only update changed attributes' do
@post = Post.create!(title: 'foo')
@post.table.expects(:update).with(@post.send(:row), 'comments_count' => 1)
@post.comments_count = 1
@post.save!
end
test 'destroy' do
@post = Post.create!
assert_equal 1, Post.count
@post.destroy
assert_equal 0, Post.count
end
test 'delete' do
@post = Post.create!
assert_equal 1, Post.count
@post.delete
assert_equal 0, Post.count
end
test 'destroy_all' do
@post1 = Post.create!
@post2 = Post.create!
assert_equal 2, Post.count
Post.destroy_all
assert_equal 0, Post.count
end
test 'delete_all' do
@post1 = Post.create!
@post2 = Post.create!
assert_equal 2, Post.count
Post.delete_all
assert_equal 0, Post.count
end
test 'update_all' do
@post1 = Post.create!
@post2 = Post.create!
assert_equal 2, Post.update_all(title: 'Foo', comments_count: 1)
assert_equal [@post1, @post2], Post.where(title: 'Foo', comments_count: 1).all
end
test 'new, save, edit treats persisted data properly' do
@post = Post.new(title: 'Bar')
assert_false @post.persisted?
@post.save!
assert_true @post.persisted?
@post.title = 'Foo'
assert_equal 'Foo', @post.title
assert_equal 'Bar', Post.find(@post.id).title
end
test 'change tracking' do
@post = Post.new(title: 'Bar')
assert_true @post.changed?
assert_equal %w(title), @post.changed
assert_equal({'title' => [nil, 'Bar']}, @post.changes)
@post.save
assert_false @post.changed?
assert_equal [], @post.changed
assert_equal({}, @post.changes)
assert_equal({}, Post.first.changes)
end
end
| true |
6ddb61ec64179a9ff272850471353cddeeda2cc4 | Ruby | kathirvalavan/data_type_validator | /spec/common_helper.rb | UTF-8 | 299 | 2.59375 | 3 | [
"MIT"
] | permissive | module CommonHelper
def get_sample_value(type)
case type
when :string
['sample1', 'sample2', 'sample3', 'sample4'].sample
when :integer
[1, 2, 3, 4].sample
when :float
[1.12, 2.12, 3.12, 4.12].sample
when :boolean
[true, false].sample
end
end
end
| true |
85be0b849a1b204e16d7956276e54404351c6d28 | Ruby | hessammehr/RubyMeep | /kpoint.rb | UTF-8 | 311 | 2.96875 | 3 | [] | no_license | module MEEP
class KPoint
attr_accessor :freqs, :k
def initialize k, freqs
@k = k
@freqs = freqs
end
# String representation of k-point
# e.g. k-point at (0, 0, 0)
def to_s
"k-point at k=(#{k[0]}, #{k[1]}, #{k[2]}) omega = #{freqs.to_s[1..-2]}"
end
end
end
| true |
f8dc10dae7458cd3df2fa867ae41bc346ee34d47 | Ruby | kopylovvlad/easy_captcha | /lib/easy_captcha/espeak.rb | UTF-8 | 1,562 | 2.90625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | module EasyCaptcha
# espeak wrapper
class Espeak
# generator for captcha images
def initialize(&block)
defaults
yield self if block_given?
end
# set default values
def defaults
@amplitude = 80..120
@pitch = 30..70
@gap = 80
@voice = nil
end
attr_writer :amplitude, :pitch, :gap, :voice
# return amplitude
def amplitude
if @amplitude.is_a? Range
@amplitude.to_a.sort_by { rand }.first
else
@amplitude.to_i
end
end
# return amplitude
def pitch
if @pitch.is_a? Range
@pitch.to_a.sort_by { rand }.first
else
@pitch.to_i
end
end
def gap
@gap.to_i
end
def voice
if @voice.is_a? Array
v = @voice.sort_by { rand }.first
else
v = @voice
end
v.try :gsub, /[^A-Za-z0-9\-\+]/, ""
end
# generate wav file by captcha
def generate(captcha, wav_file)
# get code
if captcha.is_a? Captcha
code = captcha.code
elsif captcha.is_a? String
code = captcha
else
raise ArgumentError, "invalid captcha"
end
# add spaces
code = code.each_char.to_a.join(" ")
cmd = "espeak -g 10"
cmd << " -a #{amplitude}" unless @amplitude.nil?
cmd << " -p #{pitch}" unless @pitch.nil?
cmd << " -g #{gap}" unless @gap.nil?
cmd << " -v '#{voice}'" unless @voice.nil?
cmd << " -w #{wav_file} '#{code}'"
%x{#{cmd}}
true
end
end
end
| true |
8a5cf11e60fc4960b982335784bd57ddc2ad4736 | Ruby | leedc0/tic-tac-toe-rb-online-web-sp-000 | /lib/tic_tac_toe.rb | UTF-8 | 3,572 | 4.28125 | 4 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # Define your WIN_COMBINATIONS constant
WIN_COMBINATIONS = [
[0,1,2], # Top row
[3,4,5], # Middle row
[6,7,8], # Bottom row
[0,3,6], # First column
[1,4,7], # Middle column
[2,5,8], # Last column
[0,4,8], # Left diagonal
[2,4,6] # Right diagonal
]
# Define display_board that accepts a board and prints out the current state.
def display_board(board)
puts " #{board[0]} | #{board[1]} | #{board[2]} "
puts "-----------"
puts " #{board[3]} | #{board[4]} | #{board[5]} "
puts "-----------"
puts " #{board[6]} | #{board[7]} | #{board[8]} "
end
# The #input_to_index method will take the user's input ("1"-"9") and
# convert it to the index of the board array (0-8).
def input_to_index(input)
input = input.to_i - 1
end
# The #move method takes in three arguments; (1) board array, (2) index in the
# board array they player wants to fill and (3) player's character ("X" or "O")
def move(board, input, value)
board[input] = value
end
# The #position_taken? method will evaluate player selected position against Tic
# Tac Toe board and checks whether or not the index on board array is occupied.
def position_taken?(board, index)
if board[index] == " " || board[index] == "" || board[index] == nil
return false
elsif board[index] == "X" || board[index] == "O"
return true
end
end
# The #valid_move? method accepts a board and an index to check and returns true
# if the move is valid and false or nil if not.
def valid_move?(board, index)
if index.between?(0,8) && !position_taken?(board, index)
return true
end
end
#
def turn(board)
puts "Please enter 1-9:"
input = gets.strip
index = input_to_index(input)
if valid_move?(board, index)
move(board, index, current_player(board))
display_board(board)
else
puts "invalid"
turn(board)
end
end
# Method that tracks turns played
def turn_count(board)
turn = 0
board.each do |space|
if space == "X" || space == "O"
turn += 1
end
end
return turn
end
# The #current_player method sets #turn_count method to 'turn' to determine if
# it is "X" or "O" turns and returns "X" if turn is even index or "O" for odd index
def current_player(board)
turn = turn_count(board)
turn = turn.even? ? "X" : "O"
end
#
def won?(board)
WIN_COMBINATIONS.each do | index | # iterate over WIN_COMBINATIONS collection to return value #index array
if index.all? { |i| board[i] == "X" } # iterate through each element of each WIN_COMBINATIONS array and return array's (#index) with #all? "X"
return index # return the 3 element array (#index) with "X" representing the winning combination
elsif index.all? { |i| board[i] == "O"} # iterate through each element of each WIN_COMBINATIONS array and return array's (#index) with #all? "O"
return index # return the 3 element array (#index) with "O" representing the winning combination
end
end
false # return false when 3 element array (#index) does not represent winning combination
end
def full?(board)
board.all? do |i|
i == "X" || i == "O"
end
end
def draw?(board)
!won?(board) && full?(board)
end
def over?(board)
won?(board) || draw?(board)
end
def winner(board)
if (!full?(board) || draw?(board)) && !won?(board)
return nil
elsif (board[won?(board)[0]] == "X")
return "X"
elsif (board[won?(board)[0]] == "O")
return "O"
end
end
#
def play(board)
until over?(board)
turn(board)
end
if won?(board)
puts "Congratulations #{winner(board)}!"
elsif draw?(board)
puts "Cat's Game!"
end
end
| true |
856f59ff2f4d352135780c831eed4be72cb786ee | Ruby | ctrlaltpat-flatiron-work/reverse-each-word-london-web-091718 | /reverse_each_word.rb | UTF-8 | 323 | 3.5625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def reverse_each_word(sentence)
# words = sentence.split(" ")
# words_reversed = []
# words.each do |word|
# words_reversed << word.reverse
# end
# words_reversed.join(" ")
words_reversed = []
sentence.split(" ").collect do |word|
words_reversed << word.reverse
end
words_reversed.join(" ")
end | true |
9df7f5a8f2149fe4f5248e34b8c3ab6d98799f63 | Ruby | shock/vitalsigns | /lib/vital_signs/config.rb | UTF-8 | 982 | 2.765625 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | module VitalSigns
class Config
attr_accessor :sensors
class << self
def parse_from_string config_string, filename="String", starting_line_number=1
config = new
config.instance_eval(config_string, filename, 1)
config
end
def parse_from_file filename
config_string = File.read(filename)
parse_from_string config_string, filename, 1
end
end
def initialize
@sensors = {}
end
private
def method_missing(method, *args, &block)
type = method
sensor_class = get_sensor_class(type)
sensor = sensor_class.new *args, &block
@sensors[type] ||= []
@sensors[type] << sensor
end
def get_sensor_class type
sensor_classname = type.to_s.camelcase
begin
sensor_class = eval("VitalSigns::Sensors::#{sensor_classname}")
rescue NameError
raise "#{type} is not a valid sensor type."
end
end
end
end
| true |
74ff0d189ae0388ebf81670ffab25b50aa2eb6ec | Ruby | ohmie/LutheranHymnody | /ruby/tlh.rb | UTF-8 | 2,801 | 3.078125 | 3 | [] | no_license | require 'nokogiri'
require 'open-uri'
words = Hash.new(0)
dictionary = Hash.new();
def add_word(word, words, file)
return if word == nil
word.gsub!(/[“”—,;:\*\.!?]/,'')
word.gsub!(/’s$/, '')
word.gsub!(/s’$/, 's')
words[word] += 1
#print word, " ", file, "\n" if word.include? "reconciled"
#print word, " ", file, "\n" if word == "chast’ning"
#print word, " ", file, "\n" if word.include? "reared"
#Fix words for 251
end
def add_words(line, words, file)
line.downcase.split(' ').each do |word|
if word.include? "—" then
add_word(word.split('—')[0], words, file)
add_word(word.split('—')[1], words, file)
elsif word.include? "-" then
add_word(word.split('-')[0], words, file)
add_word(word.split('-')[1], words, file)
else
add_word(word, words, file)
end
end
end
files = Dir["tlh/tlh???.txt"].each do |file|
title = nil
verse = nil
File.open(file, "r:utf-8").each do |line|
line.strip!
next if line == ""
if title == nil && /^"(.+)"$/ =~ line then
title = $1
add_words(title, words, file)
end
if /^\(St\. Louis: / =~ line then
verse = 1
elsif /^(\d+)\. (.*)$/ =~ line then
verse = $1
add_words($2, words, file)
elsif /\_{5}/ =~ line then
verse = nil
elsif verse != nil
add_words(line, words, file)
end
end
end
File.open("dictionary.txt", "r:utf-8").each do |line|
if /^(.*)->(.*)$/ =~ line then
dictionary[$1] = $2;
end
end
words.sort_by{|k,v| v}.each {|k,v|
#if !dictionary[k] && !k.include?("’") then
# ##doc = Nokogiri::HTML(open("http://www.thefreedictionary.com/" + k))
# ##list = doc.xpath("//td//span[@class='hw']/text()")
# doc = Nokogiri::HTML(open("http://dictionary.reference.com/browse/" + k))
# list = doc.xpath("//div[@class='header']/h2[@class='me']/text()")
# word = list[0].to_s
#
# if word && word != "" then
# print k, "->", word.gsub(/·/, " -- "), "\n"
# STDOUT.flush
# end
# if word.gsub(/·/, '') == k then
# print k, "->", word.gsub(/·/, " -- "), "\n"
# STDOUT.flush
# elsif word.downcase.gsub(/·/, '') == k then
# print k, "->", word.downcase.gsub(/·/, " -- "), "\n"
# STDOUT.flush
#elsif (word.gsub(/·/, '') + 'ed') == k then
# print k, "->", (word.gsub(/·/, " -- ") + 'ed'), "\n"
# STDOUT.flush
#elsif (word.gsub(/·/, '').gsub(/e$/, '') + 'ed') == k then
# print k, "->", (word.gsub(/·/, " -- ").gsub(/e$/, '') + 'ed'), "\n"
# STDOUT.flush
# elsif (word.gsub(/·/, '').gsub(/y$/, '') + 'ier') == k then
# print k, "->", (word.gsub(/·/, " -- ").gsub(/y$/, '') + 'i -- er'), "\n"
# STDOUT.flush
# elsif ('un' + word.gsub(/·/, '')) == k then
# print k, "->", ('un -- ' + word.gsub(/·/, " -- ")), "\n"
# STDOUT.flush
# end
# sleep 1
# end
if !dictionary[k] then
print k, "->", k, "\n"
STDOUT.flush
end
}
| true |
64f9b91891e0dc929ec8025dbf8b8c5026d554ca | Ruby | DrDhoom/RMVXA-Script-Repository | /00_Bug Fixes/Screen Shake Fix.rb | UTF-8 | 1,358 | 2.59375 | 3 | [
"MIT"
] | permissive | #--------------------------------------------------------------------------
# Screen Shake Fix
# Author(s):
# Hiino
#--------------------------------------------------------------------------
# This script is a little bug fix for the Screen shake event command.
# Originally, the "Wait for the end" checkbox was useless, and the game
# interpreter considered it was always checked. Plus, the wait time wasn't
# right and used the "Speed" value instead of "Duration".
# This script fixes both issues.
#
# To use it, simply copy/paste this code in Materials.
#
#--------------------------------------------------------------------------
#==============================================================================
# ** Game_Interpreter
#------------------------------------------------------------------------------
# An interpreter for executing event commands. This class is used within the
# Game_Map, Game_Troop, and Game_Event classes.
#------------------------------------------------------------------------------
class Game_Interpreter
#--------------------------------------------------------------------------
# * Fixed Screen Shake
#--------------------------------------------------------------------------
def command_225
screen.start_shake(@params[0], @params[1], @params[2])
wait(@params[2]) if @params[3]
end
end | true |
65205cd9b5bba4d0065424a3cf9d6721a0c045a5 | Ruby | shilovk/tn | /lesson2/3.rb | UTF-8 | 458 | 4.03125 | 4 | [] | no_license | # frozen_string_literal: true
# 3. Заполнить массив числами фибоначчи до 100
def fibonachi(max_value)
fib = [0, 1]
loop do
value = fib[-1] + fib[-2]
break if value >= max_value
fib << value
end
fib
end
puts fibonachi(100)
puts fibonachi(100)[10]
def fibonachi_of(numbers)
fib = [0, 1]
(2..numbers - 1).each { fib << fib[-1] + fib[-2] }
fib
end
puts fibonachi_of(10)
puts fibonachi_of(10)[10]
| true |
d25d044a162b30aa20023db89033df1ab49e720c | Ruby | estiens/tictactoe | /lib/game_runner.rb | UTF-8 | 1,910 | 3.546875 | 4 | [] | no_license | require_relative "game"
require_relative "human_player"
require_relative "./ai_players/hard_ai"
require_relative "./ai_players/medium_ai"
require_relative "./ai_players/dumb_ai"
require_relative "./ai_players/negamax_ai"
require_relative "io_parser"
X = 1
O = -1
N = 0
class Runner
attr_accessor :game, :board, :parser
def initialize
@board=Board.new
@parser = IoParser.new(@board)
end
def initialize_game
player1 = HumanPlayer.new(@board)
player2 = @parser.get_difficulty_level
@game = Game.new(board,player1,player2,player1)
end
def run_game
# choose_first_player
@game.play_game
end
def simulate_games(simulation_times=1000) #comment out #ask_to_play in game.print_winner_message if you want to simulate games
game_results=Hash.new(0)
simulation_times.times do
game = Game.new
game.player1 = HardAi.new(game.board,1)
game.player2 = HardAi.new(game.board,-1)
game.current_player = game.player1
game.play_game
if game.board.tie?
game_results["tie"] += 1
elsif game.board.winner?
game_results["#{game.player1.class} - X"] += 1 if game.current_player == game.player2
game_results["#{game.player2.class} - 0"] += 1 if game.current_player == game.player1
end
end
puts game_results
end
private
def choose_first_player
end
def choose_difficulty
puts "Would you like to play against an\n[E]asy Opponent, a [M]edium Opponent, or a [H]ard Opponent"
difficulty_choice=gets.chomp.downcase
case difficulty_choice
when "e"
@game.player2 = DumbAi.new(@game.board)
when "m"
@game.player2 = MediumAi.new(@game.board)
when "h"
@game.player2 = HardAi.new(@game.board)
else
puts "Sorry, I need an [E], [M], or [H]"
choose_difficulty
end
end
end
# runner=Runner.new
# runner.simulate_games
| true |
5672c0cf6689206c1375e128d982eb68b8394660 | Ruby | mrarthurwhite/project1_arthur_cli | /lib/actor.rb | UTF-8 | 996 | 2.703125 | 3 | [
"MIT"
] | permissive |
class Actor < Person
attr_accessor :roles, :country
def initialize(attributes)
super(attributes)
attributes.each do |k,v|
self.send("#{k}=",v) if self.respond_to?("#{k}=")
end
@roles=[]
end
def self.create(attributes)
a = Actor.new(attributes)
a.save
a
end
def add_role(character)
@roles<< character unless @roles.include?(character)
end
end
=begin
=> {"id"=>25249,
"url"=>"http://www.tvmaze.com/people/25249/bradley-whitford",
"name"=>"Bradley Whitford",
"country"=>{"name"=>"United States", "code"=>"US", "timezone"=>"America/New_York"},
"birthday"=>"1959-10-10",
"deathday"=>nil,
"gender"=>"Male",
"image"=>
{"medium"=>"http://static.tvmaze.com/uploads/images/medium_portrait/183/459454.jpg",
"original"=>"http://static.tvmaze.com/uploads/images/original_untouched/183/459454.jpg"},
"_links"=>{"self"=>{"href"=>"http://api.tvmaze.com/people/25249"}}}
=end
| true |
889d2ccf07a9a9edec455fa8039074a116e26641 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/hamming/76d9d0ba0925465e99b1b9390fec79c7.rb | UTF-8 | 211 | 3.5 | 4 | [] | no_license | class Hamming
def self.compute(strand1, strand2)
hamming = 0
i = 0
while i < strand1.length && i < strand2.length
if strand1[i] != strand2[i]
hamming += 1
end
i += 1
end
return hamming
end
end
| true |
5fc4a767d68bba2de87605428030112c3515e57e | Ruby | jin/algorithms_and_data_structures.rb | /hackerrank/maximum_subarray.rb | UTF-8 | 790 | 3.53125 | 4 | [] | no_license | # Solution for the maximum subarray problem (both contiguous and non-contiguous versions)
#
# Given a 1D integer array, find a contiguous and non-contiguous block of elements such that their sum is the maximum.
gets.to_i.times do
n = gets.to_i
ints = gets.split.map(&:to_i)
max_non_contiguous_sum = 0
max_contiguous_sum = 0
current_sum = 0
smallest_negative = -10001
ints.each do |i|
max_non_contiguous_sum += i if i > 0
smallest_negative = i if i > smallest_negative
val = current_sum + i
current_sum = val > 0 ? val : 0
max_contiguous_sum = current_sum if current_sum > max_contiguous_sum
end
puts "#{max_contiguous_sum == 0 ? smallest_negative : max_contiguous_sum} #{max_non_contiguous_sum == 0 ? smallest_negative : max_non_contiguous_sum}"
end
| true |
b205493f71b0e098fc7a5680ac70ac723da49ec8 | Ruby | imageoptimiser/abbot-ng | /lib/sproutcore/entries.rb | UTF-8 | 6,183 | 2.75 | 3 | [] | no_license | require "tsort"
Entry = Struct.new(:name, :requires, :source) do
end
# Construct a special Array that uses the Ruby TSort
# module to sort files by their dependencies
module SproutCore
class Entries < Array
include TSort
# TSort requires that tsort_each_node iterates through
# all nodes. Since this is an Array, alias to each
alias tsort_each_node each
class << self
attr_accessor :ext
attr_accessor :locale
attr_accessor :theme
end
LOCALE_MAP = {"en" => "english", "english" => "en"}
# Create a new Entries list through Entries.from_directory
def self.from_directory(dir, target, target_type = :frameworks)
list = new(dir, target, target_type)
list.sort!
end
attr_accessor :statics
def initialize(dir, target, target_type)
@directory = File.expand_path(dir)
@target_dir = "#{@directory}/#{target_type}/#{target}"
@entry_lookup = {}
# make it faster to look up an entry by name, since
# dependencies are Strings
@target = target
@target_type = target_type
@package = File.basename(@directory)
process_files
end
def associate_statics(statics)
@statics = statics
self
end
def process_files
Dir["#{@target_dir}/**/*.#{self.class.ext}"].each do |file|
next if file =~ %r{^#{@target_dir}/(debug|tests)}
source = File.read(file)
requires = source.scan(%r{\b(?:sc_)?require\(\s*['"](.*)['"]\)}).flatten
add Entry.new(file[%r{#{@target_dir}/(.*)\.#{self.class.ext}}, 1], requires, source)
end
end
def inspect
"#<Entries: #{map(&:name).join(", ")}>"
end
def app(app)
@app = app
self
end
def add(entry)
self << entry
@entry_lookup[entry.name] = entry
end
# use combine to mark a target as combinable
def combine(file)
@combine = file
self
end
def compile
@compiled ||= begin
output = inject("") do |output, file|
output << "/* >>>>>>>>>> BEGIN #{file.name}.#{self.class.ext} */\n"
output << "#{file.source}\n"
end
end
end
# sort first by the naming heuristics, then by dependencies
def sort!
# define sorting heuristics in a subclass
end
def content_for(file)
destinations[file]
end
def destinations
@destinations ||= begin
if !any?
results = {}
elsif @combine
results = {"#{destination_root}/#{@combine}" => compile }
else
results = {}
each do |entry|
results["#{destination_root}/#{entry.name}.#{self.class.ext}"] = entry.source
end
results
end
process(results)
end
end
private
def process(results)
results.each do |name, contents|
contents.gsub!(/(sc_static|static_url|sc_target)\(\s*['"](.+)['"]\s*\)/) do |resource|
url = static_or_fallback($2)
if url && url.destination
"url('#{url.destination}')"
else
puts "WARN: static not found: #{$2} (from #{entry.name}"
end
end
end
end
def static_or_fallback(name)
@statics.find_static(name) || @app.find_static(name)
end
# TODO: It seems like this part should be handled by the server, not the Entries
def destination_root
"/static/#{LOCALE_MAP[self.class.locale]}/#{@target}"
end
# TSort requires that tsort_each_child take in a node
# and then yield back once for each dependency.
def tsort_each_child(node)
node.requires.each do |name|
if entry = @entry_lookup[name]
yield entry
else
puts "WARN: #{node.name} required #{name}, but it could not be found"
end
end
end
end
class JavaScriptEntries < Entries
self.ext = "js"
self.locale = "english" # hardcode for now
def destinations
@destinations ||= super.each do |name, contents|
contents.gsub!(/sc_super\(\s*\)/, "arguments.callee.base.apply(this, arguments)")
end
end
def compile
@compiled ||= begin
super << %[\nSC.bundleDidLoad("#{@package}/#{@target}");\n]
end
end
def sort!
sort_by! do |entry|
sort_by = case entry.name
# TODO: Allow preferred filename customization
when %r{^(\w+\.)lproj/strings$} then -3
when "core" then -2
when "utils" then -1
when %r{^(lproj|resources)/.*_page$} then 1
when "main" then 2
else 0
end
frameworks = entry.name =~ /^frameworks/ ? -1 : 0
[frameworks, sort_by, entry.name]
end
replace(tsort)
end
end
class StaticEntries < Entries
StaticEntry = Struct.new(:source, :destination)
self.locale = "english" # hardcode for now
def initialize(*)
@map = {}
super
end
def process_files
Dir["#{@target_dir}/**/*.{gif,jpg,png}"].each do |file|
file =~ %r{^#{@directory}/#{@target_type}/#{@target}/(?:#{self.class.locale}\.lproj\/)?(.*)$}
add_static(file, $1)
end
end
def add_static(source, relative)
# TODO: Deal with non-English locale getting overridden, probably by sorting the statics
# before passing them in for processing
relative =~ %r{^((?:#{self.class.locale}\.lproj|english\.lproj|resources)/)?(images/)?(.*)(\.(gif|jpg|png))$}
destination = "#{destination_root}/#{$3}#{$4}"
entry = StaticEntry.new(source, destination)
@map["#{$2}#{$3}#{$4}"] = entry
@map["#{$3}#{$4}"] = entry
@map["#{$2}#{$3}"] = entry
@map[$3] = entry
end
def find_static(name)
@map[name]
end
end
class CssEntries < Entries
self.ext = "css"
self.locale = "english" # hardcode for now
self.theme = "standard_theme" # hardcode for now
attr_accessor :statics
def sort!
sort_by!(&:name)
end
end
end
| true |
0be960f9b1f6b64d0b07d11c746c55a942dc69bc | Ruby | jenmccarthy/expense_tracker_AR | /spec/expense_spec.rb | UTF-8 | 1,649 | 2.796875 | 3 | [] | no_license | require 'spec_helper'
require 'category'
describe Expense do
it { should validate_presence_of :description }
it { should validate_presence_of :price }
it 'converts the description to capital case' do
expense = Expense.create({description: 'pizza', price: 4.99})
expect(expense.description).to eq 'Pizza'
end
it 'belongs to a category' do
category1 = Category.create({name: 'home', budget: 300})
category2 = Category.create({name: 'work', budget: 500})
expense1 = Expense.create({description: 'gasoline', price: 45.20, category_id: category1.id})
expense2 = Expense.create ({description: 'groceries', price: 30.00, category_id: category1.id})
expect(expense1.category).to eq category1
end
describe 'self.time_period' do
it 'will return all the expenses for a certain time period' do
expense1 = Expense.create({description: 'pizza', price: 5.99, category_id: 1, created_at: '2014-08-20'})
expense2 = Expense.create({description: 'gasoline', price: 40.00, category_id: 2, created_at: '2014-07-01'})
expense3 = Expense.create({description: 'shampoo', price: 12.00, category_id: 3, created_at: '2014-08-13'})
expect(Expense.time_period('2014-08-01', '2014-08-24')).to eq [expense1, expense3]
end
end
it 'will total the monies spent on all expenses' do
expense1 = Expense.create({description: 'pizza', price: 5.99, category_id: 1})
expense2 = Expense.create({description: 'gasoline', price: 40.00, category_id: 2})
expense3 = Expense.create({description: 'shampoo', price: 12.00, category_id: 3})
expect(Expense.total).to eq 57.99
end
end | true |
7f4014128756b169e914ed92f9e3de681016cb0d | Ruby | jackfrostwillbeking/atcoder_sample | /ABC/ruby/061/A.rb | UTF-8 | 173 | 3.1875 | 3 | [] | no_license | A,B,C = gets().chomp.split(' ').map { |n| n.to_i }
exit if !( -100 <= A && A <= 100 && -100 <= B && B <= 100 && -100 <= C && C <= 100 )
puts A <= C && C <= B ? 'Yes' : 'No' | true |
7ae0f5a339c03b31b0cd8d36309dd787ccef6325 | Ruby | playto/ruby-object-attributes-lab-q-000 | /lib/dog.rb | UTF-8 | 173 | 3.046875 | 3 | [] | no_license | class Dog
def name=(name_string)
@name = name_string
end
def name
@name
end
def breed=(breed)
@breed = breed
end
def breed
@breed
end
end | true |
c1b0eee0d26b526288920c1f8bb2008edf7f224f | Ruby | mitchconquer/test-first-ruby | /15_in_words/in_words.rb | UTF-8 | 2,171 | 3.859375 | 4 | [] | no_license | class Fixnum
def in_words(current = self)
places = []
output = ''
if current >= 1_000_000_000_000
trillions = current / 1_000_000_000_000
current = current - (trillions * 1_000_000_000_000)
output += in_words(trillions).to_s + " trillion"
if current > 0
output += ' '
end
end
if current >= 1_000_000_000
billions = current / 1_000_000_000
current = current - (billions * 1_000_000_000)
output += in_words(billions).to_s + " billion"
if current > 0
output += ' '
end
end
if current >= 1_000_000
millions = current / 1_000_000
current = current - (millions * 1_000_000)
output += in_words(millions).to_s + " million"
if current > 0
output += ' '
end
end
if current >= 1_000
thousands = current / 1_000
current = current - (thousands * 1_000)
output += in_words(thousands).to_s + " thousand"
if current > 0
output += ' '
end
end
if current >= 100
hundreds = current / 100
current = current - (hundreds * 100)
output += in_words(hundreds).to_s + " hundred"
if current > 0
output += ' '
end
end
if current >= 20
tens = current / 10
current = current - (tens * 10)
ten_words = {2 => 'twenty', 3 => 'thirty', 4 => 'forty', 5 => 'fifty', 6 => 'sixty', 7 => 'seventy', 8 => 'eighty', 9 => 'ninety'}
output += ten_words[tens].to_s
if current > 0
output += ' ' + in_words(current).to_s
end
elsif current >= 10 && current < 20
tens = current / 10
current = current - (tens * 10)
ten_words = {10 => 'ten', 11 => 'eleven', 12 => 'twelve', 13 => 'thirteen', 14 => 'fourteen', 15 => 'fifteen', 16 => 'sixteen', 17 => 'seventeen', 18 => 'eighteen', 19 => 'nineteen'}
if tens > 1
output += ten_words[tens]
elsif tens == 1
output += ten_words[(tens * 10 ) + current].to_s
end
elsif current < 10 && current > 0
ones = {1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four', 5 => 'five', 6 => 'six', 7 => 'seven', 8 => 'eight', 9 => 'nine'}
output += ones[current].to_s
# current = current - current
elsif current == 0 && current == self
output += 'zero'
end
output
end
end
# puts 10047.in_words | true |
815039b78682f65dde8bc153e02c04d1494ed4e8 | Ruby | grandballoon/ruby-objects-has-many-through-lab-nyc-web-062518 | /lib/appointment.rb | UTF-8 | 271 | 2.859375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require "pry"
class Appointment
@@all = []
attr_reader :occurrence, :patient, :doctor
def initialize (occurrence, patient, doctor)
@occurrence = occurrence
@patient = patient
@doctor = doctor
@@all << self
#binding.pry
end
def self.all
@@all
end
end
| true |
9f21cab66f461818965a3ff067369bae69d5072d | Ruby | Unclerojelio/mazes_for_programmers | /killing_cells.rb | UTF-8 | 330 | 3.078125 | 3 | [] | no_license | require 'grid'
require 'recursive_backtracker'
grid = Grid.new(5, 5)
#orphan the cell in the northwest corner
grid[0, 0].east.west = nil
grid[0, 0].south.north = nil
# ... and the one in the southwest corner
grid[4, 4].west.east = nil
grid[4, 4].north.south = nil
RecursiveBacktracker.on(grid, start_at: grid[1, 1])
puts grid | true |
533fd952f98fa910ebf5607548674f9d66b8034e | Ruby | J-Y/RubyQuiz | /ruby_quiz/quiz81_sols/solutions/Logan Capaldo/hash_to_open_struct2.rb | UTF-8 | 1,097 | 3.296875 | 3 | [
"MIT"
] | permissive | require 'yaml'
require 'ostruct'
class Object
def hash_to_ostruct(visited = [])
self
end
end
class Array
def hash_to_ostruct(visited = [])
map { |x| x.hash_to_ostruct(visited) }
end
end
class Hash
def hash_to_ostruct(visited = [])
os = OpenStruct.new
each do |k, v|
item = visited.find { |x| x.first.object_id == v.object_id }
if item
os.send("#{k}=", item.last)
else
os.send("#{k}=", v.hash_to_ostruct(visited + [ [self, os] ]))
end
end
os
end
end
yaml_source = <<YAML
---
foo: 1
bar:
baz: [1, 2, 3]
quux: 42
doctors:
- William Hartnell
- Patrick Troughton
- Jon Pertwee
- Tom Baker
- Peter Davison
- Colin Baker
- Sylvester McCoy
- Paul McGann
- Christopher Eccleston
- David Tennant
- {w: 1, t: 7}
a: {x: 1, y: 2, z: 3}
YAML
evil_yaml = <<EVIL
---
&verily
lemurs:
unite: *verily
beneath:
- patagonian
- bread
- products
thusly: [1, 2, 3, 4]
EVIL
loaded = YAML.load(yaml_source).hash_to_ostruct
p loaded.bar.doctors.last.w
evil_loaded = YAML.load(evil_yaml).hash_to_ostruct
p evil_loaded.lemurs.beneath
p evil_loaded.lemurs.unite.thusly
| true |
19a3acf465a5ceccf955ec577e6a87b971f36aaf | Ruby | bajwahassan/badges-and-schedules-onl01-seng-ft-030220 | /conference_badges.rb | UTF-8 | 813 | 3.9375 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def badge_maker(name)
return "Hello, my name is #{name}."
end
# ----------------------------------------------------------------
def batch_badge_creator(array)
batch_messages = []
array.each do |name|
batch_messages.push("Hello, my name is #{name}.")
end
return batch_messages
end
# ----------------------------------------------------------------
def assign_rooms(array)
assigned = []
counter = 1
array.each do |name|
assigned.push("Hello, #{name}! You'll be assigned to room #{counter}!")
counter += 1
end
return assigned
end
# ----------------------------------------------------------------
def printer(array)
batch_badge_creator(array).each do |element|
puts element
end
assign_rooms(array).each do |element|
puts element
end
end
| true |
6535a2555446b50e0d774f507a1df96ae048cadb | Ruby | krishnau2/personal_expense_tracking | /app/services/transaction_creator.rb | UTF-8 | 2,315 | 2.890625 | 3 | [] | no_license | class TransactionCreator
EXPENSE = 'Expense'
INCOME = 'Income'
TRANSFER = 'Transfer'
def initialize(transaction_data)
@transaction_data = transaction_data
@expense_transactions = @transaction_data["transactions"]
@source_account = Account.find(@transaction_data["source_account_id"])
@transaction_date = @transaction_data["transaction_date"]
@destination_account = nil
end
def generate_transaction_id
DateTime.now.to_i
end
def create
AccountTransaction.transaction do
@expense_transactions.each do |expense_entry|
@destination_account = Account.find(expense_entry["destination_account_id"])
create_expense_transactions(expense_entry)
end
end
end
def create_expense_transactions(expense_entry)
transaction_id = generate_transaction_id
AccountTransaction.create_credit_transaction({
transaction_id: transaction_id,
account: @source_account,
transaction_date: @transaction_date,
comments: expense_entry["comments"],
amount: expense_entry["amount"]
})
AccountTransaction.create_debit_transaction({
transaction_id: transaction_id,
account: @destination_account,
transaction_date: @transaction_date,
comments: expense_entry["comments"],
amount: expense_entry["amount"]
})
end
# def perform_account_transaction
# Transaction.transaction do
# @form_transaction_data.each do |form_transaction|
# @destination_account = Account.find(form_transaction["destination_account_id"])
# if form_transaction["action_type"] == "spending"
# perform_account_spending_transaction(form_transaction["amount"])
# elsif form_transaction["action_type"] == "recieving"
# perform_account_recieving_transaction(form_transaction["amount"])
# elsif form_transaction["action_type"] == "transfer"
# perform_account_transfer_transaction(form_transaction["amount"])
# end
# end
# end
# end
# def perform_account_spending_transaction(amount)
# @source_account.credit(amount)
# @destination_account.debit(amount)
# end
# def perform_account_recieving_transaction(amount)
# @destination_account.credit(amount)
# @source_account.debit(amount)
# end
# def perform_account_transfer_transaction(amount)
# @source_account.credit(amount)
# @destination_account.debit(amount)
# end
end | true |
a5de8e54425dfcab3bdb8feafc6ba309497500d9 | Ruby | shouxingzi/chat-app | /app/controllers/application_controller.rb | UTF-8 | 1,657 | 2.578125 | 3 | [] | no_license | # 全てのコントローラーが継承するファイル
# deviseのコントローラーはここに記述する。なぜならば、deviseのコントローラーはGem内に記述されているため編集ができないから
class ApplicationController < ActionController::Base
before_action :authenticate_user!
# authenticate_user!
# ログイン状態によって表示するページを切り替えるdeviseのメソッド。処理が呼ばれた段階でユーザーがログインしていなければ、そのユーザーをログイン画面に遷移させる。
# before_actionで呼び出すことでアクションを実行する前にログインしていなければログイン画面に遷移させられる。
before_action :configure_permitted_parameters, if: :devise_controller?
# deviseに関するコントローラーの処理のみ、実行される前にconfigure_permitted_parameterが実行される
private
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
# sign_up(新規登録の処理)に対して、name というキーのパラメーターを新たに許可
end
end
# devise_parameter_sanitizer メソッドはdeviseでユーザー登録する場合に使用でき、特定のカラムを許容するメソッド
# nameカラムは既存のカラムに対して独自で追加したカラムなのでこのメソッドを使う
# 第一引数の処理名 sign_up は新規登録の処理を行うとき、sign_in はログインの処理を行う時、account_updateはアカウント情報更新の処理を行うときに用いられる。
| true |
f63a6840783fb2276da1d5a53ac816776c9a6759 | Ruby | kristianmandrup/on_the_map | /spec/on_the_map/geo_locatable_spec.rb | UTF-8 | 1,011 | 2.515625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | require 'spec_helper'
require 'on_the_map/geo_locatable'
class MyGeoCodableAddress
include Mongoid::Document
include OnTheMap::GeoLocatable
end
describe OnTheMap::GeoLocatable do
subject { address }
context 'empty address' do
let(:address) { MyGeoCodableAddress.create street: '', city: '' }
it 'should have a blank full address' do
expect(subject.address.full).to be_blank
end
it 'should not be geolocatable' do
expect(subject.geolocatable?).to be false
end
it 'should not be geocoded?' do
expect(subject.geocoded?).to be false
end
end
context 'invalid address' do
let(:address) { MyGeoCodableAddress.create street: 'blip blab', city: 'blop' }
it 'should be geolocatable' do
expect(subject.geolocatable?).to be_true
end
it 'should not calculate a position' do
expect(subject.position.to_a).to be_blank
end
it 'should not be geocoded?' do
expect(subject.geocoded?).to be false
end
end
end | true |
98d141b00d0f8b299dae8144eb9e0c6897ca93ac | Ruby | chantal66/jungle_beat | /test/jungle_beat_test.rb | UTF-8 | 888 | 2.984375 | 3 | [] | no_license | require 'minitest/autorun'
require 'minitest/pride'
require './lib/jungle_beat'
require 'pry'
class JungleBeatTest < Minitest::Test
def test_head_knows_nil
jb = JungleBeat.new
assert_equal nil, jb.list.head
end
def test_can_it_append
jb = JungleBeat.new
result = jb.append("deep doo ditt")
assert_equal 'deep doo ditt', result
assert_equal 'deep', jb.list.head.data
assert_equal 'doo', jb.list.head.next_node.data
end
def test_can_it_append_many_many_things
jb = JungleBeat.new
jb.append("deep doo ditt")
jb.append("woo hoo shu")
assert_equal 6, jb.count
end
def test_it_can_play
jb = JungleBeat.new
jb.append("deep doo ditt woo hoo shu")
jb.play
assert_equal 'deep doo ditt woo hoo shu', jb.list.to_string
# assert_equal 500 , jb.rate
assert_equal 6, jb.count
end
end | true |
3e9e7a3050b42806eac666a68e764cbabf8d8f0e | Ruby | ksmithbaylor/GPAgent | /app/models/student.rb | UTF-8 | 465 | 2.765625 | 3 | [] | no_license | require 'semester'
class Student
include DataMapper::Resource
property :id, Serial
property :name, String
has n, :semesters
def gpa
attempted_hours = 0
grade_points = 0
@semesters.each do |semester|
semester.courses.each do |course|
attempted_hours += course.hours if course.counts
grade_points += course.quality_points if course.counts
end
end
(grade_points / attempted_hours).round 3
end
end | true |
0689fad92ba03a3d7f5e86dcc5a6c84d80aae093 | Ruby | nachiket87/codeforces | /282A.rb | UTF-8 | 179 | 3.5 | 4 | [] | no_license | n = gets.to_i
x = 0
while(n>0)
n-=1
s = gets.chomp
if s[0] == "+" || s[-1] == "+"
x+=1
elsif s[0] == "-" || s[-1] == "-"
x-=1
end
end
puts x
| true |
751945e41b5151d88031f1605d881996c803c4a0 | Ruby | T-o-s-s-h-y/Learning | /Ruby/exercises/app/mission_d_192.rb | UTF-8 | 203 | 3.203125 | 3 | [] | no_license | =begin
文字列に感嘆符を付与する。
=end
class MissionD192
def run
# 対象の文字列
str = $stdin.gets.chomp!
# 感嘆符を付与して出力
puts "#{str}!"
end
end
| true |
f78abf9465683f098fda55edc03fca76526399f4 | Ruby | copypastel/attr_private | /lib/attr_private/active_record_base.rb | UTF-8 | 1,721 | 2.609375 | 3 | [
"MIT"
] | permissive | module ActiveRecord
class Base
class << self
def attr_private(*attributes)
attr_protected(*attributes)
write_inheritable_attribute(:attr_private,Set.new(attributes.map { |a| a.to_s }) + (private_attributes || []))
end
def private_attributes
read_inheritable_attribute(:attr_private)
end
end
alias old_attributes attributes
def attributes
attrs = old_attributes
reject_private_attributes!(attrs) unless allow_private_access?
attrs
end
alias old_attributes_before_type_cast attributes_before_type_cast
def attributes_before_type_cast
attrs = old_attributes_before_type_cast
reject_private_attributes!(attrs) unless allow_private_access?
attrs
end
private
def reject_private_attributes!(attrs)
return attrs if self.class.private_attributes.nil?
self.class.private_attributes.each do |attr|
attrs.reject! { |key,value| key.to_s == attr.to_s }
end
attrs
end
def allow_private_access?
# Check to see if the second caller (because the first would be the method that called this function)
# was invoked from within the allowable PRIVATE_ACCESSORS list
# If the third caller is in method_missing then it is auto_generating code and the fourth caller must be checked
file = if caller(3).first.split(':').last == "in `method_missing'"
caller(4).first.split(':').first.split('/').last
else
caller(2).first.split(':').first.split('/').last
end
access = ActiveRecord::PRIVATE_ACCESSORS + ["#{self.class.name.to_s.underscore}.rb"]
access.include? file
end
end
end
| true |
6d2200858f0c406b3a2a9e7abaa835b34dae4e0f | Ruby | jdejong/galactic-senate | /lib/galactic-senate/delegation.rb | UTF-8 | 2,832 | 2.78125 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module GalacticSenate
class Delegation
SUPREME_CHANCELLOR_INTERVAL = 10
SENATOR_INTERVAL = 30
RAND_INTERVAL = 15
KEY = "galactic-senate-supreme-chancellor"
def initialize
@running = true
@supreme_chancellor_timeout = 0
end
def self.instance
@galactic_senate ||= GalacticSenate::Delegation.new
end
def self.supreme_chancellor?
instance.supreme_chancellor?
end
def supreme_chancellor?
( @supreme_chancellor_timeout > Time.now.to_f )
end
alias_method :leader?, :supreme_chancellor?
class << self
alias_method :leader?, :supreme_chancellor?
end
def debate
vote_of_no_confidence
timer_task = Concurrent::TimerTask.new(execution_interval: interval) do |task|
begin
vote_now
task.execution_interval = interval
rescue => e
GalacticSenate.config.logger.error "GalacticSenate::Delegation.debate - #{e.message}"
GalacticSenate.config.logger.error "GalacticSenate::Delegation.debate - #{e.backtrace.inspect}"
end
end
timer_task.execute
end
def vote_now
if supreme_chancellor?
if update_supreme_chancellor
@supreme_chancellor_timeout = Time.now.to_f + SENATOR_INTERVAL
else
@supreme_chancellor_timeout = 0
fire_event(:ousted)
end
else
vote_of_no_confidence
end
end
def vote_of_no_confidence
if elect_me_supreme_chancellor?
@supreme_chancellor_timeout = Time.now.to_f + SENATOR_INTERVAL
fire_event(:elected)
else
@supreme_chancellor_timeout = 0
end
end
def fire_event(event, val = nil)
GalacticSenate.config.events[event].each do |block|
begin
block.call(val)
rescue => e
GalacticSenate.config.logger.error "GalacticSenate::Delegation.fire_event - #{e.message}"
GalacticSenate.config.logger.error "GalacticSenate::Delegation.fire_event - #{e.backtrace.inspect}"
end
end
end
def interval
supreme_chancellor? ? SUPREME_CHANCELLOR_INTERVAL : SENATOR_INTERVAL
end
private
def get_supreme_chancellor
GalacticSenate.config.redis.call("get",KEY)
end
def delete_supreme_chancellor
GalacticSenate.config.redis.call("del",KEY)
end
def expire_supreme_chancellor
GalacticSenate.config.redis.call("expire",KEY, SENATOR_INTERVAL)
end
def elect_me_supreme_chancellor?
val = GalacticSenate.config.redis.set(KEY, GalacticSenate.whoami, ex: SENATOR_INTERVAL, nx: true)
val
end
def update_supreme_chancellor
( get_supreme_chancellor == GalacticSenate.whoami ? expire_supreme_chancellor : 0 ) != 0
end
end
end | true |
646e1e789dd1aa6557a7473313f1442e4fe86ea6 | Ruby | mattsp1290/hipchatbot | /app/classes/reply_handler.rb | UTF-8 | 743 | 2.609375 | 3 | [
"MIT"
] | permissive | class ReplyHandler
def self.process(event)
replies = Reply.all
handled = false
replies.each do |reply|
if ((event.room == reply.room.to_i) || (reply.room == '') || (reply.room.nil?)) && (not handled)
if (reply.mention_name == '' || reply.mention_name.nil?) || (reply.mention_name == event.mention_name)
handled = process_reply(event, reply)
end
end
end
return handled
end
def self.process_reply(event, reply)
reply.keywords.each do |keyword|
if event.message.downcase.include? keyword.downcase
gif = ReplyGifHelper.gif(reply.tags)
HipChatHelper.send_message(event.room, gif) unless (gif == '') || gif.nil?
return true
end
end
return false
end
end | true |
8bf827274b8112dbd1c4253f649a25d77275eddd | Ruby | MayOneUS/mayday-2.0-backend | /spec/lib/integration/here_spec.rb | UTF-8 | 1,519 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | require 'rails_helper'
describe Integration::Here do
describe ".geocode_address" do
context "good address" do
subject(:response) do
Integration::Here.geocode_address( address:'2020 Oregon St',
city: 'Berkeley',
state: 'CA',
zip: '94703' )
end
it "returns address" do
expect(response[:address]).to eq '2020 Oregon St, Berkeley, CA 94703, United States'
end
it "returns coordinates" do
expect(response[:coordinates]).to eq [37.8570709, -122.2673874]
end
it "returns full confidence" do
expect(response[:confidence]).to eq 1
end
end
context "insufficient address" do
subject(:response) do
Integration::Here.geocode_address(address: '2020 Oregon St')
end
it "returns address" do
expect(response[:address]).to eq 'Oregon St, Fall River, MA 02720, United States'
end
it "returns moderate confidence" do
expect(response[:confidence]).to be_between(0, 1).exclusive
end
end
context "bad address" do
subject(:response) do
Integration::Here.geocode_address(address: '2020 Oregon St', zip: 'bad')
end
it "returns no address" do
expect(response[:address]).to be_nil
end
it "returns no confidence" do
expect(response[:confidence]).to be_nil
end
end
end
end | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.