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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
542bbd78ba6b7fd8832e59faddd6b749b444e2cd | Ruby | helenakolberg/project_book_shop | /models/author.rb | UTF-8 | 2,020 | 3.4375 | 3 | [] | no_license | require_relative('../db/sql_runner.rb')
class Author
attr_reader :id
attr_accessor :first_name, :last_name, :bio, :status
def initialize(options)
@id = options['id'].to_i if options['id']
@first_name = options['first_name']
@last_name = options['last_name']
@bio = options['bio']
@status = options['status']
end
def save()
sql = "INSERT INTO authors (first_name, last_name, bio, status)
VALUES ($1, $2, $3, $4) RETURNING id"
values = [@first_name, @last_name, @bio, @status]
result = SqlRunner.run(sql, values)
@id = result[0]['id'].to_i
end
def self.delete_all()
sql = "DELETE FROM authors"
SqlRunner.run(sql)
end
def delete()
sql = "DELETE FROM authors WHERE id = $1"
values = [@id]
SqlRunner.run(sql, values)
end
def self.map_items(data)
return data.map { |author| Author.new(author) }
end
def self.all()
sql = "SELECT * FROM authors"
result = SqlRunner.run(sql)
return self.map_items(result)
end
def self.find_by_id(id)
sql = "SELECT * FROM authors WHERE id = $1"
values = [id]
result = SqlRunner.run(sql, values).first
author = Author.new(result)
return author
end
def update()
sql = "UPDATE authors SET
(first_name, last_name, bio, status) = ($1, $2, $3, $4)
WHERE id = $5"
values = [@first_name, @last_name, @bio, @status, @id]
SqlRunner.run(sql, values)
end
def books()
sql = "SELECT * FROM books WHERE author_id = $1"
values = [@id]
result = SqlRunner.run(sql, values)
return Book.map_items(result)
end
def full_name()
return "#{@first_name} #{@last_name}"
end
def self.sort_alphabetically()
authors_array = Author.all()
authors = authors_array.sort_by { |author| author.last_name }
return authors
end
end | true |
451bb815c0d74c1eb40fcbb45a189c671265a532 | Ruby | andypike/stupid_data | /spec/stupid_data_spec.rb | UTF-8 | 6,711 | 2.796875 | 3 | [] | no_license | require "spec_helper"
describe StupidData do
subject(:database) { StupidData.new("dbname=stupid_data") }
context "#query" do
it "populates a collection with the correct number of records" do
results = database.query("select id, name from users")
results.count.should == 3
end
it "defines attributes that match the columns matched on the result objects" do
results = database.query("select id, name from users")
results.each do |result|
result.respond_to?(:id).should be_true
result.respond_to?(:name).should be_true
end
end
it "hydrates result object attributes with varchars" do
results = database.query("select id, name from users order by name asc")
results[0].name.should == "Amber"
results[1].name.should == "Andy"
results[2].name.should == "Michela"
end
it "hydrates result object attributes with integers" do
results = database.query("select name, age from users order by age asc")
results[0].age.should == 8
results[1].age.should == 35
results[2].age.should == 36
end
it "hydrates result object attributes with bigserial ids" do
results = database.query("select id from users order by id asc")
results[0].id.should == 1
results[1].id.should == 2
results[2].id.should == 3
end
it "hydrates result object attributes with booleans" do
results = database.query("select male from users order by id asc")
results[0].male.should be_true
results[1].male.should be_false
results[2].male.should be_false
end
it "adds magic question mark attributes for booleans" do
results = database.query("select male from users order by id asc")
results[0].male?.should be_true
results[1].male?.should be_false
results[2].male?.should be_false
end
it "hydrates result object attributes with numerics" do
results = database.query("select avg_rating from users order by avg_rating asc")
results[0].avg_rating.should == 4.5
results[1].avg_rating.should == 4.75
results[2].avg_rating.should == 5.0
end
it "hydrates result object attributes with nulls" do
results = database.query("select school from users order by id asc")
results[0].school.should be_nil
results[1].school.should be_nil
results[2].school.should == "A cool school"
end
it "hydrates result object attributes with dates" do
results = database.query("select dob from users order by id asc")
results[0].dob.should == Date.new(1977, 10, 4)
results[1].dob.should == Date.new(1978, 3, 3)
results[2].dob.should == Date.new(2005, 12, 14)
end
it "hydrates result object attributes with timestamps" do
results = database.query("select created_at from users order by id asc")
results[0].created_at.should == DateTime.new(2013, 10, 11, 20, 10, 05)
results[1].created_at.should == DateTime.new(2013, 10, 11, 12, 18, 00)
results[2].created_at.should == DateTime.new(2013, 10, 11, 05, 01, 59)
end
it "returns concrete type records if a class is supplied" do
results = database.query("select * from users order by id asc", User)
results[0].should be_a_kind_of User
results[0].name.should == "Andy"
end
it "raises an exception if there is a syntax error within the query" do
expect { database.query("select does_not_exist from wtf") }.to raise_error
end
it "supports symbol interploation of query string and hash of values (which protect against sql injection)" do
pending
end
it "supports getting a single result (first) rather than a collection" do
pending
end
end
context "#count" do
it "returns the number of matching records" do
num_of_users = database.count("select count(*) from users")
num_of_users.should == 3
end
end
context "#insert" do
it "adds a new record for an object that maps exactly object attributes -> table fields" do
order = Order.new
order.number = 123
database.insert(order)
orders = database.query("select * from orders")
orders.count.should == 1
orders.first.number.should == 123
end
it "adds a new record for an object that has additional attributes that do not match fields in the database" do
product = Product.new
product.name = "My awesome thing"
product.rating = 5
database.insert(product)
products = database.query("select * from products")
products.count.should == 1
products.first.name.should == "My awesome thing"
end
it "adds a new record for an object that has attributes missing therefore the field default value should be used instead" do
coffee = Coffee.new
coffee.name = "Instant"
database.insert(coffee)
coffees = database.query("select * from coffees")
coffees.count.should == 1
coffees.first.name.should == "Instant"
coffees.first.strength.should == 1
end
it "updates the object's id attribute with the id generated by the database" do
tea = Tea.new
tea.name = "Earl Grey"
database.insert(tea)
tea.id.should == 1
end
it "raises an error with helpful message if there is not a matching table to insert into" do
derp = Derp.new
expect { database.insert(derp) }.to raise_error "There isn't a table called 'derps' and so insert failed."
end
it "protects against sql injection (escape single quotes)" do
beer = Beer.new
beer.name = "Foster's"
database.insert(beer)
beers = database.query("select * from beers")
beers.count.should == 1
beers.first.name.should == "Foster's"
end
it "supports keyword/reserved word fields" do
pending
end
end
context "#update" do
it "overwrites all matching fields with attribute values of a given object" do
account = Account.new
account.id = 1
account.name = "New name"
account.score = 50
database.update(account)
accounts = database.query("select * from accounts")
accounts.count.should == 1
accounts.first.name.should == "New name"
accounts.first.score.should == 50
accounts.first.id.should == 1
end
it "support only updating a specific set of fields" do
pending
end
end
context "#delete" do
# deletes one or more rows by id
# supports full delete query
end
context "#find" do
# load object(s) by id(s)
end
context "#save" do
# helper that calls either insert or update based on the object id value (0 or nil -> insert else update)
end
end
| true |
6ad404a5c361ef3d1ccf7c099ab4c60537e875cc | Ruby | wdcjernigan/CS561 | /automated/pageinsight.rb | UTF-8 | 1,565 | 2.578125 | 3 | [] | no_license | require 'rubygems'
require 'nokogiri'
require 'open-uri'
require 'net/http'
require 'net/https'
require 'uri'
@log = File.open("pageSpeedresults.csv", 'a')
def logAndOutput s
@log.write(s)
@log.write("\t")
puts s
end
@log2 = File.open("MobileOKresultsDetails.log", 'a')
def logAndOutput2 s
@log2.write(s)
@log2.write("\t")
puts s
end
def ignoreError
begin
return yield
rescue
return ""
end
end
repos = []
File.open("repoList2.txt", 'r') { |file|
file.each_line {|line|
repos << line.strip
}
}
repos.each {|repo|
fixedName = repo.gsub("+","%2B")
url = "http://developers.google.com/speed/pagespeed/insights/?url=http%3A%2F%2Fweb.engr.oregonstate.edu%2F~lesliew%2Fnormal%2F#{fixedName}%2Fassets%2Fwww%2F"
require 'watir'
browser = Watir::Browser.new
browser.goto url
sleep(10.0)
doc = Nokogiri::HTML.parse(browser.html)
logAndOutput repo
logAndOutput "normal"
doc.css(".result-group").each { |item|
logAndOutput item.at_css(".value").text.gsub(" / 100", "")
}
@log.write "\n"
browser.close
sleep(7.0)
fixedName = repo.gsub("+","%2B")
url = "http://developers.google.com/speed/pagespeed/insights/?url=http%3A%2F%2Fweb.engr.oregonstate.edu%2F~lesliew%2Fcompiled%2F#{fixedName}%2Fassets%2Fwww%2F"
require 'watir'
browser = Watir::Browser.new
browser.goto url
sleep(10.0)
doc = Nokogiri::HTML.parse(browser.html)
logAndOutput repo
logAndOutput "compiled"
doc.css(".result-group").each { |item|
logAndOutput item.at_css(".value").text.gsub(" / 100", "")
}
@log.write "\n"
browser.close
sleep(10.0)
}
| true |
9d0d77ddf5f58bb01a058118538ae2ceaa8850a4 | Ruby | netizer/transitions | /lib/mongoid/transitions.rb | UTF-8 | 1,808 | 2.53125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | # Copyright (c) 2010 Krzysiek Herod
# 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.
module Mongoid
module Transitions
extend ActiveSupport::Concern
included do
include ::Transitions
before_validation :set_initial_state
validates_presence_of :state
validate :state_inclusion
end
protected
def write_state(state_machine, state)
self.state = state.to_s
save!
end
def read_state(state_machine)
self.state.to_sym
end
def set_initial_state
self.state ||= self.class.state_machine.initial_state.to_s
end
def state_inclusion
unless self.class.state_machine.states.map{|s| s.name.to_s }.include?(self.state.to_s)
self.errors.add(:state, :inclusion, :value => self.state)
end
end
end
end
| true |
0edb71635c154100bafd41ddb34ee73dd8594dee | Ruby | GabrielRMorales/enumerable_methods | /lib/enumerable.rb | UTF-8 | 1,865 | 3.28125 | 3 | [] | no_license | module Enumerable
def my_each
return "This needs a block" unless block_given?
i=0
while i!=self.length
yield(self, i)
i+=1
end
end
def my_each_with_index
return "This needs a block" unless block_given?
i=0
while i!=self.length
j=self.index(self[i])
yield(self, i, j)
i+=1
end
end
def my_select
newarr=[]
return newarr unless block_given?
i=0
while i<self.length
if yield(self, i)==true
newarr << self[i]
end
i+=1
end
newarr
end
def my_all?
i=0
all=true
while i<self.length
if yield(self, i)==false
all=false
end
i+=1
end
all
end
def my_any?
i=0
any=false
while i!=self.length
if yield(self, i)==true
any=true
end
i+=1
end
any
end
def my_none?
i=0
none=true
while i!=self.length
if yield(self, i)==true
none=false
end
i+=1
end
none
end
def my_count
return nil if self==nil
i=0
while i!=self.length
i+=1
end
i
end
def my_map
newarr=[]
i=0
while i!=self.length
newarr<< yield(self, i)
i+=1
end
newarr
end
def my_map_mod(¶m)
newarr=[]
i=0
while i!=self.length
newarr<< yield(self,i)
i+=1
end
newarr
end
def my_map_proc_or_block(p=nil)
newarr=[]
i=0
while i!=self.length
if p!=nil && block_given?
newarr<< p.call(self,i)
else
newarr<< yield(self,i)
end
i+=1
end
newarr
end
def my_inject
return nil if self.length==0
newval=self[0]
raise "This should not have letters" if self[0]==self[0].to_s
i=1
while i<self.length
raise "This should not have letters" if self[i]==self[i].to_s
newval= yield(newval, self[i].to_i)
i+=1
end
newval
end
def multiply_els
newnum=self.my_inject {|x,y| x*=y}
end
end
class Array
include Enumerable
end
| true |
08c8c72413b5cef5ab4b69b701c0f7d034048c9a | Ruby | Umnums/ruby-music-library-cli-online-web-sp-000 | /lib/song.rb | UTF-8 | 1,186 | 2.953125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require_relative './concerns/method.rb'
require_relative './artist.rb'
require_relative './genre.rb'
require_relative './music_importer.rb'
require_relative './MusicLibraryController.rb'
class Song
attr_accessor :name, :artist, :genre
@@all = []
include Concerns::Methods::InstanceMethods
extend Concerns::Findable, Concerns::Methods::ClassMethods
def self.all
@@all
end
def initialize(name, artist = nil, genre = nil)
@name = name
self.artist = artist
self.genre = genre
end
def artist=(this)
if this == nil
return nil
else
@artist = this
this.add_song(self)
end
end
def genre=(genre)
if genre == nil
nil
else
@genre = genre
genre.add_song(self)
end
end
def self.new_from_filename(file)
name = file.split(" - ")
new_obj = Song.new(name[1])
new_obj.artist = Artist.find_or_create_by_name(name[0].strip)
new_obj.genre = Genre.find_or_create_by_name(name[2].split(".mp3")[0].strip)
new_obj
end
def self.create_from_filename(file)
self.new_from_filename(file).save
end
end
obj = MusicLibraryController.new("./spec/fixtures/mp3s")
obj.list_artists
| true |
317662ac9d29bfb81bfa8131b63dbd76b2757c93 | Ruby | kakao/cmux | /lib/cmux/utils/errors.rb | UTF-8 | 4,203 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | module CMUX
# Raise when a command not registered in cmux is executed
class CMUXCommandError < StandardError
def initialize(msg = nil)
@message = msg
end
def message
"Invalid CMUX command: #{@message}"
end
end
# Raise when two or more commands are executed without being attached to
# the tmux session
class CMUXNotInTMUXError < StandardError
def message
'You are not in TMUX session!!!'
end
end
# Raise when the arguments are not supplied
class CMUXNoArgumentError < StandardError
def message
'No arugment supplied'
end
end
# Raise when the arguments are wrong
class CMUXInvalidArgumentError < StandardError
def initialize(msg = nil)
@message = msg
end
def message
"'#{@message}' is invaild argument"
end
end
# Raise when the 'cm.yaml' is not configured
class CMUXCMListError < StandardError
def initialize(msg = nil)
@message = msg
end
def message
"#{@message}: The 'cm.yaml' must be configured. Please see the README."
end
end
# Raise when any configuration is not defined in th 'cm.yaml'
class CMUXConfigError < StandardError
def initialize(msg = nil)
@message = msg
end
def message
"#{@message} must be configured in 'cm.yaml'. Please see the README."
end
end
# Raise when CMUX can not reach to the Cloudera Manager API
class CMAPIError < StandardError
def initialize(msg = nil)
@message = msg
end
def message
"Can not reach to the Cloudera Manager API: #{@message}"
end
end
# Raise when CMUX can not set the auto balancer via 'hbase-tools'
class CMUXHBaseToolBalancerError < StandardError
def initialize(msg = nil)
@message = msg
end
def message
"Can not set the auto balancer: #{@message}"
end
end
# Raise when CMUX can not empty regions via 'hbase-tools'
class CMUXHBaseToolEmptyRSError < StandardError
def initialize(msg = nil)
@message = msg
end
def message
"Can not empty region: #{@message}"
end
end
# Raise when CMUX can not export regions via 'hbase-tools'
class CMUXHBaseToolExportRSError < StandardError
def initialize(msg = nil)
@message = msg
end
def message
"Can not export region: #{@message}"
end
end
# Raise when CMUX can not import regions via 'hbase-tools'
class CMUXHBaseToolImportRSError < StandardError
def initialize(msg = nil)
@message = msg
end
def message
"Can not import region: #{@message}"
end
end
# Raise when no nameservices is configured in cluster
class CMUXNameServiceError < StandardError
def message
'Does not have any configured nameservices.'
end
end
# Raise when no nameservice is configured for HA in cluster
class CMUXNameServiceHAError < StandardError
def message
'Does not have at least one nameservice configured for High Availability.'
end
end
# Raise when kerberos configuration are wrong
class CMUXKerberosError < StandardError
end
# Raise when the specified time to wait is exceeded
class CMUXMaxWaitTimeError < StandardError
def initialize(msg = nil)
@message = msg
end
def message
'Max wait time error: ' \
"#{@message} seconds have passed since the command was executed."
end
end
# CMUX utilities
module Utils
class << self
# Print error messages
def print_error(error)
tput_rmcup
msg = "cmux: #{error.message}"
puts msg.wrap(console_col_size - 6, "\n ").red
error.backtrace.each do |e|
print ' '
puts e.wrap(console_col_size - 6, "\n ")
end
end
# Print CMUX command error messages
def print_cmux_command_error(error)
puts "cmux: #{error.message}\n".red
puts 'Did you mean one of these?'
print_cmux_cmds
exit
end
# SystemExit exception
def system_exit
tput_rmcup
raise
end
# Interrupt exception
def interrupt
exit_with_msg("\nInterrupted".red, false)
end
end
end
end
| true |
40f648d9b106d440af07e52a352dbae0466f7013 | Ruby | markmontymark/patterns | /ruby/src/common/VegetableSoup.rb | UTF-8 | 202 | 2.671875 | 3 | [] | no_license |
require "common/Soup"
class VegetableSoup < Soup
def initialize()
@soupName = 'Vegetable Soup'
@soupIngredients = [
'1 cup bullion',
'1/4 cup carrots',
'1/4 cup potatoes', ]
end
end
| true |
3feb020a3903011e5ea850a7ffc2cf8e7eedaa4b | Ruby | Nyelanioustour/programming-univbasics-4-array-simple-array-manipulations-part-2-wdc01-seng-ft-060120 | /lib/intro_to_simple_array_manipulations.rb | UTF-8 | 341 | 3.0625 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | def using_concat(array, arraytwo)
array.concat(arraytwo)
end
def using_insert(array, arraytwo)
array.insert(4,arraytwo)
end
def using_uniq(array)
array.uniq
end
def using_flatten(array)
array.flatten
end
def using_delete(array, string)
array.delete(string)
end
def using_delete_at(array, number)
array.delete_at(number)
end | true |
2580396fcc0d13475e08fe99f47180d72991bbf7 | Ruby | jj222-stack/S2D2Ruby | /jj_exo_11.rb | UTF-8 | 121 | 3.078125 | 3 | [] | no_license | puts "Entre le nb de répétition:"
print ">"
user_rep=gets.chomp.to_i
n=0
for n in 0..user_rep
puts " Hello"
end
| true |
47645c9ed45e35d1db8add438d0eef1df7e73440 | Ruby | kimvitug05/tdd-exercise | /lib/blackjack_score.rb | UTF-8 | 610 | 4.09375 | 4 | [] | no_license | # blackjack_score.rb
VALID_CARDS = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King', 'Ace']
def blackjack_score(hand)
score = 0
hand.each do |card|
case card
when 'Jack', 'Queen', 'King'
score += 10
when 'Ace'
score += 11
else
card.class == Integer && card >= 2 && card <= 10 ? score += card : (raise ArgumentError, "Invalid card: #{card}")
end
end
if score > 21
aces = hand.count('Ace')
while aces > 0
score -= 10
break if score <= 21
aces -= 1
end
end
raise ArgumentError, "Bust!" if score > 21
return score
end
| true |
ed80e5f0fabe55bb3d5137ea9ff6cbd953ed8994 | Ruby | muff1nman/Vim | /scripts/pkgbuild_submodule_sources.rb | UTF-8 | 2,333 | 2.6875 | 3 | [
"MIT"
] | permissive | #! /usr/bin/env ruby
#
# Copyright © 2014 Andrew DeMaria (muff1nman) <ademaria@mines.edu>
#
# All Rights Reserved.
require 'pathname'
require 'uri'
require 'optparse'
GIT_ENDING = ".git"
def base_name name
uri = URI.parse(name)
base = File.basename(uri.path)
base = base[0..-(GIT_ENDING.length+1)] if base.end_with? GIT_ENDING
raise "Invalid name" if base.nil? or base.empty?
base
end
def process_submodules dir, callbacks={}
Dir.chdir dir do
top_dir = Pathname.new(Dir.pwd)
submodules = `git submodule foreach --quiet 'pwd'`.lines.map do |line|
Pathname.new(line).relative_path_from(top_dir).to_s.chomp
end
callbacks[:before].call submodules, dir unless callbacks[:before].nil?
submodules.each do |submodule|
callbacks[:during].call submodule unless callbacks[:during].nil?
process_submodules submodule, callbacks
end
callbacks[:after].call submodules, dir unless callbacks[:after].nil?
end
end
def print_pushd submodules, dir
puts "pushd #{dir}" unless submodules.empty?
end
def print_popd submodules, dir
puts "popd" unless submodules.empty?
end
def print_for_submodule submodule
#puts "Processing submodule [#{submodule}]"
puts "git submodule init #{submodule}"
previous_url = `git config submodule.#{submodule}.url`
#puts "previous url: #{previous_url}"
puts "git config submodule.#{submodule}.url \"$srcdir/#{base_name previous_url}\""
puts "git submodule update #{submodule}"
end
def print_url submodule
puts `git config submodule.#{submodule}.url`
end
USAGE = "Usage: ./path_to_script [--change-remotes | --list-remotes]"
options = {}
OptionParser.new do |opts|
opts.banner = USAGE
opts.on("-c", "--change-remotes", "Print the commands required for a makepkg to setup the urls correctly") do |_|
abort("Only choose one task please") unless options[:action].nil?
options[:callbacks] = {
before: method(:print_pushd),
after: method(:print_popd),
during: method(:print_for_submodule)
}
end
opts.on("-l", "--list-remotes", "Print a listing of remotes for a makepkg") do |_|
abort("Only choose one task please") unless options[:action].nil?
options[:callbacks] = {
during: method(:print_url)
}
end
end.parse!
abort(USAGE) unless options[:callbacks]
process_submodules Dir.pwd, options[:callbacks]
| true |
f654b9e2218eefbdd245ae57046de78a2d2ceece | Ruby | JochenFromm/EssentialAlgorithms | /spec/levenshtein_spec.rb | UTF-8 | 512 | 3.265625 | 3 | [] | no_license | require './algorithms/levenshtein.rb'
RSpec.describe Levenshtein do
describe 'distance' do
it 'calculates similarity of strings' do
h = {
['kitten', 'fetching'] => 6,
['kitten', 'knowing'] => 5,
['kitten', 'sitting'] => 3,
['kitten', 'kitchen'] => 2,
['kitten', 'kitten!'] => 1,
['kitten', 'kitten'] => 0,
}
h.each do |text, distance|
expect(Levenshtein.distance(text.first, text.last)).to eq(distance)
end
end
end
end
| true |
651937b37303ccfc1cd4bc96d1db39216fe37314 | Ruby | yvettecook/Rock-Paper-Scissors | /spec/player_spec.rb | UTF-8 | 456 | 2.703125 | 3 | [] | no_license | require './app/models/player'
describe Player do
let (:player) { Player.new('Yvette') }
it "should have a name" do
expect(player.name).to eq 'Yvette'
end
it "should add a win when .win called" do
player.win
expect(player.wins).to eq(1)
end
it "should add a loss when .lose called" do
player.lose
expect(player.losses).to eq(1)
end
it "should add a draw when .draw called" do
player.draw
expect(player.draws).to eq(1)
end
end | true |
a48cbe9d5d2a3a0f64e2faa58c8f6196797f4dc8 | Ruby | nkeller1/hatchways | /app/services/posts_service.rb | UTF-8 | 506 | 2.625 | 3 | [] | no_license | class PostsService
def connection
Faraday.new(
url: 'https://hatchways.io'
)
end
def gather_posts_from_tags(tags)
response = tags.map do |tag|
connection.get('/api/assessment/blog/posts') do |req|
req.params['tag'] = tag
end
end
combine_posts(response)
end
def combine_posts(responses)
allposts = Array.new
responses.map do |rep|
allposts << JSON.parse(rep.body)['posts']
allposts
end
allposts.flatten.uniq
end
end
| true |
579029c095c97a8da42a3b738a56d8d6109bf27b | Ruby | epoch/songstable | /app/models/song.rb | UTF-8 | 1,413 | 2.515625 | 3 | [] | no_license | class Song < ActiveRecord::Base
attr_accessible :titles, :titles_attributes, :versions_attributes
has_many :titles, :dependent => :destroy
has_many :versions, :dependent => :destroy
accepts_nested_attributes_for :titles, :reject_if => :all_blank, :allow_destroy => true
accepts_nested_attributes_for :versions
validate :at_least_one_title
validate :at_least_one_version
validate :one_primary_title
validate :only_one_primary_title
after_initialize :set_defaults
def set_defaults
self.titles.build(:primary => true) if self.titles.empty?
self.versions.build if self.versions.empty?
end
def primary_title
titles.first {|t| t.primary? } || titles.where(:primary => true).first
end
def save
super
rescue ActiveRecord::RecordNotUnique
errors.add(:base, "title names needs to be unique")
false
end
def at_least_one_title
errors.add(:base, "at least one title") if titles.empty?
end
def one_primary_title
errors.add(:base, "please include one primary title") unless titles.any? {|title| title.primary? }
end
def only_one_primary_title
errors.add(:base, "please include only one primary title") if titles.select {|title| title.primary? }.size > 1
end
def at_least_one_version
errors.add(:base, "need at least one version") if versions.empty?
end
private
def only_one_title?
titles.size == 1
end
end
| true |
8d2df607805d49fa89846142e0021a85024ae07b | Ruby | Aleph-works/ruby-metaprogramming | /first_week/exercise4.rb | UTF-8 | 185 | 3.109375 | 3 | [] | no_license | class A
@@a = 1
@a = 2
a = 3
# Write your code here. Use binding method.
end
p eval('[@@a, @a, a]', *****) # Replace '*****' to your code
# Expected output is '[1, 2, 3]'
| true |
c309f5c9528c3b2b32eff0f9bb168faa78f91159 | Ruby | soumyaveer/ruby-algorithms | /spec/containers/stack_spec.rb | UTF-8 | 3,128 | 3.421875 | 3 | [] | no_license | module Containers
describe Stack do
before do
@stack = Stack.new
end
describe 'initialize' do
it 'creates an empty stack when no data is provided' do
expect(@stack.size).to eql(0)
expect(@stack.empty?).to be_truthy
end
it 'creates a stack with elements when data is provided' do
stack = Stack.new(['a', 'b', 'c'])
expect(stack.size).to eql(3)
expect(stack.empty?).to be_falsy
expect(stack.peek).to eql('c')
expect(stack.print).to eql('a, b, c')
end
end
describe 'push' do
it 'adds a new item to the top of the stack' do
@stack.push(1)
expect(@stack.size).to eql(1)
expect(@stack.peek).to eql(1)
expect(@stack.print).to eql('1')
end
it 'adds second new item to the top of the stack' do
@stack.push(1)
@stack.push(2)
expect(@stack.size).to eql(2)
expect(@stack.peek).to eql(2)
expect(@stack.print).to eql('1, 2')
end
it 'adds third new item to the top of the stack' do
@stack.push(1)
@stack.push(2)
@stack.push(3)
expect(@stack.size).to eql(3)
expect(@stack.peek).to eql(3)
expect(@stack.print).to eql('1, 2, 3')
end
end
describe 'pop' do
it 'removes the top item from the stack' do
@stack.push(1)
@stack.push(2)
@stack.push(3)
expect(@stack.pop).to eql(3)
expect(@stack.size).to eql(2)
expect(@stack.print).to eql('1, 2')
end
it 'removes another item from the top of the stack' do
@stack.push(1)
@stack.push(2)
@stack.push(3)
2.times do
@stack.pop
end
expect(@stack.size).to eql(1)
expect(@stack.peek).to eql(1)
end
end
describe 'peek' do
it 'returns the top element of the stack' do
@stack.push(1)
@stack.push(2)
@stack.push(3)
top_element = @stack.peek
expect(top_element).to eql(3)
end
end
describe 'empty?' do
it 'returns false is the stack is not empty' do
@stack.push(3)
expect(@stack.empty?).to be_falsey
end
it 'returns true if the stack is empty' do
@stack.push(3)
@stack.pop
expect(@stack.empty?).to be_truthy
end
end
describe 'clear' do
it 'clears the elements of the stack' do
@stack.push(4)
@stack.push(5)
@stack.push(6)
expect(@stack.empty?).to be_falsey
expect(@stack.clear).to match_array([])
expect(@stack.empty?).to be_truthy
end
end
describe 'size' do
it 'returns length of the stack' do
@stack.push(4)
@stack.push(5)
@stack.push(6)
expect(@stack.size).to eql(3)
end
end
describe 'print' do
it 'displays the elements of the stack' do
@stack.push(7)
@stack.push(8)
@stack.push(9)
@stack.push(10)
expect(@stack.print).to eql('7, 8, 9, 10')
end
end
end
end
| true |
b9f46488a25c844478cd5ade2235622af8231c3b | Ruby | chelseadeane14/RubyProjects | /cheight.rb | UTF-8 | 282 | 3.09375 | 3 | [] | no_license | #Hackerrank Challenge 8
n = gets.to_i
i = 0
s = {}
while i < n
str1, str2 = gets.split.map(&:to_s)
s["#{str1}"] = "#{str2}"
i+=1
end
p s
i = 0
while line = gets
if s["#{line}"] != nil
puts "#{line}=#{s[line]}"
else
puts "Not found"
end
end
| true |
363ae70e596fd5444655dacf7ea09a88cba87eae | Ruby | aasm/aasm | /lib/aasm/aasm.rb | UTF-8 | 7,508 | 2.734375 | 3 | [
"MIT"
] | permissive | module AASM
# this is used internally as an argument default value to represent no value
NO_VALUE = :_aasm_no_value
# provide a state machine for the including class
# make sure to load class methods as well
# initialize persistence for the state machine
def self.included(base) #:nodoc:
base.extend AASM::ClassMethods
# do not overwrite existing state machines, which could have been created by
# inheritance, see class method inherited
AASM::StateMachineStore.register(base)
AASM::Persistence.load_persistence(base)
super
end
module ClassMethods
# make sure inheritance (aka subclassing) works with AASM
def inherited(base)
AASM::StateMachineStore.register(base, self)
super
end
# this is the entry point for all state and event definitions
def aasm(*args, &block)
if args[0].is_a?(Symbol) || args[0].is_a?(String)
# using custom name
state_machine_name = args[0].to_sym
options = args[1] || {}
else
# using the default state_machine_name
state_machine_name = :default
options = args[0] || {}
end
AASM::StateMachineStore.fetch(self, true).register(state_machine_name, AASM::StateMachine.new(state_machine_name))
# use a default despite the DSL configuration default.
# this is because configuration hasn't been setup for the AASM class but we are accessing a DSL option already for the class.
aasm_klass = options[:with_klass] || AASM::Base
raise ArgumentError, "The class #{aasm_klass} must inherit from AASM::Base!" unless aasm_klass.ancestors.include?(AASM::Base)
@aasm ||= Concurrent::Map.new
if @aasm[state_machine_name]
# make sure to use provided options
options.each do |key, value|
@aasm[state_machine_name].state_machine.config.send("#{key}=", value)
end
else
# create a new base
@aasm[state_machine_name] = aasm_klass.new(
self,
state_machine_name,
AASM::StateMachineStore.fetch(self, true).machine(state_machine_name),
options
)
end
@aasm[state_machine_name].instance_eval(&block) if block # new DSL
@aasm[state_machine_name]
end
end # ClassMethods
# this is the entry point for all instance-level access to AASM
def aasm(name=:default)
unless AASM::StateMachineStore.fetch(self.class, true).machine(name)
raise AASM::UnknownStateMachineError.new("There is no state machine with the name '#{name}' defined in #{self.class.name}!")
end
@aasm ||= Concurrent::Map.new
@aasm[name.to_sym] ||= AASM::InstanceBase.new(self, name.to_sym)
end
def initialize_dup(other)
@aasm = Concurrent::Map.new
super
end
private
# Takes args and a from state and removes the first
# element from args if it is a valid to_state for
# the event given the from_state
def process_args(event, from_state, *args)
# If the first arg doesn't respond to to_sym then
# it isn't a symbol or string so it can't be a state
# name anyway
return args unless args.first.respond_to?(:to_sym)
if event.transitions_from_state(from_state).map(&:to).flatten.include?(args.first)
return args[1..-1]
end
return args
end
def aasm_fire_event(state_machine_name, event_name, options, *args, &block)
event = self.class.aasm(state_machine_name).state_machine.events[event_name]
begin
old_state = aasm(state_machine_name).state_object_for_name(aasm(state_machine_name).current_state)
fire_default_callbacks(event, *process_args(event, aasm(state_machine_name).current_state, *args))
if may_fire_to = event.may_fire?(self, *args)
fire_exit_callbacks(old_state, *process_args(event, aasm(state_machine_name).current_state, *args))
if new_state_name = event.fire(self, {:may_fire => may_fire_to}, *args)
aasm_fired(state_machine_name, event, old_state, new_state_name, options, *args, &block)
else
aasm_failed(state_machine_name, event_name, old_state, event.failed_callbacks)
end
else
aasm_failed(state_machine_name, event_name, old_state, event.failed_callbacks)
end
rescue StandardError => e
event.fire_callbacks(:error, self, e, *process_args(event, aasm(state_machine_name).current_state, *args)) ||
event.fire_global_callbacks(:error_on_all_events, self, e, *process_args(event, aasm(state_machine_name).current_state, *args)) ||
raise(e)
false
ensure
event.fire_callbacks(:ensure, self, *process_args(event, aasm(state_machine_name).current_state, *args))
event.fire_global_callbacks(:ensure_on_all_events, self, *process_args(event, aasm(state_machine_name).current_state, *args))
end
end
def fire_default_callbacks(event, *processed_args)
event.fire_global_callbacks(
:before_all_events,
self,
*processed_args
)
# new event before callback
event.fire_callbacks(
:before,
self,
*processed_args
)
end
def fire_exit_callbacks(old_state, *processed_args)
old_state.fire_callbacks(:before_exit, self, *processed_args)
old_state.fire_callbacks(:exit, self, *processed_args)
end
def aasm_fired(state_machine_name, event, old_state, new_state_name, options, *args)
persist = options[:persist]
new_state = aasm(state_machine_name).state_object_for_name(new_state_name)
callback_args = process_args(event, aasm(state_machine_name).current_state, *args)
new_state.fire_callbacks(:before_enter, self, *callback_args)
new_state.fire_callbacks(:enter, self, *callback_args) # TODO: remove for AASM 4?
persist_successful = true
if persist
persist_successful = aasm(state_machine_name).set_current_state_with_persistence(new_state_name)
if persist_successful
yield if block_given?
event.fire_callbacks(:before_success, self, *callback_args)
event.fire_transition_callbacks(self, *process_args(event, old_state.name, *args))
event.fire_callbacks(:success, self, *callback_args)
end
else
aasm(state_machine_name).current_state = new_state_name
yield if block_given?
end
binding_event = event.options[:binding_event]
if binding_event
__send__("#{binding_event}#{'!' if persist}")
end
if persist_successful
old_state.fire_callbacks(:after_exit, self, *callback_args)
new_state.fire_callbacks(:after_enter, self, *callback_args)
event.fire_callbacks(
:after,
self,
*process_args(event, old_state.name, *args)
)
event.fire_global_callbacks(
:after_all_events,
self,
*process_args(event, old_state.name, *args)
)
self.aasm_event_fired(event.name, old_state.name, aasm(state_machine_name).current_state) if self.respond_to?(:aasm_event_fired)
else
self.aasm_event_failed(event.name, old_state.name) if self.respond_to?(:aasm_event_failed)
end
persist_successful
end
def aasm_failed(state_machine_name, event_name, old_state, failures = [])
if self.respond_to?(:aasm_event_failed)
self.aasm_event_failed(event_name, old_state.name)
end
if AASM::StateMachineStore.fetch(self.class, true).machine(state_machine_name).config.whiny_transitions
raise AASM::InvalidTransition.new(self, event_name, state_machine_name, failures)
else
false
end
end
end
| true |
e5a46f3b5a92e5ffe48b00e0d8766103da780950 | Ruby | Beagle123/visualruby | /examples/golf_handicap/src/Score.rb | UTF-8 | 818 | 2.890625 | 3 | [
"MIT"
] | permissive |
class Score
attr_accessor :date, :score, :course_name, :course_rating, :course_slope, :used, :handicap
include GladeGUI
def initialize(course, rating, slope)
@course_name = course
@course_rating = rating
@course_slope = slope
@date = DateTime.now
@score = "0"
@used = nil
@handicap = "0"
end
def buttonSave__clicked(*a)
get_glade_variables
@used = "n" # signals save occured
@builder[:window1].destroy
end
def diff()
(@score.to_f - @course_rating.to_f) * 113 / @course_slope.to_f
end
def to_s
(@used == "y" ? "*" : " ") + diff.round(1).to_s
end
def visual_attributes
# return @used == "y" ? {background: "#ABB" , weight: 600} : {background: "white", weight: 300 }
return @used == "y" ? { weight: 1200} : {weight: 400 }
end
end
| true |
ce7f362bda0b04e9cc584f88a95b831c681d30d3 | Ruby | suryagaddipati/linqr | /lib/providers/enumerable_expression_evaluator.rb | UTF-8 | 1,210 | 2.859375 | 3 | [] | no_license | require 'ostruct'
require 'expression_evaluator_base'
class EnumerableExpessionEvaluator < ExpressionEvaluator
def visit_group_by(node)
node.expression.visit(self)
end
def visit_hash(node)
record = OpenStruct.new
node.elements.each do |e|
key = e.key.visit(self)
value = e.value.visit(self)
record.send("#{key.to_s}=".to_sym,value)
end
record
end
def visit_argslist(node)
node.map {|arg| arg.visit(self)}
end
def visit_array(node)
node.elements.collect(&:arg).reduce([]){|out,n| out << variable_val(n) ; out}
end
def visit_binary(node)
right_val = node.right.visit(self)
left_val = node.left.visit(self)
if node.operator.to_sym == :and
left_val && right_val
elsif node.operator.to_sym == :or
left_val || right_val
else
left_val.send(node.operator.to_ruby.to_sym, right_val)
end
end
def visit_call(node)
target = node.target.visit(self)
method_name = node.identifier ? node.identifier.to_sym : :[]
if (node.arguments)
arguments = node.arguments.collect { |x| x.visit(self) }
target.send(method_name, *arguments)
else
target.send(method_name)
end
end
end
| true |
910dfa5377520a69479bdac3d0b675cb3dc6fe05 | Ruby | rsinger/free_cite | /lib/utf8_parser.rb | UTF-8 | 1,232 | 2.890625 | 3 | [
"MIT"
] | permissive | class UTF8Parser < StringScanner
STRING = /(([\x0-\x1f]|[\\\/bfnrt]|\\u[0-9a-fA-F]{4}|[\x20-\xff])*)/nx
UNPARSED = Object.new
UNESCAPE_MAP = Hash.new { |h, k| h[k] = k.chr }
UNESCAPE_MAP.update({
?" => '"',
?\\ => '\\',
?/ => '/',
?b => "\b",
?f => "\f",
?n => "\n",
?r => "\r",
?t => "\t",
?u => nil,
})
UTF16toUTF8 = Iconv.new('utf-8', 'utf-16be')
def initialize(str)
super(str)
@string = str
end
def parse_string
if scan(STRING)
return '' if self[1].empty?
string = self[1].gsub(%r((?:\\[\\bfnrt"/]|(?:\\u(?:[A-Fa-f\d]{4}))+|\\[\x20-\xff]))n) do |c|
if u = UNESCAPE_MAP[$&[1]]
u
else # \uXXXX
bytes = ''
i = 0
while c[6 * i] == ?\\ && c[6 * i + 1] == ?u
bytes << c[6 * i + 2, 2].to_i(16) << c[6 * i + 4, 2].to_i(16)
i += 1
end
UTF16toUTF8.iconv(bytes)
end
end
if string.respond_to?(:force_encoding)
string.force_encoding(Encoding::UTF_8)
end
string
else
UNPARSED
end
rescue Iconv::Failure => e
raise StandardError, "Caught #{e.class}: #{e}"
end
end | true |
1b971e5bd3934097453acc7424f88f0a17a6e348 | Ruby | linaresmariano/marianol-eis20131 | /ejercicios/code_breaker_app/application.rb | UTF-8 | 957 | 3.046875 | 3 | [] | no_license | require 'sinatra/base'
require '../code_breaker/code_breaker.rb'
class MyApplication < Sinatra::Base
enable :sessions
get '/' do
redirect '/palabra'
end
get '/palabra' do
palabra = params[:p]
if palabra
begin
session[:game] = CodeBreaker.new(palabra, 3)
session[:game].build_string_showing_correct_letters
redirect '/adivinar'
rescue WordError
redirect '/palabra'
end
end
erb :palabra
end
get '/adivinar' do
letra = params[:l]
if letra
begin
@msg = (session['game'].guess letra) ? 'acierto' : 'ups!'
rescue WinnerException
@result = 'Juego terminado, ganaste'
rescue LoserException
@msg = 'ups!'
@result = 'Juego terminado, perdiste'
end
end
@lifes = session['game'].life
@state = session['game'].build_string_showing_correct_letters
erb :adivinar
end
end
| true |
b19a247e4063f25a02665daa29ed08f36d6d57e2 | Ruby | ElMassimo/crouton | /lib/crouton/presenter.rb | UTF-8 | 797 | 2.765625 | 3 | [
"MIT"
] | permissive | require 'crouton/message'
module Crouton
class Presenter
attr_reader :placeholder, :messages
delegate :each, to: :messages
def initialize(messages, options={})
@placeholder = options.delete(:placeholder) || '.crouton-placeholder'
messages = from_hash(messages) if messages.is_a?(Hash)
@messages = *messages
end
private
def from_hash(messages)
messages.delete_if {|name, msg| msg.blank? }
if (errors = messages[:errors]).present?
errors_to_messages(errors)
else
messages.map(&Message).presence || [Message.new]
end
end
# Internal: Converts errors to an array of error messages.
def errors_to_messages(errors)
errors.full_messages.map {|error| Message.new(:error, error) }
end
end
end
| true |
b3a035222b0814337e5761e6e71a1f4c5cc8982e | Ruby | fencedin/train_system | /spec/line_spec.rb | UTF-8 | 1,946 | 2.984375 | 3 | [] | no_license | require 'spec_helper'
describe 'Line' do
it 'initializes with a name' do
line = Line.new({:name => 'Blue'})
line.should be_an_instance_of Line
end
it 'gives back the line name' do
line = Line.new({:name => 'Green'})
line.name.should eq 'Green'
end
describe '.all' do
it 'starts as an empty array' do
line = Line.new({:name => 'Yellow'})
Line.all.should eq []
end
it 'adds a line with name and id' do
line = Line.new({:name => 'Blue'})
line.save
Line.all[0].id.should eq line.id
end
end
describe 'save' do
it 'saves the line and stop(s) to the array' do
line = Line.new({:name => 'Red'})
station1 = Station.new({:name => 'Charlotte'})
station2 = Station.new({:name => 'Portland'})
station1.save
station2.save
line.save
Line.all.should eq [line]
end
end
it 'is the same line if it has the same attributes' do
station1 = Line.new({:name => 'Orange'})
station2 = Line.new({:name => 'Orange'})
station1.should eq station2
end
it 'should update an attribute of the line' do
line = Line.new({:name => 'Blue'})
line.save
line.update('Red')
line.name.should eq 'Red'
end
it 'deletes the record' do
line = Line.new({:name => 'Red'})
line.save
line.delete('Red')
Line.all.should eq []
end
describe 'add_stop' do
it 'adds a stop to a line' do
line = Line.new({:name => 'Red'})
station = Station.new({:name => 'Portland'})
station.save
line.save
line.add_stop(station)
line.stops.first['name'].should eq "Portland"
end
end
describe '#stops' do
it 'returns all the stops for a line' do
line = Line.new({:name => 'Red'})
station = Station.new({:name => 'Portland'})
station.save
line.save
line.add_stop(station)
line.stops.first['name'].should eq "Portland"
end
end
end
| true |
7355bf211bd1c33f08d18d9cf6008a260a497e81 | Ruby | stridera/wellington | /app/models/membership.rb | UTF-8 | 2,951 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | # frozen_string_literal: true
# Copyright 2020 Matthew B. Gray
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Membership represents present and histircal records for types of membership
# Reservation is associated with a Membership through Order
# User is associated with a Membership through Reservation
# Membership records are displayed for purchase from the MembershipsController when they're 'active'
# Membership may also be associated to a user on import or when a Operator user uses the SetMembership class
# Cycling prices means you may have 4 Adult memberships, but it's likely only 1 will be active at a time
# Membership holds rights such as attendance, site selection, nomination and voting
# Membership types that were never available for purchase can be made by setting active_from and active_to to the same time in the past, e.g. dublin_2019
class Membership < ApplicationRecord
include ActiveScopes
monetize :price_cents
validates :active_from, presence: true
validates :price, presence: true, numericality: { greater_than_or_equal_to: 0 }
validates :name, presence: true
has_many :orders
has_many :active_orders, -> { active }, class_name: "Order"
has_many :reservations, through: :active_orders
scope :can_attend, -> { where(can_attend: true) }
scope :can_nominate, -> { where(can_nominate: true) }
scope :can_site_select, -> { where(can_site_select: true) }
scope :can_vote, -> { where(can_vote: true) }
scope :with_rights, -> { where("can_attend OR can_nominate OR can_vote") }
scope :order_by_price, -> { order(price_cents: :desc) }
scope :with_attend_rights, -> { where(can_attend: true) }
scope :with_nomination_rights, -> { where(can_nominate: true) }
scope :with_voting_rights, -> { where(can_vote: true) }
def to_s
name.humanize
end
def community?
name.match(/community/)
end
# n.b. Nomination in 2020 became unavailable to new members once Nomination opened
# So we created new active Membership records at the same price
# These match i18n values set in config/locales
def all_rights
[].tap do |rights|
rights << "rights.attend" if can_attend?
rights << "rights.site_selection" if can_site_select?
if can_vote?
rights << "rights.hugo.vote"
rights << "rights.retro_hugo.vote"
end
if can_nominate?
rights << "rights.hugo.nominate"
rights << "rights.retro_hugo.nominate"
end
end
end
end
| true |
82a0e7b782017dc6aaea4ecbad5cb4ae1562d6a9 | Ruby | Eschults/food-delivery | /app/repositories/orders_repository.rb | UTF-8 | 1,320 | 3.078125 | 3 | [] | no_license | require "csv"
require_relative "../models/order"
require_relative "base_repository"
class OrdersRepository < BaseRepository
attr_reader :employees_repository, :customers_repository, :meals_repository
def initialize(csv_file, employees_repository, customers_repository, meals_repository)
@employees_repository = employees_repository
@customers_repository = customers_repository
@meals_repository = meals_repository
super(csv_file)
end
def mark_order_as_delivered(order)
order.mark_as_delivered!
save_to_csv
end
def undelivered
@resources.reject { |order| order.delivered? }
end
private
def load_csv
CSV.foreach(@csv_file, headers: :first_row, header_converters: :symbol) do |row|
if row[:employee_id]
employee = @employees_repository.find(row[:employee_id].to_i)
customer = @customers_repository.find(row[:customer_id].to_i)
meal = @meals_repository.find(row[:meal_id].to_i)
order = Order.new(id: row[:id].to_i, customer: customer, meal: meal, delivered: row[:delivered] == "true")
employee.add_order(order) unless order.delivered?
@resources << order
else
@next_id = row[:id].to_i
end
end
end
def headers
[ "id", "employee_id", "customer_id", "meal_id", "delivered" ]
end
end | true |
e8c90b96fc4aa16776f4055bd03b6756e85abb10 | Ruby | domw30/Learn-To-Program-Chris-Pine | /Ch5-CenterString.rb | UTF-8 | 550 | 3.0625 | 3 | [] | no_license | lineWidth = 50
puts( 'Old Mother Hubbard'.center(lineWidth))
puts( 'Sat in her cupboard'.center(lineWidth))
puts( 'Eating her curds an whey,'.center(lineWidth))
puts( 'When along came a spider'.center(lineWidth))
puts( 'Which sat down beside her'.center(lineWidth))
puts('And scared her poor shoe dog away.'.center(lineWidth))
=begin
Also, I wanted to line up the .center lineWidth part,
so I put in those extra spaces before the strings.
This is just because I think it is prettier
=end
| true |
6eb9028c27eb6f83c5d05cbb10e4889b437e0d68 | Ruby | vin-droid/Airport-Fuel-Inventory-Solution | /functional_spec/spec/airport_fuel_inventory_spec.rb | UTF-8 | 1,795 | 2.625 | 3 | [
"MIT"
] | permissive | require 'singleton'
require "./bin/airport_fuel_inventory_system.rb"
RSpec.describe AirportFuelInventorySystem do
let(:airport_fuel_inventory){AirportFuelInventorySystem.instance}
let(:fuel_quantity){200000}
let(:airport_id){3}
let(:aircrapt){Aircraft.new('6E-102')}
before do
Singleton.__init__(AirportFuelInventorySystem)
airport_fuel_inventory.initiate_or_reinitiate
end
it "show full fuel summary at all airports" do
expect(airport_fuel_inventory.show_full_fuel_summary_at_all_airports).to end_with(FULL_FUEL_SUMMARY_AT_ALL_AIRPORTS_OUTPUT)
end
it "shows fuel summary at all airports" do
expect(airport_fuel_inventory.show_fuel_summary_at_all_airports).to end_with(FUEL_SUMMARY_AT_ALL_AIRPORTS_OUTPUT)
end
context "Update fuel inventory of a selected airport" do
it "adds `250000` ltrs to fuel inventory whose airport id is `3`" do
expect(airport_fuel_inventory.update_fuel_inventory_of_a_selected_airport(airport_id, fuel_quantity)).to end_with("Success: Fuel inventory updated\n")
end
it "shows error when add fuel quantity beyond fuel capacity of the airport" do
expect(airport_fuel_inventory.update_fuel_inventory_of_a_selected_airport(airport_id, fuel_quantity * 4)).to end_with("Error: Goes beyond fuel capacity of the airport\n")
end
end
context "Fill aircraft" do
it "fills aircraft if not availability at airport" do
expect(airport_fuel_inventory.fill_aircraft(airport_id, aircrapt, fuel_quantity)).to end_with("Success: Request for the has been fulfilled\n")
end
it "shows error when request for the fuel is beyond availability at airport" do
expect(airport_fuel_inventory.fill_aircraft(airport_id, aircrapt, fuel_quantity * 4)).to end_with("Failure: Request for the fuel is beyond availability at airport\n")
end
end
end | true |
b7c04d26bc491c1ca6b5aea65f6a4beb73bd2699 | Ruby | cariaso/smwcon2012bots | /lang/ruby/bot1.rb | UTF-8 | 4,341 | 2.5625 | 3 | [] | no_license | #!/usr/bin/env ruby
#########################################
#
# Read more at
#
# http://github.com/jpatokal/mediawiki-gateway
#
#########################################
#
# comment out 'private' in mediawiki-gateway/lib/media_wiki/gateway.rb line 563
# since the standard version makes make_api_request() inaccessible
#
# git clone git://github.com/jpatokal/mediawiki-gateway.git
#########################################
$LOAD_PATH << 'mediawiki-gateway/lib'
require 'media_wiki'
# you may also need
# "sudo gem install rest-client"
# "sudo gem install active_support"
#############################################################
# Settings
#############################################################
api_url = 'http://sandbox.semantic-mediawiki.org/api.php'
username='Cariaso'
password='correct horse battery staple'
#############################################################
# Read Category Titles
#############################################################
def DemoReadCategoryTitles1(mw)
# surprisingly difficult, no ruby api for this
# https://github.com/jpatokal/mediawiki-gateway/issues/9
puts "---\nBegin DemoReadCategoryTitles1"
form_data = { 'action' => 'query',
'list' => 'categorymembers',
'cmtitle'=>'Category:City'
}
xml, dummy = mw.make_api_request(form_data)
results = xml.elements["query/categorymembers"]
if results != nil
results.each do |p|
puts p.attributes["title"]
end
end
end
#############################################################
# Read Text
#############################################################
def DemoReadPageText(mw)
puts "---\nBegin DemoReadPageText\n"
pagename = 'Berlin'
pagetext = mw.get(pagename)
puts "\n================BEGIN==="
puts "From Page %s" % pagename
puts pagetext
puts "\n================END==="
cities = ['Warsaw', 'San Diego']
cities.each {|city|
pagetext = mw.get(city)
puts "\n================BEGIN==="
puts "From Page %s" % city
puts pagetext
puts "\n================END==="
}
end
#############################################################
# Write a Page
#############################################################
def DemoWritePageText(mw)
puts "---\nBegin DemoWritePageText\n"
pagename = "JustASandbox"
now = Time.new.inspect
newtext = "This is from ruby at " + now + "\n\n"
mw.edit(pagename, newtext)
end
#############################################################
# Append to a Page
#############################################################
def DemoAppendPageText(mw)
puts "---\nBegin DemoAppendPageText\n"
pagename = "JustASandbox"
now = Time.new.inspect
extratext = "This is from ruby at " + now + "\n\n"
oldtext = mw.get(pagename)
newtext = oldtext + "\n" + extratext
mw.edit(pagename, newtext)
end
#############################################################
# Semantic ask
#############################################################
require 'pp'
def DemoSemanticAsk(mw)
form_data = { 'action' => 'askargs',
'conditions' => 'Category:City | located in::Germany',
'printouts' => 'area|population',
'parameters' =>'|sort=Modification date|order=desc',
}
xml, dummy = mw.make_api_request(form_data)
results = xml.elements["query/results"]
if results != nil
results.each do |p|
name = p.attributes["fulltext"]
population = p.elements["printouts/population/value"].text
area = p.elements["printouts/area/value"].attributes["fulltext"]
print name, " \t ", population, " \t ", area, "\n"
end
end
# Note. There is a method for semantic_query but it doesn't seem to work yet
# http://rubydoc.info/gems/mediawiki-gateway/0.4.4/MediaWiki/Gateway:semantic_query
end
#############################################################
# main
#############################################################
mw = MediaWiki::Gateway.new(api_url)
#DemoReadCategoryTitles1(mw)
#DemoReadPageText(mw)
DemoSemanticAsk(mw)
mw.login(username, password)
#DemoWritePageText(mw)
#DemoAppendPageText(mw)
| true |
04bea365d35c5e5b7203abc7b507880842c48cd1 | Ruby | AJFaraday/sand_fall | /lib/row.rb | UTF-8 | 269 | 3.296875 | 3 | [
"MIT"
] | permissive | class Row
attr_reader :cells
def initialize(width, row_number, grid)
@width = width
@grid = grid
@cells = []
@width.times do |cell_number|
@cells << Cell.new(cell_number, row_number, grid)
end
end
def [](x)
@cells[x]
end
end
| true |
44792f7c52b1aa691ab3e7e6c4a0a52ada078a42 | Ruby | tannerwelsh/code-training | /web-dev/dev_bootcamp/RubyProjects/sudoku/sudoku_v2.rb | UTF-8 | 3,817 | 3.3125 | 3 | [
"MIT"
] | permissive | require 'rspec'
module Sudoku
class Puzzle
attr_reader :rows, :columns, :boxes
attr_accessor :board
def initialize(board)
@board = board.split(//)
self.format
end
def format
self.reset
@board.each.with_index do |value, cell|
@rows[row_id(cell)][cell % 9] = value
@columns[col_id(cell)][cell / 9] = value
@boxes[box_id(cell)] << value
end
end
def reset
@rows, @columns, @boxes = [], [], []
9.times { @rows << []; @columns << []; @boxes << [] }
end
# Locator helpers
def row_id(cell)
cell / 9
end
def col_id(cell)
cell % 9
end
def box_id(cell)
((row_id(cell) / 3) * 3) + (col_id(cell) / 3)
end
def group(cell)
[@rows[row_id(cell)], @columns[col_id(cell)], @boxes[box_id(cell)]]
end
# Solver helpers
def options(cell)
('1'..'9').to_a - neg_options(cell)
end
def neg_options(cell)
group(cell).inject { |a, b| a | b } - ['0']
end
end
class Solver
attr_reader :solution
def initialize(puzzle)
@puz = puzzle
end
def try_options(cell)
@puz.group[cell].each do |option|
@puz.group(cell).each do |rowcolbox|
return @puz.board[cell] = option if rowcolbox.flatten.count(option) == 1
end
end
end
def really_solved?
@puz.format
@rows.each do |row|
return false unless row.sort == ('1'..'9').to_a
end
@columns.each do |col|
return false unless col.sort == ('1'..'9').to_a
end
@boxes.each do |box|
return false unless box.sort == ('1'..'9').to_a
end
true
end
def build_option_arrays
@puz.each.with_index do |value, cell|
next if value != '0'
potentials = options(cell)
@puz[cell] = (possibles.length > 1 ? potentials : potentials[0])
end
self.format
end
def solve_for_cell(cell = 0)
# return @puz if really_solved?
# Skip this cell if it is a string
cell == 80 ? next_cell = 0 : next_cell = cell + 1
solve(next cell) if @puz[cell].is_a?(String)
try_options(cell)
solve(cell+1)
@puz.each.with_index do |value, cell|
next if value != '0' # || neg_options(cell).length < 8
@puz[cell] = ('1'..'9').to_a.select{ |n| !neg_options(cell).include?(n) }[0]
self.format
end
end
# The big kahuna
def solve_puzzle
# Start off by building all of the arrays of options
build_option_arrays if @puz.board.include?('0')
end
end
end
class Array
# Strip an array of all non-matching data types
# e.g. isolate(String) to return array with only string valueents
def isolate(data_type)
self.keep_if { |e| e.is_a?(data_type) }
end
end
# RUNTIME
# input = ARGV[0].dup
input = '080020000040500320020309046600090004000640501134050700360004002407230600000700450'
@puzzle = Sudoku::Puzzle.new(input)
# puts puzzle.solve
# puts "Solved: #{puzzle.really_solved?.to_s.upcase}"
# SPECS
describe 'Sudoku' do
before(:each) do
@puzzle = Sudoku::Puzzle.new('619030040270061008000047621486302079000014580031009060005720806320106057160400030')
end
describe 'formatting' do
before(:each) do
@puzzle.format
end
it 'formats the puzzle into rows' do
@puzzle.rows.length.should eq(9)
end
it 'formats the puzzle into columns' do
@puzzle.columns.length.should eq(9)
end
it 'formats the puzzle into boxes' do
@puzzle.boxes.length.should eq(9)
end
end
it 'takes a string as an argument and returns a solved string' do
@puzzle.solve.should \
eq('619238745274561398853947621486352179792614583531879264945723816328196457167485932')
end
end
| true |
499313fa64f2f2c6181c7d19739379cf3cf7a537 | Ruby | necocen/nand2tetris | /njc/VMWriter.rb | UTF-8 | 755 | 3.296875 | 3 | [] | no_license | class VMWriter
def initialize(file)
@file = file
end
def writePush(segment, index)
@file.puts "push #{segment} #{index}"
end
def writePop(segment, index)
@file.puts "pop #{segment} #{index}"
end
def writeArithmetic(command)
@file.puts "#{command}"
end
def writeLabel(label)
@file.puts "label #{label}"
end
def writeGoto(label)
@file.puts "goto #{label}"
end
def writeIf(label)
@file.puts "if-goto #{label}"
end
def writeCall(name, nArgs)
@file.puts "call #{name} #{nArgs}"
end
def writeFunction(name, nLocals)
@file.puts "function #{name} #{nLocals}"
end
def writeReturn
@file.puts "return"
end
def writeComment(comment)
@file.puts "// #{comment}"
end
end
| true |
7e7ce1af48252f8e28ea4590414e8e94624ff7cd | Ruby | JeremyVe/game_of_life | /spec/models/cells_spec.rb | UTF-8 | 6,402 | 3.03125 | 3 | [] | no_license | require 'rails_helper'
describe Cells do
context '#create_cell' do
cell = {'x'=>5, 'y'=>4, 'color'=>[2,3,4]}
result = Cells.new.send(:create_cell, cell)
it 'should return a cell' do
expect(result).to eq({'x' => '5', 'y' => '4', 'color' => [2,3,4]})
end
end
context '#get_new_color' do
colors = [[200, 200, 200], [100, 130, 10], [60, 60, 60]]
result = Cells.new.send(:get_new_color, colors)
it 'shoud return an average of the colors provided' do
expect(result).to eq([120, 130, 90])
end
end
context '#add_cell' do
cell = {'x' => '5', 'y' => '4', 'color' => [2,3,4]}
it 'should add the cell to the list if living is true' do
cells = {}
result = Cells.new.send(:add_cell, cell, cells, true )
expectation = {'5' => {'4' => [2,3,4]}}
expect(result).to eq(expectation)
end
it 'should not add the cell to the list if living is false' do
cells = {}
result = Cells.new.send(:add_cell, cell, cells, false )
expectation = {}
expect(result).to eq(expectation)
end
it 'should not override the list when appending a cell' do
cells = {}
cells['5'] = {'3' => [2,3,4]}
result = Cells.new.send(:add_cell, cell, cells, true )
expectation = 2
expect(result['5'].length).to eq(expectation)
end
end
context '#next_cell_state' do
it 'should return true if living neighbors is 2 or 3' do
result = Cells.new.send(:next_cell_state, 2)
expect(result).to eq(true)
result = Cells.new.send(:next_cell_state, 3)
expect(result).to eq(true)
end
it 'should return false if living neighbors is < 2' do
result = Cells.new.send(:next_cell_state, 1)
expect(result).to eq(false)
end
it 'should return false if living neighbors is > 3' do
result = Cells.new.send(:next_cell_state, 4)
expect(result).to eq(false)
end
end
context '#calculate_neighbors' do
cell = {'x' => 5, 'y' => 5, 'color' => [2,3,4]}
it 'should return the number of living neighbors if none' do
cells = {}
neighbors = {}
result = Cells.new.send( :calculate_neighbors, cell, cells, neighbors )
expect(result).to eq( 0 )
end
it 'should return the number of living neighbors' do
cells = {'5' => {'4' => [2,3,4]}, '6' => {'4' => [2,3,4]}}
neighbors = {}
result = Cells.new.send( :calculate_neighbors, cell, cells, neighbors )
expect(result).to eq( 2 )
end
it 'should set the number of living cell for each neighbor' do
cells = {}
neighbors = {
"4"=>{"4"=>{"count"=>1, "colors"=>[[2, 3, 4]]}, "5"=>{"count"=>1, "colors"=>[[2, 3, 4]]}, "6"=>{"count"=>1, "colors"=>[[2, 3, 4]]}},
"5"=>{"4"=>{"count"=>1, "colors"=>[[2, 3, 4]]}, "6"=>{"count"=>1, "colors"=>[[2, 3, 4]]}},
"6"=>{"4"=>{"count"=>1, "colors"=>[[2, 3, 4]]}, "5"=>{"count"=>1, "colors"=>[[2, 3, 4]]}, "6"=>{"count"=>1, "colors"=>[[2, 3, 4]]}}
}
Cells.new.send( :calculate_neighbors, cell, cells, neighbors )
expect(neighbors).to eq( neighbors )
end
end
context '#calculate_cell' do
cell = {'x' => 5, 'y' => 5, 'color' => [2,3,4]}
cells = {'5' => {'4' => [2,3,4]}, '6' => {'4' => [2,3,4]}}
neighbors = {}
it 'should return true if the cell will live' do
new_cell = Cells.new
allow(new_cell).to receive(:calculate_neighbors).and_return( 3 )
result = new_cell.send(:calculate_cell, cell, cells, neighbors )
expect(result).to eq(true)
end
it 'should return false if the cell will die' do
new_cell = Cells.new
allow(new_cell).to receive(:calculate_neighbors).and_return( 4 )
result = new_cell.send(:calculate_cell, cell, cells, neighbors )
expect(result).to eq(false)
end
end
context '#calculate_next_state' do
it 'should return a hash with the cells living the next round' do
life = {
'updated_cells' => {},
'neighbor_cells' => {},
}
cells = { "4"=>{"4"=>[2, 3, 4], "5"=>[2, 3, 4], "6"=>[2, 3, 4]} }
expectation = {"neighbor_cells" => {"3"=>{"3"=>{"count"=>1, "colors"=>[[2, 3, 4]]}, "4"=>{"count"=>2, "colors"=>[[2, 3, 4], [2, 3, 4]]},
"5"=>{"count"=>3, "colors"=>[[2, 3, 4], [2, 3, 4], [2, 3, 4]]}, "6"=>{"count"=>2, "colors"=>[[2, 3, 4], [2, 3, 4]]},
"7"=>{"count"=>1, "colors"=>[[2, 3, 4]]}}, "4"=>{"3"=>{"count"=>1, "colors"=>[[2, 3, 4]]}, "7"=>{"count"=>1, "colors"=>[[2, 3, 4]]}},
"5"=>{"3"=>{"count"=>1, "colors"=>[[2, 3, 4]]}, "4"=>{"count"=>2, "colors"=>[[2, 3, 4], [2, 3, 4]]}, "5"=>{"count"=>3, "colors"=>[[2, 3, 4], [2, 3, 4], [2, 3, 4]]},
"6"=>{"count"=>2, "colors"=>[[2, 3, 4], [2, 3, 4]]}, "7"=>{"count"=>1, "colors"=>[[2, 3, 4]]}}},
"updated_cells" => {"4"=>{"5"=>[2, 3, 4]}},
}
result = Cells.new.send(:calculate_next_state, cells, life)
expect(result).to eq(expectation)
end
end
context '#reborn_neighbors' do
it 'should return a hash with the cells living the next round' do
life = {"neighbor_cells" => {"3"=>{"3"=>{"count"=>1, "colors"=>[[2, 3, 4]]}, "4"=>{"count"=>2, "colors"=>[[2, 3, 4], [2, 3, 4]]},
"5"=>{"count"=>3, "colors"=>[[2, 3, 4], [2, 3, 4], [2, 3, 4]]}, "6"=>{"count"=>2, "colors"=>[[2, 3, 4], [2, 3, 4]]},
"7"=>{"count"=>1, "colors"=>[[2, 3, 4]]}}, "4"=>{"3"=>{"count"=>1, "colors"=>[[2, 3, 4]]}, "7"=>{"count"=>1, "colors"=>[[2, 3, 4]]}},
"5"=>{"3"=>{"count"=>1, "colors"=>[[2, 3, 4]]}, "4"=>{"count"=>2, "colors"=>[[2, 3, 4], [2, 3, 4]]}, "5"=>{"count"=>3, "colors"=>[[2, 3, 4], [2, 3, 4], [2, 3, 4]]},
"6"=>{"count"=>2, "colors"=>[[2, 3, 4], [2, 3, 4]]}, "7"=>{"count"=>1, "colors"=>[[2, 3, 4]]}}},
"updated_cells" => {"4"=>{"5"=>[2, 3, 4]}},
}
expectation = { "neighbor_cells" => life["neighbor_cells"],
"updated_cells"=>{"4"=>{"5"=>[2, 3, 4]}, "3"=>{"5"=>[2, 3, 4]}, "5"=>{"5"=>[2, 3, 4]}}}
result = Cells.new.send(:reborn_neighbors, life)
expect(result).to eq(expectation)
end
end
end
| true |
8395f7217937da2822f2a6fb58e4bb10b8457132 | Ruby | bcoffin9/ruby-chess | /lib/chess/pieces/knight.rb | UTF-8 | 411 | 3.1875 | 3 | [
"MIT"
] | permissive | require_relative "piece.rb"
class Knight < Piece
def initialize(color)
img = color == "white" ? "\u2658" : "\u265e"
moves = [
[1,2], # x y
[2,1],
[2,-1],
[1,-2],
[-1,-2],
[-2,-1],
[-2,1],
[-1,2]
]
super(color, img, "knight", moves, false)
@castling = true
end
end | true |
8e49025695df02f68a73a6dfb4c3a1bf0e68edd1 | Ruby | williamsjs/guessing_game | /guessing_game.rb | UTF-8 | 970 | 4.125 | 4 | [] | no_license | require 'date'
def guessing(guess)
new_milli = DateTime.now.strftime('%s').to_i.to_s
milli_array = new_milli.split('')
random_num = milli_array[8] + milli_array[9]
random_num = random_num.to_i
count = 0
hot_or_cold(guess, random_num, count)
end
def hot_or_cold(guess, random_num, count)
guessed_nums = []
while count < 4
if guessed_nums.include?(guess)
puts "you've already guessed #{guess}"
elsif guess < random_num
puts "You are too low!"
elsif guess > random_num
puts "You are too high"
end
if guess == random_num
break
end
guessed_nums.push(guess)
count += 1
guess = gets.chomp.to_i
end
guessed_nums.push(guess)
puts "You guessed #{guessed_nums}"
if guessed_nums.include?(random_num)
puts "You won!"
else
puts "Sorry, the number was #{random_num}"
puts "You lose!"
end
end
puts "Please guess a number between 1 and 100"
guess = gets.chomp.to_i
guessing(guess)
| true |
ddb1459b82bf3e0e3539aa2a12f0904f105891b8 | Ruby | simplay/word_suggestor | /lib/core_extensions/array.rb | UTF-8 | 531 | 2.984375 | 3 | [
"MIT"
] | permissive | class Array
def levenshtein_suggestions(input, options={})
global_min_distance = options[:treshold] || WordSuggestor::DEFAULT_TRESHOLD
suggestion_tuples = []
self.each do |s|
next unless s.is_a?(String)
d = s.levenshtein_distance input
tuple = WordSuggestor::Tuple.new(d, s)
suggestion_tuples << tuple
global_min_distance = d if d < global_min_distance
end
suggestion_tuples.map do |tuple|
tuple.word if tuple.distance <= global_min_distance
end.compact
end
end | true |
dceb01d0d0cd6efb07fd7903ac8afc5f795bceb0 | Ruby | stevemcquaid/trailerapp | /app/helpers/application_helper.rb | UTF-8 | 204 | 2.515625 | 3 | [] | no_license | module ApplicationHelper
#standard date for the app
def time(d)
d.strftime("%I:%M%p")
end
def date(d)
d.strftime("%m/%d/%y")
end
def date_and_time(d)
[date(d), time(d)].compact.join(" ")
end
end
| true |
41a64ab37552f8271dc9f9fb1f5bef80d1e9d0bd | Ruby | Btate712/pokemon-scraper-online-web-sp-000 | /lib/pokemon.rb | UTF-8 | 644 | 3.171875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Pokemon
attr_accessor :id, :name, :type, :db, :hp
@@all = []
def initialize(arguments)
arguments.each { |key, value| self.send(("#{key}="), value) }
@@all << self
end
def self.save(name, type, db)
db.execute("INSERT INTO pokemon (name, type) VALUES (?, ?)", [name, type])
end
def self.find(id, db)
values = db.execute("SELECT id, name, type FROM pokemon WHERE id = ?", [id])
arguments = { :id => values[0][0], :name => values[0][1], :type => values[0][2] }
self.new(arguments)
end
def alter_hp(new_hp, db)
db.execute("UPDATE pokemon SET hp = ? WHERE id = ?", [new_hp, self.id])
end
end
| true |
a9b361c5f93805b5ac5aa1c1b8a14d7461217456 | Ruby | yasmim-cieb/geos-backend | /app/models/school_regionals_search.rb | UTF-8 | 863 | 2.75 | 3 | [] | no_license | class SchoolRegionalsSearch
attr_accessor :state, :city, :type
attr_reader :schools
def initialize(query: nil, sort_field: nil, sort_direction: nil, state: nil, city: nil, page: nil, type: nil, limit: nil)
@schools = School
@state = state
@city = city
@type = type
filter_by_type
filter_by_state
filter_by_city
filter_null
distinct_regional
end
def filter_by_state
@schools = @schools.where(:city_id.in => @state.cities.pluck(:_id)) if @state.present?
end
def filter_by_city
@schools = @schools.where(:city_id => @city._id) if @city.present?
end
def filter_by_type
@schools = @schools.where(:type => @type) if @type.present?
end
def filter_null
@schools = @schools.where(:regional.nin => [nil,''])
end
def distinct_regional
@schools = @schools.distinct(:regional)
end
end | true |
32e20867300d25764169bd4736583716eb652af7 | Ruby | tobico/openaustralia2 | /config/initializers/time_formats.rb | UTF-8 | 649 | 2.875 | 3 | [] | no_license | # Used for date formatting in OpenAustralia
# has form: 18 November 2008
Date::DATE_FORMATS[:simple] = lambda {|date| date.strftime("#{date.day} %B %Y")}
Date::DATE_FORMATS[:simple_with_day] = lambda {|date| date.strftime("#{Date::DAYNAMES[date.wday]}, #{date.day} %B %Y")}
Date::DATE_FORMATS[:simple_short] = lambda {|date| date.strftime("#{date.day} %b %Y")}
Date::DATE_FORMATS[:month] = "%B %Y"
# 12 Hour clock with am/pm
Time::DATE_FORMATS[:time_12] = lambda do |t|
hour = t.hour
hour -= 12 if hour > 12
am_pm = t.strftime("%p").downcase
mins = t.strftime("%M")
"#{hour}:#{mins} #{am_pm}"
end
Time::DATE_FORMATS[:seconds] = "%H:%M:%S"
| true |
b1e5e1e3489e7d8c5f3b93a6b483b73653c8a4af | Ruby | mdb/times_grapher | /spec/models/times_query_collection_spec.rb | UTF-8 | 1,537 | 2.609375 | 3 | [] | no_license | require 'spec_helper'
describe TimesQueryCollection do
before :each do
ENV.stub(:[]).and_return 'API_KEY'
end
subject { times_query_collection }
let(:times_query_collection) { described_class.new(['bush', 'gore']) }
describe '#erms' do
subject { times_query_collection.terms }
it { should eq ['bush', 'gore'] }
end
describe '#year' do
subject { times_query_collection.year }
it { should eq '2013' }
end
describe '#items' do
subject { times_query_collection.items.class }
it { should eq Array }
end
describe "each item in #items" do
subject { times_query_collection.items[0].class }
it { should eq TimesQuery }
end
describe "#hits" do
it "reports the total number of articles in the collection" do
VCR.use_cassette('models/times_query_collection') do
query = TimesQueryCollection.new ['bush', 'gore']
query.hits.should eq 4584
end
end
end
describe "#percent" do
it "reports the percent of the total hits for the term it's passed" do
VCR.use_cassette('models/times_query_collection') do
query = TimesQueryCollection.new ['bush', 'gore']
query.percent(query.terms[0]).should eq 85
query.percent(query.terms[1]).should eq 14
end
end
end
describe "#factors" do
it "reports the percent of the total hits for the term it's passed" do
times_query_collection.stub(:hits).and_return 10
times_query_collection.factors(5).should eq [10, 8, 5, 3, 0]
end
end
end
| true |
4895927024d9edff67b41cdff95377fb6a4eda6e | Ruby | wizzywit/Ruby-Training-Session | /Quest03/ex05/college_course_average.rb | UTF-8 | 881 | 4.09375 | 4 | [] | no_license | =begin
function whch take a hash with all marks for a test and returns average mark
for the test
=end
def class_average(class_results)
# sum to hold the sum of values
sum = 0
# validate if it is a valid hash passed
if !class_results.is_a? Hash
print "Pass in a hash value"
return
end
# validate if the hash is empty
if class_results.empty?
print 0.0
return
end
# loop through every value, validate each values and add to sum
class_results.values.each do |value|
# check if any value is not an integer or float
if !value.is_a? Integer and !value.is_a? Float
print "#{value} is not a valid Number"
return
end
sum += value
end
# caluculate the average
avg = sum.to_f/class_results.size
end
print class_average ({"john"=>67})
| true |
47bc6053506e181e76f9f62a0250a42442b85adf | Ruby | Svawek/thinknetica | /lesson_7/route.rb | UTF-8 | 330 | 3.3125 | 3 | [] | no_license | class Route
include InstanceCounter
attr_reader :stations
def initialize(station_first, station_last)
@stations = [station_first, station_last]
register_instance
end
def add_station(station)
self.stations.insert(-2, station)
end
def remove_station(station)
self.stations.delete(station)
end
end
| true |
9772a193f609c7bc154ba30ef32e62bb5dfa8554 | Ruby | ignazioc/QuizletNerdClient | /lib/QuizletNerdClient/preference_manager.rb | UTF-8 | 1,269 | 2.546875 | 3 | [
"MIT"
] | permissive |
class PreferenceManager
include Singleton
def settings_file
"#{Dir.home}/.qnc.conf"
end
def reset
File.delete(settings_file) if File.exist?(settings_file)
end
def store(settings)
File.open(settings_file, 'w') do |file|
file.write(settings.to_yaml)
end
end
def store_preferences(client_id, app_secret, username)
settings = {}
settings[:client_id] = client_id
settings[:app_secret] = app_secret
settings[:username] = username
store(settings)
end
def store_token_hash(token)
return nil unless File.exist?(settings_file)
settings = YAML.load_file(settings_file)
settings[:app_token] = token
store(settings)
end
def client_id
return nil unless File.exist?(settings_file)
settings = YAML.load_file(settings_file)
settings[:client_id]
end
def app_secret
return nil unless File.exist?(settings_file)
settings = YAML.load_file(settings_file)
settings[:app_secret]
end
def app_token
return nil unless File.exist?(settings_file)
settings = YAML.load_file(settings_file)
settings[:app_token]
end
def username
return nil unless File.exist?(settings_file)
settings = YAML.load_file(settings_file)
settings[:username]
end
end
| true |
c7ce6267c87aca80e3c5caf5a1c087eba7e0c012 | Ruby | piotrmurach/github_cli | /lib/github_cli/ui.rb | UTF-8 | 964 | 2.5625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | # frozen_string_literal: true
require 'forwardable'
module GithubCLI
# Class responsible for displaying different level information
class UI
extend Forwardable
def_delegators :@prompt, :ask, :mask, :suggest
def initialize(prompt)
@prompt = prompt
@quite = false
@debug = ENV['DEBUG']
@shell = Thor::Shell::Basic.new
end
def confirm(message)
@prompt.ok(message)
end
def info(message)
@prompt.say(message)
end
def warn(messag)
@prompt.warn(message)
end
def error(message)
@prompt.error(message)
end
def debug(error, newline = nil)
message = ["#{error.class}: #{error.message}", *error.backtrace]
@prompt.say(message.join("\n"))
end
def quite!
@quite = true
end
def debug!
@debug = true
end
def print_table(table, options = {})
@shell.print_table table, options
end
end # UI
end # GithubCLI
| true |
f55c44f8feac0b6446155d4aed82687972febb65 | Ruby | kevinnio/crowd_exercises | /palindromes/lib/strategies/palindrome_strategy.rb | UTF-8 | 583 | 3.53125 | 4 | [] | no_license | # encoding: utf-8
# Palindrome generation algorithm.
# This strategy creates a palindrome by sorting the string's chars
# and split them in two strings.
class PalindromeStrategy
def generate(string)
chars = string.chars.sort
isolated_char = chars.select { |c| chars.count(c).odd? }.uniq.join
chars.delete_at chars.index(isolated_char) if isolated_char.size > 0
first_half, second_half = [], []
until chars.empty?
first_half << chars.shift
second_half << chars.shift
end
[(first_half << isolated_char << second_half.reverse).join]
end
end
| true |
d2f760d649ef39e6207cc5197c759b6bbac8b9a7 | Ruby | jcarlosgarcia/porter-stemmer | /test/test_stemmer.rb | UTF-8 | 717 | 3.03125 | 3 | [] | no_license | require 'minitest/autorun'
require 'porter-stemmer'
class StemmerTest < MiniTest::Test
include Porter
def setup
@input = File.read('test/input.txt')
@expected_output = File.read('test/output.txt')
end
def test_stem
input = @input.split(/\W+/)
expected = @expected_output.split(/\W+/)
input.each_index do |index|
stemmed_word = input[index].stem
expected_value = expected[index]
assert_equal expected_value, stemmed_word, "#{stemmed_word} does not match the expected value: #{expected_value}"
end
end
def test_stem_as_array
assert_equal @expected_output.split(/\W+/), @input.stem_as_array, "Looks like some words were not stemmed as expected"
end
end
| true |
6f0836313acd8c0d251b27614ec75e9a32cac0e9 | Ruby | JyCyunMe/rails5_mall_demo | /app/models/cart.rb | UTF-8 | 574 | 2.796875 | 3 | [] | no_license | class Cart < ApplicationRecord
# 一对多关联,销毁自身时删除所有关联项
has_many :cart_items, :dependent => :destroy
# 添加商品,累加数量
def add_product(product)
current_item = cart_items.find_by(product_id: product.id)
if current_item
current_item.count += 1
else
current_item = cart_items.build(product_id: product.id, count: 1)
end
current_item
end
def total_count
cart_items.to_a.sum { |item| item.count }
end
def total_price
cart_items.to_a.sum { |item| item.total_price }
end
end
| true |
8e318e11ae8a253551a9c6f92e98702a8744852b | Ruby | Gnuside/infobipapi | /test/test.rb | UTF-8 | 26,021 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | # vim: set sw=4 ts=4 et :
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'minitest/autorun'
require 'infobipapi/client'
API_USERNAME = ENV["API_USERNAME"]
API_PASSWORD = ENV["API_PASSWORD"]
if (API_USERNAME.nil? || API_USERNAME == '') || (API_PASSWORD.nil? || API_PASSWORD == '') then
raise "set environement variable API_USERNAME and API_PASSWORD with an Infobip valid account (see https://dev.infobip.com/docs/getting-started)"
end
NUMBERS = File::readlines(File.expand_path('../../test-numbers.txt', __FILE__)).map { |a| a.strip }
puts ""
puts "Testing API with #{API_USERNAME} / #{API_PASSWORD} credentials"
puts ""
puts "List of numbers used:"
NUMBERS.each { |num|
puts " - #{num}"
}
puts ""
puts "-------"
puts ""
class InfobipApiTest < MiniTest::Unit::TestCase
def self.test_order
return :alpha
end
def test_a_empty
assert_equal InfobipApi::Utils.empty(0), true
assert_equal InfobipApi::Utils.empty(1), false
assert_equal InfobipApi::Utils.empty('aaa'), false
assert_equal InfobipApi::Utils.empty(0.0), true
assert_equal InfobipApi::Utils.empty([]), true
assert_equal InfobipApi::Utils.empty([1]), false
assert_equal InfobipApi::Utils.empty({}), true
assert_equal InfobipApi::Utils.empty({'a' => 1}), false
assert_equal InfobipApi::Utils.empty(''), true
end
def test_a_json_get
json = '{"requestError":{"serviceException":{"text":"Request URI missing required component(s): ","messageId":"SVC0002","variables":[""]},"policyException":null}}'
request_error = InfobipApi::JSONUtils.get(json, 'requestError.serviceException.text')
assert_equal('Request URI missing required component(s): ', request_error)
end
def test_a_json_get_hash_result
json = '{"requestError":{"serviceException":{"text":"Request URI missing required component(s): ","messageId":"SVC0002","variables":[""]},"policyException":null}}'
value = InfobipApi::JSONUtils.get(json, 'requestError.serviceException')
puts value.inspect
assert_equal(value, {"messageId"=>"SVC0002", "variables"=>[""], "text"=>"Request URI missing required component(s): "})
end
def test_a_json_get_array_in_path
json = '{"requestError":{"serviceException":{"text":"Request URI missing required component(s): ","messageId":"SVC0002","variables":["abc", "cde"]},"policyException":null}}'
value = InfobipApi::JSONUtils.get(json, 'requestError.serviceException.variables.1')
assert_equal(value, "cde")
end
def test_a_json_get_with_or_paths
json = '{"requestError":{"serviceException":{"text":"Request URI missing required component(s): ","messageId":"SVC0002","variables":["abc", "cde"]},"policyException":null}}'
value = InfobipApi::JSONUtils.get(json, 'requestError.serviceException.messageId | requestError.policyException.messageId')
assert_equal(value, "SVC0002")
json = '{"requestError":{"policyException":{"text":"Request URI missing required component(s): ","messageId":"SVC0002","variables":["abc", "cde"]},"serviceException":null}}'
value = InfobipApi::JSONUtils.get(json, 'requestError.serviceException.messageId | requestError.policyException.messageId')
assert_equal(value, "SVC0002")
end
def test_a_exception_serialization
json = '{"requestError":{"serviceException":{"text":"Request URI missing required component(s): ","messageId":"SVC0002","variables":[""]},"policyException":null}}'
sms_exception = InfobipApi::Conversions.from_json(InfobipApi::InfobipApiError, json, nil)
assert(sms_exception)
assert_equal(sms_exception.message_id, 'SVC0002')
assert_equal(sms_exception.text, 'Request URI missing required component(s): ')
end
def test_a_exception_object_array
json = '{"deliveryInfoList":{"deliveryInfo":[{"address":null,"deliveryStatus":"DeliveryUncertain1"},{"address":null,"deliveryStatus":"DeliveryUncertain2"}],"resourceURL":"http://api.infobip.com/sms/1/smsmessaging/outbound/TODO/requests/28drx7ypaqr/deliveryInfos"}}'
object = InfobipApi::Conversions.from_json(InfobipApi::DeliveryInfoList, json, nil)
assert(object)
assert(object.delivery_info)
assert_equal(2, object.delivery_info.length)
assert_equal("DeliveryUncertain1", object.delivery_info[0].delivery_status)
assert_equal("DeliveryUncertain2", object.delivery_info[1].delivery_status)
end
def test_a_login
@@sms_connector = InfobipApi::SmsClient.new(API_USERNAME, API_PASSWORD)
refute_instance_of(InfobipApi::InfobipApiError, @@sms_connector)
end
def test_a_sms_usage_single_gsm7
test_sms = [
"Hello",
"Hello, are you ok ?",
"Bonjour, es-tu assoiffé ?"
].each { |message|
usage = @@sms_connector.compute_sms_usage(message)
assert_equal(:gsm7, usage[:format], "Failed to compute the right format on message '#{message}'")
assert_equal(message.length, usage[:length], "Failed length on message '#{message}'")
assert_equal(160, usage[:length_by_sms], "Failed length by SMS on message '#{message}'")
assert_equal(1, usage[:number_of_sms], "Failed number of SMS on message '#{message}'")
}
end
def test_a_sms_usage_multi_gsm7
test_sms = [
"Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello ",
"Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? ",
"Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ?"
].each { |message|
usage = @@sms_connector.compute_sms_usage(message)
assert_equal(:gsm7, usage[:format], "Failed to compute the right format on message '#{message}'")
assert_equal(message.length, usage[:length], "Failed length on message '#{message}'")
assert_equal(153, usage[:length_by_sms], "Failed length by SMS on message '#{message}'")
assert_equal(
(message.length.to_f / 153.0).ceil,
usage[:number_of_sms],
"Failed number of SMS on message #{message}")
}
end
def test_a_sms_usage_single_utf8
test_sms = [
"Hello č",
"Hello, are you ok ? č",
"Bonjour, es-tu assoiffé ? œŒ"
].each { |message|
usage = @@sms_connector.compute_sms_usage(message)
assert_equal(:unicode, usage[:format], "Failed to compute the right format on message '#{message}'")
assert_equal(message.length, usage[:length], "Failed length on message '#{message}'")
assert_equal(70, usage[:length_by_sms], "Failed length by SMS on message '#{message}'")
assert_equal(1, usage[:number_of_sms], "Failed number of SMS on message '#{message}'")
}
end
def test_a_sms_usage_multi_utf8
test_sms = [
"Hellœ Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello ",
"Hellœ, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? ",
"Bœnjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ?"
].each { |message|
usage = @@sms_connector.compute_sms_usage(message)
assert_equal(:unicode, usage[:format], "Failed to compute the right format on message '#{message}'")
assert_equal(message.length, usage[:length], "Failed length on message '#{message}'")
assert_equal(67, usage[:length_by_sms], "Failed length by SMS on message '#{message}'")
assert_equal(
(message.length.to_f / 67.0).ceil,
usage[:number_of_sms],
"Failed number of SMS on message #{message}")
}
end
# use prefix test_b for any function that needs to be run after test_a_login
def test_b_single_text_sms_00001
sms = InfobipApi::SimpleTextSMSRequest.new
sms.from = 'InfobipApiRuby'
sms.to = NUMBERS[0]
sms.text = "Unit Testing: #{__method__}"
response = @@sms_connector.single_text_sms(sms)
refute_instance_of(InfobipApi::InfobipApiError, response)
assert_equal(response.messages.length, 1)
end
def test_b_single_text_sms_0000n
sms = InfobipApi::SimpleTextSMSRequest.new
sms.from = 'InfobipApiRuby'
sms.to = NUMBERS
sms.text = "Unit Testing: #{__method__}"
response = @@sms_connector.single_text_sms(sms)
refute_instance_of(InfobipApi::InfobipApiError, response)
assert_equal(response.messages.length, NUMBERS.length)
end
# def test_b_single_text_sms_03000
# sms = InfobipApi::SimpleTextSMSRequest.new
# sms.from = 'InfobipApiRuby'
# sms.to = (NUMBERS[0].to_i..(NUMBERS[0].to_i + 2999)).to_a
# sms.text = "Unit Testing: #{__method__}"
# response = @@sms_connector.single_text_sms(sms)
# refute_instance_of(InfobipApi::InfobipApiError, response)
# assert_equal(response.messages.length, 3000)
# end
# def test_b_single_text_sms_10000
# sms = InfobipApi::SimpleTextSMSRequest.new
# sms.from = 'InfobipApiRuby'
# sms.to = (NUMBERS[0].to_i..(NUMBERS[0].to_i + 9999)).to_a
# sms.text = "Unit Testing: #{__method__}"
# response = @@sms_connector.single_text_sms(sms)
# refute_instance_of(InfobipApi::InfobipApiError, response)
# assert_equal(response.messages.length, 10000)
# end
def test_b_multiple_text_sms_00001
smss = []
NUMBERS.each { |num|
sms = InfobipApi::SimpleTextSMSRequest.new
sms.from = 'InfobipApiRuby'
sms.to = num
sms.text = "Unit Testing: #{__method__} for '#{num}'"
smss.push sms
}
response = @@sms_connector.multiple_text_sms(smss)
refute_instance_of(InfobipApi::InfobipApiError, response)
assert_equal(smss.length, response.messages.length)
end
def test_b_single_utf8_sms_00001
sms = InfobipApi::SimpleTextSMSRequest.new
sms.from = 'InfobipApiRuby'
sms.to = NUMBERS[0]
sms.text = "Unit Testing: #{__method__}"
response = @@sms_connector.single_utf8_sms(sms)
refute_instance_of(InfobipApi::InfobipApiError, response)
assert_equal(response.messages.length, 1)
end
def test_b_single_utf8_sms_0000n
sms = InfobipApi::SimpleTextSMSRequest.new
sms.from = 'InfobipApiRuby'
sms.to = NUMBERS
sms.text = "Unit Testing: #{__method__}"
response = @@sms_connector.single_utf8_sms(sms)
refute_instance_of(InfobipApi::InfobipApiError, response)
assert_equal(response.messages.length, NUMBERS.length)
end
def test_b_multiple_utf8_as_text_sms_00001
smss = []
NUMBERS.each { |num|
sms = InfobipApi::SimpleTextSMSRequest.new
sms.from = 'InfobipApiRuby'
sms.to = num
sms.text = "Unit Testing: #{__method__} for '#{num}'"
smss.push sms
}
answers = @@sms_connector.multiple_utf8_sms(smss)
assert_equal(2, answers.length)
answer_text = answers[0]
answer_bin = answers[1]
assert_nil(answer_bin)
refute_nil(answer_text)
refute_instance_of(InfobipApi::InfobipApiError, answer_text)
assert_equal(smss.length, answer_text.messages.length)
end
def test_b_multiple_utf8_as_binary_sms_00001
smss = []
NUMBERS.each { |num|
sms = InfobipApi::SimpleTextSMSRequest.new
sms.from = 'InfobipApiRuby'
sms.to = num
sms.text = "Unit Testing: #{__method__} fœr '#{num}'"
smss.push sms
}
answers = @@sms_connector.multiple_utf8_sms(smss)
assert_equal(2, answers.length)
answer_text = answers[0]
answer_bin = answers[1]
refute_nil(answer_bin)
assert_nil(answer_text)
refute_instance_of(InfobipApi::InfobipApiError, answer_bin)
binding.pry
assert_equal(smss.length, answer_bin.messages.length)
end
def test_b_multiple_utf8_as_mixte_sms_00001
smss = []
NUMBERS.each_with_index { |num, i| # we need at least 2 numbers for this test to pass
sms = InfobipApi::SimpleTextSMSRequest.new
sms.from = 'InfobipApiRuby'
sms.to = num
if i.modulo(2) == 0 then
sms.text = "Unit Testing: #{__method__} fœr '#{num}'"
else
sms.text = "Unit Testing: #{__method__} for '#{num}'"
end
smss.push sms
}
answers = @@sms_connector.multiple_utf8_sms(smss)
assert_equal(2, answers.length)
answer_text = answers[0]
answer_bin = answers[1]
refute_nil(answer_bin)
refute_nil(answer_text)
refute_instance_of(InfobipApi::InfobipApiError, answer_bin)
refute_instance_of(InfobipApi::InfobipApiError, answer_text)
assert_equal(smss.length, answer_bin.messages.length + answers_text.messages.length)
end
def test_b_gsm7_cmp_sms_usage_to_realone
sms = InfobipApi::SimpleTextSMSRequest.new
sms.from = 'InfobipApiRuby'
sms.to = NUMBERS[0]
sms.text = "Unit Testing: #{__method__}"
test_sms = [
"Hello",
"Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? ",
"Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ?"
].each { |message|
usage = @@sms_connector.compute_sms_usage(message)
assert_equal(:gsm7, usage[:format], "Failed to compute the right format on message '#{message}'")
assert_equal(message.length, usage[:length], "Failed length on message '#{message}'")
if message.length > 160 then
assert_equal(153, usage[:length_by_sms], "Failed length by SMS on message '#{message}'")
assert_equal(
(message.length.to_f / 153.0).ceil,
usage[:number_of_sms],
"Failed number of SMS on message '#{message}'")
else
assert_equal(160, usage[:length_by_sms], "Failed length by SMS on message '#{message}'")
assert_equal(1, usage[:number_of_sms], "Failed number of SMS on message '#{message}'")
end
sms.text = message
response = @@sms_connector.single_text_sms(sms)
refute_instance_of(InfobipApi::InfobipApiError, response)
assert_equal(1, response.messages.length)
assert_equal(response.messages[0].sms_count, usage[:number_of_sms], "Failed to match computed usage and API measurement on message '#{message}'")
}
end
def test_b_utf8_cmp_sms_usage_to_realone
sms = InfobipApi::SimpleTextSMSRequest.new
sms.from = 'InfobipApiRuby'
sms.to = NUMBERS[0]
sms.text = "Unit Testing: #{__method__}"
test_sms = [
"Hellœ",
"Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? ",
"Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ? Bœnjour, es-tu assoiffé ?"
].each { |message|
usage = @@sms_connector.compute_sms_usage(message)
assert_equal(:unicode, usage[:format], "Failed to compute the right format on message '#{message}'")
assert_equal(message.length, usage[:length], "Failed length on message '#{message}'")
if message.length > 70 then
assert_equal(67, usage[:length_by_sms], "Failed length by SMS on message '#{message}'")
assert_equal(
(message.length.to_f / 67.0).ceil,
usage[:number_of_sms],
"Failed number of SMS on message '#{message}'")
else
assert_equal(70, usage[:length_by_sms], "Failed length by SMS on message '#{message}'")
assert_equal(1, usage[:number_of_sms], "Failed number of SMS on message '#{message}'")
end
sms.text = message
response = @@sms_connector.single_utf8_sms(sms)
refute_instance_of(InfobipApi::InfobipApiError, response)
assert_equal(1, response.messages.length)
assert_equal(response.messages[0].sms_count, usage[:number_of_sms], "Failed to match computed usage and API measurement on message '#{message}'")
}
end
def test_b_utf8_as_gsm7_cmp_sms_usage_to_realone
sms = InfobipApi::SimpleTextSMSRequest.new
sms.from = 'InfobipApiRuby'
sms.to = NUMBERS[0]
sms.text = "Unit Testing: #{__method__}"
test_sms = [
"Hello",
"Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? Hello, are you ok ? ",
"Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ?"
].each { |message|
usage = @@sms_connector.compute_sms_usage(message)
assert_equal(:gsm7, usage[:format], "Failed to compute the right format on message '#{message}'")
assert_equal(message.length, usage[:length], "Failed length on message '#{message}'")
if message.length > 160 then
assert_equal(153, usage[:length_by_sms], "Failed length by SMS on message '#{message}'")
assert_equal(
(message.length.to_f / 153.0).ceil,
usage[:number_of_sms],
"Failed number of SMS on message '#{message}'")
else
assert_equal(160, usage[:length_by_sms], "Failed length by SMS on message '#{message}'")
assert_equal(1, usage[:number_of_sms], "Failed number of SMS on message '#{message}'")
end
sms.text = message
answer = @@sms_connector.single_utf8_sms(sms)
refute_nil(answer)
refute_instance_of(InfobipApi::InfobipApiError, answer)
assert_equal(1, answer.messages.length)
assert_equal(answer.messages[0].sms_count,
usage[:number_of_sms],
"Failed to match computed usage and API measurement on message '#{message}'")
}
end
def test_b_utf8_as_binary_cmp_sms_usage_to_realone
sms = InfobipApi::SimpleTextSMSRequest.new
sms.from = 'InfobipApiRuby'
sms.to = NUMBERS[0]
sms.text = "Unit Testing: #{__method__}"
test_sms = [
"Hellœ",
"Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? Hellœ, are you ok ? ",
"Bœnjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ? Bonjour, es-tu assoiffé ?"
].each { |message|
usage = @@sms_connector.compute_sms_usage(message)
assert_equal(:unicode, usage[:format], "Failed to compute the right format on message '#{message}'")
assert_equal(message.length, usage[:length], "Failed length on message '#{message}'")
if message.length > 70 then
assert_equal(67, usage[:length_by_sms], "Failed length by SMS on message '#{message}'")
assert_equal(
(message.length.to_f / 67.0).ceil,
usage[:number_of_sms],
"Failed number of SMS on message '#{message}'")
else
assert_equal(70, usage[:length_by_sms], "Failed length by SMS on message '#{message}'")
assert_equal(1, usage[:number_of_sms], "Failed number of SMS on message '#{message}'")
end
sms.text = message
answer = @@sms_connector.single_utf8_sms(sms)
refute_nil(answer)
refute_instance_of(InfobipApi::InfobipApiError, answer)
assert_equal(1, answer.messages.length)
assert_equal(answer.messages[0].sms_count,
usage[:number_of_sms],
"Failed to match computed usage and API measurement on message '#{message}'")
}
end
def test_b_get_delivery_reports
sms = InfobipApi::SimpleTextSMSRequest.new
sms.from = 'InfobipApiRuby'
sms.to = NUMBERS
sms.text = "Unit Testing: #{__method__}"
response = @@sms_connector.single_utf8_sms(sms)
refute_instance_of(InfobipApi::InfobipApiError, response)
assert_instance_of(InfobipApi::SimpleSMSAnswer, response)
dr = @@sms_connector.delivery_reports({:bulkId => response.bulk_id})
refute_instance_of(InfobipApi::InfobipApiError, dr)
assert_instance_of(InfobipApi::DeliveryReportList, dr)
end
end
| true |
19f50f057aff12f580ef2d88e03063a9cd2c9599 | Ruby | itggot-ludvig-pennert/standard-biblioteket | /lib/min_of_three.rb | UTF-8 | 438 | 4.4375 | 4 | [] | no_license | # Public: Compare three numbers and return the smallest
#
# n1 - The first number to be compared.
# n2 - The second number to be compared.
# n3 - The third number to be compared.
#
# Examples
# min_of_four('4', '5', '6')
# # => '4'
#
# Returns the smallest number
def min_of_three(n1, n2, n3)
smallest = n1
if n2 < n3
smallest = n2
end
if n3 < smallest
smallest = n3
end
return smallest
end | true |
8ac5c5da103c9647582e3a29db8dc61b7d063529 | Ruby | kevinladkins/playlister-sinatra-v-000 | /app/models/genre.rb | UTF-8 | 319 | 2.578125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Genre < ActiveRecord::Base
has_many :song_genres
has_many :songs, :through => :song_genres
has_many :artists, through: :songs
def slug
slug = self.name.downcase.strip.gsub(' ', '-')
slug
end
def self.find_by_slug(slug)
genre = self.all.detect {|s| s.slug == slug}
genre
end
end
| true |
5f7c7bbef3633aae7cf19e801b69a0f23fcc83c1 | Ruby | mjester93/ice-cream-app-backend | /app/models/store.rb | UTF-8 | 451 | 2.578125 | 3 | [] | no_license | class Store < ApplicationRecord
has_many :reviews
has_many :favorite_stores
has_many :ice_cream_stores
has_many :ice_creams, through: :ice_cream_stores
def ice_cream_count
return self.ice_creams.count
end
def avg_rating
if self.reviews.count != 0 then
return (self.reviews.map {|review| review.rating}.sum) / (self.reviews.count)
else
return 0
end
end
end
| true |
5c39fff3c586670de373a8dd098284244d5c066f | Ruby | adnanpirota/echopirota | /app/workers/matching_worker.rb | UTF-8 | 2,266 | 2.859375 | 3 | [] | no_license | require 'json'
class MatchingWorker
include Sidekiq::Worker
def perform(file_name, radio_id)
# We execute the shell command to get the echoprint codegen
cmd = `echoprint-codegen #{file_name}`
data = JSON.parse(cmd)
# we extract the fingerprint
fp_code = data[0]['code']
track_id = does_fingerprint_exist(fp_code)
if track_id.length > 0
# if fingerprint exists we add it to matches table
add_to_matches(track_id, radio_id)
else
# else we insert fingerprint in echoprint and local database
insert_fingerprint(fp_code)
end
end
# does_fingerprint_exist method checks weather fingerprint exist in echonest database and if it exists it returns fingerprints track_id
def does_fingerprint_exist(fp_code)
track_id = ''
# we check if fingerprint exists in echoprint
http = Curl.get("http://localhost:8080/query", {fp_code: fp_code})
body_str = http.body_str
data = JSON.parse(body_str)
# we extract the match element
fp_match = data['match']
# if match is true we respond with track_id otherwase send empty response
if fp_match == true
# if fingerprint is matched we return track_id that we can use to identify the fingerprint in local database to insert the match
track_id = data['track_id']
else
track_id = ''
end
#match
end
# insert_fingerprint method inserts fingerprint to echonest as well as local database
def insert_fingerprint(fp_code)
# we insert the fingerprint in the echprint database
http = Curl.post("http://localhost:8080/ingest", {fp_code: fp_code, length: 40 , codever: 4.12})
body = http.body_str
data = JSON.parse(body)
# we retrieve the returned track_id and title so that we can insert it in our local database
track_id = data['track_id']
track_title = data['title']
# we insert the fingerprint in local database
fp_lokal = Fingerprint.create(track_id: track_id, title: track_title, fingerprint: fp_code)
end
# add_to_matches method adds the matched fingerprint to matches table
def add_to_matches(track_id, radio_id)
fp_matched = Fingerprint.find_by track_id: track_id
Match.create(fingerprint_id: fp_matched.id, radio_id: radio_id)
end
end
| true |
b5b5651acb451e6d02081e92505c491cc46a3d16 | Ruby | maryrosecook/playmarymixtape | /app/models/file_upload.rb | UTF-8 | 2,758 | 2.703125 | 3 | [] | no_license | require File.dirname(__FILE__) + '/../../config/boot'
class FileUpload < ActiveRecord::Base
has_one :track
FILE_DIRECTORY = "public/mp3s/"
HTTP_OK_CODE = "200"
MIN_FILE_LENGTH = 100000
def file=(file_field)
self.save_content_and_upload(file_field.original_filename, file_field.read)
self
end
def self.new_and_save_from_remote_url(url)
file_upload = nil
track = get_remote_track(url)
if track && track.code == HTTP_OK_CODE # got track OK so save it locally
if track.body.length > MIN_FILE_LENGTH
file_upload = self.new()
file_upload.save_content_and_upload(File.basename(url), track.body)
end
end
file_upload
end
def save_content_and_upload(basename, content)
self.save()
sanitised_basename = basename.downcase().gsub(/\.mp3/, "extensionextensionextension").gsub(/\W/, "").gsub(/extensionextensionextension/, ".mp3")
name = FileUpload::get_next_filename(sanitised_basename, self.id)
File.open("#{FILE_DIRECTORY}#{name}", "w") { |f| f.write(content) }
self.local_path = FILE_DIRECTORY.to_s + name.to_s
upload_file_to_s3(self.local_path) # send file to S3
end
# returns url to submission file for this uploaded file (stored on S3)
def url()
Configuring.get("static_repository") + self.filename()
end
# returns local filename of submission file for this uploaded file
def filename()
File.basename(self.local_path)
end
private
def self.get_remote_track(url)
track = nil
begin
Timeout::timeout(60) do
track = Net::HTTP.get_response(URI.parse(APIUtil::make_url_safe(url))) # get_response takes an URI object
end
rescue Timeout::Error # failure - got_track is already false
rescue # let through other errors
end
track
end
# formulate a filename
def self.get_next_filename(original_filename, unique_id)
unique_id.to_s + original_filename
end
# uploads file at passed path to S3
def upload_file_to_s3(path)
if /^#{ FILE_DIRECTORY }(.+[^~])$/.match(path) && File.readable?(path)
key = Regexp.last_match[1]
mime = 'text/jpeg'
datafile = File.open(path)
filesize = File.size(path)
puts "uploading #{ path } as #{ key } mime #{ mime }"
conn = S3::AWSAuthConnection.new(Configuring.get("aws_access_key_id"), Configuring.get("aws_secret_access_key"), false)
conn.put(Configuring.get("bucket_name"), key, datafile.read,
{ "Content-Type" => mime, "Content-Length" => filesize.to_s,
"Content-Disposition"=> "inline;filename=#{File.basename(key).gsub(/\s/, '_')}",
"x-amz-acl" => "public-read" })
end
end
end | true |
bde431eca8dc3ae901f5f82aff542a29bb7c5d12 | Ruby | fanjieqi/LeetCodeRuby | /1201-1300/1217. Play with Chips.rb | UTF-8 | 320 | 3.09375 | 3 | [
"MIT"
] | permissive | # @param {Integer[]} chips
# @return {Integer}
def min_cost_to_move_chips(chips)
positions = chips.inject({}) { |hash, position| hash.merge(position => hash[position].to_i + 1) }
positions.keys.map do |i|
positions.inject(0) do |sum, (j, count)|
sum += (j-i).abs.odd? ? 1 * count : 0
end
end.min
end
| true |
c308f214ac6b29c1be5618cf67ad7db9d6a949ef | Ruby | acltc/vg_tools | /lib/helper_tools/update_map.rb | UTF-8 | 701 | 3.09375 | 3 | [
"MIT"
] | permissive | module UpdateMap
def reset_screen
print "\e[2J\e[H"
end
def reset_map
self.presenting_map = dup_map
end
def place_character(alt_map=nil)
if alt_map
alt_map[current_square[0]][current_square[1]] = character
else
presenting_map[current_square[0]][current_square[1]] = character
end
end
def print_map(map_array=nil)
(map_array || presenting_map).each { |row| puts row.join("") }
end
def update_and_print
reset_screen
reset_map
place_character
print_map
end
private
def deep_dup(array)
dup_array = array.dup
dup_array.map! { |element| element.dup }
end
def dup_map
map.dup.map! { |e| deep_dup(e) }
end
end | true |
65010336b429ec40e93f9050b9c86a1f284163bf | Ruby | Harritone/Thinknetica | /lesson_4/lib/dialogs/train_routes_management_dialog.rb | UTF-8 | 988 | 3.078125 | 3 | [] | no_license | require_relative 'dialog'
# require_relative 'station'
class TrainRoutesManagementDialog < Dialog
private
def get_input
@current_choice = nil
@current_route = nil
@current_train = nil
clear
show_dialog_name 'Train routes management dialog'
puts 'Here you can set route to train.'
show_trains
clear
show_routes
end
def handle_choice
set_route_to_train
msg = 'Route was set.'
ask_again(msg)
end
def show_trains
trains = @app_state.trains
puts 'Choose the train to set route to.'
render_collection(trains)
@current_choice = check_choice(gets.chomp).to_i
@current_train = trains[@current_choice - 1]
end
def show_routes
routes = @app_state.routes
puts 'Choose the route.'
render_collection(routes)
@current_choice = check_choice(gets.chomp).to_i
@current_route = routes[@current_choice - 1]
end
def set_route_to_train
@current_train.set_route(@current_route)
end
end
| true |
15a1a72775b7b90f316f3e2b0007e831b158d35a | Ruby | Colex/trojan-rb | /lib/trojan/spy.rb | UTF-8 | 1,064 | 3.109375 | 3 | [] | no_license | module Trojan
class Spy
DEFAULT_CALL_STRATEGY_VALUE = [nil]
attr_reader :calls
def initialize(obj, method_name)
@hooked = false
@object = obj
@method_name = method_name
@original_method = @object.method(method_name)
@calls = []
@call_strategy = :static_return
@call_strategy_value = DEFAULT_CALL_STRATEGY_VALUE
@call_strategy_index = 0
end
def hooked?
@hooked
end
def hook!
raise "spy has already been hooked" if hooked?
@object.define_singleton_method(@method_name, stub_method)
@hooked = true
end
def unhook!
raise "spy has not been hooked yet" unless hooked?
@object.define_singleton_method(@method_name, @original_method)
@hooked = false
end
private
def stub_method
this = self
proc { |*args| this.send(:process_call, *args) }
end
def process_call(*args)
record_call(args)
end
def record_call(args)
@calls << args
end
end
end
| true |
6086811ac944092d76f29d4f0fdf86f509d0d366 | Ruby | BuonOmo/brawlstats | /main.rb | UTF-8 | 666 | 2.765625 | 3 | [] | no_license | # frozen_string_literal: true
require "json"
require_relative "lib/brawl_api"
TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkaXNjb3JkX3VzZXJfaWQiOiIzMTk" \
"zMjMwOTcxNjM0OTc0NzIiLCJyZWFzb24iOiJQZXJzb25uYWwiLCJ2ZXJzaW9uIjoxLCJ" \
"pYXQiOjE1NjkwODc0NTh9.UNR49QnwwHcFA85vyDwGYrE_9cD4VsAbzNvIUxK_gXE"
brawlAPI = BrawlAPI.new(TOKEN)
battles = brawlAPI.battles("9GC8JLRUV")["items"]
first, last = battles.minmax_by { |battle| battle["battleTime"] }
previous_last = IO.read(".last") rescue nil
File.open("battles", "a") do |file|
battles.select { |battle| previous_last.nil? || battle["battleTime"] > previous_last }
.sort_by { |battle| battle["battleTime"] }
.each { |battle| file.puts JSON.dump(battle) }
.tap { |ary| puts "Inserted #{ary.length} battles" }
end
IO.write(".last", last["battleTime"])
| true |
b8c61097d08b42a426689b37efa58076ff3d1db1 | Ruby | danbernier/zombie_scout | /lib/zombie_scout/flog_scorer.rb | UTF-8 | 577 | 2.828125 | 3 | [
"Apache-2.0"
] | permissive | require 'flog'
module ZombieScout
class FlogScorer
def initialize(zombie, flog=nil)
@zombie = zombie
@flog = flog || Flog.new(methode: true, quiet: true, score: false)
end
def score
raw_score.round(1)
end
private
attr_reader :flog
def raw_score
all_scores = flog.flog(zombie_path)
# default to {} in case there is no score. (it's a 0)
scores = all_scores.fetch(@zombie.full_name, {})
flog.score_method(scores)
end
def zombie_path
@zombie.location.sub(/\:\d+$/, '')
end
end
end
| true |
1aa3773dd6797092b7c71f9239d50461044f7a48 | Ruby | atduskgreg/slipcover | /lib/slipcover.rb | UTF-8 | 849 | 3.046875 | 3 | [] | no_license | class Slipcover
attr_accessor :silenced_errors, :members
def initialize(members)
@members = Array(members)
@silenced_errors = []
end
def add_member member
@members << member
end
def remove_member(member=nil, &block)
@members.delete(member) if member
@members.reject!{ |m| block.call(m) } if block_given?
end
def method_missing(method, *args, &block)
results = []
threads = []
@members.each do |m|
threads << Thread.new(m) do |member|
begin
results << member.send(method, *args)
rescue Exception => e
raise e unless silenced_errors_include? e
end
end
end
threads.each{|t| t.join}
results
end
private
def silenced_errors_include? e
@silenced_errors.any?{|eklass| e.is_a? eklass}
end
end
| true |
f77e9209fab844606f88c79052cf0da2fbc60e09 | Ruby | rubygitflow/thinknetica_ruby | /first_lesson/idial_weight.rb | UTF-8 | 712 | 4 | 4 | [] | no_license | load 'ex_routines.rb'
def result(name, height)
weight = ((height - 110) * 1.15).round(1)
if weight < 0.0
puts "#{name}. Ваш вес уже идеальный"
else
puts "#{name}. Ваш вес: #{weight}"
end
end
def dialogue(name)
print 'Ваш рост в сантиметрах: '
height = gets.chomp
if check_exit(height)
puts "Bye-bye, #{name}!"
else
height = height.to_i
if check_input(height, 1)
result(name, height)
else
dialogue(name)
end
end
end
def main
print 'Ваше имя: '
name = gets.chomp!.capitalize
if check_exit(name)
puts 'Bye-bye!'
elsif check_input(name, 0)
dialogue(name)
else
main
end
end
main
| true |
55bec626a05f5277fdceeb57c2c5aeb6232afb19 | Ruby | Aaron-McD/connect-four | /lib/game.rb | UTF-8 | 4,357 | 3.765625 | 4 | [] | no_license | require_relative "board.rb"
class Game
attr_reader :board, :winner
def initialize(symbol1, symbol2)
@symbol1 = symbol1
@symbol2 = symbol2
@board = Board.new
@winner = nil
@previous_pos = []
@rounds = 0
@previous_player = nil
@current_player = @symbol1
end
def player_insert(sym, x_coor)
if self.board.insert(sym, x_coor)
i = 0
while self.board[i][x_coor] != sym
i += 1
end
@previous_pos = [i, x_coor]
return true
else
return false
end
end
def reset
self.board.reset
@winner = nil
@rounds = 0
end
def won?
if(@rounds < 7)
return false
else
if(four_horizontal? || four_verticle? || four_diagonal?)
@winner = @previous_player
return true
else
return false
end
end
end
def play_round
puts "It is #{@current_player == @symbol1 ? "player 1" : "player 2"}'s turn, please type in a slot number to drop your piece in: "
input = gets.chomp.to_i
until player_insert(@current_player, input)
puts "Please enter a valid location that is not full already: "
input = gets.chomp.to_i
end
@rounds += 1
@previous_player = @current_player
@current_player = @current_player == @symbol1 ? @symbol2 : @symbol1
end
def pretty_print
out_string = " 0 1 2 3 4 5 6 \n"
self.board.board.each do |array|
array.each do |item|
out_string += "| #{item == nil ? " " : item} "
end
out_string += "|\n"
end
return out_string
end
private
def four_horizontal?
amount = 1
x = @previous_pos[1]
y = @previous_pos[0]
while x < 6
x += 1
if self.board[y][x] == @previous_player
amount += 1
else
break
end
end
x = @previous_pos[1]
while x > 0
x -= 1
if self.board[y][x] == @previous_player
amount += 1
else
break
end
end
return amount >= 4
end
def four_verticle?
amount = 1
x = @previous_pos[1]
y = @previous_pos[0]
while y < 5
y += 1
if self.board[y][x] == @previous_player
amount += 1
else
break
end
end
y = @previous_pos[0]
while y > 0
y -= 1
if self.board[y][x] == @previous_player
amount += 1
else
break
end
end
return amount >= 4
end
def four_diagonal?
amount_left_to_right = 1
amount_right_to_left = 1
x = @previous_pos[1]
y = @previous_pos[0]
while x < 6 && y > 0
x += 1
y -= 1
if self.board[y][x] == @previous_player
amount_left_to_right += 1
else
break
end
end
x = @previous_pos[1]
y = @previous_pos[0]
while x > 0 && y < 5
x -= 1
y += 1
if self.board[y][x] == @previous_player
amount_left_to_right += 1
else
break
end
end
x = @previous_pos[1]
y = @previous_pos[0]
while x < 6 && y < 5
x += 1
y += 1
if self.board[y][x] == @previous_player
amount_right_to_left += 1
else
break
end
end
x = @previous_pos[1]
y = @previous_pos[0]
while x > 0 && y > 0
x -= 1
y -= 1
if self.board[y][x] == @previous_player
amount_right_to_left += 1
else
break
end
end
if amount_left_to_right >= 4
return true
elsif amount_right_to_left >= 4
return true
else
return false
end
end
end | true |
b4845da326bbd7df483b242bceb38b42e27cdd45 | Ruby | alabamaair/thinknetica | /Lesson2/2.rb | UTF-8 | 70 | 3.265625 | 3 | [] | no_license | array = []
i = 10
while i <= 100
array << i
i += 5
end
puts array | true |
6253fd86361cf66c22e1e0ce7d8017004b0125d1 | Ruby | lmaths/RailsApi---APS | /app/models/skill.rb | UTF-8 | 718 | 2.71875 | 3 | [] | no_license | class Skill < ApplicationRecord
belongs_to :character
validates :name, presence: true
validates_inclusion_of :ability, in: [ "strength","dexterity", "constitution","intelligence","wisdom" ,"charisma"], presence: true
def get_atributo
if Character.column_names.include?self.ability
self.ability
end
end
def set_modificador
valor = character.read_attribute(get_atributo)
ability = 1
modificador = -5
while ability < valor
modificador += 1
ability += 2
end
modificador
end
def score
if self.proficient
return modificador + character.proficient_bonus
else
set_modificador
end
end
end
| true |
a1b26a185fe0f0523714ed33ef553d53c6c77517 | Ruby | louispellerin/afloat-budget | /budget/test/unit/period_test.rb | UTF-8 | 2,066 | 2.75 | 3 | [] | no_license | require 'test_helper'
class PeriodTest < ActiveSupport::TestCase
test "the transactions sum is correctly calculated" do
period = Period.new(:start_date => Date.today, :end_date => Date.today)
period.transactions.build(:description => "description", :date => Date.today, :amount => BigDecimal("30"))
period.transactions.build(:description => "description", :date => Date.today, :amount => BigDecimal("20"))
assert period.save
assert_equal 2, period.transactions.count
assert_equal BigDecimal("50"), period.total_transactions
end
test "last date is correctly calculated" do
base_date = @january.start_date - 7
last_date = @january.get_last_date(base_date, 1)
assert_equal @january.start_date, last_date
end
test "the next date is calculated according to frequency" do
date = Date.today
period = Period.new(:start_date => date, :end_date => date)
assert period.save
assert_equal date + 7, period.get_next_date(date, 1)
assert_equal date + 14, period.get_next_date(date, 2)
assert_equal date >> 1, period.get_next_date(date, 3)
assert_equal date, period.get_next_date(date, 4)
end
test "the next working day is correctly calculated" do
today = Date.today
sunday = today - today.wday
saturday = sunday - 1
monday = sunday + 1
tuesday = sunday + 2
wednesday = sunday + 3
thursday = sunday + 4
friday = sunday + 5
period = Period.new(:start_date => today, :end_date => today)
assert period.save
assert_equal monday, period.get_next_working_day(saturday)
assert_equal monday, period.get_next_working_day(sunday)
assert_equal monday, period.get_next_working_day(monday)
assert_equal tuesday, period.get_next_working_day(tuesday)
assert_equal wednesday, period.get_next_working_day(wednesday)
assert_equal thursday, period.get_next_working_day(thursday)
assert_equal friday, period.get_next_working_day(friday)
end
test "the period is populated with recurring transactions" do
@january.append_recurring_transactions
assert @january.save
assert_equal 6, @january.transactions.count
end
end
| true |
67306a7c3790632f1fd9911cef18869880073dcb | Ruby | edpaget/mini_tarball | /lib/mini_tarball/header_writer.rb | UTF-8 | 2,189 | 2.734375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module MiniTarball
class HeaderWriter
def initialize(io)
@io = io
end
def write(header)
write_long_name_header(header) if has_long_name?(header)
@io.write(to_binary(header))
end
private
def to_binary(header)
values_by_field = {}
Header::FIELDS.each do |name, field|
value = values_by_field[name] = header.value_of(name)
case field[:type]
when :number
values_by_field[name] = HeaderFormatter.format_number(value, field[:length])
when :mode
values_by_field[name] = HeaderFormatter.format_permissions(value, field[:length])
when :checksum
values_by_field[name] = " " * field[:length]
end
end
update_checksum(values_by_field)
add_padding(encode(values_by_field.values))
end
def update_checksum(values_by_field)
checksum = encode(values_by_field.values).unpack("C*").sum
values_by_field[:checksum] = format_checksum(checksum)
end
def format_checksum(checksum)
length = Header::FIELDS[:checksum][:length] - 1
HeaderFormatter.format_number(checksum, length) << "\0 "
end
def encode(values)
@pack_format ||= Header::FIELDS.values
.map { |field| "a#{field[:length]}" }
.join("")
values.pack(@pack_format)
end
def add_padding(binary)
padding_length = (Header::BLOCK_SIZE - binary.length) % Header::BLOCK_SIZE
binary << "\0" * padding_length
end
def has_long_name?(header)
header.value_of(:name).bytesize > Header::FIELDS[:name][:length]
end
def write_long_name_header(header)
name = header.value_of(:name)
private_header = long_link_header(name, Header::TYPE_LONG_LINK)
data = [header.value_of(:name)].pack("Z*")
@io.write(to_binary(private_header))
@io.write(add_padding(data))
end
def long_link_header(name, type)
Header.new(
name: "././@LongLink",
mode: 0644,
uid: 0,
gid: 0,
size: name.bytesize + 1,
typeflag: type,
uname: "root",
gname: "root"
)
end
end
end
| true |
603137207a73644e30b5f1f4fe13bfdd507d1919 | Ruby | ketan/dmon | /lib/dmon/proc_or_object.rb | UTF-8 | 956 | 2.890625 | 3 | [
"MIT"
] | permissive | # Copyright (c) 2011 Ketan Padegaonkar.
# Licenced under the MIT License (http://www.opensource.org/licenses/mit-license.php)
module Dmon
# Use in place of +attr_accessor+ that can use return values of procs
# class Person
# include Dmon::ProcOrObject
# proc_or_object :name
# end
#
# p = Person.new
# p.name = { 'joe' }
# p.name
# => joe
module ProcOrObject
module ClassMethods #nodoc:
#
def proc_or_object(*names)
names.each do |name|
class_eval(<<-EOS, __FILE__, __LINE__)
@@__#{name} = nil
def #{name}
@@__#{name}.respond_to?(:call) ? @@__#{name}.call : @@__#{name}
end
def #{name}=(value_or_proc)
@@__#{name} = value_or_proc
end
EOS
end
end
end
def self.included(receiver)
receiver.extend ClassMethods
end
end
end | true |
f4c8ae202b8521b76e95b9d3aac427201aa03add | Ruby | carlosjhr64/helpema | /test/tc_ssss | UTF-8 | 675 | 2.625 | 3 | [
"MIT"
] | permissive | #! ruby
require 'test/unit'
require 'helpema'
class TestSSSS < Test::Unit::TestCase
def test_ssss
pwds = Helpema::SSSS.split(secret: 'MyTopSecretPassphrase', threshold: 3, shares: 6)
assert_equal 6, pwds.length
secret1 = Helpema::SSSS.combine(secrets: pwds.shuffle, threshold: 3)
secret2 = Helpema::SSSS.combine(secrets: pwds.shuffle[0..2], threshold: 3)
assert_equal 'MyTopSecretPassphrase', secret1
assert_equal 'MyTopSecretPassphrase', secret2
error = assert_raises(RuntimeError) do
Helpema::SSSS.combine(secrets: pwds.shuffle[0..1], threshold: 3)
end
assert_equal 'Need threshold number of secrets.', error.message
end
end
| true |
a5dcb5a07855070f81b172613fc61a6915fd6786 | Ruby | cdsandoval/codeable-exercises-wk2 | /cat/cat.rb | UTF-8 | 278 | 2.875 | 3 | [] | no_license | require 'http'
require 'json'
# API text
response = HTTP.get('https://cat-fact.herokuapp.com/facts/random')
hash = JSON.parse(response)
puts hash["text"]
#API img
response_img = HTTP.get('https://aws.random.cat/meow')
hash_img = JSON.parse(response_img)
puts hash_img["file"]
| true |
c925e382d5c9204e3fc61a91e362cf3a639b4055 | Ruby | jweissman/vico | /lib/vico/cli.rb | UTF-8 | 2,196 | 2.828125 | 3 | [
"MIT"
] | permissive | require 'thor'
require 'vico'
module Vico
module Name
def self.generate!
adjs = %w[ wooly wild weird wonderful wannabe weeping whataboutist waxy wheeling warlike ]
nouns = %w[ wallaby walrus warthog whale wasp narwhal wildebeest wondertron willow winterbear ]
[ adjs.sample, nouns.sample ].join('_')
end
end
class CLI < Thor
desc "hello NAME", "say hello to NAME"
def hello(name)
puts "Hello #{name}"
end
desc "world NAME", "start world NAME"
def world(name='omnia')
puts "SERVE WORLD #{name}"
# TODO same check for city...
if World.where(name: name).any?
world = World.where(name: name).first
else
world = World.new(name: name)
world.save
map = SpaceMap.new(width: 50, height: 20) #, space: world)
map.generate!
map.save
world.space_map = map
map.save
end
# binding.pry
server = Server.new(space: world)
server.listen!
end
desc "city NAME", "start city NAME"
def city(name='aeternitas')
puts "SERVE CITY #{name}"
if City.where(name: name).any?
city = City.where(name: name).first
else
city = City.new(name: name)
city.save
map = SpaceMap.new(width: 120, height: 80)
map.generate!
map.save
city.space_map = map
map.save
end
server = Server.new(space: city, register: true, port: 7070)
server.listen!
end
# desc "zone ADDRESS", "start zone with ADDRESS"
# def zone(address)
# puts "SERVE ZONE #{address}"
# ZoneServer.new(address: adress)
# end
# plaintext, line-oriented
# console/cli/os
# core of uniscript
desc "text", "connect to world over text interface"
def text
puts "---> Launch text interface to world!"
text_client = Text.new
# text_client.connect!
text_client.engage!
end
desc "screen", "connect to world over screen interface"
def screen
puts "---> Launch screen interface to world!"
screen_client = Screen::Engine.new
# screen_client.connect!
screen_client.engage!
end
end
end
| true |
59f716a23dbcb14b5fed3f035fc36d7312c66ac1 | Ruby | georgeredinger/CoffeeStatus | /get_current.rb | UTF-8 | 411 | 2.828125 | 3 | [] | no_license | require "serialport"
port_str = "/dev/ttyUSB0"
baud_rate = 9600
data_bits = 8
stop_bits = 1
parity = SerialPort::NONE
sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity)
series=[]
done=false
until done
currents=sp.gets
unless currents.nil?
a,b = currents.split
if a == b
puts "#{Time.now.to_i} #{a.to_f}"
done=true
end
end
end
sp.close
| true |
d14d42493c7712e75f77390515fc2005dc60ed32 | Ruby | nathanworden/RB130-Ruby-Foundations-More-Topics | /04.Studying With Other Students/43.120319_juliette_siny.rb | UTF-8 | 3,126 | 4.46875 | 4 | [] | no_license | # Juliette gave me this problem she found on leetcode.
# She said it was a easy or medium level problem.
# Given a string, find the length of the longest substring without repeating characters.
# Example 1:
# Input: "abcabcbb"
# Output: 3
# Explanation: The answer is "abc", with the length of 3.
# Example 2:
# Input: "bbbbb"
# Output: 1
# Explanation: The answer is "b", with the length of 1.
# Example 3:
# Input: "pwwkew"
# Output: 3
# Explanation: The answer is "wke", with the length of 3.
# Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
# PEDAC
# Problem
# Find the length of the longest substring without repeating characters within a given string.
# Example
# Nathan is trying
# s trying
# Data Structure
# Array
# Strings
# Algorithm
# Given a String
# Convert to an Array
# For each letter in the string:
# Create a empty array
# Push letters into the array if the letter isn't already in there
# If it is, break and save the substring length.
# Return the max substring length
# Return the length of the longest chunk
# Code
# Add characters to substring until there is a duplicate character
# Save the length of the current substring
# Get the index the character that is curretnly in the the substring that matches the new character
# Git rid of all characters up to that index.
# Continue the process starting with the index
# require 'pry'
def length_of_longest_substring(str)
arr = str.chars
lengths = []
sub_str = []
arr.each do |letter|
if sub_str.include?(letter)
lengths << sub_str.length
idx = sub_str.index(letter)
sub_str = sub_str[idx + 1..-1]
end
sub_str << letter
end
lengths << sub_str.length
lengths.max
end
# def length_of_longest_substring(s)
# current = []
# longest = 0
# s.each_char do |char|
# if current.include?(char)
# longest = [longest, current.size].max
# index = current.index(char) + 1
# current = current[index..-1] # remove first letters until duplicate value
# end
# current << char
# end
# [longest, current.size].max
# end
p length_of_longest_substring('abcabcbb') #== 3 #'abc'
# p length_of_longest_substring('bbbbb') == 1 # 'b'
# p length_of_longest_substring('pwwkew') == 3 # 'wke'
# p length_of_longest_substring(' ') == 1
# p length_of_longest_substring('au') == 2
# p length_of_longest_substring('aab') == 2
# p length_of_longest_substring('Nathan is trying') == 8 # 's trying'
# Jamima Answer
# def longest_substring_length(string)
# string_length = string.length
# string_length.downto(1) do |substring_length|
# max = string_length - substring_length
# (0..max).each do |start|
# substring = string[start, substring_length]
# puts "substring_length: #{substring_length}"
# puts "start: #{start}"
# puts substring
# return substring_length if unique?(substring)
# end
# end
# end
# def unique?(string)
# string.chars.uniq.length == string.length
# end | true |
ff4eca87c9724b0c1960faf31f92642fe62b9efb | Ruby | darvs/advent-of-code | /2018/1805.rb/lib/1805.rb | UTF-8 | 712 | 2.984375 | 3 | [] | no_license | def parse(line, skip = nil)
head = []
tail = line.chars
until tail.empty?
if !skip.nil? && skip.casecmp?(tail[0])
tail.shift
elsif head.empty?
head = [tail.shift]
elsif head[-1].swapcase == tail[0]
head.pop
tail.shift
else
head.concat([tail.shift])
end
end
head.join
end
def exec_file(filename)
polymer = File.open(File.join('data', filename)).map(&:strip)
.reject(&:empty?).first
stable = parse(polymer)
filtering = %i[unit len result].zip(('a'..'z').map{|c|
result = parse(polymer, c)
[c, result.length, result]
}
.min_by{|_, len, _| len}).to_h
#puts "filtering #{filtering}"
[stable, filtering]
end
| true |
a919b02f4ff682aaaf2790881f4ecdee991a62f6 | Ruby | agc/aplicacionesrails | /tutorialruby/basico/ejcadena1_spec.rb | UTF-8 | 1,303 | 3.0625 | 3 | [] | no_license | require_relative "ejcadena1.rb"
require_relative 'spec/spec_helper'
#require File.expand_path("../ejcadena1.rb", __FILE__)
describe "Operaciones basicas con Strings" do
subject {"Hola mundo"}
its(:length) {should == 10}
it "Las cadenas se pueden concatenar" do
subject.should eq("Hola"+" mundo")
subject.should eq("Hola"<<" mundo")
end
it "Las cadenas se pueden multiplicar" do
producto="Hola"*3
producto.should =="HolaHolaHola"
end
it "Se puede insertar la salida de un comando shell" do
salida=`ruby --version`
salida.should match(/ruby 1.9.3/)
end
it "Se puede realizar string substitution" do
persona="Juan"
"Hola #{persona}".should eql "Hola Juan"
"La suma es #{2+2}".should match /4/
end
it "Las cadenas se pueden formatear" do
saludo ="Hola %s"
("Hola %s"%"Mundo").should =="Hola Mundo"
("%s %s"%["Hola","Mundo"]).should =="Hola Mundo"
end
it "Se puede evaluar una cadena" do
suma = eval "sumando=3;2+sumando"
suma.should == 5
end
it "debe decir 'Hola Mundo' cuando recibe el mensaje saludo() " do
ejemplo1 = EjCadena1.new
saludo = ejemplo1.saludo
saludo.should == "Hola mundo"
end
end | true |
e41550ee05f44d9aa4ead133c5dfd266484c6720 | Ruby | njonsson/cape | /lib/cape/dsl.rb | UTF-8 | 7,824 | 3.09375 | 3 | [
"MIT"
] | permissive | require 'cape/capistrano'
require 'cape/rake'
module Cape
# Provides methods for integrating Capistrano and Rake.
module DSL
# Enumerates Rake tasks.
#
# @param [String, Symbol] task_expression the full name of a task or
# namespace to filter
# @param [Proc] block a block that processes tasks
#
# @yield [task] a block that processes tasks
# @yieldparam [Hash] task metadata on a task
#
# @return [DSL] the object
#
# @example Enumerating all Rake tasks
# # config/deploy.rb
#
# require 'cape'
#
# Cape do
# each_rake_task do |t|
# # Do something interesting with this hash:
# # * t[:name] -- the full name of the task
# # * t[:parameters] -- the names of task arguments
# # * t[:description] -- documentation on the task, including
# # parameters
# end
# end
#
# @example Enumerating some Rake tasks
# # config/deploy.rb
#
# require 'cape'
#
# Cape do
# each_rake_task :foo do |t|
# # Do something interesting with this hash:
# # * t[:name] -- the full name of the task
# # * t[:parameters] -- the names of task arguments
# # * t[:description] -- documentation on the task, including
# # parameters
# end
# end
def each_rake_task(task_expression=nil, &block)
rake.each_task(task_expression, &block)
self
end
# The command used to run Rake on the local computer.
#
# @return [String] the command used to run Rake on the local computer
#
# @see Rake::DEFAULT_EXECUTABLE
def local_rake_executable
rake.local_executable
end
# Sets the command used to run Rake on the local computer.
#
# @param [String] value the command used to run Rake on the local computer
#
# @return [String] _value_
#
# @example Changing the local Rake executable
# require 'cape'
#
# Cape do
# self.local_rake_executable = '/path/to/rake'
# $stdout.puts 'We changed the local Rake executable to ' +
# "#{local_rake_executable.inspect}."
# end
def local_rake_executable=(value)
rake.local_executable = value
end
# Makes the use of a Cape block parameter optional by forwarding non-Cape
# method calls to the containing binding.
#
# @param [Symbol, String] method the method called
# @param [Array] args the arguments passed to _method_
# @param [Proc] block the block passed to _method_
#
# @return the result of the forwarded method call
def method_missing(method, *args, &block)
@outer_self.send(method, *args, &block)
end
# Defines Rake tasks as Capistrano recipes.
#
# @param [String, Symbol] task_expression the full name of a Rake task or
# namespace to filter
#
# @yield [recipes] a block that customizes the Capistrano recipe(s)
# generated for the Rake task(s); optional
# @yieldparam [RecipeDefinition] recipes an interface for customizing the
# Capistrano recipe(s) generated for
# the Rake task(s)
#
# @return [DSL] the object
#
# @note Any parameters that the Rake tasks have are integrated via environment variables, since Capistrano does not support recipe parameters per se.
#
# @example Mirroring all Rake tasks
# # config/deploy.rb
#
# require 'cape'
#
# Cape do
# # Create Capistrano recipes for all Rake tasks.
# mirror_rake_tasks
# end
#
# @example Mirroring some Rake tasks, but not others
# # config/deploy.rb
#
# require 'cape'
#
# Cape do
# # Create Capistrano recipes for the Rake task 'foo' and/or for the
# # tasks in the 'foo' namespace.
# mirror_rake_tasks :foo
# end
#
# @example Mirroring Rake tasks that require renaming, Capistrano recipe options, path switching, and/or environment variables
# # config/deploy.rb
#
# require 'cape'
#
# Cape do
# # Display defined Rails routes on application server remote machines
# # only.
# mirror_rake_tasks :routes do |recipes|
# recipes.options[:roles] = :app
# end
#
# # Execute database migration on application server remote machines
# # only, and set the 'RAILS_ENV' environment variable to the value of
# # the Capistrano variable 'rails_env'.
# mirror_rake_tasks 'db:migrate' do |recipes|
# recipes.options[:roles] = :app
# recipes.env['RAILS_ENV'] = lambda { rails_env }
# end
#
# # Support a Rake task that must be run on application server remote
# # machines only, and in the remote directory 'release_path' instead of
# # the default, 'current_path'.
# before 'deploy:symlink', :spec
# mirror_rake_tasks :spec do |recipes|
# recipes.cd { release_path }
# recipes.options[:roles] = :app
# end
#
# # Avoid collisions with the existing Ruby method #test, run tests on
# # application server remote machines only, and set the 'RAILS_ENV'
# # environment variable to the value of the Capistrano variable
# # 'rails_env'.
# mirror_rake_tasks :test do |recipes|
# recipes.rename do |rake_task_name|
# "#{rake_task_name}_task"
# end
# recipes.options[:roles] = :app
# recipes.env['RAILS_ENV'] = lambda { rails_env }
# end
# end
#
# @example Mirroring Rake tasks into a Capistrano namespace
# # config/deploy.rb
#
# require 'cape'
#
# namespace :rake_tasks do
# Cape do |cape|
# cape.mirror_rake_tasks
# end
# end
def mirror_rake_tasks(task_expression=nil, &block)
rake.each_task task_expression do |t|
deployment_library.define_rake_wrapper(t, :binding => binding, &block)
end
self
end
# The command used to run Rake on remote computers.
#
# @return [String] the command used to run Rake on remote computers
#
# @see Rake::DEFAULT_EXECUTABLE
def remote_rake_executable
rake.remote_executable
end
# Sets the command used to run Rake on remote computers.
#
# @param [String] value the command used to run Rake on remote computers
#
# @return [String] _value_
#
# @example Changing the remote Rake executable
# require 'cape'
#
# Cape do
# self.remote_rake_executable = '/path/to/rake'
# $stdout.puts 'We changed the remote Rake executable to ' +
# "#{remote_rake_executable.inspect}."
# end
def remote_rake_executable=(value)
rake.remote_executable = value
end
protected
# Returns an abstraction of the Rake installation and available tasks.
def rake
@rake ||= new_rake
end
private
def deployment_library
return @deployment_library if @deployment_library
raise_unless_capistrano
@deployment_library = new_capistrano(:rake => rake)
end
def new_capistrano(*arguments)
Capistrano.new(*arguments)
end
def new_rake(*arguments)
Rake.new(*arguments)
end
def raise_unless_capistrano
if @outer_self.method(:task).owner.name !~ /^Capistrano::/
raise 'Use this in the context of Capistrano recipes'
end
end
end
end
| true |
087169f12c4e5bc787e52897e2ec2256268ff58f | Ruby | sergii/daily-ruby-tips | /130/struct_values_as_hash.rb | UTF-8 | 794 | 4.15625 | 4 | [] | no_license | # Class Struct includes enumerable so we get a little more than a normal Class.
# Today's example shows the output of our attributes
Course = Struct.new(:name, :student_ids)
@struct = Course.new("Eastern Art History", [23, 456, 2342, 221, 3, 45, 987])
@struct.each_pair { |name, value| p("#{name} => #{value}") }
#=> "name => Eastern Art History"
#=> "student_ids => [23, 456, 2342, 221, 3, 45, 987]"
p enum = @struct.each
#=> #<Enumerator: #<struct Course name="Eastern Art History", student_ids=[23, 456, 2342, 221, 3, 45, 987]>:each>
# Spit out the count of attributes
p "The Object has #{enum.count{|attr| attr if attr.is_a?(Array)}} Array(s)"
p "The Object has #{enum.count{|attr| attr if attr.is_a?(String)}} String(s)"
#=> "The Object has 1 Array(s)"
#=> "The Object has 1 String(s)"
| true |
06e02df503c72a81dfc0e191cff989bc41210f23 | Ruby | PiotrWald/Sinatra | /hangman.rb | UTF-8 | 2,398 | 3.171875 | 3 | [] | no_license | require 'sinatra'
require "sinatra/reloader" if development?
require 'sass'
require 'set'
get('/styles.css'){scss :styles}
#Caesar class used to encode a string
@@ciphered = ""
class Caesar
def encode_string(my_string, shift_value)
shift_value %= 26
for i in 0..my_string.size-1 do
if my_string[i].ord > 122 or my_string[i].ord < 97
next
end
check_value = my_string[i].ord + shift_value
if check_value > 122
check_value -= 26
elsif check_value < 97
check_value += 26
end
my_string[i] = check_value.chr
end
return my_string
end
end
x = Caesar.new
#Initializers for Hangman
words = ["obstruction", "manipulation", "indentation", "vibrant",
"redemtion", "hapiness", "smallpox", "strawberry"]
messages_failure = ["not like this", "try again", "you are doing it wrong"]
messages_success = ["keep it up", "you are getting there", "good job"]
my_word = words[rand(8)]
guessed_letters = Set.new
@@counter = 0
@@message = "guess the word!"
get '/' do
haml "index.html".to_sym, :layout => "layout.html".to_sym
end
## Caesar ##
get '/caesar' do
to_cipher = params['to_cipher']
shift_value = params['shift_value'].to_i
if not to_cipher.nil?
@@ciphered = x.encode_string(to_cipher,shift_value)
end
haml "caesar.html".to_sym, :layout => "layout.html".to_sym
end
## Hangman ##
get '/hangman' do
if params['reset'] == "reset"
@@counter = 0
guessed_letters = Set.new
my_word = words[rand(8)]
@message = "guess the word!"
end
#Check if the letter has allready been used
success = false
@@my_word_display = ""
guess = params['guess']
new_word = params['new_word']
if not guess.nil? and @@counter < 9
for i_idx in 0..my_word.size-1
if my_word[i_idx] == guess and not guessed_letters.include?(guess)
success = true
end
end
if success
@@message = messages_success[rand(3)]
guessed_letters.add(guess)
else
@@message = messages_failure[rand(3)]
@@counter += 1
end
end
#Creation of a word with missing spaces for player to see
for i_idx in 0..my_word.size-1
if guessed_letters.include?(my_word[i_idx])
@@my_word_display += my_word[i_idx]
else
@@my_word_display += "_"
end
end
if @@counter == 9
@@message = "You are hanged!"
@@my_word_display = my_word
end
@@current_stage_image = @@counter.to_s + ".jpg"
haml "hangman.html".to_sym, :layout => "layout.html".to_sym
end
| true |
0c1c73a99f2c3c38e545cdc51c59ee9783cab1fd | Ruby | weicool/weitracer | /shape.rb | UTF-8 | 1,252 | 3.234375 | 3 | [] | no_license | require 'utilities'
require 'ray'
class Shape
attr_reader :brdf
def initialize(brdf, transform)
@brdf = brdf
@transform = transform
end
def intersect(ray)
nil
end
end
class Sphere < Shape
def initialize(center, radius, brdf, transform)
super(brdf, transform)
@center = center
@radius = radius
end
def intersect(ray)
e = ray.point
d = ray.direction
c = @center
k = e - c
discriminant = (d.dot(k)**2) - (d.dot(d)*(k.dot(k) - @radius**2))
return nil if discriminant <= 0
t1 = ((-d.dot(k) + Math.sqrt(discriminant)) / d.dot(d))
t2 = ((-d.dot(k) - Math.sqrt(discriminant)) / d.dot(d))
t_hit = -1.0
if (t1 >= ray.t_min && t1 <= ray.t_max) || (t2 >= ray.t_min && t2 <= ray.t_max)
t_hit = [t1, t2].min
t_hit = [t1, t2].max if t_hit < ray.t_min || t_hit > ray.t_max
else
return nil
end
intercept_point = e + d*t_hit
normal = (intercept_point - c).normalize
Intersection.new(self, intercept_point, normal, t_hit)
end
end
class ShapeList < Array
def intersect(ray)
intersects = self.map{|shape| shape.intersect(ray)}.select{|intersect| intersect}
intersects.min{|int_a, int_b| int_a.t_hit <=> int_b.t_hit}
end
end
| true |
b1999ad235b8c828e34b7bfa1a35880a26e18d48 | Ruby | designedbyscience/Pinboard.in-Adium-Script | /pinboardurl.rb | UTF-8 | 1,104 | 2.59375 | 3 | [] | no_license | #!/usr/bin/ruby
require 'rubygems'
require 'net/http'
require 'net/https'
require 'uri'
require 'cgi'
require 'nokogiri'
require 'open-uri'
#sender found at ARGV[0]
#message found at STDIN
#Pull out url
message = STDIN.read.strip
foundurl = URI.extract(message)[0]
if foundurl
#Get page title
page = Nokogiri::HTML(open(foundurl))
title = page.css('title')[0].content
#Post to pinboard
uri = URI.parse("https://api.pinboard.in/v1/posts/add")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
querystring = "?"
query = {'url' => foundurl,
'description' => title,
"tags" => 'im ' + ARGV[0].gsub(/\s/, "")
}.each_pair do |key, value|
querystring += key + "=" + CGI.escape(value) + "&"
end
request = Net::HTTP::Get.new(uri.request_uri + querystring)
request.basic_auth("pinboarduser","pinboardpass")
response = http.request(request)
end | true |
754652528c8e2bc0776c24c3c2c65ad56e70efbf | Ruby | ocpsoft/rewrite | /transform-markup/src/main/resources/ruby/sass/lib/sass/tree/supports_node.rb | UTF-8 | 1,212 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | module Sass::Tree
# A static node representing a `@supports` rule.
# `@supports` rules behave differently from other directives
# in that when they're nested within rules,
# they bubble up to top-level.
#
# @see Sass::Tree
class SupportsNode < DirectiveNode
# The name, which may include a browser prefix.
#
# @return [String]
attr_accessor :name
# The supports condition.
#
# @return [Sass::Supports::Condition]
attr_accessor :condition
# @see RuleNode#tabs
attr_accessor :tabs
# @see RuleNode#group_end
attr_accessor :group_end
# @param condition [Sass::Supports::Condition] See \{#condition}
def initialize(name, condition)
@name = name
@condition = condition
@tabs = 0
super('')
end
# @see DirectiveNode#value
def value; raise NotImplementedError; end
# @see DirectiveNode#resolved_value
def resolved_value
@resolved_value ||= "@#{name} #{condition.to_css}"
end
# True when the directive has no visible children.
#
# @return [Boolean]
def invisible?
children.all? {|c| c.invisible?}
end
# @see Node#bubbles?
def bubbles?; true; end
end
end
| true |
a4741515e07b9610a1c478b673502a3f0d27bae1 | Ruby | ashishvalu/ruby-1 | /exer1/shop_order.rb | UTF-8 | 2,466 | 3.625 | 4 | [] | no_license | class Order
def initialize
@order ={}
end
def new_order
print "Enter your order:" #date and amount
order = gets.chomp
# date & amount lakhva order ne split karvu pade
date,amount = order.split(' ')
day,month,year = date.split('-')
if @order[year].nil?
@order[year] = {}
end
if @order[year][month].nil?
@order[year][month] = {}
end
if @order[year][month][day].nil?
@order[year][month][day] =[]
end
@order[year][month][day] << amount.to_i
end
def day_order
print "Enter your date:"
date = gets.chomp
day, month,year = date.split('-')
orders = @order.dig(year, month, day)
orders = [] if orders.nil?
puts "Orders Details"
puts "-----------------"
puts "Total Order: #{orders.size}"
puts "Total Amount: #{orders.sum}"
puts "Minimum Order: #{orders.min}"
puts "Maximum Order: #{orders.max}"
avg = orders.size > 0 ? orders.sum / orders.size : 0
puts "Average Order: #{avg}"
puts "**********************"
end
def month_order
print "Entrr your month & year:"
month =gets.chomp
month,year = month.split('-')
orders =[]
if @order[year] && @order[year][month]
@order[year][month].each do |day,value|
orders += value
end
orders =@order[year][month].values.flatten
end
puts "Orders Details"
puts "-----------------"
puts "Total Order: #{orders.size}"
puts "Total Amount: #{orders.sum}"
puts "Minimum Order: #{orders.min}"
puts "Maximum Order: #{orders.max}"
avg = orders.size > 0 ? orders.sum / orders.size : 0
puts "Average Order: #{avg}"
puts "-----------------------"
end
def input
puts "----------------------"
puts " Welcome to My Shop "
puts "----------------------"
loop do
puts "1 Create New Order" #navo order leva mate type 1
puts "2 Print Day Details" #dates (days) Details print karva = total order,total amount,max order,min order,avg order
puts "3 Print Month Details" # month Details print karva = total order,total amount,max order,min order,avg order
puts "How may I help you?(1, 2, 3 or quit)"
condition = gets.chomp.to_i
case condition
when 1
new_order
when 2
day_order
when 3
month_order
end
if condition < 1 || condition > 3
break
end
end
end
end
shop = Order.new
shop.input
| true |
a7e9b40a0f4b2459dec880dc6ffa7b789ac31c4d | Ruby | kinsbrunner/interview-cake-ruby | /10-second-largest-in-bst/spec/binary_tree_node_spec.rb | UTF-8 | 1,232 | 2.859375 | 3 | [] | no_license | require 'spec_helper'
RSpec.describe BinaryTreeNode, type: :model do
describe "#get_second_largest method" do
let(:btree1){
root = BinaryTreeNode.new(5)
second_level_a = root.insert_left(3)
second_level_b = root.insert_right(8)
third_level_a = second_level_a.insert_left(1)
third_level_b = second_level_a.insert_right(4)
third_level_c = second_level_b.insert_left(7)
third_level_d = second_level_b.insert_right(9)
return root
}
let(:btree2){
root = BinaryTreeNode.new(5)
second_level_a = root.insert_left(3)
second_level_b = root.insert_right(8)
third_level_a = second_level_a.insert_left(1)
third_level_b = second_level_a.insert_right(4)
third_level_c = second_level_b.insert_left(7)
third_level_d = second_level_b.insert_right(12)
forth_level_a = third_level_d.insert_left(10)
fifth_level_a = forth_level_a.insert_left(9)
fifth_level_b = forth_level_a.insert_right(11)
return root
}
it "should return 8 as result" do
expect(btree1.get_second_largest).to eq 8
end
it "should return 11 as result" do
expect(btree2.get_second_largest).to eq 11
end
end
end | true |
40c6e38d12023c85893543b645c8eaf626cae368 | Ruby | TommyTeaVee/critter4us | /test/end-to-end/taking-out-of-service-tests.rb | UTF-8 | 2,359 | 2.515625 | 3 | [] | no_license | require './test/testutil/requires'
require 'capybara'
class TakingOutOfServiceTestCase < EndToEndTestCase
def setup
super
Procedure.random(:name => 'venipuncture')
Procedure.random(:name => 'physical', :days_delay => 3)
Animal.random(:name => 'veinie')
Animal.random(:name => 'bossie')
Animal.random(:name => 'staggers')
make_reservation('2010-12-12', %w{veinie staggers}, %w{venipuncture})
make_reservation('2009-01-01', %w{bossie}, %w{physical})
end
def get_animals_that_can_be_taken_out_of_service
get('/json/animals_that_can_be_taken_out_of_service',
:date => '2009-01-02')
assert_equal(['bossie'], unjsonify(last_response)['unused animals'])
end
def get_animals_with_pending_reservations
get('/animals_with_pending_reservations', :date => '2009-01-02')
assert_match(/staggers/, last_response.body)
assert_match(/veinie/, last_response.body)
assert_body_has_selector('a', :text => '2010-12-12')
end
def post_take_animals_out_of_service
post('/json/take_animals_out_of_service',
{:data => {
:animals => ['bossie'],
:date => '2009-06-06'
}.to_json})
end
def check_if_animal_in_service_before_out_of_service_date
get('/json/animals_and_procedures_blob',
:timeslice => encode_url_param({
:firstDate => '2009-02-02',
:lastDate => '2009-02-02',
:times => ['morning']
}))
assert_equal(["bossie", "staggers", "veinie"], unjsonify(last_response)['animals'])
end
def check_if_animal_out_of_service_afterwards
get('/json/animals_and_procedures_blob',
:timeslice => encode_url_param({
:firstDate => '2009-06-01',
:lastDate => '2009-06-06',
:times => ['morning', 'evening']
}))
assert_equal(["staggers", "veinie"], unjsonify(last_response)['animals'])
end
should "do end-to-end trip" do
get_animals_that_can_be_taken_out_of_service
get_animals_with_pending_reservations
post_take_animals_out_of_service
check_if_animal_in_service_before_out_of_service_date
check_if_animal_out_of_service_afterwards
end
end
| true |
01ad7dc3f2e9ebb7831cfec2b3431b1a7fda9232 | Ruby | theinterned/faq_engine | /test/unit/faq_test.rb | UTF-8 | 896 | 2.609375 | 3 | [] | no_license | require 'test/test_helper'
class FaqTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
test "faq should save wiht question and answer provided" do
faq = Faq.new(:question => "What?", :answer => "I don't know!")
assert faq.save
end
test "faq should not save without question" do
faq = Faq.new(:answer => "test answer")
assert !faq.save, "Saved the FAQ without a question"
end
test "faq should not save without answer" do
faq = Faq.new(:question => "test question")
assert !faq.save, "Saved the FAQ without a answer"
end
test "faq should save csv tag string as an array" do
faq = Faq.new(:question => "What?", :answer => "I don't know!", :tag_list => "Tag One, Tag Two, Tag Three")
assert_equal faq.tag_list, ["Tag One", "Tag Two", "Tag Three"]
assert faq.save
end
end | true |
86b339ad4c5b3a15a496881dcd54842879b5c931 | Ruby | davidhu2000/coursework | /w2d3/poker/lib/player.rb | UTF-8 | 1,239 | 3.640625 | 4 | [] | no_license | require_relative 'hand'
class Player
attr_reader :name, :hand, :folded
attr_accessor :chips
def initialize(name, chips)
@name = name
@hand = Hand.new
@chips = chips
@folded = false
end
def get_discard
# puts "Enter in the suit and card value that you want to discard: "
suit, value = $stdin.gets.chomp.split(/\s*,\s*/)
suit = suit.to_sym
value = value == 'a' ? value.to_sym : value.to_i
raise 'card not in hand' unless has_card?(suit, value)
[suit, value]
end
def discard_card
suit, value = get_discard
@hand.discard(suit, value)
end
def get_action
action = $stdin.gets.chomp
raise "Invalid Action" unless %w(f c r).include?(action[0])
action[0]
end
def do_action(bet)
action = get_action
if action == 'f'
@folded = true
elsif action == 'c'
@chips -= bet
else
# puts "Enter raised bet: "
player_raise = bet
until player_raise > bet
player_raise = $stdin.gets.chomp.to_i
end
@chips -= player_raise
return player_raise
end
nil
end
private
def has_card?(suit, value)
hand.cards.any? do |card|
card.value == value && card.suit == suit
end
end
end
| true |
8d0de1372e65c4e4270a29304cac0a0e413e5356 | Ruby | bstiber/launch_school_exercises | /small_problems/easy4/1.rb | UTF-8 | 1,317 | 4.84375 | 5 | [] | no_license | # Write a method that takes two strings as arguments, determines the longest of the two strings, and then
# returns the result of concatenating the shorter string, the longer string, and the shorter string once
# again. You may assume that the strings are of different lengths.
# using my method
def short_long_short(string1, string2)
if string1.length < string2.length
puts "#{string1}#{string2}#{string1}" # used puts so I could see what was printing out and returning.
else
puts "#{string2}#{string1}#{string2}"
end
end
# shortened way
def short_long_short(string1, string2)
return string1 + string2 + string1 if string1.length < string2.length
return string2 + string1 + string2
end
# solution, doesn't use strings in a puts statement
def short_long_short(string1, string2)
if string1.length < string2.length
string1 + string2 + string1
else
string2 + string1 + string2
end
end
# a shorter way using sort_by method and (first and last)
def short_long_short(array1, array2)
arr = [array1, array2].sort_by { |element| element.length }
arr.first + arr.last + arr.first
end
p short_long_short('abcde', 'fgh') == "fghabcdefgh"
p short_long_short('abc', 'defgh') == "abcdefghabc"
p short_long_short('abcde', 'fgh') == "fghabcdefgh"
p short_long_short('', 'xyz') == "xyz"
| true |
f5384d65a6a57abc57cbd02b367bec2173deda4a | Ruby | qwaszx102938/smaile-remember | /app/services/memory_service.rb | UTF-8 | 2,029 | 2.75 | 3 | [] | no_license | =begin
第一个记忆周期是 5分钟
第二个记忆周期是30分钟
第三个记忆周期是12小时
这三个记忆周期属于短期记忆的范畴。
下面是几个比较重要的周期。
第四个记忆周期是 1天
第五个记忆周期是 2天
第六个记忆周期是 4天
第七个记忆周期是 7天
第八个记忆周期是15天
=end
class MemoryService
#下一级间隔时间(秒)
@@alert_list=[
#0-1
5*60,
#1-2
25*60,
#2-3
11.5*60*60,
#3-4
12*60*60,
#4-5
24*60*60,
#5-6
2*24*60*60,
#6-7
3*24*60*60,
#7-8
8*24*60*60
]
def self.had_remembered alert_item
if alert_item
AlertItemHist.create remember_item: (alert_item.remember_item), user_id: (alert_item.user_id), state: 1, level: alert_item.level, alert_time: (alert_item.alert_time)
if alert_item.level<8
alert_item.alert_time=Time.now+@@alert_list[alert_item.level]
alert_item.level=alert_item.level+1
alert_item.state=0
alert_item.save
else
alert_item.delete
end
end
end
def self.get_remember remember_item
alert_item=AlertItem.find_by_remember_item_id remember_item
AlertItem.create remember_item: remember_item, user_id: (remember_item.user_id), state: 0, level: 1, alert_time: (Time.now+@@alert_list[0])
if alert_item
AlertItemHist.create remember_item: remember_item, user_id: (remember_item.user_id), state: 0, level: alert_item.level, alert_time: (alert_item.alert_time)
alert_item.delete
end
end
def self.miss_alert_item alert_item
if alert_item
AlertItemHist.create remember_item: (alert_item.remember_item), user_id: (alert_item.user_id), state: 2, level: alert_item, alert_time: (alert_item.alert_time)
alert_item.alert_time=Time.now+@@alert_list[alert_item.level-1]
alert_item.state=0
alert_item.save
end
end
end | true |
a77f916f56c144fcd0ceec3e71d0a1538a2c7109 | Ruby | Carriane/Image123 | /image.rb | UTF-8 | 259 | 3.46875 | 3 | [] | no_license | class Image
def initialize(row)
@row = row
end
def output_image
@row.each do |cell|
puts cell.join
end
end
end
image = Image.new([
[0, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]
])
image.output_image
| true |
9e601eb89ae597aa016055108ebf05f4ccbdc5c5 | Ruby | ursmartini/webserver-mock | /webserver.rb | UTF-8 | 1,747 | 2.625 | 3 | [
"MIT"
] | permissive | def add_headers(res, headers)
headers.each_pair { |key, val| res[key] = val }
res
end
def echo(req)
body = "#{req.request_line}\n"
req.raw_header.each { |header| body += "#{header.strip}\n" }
body += "\n#{req.body}"
body
end
require 'webrick'
if ENV['allow_http_verbs']
module WEBrick
module HTTPServlet
# Allowing server to respond to requests using custom HTTP verbs
class ProcHandler
ENV['allow_http_verbs'].split(',').each do |verb|
alias_method "do_#{verb}", 'do_GET'
end
end
end
end
end
if ENV['ssl']
require 'webrick/https'
opts = { Port: 443, SSLEnable: true, SSLCertName: [%w(CN localhost)] }
else
opts = { Port: 80 }
end
server = WEBrick::HTTPServer.new(opts)
predefined_responses = {
400 => '/bad-request',
401 => '/unauthorized',
403 => '/forbidden',
404 => '/not-found',
500 => '/internal-server-error',
502 => '/bad-gateway',
503 => '/service-unavailable',
504 => '/gateway-timeout'
}
predefined_responses.each_pair do |status, path|
server.mount_proc path do |_req, res|
res.status = status
end
end
if ENV['custom_responses_config']
require 'yaml'
custom_responses_config = YAML::load_file(ENV['custom_responses_config'])
custom_responses_config.each do |custom_response|
server.mount_proc custom_response['path'] do |req, res|
res = add_headers(res, custom_response['headers']) if custom_response['headers']
res.status = custom_response['status'] || 200
res.body = custom_response['body'] ? File.read(custom_response['body']) : echo(req)
end
end
else
# fallback to echo server
server.mount_proc '/' do |req, res|
res.status = 200
res.body = echo(req)
end
end
server.start
| true |
4d9add27d01410556a37f104d611426feeb70aeb | Ruby | lsamano/key-for-min-value-dumbo-web-121018 | /key_for_min.rb | UTF-8 | 378 | 3.484375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # prereqs: iterators, hashes, conditional logic
# Given a hash with numeric values, return the key for the smallest value
def key_for_min_value(name_hash)
current_minimum = nil
minimum_key = nil
name_hash.each do |name, value|
if current_minimum == nil || value < current_minimum
current_minimum = value
minimum_key = name
end
end
minimum_key
end
| true |
b8bde3592fcf9bed8f60c1cc8d5c681a870726a9 | Ruby | BaltimorePublicArtCommons/baltimore_public_art_commons | /app/models/importers/csv/image_creator.rb | UTF-8 | 1,260 | 2.5625 | 3 | [] | no_license | module Importers
class Csv::ImageCreator
def self.create_item_images_from_row(item, row, image_file_path)
return if image_file_path.nil?
self.new.create_item_images_from_row(item, row, image_file_path)
end
def create_item_images_from_row(item, row, image_file_path)
image = create_item_image_from_row(item, row, image_file_path)
create_image_version(image, row, image_file_path)
end
private
def create_item_image_from_row(item, row, image_file_path)
attrs = find_model_attrs_in_row('image', row)
return if attrs_are_blank?(attrs)
attrs['file'] = File.open("#{image_file_path}/#{attrs['file']}")
item.images.create!(attrs)
end
def create_image_version(image, row, image_file_path)
attrs = find_model_attrs_in_row('image_version', row)
return if attrs_are_blank?(attrs)
attrs['file'] = File.open("#{image_file_path}/#{attrs['file']}")
image.image_versions.create!(attrs)
end
def attrs_are_blank?(attrs)
attrs.all? { |k,v| v.nil? }
end
def find_model_attrs_in_row(model_name, row)
row.to_h.
select { |k,v| k =~ /\[#{model_name}\]/ }.
transform_keys { |k| k.gsub("[#{model_name}]", '') }
end
end
end
| true |
5045b8a4aac6319a445a48b7b6db42958bb6c7d1 | Ruby | NREL/OpenStudio-analysis-spreadsheet | /measures/LifeCycleCostReport/resources/os_lib_reporting_custom.rb | UTF-8 | 5,290 | 2.984375 | 3 | [] | no_license | require 'json'
module OsLib_Reporting
# setup - get model, sql, and setup web assets path
def self.setup(runner)
results = {}
results[:web_asset_path] = OpenStudio.getSharedResourcesPath / OpenStudio::Path.new('web_assets')
return results
end
# developer notes
# - Other thant the 'setup' section above this file should contain methods (def) that create sections and or tables.
# - Any method that has 'section' in the name will be assumed to define a report section and will automatically be
# added to the table of contents in the report.
# - Any section method should have a 'name_only' argument and should stop the method if this is false after the
# section is defined.
# - Generally methods that make tables should end with '_table' however this isn't critical. What is important is that
# it doesn't contain 'section' in the name if it doesn't return a section to the measure.
# - The data below would typically come from the model or simulation results, but can also come from elsewhere or be
# defeined in the method as was done with these examples.
# - You can loop through objects to make a table for each item of that type, such as air loops
# create template section
def self.life_cycle_cost_section(model, sqlFile, runner, name_only = false)
# array to hold tables
template_tables = []
# gather data for section
@template_section = {}
@template_section[:title] = 'LifeCycle Costs'
@template_section[:tables] = template_tables
# stop here if only name is requested this is used to populate display name for arguments
if name_only == true
return @template_section
end
array_header = ['Object','Object Type','Unit Type','Unit Cost','Total Cost','Frequency','Years From Start']
array_units = ['','','','','$','Years','Years']
# create table
template_table_01 = {}
template_table_01[:title] = 'Construction'
template_table_01[:header] = array_header
template_table_01[:units] = array_units
template_table_01[:data] = []
# create table
template_table_02 = {}
template_table_02[:title] = 'Maintainance'
template_table_02[:header] = array_header
template_table_02[:units] = array_units
template_table_02[:data] = []
# create table
template_table_03 = {}
template_table_03[:title] = 'Salvage'
template_table_03[:header] = array_header
template_table_03[:units] = array_units
template_table_03[:data] = []
# get lifecycle costs and add rows
model.getLifeCycleCosts.sort.each do |lifecycle_cost|
next if lifecycle_cost.totalCost == 0
if lifecycle_cost.costUnits == "CostPerArea"
neat_cost = "#{OpenStudio::toNeatString(OpenStudio::convert(lifecycle_cost.cost,"$/m^2","$/ft^2").get,2,true)} ($/ft^2)"
else
neat_cost = "#{OpenStudio::toNeatString(lifecycle_cost.cost,2,true)} ($)"
end
neat_total_cost = OpenStudio::toNeatString(lifecycle_cost.totalCost,2,true)
array_data = [lifecycle_cost.item.name,lifecycle_cost.itemType,lifecycle_cost.costUnits,neat_cost,neat_total_cost,lifecycle_cost.repeatPeriodYears,lifecycle_cost.yearsFromStart]
if lifecycle_cost.category == "Construction"
template_table_01[:data] << array_data
elsif lifecycle_cost.category == "Maintenance"
template_table_02[:data] << array_data
elsif lifecycle_cost.category == "Salvage"
template_table_03[:data] << array_data
else
runner.registerWarning("Unexpected LifeCycle Cost Catetory of #{lifecycle_cost.category}")
end
end
# add table to array of tables
template_tables << template_table_01
template_tables << template_table_02
template_tables << template_table_03
return @template_section
end
# create template section
def self.life_cycle_parameters_section(model, sqlFile, runner, name_only = false)
# array to hold tables
template_tables = []
# gather data for section
@template_section = {}
@template_section[:title] = 'LifeCycle Cost Parameters'
@template_section[:tables] = template_tables
# stop here if only name is requested this is used to populate display name for arguments
if name_only == true
return @template_section
end
# create table
template_table_01 = {}
template_table_01[:header] = ['Description','Value']
template_table_01[:data] = []
# get lifecycle cost parameters
lccp = model.getLifeCycleCostParameters
# populate table
template_table_01[:data] << ["Analysis Type",lccp.analysisType]
template_table_01[:data] << ["Discounting Convention",lccp.discountingConvention]
template_table_01[:data] << ["Inflation Approach",lccp.inflationApproach]
template_table_01[:data] << ["Length Of Study Period In Years",lccp.lengthOfStudyPeriodInYears]
template_table_01[:data] << ["Depreciation Method ",lccp.depreciationMethod ]
template_table_01[:data] << ["Use NIST Fuel Escalation Rates",lccp.useNISTFuelEscalationRates]
template_table_01[:data] << ["NIST Region",lccp.nistRegion ]
template_table_01[:data] << ["NIST Sector",lccp.nistSector]
# add table to array of tables
template_tables << template_table_01
return @template_section
end
end
| true |
165234817f4337cd83675fea2a6b44591c402d6b | Ruby | sul-dlss/stacks | /app/models/approved_location.rb | UTF-8 | 649 | 2.53125 | 3 | [] | no_license | # frozen_string_literal: true
###
# Simple class that will return an approved location (for restricted content)
# based on a provided locatable object's IP address
class ApprovedLocation
delegate :to_s, to: :location_for_ip
def initialize(locatable)
@locatable = locatable
end
def locations
return [] unless locatable.try(:ip_address)
location_configuration.select do |_, ip_addresses|
ip_addresses.include?(locatable.ip_address)
end.keys.map(&:to_s)
end
private
attr_reader :locatable
def location_for_ip
locations.first
end
def location_configuration
Settings.user.locations.to_h
end
end
| true |
239d705cf39b4e8fbf172c0a0e0f75aa9f0b6fa7 | Ruby | joeltio/proficiency | /src/proficiency/math/prime_checker/prime_checker.rb | UTF-8 | 256 | 3.75 | 4 | [
"MIT"
] | permissive | def prime_checker(n)
if n < 2
false
elsif n == 2
true
elsif n % 2 == 0
false
else
for i in (3..n).step(2)
if n % i == 0
return false
end
end
true
end
end
puts prime_checker(ARGV[0].to_i)
| true |
34b69b997700300ce20a01785d7df5df6f62558c | Ruby | abarnes1/ruby-exercises | /data-structures/linked-list/linked_list.rb | UTF-8 | 2,766 | 3.578125 | 4 | [] | no_license | require_relative 'node'
class LinkedList
attr_reader :head, :tail
def initialize
@head = nil
@tail = nil
@size = 0
end
def append(value)
if @head.nil?
@head = Node.new(value)
@tail = @head
else
new_tail = Node.new(value)
@tail.next_node = new_tail
@tail = new_tail
end
@size += 1
end
def prepend(value)
if @head.nil?
@head = Node.new(value)
@tail = @head
else
old_head = @head
@head = Node.new(value)
@head.next_node = old_head
end
@size += 1
end
def size
@size
end
def at(index)
return nil if @head.nil?
current_node = @head
counter = 0
until counter == index
return nil if current_node.next_node.nil?
current_node = current_node.next_node
counter += 1
end
return current_node
end
def pop
return nil if @tail.nil?
popped_node = @tail
@tail = at(@size - 2)
@tail.next_node = nil unless @tail.nil?
@size -= 1
if @size.zero?
@head = nil
@tail = nil
end
popped_node
end
def contains?(value)
node = @head
until node.nil?
return true if node.value == value
node = node.next_node
end
false
end
def find(value)
index = -1
node = @head
until node.nil?
index += 1 unless node.nil?
return index if node.value == value
node = node.next_node
end
nil
end
def insert_at(value, index)
return nil if index.negative? || index > @size
new_node = Node.new(value)
#traverses twice, could be once if done here
node_before = at(index - 1)
node_after = at(index)
if node_before.nil?
new_node.next_node = @head
@head = new_node
elsif node_after.nil?
node_before.next_node = new_node
@tail = new_node
else
node_before.next_node = new_node
new_node.next_node = node_after
end
puts "tail: #{@tail.value}"
@size += 1
new_node
end
def remove_at(index)
return nil if index.negative? || index > (@size - 1)
deleted_node = nil
#traverses twice, could be once if done here
node_before = at(index - 1)
node_after = at(index + 1)
if node_before.nil?
deleted_node = @head
@head = @head.next_node
elsif node_after.nil?
deleted_node = @tail
node_before.next_node = nil
@tail = node_before
else
deleted_node = node_before.next_node
node_before.next_node = node_after
end
@size -= 1
deleted_node
end
def to_s
return nil if @head.nil?
node = @head
output = ''
until node.nil?
output += "( #{node.value } ) -> "
node = node.next_node
end
output += 'nil'
end
end | true |
cad42f3ff733b8e5c8d81af3c52457590cb623e3 | Ruby | digibib/bokanbefalinger | /lib/api.rb | UTF-8 | 5,426 | 2.59375 | 3 | [] | no_license | # encoding: UTF-8
# -----------------------------------------------------------------------------
# api.rb - API abstraction
# -----------------------------------------------------------------------------
# The API module is responsible for fetching and pushing resources to the API.
# All methods yields to a block if unsucsessfull, so client must suply a block
# to handle failures.
# TODO refactor requests so that get/post/put/delete uses one request method,
# with one rescue etc
# TODO Make sure all connection errors are rescued (check Errno::xxx)
# TODO set request timeout! a few secounds
require "faraday"
module API
ENDPOINTS = {:reviews => Faraday.new(:url => Settings::API + "reviews"),
:works => Faraday.new(:url => Settings::API + "works"),
:sources => Faraday.new(:url => Settings::API + "sources"),
:users => Faraday.new(:url => Settings::API + "users"),
:authenticate => Faraday.new(:url => Settings::API + "users/authenticate"),
:mylists => Faraday.new(:url => Settings::API + "users/mylists")}
def self.log(msg)
puts msg # TODO use JBOSS logger
end
def self.get(endpoint, params, headers={})
# Perform GET request with parmas as query-params.
# It returns the parsed JSON result, or yields to a block with an error
# if the request failed.
resp = ENDPOINTS[endpoint].get do |req|
req.headers = headers.merge({"Content-Type" => "application/json"})
req.params = params
log "API REQUEST to #{ENDPOINTS[endpoint].url_prefix.path}: #{req.body}"
end
rescue Faraday::Error, Errno::ENOENT, Errno::ETIMEDOUT, Errno::ECONNREFUSED => err
log "API request to #{ENDPOINTS[endpoint].url_prefix.path} with params" +
" #{params} failed because: #{err.message}"
yield StandardError.new("Forespørsel til eksternt API(#{Settings::API})" +
" brukte for lang tid på å svare.")
else
log "API RESPONSE [#{resp.status}]"
if resp.body.match(/not found/) || resp.status != 200 #TODO match other bodies as well, remember string can also
# match review bodies, as 'error' did on astrid werner
yield StandardError.new("Finner ingen ressurs med denne ID-en:" +
" #{params[:uri] || params}.")
else
JSON.parse(resp.body)
end
end
def self.post(endpoint, params, headers={})
# Perform a POST request with parmas as JSON-encoded body.
# It returns the parsed JSON result, or yields to a block with an error
# if the request failed.
resp = ENDPOINTS[endpoint].post do |req|
req.headers = headers.merge({"Content-Type" => "application/json"})
req.body = params.to_json
log "API REQUEST to #{ENDPOINTS[endpoint].url_prefix.path}: #{req.body}"
end
rescue Faraday::Error, Errno::ETIMEDOUT => err
log "API request to #{ENDPOINTS[endpoint].url_prefix.path} with params" +
" #{params} failed because: #{err.message}"
yield StandardError.new("Forespørsel til eksternt API(#{Settings::API})" +
" brukte for lang tid på å svare.")
else
log "API RESPONSE [#{resp.status}]"
unless [200, 201].include? resp.status
yield StandardError.new("Forespørsel feilet")
else
JSON.parse(resp.body)
end
end
def self.put(endpoint, params, headers={})
# Perform a POST request with parmas as JSON-encoded body.
# It returns the parsed JSON result, or yields to a block with an error
# if the request failed.
resp = ENDPOINTS[endpoint].put do |req|
req.headers = headers.merge({"Content-Type" => "application/json"})
req.body = params.to_json
log "API REQUEST to #{ENDPOINTS[endpoint].url_prefix.path}: #{req.body}"
end
rescue Faraday::Error, Errno::ETIMEDOUT => err
log "API request to #{ENDPOINTS[endpoint].url_prefix.path} with params" +
" #{params} failed because: #{err.message}"
yield StandardError.new("Forespørsel til eksternt API(#{Settings::API})" +
" brukte for lang tid på å svare.")
else
log "API RESPONSE [#{resp.status}]"
unless resp.status == 200
yield StandardError.new("Forespørsel feilet")
else
JSON.parse(resp.body)
end
end
def self.delete(endpoint, params, headers={})
# Perform a DELETE request with parmas as query-params.
# It returns the parsed JSON result, or yields to a block with an error
# if the request failed.
resp = ENDPOINTS[endpoint].delete do |req|
req.headers = headers.merge({"Content-Type" => "application/json"})
req.params = params
log "API REQUEST to #{ENDPOINTS[endpoint].url_prefix.path}: #{req.body}"
end
rescue Faraday::Error, Errno::ETIMEDOUT => err
log "API request to #{ENDPOINTS[endpoint].url_prefix.path} with params" +
" #{params} failed because: #{err.message}"
yield StandardError.new("Forespørsel til eksternt API(#{Settings::API})" +
" brukte for lang tid på å svare.")
else
log "API RESPONSE [#{resp.status}]"
unless resp.status == 200
yield StandardError.new("Forespørsel feilet")
else
JSON.parse(resp.body)
end
end
end | true |
97d180d9c74fe18a45a5f7a81e41256ffdc3243d | Ruby | Ssenkowski/sinatra-mvc-lab-v-000 | /models/piglatinizer.rb | UTF-8 | 1,119 | 3.765625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
class PigLatinizer
def piglatinize(word)
alpha = ('a'..'z').to_a
vowels = %w[a e i o u A E I O U]
consonants = alpha - vowels
if vowels.include?(word[0])
word + 'way'
elsif consonants.include?(word[0]) && consonants.include?(word[1]) && consonants.include?(word[2])
word[3..-1] + word[0..2] + 'ay'
elsif consonants.include?(word[0]) && consonants.include?(word[1])
word[2..-1] + word[0..1] + 'ay'
elsif consonants.include?(word[0])
word[1..-1] + word[0] + 'ay'
else
word # return unchanged
end
end
def to_pig_latin(phrase)
initial_phrase = phrase.downcase.split(" ").map {|word| piglatinize(word)}.join(" ")
if initial_phrase[0][0] == "i"
initial_phrase
elsif initial_phrase[0][0] == "o"
final_phrase = initial_phrase.capitalize
final_phrase
else
final_phrase2 = initial_phrase.capitalize
array = final_phrase2.split
array[0].gsub!("Ehay", "eHay")
array[13].gsub!("ulfgay", "ulfGay")
array[14].gsub!("eamstray", "eamStray")
array.join(" ")
end
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.