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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
e9d7b20a1eb9b833019406c01f19d4ecdbfc5dfc | Ruby | begin-again/code-puzzles | /Ruby/even-or-odd.rb | UTF-8 | 172 | 3.03125 | 3 | [
"Unlicense"
] | permissive | # Even Numbers
myfile = ARGV[0]
if File.exists?(myfile)
File.open(myfile) do |file|
file.each_line do |line|
puts line.to_i % 2 == 0 ? 1 : 0
end
end
end
| true |
5c1c0d9eae8fabb7c34430c51b84556e03ca23c9 | Ruby | phuzisham/parcel_calc | /lib/parcel.rb | UTF-8 | 767 | 3.171875 | 3 | [
"MIT"
] | permissive | class Parcel
def initialize(length,width,depth)
@length = length.to_i
@width = width.to_i
@depth = depth.to_i
# @weight = weight.to_i
end
def volume
volume = @length * @width * @depth
return volume
end
def cost_to_ship(distance,speed)
distance = distance.to_i
cost = volume/3
if distance < 20
if speed.downcase.to_s === "air"
cost += volume/4
end
if speed.downcase === "ground"
cost += volume/6
end
end
if distance >= 20
if speed.downcase.to_s === "air"
cost += (volume/4 * distance/4)
end
if speed.downcase === "ground"
cost += (volume/6 * distance/4)
end
end
return cost
end
def parcel_calculator
end
end
| true |
df3e8fbc6b8bef631ab1878206ba63034d5178f0 | Ruby | yhara/unbabel | /ruby/spec/spec_java.rb | UTF-8 | 454 | 2.65625 | 3 | [] | no_license | $LOAD_PATH << File.expand_path("../lib", File.dirname(__FILE__))
require 'unbabel'
describe "Unbabel" do
it "should call Java function" do
fib = Unbabel::Java.new((<<-EOD).unindent)
// fib :: Int -> Int
public static int fib (int x) {
switch(x){
case 0: return 0;
case 1: return 1;
default:
return fib(x-2) + fib(x-1);
}
}
EOD
fib[10].should == 55
end
end
| true |
b4bf09ae8f2728569d54e372e4028aa6c6e4052e | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/raindrops/db31706d287242699db2b551a93fcccc.rb | UTF-8 | 427 | 3.46875 | 3 | [] | no_license | require 'prime'
class Raindrops
def self.convert(drop)
Raindrop.new(drop).make_noise()
end
end
class Raindrop
NOISES = {3 => "Pling",
5 => "Plang",
7 => "Plong"}
def initialize(drop)
@drop = drop
end
def make_noise
noise = ""
Prime.each(@drop) do |prime|
noise += NOISES[prime].to_s if @drop % prime == 0
end
noise.empty? ? @drop.to_s : noise
end
end
| true |
cab0d063fa2454be3c378efa08450d4f4b9037f0 | Ruby | jimherz/devise_security_extension | /lib/devise_security_extension/models/secure_validatable.rb | UTF-8 | 2,661 | 2.546875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | module Devise
module Models
# SecureValidatable creates better validations with more validation for security
#
# == Options
#
# SecureValidatable adds the following options to devise_for:
#
# * +email_regexp+: the regular expression used to validate e-mails;
# * +password_length+: a range expressing password length. Defaults from devise
# * +password_regex+: need strong password. Defaults to /(?=.*\d)(?=.*[a-z])(?=.*[A-Z])/
#
module SecureValidatable
def self.included(base)
base.extend ClassMethods
assert_secure_validations_api!(base)
base.class_eval do
# uniq login
validates authentication_keys[0], :uniqueness => {:scope => authentication_keys[1..-1], :case_sensitive => (case_insensitive_keys != false)}, :if => :email_changed?
# validates email
validates :email, :presence => true, :if => :email_required?
validates :email, :uniqueness => true, :allow_blank => true, :if => :email_changed? # check uniq for email ever
validates :email, :email => email_validation if email_validation # use rails_email_validator or similar
# validates password
validates :password, :presence => true, :length => password_length, :format => password_regex, :confirmation => true, :if => :password_required?
# don't allow use same password
validate :current_equal_password_validation
end
end
def self.assert_secure_validations_api!(base)
raise "Could not use SecureValidatable on #{base}" unless base.respond_to?(:validates)
end
def current_equal_password_validation
if not self.new_record? and not self.encrypted_password_change.nil?
dummy = self.class.new
dummy.encrypted_password = self.encrypted_password_change.first
dummy.password_salt = self.password_salt_change.first if self.respond_to? :password_salt_change and not self.password_salt_change.nil?
self.errors.add(:password, :equal_to_current_password) if dummy.valid_password?(self.password)
end
end
protected
# Checks whether a password is needed or not. For validations only.
# Passwords are always required if it's a new record, or if the password
# or confirmation are being set somewhere.
def password_required?
!persisted? || !password.nil? || !password_confirmation.nil?
end
def email_required?
true
end
module ClassMethods
Devise::Models.config(self, :password_regex, :password_length, :email_validation)
end
end
end
end
| true |
caec3c5551f5e1bcc194b7c6f62bd87701e53b61 | Ruby | perspectivezoom/urlshorten | /app/models/url.rb | UTF-8 | 478 | 2.578125 | 3 | [] | no_license | class Url < ActiveRecord::Base
attr_accessible :long_url, :short_id
has_many :clicks
before_save :prep_fields_for_save
def prep_fields_for_save
add_http
generate_short_id
end
def add_http
self.long_url = 'http://' + self.long_url unless self.long_url.start_with?('http')
end
def generate_short_id
unless (!self.short_id.nil?) && self.short_id.match(/[a-z]\w*/)
self.short_id = (0...8).map { ('a'..'z').to_a[rand(26)] }.join
end
end
end
| true |
7a86eed05a8ddcaf665d8230da34367a4846c397 | Ruby | kutikina/LaunchSchool-Prep | /more_stuff.rb | UTF-8 | 1,245 | 4.40625 | 4 | [] | no_license | #Intro to Programming
#More Stuff
#Excercise 1
#Write a program that checks a series of stings for the letter 'lab'. If it does exist, print out the word.
puts "Excercise 1"
"laboratory" - "experiment" - "Pans Labyrinth" - "elaborate" - "polar bear"
def has_lab?(string)
if /lab/ =~ string
puts string
end
end
has_lab?("laboratory")
has_lab?("experiment")
has_lab?("Pans Labyrinth")
has_lab?("elaborate")
has_lab?("Polar bear")
#Excercise 2
#What does a given program print, and return?
puts "Excercise 2"
puts "Prints: nothing as the block is not called"
puts "Returns: a Proc object"
#Excercise 3
#What is exception handling and what does it solve?
puts "Excercise 3"
puts "Exception handling is a way of dealing with errors that occur when a program is run. This solves the problem of a program terminating at runtime when an error occurs."
#Excercise 4
#Modify the code from Excercise 2 so it runs correctly
puts "Excercise 4"
def execute(&block)
block.call
end
execute { puts "Hello from inside the execute method!" }
#Excercise 5
#Interperate error code
puts "Excercise 5"
puts "The error is caused by a missing & sign before the block. The block must always be the last parameter and the program is expecting one."
| true |
7794e2ba69fa10e41279fb74e54e457ea20a7cf8 | Ruby | dweverson/learn-ruby | /letter-to-alphabet-position.rb | UTF-8 | 280 | 3.171875 | 3 | [] | no_license | def alphabet_position(text)
alpha_array = ("a".."z").to_a
a_hash = {}
end_array = []
text = text.downcase.chars
alpha_array.each_with_index { |x, index| a_hash[x] = index + 1 }
text.each {|t| end_array << a_hash[t] if t =~ /[a-z]/}
return end_array.join(" ")
end
| true |
5162c46ce043e91325c1be6298d31546b80b596f | Ruby | Lili-Mae/programming-univbasics-3-build-a-calculator-lab-london-web-120919 | /lib/math.rb | UTF-8 | 444 | 3.8125 | 4 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | def addition(num1, num2)
sum = num1 + num2
puts sum
end
def subtraction(num1, num2)
sum = num1 - num2
puts sum
end
def division(num1, num2)
sum = num1 / num2
puts sum
end
def multiplication(num1, num2)
sum = num1 * num2
puts sum
end
def modulo(num1, num2)
sum = num1 % num2
puts sum
end
def square_root(num)
num = num1 * num1
puts num
end
addition(5,4)
subtraction(10,5)
division(50,2)
multiplication(4,30)
modulo(34.5)
square_root(81) | true |
8de701152e25ac6b3d073b560f7cf841e293e480 | Ruby | aswinsanakan/taskbox | /app/models/project.rb | UTF-8 | 1,809 | 2.6875 | 3 | [] | no_license | class Project < ActiveRecord::Base
has_many :tasks
has_many :project_categories
has_many :categories, through: :project_categories
belongs_to :client
belongs_to :user
validates :name, presence: true
# when arguments are passed for a method we use : before, and for options for the method we pass : after, the values for the options we pass : before
validates_length_of :description, minimum: 10
validates_presence_of :status
#custom validations
#this validation will only get invoked at the time of creating a new record, and not upddating
#validate :check_status_on_create, on: :create
validate :start_date_one_week
validate :client_unique_project #One client - 2 projects
validates_uniqueness_of :name
#validate :unique_projectname #Checck uniqueness of projectname
def overdue_tasks
self.tasks.where('is_completed = ? AND due_date > ?', false, Date.today)
end
def incomplete_tasks
self.tasks.where('is_completed = ?', false)
end
def completed_tasks
self.tasks.where('is_completed = ?', true)
end
def calc_completed
return ((self.completed_tasks.size / self.tasks.size.to_f) * 100).round(2)
end
def calc_incomplete
return ((self.incomplete_tasks.size / self.tasks.size.to_f) * 100).round(2)
end
def calc_overdue
return ((self.overdue_tasks.size / self.tasks.size.to_f) * 100).round(2)
end
private
def check_status_on_create
if self.status !="new"
errors.add(:status, " is not new")
end
end
def start_date_one_week
if !(self.start_date.nil?) && self.start_date > Date.today + 7.days
errors.add(:start_date, " is greater than one week from today")
end
end
def client_unique_project
c = Project.where('client_id = ?', self.client_id).count
if c >= 10
errors.add(:client_id, "cannot have more than 2 projects")
end
end
end
| true |
f90b4b7cadfffba3ff77fb99f351bc6e7d8c414c | Ruby | nettan20/trellis | /lib/trellis/utils.rb | UTF-8 | 8,107 | 2.8125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
#--
# Copyright &169;2001-2008 Integrallis Software, LLC.
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
class Object #:nodoc:
def meta_def(m,&b) #:nodoc:
metaclass.send(:define_method,m,&b)
end
def metaclass
class<<self;self end
end
def call_if_provided(sym)
send sym if respond_to? sym
end
def instance_variable_set_if_different(persistent_field, value)
field = "@#{persistent_field}".to_sym
current_value = instance_variable_get(field)
if current_value != value && value != nil
instance_variable_set(field, value)
end
end
end
class Class #:nodoc:
def class_to_sym
underscore_class_name.to_sym
end
def underscore_class_name
value = (name.empty? || name =~ /<class:(.*)/) ? self : name
value.to_s.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase.split('/').last
end
def instance_attr_accessor(*syms)
syms.flatten.each do |sym|
instance_eval { attr_accessor(sym) }
end
end
def class_attr_accessor(*syms)
class_attr(:accessor, *syms)
end
def class_attr_reader(*syms)
class_attr(:reader, *syms)
end
def class_attr_writer(*syms)
class_attr(:writer, *syms)
end
def class_attr(kind, *syms)
syms.flatten.each do |sym|
case kind
when :accessor
metaclass.instance_eval { attr_accessor(sym) }
when :reader
metaclass.instance_eval { attr_reader(sym) }
when :writer
metaclass.instance_eval { attr_writer(sym) }
end
end
end
def attr_array(plural_array_name_sym, options={})
create_accessor = options[:create_accessor].nil? ? true : options[:create_accessor]
plural_array_name_sym = plural_array_name_sym.to_s #convert to string if it is a symbol
instance_variable = "@#{plural_array_name_sym}".to_sym
instance_variable_set(instance_variable, Array.new)
meta_def(plural_array_name_sym) { instance_variable_get(instance_variable) } if create_accessor
end
def create_child(class_name, mod = Object, register = true, &block)
klass = Class.new self
klass.class_eval &block if block_given?
mod.const_set class_name, klass if register
klass
end
end
class String #:nodoc:
PLURALS = [['(quiz)$', '\1zes'],['(ox)$', '\1en'],['([m|l])ouse$', '\1ice'],['(matr|vert|ind)ix|ex$', '\1ices'],
['(x|ch|ss|sh)$', '\1es'],['([^aeiouy]|qu)ies$', '\1y'],['([^aeiouy]|q)y$$', '\1ies'],['(hive)$', '\1s'],
['(?:[^f]fe|([lr])f)$', '\1\2ves'],['(sis)$', 'ses'],['([ti])um$', '\1a'],['(buffal|tomat)o$', '\1oes'],['(bu)s$', '\1es'],
['(alias|status)$', '\1es'],['(octop|vir)us$', '\1i'],['(ax|test)is$', '\1es'],['s$', 's'],['$', 's']]
SINGULARS =[['(quiz)zes$', '\1'],['(matr)ices$', '\1ix'],['(vert|ind)ices$', '\1ex'],['^(ox)en$', '\1'],['(alias|status)es$', '\1'],
['(octop|vir)i$', '\1us'],['(cris|ax|test)es$', '\1is'],['(shoe)s$', '\1'],['[o]es$', '\1'],['[bus]es$', '\1'],['([m|l])ice$', '\1ouse'],
['(x|ch|ss|sh)es$', '\1'],['(m)ovies$', '\1ovie'],['[s]eries$', '\1eries'],['([^aeiouy]|qu)ies$', '\1y'],['[lr]ves$', '\1f'],
['(tive)s$', '\1'],['(hive]s$', '\1'],['([^f]]ves$', '\1fe'],['(^analy)ses$', '\1sis'],
['([a]naly|[b]a|[d]iagno|[p]arenthe|[p]rogno|[s]ynop|[t]he)ses$', '\1\2sis'],['([ti])a$', '\1um'],['(news)$', '\1ews']]
def singular()
match_patterns(SINGULARS)
end
def plural()
match_patterns(PLURALS)
end
def match_patterns(patterns)
patterns.each { |match_exp, replacement_exp| return gsub(Regexp.compile(match_exp), replacement_exp) unless match(Regexp.compile(match_exp)).nil? }
end
def plural?
PLURALS.each {|match_exp, replacement_exp| return true if match(Regexp.compile(match_exp))}
false
end
def blank?
self !~ /\S/
end
def replace_ant_style_property(property, value)
result = self.gsub(/\$\{#{property.to_s}\}/) do |match|
value
end
result
end
def replace_ant_style_properties(properties)
text = self
properties.each_pair do |key,value|
text = text.replace_ant_style_property(key, value)
end
text
end
def humanize
gsub(/_id$/, "").gsub(/_/, " ").capitalize
end
end
class Array #:nodoc:
def next_to_last
self.last(2).first if self.size > 1
end
end
class Hash #:nodoc:
def keys_to_symbols
self.each_pair do |key, value|
self["#{key}".to_sym] = value if key
end
end
def each_pair_except(*exceptions)
_each_pair_except(exceptions)
end
def exclude_keys(*exceptions)
result = Hash.new
self._each_pair_except(exceptions) do |key, value|
result[key] = value
end
result
end
protected
def _each_pair_except(exceptions)
self.each_pair do |key, value|
unless exceptions.include?(key) then
yield [key, value]
end
end
end
end
class File
def self.find(dir, filename="*.*", subdirs=true)
Dir[ subdirs ? File.join(dir.split(/\\/), "**", filename) : File.join(dir.split(/\\/), filename) ]
end
def self.find_first(dir, filename, subdirs=false)
find(dir, filename, subdirs).first
end
end
# class Radius::TagBinding #:nodoc:
#
# end
module Utils
# TODO open the tag ==> TagContext?? class
def self.expand_properties_in_tag(text, tag)
# resolve the ${} variables
result = text #TODO not tested!
result = text.gsub(/\$\{.*?\}/) do |match|
name = match.split(/\$\{|\}/)[1]
unless name.include?('.')
tag.locals.send(name.to_sym) || tag.globals.send(name.to_sym)
else
target_name, method = name.split('.')
target = tag.locals.send(target_name.to_sym) || tag.globals.send(target_name.to_sym)
target.send(method.to_sym) if target
end
end if text
result
end
# TODO open the tag ==> TagContext?? class
def self.evaluate_tag_attribute(attribute_name, tag)
result = nil
source = tag.attr[attribute_name]
if source
source = expand_properties_in_tag(source, tag)
begin
local = tag.locals.instance_eval(source)
rescue
# log that they try to get a value that doesn't exist/can't be reached
end
begin
global = tag.globals.instance_eval(source)
rescue
# same as above
end
if local
result = local
elsif global
result = global
end
end
result
end
end
module Markaby
def self.build(*args, &block)
Markaby::Builder.new(*args, &block).to_s
end
class Builder
def thtml(&block)
tag!(:html,
:xmlns => "http://www.w3.org/1999/xhtml",
"xml:lang" => "en",
:lang => "en",
"xmlns:trellis" => "http://trellisframework.org/schema/trellis_1_0_0.xsd", &block)
end
def bluecloth(body)
thtml { body { text "#{BlueCloth.new(body).to_html}" } }
end
def render_body
text %[@!{@body}@]
end
end
end
| true |
5b29e9d9bcfb7cfd10cc9bfb70eed1f75739dea1 | Ruby | vincentericsson/SevenLanguages | /ruby/day2/print_array.rb | UTF-8 | 171 | 3.984375 | 4 | [] | no_license | a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
# Using each
(0..3).each{|i| puts "#{a[(4*i)..(4*i+3)]}"}
# Using each_slice
a.each_slice(4){|x| puts "#{x}"} | true |
15d9300d66e8c82a0fdac82a8942e40a24bd0455 | Ruby | mikesnchz/learning-ruby | /greeter.rb | UTF-8 | 343 | 3.96875 | 4 | [] | no_license | def greeter(name)
return "Hello, #{name}!"
end
def by_three?(x)
return x % 3 == 0
end
puts "Enter name:"
my_name = gets.chomp
output = greeter(my_name)
puts output
puts "Enter #:"
num = gets.chomp
output = by_three?(num.to_i)
puts output
<<<<<<< HEAD
end
=======
>>>>>>> 43ea0ee609d5c719de6c057ede0585b623c91569
| true |
33f39ce92392918b75899eeebbb6337d00195a37 | Ruby | Karibinn/karibinnV2 | /spec/system/booking_spec.rb | UTF-8 | 4,901 | 2.5625 | 3 | [] | no_license | # frozen_string_literal: true
require 'rails_helper'
# TODO: last sprint change. We're not booking, we're only asking for quotations.
# Sorry.
RSpec.describe 'Booking a trip' do
let!(:product1) do
create(:product,
:with_image,
title_en: 'Beautiful Villa',
specific: create(:property,
room_types: [create(:room_type, price_cents: 10000)])
)
end
let!(:product2) do
create(:product,
:with_image,
title_en: 'Amazing Apartment',
specific: create(:property,
room_types: [create(:room_type, price_cents: 13800)]))
end
let!(:activity1) do
create(:product,
:with_image,
title_en: 'Breath-taking ride',
specific: create(:activity, price_cents: 5200))
end
scenario 'booking as an existing user' do
user = create(:user)
sign_in user
book_property product1, date_range: '05/05/2018 - 08/05/2018', guests: 2
expect(page).to have_content(I18n.t('booking_items.show.header'))
expect(page).to have_content('3 nights, 2 persons')
expect(page).to have_content(product1.title)
book_property product2, date_range: '08/05/2018 - 12/05/2018', guests: 2
expect(page).to have_content('4 nights, 2 persons')
expect(page).to have_content(product2.title)
book_activity(activity1, date: '11-05-2018', guests: 3)
expect(page).to have_content('3 persons')
expect(page).to have_content('€156.00') # 52 * 3 people
click_on I18n.t('booking_items.show.view_journey')
click_on I18n.t('bookings.show.checkout')
expect(page).to have_content(I18n.t('bookings.checkout.header'))
expect(page).to have_content(product1.title)
expect(page).to have_content(product2.title)
expect(page).to have_content(activity1.title)
click_on I18n.t('bookings.checkout.confirm')
fill_in_personal_information_form
expect(page).to have_content(I18n.t('bookings.confirmation.header'))
visit booking_path
expect(page).to have_content(I18n.t('bookings.empty.header'))
end
scenario 'booking as an anonymous user' do
book_property product1, date_range: '05/05/2018 - 08/05/2018', guests: 4
expect(page).to have_content(I18n.t('booking_items.show.header'))
expect(page).to have_content('3 nights, 4 persons')
expect(page).to have_content(product1.title)
book_property product2, date_range: '08/05/2018 - 12/05/2018', guests: 2
expect(page).to have_content('4 nights, 2 persons')
expect(page).to have_content(product2.title)
book_activity(activity1, date: '11-05-2018', guests: 3)
expect(page).to have_content('3 persons')
expect(page).to have_content('€156.00') # 52 * 3 people
click_on I18n.t('booking_items.show.view_journey')
expect(page).to have_content(product1.title)
expect(page).to have_content(product2.title)
expect(page).to have_content(activity1.title)
click_on I18n.t('bookings.show.checkout')
expect(page).to have_content(I18n.t('bookings.checkout.header'))
expect(page).to have_content(product1.title)
expect(page).to have_content(product2.title)
click_on I18n.t('bookings.checkout.confirm', amount: '€238.00')
fill_in_personal_information_form
expect(page).to have_content(I18n.t('bookings.confirmation.header'))
visit booking_path
expect(page).to have_content(I18n.t('bookings.empty.header'))
end
scenario 'removing an item from cart' do
sign_in create(:user)
book_property product1, date_range: '05/05/2018 - 08/05/2018', guests: 2
visit booking_path
click_on I18n.t('bookings.show.remove_from_booking')
expect(page).to have_content(I18n.t('bookings.show.removed_message', title: product1.title))
expect(page).not_to have_content('3 nights, two persons')
end
private
def book_property(product, date_range:, guests:)
visit properties_path
click_on product.title
fill_in 'room_booking_form_date_range_s', with: date_range
fill_in 'Guests', with: guests
click_on I18n.t('booking_component.submit')
end
def book_activity(product, date:, guests:)
visit activities_path
click_on product.title
fill_in I18n.t('booking_component.date'), with: date
fill_in I18n.t('booking_component.number_of_people'), with: guests
click_on I18n.t('booking_component.submit')
end
def fill_in_personal_information_form
within('#new_bookings_personal_information_form') do
fill_in 'First name', with: 'John'
fill_in 'Last name', with: 'Smith'
fill_in 'Email', with: 'john.smith@example.com'
fill_in 'Phone', with: '+12 123 345 3451'
select 'United Kingdom', from: 'Country'
fill_in 'Number of adults', with: 3
fill_in 'Number of children', with: 1
click_on I18n.t('bookings.personal_information.ask_for_quotation')
end
end
end
| true |
c0813f005a95d9f345a5a9033092c97852ecbce3 | Ruby | threez/rack-rpc | /lib/rack/rpc/endpoint/xmlrpc.rb | UTF-8 | 3,962 | 2.546875 | 3 | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | permissive | require 'xmlrpc/server' unless defined?(XMLRPC::BasicServer)
require 'builder' # @see http://rubygems.org/gems/builder
# Monkey patch the xml writer for problems with double arrays
# Problem is filed as: http://jira.codehaus.org/browse/JRUBY-6670
class XMLRPC::XMLWriter::Simple
alias_method :unsave_element, :element
def element(name, attrs, *children)
unsave_element(name, attrs, *children.flatten)
end
end
class Rack::RPC::Endpoint
##
# @see http://en.wikipedia.org/wiki/XML-RPC
# @see http://www.xmlrpc.com/spec
module XMLRPC
CONTENT_TYPE = 'application/xml; charset=UTF-8'
##
# @see http://ruby-doc.org/stdlib/libdoc/xmlrpc/rdoc/classes/XMLRPC/BasicServer.html
class Server < ::XMLRPC::BasicServer
##
# @param [Rack::RPC::Server] server
# @param [Hash{Symbol => Object}] options
def initialize(server, options = {})
@server = server
super()
add_multicall unless options[:multicall] == false
add_introspection unless options[:introspection] == false
add_capabilities unless options[:capabilities] == false
server.class.rpc.each do |rpc_name, method_name|
add_handler(rpc_name, nil, nil, &server.method(method_name))
end
end
##
# @param [Rack::Request] request
# @return [Rack::Response]
def execute(request)
@server.request = request # Store the request so it can be accessed from the server methods
request_body = request.body.read
request_body.force_encoding(Encoding::UTF_8) if request_body.respond_to?(:force_encoding) # Ruby 1.9+
Rack::Response.new([process(request_body)], 200, {
'Content-Type' => (request.content_type || CONTENT_TYPE).to_s,
})
end
##
# Process requests and ensure errors are handled properly
#
# @param [String] request body
def process(request_body)
begin
super(request_body)
rescue RuntimeError => e
error_response(-32500, "application error - #{e.message}")
end
end
##
# Implements the `system.getCapabilities` standard method, enabling
# clients to determine whether a given capability is supported by this
# server.
#
# @param [Hash{Symbol => Object}] options
# @option options [Boolean] :faults_interop (true)
# whether to indicate support for the XMLRPC-EPI Specification for
# Fault Code Interoperability
# @return [void]
# @see http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php
def add_capabilities(options = {})
add_handler('system.getCapabilities', %w(struct), '') do
capabilities = {}
unless options[:faults_interop] == false
capabilities['faults_interop'] = {
'specUrl' => 'http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php',
'specVersion' => 20010516,
}
end
capabilities
end
self
end
##
# Create a valid error response for a given code and message
#
# @param [Int] error code
# @param [String] error message
# @return [String] response xml string
def error_response(code, message)
xml = Builder::XmlMarkup.new
xml.instruct! :xml, :version=>"1.0"
xml.methodResponse{
xml.fault {
xml.value{
xml.struct{
xml.member{
xml.name('faultCode')
xml.value{
xml.int(code)
}
}
xml.member{
xml.name('faultString')
xml.value{
xml.string(message)
}
}
}
}
}
}
end
end # Server
end # XMLRPC
end # Rack::RPC::Endpoint
| true |
747737325090e23c63cbfbe9f27563de9926a64b | Ruby | nsikanikpoh/ruby_dev | /word.rb | UTF-8 | 120 | 2.8125 | 3 | [] | no_license | def valid_word?(word, characters)
word.chars.all? { |c| characters.delete_at(characters.index(c)) rescue nil }
end
| true |
335b22bbd7fbfe1633a76a863aad18c2b64c40d2 | Ruby | Gamoundo/ruby-oo-self-count-sentences-lab-nyc04-seng-ft-041920 | /lib/count_sentences.rb | UTF-8 | 365 | 3.234375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
class String
def sentence?
if self.end_with?(".")
true
else
false
end
end
def question?
if self.end_with?("?")
true
else
false
end
end
def exclamation?
if self.end_with?("!")
true
else
false
end
end
def count_sentences
self.split(/[.?!]/).reject {|n| n.empty? || n == ","}.length
end
end | true |
93519a19fa0a46d2fc116c1a22eea8ea8ebd960a | Ruby | bmnick/bbq | /app/helpers/tag_cloud_helper.rb | UTF-8 | 802 | 2.953125 | 3 | [] | no_license | module TagCloudHelper
def tag_cloud_for collection, sort_method, display_property
sorted = collection.sort_by(&sort_method).reverse
scores = score_array sorted
collection.map do |tag|
tag_output_for(tag, scores[tag.id], display_property)
end.join(" ")
end
def tag_output_for tag, score, display_property
link_to tag.send(display_property), tag, class: "tag-cloud-#{score+1}"
end
def score_array sorted_array
chunks = chunk_array sorted_array, 6
scores = {}
chunks.each_with_index do |chunk, score|
chunk.each do |tag|
scores[tag.id] = score
end
end
scores
end
def chunk_array array, num_chunks
width = (array.length / num_chunks) + 1
array.each_slice(width).to_a
end
end | true |
7a92e8840a1dee534df167c4f9724f162d9fd313 | Ruby | FelipeLozano/Teste_Livro_casa_codigo_Ruby | /TesteEncapsulamentoCapitulo9/lib/fatura.rb | UTF-8 | 307 | 3.078125 | 3 | [] | no_license | class Fatura
attr_reader :pagamentos , :valor
def initialize(cliente , valor)
@pagamentos=[]
@valor=valor
end
def adiciona_pagamento pagamento
@pagamentos << pagamento
valor_total = @pagamentos.map(&:valor).reduce(:+)
@paga=true if valor_total >= @valor
end
def paga?
@paga
end
end | true |
591ec24ec9dd3955105905ad32793ba762e3dcab | Ruby | zpalmquist/flashcards | /lib/round.rb | UTF-8 | 1,390 | 3.796875 | 4 | [] | no_license | require_relative 'deck'
require_relative 'guess'
require 'pry'
class Round
attr_reader :deck, :guesses
attr_accessor :current, :correct
def initialize(deck)
@deck = deck
@guesses = []
@current = 0
@correct = 0
end
def record_guess(response)
guess = Guess.new(current_card, response)
@guesses.push(guess)
if response == current_card.answer
add_correct
end
add_current
end
def start
puts "Welcome! You're playing with #{deck.count} cards."
puts "≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈"
end
def play
deck.cards.count.times do
puts current_card.question
input = $stdin.gets.chomp.downcase
# had to use $stdin to let input hit
record_guess(input)
puts guesses[current-1].feedback
end
puts "∆∆∆∆∆ Game over! ∆∆∆∆∆"
puts "You got #{correct} correct out of #{deck.count}" +
" for a total score of #{percent_correct}%"
end
def current_card
deck.cards[current]
end
def number_correct
return @correct
end
def percent_correct
return (@correct.to_f / guesses.count.to_f * 100.0).round(2)
end
def add_current
@current += 1
end
def add_correct
@correct += 1
end
end
| true |
ea7867fdc57d0237b4abba49dddebb40af85bc12 | Ruby | ejdelsztejn/sweater_weather | /app/poros/image.rb | UTF-8 | 353 | 2.671875 | 3 | [] | no_license | class Image
attr_reader :location,
:image_url,
:credit
def initialize(location, image_data)
@location = location
@image_url = image_data[:largeImageURL]
@credit = {
source: "pixabay.com",
author: image_data[:user],
logo: "https://pixabay.com/static/img/logo_square.png"
}
end
end
| true |
6f45221a8080268739b49ab8a16635cbdc963c89 | Ruby | shalomchin/E_commerce-stripe | /app/models/cart.rb | UTF-8 | 1,066 | 2.703125 | 3 | [] | no_license | class Cart < ApplicationRecord
has_one :payment
has_many :line_items
has_many :products, through: :line_items
def total_price
total_price = 0
self.line_items.each do |qty|
total_price += qty.subtotal
end
total_price
end
# def update_inventory
# self.line_items.each do |item|
# item.product.slot -= item.quantity
# item.product.save
# end
# end
def stack_item(product, quantity, reservation)
self.add_item(product, quantity, reservation)
end
def increase_quantity(product, quantity)
line_item = self.line_items.find_by(product: product)
line_item.quantity = quantity
line_item.save!
end
def add_item(product, quantity, reservation)
self.line_items.create!(product: product, quantity: quantity, reservation: reservation)
end
# def item_already_exists?(product)
# self.line_items.find_by(product: product).present?
# end
def self.find_or_create(cart_id)
if cart_id == nil
cart = Cart.create
else
cart = Cart.find(cart_id)
end
end
end
| true |
9cf4cdcce1f4f6862c83d58b460f7abd9d6564e8 | Ruby | sinstein/rapid_share_mock_up | /app/models/attachment.rb | UTF-8 | 593 | 2.578125 | 3 | [] | no_license | class Attachment < ActiveRecord::Base
belongs_to :user
validates :name, presence: true, allow_nil: false
validate :file_format
def file_format
whitelist = ["pdf","png","jpg","jpeg","rb","txt","azw"]
if(!self.name.nil?)
ext = self.name.split('.')[-1]
end
if !whitelist.include? ext
errors.add(:file , " format not supported!")
end
end
def validate_file_size(file_io)
one_mb = 1048576
if (file_io.size.to_f / one_mb > 2)
errors.add(:file, " is larger than maximum permitted size (2 MB)")
return false
end
true
end
end
| true |
a5fd25d4cf79546daedb4008d67dc0b249beaa19 | Ruby | Stephdajon/ruby_activity | /lesson_1/liskov.rb | UTF-8 | 832 | 3.28125 | 3 | [] | no_license | #liskov
class Liskov
def initialize(salary, num_of_days, number_of_hired, commission, deduction)
@salary = salary
@num_of_days = num_of_days
@commission = commission
@number_of_hired = number_of_hired
@deduction = deduction
end
def monthly_income
total_salary + total_commission
end
private
def total_salary
@salary * @num_of_days -@deduction
end
def total_commission
@commission * @number_of_hired
end
end
class Admin < Liskov
def take_over_account(user)
end
end
class Employee < Liskov
def online_transactions(money_transfer, payment_methods)
end
end
user = Liskov.new(850, 25, 3, 2000, 1500)
puts user.monthly_income
admin = Admin.new(850, 25, 6, 2000, 1500)
puts admin.monthly_income
employee = Employee.new(850, 25, 9, 2000, 1500)
puts employee.monthly_income
| true |
e7c7a617aa3343a575edbde9fba8948fba72a782 | Ruby | gengogo5/atcoder | /typical90/t013.rb | UTF-8 | 4,541 | 3.390625 | 3 | [] | no_license | def array(n,ini=nil); Array.new(n) { ini } end
class PriorityQueue
attr_reader :heap
def initialize
# ヒープ配列
@heap = []
# 小さい順に優先度が高い
# [ノード番号,暫定距離]のペアで格納される
@comp = -> (x,y) { x[1] < y[1] }
end
def <<(new_one)
# 新規アイテムを末尾に入れる
@heap << new_one
# 末尾から上っていく
cur = @heap.size - 1
# ヒープ再構築
while (cur > 0)
# 親ノードの要素番号を取得
par = (cur - 1) >> 1
# 追加アイテムより親の方が優先度が高くなったら抜ける
# = 追加アイテムはcurの位置に収まるのが適切
break if @comp[@heap[par],new_one]
# 親の方が優先度が高くなるまで、子に親の値を入れていく
# 親子入れ替えを行うと計算量が増えるため、子の値を順に上書きして最後に新規アイテムを入れる
@heap[cur] = @heap[par]
cur = par
end
@heap[cur] = new_one
self
end
def top
return nil if @heap.size == 0
@heap[0]
end
def deq
latest = @heap.pop # 末尾を取り出す
return latest if @heap.size == 0 # 最後の1個ならそのまま返す
# 末尾を根に置き換える
highest = @heap[0]
@heap[0] = latest
size = @heap.size
par = 0
l = (par << 1) + 1 # 左の子
while (l < size)
r = l + 1 # 右の子
# 優先度の高い方の子を交換候補にする
cld = r >= size || @comp[@heap[l],@heap[r]] ? l : r
# 親の方が優先度が高ければ交換をやめる
break if @comp[latest,@heap[cld]]
# 子の値を親に入れる
@heap[par] = @heap[cld]
# 親
par = cld
l = (par << 1) + 1 # 左の子
end
# 根に仮置きした値を適切な位置に置く
@heap[par] = latest
highest
end
def clear
@heap = []
end
end
N,M = gets.split.map(&:to_i)
A,B,C = M.times.map { gets.split.map(&:to_i) }.transpose
graph = Array.new(N+1) { Array.new }
M.times do |i|
# 街Aから街Bまでの距離
graph[A[i]] << [B[i],C[i]]
# 街Bから街Aまでの距離
graph[B[i]] << [A[i],C[i]]
end
# 頂点nから各ノードへの最短距離を配列で返す
# 1. 始点に0を書き込む
# 2. 未確定の頂点の中から、現時点で最も距離の小さい頂点をひとつ選び確定させる(必要な場合はルートを記録する)
# 3. 2で確定した頂点と直接つながっていて、かつ未確定な頂点に対して、始点からの所要時間を計算し、記録されている時間より短ければ更新する
# 4. 全地点が確定していれば終了、そうでなければ2に戻る
def dijkstra(n,graph,num)
# 優先度付きキュー
# 最短距離未確定の頂点の確定待ちキュー
q = PriorityQueue.new
# 関数が返す最短距離配列(添字0は不使用)
# 全要素最長距離で初期化
dist = array(num+1,Float::INFINITY)
# [1] 始点の最短距離を0で設定
# 始点と最短距離のペア
dist[n] = 0
# 経路を保持する(問いには不要だが学習用として)
prev = array(num+1, -1)
q << [n, 0]
# キューが空になるまで続ける
# 確定待ちがいない = すべてのノードが確定している
while (q.heap.size > 0)
# [2] 未確定の中で最も優先度が高い(始点からの最短距離が短い)街Pの情報を取り出す
# posは確定
pos = q.top.first
q.deq
# [3] 2で確定した街と直接つながっている街をすべて見る
graph[pos].each do |g|
to = g[0] # 行き先の街
cost = g[1] # 街Pから直接行く場合のコスト
# 最短距離配列の更新(toへ行くための最短距離が知ってる距離より短い場合)
# 確定済頂点の場合、dist[to]より小さいdist[pos]+costが存在しない為、この分岐に入らない
if (dist[to] > dist[pos] + cost)
# dist[pos](始点からposまでのコスト) + posからtoまでのコスト
dist[to] = dist[pos] + cost
prev[to] = pos # toを通ってposに着いた経路記録(最後に記録されたものが最短なので上書き)
# 未確定の頂点を確定待ちキューに入れる
q << [to, dist[to]]
end
end
end
dist
end
dist1 = dijkstra(1,graph,N)
distN = dijkstra(N,graph,N)
(1..N).each do |i|
puts dist1[i] + distN[i]
end
| true |
9459ceb6bb4e7dbb6585e3abd963356728ebeb9b | Ruby | masakisanto/ecuacovid | /lib/ecuacovid/cargar_positivas.rb | UTF-8 | 918 | 2.796875 | 3 | [
"WTFPL"
] | permissive | require "ecuacovid/cliente"
require "ecuacovid/data"
module Ecuacovid
class CargarPositivas
attr_reader :datos
def initialize(options={})
@vista = options[:vista]
@cliente = options[:cliente] || Ecuacovid::Cliente.new
@datos = []
end
def grabar(registro)
(@datos ||= []) << registro
end
def nacional
@area = :nacional
log("Area nacional seleccionada.")
end
def provincial
@area = :provincial
log("Area provincial seleccionada.")
end
def cantonal
@area = :cantonal
log("Area cantonal seleccionada.")
end
def operar
@datos = @cliente.positivas(predicados: [[:area, :igual, area]]) if !hay_datos?
@vista.listo
end
def hay_datos?
!@datos.empty?
end
private
def area
@area || :nacional
end
def log(msg)
@vista.log(msg)
end
end
end
| true |
282bae593820a5905a8c15b1f68d27ba057b566d | Ruby | noamdeul/redmine-issues | /get_issues.rb | UTF-8 | 1,961 | 2.90625 | 3 | [] | no_license | require 'httparty'
require 'json'
@config = JSON.load(File.read('config.json'))
def get_issues(project_id, type, key)
query = project_id ? { project_id: project_id } : {}
headers = {
'X-Redmine-API-Key' => @config['redmine_api_key']
}
response = HTTParty.get(
"http://#{@config['redmine_url']}/#{type}",
:query => query,
:headers => headers
)
if response.code == 200
response[key]
else
[]
end
end
def get_weather
url = "http://api.wunderground.com/api/#{@config['weather_api_key']}/conditions/q/Hod_Hasharon.json"
response = HTTParty.get(url)
if response.code == 200
response["current_observation"]
else
{}
end
end
def get_image
headers = { 'X-Redmine-API-Key' => @config['redmine_api_key'] }
query = { project_id: 5 }
response = HTTParty.get(
"http://#{@config['redmine_url']}/issues/534.json?include=attachments",
:query => query,
:headers => headers
)
link = response.parsed_response["issue"]["attachments"].last["content_url"]
pic = HTTParty.get(
link,
:headers => headers
)
File.open('images/page3.jpg', 'w') { |file| file.write(pic) }
end
messages = get_issues(5, 'issues.json', 'issues').map do |r|
{
"title" => r["subject"].tr("'"," "),
"description" => r["description"].tr("\n"," ").tr("\r"," ").tr("'"," "),
"date" => r["start_date"]
}
end
issues = get_issues(1, "issues.json", "issues").map do |r|
{
'id' => r['id'] ,
"subject" => r["subject"].tr("'"," "),
"status" => r["status"]["name"],
"created_on" => Time.parse(r["created_on"]).strftime("%d-%m-%Y"),#.to_date,
"days_open" => "#{(Time.now.to_date - Time.parse(r["created_on"]).to_date).round}" #r["created_on"]
}
end
weather = get_weather
get_image
# open and write to a file with ruby
open('issues.json', 'w') { |f|
f.puts "data = '" + issues.to_json + "';\nmessages = '" + messages.to_json + "';\nweather = '" + weather.to_json + "';"
}
| true |
a49943c3a816ed955ea38d2498a2e3fa2b97a5f1 | Ruby | JocelynDev/trainruby | /exo_methode.rb | UTF-8 | 330 | 3.5625 | 4 | [] | no_license | def convert_to_min(secondes)
return secondes / 60
end
def direBonjour(prenom)
return "Bonjour #{prenom} !"
end
def salutation(nom, prefix)
puts "#{prefix} #{nom} !"
end
def reorganiser_list(*nom)
nom = nom.to_s
puts nom.sort
end
puts direBonjour("jocelyn")
salutation("jocelyn", "Coucou")
reorganiser_list
| true |
82b3a5d0279df051b13565dcfda06beb3c324921 | Ruby | mfioravanti2/maadi-ads | /lib/custom/analyzer/StatusComparison.rb | UTF-8 | 2,008 | 2.71875 | 3 | [] | no_license | # Author : Mark Fioravanti (mfioravanti@my.fit.edu)
# Florida Institute of Technology
# Course : CSE5400 Special Topics - High Volume Automated Testing
# Date : 01/18/2013
# File : comparison.rb
#
# Summary: This is a Comparison Analyzer which compares the results from
# multiple applications and flags deviations as potential failures.
require_relative 'factory'
require_relative '../../core/helpers'
module Maadi
module Analyzer
class StatusComparison < Analyzer
def initialize
super('StatusComparison')
@options['USE_VERTICAL'] = 'TRUE'
@options['USE_HORIZONTAL'] = 'TRUE'
@notes['USE_VERTICAL'] = 'Perform a Vertical Comparison (compare results, SAME application DIFFERENT steps)'
@notes['USE_HORIZONTAL'] = 'Perform a Horizontal Comparison (compare results, DIFFERENT applications, SAME steps)'
end
def analyze
if @repositories.length > 0
@repositories.each do |repository|
Maadi::post_message(:Info, "Analyzer (#{@type}:#{@instance_name}) checking (#{repository.to_s}) for results")
if @options['USE_HORIZONTAL'] == 'TRUE'
puts
puts 'PIDs that have statuses which differ between applications'
list = repository.pids_from_status_mismatch_by_horizontal
if list.length > 0
puts "\tIDs: #{list.join(', ')}"
else
puts "\tNo Procedural result differences found."
end
end
if @options['USE_VERTICAL'] == 'TRUE'
puts
puts 'PIDs that have statuses which differ between steps'
list = repository.pids_from_status_mismatch_by_vertical( 'EQUALS' )
if list.length > 0
puts "\tIDs: #{list.join(', ')}"
else
puts "\tNo Procedural result differences found."
end
end
puts
end
end
end
end
end
end | true |
46797a54da0c3b20b88ec6643ea00f0bdad31355 | Ruby | handofthecode/ruby-sinatra | /ruby_foundations/weekly_challenges/word_count.rb | UTF-8 | 257 | 3.5625 | 4 | [] | no_license | class Phrase
def initialize(words)
@words = words.downcase.gsub(/((\s'|'\s)|[^\w'\d]+)/, ' ').squeeze(" ").split
end
def word_count
result = {}
@words.each { |w| result.include?(w) ? result[w] += 1 : result[w] = 1 }
result
end
end | true |
ebe3cedc5f5c06521a424c9abfc697294a187bf8 | Ruby | eddieleeper/tableschema-rb | /lib/tableschema/constraints/pattern.rb | UTF-8 | 564 | 2.53125 | 3 | [
"MIT"
] | permissive | module TableSchema
class Constraints
module Pattern
def check_pattern
constraint = lambda { |value| value.match(/#{@constraints[:pattern]}/) }
if @field.type == 'yearmonth'
valid = constraint.call(Date.new(@value[:year], @value[:month]).strftime('%Y-%m'))
else
valid = constraint.call(@value.to_json)
end
unless valid
raise TableSchema::ConstraintError.new("The value for the field `#{@field[:name]}` must match the pattern")
end
true
end
end
end
end
| true |
b7dd93d8f239c2f7905422eaee74ac3ecd75d2ee | Ruby | abarnes26/museo | /lib/curator.rb | UTF-8 | 503 | 3.234375 | 3 | [] | no_license |
class Curator
attr_reader :artists,
:museums,
:photographs
def initialize
@artists = []
@museums = []
@photographs = []
end
def add_museum(info)
@museums << Museum.new(info)
end
def add_artist(info)
@artists << Artist.new(info)
end
def add_photograph(info)
@photographs << Photograph.new(info)
end
def find_museum(position)
@museums[position]
end
def find_artist(position)
@artists[position]
end
end
| true |
92cc27e8c98273667c2b6a5dbd4ef165c212c7b0 | Ruby | tauqeer-ahmad92/test_solution | /app/services/log_file_service.rb | UTF-8 | 1,795 | 3.078125 | 3 | [] | no_license | require 'open-uri'
class LogFileService
def process_log_file(file_url)
response = {}
open(file_url, 'r').each do |line|
_, timestamp, exception = line.split(' ')
time_value = Time.zone.strptime(timestamp.to_s, '%Q')
time_range = create_range(time_value.hour, time_value.min)
response[time_range] = {} if response[time_range].blank?
response[time_range][exception] = 0 if response[time_range][exception].blank?
response[time_range][exception] = response[time_range][exception] + 1
end
response
end
def create_range(hour, minutes)
case minutes
when 0..15
return format_range(hour, 0, 15)
when 15..30
return format_range(hour, 15, 30)
when 30..45
return format_range(hour, 30, 45)
when 45..59
return format_range(hour, 45, 0, true)
end
end
def format_range(hour, start_min, end_min, cycle=false)
next_hour = hour
next_hour += 1 if cycle == true
[Time.parse("#{hour}:#{start_min}").strftime("%H:%M"), Time.parse("#{next_hour}:#{end_min}").strftime("%H:%M")].join('-')
end
def format_log_response(response)
res = {}
response.each do |file_res|
file_res.each do |time_range, data|
res[time_range] = {} if res[time_range].blank?
data.each do |exception, count|
res[time_range][exception] = 0 if res[time_range][exception].blank?
res[time_range][exception] = res[time_range][exception] + count
end
end
end
final_response = []
res.each do |range, data|
logs = []
data.each do |key, value|
logs << {exception: key, count: value}
end
final_response << {
timestamp: range,
logs: logs
}
end
final_response
end
end
| true |
9c421afc560c6cce1503e23d67d7613908b0480c | Ruby | trollric/ruby_training | /lines.rb | UTF-8 | 265 | 3.71875 | 4 | [] | no_license | puts "you're Swell"
puts "you're \"Swell\""
myString = "...You can say that again..."
puts myString
puts myString
puts "Hello there, what's your name?"
name = gets.chomp
puts "Your name is #{name}? What a lovely name!"
puts "I am please to meet you, #{name}. :)"
| true |
fedf72fad1ad0c0479da963c10f97170977aa883 | Ruby | gizele22/Week-2-Challenge | /studentdirectory2.rb | UTF-8 | 1,118 | 3.25 | 3 | [] | no_license | old_sync = $stdout.sync
$stdout.sync = true
#require './lib/sudentdirectory.rb'
#Student Directory - Friday Challenge Week 2
#List of students enrollment
#List of input students details(name,gender,age)
puts "Student Directory"
puts "Press Enter To Begin Listing"
intro = gets.chomp
puts "Student Name"
name = gets.chomp
puts "Age"
age = gets.chomp
puts "Gender"
gender = gets.chomp
def listing(students)
name = []
gender = []
age = []
students = [{name:'Gizele', gender: 'female', age: 15}]
print students
lists = [{ name: 'Tasha', gender: 'female', age: 20}, { name: 'carlton', gender: 'male', age: 18},
{ name: 'fairuz', gender: 'male', age: 21}, { name: 'amin', gender: 'male', age: 25},
{ name: 'moon', gender: 'male', age: 23}, { name: 'wendy', gender: 'female', age: 22}]
def students(list)
list.each do |details|
sentence << "Student Name #{students[:name]} Gender #{students[:gender]} Age #{students[:age]} years old"
print "Student Name #{students[:name]} Gender #{students[:gender]} Age #{students[:age]} years old"
end
end
end
| true |
604848489c11312848e60aacd3db7a7df27ed778 | Ruby | pirainogi/ruby-oo-guided-youtube-exercise | /lib/youtube.rb | UTF-8 | 747 | 2.875 | 3 | [] | no_license | module Youtube
class Adapter
attr_accessor :results
attr_reader :keyword
def initialize(keyword)
@keyword = keyword
end
def get_videos_from_youtube
self.results = HTTParty.get(api_url)["items"]
create_videos
end
private
def create_videos
results.map do |video_data|
title = video_data["snippet"]["title"]
link = video_url(video_data["id"]["videoId"])
Video.new(title, link)
end
end
def api_url
"https://www.googleapis.com/youtube/v3/search?part=snippet&key=#{api_key}&q=#{self.keyword}&type=video"
end
def video_url(id)
"https://www.youtube.com/watch?v=#{id}"
end
def api_key
ENV["API_KEY"]
end
end
end
| true |
49db4a31bda6a31a7b6c1da32e6ad4bf2ddf2764 | Ruby | marloncarvalho/codility | /nesting.rb | UTF-8 | 305 | 3.40625 | 3 | [] | no_license | def solution(s)
return 1 if s.length == 0
return 0 if s.length.odd?
return 0 if s[0].eql? ')'
return 0 if s[s.length - 1].eql? '('
return 0 if s.count('(') != s.count(')')
return 1
end
#puts solution('()')
#puts solution('(')
#puts solution(')(')
#puts solution('')
puts solution('())()(()')
| true |
32a69fdf02d5388596292704b935a2747e5e0954 | Ruby | smoline/enumerable_testing | /enumerable_test.rb | UTF-8 | 5,629 | 3.328125 | 3 | [] | no_license | require 'minitest/spec'
require 'minitest/autorun'
require 'minitest/pride'
require_relative 'lib/de_enumerable'
require_relative 'lib/book'
require_relative 'your_code_here'
describe "Enumerable" do
before(:all) do
@war_and_peace = Book.new("War and Peace", 1869, "Leo Tolstoy", 1225)
@h2g2 = Book.new("The Hitchhiker's Guide to the Galaxy", 1979, "Douglas Adams", 224)
@moby_dick = Book.new("Moby Dick", 1851, "Herman Melville", 927)
@pride = Book.new("Pride and Prejudice", 1813, "Jane Austen", 432)
@books = [@war_and_peace, @h2g2, @moby_dick, @pride]
de_enumerable(@books)
@reimplements_enumerable = ReimplementEnumerable.new(@books)
end
it "implements all? correctly when results are true" do
results = @reimplements_enumerable.all? { |book| book.year > 1800 }
assert_equal true, results
end
it "implements all? correctly when the results are false" do
results = @reimplements_enumerable.all? { |book| book.year == 1800 }
assert_equal false, results
end
it "implements count correctly" do
results = @reimplements_enumerable.count { |book| book.page_count > 300 }
assert_equal 3, results
end
it "implements count correctly" do
results = @reimplements_enumerable.count { |book| book.page_count == 1225 }
assert_equal 1, results
end
it "implements count correctly" do
results = @reimplements_enumerable.count { |book| book.page_count > 3000 }
assert_equal 0, results
end
it "implements find correctly when there is a match" do
results = @reimplements_enumerable.find { |book| book.year > 1970 }
assert_equal @h2g2, results
end
it "implements find correctly when there is not a match" do
results = @reimplements_enumerable.find { |book| book.year < 1492 }
assert_nil results
end
it "implements each_with_index correctly" do
object_results = []
index_results = []
@reimplements_enumerable.each_with_index do |book, index|
object_results << book
index_results << index
end
assert_equal [@war_and_peace, @h2g2, @moby_dick, @pride], object_results
assert_equal [0, 1, 2, 3], index_results
end
it "implements drop correctly" do
assert_equal [@moby_dick, @pride], @reimplements_enumerable.drop(2)
end
it "implements drop_while correctly" do
results = @reimplements_enumerable.drop_while { |book| book.year < 1900 }
assert_equal [@h2g2, @moby_dick, @pride], results
end
it "implements find index correctly when there is a match" do
results = @reimplements_enumerable.find_index { |book| book.year == 1851 }
assert_equal 2, results
end
it "implements find index correctly when there is no match" do
results = @reimplements_enumerable.find_index { |book| book.year == 2017 }
assert_nil @reimplements_enumerable.find { |book| book.year == 2017 }
end
it "implements include? correctly when there is a match" do
results = @reimplements_enumerable.include?(@war_and_peace)
assert_equal true, results
end
it "implements include? correctly when there is no match" do
not_in_list = Book.new("A Brief History of Time", 1988, "Stephen Hawking", 256)
results = @reimplements_enumerable.include?(@not_in_list)
assert_equal false, results
end
it "implements map correctly" do
results = [1869, 1979, 1851, 1813]
assert_equal results, @reimplements_enumerable.map { |book| book.year }
end
it "implements max_by correctly" do
results = @h2g2
assert_equal results, @reimplements_enumerable.max_by { |book| book.year }
end
it "implements min_by correctly" do
results = @pride
assert_equal results, @reimplements_enumerable.min_by { |book| book.year }
end
it "implements reject correctly" do
short_books = [@h2g2, @pride]
assert_equal short_books, @reimplements_enumerable.reject { |book| book.page_count > 500 }
end
it "implements reverse_each correctly based on yield" do
# Look to see that reverse_each yields each element in reverse order
reversed_array = []
@reimplements_enumerable.reverse_each { |book| reversed_array << book }
expected_books_array = [@pride, @moby_dick, @h2g2, @war_and_peace]
assert_equal expected_books_array, reversed_array
end
it "implements reverse_each correctly based on the RETURN value" do
expected_books_array = [@pride, @moby_dick, @h2g2, @war_and_peace]
# See that reverse_each returns the array reversed
what_does_reverse_each_return = @reimplements_enumerable.reverse_each { |book| book }
assert_equal expected_books_array, what_does_reverse_each_return
end
it "implements partition correctly" do
results = [[@war_and_peace, @h2g2], [@moby_dick, @pride]]
assert_equal results, @reimplements_enumerable.partition { |book| book.year > 1860 }
end
it "implements one? correctly when true" do
assert_equal true, @reimplements_enumerable.one? { |book| book.page_count == 1225 }
end
it "implements one? correctly when false" do
assert_equal false, @reimplements_enumerable.one? { |book| book.year == 1900 }
end
it "implements none? correctly when false" do
assert_equal false, @reimplements_enumerable.none? { |book| book.page_count == 1225 }
end
it "implements none? correctly when true" do
assert_equal true, @reimplements_enumerable.none? { |book| book.year == 1900 }
end
it "implements each_slice correctly" do
skip
results = [@war_and_peace, @h2g2] [@moby_dick, @pride]
assert_equal results, @reimplements_enumerable.each_slice(2) { |book| p book }
end
# slice_before
end
| true |
33681ed9e6589fadb67541e43716c28241eb587d | Ruby | nptravis/oxford-comma-v-000 | /lib/oxford_comma.rb | UTF-8 | 388 | 2.953125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def oxford_comma(array)
if (array.size < 3)
array.join(" and ")
else
[array[0..-2].join(", "), ", and ", array[-1]].join
end
end
# def join_all(join_with = ", ", connector = "and", last_comma = false)
# return self.to_s if self.empty? || self.size==1
# connector = join_with+connector if last_comma
# [list[0...-1].join(join_with), list.last].join(connector)
# end | true |
f36eb6a931eed11244f4fe26cd80fdd06870ee02 | Ruby | RayMPerry/kitchen-sink | /ruby/anagram_checker.rb | UTF-8 | 238 | 3.96875 | 4 | [] | no_license | print "Enter the first word: "
word1 = gets.chomp
print "Enter the second word: "
word2 = gets.chomp
is_anagram = word1.chars.sort == word2.chars.sort
puts "#{word1.upcase} and #{word2.upcase} are #{is_anagram ? '' : 'NOT '}anagrams."
| true |
259f094aa2d60ad29da3f4a196df7f2b549ec8c2 | Ruby | pguharay/ruby-repo | /countingsort.rb | UTF-8 | 670 | 3.40625 | 3 | [] | no_license | #!/usr/bin/env ruby -wKU
require_relative 'sort_util'
def countingsort(array)
countArray = Array.new(9,0);
sortedArray = Array.new(array.size, 0)
(0 .. array.size-1).each{|i|
countArray[array[i].to_i] = (countArray[array[i].to_i]).to_i + 1
}
(0 .. 8).each{|i|
countArray[i+1] = Integer(countArray[i+1]) + Integer(countArray[i])
}
(0 .. array.size-1).each{|i|
sortedArray[countArray[array[i].to_i].to_i] = array[i]
countArray[array[i].to_i] -= 1
}
return sortedArray
end
if __FILE__ == $0
array = [5,3,4,8,9,2,6,1,7,5,3,4,2]
sortedArray = countingsort(array)
$logger.debug("Sorted sequence is [ " + String(sortedArray.join(',')) + " ]")
end | true |
55219a3519042e4c8ba6f5d31e31e8d0b7c0ce7a | Ruby | jomi-se/aoc | /2017/spec/day3/part_2_spec.rb | UTF-8 | 869 | 2.921875 | 3 | [] | no_license | require "spec_helper"
require_relative "../../day3/part_2.rb"
describe "Day 3" do
let(:solver) { Day3::Part2 }
describe "puzzle" do
it "1st solution" do
expect(solver.run(1)).to eq(1)
end
it "2nd solution" do
expect(solver.run(2)).to eq(1)
end
it "3rd solution" do
expect(solver.run(3)).to eq(2)
end
it "4th solution" do
expect(solver.run(4)).to eq(4)
end
it "5th solution" do
expect(solver.run(5)).to eq(5)
end
it "6th solution" do
expect(solver.run(6)).to eq(10)
end
it "7th solution" do
expect(solver.run(7)).to eq(11)
end
it "8th solution" do
expect(solver.run(8)).to eq(23)
end
it "9th solution" do
expect(solver.run(9)).to eq(25)
end
xit "nth solution" do
expect(solver.run(277678)).to eq(25)
end
end
end
| true |
2a9ead386b5c3ae7d29c303b924f862be7a4466e | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/rna-transcription/b58fbee204f54e01908e5094ff7ac7df.rb | UTF-8 | 429 | 3.15625 | 3 | [] | no_license | class Complement
DNA_NUCLEOTIDES = "ACGT"
RNA_NUCLEOTIDES = "UGCA"
def self.of_dna(seq)
raise ArgumentError.new("Uracil (U) can't be found in DNA") if seq.match "U"
seq.tr(DNA_NUCLEOTIDES, RNA_NUCLEOTIDES)
end
def self.of_rna(seq)
raise ArgumentError.new("Thymine (T) can't be found in RNA") if seq.match "T"
seq.tr(RNA_NUCLEOTIDES, DNA_NUCLEOTIDES)
end
end
| true |
000b16de8316b2fb78eb61014a0976a5c03a7528 | Ruby | igorsimdyanov/ruby | /mixins/prepend.rb | UTF-8 | 400 | 3.46875 | 3 | [] | no_license | class Greet
def say(name)
"Greet#say: Hello, #{name}!"
end
end
module Greetable
def say(name)
"Greetable#say: Hello, #{name}!"
end
end
class Hello < Greet
prepend Greetable
def say(name)
"Hello#say: Hello, #{name}!"
end
end
hello = Hello.new
puts hello.say('Ruby') # Greetable#say: Hello, Ruby!
p Hello.ancestors # [Greetable, Hello, Greet, Object, Kernel, BasicObject]
| true |
0c1b24bf7510e9edbf845f11763786756c6fe430 | Ruby | cristgl/Object-Oriented-Programming-and-Design | /Napakalaki-Ruby/lib/treasure_kind.rb | UTF-8 | 634 | 2.625 | 3 | [] | no_license | #encoding: utf-8
# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
module NapakalakiGame
module TreasureKind
ARMOR=:armor
HELMET=:helmet
ONEHAND=:onehand
BOTHHANDS=:bothhands
SHOES=:shoes
def to_s
out = case
when self == ARMOR then "Armadura \n"
when self == HELMET then "Casco \n"
when self == ONEHAND then "Arma de una mano \n"
when self == BOTHHANDS then "Arma de dos manos \n"
when self == SHOES then "Zapatos \n"
end
out
end
end
end | true |
d8d6022417689d5f6a097491a07eb78dba45fa4f | Ruby | RyanSpittler/lrthw_exercises | /chapter_six/ex6.rb | UTF-8 | 1,095 | 4.5 | 4 | [] | no_license | # This assigns the Fixnum 10 to types of people.
types_of_people = 10
# This assigns a string with interpolation to x.
x = "There are #{types_of_people} types of people."
# This assigns the string "binary" to a variable of the same name.
binary = 'binary'
# This assigns the string "don't" to a variable.
do_not = "don't"
# This assigns a string with more interpolation to y.
y = "Those who know #{binary} and those who #{do_not}."
# This outputs the variable x.
puts x
# This outputs the variable y.
puts y
# This outputs a string, interpolated with x.
puts "I said: #{x}."
# This outputs a string, interpolated with y.
puts "I also said: '#{y}'."
# This assigns the boolean "false" to hilarious.
hilarious = false
# This assigns a string with interpolation to a variable.
joke_evaluation = "Isn't that joke so funny?! #{hilarious}"
# This outputs the variable joke_evaluation.
puts joke_evaluation
# This assigns a string to w.
w = 'This is the left side of...'
# This assigns a string to e.
e = 'a string with a right side.'
# This outputs two strings concatenated together.
puts w + e
| true |
b2dd70a5821491f32cd4c6ce5850884a260250c6 | Ruby | gchan/advent-of-code-ruby | /2020/day-13/day-13-part-2.rb | UTF-8 | 1,126 | 2.9375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
file_path = File.expand_path('day-13-input.txt', __dir__)
input = File.read(file_path)
buses = input.split("\n").last.split(?,)
ids = buses
.map.with_index { |id, idx| [id.to_i, idx] }
.reject { |id, _| id.zero? }
.sort.reverse
id, idx = ids.first
# Solve for the first bus, and time step for the next valid timestamp
t = id - idx
step = id
# Solve for each additional bus
ids.each do |id, idx|
while true
break if (t + idx) % id == 0
t += step
end
# Find next time step for this subset of buses by locating the next timestamp
# OR simply `step *= id` if you know you are dealing only with prime numbers
t2 = t
subset = ids[0..(ids.index([id, idx]))]
while true
t2 += step
break if subset.all? { |id, i| (t2 + i) % id == 0 }
end
step = t2 - t
end
puts t
exit
# Solution below is too slow for non-example input
ids = buses
.map.with_index { |id, idx| [id.to_i, idx] }
.reject { |id, _| id.zero? }
.sort
step = ids.last[0]
adj = ids.last[1]
t = step - adj
while true
break if ids.all? { |id, i| (t + i) % id == 0 }
t += step
end
puts t
| true |
1f94888018c68ed5916f2cdff3d7a6d860b83bfb | Ruby | jkeiser/pathblazer | /lib/pathblazer/path_set/charset.rb | UTF-8 | 4,117 | 3.09375 | 3 | [
"Apache-2.0"
] | permissive | module Pathblazer
class PathSet
class Charset
# Ranges must be sorted and not intersecting.
def initialize(*ranges)
@ranges = Charset.init_ranges(ranges)
end
attr_reader :ranges
UNICODE_MAX = 0x10FFFF
UNICODE_MAX_CHAR = "\u10FFFF"
def ==(other)
other.is_a?(Charset) && ranges == other.ranges
end
def self.any
Charset.new([0, 0x10FFFF])
end
def self.none
Charset.new
end
def to_s
if ranges == [ [ 0, UNICODE_MAX ] ]
"."
elsif ranges.last[1] == UNICODE_MAX
inverted = ~self
"[^#{inverted.ranges.map { |min,max| min==max ? Charset.from_codepoint(min) : "#{Charset.from_codepoint(min)}-#{Charset.from_codepoint(max)}" }.join(",")}]"
else
"[#{ranges.map { |min,max| min==max ? Charset.from_codepoint(min) : "#{Charset.from_codepoint(min)}-#{Charset.from_codepoint(max)}" }.join(",")}]"
end
end
def first
ranges[0] ? Charset.from_codepoint(ranges[0][0]) : nil
end
# def each
# ranges.each do |min, max|
# min.upto(max) do |codepoint|
# yield Charset.from_codepoint(codepoint)
# end
# end
# end
def size
sum = 0
ranges.each do |min,max|
sum += max - min + 1
end
sum
end
def match?(ch)
if ch.size == 1
ranges.any? { |min,max| ch.codepoints[0] >= min && ch.codepoints[0] <= max }
else
false
end
end
def intersect_pair(a, b)
min = [ a[0], b[0] ].max
max = [ a[1], b[1] ].min
max >= min ? [ [ min, max ] ] : []
end
def &(other)
if other.is_a?(String)
return match?(other) ? Charset.new(other) : Charset.new
end
new_ranges = []
index = other_index = 0
while index < ranges.size && other_index < other.ranges.size
new_ranges += intersect_pair(ranges[index], other.ranges)
if other.ranges[other_index][0] < ranges[other_index][0]
other_index += 1
else
index += 1
end
end
Charset.new(new_ranges)
end
def |(other)
# deduping will happen on the other side
Charset.new(new_ranges+other_ranges)
end
def -(other)
self & ~other
end
def ~()
new_ranges = []
new_min = 0
ranges.each do |min, max|
new_ranges << [ new_min, min-1 ] if new_min < min
new_min = max+1
end
if new_min <= UNICODE_MAX
new_ranges << [ new_min, UNICODE_MAX ]
end
Charset.new(*new_ranges)
end
def empty?
ranges.size == 0
end
private
def self.from_codepoint(codepoint)
[ codepoint ].pack('U*')
end
def self.init_ranges(ranges)
new_ranges = ranges.map do |min,max|
if min.is_a?(String)
if min.size == 3 && min[1] == '-' && !max
max = min[2]
min = min[0]
elsif min.size != 1
raise "Passed #{min.inspect} to Charset.new! Pass either a Unicode codepoint or a pair of single-character strings to Charset!"
end
min = min.codepoints[0]
end
if max.is_a?(String)
if max.size != 1
raise "Passed #{max.inspect} to Charset.new! Pass either a Unicode codepoint or a pair of single-character strings to Charset!"
end
max = max.codepoints[0]
end
max ||= min
[ min, max ]
end
# Sort by min, then dedup overlapping and consecutive ranges.
new_ranges = new_ranges.sort_by { |min,max| min }
new_ranges.each do |min,max|
if new_ranges.size == 0 || min > new_ranges[-1][0]+1
new_ranges << [ min, max ]
else
new_ranges[-1][1] = max if new_ranges[-1][1] < max
end
end
new_ranges
end
end
end
end
| true |
691063132446b7c85290d8ae30c44c1db739c84b | Ruby | carolineartz/pairing_scheduler | /spec/services/project_sprint_pairing_scheduler_spec.rb | UTF-8 | 5,599 | 2.6875 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe ProjectSprintPairingScheduler do
describe "#schedule!" do
let(:project) {
FactoryBot.create(
:project,
:with_sprints,
:with_engineers,
sprint_count: sprint_count,
engineer_count: engineer_count
)
}
let(:scheduler) { described_class.new(project: project) }
shared_examples "rotate repeated pairings in a round-robin fashion" do
# the following examples all assume some repeats are necessary
before { expect(num_weeks_of_unique_pairs).to be < project.sprints.count }
it "exhausts all unique pairings before necessary repeats" do
sprints_with_unique_pairs = project.sprints.first(num_weeks_of_unique_pairs)
unqiue_pairings = sprints_with_unique_pairs.flat_map(&:pairings).map(&:pair)
possible_pairs = project.engineers.to_a.combination(2).map { |engs| Pair.new(*engs) }
expect(possible_pairs).to match_array(unqiue_pairings)
end
it "starts at the beginning when repeating pairs" do
first_sprint = project.sprints.first!
first_repeated_pair_sprint = project.sprints.offset(num_weeks_of_unique_pairs).first!
expect(first_sprint.pairings.map(&:pair)).to match_array(first_repeated_pair_sprint.pairings.map(&:pair))
end
end
shared_examples "even number of engineers" do
it "does not have any sprints with solo engineers" do
expect(project.pairings).to be_present # make sure the scheduler has been called so as to not get false positive
expect(project.sprints.flat_map(&:solo_engineers).compact).to be_empty
end
end
shared_examples "odd number of engineers" do
it "has one solo engineer for each sprint" do
expect(project.pairings).to be_present # make sure the scheduler has been called so as to not get false positive
expect(project.sprints.flat_map(&:solo_engineers).compact.count).to eq project.sprints.count
end
end
shared_examples "more unique pairs than sprint pairings" do
it "has unique pairs across all sprints" do
expect(project.pairings).to be_present
expect(project.pairings.map(&:pair).uniq.length).to eq(project.pairings.length)
end
end
context "For a project with more sprints than possible pairings" do
# 4 engineers => 3 weeks of unique pairings
#
# 6 pair combinations
# 2 pairings / week
let(:num_unique_pair_combinations) { [*1..engineer_count].combination(2).to_a.length }
let(:pairings_per_week) { engineer_count / 2 }
let(:num_weeks_of_unique_pairs) { num_unique_pair_combinations / pairings_per_week }
context "and an even number of engineers" do
let(:sprint_count) { 4 }
let(:engineer_count) { 4 }
before { scheduler.schedule! }
include_examples "rotate repeated pairings in a round-robin fashion"
include_examples "even number of engineers"
end
context "and an odd number of engineers" do
let(:sprint_count) { 5 }
let(:engineer_count) { 3 }
before { scheduler.schedule! }
include_examples "rotate repeated pairings in a round-robin fashion"
include_examples "odd number of engineers"
it "starts repeating solo engineers after everyone has taken a turn" do
first_set_of_solos = project.sprints.first(num_weeks_of_unique_pairs).flat_map(&:solo_engineers)
# expect(first_set_of_solos.length).to eq(project.engineers.length)
expect(first_set_of_solos).to match_array(project.engineers)
expect(project.sprints.offset(num_weeks_of_unique_pairs).first.solo_engineers)
.to match_array(project.sprints.first.solo_engineers)
end
end
end
context "For a project with less sprints than possible pairings" do
context "and an odd number of engineers" do
let(:sprint_count) { 3 }
let(:engineer_count) { 5 }
before { scheduler.schedule! }
include_examples "odd number of engineers"
include_examples "more unique pairs than sprint pairings"
end
context "and an even number of engineers" do
let(:sprint_count) { 3 }
let(:engineer_count) { 6 }
before { scheduler.schedule! }
include_examples "even number of engineers"
include_examples "more unique pairs than sprint pairings"
it "has a different solo engineer each sprint" do
expect(project.pairings).to be_present
expect(project.pairings.map(&:pair).uniq.length).to eq(project.pairings.length)
end
end
end
context "For a project that has already started" do
let(:engineer_count) { 4 }
let(:sprint_count) { 2 }
it "does not update pairs for that have already ended" do
first_sprint = project.sprints.first!
eng1 = project.engineers.third!
eng2 = project.engineers.fourth!
expect(project.pairings).to be_empty
# create a pairing for the first sprint
FactoryBot.create(:pairing, pair: Pair.new(eng1, eng2), sprint: first_sprint)
# travel to a time after the first sprint has ended
travel_to(first_sprint.end_date + 1.day) do
scheduler.schedule!
# confirm that the scheduler did schedule something
expect(project.pairings.length).to be > 1
# confirm that the scheduler did not add any pairings to the first sprint
expect(first_sprint.pairings.length).to eq 1
end
end
end
end
end | true |
314a7009dd31bb3efcaf1dc71441d82bfb2e0c66 | Ruby | pazguille/getting-started-with-ruby | /methods.rb | UTF-8 | 531 | 4.25 | 4 | [] | no_license | def friend(name)
puts "My friend is " + name + "."
end
def friend2(name)
puts "My friend is #{name}."
end
def add(a, b)
return a + b
end
# Splat arguments: "Hey Ruby, I don't know how many arguments there are about to be, but it could be more than one."
def what_up(greeting, *bros)
bros.each { |bro| puts "#{greeting}, #{bro}!" }
end
what_up("What up", "Justin", "Ben", "Kevin Sorbo")
def alphabetize(arr, rev=false)
if rev
arr.sort { |a, b| b <=> a }
else
arr.sort { |a, b| a <=> b }
end
end | true |
5f2095d22dd9f46e73786dd839f02de1741d0e60 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/src/1506.rb | UTF-8 | 232 | 3.203125 | 3 | [] | no_license | def compute(a, b)
# Find the shorter of the strings
smallest = [a, b].min_by(&:length)
# Count the number of character-wise differences between a and b
smallest.split('').each_index.count { |i| a[i] != b[i] }
end | true |
b1b9718940ae014818b338596de49b74a8473997 | Ruby | beca-g/Process-Workshops | /LeapYear/spec/leapyear_spec.rb | UTF-8 | 539 | 2.6875 | 3 | [] | no_license | require './lib/leapyear'
describe '#leapyear' do
it 'checks if the year is divisable by 400' do
expect(leap_year?(2000)).to be true
end
it 'year is not divisable by 400 return false' do
expect(leap_year?(1970)).to be false
end
it 'checks if the year is divisable by 400' do
expect(leap_year?(1900)).to be false
end
it 'checks if the year is divisable by 400' do
expect(leap_year?(1988)).to be true
end
it 'checks if the year is divisable by 400' do
expect(leap_year?(1500)).to be false
end
end | true |
d0e0911a8a5ee3d1b808e14ab79e40ac6b6de16a | Ruby | jennie-quinton/maths_problems | /src/ruby/travelling-salesman.rb | UTF-8 | 2,674 | 3.625 | 4 | [] | no_license | class TravellingSalesman
def initialize(nodes, startMatrix)
@nodes = nodes
@startMatrix = startMatrix
@shortestPath = []
@shortestDistance
@order = []
@matrix = createStartMatrix
@distance = 0
end
##
# shortest path function
# need to fix matrix override
def shortestPath
@nodes.each_with_index do |_, nodeIndex|
addOption(0, nodeIndex)
addNextNode(0, nodeIndex)
end
return {
distance: @shortestDistance,
path: @shortestPath.join(", ")
}
end
# add option to current order and distance
private
def addOption(distance, index)
@matrix.each {|row| row[index] = 0}
@order << @nodes[index]
@distance += distance
end
# goes to next node to add to route
def addNextNode(distance, index)
if (noOptionsAvailable(@matrix[index]))
updateShortest
goBackNode(distance, index)
else
@matrix[index].each_with_index do |option, index|
if (option != 0)
addOption(option, index)
addNextNode(option, index)
end
end
goBackNode(distance, index)
end
end
# check to see if at a dead end
def noOptionsAvailable(row)
row.none? {|cell| cell != 0}
end
# go back to previous node to go down other paths from that node
def goBackNode(distance, index)
original = createStartMatrix
original.length.times {|i| @matrix[i][index] = original[i][index]}
@order.pop
@distance -= distance
end
##
# if the current order is valid and the distance is shorter
# update the shortest path and distance
def updateShortest
if (@order.length == @startMatrix.length && (@shortestDistance.nil? || @distance < @shortestDistance ))
@shortestPath = @order.dup
@shortestDistance = @distance
end
end
##
# create immutable start matrix
def createStartMatrix
@startMatrix.map{|row| row.dup}
end
end
# change to matrix
startMatrix = [
[0, 3, 2, 5, 0, 0, 0, 0],
[3, 0, 3, 0, 3, 0, 0, 0],
[2, 3, 0, 2, 5, 3, 7, 0],
[5, 0, 2, 0, 0, 6, 0, 0],
[0, 3, 5, 0, 0, 0, 4, 0],
[0, 0, 3, 6, 0, 0, 0, 1],
[0, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 0, 0, 0, 1, 2, 0]
]
nodes = ["1","2","3","4","5","6","7","8"]
travellingSalesman = TravellingSalesman.new(nodes, startMatrix)
puts travellingSalesman.shortestPath
| true |
eb2215942367ce4a682d52ff084ed91e89ae3e04 | Ruby | lafwind/My_LeetCode | /lib/two_sum.rb | UTF-8 | 197 | 3.25 | 3 | [] | no_license | def two_sum(numbers, target)
numbers.each_index do |i|
t = target-numbers[i]
if numbers.include?(t) && i != numbers.index(t)
return [i+1, numbers.index(t)+1].sort
end
end
end
| true |
a6b5a4e20996b47eebbb7a9a023b41be6c299ba6 | Ruby | RomanADavis/euler-solutions | /Ruby/euler3.rb | UTF-8 | 1,779 | 3.8125 | 4 | [] | no_license | arb = 600851475143
def prime? num
(2..Math.sqrt(num)).each do |j|
return false if num % j == 0
end
return true
end
largest = 1
(1...Math.sqrt(arb)).each do |i|
largest = i if prime? i if arb % i == 0
end
puts largest
# Does the same thing as prime? except recursively
def prime_rec? candidate, top=Math.sqrt(candidate).floor
return true if top == 1
return false if candidate % top == 0
prime_rec? candidate, top - 1
end
# solves the same problem as above, except recursively
def largest_factor(n=600851475143, largest=1, plus_one=3)
return largest if plus_one > n
largest, n = plus_one, (n / plus_one) if (n % plus_one == 0) && prime_rec?(plus_one)
largest_factor(n, largest, plus_one + 2)
end
p largest_factor
# This is a way more clever verson. It just divides by every factor that goes
# into it, and repeats the same factor if successful, so every number has to be
# prime and you never have to check for primeness. And, the icing on the cake
# that it starts from 2 and goes up, so it never even has to check if it's the
# greatest factor. The last factor that succeeds is the greatest factor.
n, factor, last_factor = arb, 2, 1
while n > 1
last_factor, n = factor, n / factor if n % factor == 0
while n % factor == 0
n = n /factor
end
factor += 1
end
p last_factor
# Of course, we can halve the number of times it has to loop through if we treat
# two seperately, and then loop through every odd number after that.
n, factor, last_factor = arb, 2, 1
if n % 2 == 0
last_factor = 2
while n % 2 == 0
n = n / 2
end
end
while n > 1
last_factor, n = factor, n / factor if n % factor == 0
while n % factor == 0
n = n /factor
end
factor += 1
end
p last_factor
| true |
a1c15f2ed13c081a3c7c0e75d941a9562803792c | Ruby | Istanful/safettp | /spec/safettp/guard_spec.rb | UTF-8 | 2,909 | 2.59375 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
RSpec.describe Safettp::Guard do
describe '#evaluate!' do
context 'when the guard is not safe' do
it 'raises an error' do
guard = described_class.new(stubbed_response)
allow(guard).to receive(:safe?).and_return(false)
evaluation = -> { guard.evaluate! }
expect(evaluation).to raise_error(Safettp::Guard::StatesNotCovered)
end
end
context 'when the guard is safe' do
it 'returns the response' do
response = stubbed_response
guard = described_class.new(response)
allow(guard).to receive(:safe?).and_return(true)
result = guard.evaluate!
expect(result).to eq(response)
end
end
end
describe '#on_success' do
it 'covers the success state' do
response = stubbed_response(success: true)
guard = described_class.new(response)
allow(guard).to receive(:cover).and_call_original
guard.on_success {}
expect(guard).to have_received(:cover).with(:success)
end
end
describe '#on_failure' do
it 'covers the failure state' do
response = stubbed_response(success: false)
guard = described_class.new(response)
allow(guard).to receive(:cover).and_call_original
guard.on_failure {}
expect(guard).to have_received(:cover).with(:failure)
end
end
describe '#cover' do
context 'when block is yielded' do
context 'when request have the given state' do
it 'yields the result to the block' do
response = stubbed_response(success: true)
guard = described_class.new(response)
expect { |b| guard.cover(:success, &b) }.to yield_with_args(response)
end
end
context 'when request does not have state' do
it 'does not yield the block' do
response = stubbed_response(success: false)
guard = described_class.new(response)
expect { |b| guard.cover(:success, &b) }.to_not yield_with_args(response)
end
end
end
end
describe '#guarded?' do
context 'when success and failure states given' do
it 'returns true' do
response = stubbed_response
guard = described_class.new(response)
guard.on_success {}
guard.on_failure {}
expect(guard).to be_safe
end
end
context 'when only success state given' do
it 'returns false' do
response = stubbed_response
guard = described_class.new(response)
guard.on_success {}
expect(guard).to_not be_safe
end
end
context 'when only failure state given' do
it 'returns false' do
response = stubbed_response
guard = described_class.new(response)
guard.on_failure {}
expect(guard).to_not be_safe
end
end
end
def stubbed_response(success: true)
double(Safettp::Response, success?: success, failure?: !success)
end
end
| true |
ca8f7322a2b5efa199ff769e3f1a237183c9c95c | Ruby | robzenn92/LUS | /sequence labeling/fst/fsa_generator.rb | UTF-8 | 752 | 2.75 | 3 | [] | no_license | @tag_count = "tag.count";
@token_tag_count = "token-tag.count";
@output_path = "out.txt";
@tags = [];
def count(lookup)
f = File.open(@tag_count, "r");
f.each_line do |line|
c, tag_found = line.split(' ')
@tags << tag_found
return ("%.2f" % c).to_f if(tag_found == lookup)
end
f.close
end
def read_token_tag_file()
f = File.open(@token_tag_count, "r");
o = File.open(@output_path, 'w')
prob = 0.0;
f.each_line do |line|
c, token, tag = line.split(' ')
prob = ("%.2f" % c).to_f / count(tag)
o.puts "0\t0\t" + token + "\t" + tag + "\t" + (-Math.log(prob)).to_s
end
f.close
@tags.uniq.each do |t|
o.puts "0\t0\t<unk>\t" + t + "\t" + (-Math.log((1.0 / @tags.uniq.length))).to_s
end
o.puts "0"
o.close
end
read_token_tag_file | true |
4198a98e67ddd4f03f2108df7a6a9b3eaaf22a22 | Ruby | takkkun/multilang | /lib/multilang/slot.rb | UTF-8 | 1,978 | 3.21875 | 3 | [
"MIT"
] | permissive | require 'multilang/language_names'
module Multilang
class Slot
def initialize
@items = {}
end
# Register the object to the slot.
#
# @param [String, Symbol] language_spec the language specifier
# @param [Object] object object to register
# @yield called once at getting the object first
#
# @see Multilang::Slot#[]
def register(language_spec, object, &first)
item = {:object => object}
item[:first] = first if first
@items[LanguageNames[language_spec]] = item
end
# Determine if registered with the language specifier in the slot.
#
# @param [String, Symbol] language_spec the language specifier
# @return whether registered with the language specifier in the slot
def exists?(language_spec)
!!@items[LanguageNames[language_spec]]
end
# Get the object by the language specifier. And call once the block that was
# given at registration the object.
#
# @param [String, Symbol] language_spec the language specifier
# @return [Object] registered object in the slot
#
# @see Multilang::Slot#register
def [](language_spec)
language_name = LanguageNames[language_spec]
raise ArgumentError, "#{language_spec.inspect} does not register" unless @items.key?(language_name)
item = @items[language_name]
if item[:first]
item[:first].call
item.delete(:first)
end
item[:object]
end
module Access
# @attribute [r] slot
# @return [Multilang::Slot] slot that is bound to class or module
def slot
instance_variable_get(Multilang::SLOT_KEY)
end
# Get registered object in the slot.
#
# @param [String, Symbol] language_spec
# @return [Object] registered object to the slot
#
# @see Multilang::Slot::Access#slot
# @see Multilang::Slot#[]
def [](language_spec)
slot[language_spec]
end
end
end
end
| true |
3e5911290202a2e2a39286b1e68a85a5c8b693f2 | Ruby | tellingeric/GlobalFlush | /app/controllers/bathrooms_controller.rb | UTF-8 | 2,986 | 2.5625 | 3 | [] | no_license | # Bathrooms Controller
# It controls all the pages are related to all the CRUD page for bathrooms
# log in is required for CUD, displaying is not required log in
class BathroomsController < ApplicationController
before_filter :require_user, :only => [:new, :create, :update, :edit, :destroy]
before_filter :is_admin, :only => :destroy
# GET /bathrooms/new
# Bathroom creation page, creates a temporary bathroom object with 1 address, 5 bathroom_specs, and 3 bathroom_photos
def new
@bathroom = Bathroom.new
@bathroom.build_address
5.times do
@bathroom.bathroom_specs.build
end
3.times do
@bathroom.photos.build
end
end
# POST /bathrooms
# Bathroom creation action. Create a bathroom by using data passed from params
# Return to the bathroom page if it creates successfully
# Else stays on the 'new' page and indicates the errors
def create
@bathroom = Bathroom.new(params[:bathroom])
@bathroom.build_address(params[:bathroom][:address_attributes])
if params[:bathroom][:bathroom_specs]
@bathroom.bathroom_specs.build(params[:bathroom][:bathroom_specs])
end
if params[:bathroom][:photos]
@bathroom.photos.build(params[:bathroom][:photos])
end
# Temporary method to construct the title
@bathroom.title = "#{params[:bathroom][:title]} - #{@bathroom.address.inside_location} - #{@bathroom.gender.to_s}"
if @bathroom.save
flash[:notice] = "Bathroom created!"
redirect_to bathroom_path(@bathroom.id)
else
render :new
end
end
# GET /bathrooms
# Index page for bathrooms. Query all bathroom and ordered by descending updated_at time
def index
@bathrooms = Bathroom.find(:all,:order => 'updated_at DESC')
@is_admin = is_admin
end
# GET /bathrooms/:id
# Page for showing a single bathroom.
def show
@bathroom = Bathroom.find(params[:id])
end
# GET /bathrooms/:id/edit
# Page for editing a single bathroom.
def edit
@bathroom = Bathroom.find(params[:id])
end
# PUT /bathrooms/:id
# Update the bathroom by the params
# redirect back to the bathroom page if updates successfully
def update
@bathroom = Bathroom.find(params[:id])
respond_to do |format|
if @bathroom.update_attributes(params[:bathroom]) #&& @bathroom.address.update_attributes(params[:bathroom][:address])
format.html { redirect_to(@bathroom, :notice => 'Bathroom was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @bathroom.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /bathrooms/:id
# Delete the bathrooms only if the current user is an admin
# Redirect back to the bathrooms page afterwards
def destroy
@bathroom = Bathroom.find(params[:id])
@bathroom.destroy
respond_to do |format|
format.html { redirect_to bathrooms_url }
end
end
end
| true |
2d95eeb7e3f2d81be5a7312d2072796d8778a320 | Ruby | PopulateTools/gobierto-etl-utils | /lib/file_uploader_service/local.rb | UTF-8 | 1,154 | 2.578125 | 3 | [] | no_license | # frozen_string_literal: true
module FileUploaderService
class Local
FILE_PATH_PREFIX = "/tmp/"
attr_reader :file, :file_name
def initialize(file:, file_name:)
@file = file
@file_name = file_name
end
def call
upload || file_uri
end
def upload
upload! if !uploaded_file_exists? && @file
end
def upload!
FileUtils.mkdir_p(file_base_path) unless File.exist?(file_base_path)
FileUtils.mv(file.tempfile.path, file_path)
File.chmod(0o664, file_path)
ObjectSpace.undefine_finalizer(file.tempfile)
file_uri
end
def uploaded_file_exists?
File.exist?(file_path)
end
private
def file_uri
File.join("/", FILE_PATH_PREFIX, file_name)
end
def file_path
File.join(file_base_path, file_basename)
end
def file_base_path
File.join(
defined?(Rails) ? Rails.public_path : "",
FILE_PATH_PREFIX,
file_dirname
)
end
protected
def file_dirname
Pathname.new(file_name).dirname
end
def file_basename
Pathname.new(file_name).basename
end
end
end
| true |
cce663b40a87cc77e090ebbb293f1f31cc4c8d7d | Ruby | Justme0/leetcode | /019-remove-nth-node-from-end-of-list.rb | UTF-8 | 454 | 3.8125 | 4 | [] | no_license | class ListNode
attr_accessor :val, :next
def initialize(val)
@val = val
@next = nil
end
def delete_at(index)
fail unless index >= 1
p = self
(index - 1).times do
p = p.next
end
p.next = p.next.next
end
def size
size = 1
p = @next
while !p.nil?
p = p.next
size += 1
end
size
end
end
def remove_nth_from_end(head, n)
size = head.size
num = size - n
return head.next if num == 0
head.delete_at(num)
head
end
| true |
b5bf61e1f9437a4df6ae061910182cd42fd7e756 | Ruby | realbite/fuzzy_date | /features/support/fuzzy_steps.rb | UTF-8 | 976 | 2.578125 | 3 | [
"MIT"
] | permissive | Then(/^parse the following dates :$/) do |table|
table.hashes.each do |h|
f = FuzzyDate.parse(h["date"])
f.year.should eql( to_int(h["year"])) , "Invalid Year=#{f.year}!"
f.month.should eql( to_int(h["month"])) , "Invalid Month=#{f.month}!"
f.day.should eql( to_int(h["day"])) , "Invalid Day=#{f.day}!"
f.wday.should eql( to_int(h["wday"])) , "Invalid WeekDay=#{f.wday}!"
f.bce?.should eql( to_bool(h["bce?"])) , "Invalid BCE=#{f.bce?}!"
f.circa?.should eql( to_bool(h["circa?"])) , "Invalid CIRCA=#{f.circa?}!"
f.complete?.should eql( to_bool(h["complete?"])) , "Invalid COMPLETE=#{f.complete?}!" if h.key?("complete?")
f.unknown?.should eql( to_bool(h["unknown?"])) , "Invalid UNKNOWN=#{f.unknown?}!" if h.key?("unknown?")
end
end
Then(/^parse "(.*?)" random dates$/) do |count|
count.to_i.times do
f = make_fuzzy_date
puts f.to_s
f2 = FuzzyDate.parse(f.to_s)
f2.to_db.should == f.to_db
end
end
| true |
bddfca61a7f99b357426ce48b0b6212f092a989d | Ruby | amatsukixgithub/atcoder | /ABC/ABC156/D.rb | UTF-8 | 264 | 3 | 3 | [] | no_license | # xCy
def c(x,y)
a=1
y.times do |i|
a*=x-i
end
b=1
y.times do |j|
b*=j+1
end
a/b
end
N,A,B=gets.chomp.split.map(&:to_i)
a=0
b=0
ans=[]
N.times do |n|
n+=1
ans.push(c(N,n))
end
ans[A-1]=0
ans[B-1]=0
puts ans.inject(:+) % (1000000000+7)
| true |
87117f87b1f77a0514293122ac1df44bb9af1a38 | Ruby | khris22/js-rails-as-api-custom-json-rendering-using-rails-online-web-pt-061019 | /app/controllers/birds_controller.rb | UTF-8 | 1,217 | 3.015625 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | class BirdsController < ApplicationController
def index
birds = Bird.all
# render json: birds
# slice works fine for a single hash, as with bird, it won't work for an array of hashes
# we can add in the only: option directly after listing an object we want to render to JSON
# render json: birds, only: [:id, :name, :species]
render json: birds.to_json(except: [:created_at, :updated_at])
end
def show
bird = Bird.find_by(id: params[:id])
# render json: bird
# no more insance variable, since we're immediately rendering birds and bird to JSON and not using ERB
# render json: {id: bird.id, name: bird.name, species: bird.species }
# created a new hash out of three keys, assigning the keys manually with the attributes of bird
# render json: bird.slice(:id, :name, :species)
# Rather than having to spell out each key, the Hash slice method returns a new hash with only the keys that are passed into slice.
# Error Messaging When Rendering JSON Data
if bird
render json: { id: bird.id, name: bird.name, species: bird.species }
else
render json: { message: 'Bird not found' }
end
end
end | true |
17286c6f7d18e46d77ba83edf9d40159f66950a0 | Ruby | rhivent/ruby_code_N_book | /book-of-ruby/ch9/ensure2.rb | UTF-8 | 347 | 3.375 | 3 | [] | no_license | # The Book of Ruby - http://www.sapphiresteel.com
f = File.new( "test.txt" )
begin
for i in (1..6) do
puts("line number: #{f.lineno}")
line = f.gets.chomp
num = line.to_i
puts( "Line '#{line}' is converted to #{num}" )
puts( 100 / num )
end
rescue Exception => e
puts( e.class )
puts( e )
ensure
f.close
puts( "File closed" )
end
| true |
fa5a4dd725dda50384d323e1eafa5f48d5a4a86b | Ruby | ktrops/C3Projects--Shipping | /spec/models/shipping_rate_spec.rb | UTF-8 | 3,667 | 2.65625 | 3 | [] | no_license | require 'rails_helper'
require 'shipping_rate'
RSpec.describe ShippingRate do
let(:location1) { ShippingLocation.new(country: 'US', state: 'CA', city: 'Beverly Hills', zip: '90210') }
let(:location2) { ShippingLocation.new(country: 'US', state: 'WA', city: 'Seattle', zip: '98101') }
let(:package) { ActiveShipping::Package.new(12, [15, 10, 4.5], :units => :imperial) }
describe 'validations' do
it 'is valid' do
r = ShippingRate.new(origin: location1, destination: location2, package: package)
expect(r).to be_valid
end
it 'requires an origin' do
r = ShippingRate.new(destination: location2, package: package)
expect(r).to be_invalid
expect(r.errors).to include :origin
end
it 'requires a destination' do
r = ShippingRate.new(origin: location1, package: package)
expect(r).to be_invalid
expect(r.errors).to include :destination
end
it 'requires a package' do
r = ShippingRate.new(origin: location1, destination: location2)
expect(r).to be_invalid
expect(r.errors).to include :package
end
describe "location validations" do
let(:location_string) { "location" }
let(:invalid_location) { ShippingLocation.new(country: 'US', state: 'WA', city: 'Seattle') }
describe "origin" do
it "does not accept a string" do
r = ShippingRate.new(origin: location_string, destination: location2, package: package)
expect(r).to be_invalid
expect(r.errors).to include :origin
end
it "does not accept an invalid location object" do
r = ShippingRate.new(origin: invalid_location, destination: location2, package: package)
expect(r).to be_invalid
expect(r.errors).to include :origin
end
end
describe "destination" do
it "does not accept a string" do
r = ShippingRate.new(origin: location1, destination: location_string, package: package)
expect(r).to be_invalid
expect(r.errors).to include :destination
end
it "does not accept an invalid location object" do
r = ShippingRate.new(origin: location1, destination: invalid_location, package: package)
expect(r).to be_invalid
expect(r.errors).to include :destination
end
end
end
describe "package validations" do
let(:package_string) { "package" }
it "does not accept a string" do
r = ShippingRate.new(origin: location1, destination: location2, package: package_string)
expect(r).to be_invalid
expect(r.errors).to include :package
end
end
end
describe "UPS" do
let(:ups) {ShippingRate.new(origin: location1, destination: location2, package: package)}
let(:response) {VCR.use_cassette("/ups_rates", record: :new_episodes) {ups.ups_rates}}
it "returns an array" do
expect(response).to be_an_instance_of Array
end
it "should sort by price" do
rates = response.map { |rate| rate[:price] }
expect(rates.sort).to eq(rates)
end
end
describe '#usps_rates' do
let(:shipping_rate) { ShippingRate.new( origin: location1, destination: location2, package: package ) }
describe "the response" do
let(:response) { VCR.use_cassette('USPS') { shipping_rate.usps_rates } }
it "returns an array of hashes" do
expect(response).to be_an_instance_of(Array)
expect(response.first).to be_an_instance_of(Hash)
end
it "is sorted by price" do
rates = response.map{ |rate| rate[:price] }
expect(rates.sort).to eq(rates)
end
end
end
end
| true |
6f26d74317dc85715ae2c30f31087c7790d599bb | Ruby | rwilt/ruby-oo-object-relationships-has-many-through-nyc01-seng-ft-042020 | /lib/meal.rb | UTF-8 | 475 | 3.328125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Meal
attr_accessor :waiter, :customer, :total, :tip
# has access to customers, waiters, total and tip
#adding accessores for these instances allow
#to read and edit them.
@@all = []
#class method to store
#every instance of a meal.
def initialize(waiter, customer, total, tip =0)
@waiter = waiter
@customer = customer
@total = total
@tip = tip
Meal.all << self
end
def self.all
@@all
end
#allows us to return an array of
#all the instances of a meal.
end | true |
a8c9abd0b84779cf9b4c6189ffae9a80848bd1ef | Ruby | jenshaw86/blood-oath-relations-seattle-web-051319 | /tools/console.rb | UTF-8 | 1,558 | 3.109375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require_relative '../config/environment.rb'
def reload
load 'config/environment.rb'
end
# Insert code here to run before hitting the binding.pry
# This is a convenient place to define variables and/or set up new object instances,
# so they will be available to test and play around with in your console
doggist = Cult.new("Doggist", "Seattle", 2019, "Let's play")
cat_com = Cult.new("Cat Communion", "New York", 2018, "Me-ow")
fish_fan = Cult.new("Fish Fanatics", "Austin", 2017, "Bloop")
antologist = Cult.new("Antologists", "Austin", 2008, "Ants Elope")
jenny = Follower.new("Jenny", 32, "Seize Everything")
peanut = Follower.new("Peanut", 11, "Eat Everything")
tella = Follower.new("Tella", 4, "Question Everything")
teddy = Follower.new("Teddy", 10, "Paws Off")
preston = Follower.new("Preston", 10, "Blah")
garfield = Follower.new("Garfield", 50, "I hate Mondays")
odie = Follower.new("Odie", 35, "Wuf")
maru = Follower.new("Maru", 8, "Mao")
rosa = Follower.new("Rosa", 12, "Tripods Unite")
souffie = Follower.new("Souffie", 8, "whine")
grumpy_cat = Follower.new("Grumpy Cat", 7, "Get out of my face")
grumpy_cat.join_cult(cat_com)
souffie.join_cult(fish_fan)
souffie.join_cult(doggist)
rosa.join_cult(doggist)
odie.join_cult(doggist)
garfield.join_cult(cat_com)
peanut.join_cult(doggist)
peanut.join_cult(cat_com)
tella.join_cult(doggist)
jenny.join_cult(doggist)
jenny.join_cult(antologist)
jenny.join_cult(cat_com)
teddy.join_cult(cat_com)
preston.join_cult(cat_com)
binding.pry
puts "Mwahahaha!" # just in case pry is buggy and exits
| true |
08bb3afc1808c668fd02fb4df7684cd7bce7b6f7 | Ruby | rishey/schedule | /helpers.rb | UTF-8 | 642 | 3.640625 | 4 | [] | no_license | def findFriday(date)
# checks if date is friday, if not checks to find the next
# friday and returns it.
until date.friday?
date += 1
end
date
end
def parseDate(dateString)
# checks to see if the date is in valid format, then checks to see
# if it is a valid date. if so, it returns a date object
dateHash = {}
if (dateHash = dateString.match('(\d\d)[\/\-\.]?(\d\d)[\/\-\.]?(\d{4})'))
month = dateHash[1].to_i
day = dateHash[2].to_i
year = dateHash[3].to_i
if Date.valid_date?(year,month,day)
return Date.new(year,month,day)
else
return false
end
else
return false
end
end | true |
7c8869f910462a46aede4048914f660af471f8c2 | Ruby | rarao/GoJekAssignment_SDET | /cleartriptestframework/api/flights/RoundTripBooking_spec.rb | UTF-8 | 1,730 | 2.53125 | 3 | [] | no_license | require_relative "../../spec_helper"
require_relative "../../payloads/geflightinfo_payload"
require_relative "../../utility/httptransport"
require_relative "../../validations/getflightinfo_validator"
require_relative "../../factories/resultsfactory"
require 'json'
describe "RoundTripTestSuite", :type => :api do
before(:all) do
# This should be picked from configuration file
@host = "https://cleartrip.com"
end
it "validates a simple round trip booking with a single traveler for DEL - BOM" do
resultsfactory = FactoryGirl.create(:results)
#In the next line of code, few parameters are being passed in addition to the factory because factories would only have those attributes which would be common to every testcase.
#The other testcase would be another 'it' block, where we could vary the request parameters.
#We could actually take whole of this code out in method and re-use it for every 'it'block(testcase)
results_endpoint = @host + "/flights/results?" + CreateResultsRequestURL(resultsfactory,"RoundTrip","New Delhi, IN - Indira Gandhi Airport DEL","DEL","Mumbai, IN - Chatrapati Shivaji Airport BOM","BOM")
resultsResponse = httpGet(results_endpoint)
expect(resultsResponse.status).to eq 200
resultsResponseHash = JSON.parse resultsResponse.body
ValidateResultsResponse(resultsResponseHash)
itinerary_id = resultsResponseHash["sid"]
getflightinfo_endpoint = @host + "/book/getflightinfo?" + itinerary_id + "&request_type=mr,bi"
getflightinfoResponse = httpGet(getflightinfo_endpoint)
expect(getflightinfoResponse.status).to eq 200
getflightinfoResponseHash = JSON.parse getflightinfoResponse.body
ValidateGetFlightInfoResponse(getflightinfoResponseHash)
end
end
end | true |
a655d5e0e852f99587ba9efe6ce11abb8bb70ad6 | Ruby | codeworm96/risp | /src/function.rb | UTF-8 | 927 | 3.046875 | 3 | [] | no_license | require_relative 'interpreter.rb'
require_relative 'environment.rb'
require_relative 'kont.rb'
require_relative 'state.rb'
class Function
def eval_term(term, env)
lambda do |list|
Interpreter.eval(term, env,
lambda do |res|
list + [res]
end)
end
end
def eval_arg_list(args, env, kont)
while !args.empty?
kont = Kont.bind(eval_term(args.last, env), kont)
args = args[0..-2]
end
kont[[]]
end
def apply(args, env, kont)
eval_arg_list(args, env,
lambda do |values|
body(*values, &kont)
end)
end
end
class Closure < Function
def initialize(formals, body, env)
@formals = formals
@body = body
@table = env
end
def body(*values, &kont)
e = Environment.new
i = 0
@formals.each {|formal|
e.define(formal, values[i])
i += 1
}
e.chain(@table)
State.new(@body, e, kont)
end
end
| true |
e43285efeb75e1843608e338b9af78a94f99e797 | Ruby | 4rchenix/rubycoast | /classes/help.rb | UTF-8 | 173 | 2.640625 | 3 | [] | no_license | class Help
attr_accessor :name, :desc, :usage, :tag
def initialize(name, desc, usage, tag)
@name = name
@desc = desc
@usage = usage
@tag = tag
end
end
| true |
d791bb82ef728c42143d47f91486eec36e991328 | Ruby | skwiens/Solar-System | /solar_system_wave3.rb | UTF-8 | 9,075 | 4.15625 | 4 | [] | no_license | # Define the class Solar System
class SolarSystem
attr_reader :planets, :age, :planet_names
# Initialize @planets as an array of planet instances
def initialize(planets)
@planets = planets
@num_of_planets = @planets.length
@age = 4600 #in million of years
@planet_names = planet_name_array
end
def num_of_planets
@num_of_planets = @planets.length
end
# Method to add planets to the array. Added planets should be objects.
def add_planet(planet_to_add)
@planets << planet_to_add
@num_of_planets = @planets.length
@planet_names = planet_name_array
end
#Create an array of planet names
def planet_name_array
@planet_names = []
@planets.each do |planet_object|
planet_name = planet_object.name.downcase
@planet_names << planet_name
end
return @planet_names
end
#Generates a list of planet names
def list_planets
planet_list = ""
i = 1
@planet_names.each do |planet_name|
planet_list << "#{i}. #{planet_name.capitalize}\n"
i += 1
end
return planet_list
end
# This method finds the distance assuming they are in a straight line out from the sun.
def find_distance_between_planets(planet_1, planet_2)
information_hash = {}
information_hash[:planet_1] = @planets[planet_1.to_i].name
information_hash[:planet_2] = @planets[planet_2.to_i].name
distance = @planets[planet_1.to_i].distance_from_sun - @planets[planet_2.to_i].distance_from_sun
information_hash[:distance] = distance.abs
return information_hash
end
end #End of Solar System class
class Planet
attr_reader :name, :named_for, :diameter, :distance_from_sun, :type, :year_length, :star_system, :color, :day
def initialize(attributes = {})
@name = attributes[:name]
@named_for = attributes[:named_for] #meaning of name
@diameter = attributes[:diameter] #measured in km
@distance_from_sun = attributes[:distance_from_sun] #measured in million km
@type = attributes[:type]
@year_length = attributes[:year_length] #measured in Earth years
@star_system = attributes[:star_system]
@color = attributes[:color]
@day = attributes[:day]
end
def return_attributes
planet_summary = "
Name: #{@name}
Meaning of Name: #{@named_for}
Diameter: #{@diameter}
Celestial Object: #{@type}
Color: #{@color}
Length of Year (in Earth years): #{@year_length}
Distance from the sun: #{@distance_from_sun.to_s} million km
Star System: #{@star_system} System
Length of day: #{@day}"
return planet_summary
end
end #End of Planet class
# Initial message used to let the determine how they want to interact with the program.
def get_choice
puts "\nThank you for using our Solar System Explorer! Here are your options:
(A) Add a planet to the list
(B) View a planet
(C) Find distance between two planets
(D) Find the local age of a planet
(E) Exit the program"
print "\nPlease select a letter: "
choice = gets.chomp.upcase
return choice
end
# If the user enters a planet name the first time, it will be accepted. If the user does not enter a correct number or name it will prompt them to enter an existing number until they do.
def valid_entry(solar_system)
print "Select a planet: "
planet_number = gets.chomp
# if user enters a planet name instead of number, that name will be used to find the index value.
if solar_system.planet_names.include?(planet_number.downcase)
planet_number = solar_system.planet_names.index(planet_number.downcase)
return planet_number.to_i
end
# If user does not enter a valid name or number they will be prompted to enter again.
until (planet_number.to_i.to_s == planet_number) && (planet_number.to_i <= solar_system.num_of_planets && planet_number.to_i>0)
print "Please select a valid number to represent a planet: "
planet_number = gets.chomp
end
planet_number = planet_number.to_i - 1
return planet_number
end
#(Choice A)
def view_planet_summary(solar_system)
puts "Choose a planet to view some if it's information: "
puts solar_system.list_planets
puts
planet_chosen = valid_entry(solar_system)
puts solar_system.planets[planet_chosen].return_attributes
end
#(Choice B)
def create_new_planet
planet = {}
planet[:name]= ""
while planet[:name] == ""
puts "Please enter the name of the planet you would like to add: "
planet[:name] = gets.chomp.capitalize
end
puts "Please provide the following attributes. (If any are unkown please type 'unknown') "
print "Meaning of planet name: "
planet[:named_for] = gets.chomp
print "Diameter(in km): "
planet[:diameter] = gets.chomp
print "Distance from the Sun (or it's star) (units: million km): "
planet[:distance_from_sun] = gets.chomp
print "Type of Celestial Object: "
planet[:type] = gets.chomp
print "Length of Year (units: Earth years): "
planet[:year_length] = gets.chomp
print "Star System: "
planet[:star_system] = gets.chomp
print "Color: "
planet[:color] = gets.chomp
print "Length of Day: "
planet[:day] = gets.chomp
planet_object = Planet.new(planet)
return planet_object
end
#(Choice C)
def view_distance_between_planets(solar_system)
puts "Choose two planets from the following list to find the distance between them:"
puts solar_system.list_planets
puts
print "Planet 1: "
planet_1 = valid_entry(solar_system)
print "Planet 2: "
planet_2 = valid_entry(solar_system)
information_hash = solar_system.find_distance_between_planets(planet_1, planet_2)
puts "The distance between #{information_hash[:planet_1]} and #{information_hash[:planet_2]} is: "
puts "#{information_hash[:distance]} million km"
end
#(Choice D)
def view_local_age_of_planet(solar_system)
puts "Choose a planet to determine it's local age: "
puts solar_system.list_planets
puts
planet_chosen = valid_entry(solar_system).to_i
local_age = solar_system.age / solar_system.planets[planet_chosen].year_length
puts format("The local age of #{solar_system.planets[planet_chosen].name} is %.2f million years", local_age)
end
#(Choice E)
def leave_program
puts "Thank you! Have a nice day!"
exit
end
# Pre-populated solar system
# distance from sun is represented in million km.
planets_in_ss = [
{
name: "Mercury",
named_for: "Messenger of the Roman gods",
diameter: 4_878,
color: "gray",
type: "planet",
year_length: 0.241,
star_system: "Solar",
day: "58.6 Earth days",
distance_from_sun: 57.9
},
{
name: "Venus",
named_for: "Roman goddess of love and beauty",
diameter: 12_104,
color: "yellow",
type: "planet",
year_length: 0.615,
star_system: "Solar",
day: "241 Earth days",
distance_from_sun: 108.2
},
{
name: "Earth",
diameter: 12_760,
color: "blue",
type: "planet",
year_length: 1,
star_system: "Solar",
day: "24 hours",
distance_from_sun: 149.6
},
{
name: "Mars",
named_for: "Roman god of war",
diameter: 6_787,
color: "red",
type: "planet",
year_length: 1.88,
star_system: "Solar",
day: "1 Earth day",
distance_from_sun: 227.9
},
{
name: "Jupiter",
named_for: "Ruler of the Roman gods",
diameter: 139_822,
color: "orange and white",
type: "planet",
year_length: 11.86,
star_system: "Solar",
day: "9.8 Earth hours",
distance_from_sun: 778.3
},
{
name: "Saturn",
named_for: "Roman god of agriculture",
diameter: 120_500,
color: "pale gold",
type: "planet",
year_length: 29.46,
star_system: "Solar",
day: "10.5 Earth hours",
distance_from_sun: 1427
},
{
name: "Uranus",
named_for: "Personification of heaven in ancient myth",
diameter: 51_120,
color: "pale blue",
type: "planet",
year_length: 84.01,
star_system: "Solar",
day: "18 earth hours",
distance_from_sun: 2871
},
{
name: "Neptune",
named_for: "Roman god of water",
diameter: 49_530,
color: "pale blue",
type: "dwarf-planet",
year_length: 164.79,
star_system: "Solar",
day: "60,200 earth days",
distance_from_sun: 4497
},
{
name: "Pluto",
named_for: "Roman god of the underworld, Hades",
diameter: 2_301,
color: "red",
type: "planet",
year_length: 248.59,
star_system: "Solar",
day: "6.4 earth days",
distance_from_sun: 5913
},
]
# Creates an array of planet objects based on the planet hashes defined above.
solar_system_planets = []
planets_in_ss.each do |planet_hash|
solar_system_planets << Planet.new(planet_hash)
end
#Creates a new solar system instance based on the planet instances
solar_system_object = SolarSystem.new(solar_system_planets)
# User interface
while true
choice = get_choice
case choice
when "A"
new_planet = create_new_planet
solar_system_object.add_planet(new_planet)
when "B"
view_planet_summary(solar_system_object)
when "C"
view_distance_between_planets(solar_system_object)
when "D"
view_local_age_of_planet(solar_system_object)
when "E"
leave_program
else
puts "\nI'm sorry that's not a valid selection. Please try again."
end
end
#############################################
| true |
4efc7de837639f789184cc5d34fc15c94f14eea4 | Ruby | machida4/pnglitch | /lib/pnglitch/base.rb | UTF-8 | 18,021 | 2.71875 | 3 | [
"MIT"
] | permissive | module PNGlitch
# Base is the class that represents the interface for PNGlitch functions.
#
# It will be initialized through PNGlitch#open and be a mainly used instance.
#
class Base
attr_reader :width, :height, :sample_size, :is_compressed_data_modified
attr_accessor :head_data, :tail_data, :compressed_data, :filtered_data, :idat_chunk_size
#
# Instanciate the class with the passed +file+
#
def initialize file, limit_of_decompressed_data_size = nil
path = Pathname.new file
@head_data = StringIO.new
@tail_data = StringIO.new
@compressed_data = Tempfile.new 'compressed', encoding: 'ascii-8bit'
@filtered_data = Tempfile.new 'filtered', encoding: 'ascii-8bit'
@idat_chunk_size = nil
@head_data.binmode
@tail_data.binmode
@compressed_data.binmode
@filtered_data.binmode
open(path, 'rb') do |io|
idat_sizes = []
@head_data << io.read(8) # signature
while bytes = io.read(8)
length, type = bytes.unpack 'Na*'
if length > io.size - io.pos
raise FormatError.new path.to_s
end
if type == 'IHDR'
ihdr = {
width: io.read(4).unpack('N').first,
height: io.read(4).unpack('N').first,
bit_depth: io.read(1).unpack('C').first,
color_type: io.read(1).unpack('C').first,
compression_method: io.read(1).unpack('C').first,
filter_method: io.read(1).unpack('C').first,
interlace_method: io.read(1).unpack('C').first,
}
@width = ihdr[:width]
@height = ihdr[:height]
@interlace = ihdr[:interlace_method]
@sample_size = {0 => 1, 2 => 3, 3 => 1, 4 => 2, 6 => 4}[ihdr[:color_type]]
io.pos -= 13
end
if type == 'IDAT'
@compressed_data << io.read(length)
idat_sizes << length
io.pos += 4 # crc
else
target_io = @compressed_data.pos == 0 ? @head_data : @tail_data
target_io << bytes
target_io << io.read(length + 4)
end
end
@idat_chunk_size = idat_sizes.first if idat_sizes.size > 1
end
if @compressed_data.size == 0
raise FormatError.new path.to_s
end
@head_data.rewind
@tail_data.rewind
@compressed_data.rewind
decompressed_size = 0
expected_size = (1 + @width * @sample_size) * @height
expected_size = limit_of_decompressed_data_size unless limit_of_decompressed_data_size.nil?
z = Zlib::Inflate.new
z.inflate(@compressed_data.read) do |chunk|
decompressed_size += chunk.size
# raise error when the data size goes over 2 times the usually expected size
if decompressed_size > expected_size * 2
z.close
self.close
raise DataSizeError.new path.to_s, decompressed_size, expected_size
end
@filtered_data << chunk
end
z.close
@compressed_data.rewind
@filtered_data.rewind
@is_compressed_data_modified = false
end
#
# Explicit file close.
#
# It will close tempfiles that used internally.
#
def close
@compressed_data.close
@filtered_data.close
self
end
#
# Returns an array of each scanline's filter type value.
#
def filter_types
types = []
wrap_with_rewind(@filtered_data) do
scanline_positions.each do |pos|
@filtered_data.pos = pos
byte = @filtered_data.read 1
types << byte.unpack('C').first
end
end
types
end
#
# Manipulates the filtered (decompressed) data as String.
#
# To set a glitched result, return the modified value in the block.
#
# Example:
#
# p = PNGlitch.open 'path/to/your/image.png'
# p.glitch do |data|
# data.gsub /\d/, 'x'
# end
# p.save 'path/to/broken/image.png'
# p.close
#
# This operation has the potential to damage filter type bytes. The damage will be a cause of
# glitching but some viewer applications might deny to process those results.
# To be polite to the filter types, use +each_scanline+ instead.
#
# Since this method sets the decompressed data into String, it may use a massive amount of
# memory. To decrease the memory usage, treat the data as IO through +glitch_as_io+ instead.
#
def glitch &block # :yield: data
warn_if_compressed_data_modified
wrap_with_rewind(@filtered_data) do
result = yield @filtered_data.read
@filtered_data.rewind
@filtered_data << result
truncate_io @filtered_data
end
compress
self
end
#
# Manipulates the filtered (decompressed) data as IO.
#
def glitch_as_io &block # :yield: data
warn_if_compressed_data_modified
wrap_with_rewind(@filtered_data) do
yield @filtered_data
end
compress
self
end
#
# Manipulates the after-compressed data as String.
#
# To set a glitched result, return the modified value in the block.
#
# Once the compressed data is glitched, PNGlitch will warn about modifications to
# filtered (decompressed) data because this method does not decompress the glitched
# compressed data again. It means that calling +glitch+ after +glitch_after_compress+
# will make the result overwritten and forgotten.
#
# This operation will often destroy PNG image completely.
#
def glitch_after_compress &block # :yield: data
wrap_with_rewind(@compressed_data) do
result = yield @compressed_data.read
@compressed_data.rewind
@compressed_data << result
truncate_io @compressed_data
end
@is_compressed_data_modified = true
self
end
#
# Manipulates the after-compressed data as IO.
#
def glitch_after_compress_as_io &block # :yield: data
wrap_with_rewind(@compressed_data) do
yield @compressed_data
end
@is_compressed_data_modified = true
self
end
#
# (Re-)computes the filtering methods on each scanline.
#
def apply_filters prev_filters = nil, filter_codecs = nil
prev_filters = filter_types if prev_filters.nil?
filter_codecs = [] if filter_codecs.nil?
current_filters = []
prev = nil
line_sizes = []
scanline_positions.push(@filtered_data.size).inject do |m, n|
line_sizes << n - m - 1
n
end
wrap_with_rewind(@filtered_data) do
# decode all scanlines
prev_filters.each_with_index do |type, i|
byte = @filtered_data.read 1
current_filters << byte.unpack('C').first
line_size = line_sizes[i]
line = @filtered_data.read line_size
filter = Filter.new type, @sample_size
if filter_codecs[i] && filter_codecs[i][:decoder]
filter.decoder = filter_codecs[i][:decoder]
end
if !prev.nil? && @interlace_pass_count.include?(i + 1) # make sure prev to be nil if interlace pass is changed
prev = nil
end
decoded = filter.decode line, prev
@filtered_data.pos -= line_size
@filtered_data << decoded
prev = decoded
end
# encode all
filter_codecs.reverse!
line_sizes.reverse!
data_amount = @filtered_data.pos # should be eof
ref = data_amount
current_filters.reverse_each.with_index do |type, i|
line_size = line_sizes[i]
ref -= line_size + 1
@filtered_data.pos = ref + 1
line = @filtered_data.read line_size
prev = nil
if !line_sizes[i + 1].nil?
@filtered_data.pos = ref - line_size
prev = @filtered_data.read line_size
end
# make sure prev to be nil if interlace pass is changed
if @interlace_pass_count.include?(current_filters.size - i)
prev = nil
end
filter = Filter.new type, @sample_size
if filter_codecs[i] && filter_codecs[i][:encoder]
filter.encoder = filter_codecs[i][:encoder]
end
encoded = filter.encode line, prev
@filtered_data.pos = ref + 1
@filtered_data << encoded
end
end
end
#
# Re-compress the filtered data.
#
# All arguments are for Zlib. See the document of Zlib::Deflate.new for more detail.
#
def compress(
level = Zlib::DEFAULT_COMPRESSION,
window_bits = Zlib::MAX_WBITS,
mem_level = Zlib::DEF_MEM_LEVEL,
strategy = Zlib::DEFAULT_STRATEGY
)
wrap_with_rewind(@compressed_data, @filtered_data) do
z = Zlib::Deflate.new level, window_bits, mem_level, strategy
until @filtered_data.eof? do
buffer_size = 2 ** 16
flush = Zlib::NO_FLUSH
flush = Zlib::FINISH if @filtered_data.size - @filtered_data.pos < buffer_size
@compressed_data << z.deflate(@filtered_data.read(buffer_size), flush)
end
z.finish
z.close
truncate_io @compressed_data
end
@is_compressed_data_modified = false
self
end
#
# Process each scanline.
#
# It takes a block with a parameter. The parameter must be an instance of
# PNGlitch::Scanline and it provides ways to edit the filter type and the data
# of the scanlines. Normally it iterates the number of the PNG image height.
#
# Here is some examples:
#
# pnglitch.each_scanline do |line|
# line.gsub!(/\w/, '0') # replace all alphabetical chars in data
# end
#
# pnglicth.each_scanline do |line|
# line.change_filter 3 # change all filter to 3, data will get re-filtering (it won't be a glitch)
# end
#
# pnglicth.each_scanline do |line|
# line.graft 3 # change all filter to 3 and data remains (it will be a glitch)
# end
#
# See PNGlitch::Scanline for more details.
#
# This method is safer than +glitch+ but will be a little bit slow.
#
# -----
#
# Please note that +each_scanline+ will apply the filters *after* the loop. It means
# a following example doesn't work as expected.
#
# pnglicth.each_scanline do |line|
# line.change_filter 3
# line.gsub! /\d/, 'x' # wants to glitch after changing filters.
# end
#
# To glitch after applying the new filter types, it should be called separately like:
#
# pnglicth.each_scanline do |line|
# line.change_filter 3
# end
# pnglicth.each_scanline do |line|
# line.gsub! /\d/, 'x'
# end
#
def each_scanline # :yield: scanline
return enum_for :each_scanline unless block_given?
prev_filters = self.filter_types
is_refilter_needed = false
filter_codecs = []
wrap_with_rewind(@filtered_data) do
at = 0
scanline_positions.push(@filtered_data.size).inject do |pos, delimit|
scanline = Scanline.new @filtered_data, pos, (delimit - pos - 1), at
yield scanline
if fabricate_scanline(scanline, prev_filters, filter_codecs)
is_refilter_needed = true
end
at += 1
delimit
end
end
apply_filters(prev_filters, filter_codecs) if is_refilter_needed
compress
self
end
#
# Access particular scanline(s) at passed +index_or_range+.
#
# It returns a single Scanline or an array of Scanline.
#
def scanline_at index_or_range
base = self
prev_filters = self.filter_types
filter_codecs = Array.new(prev_filters.size)
scanlines = []
index_or_range = self.filter_types.size - 1 if index_or_range == -1
range = index_or_range.is_a?(Range) ? index_or_range : [index_or_range]
at = 0
scanline_positions.push(@filtered_data.size).inject do |pos, delimit|
if range.include? at
s = Scanline.new(@filtered_data, pos, (delimit - pos - 1), at) do |scanline|
if base.fabricate_scanline(scanline, prev_filters, filter_codecs)
base.apply_filters(prev_filters, filter_codecs)
end
base.compress
end
scanlines << s
end
at += 1
delimit
end
scanlines.size <= 1 ? scanlines.first : scanlines
end
def fabricate_scanline scanline, prev_filters, filter_codecs # :nodoc:
at = scanline.index
is_refilter_needed = false
unless scanline.prev_filter_type.nil?
is_refilter_needed = true
else
prev_filters[at] = scanline.filter_type
end
codec = filter_codecs[at] = scanline.filter_codec
if !codec[:encoder].nil? || !codec[:decoder].nil?
is_refilter_needed = true
end
is_refilter_needed
end
#
# Changes filter type values to passed +filter_type+ in all scanlines
#
def change_all_filters filter_type
each_scanline do |line|
line.change_filter filter_type
end
compress
self
end
#
# Checks if it is interlaced.
#
def interlaced?
@interlace == 1
end
#
# Rewrites the width value.
#
def width= w
@head_data.pos = 8
while bytes = @head_data.read(8)
length, type = bytes.unpack 'Na*'
if type == 'IHDR'
@head_data << [w].pack('N')
@head_data.pos -= 4
data = @head_data.read length
@head_data << [Zlib.crc32(data, Zlib.crc32(type))].pack('N')
break
end
end
@head_data.rewind
w
end
#
# Rewrites the height value.
#
def height= h
@head_data.pos = 8
while bytes = @head_data.read(8)
length, type = bytes.unpack 'Na*'
if type == 'IHDR'
@head_data.pos += 4
@head_data << [h].pack('N')
@head_data.pos -= 8
data = @head_data.read length
@head_data << [Zlib.crc32(data, Zlib.crc32(type))].pack('N')
@head_data.rewind
break
end
end
@head_data.rewind
h
end
#
# Save to the +file+.
#
def save file
wrap_with_rewind(@head_data, @tail_data, @compressed_data) do
open(file, 'wb') do |io|
io << @head_data.read
chunk_size = @idat_chunk_size || @compressed_data.size
type = 'IDAT'
until @compressed_data.eof? do
data = @compressed_data.read(chunk_size)
io << [data.size].pack('N')
io << type
io << data
io << [Zlib.crc32(data, Zlib.crc32(type))].pack('N')
end
io << @tail_data.read
end
end
self
end
alias output save
private
# Truncates IO's data from current position.
def truncate_io io
eof = io.pos
io.truncate eof
end
# Rewinds given IOs before and after the block.
def wrap_with_rewind *io, &block
io.each do |i|
i.rewind
end
yield
io.each do |i|
i.rewind
end
end
# Calculate positions of scanlines
def scanline_positions
scanline_pos = [0]
amount = @filtered_data.size
@interlace_pass_count = []
if self.interlaced?
# Adam7
# Pass 1
v = 1 + (@width / 8.0).ceil * @sample_size
(@height / 8.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 2
v = 1 + ((@width - 4) / 8.0).ceil * @sample_size
(@height / 8.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 3
v = 1 + (@width / 4.0).ceil * @sample_size
((@height - 4) / 8.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 4
v = 1 + ((@width - 2) / 4.0).ceil * @sample_size
(@height / 4.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 5
v = 1 + (@width / 2.0).ceil * @sample_size
((@height - 2) / 4.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 6
v = 1 + ((@width - 1) / 2.0).ceil * @sample_size
(@height / 2.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 7
v = 1 + @width * @sample_size
((@height - 1) / 2.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
scanline_pos.pop # no need to keep last position
end
loop do
v = scanline_pos.last + (1 + @width * @sample_size)
break if v >= amount
scanline_pos << v
end
scanline_pos
end
# Makes warning
def warn_if_compressed_data_modified # :nodoc:
if @is_compressed_data_modified
trace = caller_locations 1, 2
message = <<-EOL.gsub(/^\s*/, '')
WARNING: `#{trace.first.label}' is called after a modification to the compressed data.
With this operation, your changes on the compressed data will be reverted.
Note that a modification to the compressed data does not reflect to the
filtered (decompressed) data.
It's happened around #{trace.last.to_s}
EOL
message = ["\e[33m", message, "\e[0m"].join if STDOUT.tty? # color yellow
warn ["\n", message, "\n"].join
end
end
end
end
| true |
0372fd74df0711ab3fc73753cd157d0a64483631 | Ruby | msavoury/ruby-playground | /procs/ex1.rb | UTF-8 | 493 | 4.28125 | 4 | [] | no_license | #!/usr/bin/ruby
#Using the Proc constructor
double = Proc.new {|y| y * 2}
puts double.call(5)
#Using the lambda keyword
add2 = lambda {|x| x + 2}
puts add2.call(11)
#Using the -> operator
subtract4 = ->(x) { x - 4}
puts subtract4.call(40)
#the & operator
def use_block(param1, &block)
puts block.class if block_given?
param1 + 1
end
def turn_block_to_proc(&block)
block
end
use_block(1)
use_block(1){|x| x + 1}
b = turn_block_to_proc do |y|
y + 12
end
puts b.call(24)
| true |
75ce8438e24696fd70eb496ec5c835d5282779de | Ruby | jasirguzman123/hackerrank_weather | /config/initializers/hash.rb | UTF-8 | 312 | 3.03125 | 3 | [] | no_license | class Hash
def recursive_compact
each_with_object({}) do |(k, v), new_hash|
if v&.class == Hash
compacted_hash = v.recursive_compact
new_hash[k] = compacted_hash if compacted_hash.present?
elsif !v&.class.nil?
new_hash[k] = v
end
new_hash
end
end
end
| true |
5666e8261a3dd996b7872f27dc2729e2ae63e0b9 | Ruby | Suremaker/consul-deployment-agent | /tools/upload_to_artifactory.rb | UTF-8 | 1,718 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | #!/usr/bin/env ruby
require 'uri'
require 'digest/md5'
artifactory_base_url = 'http://view.artifacts.ttldev/artifactory/'
artifactory_user = ENV['ARTIFACTORY_USER']
artifactory_password = ENV['ARTIFACTORY_PASSWORD']
if ARGV.length < 2
puts "Usage: #{File.basename(__FILE__)} <base_url_path> <file1> [file2] [file3] ..."
puts
puts "E.g. #{File.basename(__FILE__)} yum-internal-master/OEL/7/x86_64 *.rpm"
exit 1
end
url_path = ARGV[0]
abort "Don't include the initial 'artifactory' in the url sub-path, just start with the repo & go down as deep as you need" if url_path =~ /^\/*artifactory\//
abort "Don't include a slash at the start of the base-artifactory-path" if url_path =~ /^\//
abort "Don't include a slash at the end of the base-artifactory-path" if url_path =~ /\/$/
abort "Provide a artifactory_user environment variable" unless artifactory_user && !artifactory_user.empty?
abort "Provide a artifactory_password environment variable" unless artifactory_password && !artifactory_password.empty?
ARGV.shift
def upload_to_artifactory( filename, url, user, password )
digMD5 = Digest::MD5.new
digSHA1 = Digest::SHA1.new
File.open( filename, 'rb' ) do |io|
buf = ""
while io.read(65536, buf) do
digMD5.update(buf)
digSHA1.update(buf)
end
end
system( "curl -v -X PUT -i -T #{filename} -u \"#{user}:#{password}\" -H\"X-Checksum-Md5:#{digMD5}\" -H\"X-Checksum-Sha1:#{digSHA1}\" #{url}" )
end
ARGV.each do |file|
puts "Uploading #{file} to ..."
file_basename = File.basename( file )
uri = URI::join( artifactory_base_url, url_path+'/', file_basename )
url = uri.to_s
puts url
upload_to_artifactory( file, url, artifactory_user, artifactory_password )
end
| true |
41c42b7c2b2e843ce2e1a01a595af9fca48917ad | Ruby | TylerBrock/books | /Practical Object Oriented Design in Ruby/chapter9/ex6.rb | UTF-8 | 1,621 | 3.109375 | 3 | [] | no_license | require 'minitest/autorun'
class Trip
attr_reader :bicycles, :customers, :vehicle
# this 'mechanic' argument could be of any class
def prepare(preparers)
preparers.each {|preparer| preparer.prepare_trip(self)}
end
end
# when every preparer is a Duke
# that responds to 'prepare_trip'
class Mechanic
def prepare_trip(trip)
trip.bicycles.each {|bicycle| prepare_bicycle(bicycle)}
end
def prepare_bicycle(bicycle)
# ...
end
end
class TripCoordinator
def prepare_trip(trip)
buy_food(trip.customers)
end
def buy_food(customers)
# ...
end
end
class Driver
def prepare_trip(trip)
vehicle = trip.vehicle
gas_up(vehicle)
fill_water_tank(vehicle)
end
def gas_up(vehicle)
# ...
end
def fill_water_tank(vehicle)
# ...
end
end
module PreparerInterfaceTest
def test_implements_the_preparer_interface
assert_respond_to(@object, :prepare_trip)
end
end
class MechanicTest < MiniTest::Unit::TestCase
include PreparerInterfaceTest
def setup
@mechanic = @object = Mechanic.new
end
end
class TripCoordinatorTest < MiniTest::Unit::TestCase
include PreparerInterfaceTest
def setup
@trip_coordinator = @object = TripCoordinator.new
end
end
class DriverTest < MiniTest::Unit::TestCase
include PreparerInterfaceTest
def setup
@driver = @object = Driver.new
end
end
class TripTest < MiniTest::Unit::TestCase
def test_requests_trip_preparation
@preparer = MiniTest::Mock.new
@trip = Trip.new
@preparer.expect(:prepare_trip, nil, [@trip])
@trip.prepare([@preparer])
@preparer.verify
end
end | true |
f63aeeb768091025ea8a0634ddd5cd52eb0f185c | Ruby | feiyu2016/feedbunch | /app/jobs/subscribe_user_job.rb | UTF-8 | 7,365 | 2.71875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ##
# Background job to subscribe a user to a feed and, optionally, put the feed in a folder.
#
# Its perform method will be invoked from a Resque worker.
class SubscribeUserJob
@queue = :subscriptions
##
# Subscribe a user to a feed and optionally put the feed in a folder
#
# Receives as arguments:
# - id of the user
# - url of the feed
# - id of the folder. It must be owned by the user. If a nil is passed, ignore it
# - boolean indicating whether the subscription is part of an OPML import process
# - id of the SubscribeJobState instance that reflects the state of the job. If a nil is passed, ignore it.
#
# If requested, the opml_import_job_state of the user is updated so that the user can see the import progress.
#
# If a job_state_id is passed, the state field of the SubscribeJobState instance will be updated when
# the job finishes, to reflect whether it finished successfully or with an error.
#
# This method is intended to be invoked from Resque, which means it is performed in the background.
def self.perform(user_id, feed_url, folder_id, running_opml_import_job, job_state_id)
# Find the SubscribeJobState instance for this job, if it exists
if job_state_id.present?
if SubscribeJobState.exists? job_state_id
job_state = SubscribeJobState.find job_state_id
# Check that the subscribe_job_state is in state "RUNNING"
if job_state.state != SubscribeJobState::RUNNING
Rails.logger.warn "Processing SubscribeUserJob for subscribe_job_state_id #{job_state_id}, it should be in state RUNNING but it is in state #{job_state.state}. Aborting."
return
end
end
end
# Check if the user actually exists
if !User.exists? user_id
Rails.logger.error "Trying to add subscription to non-existing user @#{user_id}, aborting job"
job_state.destroy if job_state.present?
return
end
user = User.find user_id
# Check if the folder actually exists and is owned by the user
if folder_id.present?
if !Folder.exists? folder_id
Rails.logger.error "Trying to add subscription in non-existing folder @#{folder_id}, aborting job"
job_state.destroy if job_state.present?
return
end
folder = Folder.find folder_id
if !user.folders.include? folder
Rails.logger.error "Trying to add subscription in folder #{folder.id} - #{folder.title} which is not owned by user #{user.id} - #{user.email}, aborting job"
job_state.destroy if job_state.present?
return
end
end
# Check that user has a opml_import_job_state with state RUNNING if requested to update it
if running_opml_import_job
if user.opml_import_job_state.try(:state) != OpmlImportJobState::RUNNING
Rails.logger.error "User #{user.id} - #{user.email} does not have a data import with state RUNNING, aborting job"
job_state.destroy if job_state.present?
return
end
end
feed = self.subscribe_feed feed_url, user, folder
# Set job state to "SUCCESS" and save the id of the actually subscribed feed
job_state.update state: SubscribeJobState::SUCCESS, feed_id: feed.id if job_state.present?
rescue RestClient::Exception, SocketError, Errno::ETIMEDOUT, AlreadySubscribedError, EmptyResponseError, FeedAutodiscoveryError, FeedFetchError, OpmlImportError => e
# all these errors mean the feed cannot be subscribed, but the job itself has not failed. Do not re-raise the error
Rails.logger.error e.message
Rails.logger.error e.backtrace
job_state.update state: SubscribeJobState::ERROR if job_state.present?
rescue => e
Rails.logger.error e.message
Rails.logger.error e.backtrace
job_state.update state: SubscribeJobState::ERROR if job_state.present?
# The job has failed. Re-raise the exception so that Resque takes care of it
raise e
ensure
# Once finished, mark import state as SUCCESS if requested.
self.update_import_state user, feed_url, folder_id if running_opml_import_job && user.try(:opml_import_job_state).present?
end
private
##
# Sets the opml_import_job_state state for the user as SUCCESS.
#
# Receives as argument the user whose import process has finished successfully, the
# URL of the feed just subscribed, and the ID of the folder into which the feed as been moved.
def self.update_import_state(user, feed_url, folder_id)
user.opml_import_job_state.processed_feeds += 1
user.opml_import_job_state.save
if self.import_finished? user, feed_url, folder_id
user.opml_import_job_state.state = OpmlImportJobState::SUCCESS
user.opml_import_job_state.save
Rails.logger.info "Sending data import success email to user #{user.id} - #{user.email}"
OpmlImportMailer.import_finished_success_email(user).deliver
end
end
##
# Subscribe a user to a feed.
#
# Receives as arguments:
# - the url of the feed
# - the user who requested the import (and who will be subscribed to the feed)
# - optionally, the folder in which the feed will be (defaults to none)
#
# If the feed already exists in the database, the user is subscribed to it.
#
# Returns the subscribed feed
def self.subscribe_feed(url, user, folder)
Rails.logger.info "Subscribing user #{user.id} - #{user.email} to feed #{url}"
feed = user.subscribe url
if folder.present? && feed.present?
Rails.logger.info "As part of OPML import, moving feed #{feed.id} - #{feed.title} to folder #{folder.title} owned by user #{user.id} - #{user.email}"
folder.feeds << feed
end
return feed
end
##
# Check if the OPML import process has finished (all enqueued jobs have finished running).
#
# Receives as argument the user whose import process is to be checked, the URL of
# the feed just subscribed, and the ID of the folder into which it's been moved.
#
# Returns a boolean: true if import is finished, false otherwise.
def self.import_finished?(user, feed_url, folder_id)
# If the number of processed feeds equals the total number of feeds in the OPML, import is finished
if user.opml_import_job_state.processed_feeds == user.opml_import_job_state.total_feeds
return true
end
# If a ImportSubscriptionJob or another SubscribeUserJob for the user is still running, import process is not finished
Resque.working.each do |w|
working_class = w.job['payload']['class']
if working_class == 'ImportSubscriptionsJob'
return false if w.job['payload']['args'][1] == user.id
elsif working_class == 'SubscribeUserJob'
args = w.job['payload']['args']
return false if args[0] == user.id && (args[1] != feed_url || args[2] != folder_id) && args[3] == true
end
end
# If a SubscribeUserJob is enqueued, import process is not finished
peek_start = 0
job = Resque.peek 'subscriptions', peek_start
while job.present?
if job['class'] == 'SubscribeUserJob'
args = job['args']
return false if args[0] == user.id && (args[1] != feed_url || args[2] != folder_id) && args[3] == true
end
peek_start += 1
job = Resque.peek 'subscriptions', peek_start
end
# If no jobs related to the import are running or queued, the import process has finished
return true
end
end | true |
6027219a5d813be43ea7fa108e5c6dd5429c77e8 | Ruby | NobodysNightmare/sprit | /app/models/fuel.rb | UTF-8 | 284 | 2.515625 | 3 | [] | no_license | # frozen_string_literal: true
class Fuel < ApplicationRecord
validates :name, presence: true
validates :unit, presence: true
# Whether or not this application is able to pull statistics about this fuel
# from an automated meter.
def meterable?
unit == 'kWh'
end
end
| true |
4308475d5d202492d74f4f0c49aed7b08e1012ed | Ruby | dkulback/backend_mod_1_prework | /section1/ex7.rb | UTF-8 | 353 | 4.28125 | 4 | [] | no_license | # Excercise 7 Asking Questions
print "How old are you? "
age = gets.chomp
print "How tall are you? "
height = gets.chomp
print "How much do you weigh? "
weight = gets.chomp
puts "So, youre #{age} old, #{height} tall and #{weight} heavy."
p "What is your name?"
name = gets.chomp
if name == "Darren"
puts "Hello Darren, we were expecting you!"
end
| true |
1701573a95632bb87018d4d48fc50d95917d9b3d | Ruby | felipegruoso/univem-scraper | /scraper.rb | UTF-8 | 429 | 3.03125 | 3 | [] | no_license | # encoding: utf-8
require 'mechanize'
class Scraper
URL = "http://univem.edu.br/"
def self.run
Scraper.new.run
end
def initialize
@agent = Mechanize.new
end
def run
@agent.get URL
courses = @agent.page.parser.css('.nomecurso')
courses_name = courses.map do |course|
course.text.gsub(/\:/, '').strip
end
puts courses_name
end
end
Scraper.run
| true |
e3b6c7fa765993560062d792392096fc187859c0 | Ruby | jgonzalezd/advent_of_code_2016 | /day_6/day_6.rb | UTF-8 | 2,241 | 3.921875 | 4 | [] | no_license | require 'byebug'
# --- Day 6: Signals and Noise ---
#
# Something is jamming your communications with Santa. Fortunately, your signal is only partially jammed, and protocol in situations like this is to switch to a simple repetition code to get the message through.
#
# In this model, the same message is sent repeatedly. You've recorded the repeating message signal (your puzzle input), but the data seems quite corrupted - almost too badly to recover. Almost.
#
# All you need to do is figure out which character is most frequent for each position. For example, suppose you had recorded the following messages:
#
# eedadn
# drvtee
# eandsr
# raavrd
# atevrs
# tsrnev
# sdttsa
# rasrtv
# nssdts
# ntnada
# svetve
# tesnvt
# vntsnd
# vrdear
# dvrsen
# enarar
# The most common character in the first column is e; in the second, a; in the third, s, and so on. Combining these characters returns the error-corrected message, easter.
#
# Given the recording in your puzzle input, what is the error-corrected version of the message being sent?
#
file = File.open('input.txt')
ocurrences = {}
file.each_line do |line|
line.strip.split("").each_with_index do |char, index|
ocurrences[index] ||= Hash.new(0)
ocurrences[index][char] += 1
end
end
file.close
puts ocurrences.inject([]){|obj,pair| obj << pair[1].max_by{|c,f| f }[0] }.join
# --- Part Two ---
#
# Of course, that would be the message - if you hadn't agreed to use a modified repetition code instead.
#
# In this modified code, the sender instead transmits what looks like random data, but for each character, the character they actually want to send is slightly less likely than the others. Even after signal-jamming noise, you can look at the letter distributions in each column and choose the least common letter to reconstruct the original message.
#
# In the above example, the least common character in the first column is a; in the second, d, and so on. Repeating this process for the remaining characters produces the original message, advent.
#
# Given the recording in your puzzle input and this new decoding methodology, what is the original message that Santa is trying to send?
puts ocurrences.inject([]){|obj,pair| obj << pair[1].min_by{|c,f| f }[0] }.join
| true |
fe8addec78cb0102fd756d5f94d39574f47c9bc1 | Ruby | zendesk/Hermann | /lib/hermann.rb | UTF-8 | 833 | 2.671875 | 3 | [
"MIT"
] | permissive | module Hermann
def self.jruby?
return RUBY_PLATFORM == "java"
end
# Validates that the args are non-blank strings
#
# @param [Object] key to validate
#
# @param [Object] val to validate
#
# @raises [ConfigurationErorr] if either values are empty
def self.validate_property!(key, val)
if key.to_s.empty? || val.to_s.empty?
raise Hermann::Errors::ConfigurationError
end
end
# Packages options into Java Properties object
#
# @params [Hash] hash of options to package
#
# @return [Properties] packaged java properties
def self.package_properties(options)
properties = JavaUtil::Properties.new
options.each do |key, val|
Hermann.validate_property!(key, val)
properties.put(key, val)
end
properties
end
end
if Hermann.jruby?
require 'hermann/java'
end
| true |
2817e39faf1e5bdde6256ea3a21720870af0e7d9 | Ruby | aforesti/hw1 | /part5_spec.rb | UTF-8 | 310 | 2.765625 | 3 | [] | no_license | require "rspec"
require "rspec/autorun"
require "./part5"
class Foo
attr_accessor_with_history :bar
end
describe Foo do
it "should has history" do
f = Foo.new
f.bar = 3
f.bar = :wowzo
f.bar = 'boo!'
f.bar_history.should eq [nil, 3, :wowzo, 'boo!']
end
end | true |
241f3dec0e2652c530c7ab6540aa9e57de661f47 | Ruby | perrinjack/oystercard_challenge | /spec/oystercard_spec.rb | UTF-8 | 1,869 | 2.84375 | 3 | [] | no_license | # frozen_string_literal: true
require 'oystercard'
describe Oystercard do
let(:entry_station) { double(:entry_station) }
let(:exit_station) { double(:exit_station) }
let(:journey) { double(:Journey) }
let(:zero_card) { Oystercard.new }
let(:new_card) { Oystercard.new(10, journey) }
it 'starts with an empty list of journeys' do
expect(new_card.journeys).to eq []
end
it 'has a balance' do
expect(Oystercard.new.balance).to eq(Oystercard::DEFAULT_BALANCE)
end
it 'tops up balance with' do
expect { new_card.top_up(10) }.to change { new_card.balance }.by 10
end
it 'errors with over limit' do
message = "Error, card has limit of #{Oystercard::TOP_UP_LIMIT}"
expect { new_card.top_up(Oystercard::TOP_UP_LIMIT + 1) } .to raise_error message
end
it "should raise_error 'No money' if balance is below min_fare" do
expect { zero_card.touch_in(entry_station) }.to raise_error('No money')
end
#it 'new test' do
# allow(journey).to receive(:new) { journey }
#allow(journey).to receive(:nil?) { false}
#new_card.touch_in(entry_station)
#expect { new_card.touch_in(entry_station) }.to change { new_card.balance }.by -Oystercard::PENALTY_FARE
#end
before do
allow(journey).to receive(:new) { journey }
allow(journey).to receive(:calculate_fare) { Oystercard::PENALTY_FARE}
end
it 'deducts from balance when you forget to touch out' do
new_card.touch_in(entry_station)
expect { new_card.touch_in(entry_station) }.to change { new_card.balance }.by -Oystercard::PENALTY_FARE
end
it 'deducts from balance when you forget to touch in' do
allow(journey).to receive(:nil?) { true}
new_card.touch_in(entry_station)
new_card.touch_out(exit_station)
expect { new_card.touch_out(exit_station) }.to change { new_card.balance }.by -Oystercard::PENALTY_FARE
end
end
| true |
8ece4f970b0cb9c75ccc6dd28d0f576d71a1bca3 | Ruby | bootstraponline/angular_webdriver | /lib/angular_webdriver/protractor/by_repeater_inner.rb | UTF-8 | 4,264 | 2.875 | 3 | [] | no_license | module AngularWebdriver
class ByRepeaterInner
attr_reader :exact, :repeat_descriptor, :row_index, :column_binding
# Takes args and returns wrapped repeater if the first arg is a repeater
#
# @param args [Array] args to wrap
def self.wrap_repeater args
if args && args.first.is_a?(self)
[repeater: args.first.process] # watir requires an array containing a hash
else
args
end
end
# Generate either by.repeater or by.exactRepeater
# @option opts [Boolean] :exact exact matching
# @option opts [String] :repeat_descriptor repeat description
def initialize opts={}
exact = opts.fetch(:exact)
raise "#{exact} is not a valid value" unless [true, false].include?(exact)
repeat_descriptor = opts.fetch(:repeat_descriptor)
raise "#{repeat_descriptor} is not a valid repeat_descriptor" unless repeat_descriptor.is_a?(String)
@exact = exact
@repeat_descriptor = repeat_descriptor
self
end
def row row_index
raise "#{row_index} is not a valid row index" unless row_index.is_a?(Integer)
@row_index = row_index
self
end
def column column_binding
raise "#{column_binding} is not a valid column binding" unless column_binding.is_a?(String)
@column_binding = column_binding
self
end
# Return JSON representation of the correct repeater method and args
def process
# findRepeaterElement - (repeater, exact, index, binding, using, rootSelector) - by.repeater('baz in days').row(0).column('b') - [baz in days, false, 0, b, null, body]
# findRepeaterRows - (repeater, exact, index, using) - by.repeater('baz in days').row(0) - [baz in days, false, 0, null, body]
# findRepeaterColumn - (repeater, exact, binding, using, rootSelector) - by.repeater('baz in days').column('b') - [baz in days, false, b, null, body]
# findAllRepeaterRows - (repeater, exact, using) - by.repeater('baz in days') - [baz in days, false, null, body]
#
#
# using - parent element
# rootSelector - selector for finding angular js
# exact - true if by.exactRepeater false when by.repeater
#
#
# repeater (repeat_descriptor), binding (column_binding), index (row_index)
#
# findRepeaterElement - (repeat_descriptor, row_index, column_binding)
# findRepeaterRows - (repeat_descriptor, row_index)
# findRepeaterColumn - (repeat_descriptor, column_binding)
# findAllRepeaterRows - (repeat_descriptor)
result = if repeat_descriptor && row_index && column_binding
{
script: :findRepeaterElement,
args: {
repeat_descriptor: repeat_descriptor,
exact: exact,
row_index: row_index,
column_binding: column_binding,
}
}
elsif repeat_descriptor && row_index
{
script: :findRepeaterRows,
args: {
repeat_descriptor: repeat_descriptor,
exact: exact,
row_index: row_index
}
}
elsif repeat_descriptor && column_binding
{
script: :findRepeaterColumn,
args: {
repeat_descriptor: repeat_descriptor,
exact: exact,
column_binding: column_binding
}
}
elsif repeat_descriptor
{
script: :findAllRepeaterRows,
args: {
repeat_descriptor: repeat_descriptor,
exact: exact
}
}
else
raise 'Invalid repeater'
end
result.to_json
end # def process
end # class ByRepeaterInner
end # module AngularWebdriver
| true |
b62d20fd9c8d1842dcbc2eea3d3a29f2981cf13d | Ruby | TabathaSlatton/collections_practice-onl01-seng-ft-081720 | /collections_practice.rb | UTF-8 | 1,006 | 3.765625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def sort_array_asc(array)
array.sort
end
def sort_array_desc(array)
array.sort.reverse
end
def sort_array_char_count(array)
array.sort do |a,b|
a.length <=> b.length
end
end
def swap_elements(array)
second = array[1]
third = array[2]
array[2] = second
array[1] = third
array
end
def reverse_array(array)
array.reverse
end
def kesha_maker(array)
array.map do|name|
name_array = name.split("")
name_array[2] = "$"
name_array.join
end
end
def find_a(array)
i=0
new_array = []
while i < array.length
new_array << array[i] if array[i].start_with?("a")
i += 1
end
new_array
end
def sum_array(array)
i = 0
sum = 0
while i < array.length
sum += array[i]
i += 1
end
sum
end
def add_s(array)
i = 0
new_array = []
while i < array.length
i == 1 ? new_array.push(array[i]) : new_array.push(array[i] + "s")
i += 1
end
new_array
end | true |
ab7d01dfc406fd80027bdc9cf6c9376848a316d3 | Ruby | Vaa3D/vaa3d_tools | /released_plugins/v3d_plugins/open_fiji/Fiji.app/plugins/Examples/Plasma_Cloud.rb | UTF-8 | 6,271 | 3.375 | 3 | [
"MIT"
] | permissive | # This is a simple script showing how to create a "plasma cloud" in
# JRuby. This is *very* slow way of implementing this, but hopefully
# it's an instructive example. See this page for more details:
#
# http://fiji.sc/wiki/index.php/JRuby_Scripting
# ------------------------------------------------------------------------
# The width and the height; these are global variables so that
# "to_index" can use them:
$w = 400
$h = 300
# Create a single slice RGB image and get the pixels array:
cp = ij.process.ColorProcessor.new($w,$h)
$i = ij.ImagePlus.new "Plasma Cloud", cp
pixels = cp.getPixels
# A helper function to find the index into the pixel array:
def to_index( x, y )
x + y * $w
end
# Take a list of integer values and return a list with the midpoint
# between each inserted into the list:
def subdivide( points )
new_points = []
points.each_index do |index|
next if index == (points.length - 1)
min = points[index]
max = points[index+1]
new_points.push min
mid = (min + max) / 2
new_points.push mid
end
new_points.push points.last
new_points
end
# Seed the random number generator so we get a different cloud each time:
$rng = java.util.Random.new( Time.now.to_i )
# Keep track of the last time we updated the display:
$last_time_displayed = java.lang.System.currentTimeMillis
$update_every = 1000
def set_interpolated_points( pixels, x_min, x_mid, x_max, y_min, y_mid, y_max )
# Don't redraw all the time, only every $update_every milliseconds
now = java.lang.System.currentTimeMillis
if (now - $last_time_displayed) > $update_every
$last_time_displayed = now
$i.updateAndDraw
end
# Do nothing if there are no pixels to fill in:
return if (((x_max - x_min) <= 1) && ((y_max - y_min) <= 1))
# Set the points in the middle of the top row and the bottom row:
if x_mid != x_min
pixels[ to_index( x_mid, y_min ) ] =
color_between( x_max - x_mid,
[ pixels[ to_index( x_min, y_min ) ],
pixels[ to_index( x_max, y_min ) ] ] )
pixels[ to_index( x_mid, y_max ) ] =
color_between( x_max - x_mid,
[ pixels[ to_index( x_min, y_max ) ],
pixels[ to_index( x_max, y_max ) ] ] )
end
# Set the points in the middle of the left colum and the right column:
if y_mid != y_min
pixels[ to_index( x_min, y_mid ) ] =
color_between( y_max - y_mid,
[ pixels[ to_index( x_min, y_min ) ],
pixels[ to_index( x_min, y_max ) ] ] )
pixels[ to_index( x_max, y_mid ) ] =
color_between( y_max - y_mid,
[ pixels[ to_index( x_max, y_min ) ],
pixels[ to_index( x_max, y_max ) ] ] )
end
# Now the middle point:
xdiff = (x_max - x_min) / 2.0
ydiff = (y_max - y_min) / 2.0
separation = Math.sqrt( xdiff*xdiff + ydiff*ydiff )
pixels[ to_index( x_mid, y_mid ) ] =
color_between( separation,
[ pixels[ to_index( x_min, y_min ) ],
pixels[ to_index( x_max, y_min ) ],
pixels[ to_index( x_min, y_max ) ],
pixels[ to_index( x_max, y_max ) ] ] )
end
# Get a random RGB value for the initial corner points:
def random_color
r = $rng.nextInt 256
g = $rng.nextInt 256
b = $rng.nextInt 256
b + (g << 8) + (r << 16)
end
# Return 'old_value' plus some noise up to 'greatest_difference',
# making sure we don't return a value > 255 or < 0:
def add_noise( old_value, greatest_difference )
new_value = old_value + $rng.nextInt( 2 * greatest_difference ) - greatest_difference
if new_value > 255
255
elsif new_value < 0
0
else
new_value
end
end
# 'colors' is a list of the colors at 'separation' distance form some
# point; return a color which is an average of those plus some random
# noise linearly related to the separation:
def color_between( separation, colors )
separation = 1 if separation < 1
sum_red = sum_green = sum_blue = n = 0
colors.each do |c|
n += 1
sum_blue += c & 0xFF
sum_green += (c >> 8) & 0xFF;
sum_red += (c >> 16) & 0xFF;
end
# The basic value is the mean of the surrounding colors:
new_r = sum_red / n
new_g = sum_green / n
new_b = sum_blue / n
# Let's say we can add a random value between -256 and 256 when the
# separation is half the maximum of $w and $h, and we can only add 0
# if they're adjacent:
greatest_difference = Integer( ( 256.0 * separation ) / ([ $w, $h ].max / 2) )
new_r = add_noise( new_r, greatest_difference )
new_g = add_noise( new_g, greatest_difference )
new_b = add_noise( new_b, greatest_difference )
# Now return the result:
new_b + (new_g << 8) + (new_r << 16)
end
# Set random colors in the corners:
pixels[ 0 ] = random_color
pixels[ to_index( 0, $h - 1 ) ] = random_color
pixels[ to_index( $w - 1, 0 ) ] = random_color
pixels[ to_index( $w - 1, $h - 1 ) ] = random_color
x_points = [ 0, $w - 1 ]
y_points = [ 0, $h - 1 ]
did_something_last_time = true
$i.show
while true
did_something_last_time = false
# Divide up the x_points and y_points to find the midpoints to add:
new_x_points = subdivide x_points
new_y_points = subdivide y_points
# Now for each sub-rectangle we should have set the colours of the
# corners, so set the interpolated midpoints based on those:
new_y_points.each_index do |y_min_index|
next unless (y_min_index % 2) == 0
next unless y_min_index < (new_y_points.length - 2)
y_min = new_y_points[y_min_index]
y_mid = new_y_points[y_min_index+1]
y_max = new_y_points[y_min_index+2]
new_x_points.each_index do |x_min_index|
next unless (x_min_index % 2) == 0
next unless x_min_index < (new_x_points.length - 2)
x_min = new_x_points[x_min_index]
x_mid = new_x_points[x_min_index+1]
x_max = new_x_points[x_min_index+2]
set_interpolated_points( pixels, x_min, x_mid, x_max, y_min, y_mid, y_max )
end
end
x_points = new_x_points.uniq
y_points = new_y_points.uniq
# We can break when the list of edge points in x and y is the same
# as the width and the height:
break if (x_points.length == $w) && (y_points.length == $h)
end
$i.updateAndDraw
| true |
a6bd80071ef08a6ee4c5f7e44383fd0da8ee4ae3 | Ruby | seccabimmons/onboarding | /week_1/2_word_count.rb | UTF-8 | 455 | 3.875 | 4 | [] | no_license | # given an array of strings, return a Hash with a key for each different string,
# with the value the number of times that string appears in the array.
# wordCount(["a", "b", "a", "c", "b"]) → {"a": 2, "b": 2, "c": 1}
# wordCount(["c", "b", "a"]) → {"a": 1, "b": 1, "c": 1}
# wordCount(["c", "c", "c", "c"]) → {"c": 4}
class String_Count
def search_array (some_array)
some_array.group_by(&:itself).transform_values(&:count)
end
end | true |
88081d10fea365484874bb9a0b91ead321e50b66 | Ruby | Pi-hils/process_review | /review_2/lib/filter.rb | UTF-8 | 527 | 3.28125 | 3 | [] | no_license | class Filter
DEFAULT_LOWEST = 40
DEFAULT_HIGHEST = 1000
def music_filter(sound_wave,lowest_filter=DEFAULT_LOWEST, highest_filter= DEFAULT_HIGHEST)
new_sound_wave = []
raise "no soundwave provided" if sound_wave == []
sound_wave.each do |freq|
if freq > highest_filter
new_sound_wave << highest_filter
elsif
freq < lowest_filter
new_sound_wave<<lowest_filter
else
new_sound_wave<<freq
end
end
return new_sound_wave
end
end | true |
b121175941398ff3c9e05d94f5c96b7752140fef | Ruby | apriichiu/GSCC-Web | /vendor/gems/faraday-0.4.6/test/connection_app_test.rb | UTF-8 | 1,449 | 2.65625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | require File.expand_path(File.join(File.dirname(__FILE__), 'helper'))
class TestConnectionApps < Faraday::TestCase
class TestAdapter
def initialize(app)
@app = app
end
def call(env)
[200, {}, env[:test]]
end
end
class TestMiddleWare
def initialize(app)
@app = app
end
def call(env)
env[:test] = 'hi'
@app.call(env)
end
end
def setup
@conn = Faraday::Connection.new do |b|
b.use TestMiddleWare
b.use TestAdapter
end
end
def test_builder_is_built_from_faraday_connection
assert_kind_of Faraday::Builder, @conn.builder
assert_equal 3, @conn.builder.handlers.size
end
def test_builder_adds_middleware_to_builder_stack
assert_kind_of TestMiddleWare, @conn.builder[0].call(nil)
assert_kind_of TestAdapter, @conn.builder[1].call(nil)
end
def test_to_app_returns_rack_object
assert @conn.to_app.respond_to?(:call)
end
def test_builder_is_passed_to_new_faraday_connection
new_conn = Faraday::Connection.new :builder => @conn.builder
assert_equal @conn.builder, new_conn.builder
end
def test_builder_is_built_on_new_faraday_connection
new_conn = Faraday::Connection.new
new_conn.build do |b|
b.run @conn.builder[0]
b.run @conn.builder[1]
end
assert_kind_of TestMiddleWare, new_conn.builder[0].call(nil)
assert_kind_of TestAdapter, new_conn.builder[1].call(nil)
end
end
| true |
c66eafef2d179fc6e4f989b21444490dcce22e55 | Ruby | idealprojectgroup/ey-notifier | /spec/support/deploy.rb | UTF-8 | 135 | 2.546875 | 3 | [
"MIT"
] | permissive | class Deploy
def some_method(what)
# no-op
end
def callback(what)
some_method(what)
"some return value"
end
end
| true |
ba0c97b0616a10669d930bc787eb4fc806c3d730 | Ruby | moonmaster9000/board_app | /board/lib/board/use_cases/standups/archive_standup_use_case.rb | UTF-8 | 1,059 | 2.6875 | 3 | [] | no_license | module Board
module UseCases
class ArchiveStandupUseCase
class << self
def archivers
@archivers ||= []
end
def add_archiver(lambda)
archivers << lambda
end
end
def initialize(whiteboard_id:, observer:, date:, repo_factory:)
@repo_factory = repo_factory
@observer = observer
@whiteboard_id = whiteboard_id
@date = date
end
def execute
run_archivers
notify_observer
end
private
def run_archivers
self.class.archivers.each do |archiver|
archiver.call(repo_factory: @repo_factory, whiteboard_id: @whiteboard_id, date: @date)
end
end
def notify_observer
@observer.standup_archived
end
end
end
end
Dir[File.join(__dir__, "..", "**", "standup_item_archivers", "*.rb")].each do |archiver|
require archiver
end
module Board
class UseCaseFactory
def archive_standup(*args)
UseCases::ArchiveStandupUseCase.new(*args)
end
end
end
| true |
02a781de989716ac9eb9b18d0a0969fe1bdc0dc6 | Ruby | ed-karabinus/project-euler-multiples-3-5-q-000 | /lib/multiples.rb | UTF-8 | 348 | 3.484375 | 3 | [] | no_license | # Enter your procedural solution here!
def collect_multiples(limit)
multiples = Array.new
index = 1
until index == limit
if index % 3 == 0 || index % 5 == 0
multiples << index
end
index += 1
end
multiples
end
def sum_multiples(limit)
sum = 0
collect_multiples(limit).each do |index|
sum += index
end
sum
end | true |
22b27c3a06b229b66b99165fe52a1af546b1cbf3 | Ruby | punjabdapunk/pinvaders | /lib/pinvaders/star.rb | UTF-8 | 789 | 2.953125 | 3 | [
"MIT"
] | permissive | module Pinvaders
class Star
attr_accessor :x, :y
def initialize(args={})
@vp = args[:vp]
@brake = default_brake
@height = default_height
@x = 0
@y = 0
@brake_count = @brake
@brush = Painter.new(@vp)
end
def default_brake
1
end
def default_height
1
end
def default_star
@vp.move(x, y)
@brush.rainbow {@vp.draw(".")}
end
def reset
x = 0
y = 0
@brake_count = @brake
end
def pos(x, y)
@x = x
@y = y
end
def scroll_y
@y += 1 if @brake_count == 0
end
def draw
default_star
@brake_count = (@brake_count == 0) ? @brake : @brake_count - 1
end
def scrolled_off?
y > @vp.y_end
end
end
end
| true |
13dd4841a93e6fc58fec676501bafc2335c1b258 | Ruby | Alefuentes982/desafios-ciclos | /fuerza_bruta.rb | UTF-8 | 458 | 3.21875 | 3 | [] | no_license | puts "Ingrese password"
contraseña = gets.chomp
def descubre_metodo(contraseña)
arreglo = contraseña.chars
intentos= 0
cadena = ""
letra = "a"
if arreglo != letra
for i in ("a"..contraseña)
cadena += letra
letra = letra.next
i = 1
for j in (1..i)
intentos += j
end
end
puts "#{intentos} intentos"
print "su password es: #{arreglo.join('')}"
end
end
descubre_metodo(contraseña)
| true |
0793e53e0a25d7a1c4f98b1bce3663b824136e18 | Ruby | choplin/fluent-plugin-statsite | /lib/fluent/plugin/statsite/metric_format.rb | UTF-8 | 852 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | module Fluent
module StatsitePlugin
# This represent a key/value format of Metric
class MetricFormat
CONSTANT_VALUE = '\w+'
SUBSTITUTE = '\$\{\w+\}'
SUBSTITUTE_REGEXP = /\$\{(\w+)\}/
ELEMENT = "(?:#{CONSTANT_VALUE}|#{SUBSTITUTE})"
PATTERN = "#{ELEMENT}+"
def initialize(str)
@str = str
@no_substitute = str.index('$').nil?
end
def convert(record)
if @no_substitute
@str
else
@str.gsub(SUBSTITUTE_REGEXP) { record.fetch($1) } rescue nil
end
end
def to_s
@str
end
def self.validate(str)
if /^#{PATTERN}$/.match(str).nil?
raise ConfigError, "invalid format of key/value field, it must be #{PATTERN}, but specified as #{str}"
end
new(str)
end
end
end
end
| true |
98d3d8fc8c02a270d267b7873d20b3d24d103d8d | Ruby | KellyAH/ruby_school | /play/var_pointer_ex01.rb | UTF-8 | 495 | 3.421875 | 3 | [] | no_license | a = "cat"
p a
p a.object_id
myarray = Array.new(3, a)
p myarray
p myarray.object_id
def get_array_contents(array)
print "-" * 8
puts "array contents:"
p array
puts "array contents ids:"
array.each {|item| p item.object_id}
end
get_array_contents(myarray)
print "-" * 8
puts "before mutation of var a:"
p a
puts "after mutation of var a:"
a.upcase!
p a
get_array_contents(myarray)
print "-" * 8
puts "reassignment of a:"
a = "dog"
p a
p a.object_id
get_array_contents(myarray)
| true |
658b845e017b24549994f12a317d98d90850c9a3 | Ruby | stennity8/ttt-with-ai-project-online-web-sp-000 | /lib/players/computer.rb | UTF-8 | 2,607 | 3.390625 | 3 | [] | no_license | module Players
class Computer < Player
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], #Second Column
[2, 5, 8], #Third Column
[0, 4, 8], #Diagonal left to right
[2, 4, 6], #Diagonal right to left
]
def move(board)
if board.cells.count{|position| position != " " } == 0
"1"
elsif board.cells.count{|position| position != " " } == 1
board.cells.find_index("X") == 5 ? "1" : "7"
else
if board.cells.count{|position| position != " " } >= 4
move = ""
available_moves = []
available_moves_ints = []
board.cells.map.with_index(1) do |position, index|
if position == " "
available_moves << index.to_s
available_moves_ints << index
end
end
available_moves_ints.each do |move_option|
WIN_COMBINATIONS.each do |winning_combo|
if winning_combo.include?(move_option)
make_move_array = winning_combo.reject{|e| e == move_option}
if board.cells[make_move_array[0]] == board.cells[make_move_array[1]] && board.cells[make_move_array[0]] == self.token
move = move_option.to_s
end
end
end
end
if move == ""
available_moves.sample
else
move
end
else
available_moves = []
board.cells.map.with_index(1) do |position, index|
if position == " "
available_moves << index.to_s
end
end
available_moves.sample
end
end
end
end
end
# no strategy
# module Players
# class Computer < Player
# def move(board)
# output = (1..9).to_a.sample.to_s
# end
# end
# end
# Basic Strategy
# module Players
# class Computer < Player
# def move(board)
# if board.cells.count{|position| position != " " } == 0
# "1"
# elsif board.cells.count{|position| position != " " } == 1
# board.cells.find_index("X") == 4 ? "0" : "5"
# else
# available_moves = []
# board.cells.map.with_index(1) do |position, index|
# if position == " "
# available_moves << index.to_s
# end
# end
# available_moves.sample
# 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.