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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
6c32cc974b10bd0e7c2eb76a93eb448cc74d04d9 | Ruby | lewisbrown1993/snakes-and-ladders | /dice.rb | UTF-8 | 150 | 3.15625 | 3 | [] | no_license | class Dice
attr_reader :value
def initialize
@value = nil # not, I suppose, really needed
end
def roll
return rand(1..6)
end
end | true |
40c4f0212d807bdb21262ab34865767b7c82cae1 | Ruby | kfinn/jack-sudoku-experiment | /app/models/puzzle.rb | UTF-8 | 1,377 | 2.96875 | 3 | [] | no_license | class Puzzle
include ActiveModel::Model
attr_accessor :board
BOARD_SIZE = 9
def self.from_file(file)
rows = file.each_line.map do |line|
cells = line.split(' ')
raise "invalid line: #{line}" unless cells.size == BOARD_SIZE
cells.map do |cell|
if cell == '0'
nil
else
cell.to_i
end
end
end
raise "invalid file: #{file}" unless rows.size == BOARD_SIZE
new(board: Board.new(rows))
end
def solve!
moves = []
while board.next_empty_cell_position.present?
empty_cell_position = board.next_empty_cell_position
valid_move_for_empty_cell_position = Move.next_valid_move_for(empty_cell_position, board)
if valid_move_for_empty_cell_position.present?
valid_move_for_empty_cell_position.apply!
moves.push(valid_move_for_empty_cell_position)
else
reconsidered_move = moves.pop
next_reconsidered_move = Move.next_valid_move_for(reconsidered_move.position, board)
while next_reconsidered_move.nil?
reconsidered_move.reset!
reconsidered_move = moves.pop
next_reconsidered_move = Move.next_valid_move_for(reconsidered_move.position, board)
end
next_reconsidered_move.apply!
moves.push(next_reconsidered_move)
end
end
end
delegate :to_s, to: :board
end
| true |
55435c64de7d2e6b142e925baadcb47ea9bd8d9d | Ruby | ajduncan/lol | /client.rb | UTF-8 | 908 | 2.546875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
# coding: UTF-8
require "rubygems"
require "eventmachine"
HOST = '127.0.0.1'
SSL_PORT = 9001
class LOLKeyboardHandler < EM::Connection
include EM::Protocols::LineText2
attr_reader :queue
def initialize(q)
@queue = q
end
def receive_line(data)
@queue.push(data)
end
end
class LOLClientSSLHandler < EM::Connection
attr_reader :queue
def initialize(q)
@queue = q
cb = Proc.new do |msg|
send_data(msg)
q.pop &cb
end
q.pop &cb
end
def connection_completed
start_tls
end
def receive_data(data)
puts data
end
def ssl_handshake_completed
puts "SSL handshake completed successfully."
end
def unbinding
puts "Disconnecting..."
end
end
if __FILE__ == $0
EM.run {
q = EM::Queue.new
EM.connect(HOST, SSL_PORT, LOLClientSSLHandler, q)
EM.open_keyboard(LOLKeyboardHandler, q)
}
end
| true |
1fb6aeee804ee9f9f4bea001ba4189beedd2a70c | Ruby | max888/strandedtravel | /db/seeds.rb | UTF-8 | 1,831 | 2.515625 | 3 | [] | no_license | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
Destination.delete_all
destinations = Destination.create! ([
{ city: 'Barcelona', country: 'Spain', description: 'Barcelona is hot, energetic, and full of life. The city has beaches, mountains, great architecture, hills, art works, and a vibrant history. The people are great and the life is good. Top everything off with a little touch of Catalunyan pride and you have Barcelona.', user_id: 2},
{ city: 'Queenstown', country: 'New Zealand', description: 'The lake and mountain landscape make it suited to all kinds of adventure. There’s skiing in the winter and activities such as bungy jumping, sky diving, canyon swinging, jet boating, horse trekking and river rafting all year round. If hardcore adventure isnt your thing, there are plenty of mellow options available.', user_id: 2},
{ city: 'Lagos', country: 'Portugal', description: 'Amazing surfing and partying at the bottom of Portugal', user_id: 2},
{ city: 'Split', country: 'Croatio', description: 'Set sail from here on one of the amazing yacht weeks', user_id: 2},
{ city: 'Budapest', country: 'Hungary', description: 'Explore all the ruin bars for a night of your life', user_id: 2},
{ city: 'Sydney', country: 'Australia', description: 'beaches babes and beers', user_id: 2},
{ city: 'London', country: 'United Kingdom', description: 'Pubs and sports in the cultural capital', user_id: 2},
{ city: 'Krakow', country: 'Poland', description: 'youthful vibe in a city full of history', user_id: 2}
]) | true |
b31cb571985d5090698dd4d70cb99c9491449c93 | Ruby | EasyPost/easypost-ruby | /lib/easypost/services/billing.rb | UTF-8 | 2,440 | 2.734375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'easypost/constants'
class EasyPost::Services::Billing < EasyPost::Services::Service
# Get payment method info (type of the payment method and ID of the payment method)
def self.get_payment_method_info(priority)
payment_methods = EasyPost::Services::Billing.retrieve_payment_methods
payment_method_map = {
'primary' => 'primary_payment_method',
'secondary' => 'secondary_payment_method',
}
payment_method_to_use = payment_method_map[priority]
error_string = EasyPost::Constants::INVALID_PAYMENT_METHOD
suggestion = "Please use a valid payment method: #{payment_method_map.keys.join(', ')}"
if payment_methods[payment_method_to_use].nil?
raise EasyPost::Errors::InvalidParameterError.new(
error_string,
suggestion,
)
end
payment_method_id = payment_methods[payment_method_to_use]['id']
unless payment_method_id.nil?
if payment_method_id.start_with?('card_')
endpoint = '/v2/credit_cards'
elsif payment_method_id.start_with?('bank_')
endpoint = '/v2/bank_accounts'
else
raise EasyPost::Errors::InvalidObjectError.new(error_string)
end
end
[endpoint, payment_method_id]
end
# Fund your EasyPost wallet by charging your primary or secondary card on file.
def fund_wallet(amount, priority = 'primary')
payment_info = EasyPost::Services::Billing.get_payment_method_info(priority.downcase)
endpoint = payment_info[0]
payment_id = payment_info[1]
wrapped_params = { amount: amount }
@client.make_request(:post, "#{endpoint}/#{payment_id}/charges", EasyPost::Models::EasyPostObject, wrapped_params)
# Return true if succeeds, an error will be thrown if it fails
true
end
# Delete a payment method.
def delete_payment_method(priority)
payment_info = EasyPost::Services::Billing.get_payment_method_info(priority.downcase)
endpoint = payment_info[0]
payment_id = payment_info[1]
@client.make_request(:delete, "#{endpoint}/#{payment_id}")
# Return true if succeeds, an error will be thrown if it fails
true
end
# Retrieve all payment methods.
def retrieve_payment_methods
response = @client.make_request(:get, '/v2/payment_methods')
if response['id'].nil?
raise EasyPost::Errors::InvalidObjectError.new(EasyPost::Constants::NO_PAYMENT_METHODS)
end
response
end
end
| true |
02e9155ee251eac6358cb1c853e36a9e03bd2eb8 | Ruby | mixeeff/rubylessons | /lesson_7/carriage.rb | UTF-8 | 1,369 | 3.5625 | 4 | [] | no_license | require_relative('manufacturer')
require_relative('instance_counter')
class Carriage
include Manufacturer
include InstanceCounter
attr_reader :space, :free_space, :number, :owner
NUMBER_FORMAT = /^[A-Z]+\d+$/
OWNER_ERROR = 'Owner must be a Train or Nil'
WRONG_NUMBER_ERROR = 'Number must be String'
EMRTY_NUMBER_ERROR = 'Number can\'t be empty'
NUMBER_FORMAT_ERROR = 'Wrong number format'
WRONG_SPACE = 'Carrige\'s space must be more than zero'
NOT_ENOUGH_SPACE = 'There\'s not enough free space in carriage'
def initialize(number, space)
@number = number
@space = space
@free_space = space
validate!
register_instance
end
def reserve_space(space)
raise NOT_ENOUGH_SPACE if space > @free_space
@free_space -= space
end
def reserved_space
@space - @free_space
end
def to_s
result = "Carriage №#{number}"
result += ", made by #{manufacturer}" if manufacturer
result
end
def owner=(owner)
raise OWNER_ERROR unless (owner.is_a? Train) || owner.nil?
@owner = owner
end
def valid?
validate!
true
rescue
false
end
protected
def validate!
raise WRONG_NUMBER_ERROR unless number.is_a? String
raise EMRTY_NUMBER_ERROR if number.size.zero?
raise NUMBER_FORMAT_ERROR if number !~ NUMBER_FORMAT
raise WRONG_SPACE if space <= 0
end
end
| true |
359840b5152199964c73d83b23f848b4bf1d9a10 | Ruby | D4L/projectEuler | /src/problem-179/hral.rb | UTF-8 | 617 | 2.90625 | 3 | [] | no_license | public
def hral
count = 0
numDivisors = Array.new
isPrime = Array.new
remain = Array.new
(0..10000001).each do |i|
remain.push i
isPrime.push true
numDivisors.push 1
end
(2..5000000).each do |i|
if isPrime[i]
n = i * 2
begin
isPrime[n] = false
c = 0
while (remain[n] && remain[n] > 1 and remain[n] % i == 0)
remain[n] /= i
c += 1
end
numDivisors[n] *= c + 1
n += i
end while n < 10000000
end
end
(2..9999999).each do |i|
count += 1 if numDivisors[i] == numDivisors[i+1]
end
count
end
| true |
e4c8cee6d0970951af14c296af59fa9f9db1ad98 | Ruby | erezbosch/Goals | /GoalApp/app/models/cheer.rb | UTF-8 | 543 | 2.53125 | 3 | [] | no_license | class Cheer < ActiveRecord::Base
validates :user_id,
uniqueness: { scope: :goal_id, message: "Can't cheer goal more than once" }
validate :cannot_cheer_own_goal
validate :maximum_cheer_number
validates :user_id, :goal_id, presence: true
belongs_to :user
belongs_to :goal
private
def cannot_cheer_own_goal
if goal.user == user
errors[:user] << "Can't cheer your own goal"
end
end
def maximum_cheer_number
if user.cheers.length >= 10
errors[:user] << "You are out of cheers"
end
end
end
| true |
896c84be66a3e515957ff4cfd7563f33efc33113 | Ruby | AKB428/inazuma | /urisure/urisure_dat_extraction.rb | UTF-8 | 303 | 2.78125 | 3 | [] | no_license | open(ARGV[0]) {|file|
while line = file.gets
res_data = line.split("<>")
if res_data.size > 3
stage1 = res_data[3].delete("<br>").delete(">").delete(";&").delete("http://").delete("imu").delete("co")
puts stage1.gsub(/(jp|imgur|https|com|jpeg|png|hp)/, ' ')
end
end
}
| true |
99a8f86bbeac5098043d5ae0bca77da68ce1e49a | Ruby | aidasharif/ML-NLP-Projects | /Home_Credit_Kaggle/HomeCredit_3/transformers.rb | UTF-8 | 8,867 | 2.78125 | 3 | [] | no_license | ##transformers.rb
#### KEEP THIS AT THE TOP OF YOUR FILE ####
class TransformingLearner
include Learner
attr_accessor :name
def initialize transformer, learner
@parameters = learner.parameters
@parameters["learner"] = learner.parameters["name"] || learner.class.name
@transformer = transformer
@learner = learner
@name = self.class.name
end
def train dataset
@transformer.train dataset
transformed_examples = @transformer.apply dataset["data"]
train_dataset = dataset.clone
train_dataset["data"] = transformed_examples
@learner.train train_dataset
end
def predict example
transformed_example = @transformer.apply [example]
@learner.predict transformed_example.first
end
def evaluate dataset
transformed_dataset = dataset.clone
transformed_dataset["data"] = @transformer.apply dataset["data"]
@learner.evaluate transformed_dataset
end
end
class CopyingTransformingLearner
include Learner
attr_accessor :name
def initialize transformer, learner
@parameters = learner.parameters
@parameters["learner"] = learner.parameters["name"] || learner.class.name
@transformer = transformer
@learner = learner
@name = self.class.name
end
def clone_example example
e = example.clone
e["features"] = example["features"].clone
return e
end
def clone_dataset dataset
cloned_dataset = dataset.clone
cloned_dataset["features"] = dataset["features"].clone
cloned_dataset["data"] = dataset["data"].map {|e| clone_example(e)}
return cloned_dataset
end
def train dataset
@transformer.train clone_dataset(dataset)
train_dataset = clone_dataset(dataset)
transformed_examples = @transformer.apply train_dataset["data"]
train_dataset["data"] = transformed_examples
@learner.train train_dataset
end
def predict example
transformed_example = @transformer.apply [clone_example(example)]
@learner.predict transformed_example.first
end
def evaluate dataset
transformed_dataset = clone_dataset dataset
transformed_examples = @transformer.apply transformed_dataset["data"]
transformed_dataset["data"] = transformed_examples
@learner.evaluate transformed_dataset
end
end
### ADD YOUR CODE AFTER THIS ###
class FeatureTransformPipeline
def initialize *transformers
@transformers = transformers
end
def train dataset
@transformers.each do |item|
transform=item
transform.train dataset
transform.apply dataset["data"]
end
end
def apply example_batch
return @transformers.inject(example_batch) do |u, transform|
u = transform.apply example_batch
end
end
end
class AgeRangeAsVector
def initialize; end
def train dataset; end
def apply(example_batch)
min_age = 0
max_age = 100
feature_name = "days_birth"
pattern = "age_range_%d"
example_batch.each do |item|
next if !(item["features"][feature_name])
age=5*((-item["features"][feature_name])/(365*5)).floor
if age>100
age=100
end
if age<0
age=0
end
item["features"][pattern % [age]]=1
item["features"].delete(feature_name)
end
return example_batch
end
end
class DaysEmployedVector
def initialize; end
def train dataset; end
def apply(example_batch)
min_age = 0
max_age = 100
feature_name = "days_employed"
pattern = "employed_range_%d"
example_batch.each do |item|
next if !(item["features"][feature_name])
age=5*((-item["features"][feature_name])/(365*5)).floor
if age>100
age=100
end
if age<0
age=0
end
item["features"][pattern % [age]]=1
item["features"].delete(feature_name)
end
return example_batch
end
end
class TargetAveraging
attr_reader :means
def initialize feature_names
@means = Hash.new {|h,k| h[k] = Hash.new {|h,k| h[k] = 0}}
@feature_names = feature_names
@pattern = "avg_%s"
@total=Hash.new {|h,k| h[k] = Hash.new {|h,k| h[k] = 0}}
end
def train dataset
dataset["data"].each do |item|
item["features"].each do |key,array|
if (array.is_a? (String))
@total[key][array]+=1.0
end
end
end
dataset["data"].each do |item|
item["features"].each do |key,array|
if (array.is_a? (String)) and item["label"]==1 and @feature_names.include? key
@means[key][array]+=1.0/(@total[key][array])
end
end
end
end
def apply(example_batch)
example_batch.clone.each do |item|
item["features"].clone.each do |key,array|
if (array.is_a? (String)) and (@feature_names.include? key)
new_key="avg_"+key
item["features"][new_key] = @means[key][array]
item["features"].delete(key)
end
end
end
return example_batch
end
end
class MeanImputation
attr_reader :means
def initialize feature_names
@means = Hash.new {|h,k| h[k] = 0}
@miss = Hash.new {|h,k| h[k] = 0}
@feature_names = feature_names
end
def train dataset
data=dataset["data"]
@feature_names.each do |feature|
mean=[]
data.each do |item|
next if item["features"][feature].nil?
next if !(item["features"][feature].is_a? Numeric)
mean << item["features"][feature]
end
@means[feature] = mean(mean)
end
end
def apply(example_batch)
example_batch.each do |item|
@feature_names.each do |feature|
if item["features"][feature]==nil and @means[feature].is_a? (Numeric)
item["features"][feature]=@means[feature]
end
end
end
return example_batch
end
end
class L2Normalize
def train dataset; end
def apply(example_batch)
number=0
total=Hash.new {|h,k| h[k] = 0}
example_batch.each do |item|
item["features"].each do |key,array|
if (array.is_a? (Numeric))
total[number]=(array)**2+total[number]
end
end
number+=1
end
number=0
example_batch.each do |item|
item["features"].each do |key,array|
if (array.is_a? (Numeric))
item["features"][key]=array.to_f/((total[number])**0.5)
end
end
number+=1
end
return example_batch
end
end
class OneHotEncoding
def initialize feature_names
@feature_names = feature_names
@pattern = "%s=%s"
end
def train dataset; end
def apply(example_batch)
example_batch.clone.each do |item|
@feature_names.each do |feature|
if (item["features"][feature].is_a? (String))
new_key=feature+"="+item["features"][feature]
item["features"][new_key] = 1.0
item["features"].delete(feature)
end
end
end
return example_batch
end
end
class LogTransform
def initialize feature_names
@feature_names = feature_names
@pattern = "log_%s"
end
def train dataset; end
def apply(example_batch)
example_batch.clone.each do |item|
@feature_names.each do |feature|
if (item["features"][feature].is_a? (Numeric)) and item["features"][feature]>0
new_key="log_"+feature
item["features"][new_key] = Math.log(item["features"][feature])
item["features"].delete(feature)
end
end
end
return example_batch
end
end
class ZScoreTransformer
attr_reader :means, :stdevs
def initialize feature_names
@means = Hash.new {|h,k| h[k] = 0}
@miss = Hash.new {|h,k| h[k] = 0}
@stdevs = Hash.new {|h,k| h[k] = 0}
@feature_names = feature_names
end
def train dataset
data = dataset["data"]
@feature_names.each do |feature|
mean=[]
data.each do |item|
next if item["features"][feature].nil?
next if !(item["features"][feature].is_a? Numeric)
mean << item["features"][feature]
end
@means[feature] = mean(mean)
end
@feature_names.each do |feature|
data.each do |item|
next if item["features"][feature].nil? or !(item["features"][feature].is_a? (Numeric))
@stdevs[feature]=(item["features"][feature]-@means[feature])**2 +@stdevs[feature]
end
@stdevs[feature] = (@stdevs[feature].to_f/data.size)**0.5
end
end
def apply example_batch
example_batch.each do |item|
@feature_names.each do |feature|
next if !(item["features"][feature]) or @stdevs[feature]==0 or !((item["features"][feature]).is_a? (Numeric))
item["features"][feature]=(item["features"][feature]-@means[feature])/(@stdevs[feature])
end
end
return example_batch
end
end
| true |
dc77fdf059dbe1233adff32cdbc93bd3102d4a1c | Ruby | mmosche2/project-euler | /problem17.rb | UTF-8 | 3,007 | 4.21875 | 4 | [] | no_license | def convert_to_string(num)
if num == 0
num_string = ""
elsif num == 1
num_string = "one"
elsif num == 2
num_string = "two"
elsif num == 3
num_string = "three"
elsif num == 4
num_string = "four"
elsif num == 5
num_string = "five"
elsif num == 6
num_string = "six"
elsif num == 7
num_string = "seven"
elsif num == 8
num_string = "eight"
elsif num == 9
num_string = "nine"
elsif num == 10
num_string = "ten"
elsif num == 11
num_string = "eleven"
elsif num == 12
num_string = "twelve"
elsif num == 13
num_string = "thirteen"
elsif num == 14
num_string = "fourteen"
elsif num == 15
num_string = "fifteen"
elsif num == 16
num_string = "sixteen"
elsif num == 17
num_string = "seventeen"
elsif num == 18
num_string = "eighteen"
elsif num == 19
num_string = "nineteen"
end
return num_string
end
def convert_tens(num)
if num == 2
num_string = "twenty"
elsif num == 3
num_string = "thirty"
elsif num == 4
num_string = "forty"
elsif num == 5
num_string = "fifty"
elsif num == 6
num_string = "sixty"
elsif num == 7
num_string = "seventy"
elsif num == 8
num_string = "eighty"
elsif num == 9
num_string = "ninety"
end
return num_string
end
def convert_hundreds(num)
if num == 1
num_string = "onehundred"
elsif num == 2
num_string = "twohundred"
elsif num == 3
num_string = "threehundred"
elsif num == 4
num_string = "fourhundred"
elsif num == 5
num_string = "fivehundred"
elsif num == 6
num_string = "sixhundred"
elsif num == 7
num_string = "sevenhundred"
elsif num == 8
num_string = "eighthundred"
elsif num == 9
num_string = "ninehundred"
end
return num_string
end
sum = 0
x = 1
while x < 1001
num_string = ""
hundreds_string = ""
tens_string = ""
digit_string = ""
if x < 20
num_string = convert_to_string(x)
num = num_string.length
sum = sum + num
elsif x < 100
ten_val = x / 10
tens_string = convert_tens(ten_val)
remainder = x % 10
digit_string = convert_to_string(remainder)
num_string = tens_string + digit_string
num = num_string.length
sum = sum + num
elsif x < 1000
hundred_val = x / 100
hundreds_string = convert_hundreds(hundred_val)
remainder_tens = x % 100
tens_val = remainder_tens / 10
if tens_val < 2
# go here if its in the teens
digit_string = convert_to_string(remainder_tens)
else
tens_string = convert_tens(tens_val)
remainder_digits = remainder_tens % 10
digit_string = convert_to_string(remainder_digits)
end
if (tens_string.length > 0 || digit_string.length > 0)
num_string = hundreds_string + "and" + tens_string + digit_string
else
num_string = hundreds_string
end
# puts "hundreds_string: #{hundreds_string}"
# puts "tens_string: #{tens_string}"
# puts "num_string: #{num_string}"
# puts "num_string: #{num_string}"
num = num_string.length
sum = sum + num
elsif x == 1000
num_string = "onethousand"
num = num_string.length
sum = sum + num
end
x = x +1
end
puts sum | true |
c0bcdead0df91b4421ab9e321558695187f80e11 | Ruby | pasosdeJesus/sip | /app/helpers/sip/importa_helper.rb | UTF-8 | 2,520 | 2.96875 | 3 | [
"ISC"
] | permissive |
module Sip
module ImportaHelper
def nombre_en_tabla_basica(tbasica, nombre, menserror,
camponombre = 'nombre')
if !nombre || nombre == ''
return nil
end
d = tbasica.where("upper(unaccent(#{camponombre})) = upper(unaccent(?))",
nombre)
if d.count == 0
menserror << " No se encontró '#{nombre}' en tabla básica #{tbasica.to_s} al buscar en el campo #{camponombre}."
return nil
elsif d.count > 1
menserror << " En la tabla básica #{tbasica.class} hay #{d.count} registros cuyo campo #{camponombre} es #{nombre}."
return nil
else # d.count == 1
return d.take
end
end
module_function :nombre_en_tabla_basica
# @param f es fecha en formato dd/M/aaaa
# @param menserror es colchon de mensajes de error.
# @return objeto Date con fecha de f si no hay error
# Si hay error reotrna nil y agrega en menserror el error
def fecha_local_colombia_a_date(f, menserror)
d = Sip::FormatoFechaHelper.fecha_local_colombia_estandar(f, menserror)
if !d
menserror << " No pudo reconocer fecha #{f}."
return nil
else
d = Date.strptime(d, '%Y-%m-%d')
end
end
module_function :fecha_local_colombia_a_date
# @param nombre Apellido y nombre
# @return arreglo con nombre y apellido separados usando heurística simple
def separa_apellidos_nombres(nombre, menserror)
apellidos = 'N'
nombres = 'N'
n = nombre.gsub(/ */, ' ').gsub(/^ /, '').gsub(/ $/, '')
p = n.split(' ')
if p.count == 0
elsif p.count == 1
apellidos = p[0]
elsif p.count == 2
apellidos = p[0]
nombres = p[1]
elsif p.count == 3
apellidos = p[0] + ' ' + p[1]
nombres = p[2]
elsif p.count == 4
apellidos = p[0] + ' ' + p[1]
nombres = p[2] + ' ' + p[3]
elsif p.count == 5
apellidos = p[0] + ' ' + p[1] + ' ' + p[2]
nombres = p[3] + ' ' + p[4]
elsif p.count == 6
apellidos = p[0] + ' ' + p[1] + ' ' + p[2]
nombres = p[3] + ' ' + p[4] + ' ' + p[5]
elsif p.count == 7
apellidos = p[0] + ' ' + p[1] + ' ' + p[2] + ' ' + p[3]
nombres = p[4] + ' ' + p[5] + ' ' + p[6]
else
menserror = "No se esperaban tantas partes en nombre '#{n}'"
end
return [nombres, apellidos]
end
module_function :separa_apellidos_nombres
end
end
| true |
c2b06ce170b4d8b2e4baff243430b6db08e57c3a | Ruby | Caroguti/Ruby3 | /11_Patron3/patron3.rb | UTF-8 | 157 | 2.96875 | 3 | [] | no_license | n=ARGV[0].to_i
n.times do |i|
if i%6==0 || i%6==1
print '.'
elsif i%6==2 || i%6==3
print '*'
else
print '|'
end
end
puts "\n" | true |
c2b7da274407cf2f641cc1eab137c417c8cdaf5f | Ruby | jennafritz/phase-3-object-relations-practice-code-challenge-students-one-many | /app/models/cohort.rb | UTF-8 | 779 | 3.265625 | 3 | [] | no_license | require 'pry'
class Cohort < ActiveRecord::Base
has_many :students
def add_student(name, age)
self.students << Student.create(name: name, age: age)
end
def average_age
self.students.average(:age).to_f
end
def total_students
self.students.count
end
def self.biggest
# counts = Cohort.all.map do |cohort_instance|
# cohort_instance.total_students
# end
# biggest = sort.
sorted = self.all.sort do |cohort_a, cohort_b|
cohort_a.total_students <=> cohort_b.total_students
end
sorted.last
end
def self.sort_by_mod
self.all.sort do |cohort_a, cohort_b|
cohort_a.current_mod <=> cohort_b.current_mod
end
end
end | true |
44bcb03911e3a32df6a003ecbbee9f745a0dd3da | Ruby | Zekimar/CS1632 | /d2/tests/drive_update_test.rb | UTF-8 | 1,317 | 3.390625 | 3 | [] | no_license | require 'minitest/autorun'
require_relative '../Place'
require_relative '../Driver'
# Unit tests for Driver.update method
# EQUIVALENCE CLASSES:
# @books is updated when location == "Hillman"
# @toys is updated when location == "Museum"
# @classes is updated when location == "Cathedral"
# 1 variable is incrementing at a time
class DriverUpdateTest < Minitest::Test
#tests if books increments by 1 when location == "Hillman"
def test_books_update
pl = Place::new "eeeee"
d = Driver::new "Hello", pl
d.update "Hillman"
assert_equal d.books, 1
end
#tests if toys increments by 1 when location == "Museum"
def test_toys_update
pl = Place::new "eeeee"
d = Driver::new "Hello", pl
d.update "Museum"
assert_equal d.toys, 1
end
#tests if classes doubles when location == "Cathedral"
#method is called twice to ensure that it is doubled, not incremented by 1
def test_classes_update
pl = Place::new "eeeee"
d = Driver::new "Hello", pl
d.update "Cathedral"
d.update "Cathedral"
assert_equal d.classes, 4
end
#ensures that toys is not incrementing when location is "hillman"
#EDGE CASE
def test_other_args_not_incrementing
pl = Place::new "eeeee"
e = Driver::new "hello", pl
e.update "Hillman"
refute_equal e.toys, 1
end
end
| true |
fb9e75ceb105f9bd7fd517c51dddd561e70afa81 | Ruby | mdixon47/Codewars-Ruby | /8-kyu/Enumerable Magic #2 - True for Any.rb | UTF-8 | 251 | 3.765625 | 4 | [] | no_license | #Description:
#Create an any? function that accepts an array and a block,
#and returns true if the block returns true for any item in the array.
#If the array is empty, the function should return false.
def any? list, &block
list.any?(&block)
end | true |
de64fe9c345fea368fd1a5c6c85a1a8e631ae0d0 | Ruby | SAMTHP/recipe_scraper | /spec/recipe_marmiton_spec.rb | UTF-8 | 3,058 | 2.734375 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
describe "http://www.marmiton.org recipe crawler" do
before(:each) do
marmiton_url = 'http://www.marmiton.org/recettes/recette_burger-d-avocat_345742.aspx'
@recipe = RecipeScraper::Recipe.new marmiton_url
end
it 'should create the recipe' do
expect(@recipe).not_to be nil
end
it 'should get the right title' do
expect(@recipe.title).to eq("Burger d'avocat")
end
it 'should get the right times' do
expect(@recipe.preptime).to eq(20)
expect(@recipe.cooktime).to eq(7)
end
it 'should get ingredients' do
array_exepted = ["2 avocats", "2 steaks hachés de boeuf", "2 tranches de cheddar", "feuille de salade", "0.5 oignon rouge", "1 tomate", "sésame", "1 filet d'huile d'olive", "1 pincée de sel", "1 pincée de poivre", "2 avocats", "2 steaks hachés de boeuf", "2 tranches de cheddar", "feuille de salade", "0.5 oignon rouge", "1 tomate", "sésame", "1 filet d'huile d'olive", "1 pincée de sel", "1 pincée de poivre"]
expect(@recipe.ingredients).to be_kind_of(Array)
expect(@recipe.ingredients).to eq array_exepted
end
it 'should get steps' do
expect(@recipe.steps).to be_kind_of(Array)
expect(@recipe.steps.include?('Laver et couper la tomate en rondelles'))
end
it 'should get image url' do
expect(@recipe.image).to eq "https://image.afcdn.com/recipe/20160914/63596_w404h340c1cx2000cy3000.jpg"
end
it 'should export all informations to an array' do
exepted_hash = { :cooktime => 7,
:image => "https://image.afcdn.com/recipe/20160914/63596_w404h340c1cx2000cy3000.jpg",
:ingredients => ["2 avocats", "2 steaks hachés de boeuf", "2 tranches de cheddar", "feuille de salade", "0.5 oignon rouge", "1 tomate", "sésame", "1 filet d'huile d'olive", "1 pincée de sel", "1 pincée de poivre", "2 avocats", "2 steaks hachés de boeuf", "2 tranches de cheddar", "feuille de salade", "0.5 oignon rouge", "1 tomate", "sésame", "1 filet d'huile d'olive", "1 pincée de sel", "1 pincée de poivre"],
:preptime => 20,
:steps => ["Éplucher et couper l'oignon en rondelles. Laver et couper la tomate en rondelles. Cuire les steaks à la poêle avec un filet d'huile d'olive. Saler et poivrer. Toaster les graines de sésames. Ouvrir les avocats en 2, retirer le noyau et les éplucher. Monter les burger en plaçant un demi-avocat face noyau vers le haut, déposer un steak, une tranche de cheddar sur le steak bien chaud pour qu'elle fonde, une rondelle de tomate, une rondelle d'oignon, quelques feuilles de salade et terminer par la seconde moitié d'avocat. Parsemer quelques graines de sésames."],
:title => "Burger d'avocat",
}
expect(@recipe.to_hash).to eq exepted_hash
end
it 'should a m.marmiton.org url into a valid url' do
url = 'http://m.marmiton.org/recettes/recette_burger-d-avocat_345742.aspx'
recipe = RecipeScraper::Recipe.new url
expect(recipe).not_to be nil
expect(recipe.title).to eq("Burger d'avocat")
end
end
| true |
83eef5a3acf53f23d1201628b7ee063e919a4bd2 | Ruby | gsorokolit/mon26_reinforcement | /reinforcement.rb | UTF-8 | 1,192 | 2.65625 | 3 | [] | no_license | project = {
committee: ["Stella", "Salma", "Kai"],
title: "Very Important Project",
due_date: "December 14, 2019",
id: "3284",
steps: [
{description: "conduct interviews", due_date: "August 1, 2018"},
{description: "code of conduct", due_date: "January 1, 2018"},
{description: "compile results", due_date: "November 10, 2018"},
{description: "version 1", due_date: "January 15, 2019"},
{description: "revisions", due_date: "March 30, 2019"},
{description: "version 2", due_date: "July 12, 2019"},
{description: "final edit", due_date: "October 1, 2019"},
{description: "final version", due_date: "November 20, 2019"},
{description: "Wrap up", due_date: "December 1, 2019"}
]
}
#read committee array
project[:steps].each do |name|
#add PERSON key/value to each hash
name[:member] = project[:committee].first#name[:member] assigns values from |name| to kv pair as value
project[:committee].rotate!#rotate runs through list of committee array objects
end
p project
#assign each name in the committee to a variable ?
# add committee member name to each step
# steps per member should be equal
#member names should only appear once in code
| true |
3d005b4e08cd902f694a5535faf7c9d0ee1b0ce5 | Ruby | jkmarx/ActorNameGameApi | /app/models/movie.rb | UTF-8 | 815 | 2.703125 | 3 | [] | no_license | class Movie
include ActiveModel::Model
def self.getPersonsData(arrId)
JSON.parse(MovieDetail::requestPerson(arrId).body)["person_results"][0]
end
def self.parseNameImage(data)
data.map{ |person| {name: person["name"], image: "https://image.tmdb.org/t/p/w185" + person["profile_path"]} }
end
def self.addValidCast(castIds)
validCast = []
ind = 0
while validCast.length < 5 && ind < castIds.length
tempActor = getPersonsData(castIds[ind])
if tempActor && tempActor["name"] && tempActor["profile_path"]
validCast << tempActor
end
ind = ind + 1
end
validCast
end
def self.getFiveCastImage(movieId)
castIds = MovieDetail::getMovieCastIds(movieId)
personsDetails = addValidCast(castIds)
parseNameImage(personsDetails)
end
end
| true |
2a1dfb5a4520e9603c7b5005839eeb310c6b6661 | Ruby | Rabenmund/simple_app | /app/models/player.rb | UTF-8 | 3,106 | 2.625 | 3 | [] | no_license | class Player < ActiveRecord::Base
has_one :profession, as: :professionable
has_one :human, through: :profession
has_many :contracts, through: :human
has_many :organizations, through: :contracts
has_many :teams,
through: :organizations,
source: "organizable",
source_type: "Team"
has_many :offers
has_many :lineups, class_name: "LineupActor", as: :actorable
has_many :keeps, -> { where type: "Keeper" }, as: :actorable
has_many :defends, -> { where type: "Defender" }, as: :actorable
has_many :midfields, -> { where type: "Midfielder" }, as: :actorable
has_many :attacks, -> { where type: "Attacker" }, as: :actorable
scope :keepers, -> { where.not(keeper: 0).order(keeper: :desc) }
scope :defenders, -> { where.not(defense: 0).order(defense: :desc) }
scope :midfielders, -> { where.not(midfield: 0).order(midfield: :desc) }
scope :attackers, -> { where.not(attack: 0).order(attack: :desc) }
scope :active, -> { joins(:profession).where("professions.active = TRUE") }
scope :without_offer_by, ->(team_id, date) {
joins('LEFT OUTER JOIN offers ON offers.player_id = players.id')
.where("(players.id NOT IN ("\
"SELECT offers.player_id "\
"FROM offers "\
"WHERE offers.team_id = ? "\
"AND offers.negotiated IS FALSE "\
"AND offers.start_date >= ?"\
"))",
team_id, date)
.uniq
}
scope :without_contract_at, ->(date) do
joins(:human)
.joins('LEFT OUTER JOIN contracts '\
'ON contracts.human_id = humen.id')
.where('(GREATEST(contracts.to) < ?) OR contracts.id IS NULL', date)
end
scope :without_too_many_hard_competitors, ->(reputation) do
joins('LEFT OUTER JOIN offers '\
'ON offers.player_id = players.id')
.where("((SELECT COUNT(*) FROM offers "\
"where (offers.player_id = players.id "\
"AND offers.negotiated = false "\
"AND offers.reputation > ?)
) < 3) "\
"OR offers.id IS NULL ", reputation)
end
def self.strength
sum("players.keeper + players.defense + players.midfield + players.attack")
end
def self.linable
active#.
# wir brauchen polymorphe PlayerZustände, die einen Abwesenheitstyp haben
# und ein until date
# joins('LEFT OUTER JOIN zustaende ON zustaende.human_id = professions.human_id').
# where("NOT (zustaende.unavailable = TRUE AND zustaende.until > ?) OR (zustaende.id IS NULL)", LogicalDate)
end
delegate :birthday, :name, :age, to: :human
STRENGTH = { keeper: :keepers,
defense: :defenders,
midfield: :midfielders,
attack: :attackers
}
def keeper?
nearby(main_strength, keeper)
end
def defender?
nearby(main_strength, defense)
end
def midfielder?
nearby(main_strength, midfield)
end
def attacker?
nearby(main_strength, attack)
end
private
def nearby(main, strength)
strength > main * 0.9
end
def main_strength
[keeper, defense, midfield, attack].max
end
end
| true |
ea3cad34c73b7c39010cf757c4078c310bc1acf1 | Ruby | BLauris/car-importer | /db/seeds.rb | UTF-8 | 291 | 2.65625 | 3 | [] | no_license | manufacturers = ["Honda", "Ford", "Mazda", "Opel", "Peogeot", "Lada"]
puts "Started Seeding..."
30.times do
Car.create!(
manufacturer: manufacturers.sample,
price: rand(1000..100000),
used: [true, false].sample,
note: Faker::Lorem.sentence
)
end
puts "Seed Finished!"
| true |
c7628dc3255df1ccd4096b38dc456bebb8e3702c | Ruby | Escape-Games-by-Thought-Works/crypto-challenge | /ruby/lib/swap_round.rb | UTF-8 | 93 | 2.765625 | 3 | [] | no_license | class SwapRound
def run(blocks)
[blocks[0], blocks[2], blocks[1], blocks[3]]
end
end
| true |
34730041dd9d7be65985fb46207eee8cf1ed4a72 | Ruby | calorie/cluster-packer | /lib/cluster/lib/cluster/configure.rb | UTF-8 | 2,616 | 2.625 | 3 | [
"MIT"
] | permissive | require 'yaml'
require 'erb'
module Cluster
class Configure
attr_reader :config
CONFIG_FILE = 'config.yml'
KEY_FILE = 'insecure_key'
CHEF_REPO = 'chef-repo'
VAGRANT_FILE = 'Vagrantfile'
PACKER_NFS = 'packer-nfs.json'
PACKER_MPI = 'packer-mpi.json'
def initialize(production = false)
@production = production
@root = Dir.pwd
config = YAML.load_file(config_path) if config?
@config = default.deep_merge(config)
end
def root_path
@root
end
def config_path
File.join(@root, CONFIG_FILE)
end
def key_path
File.join(@root, KEY_FILE)
end
def chef_repo
File.join(@root, CHEF_REPO)
end
def vagrant_file
File.join(@root, VAGRANT_FILE)
end
def packer_nfs
File.join(@root, PACKER_NFS)
end
def packer_mpi
File.join(@root, PACKER_MPI)
end
def env_config
production? ? production : staging
end
def staging
@config[:staging]
end
def production
@config[:production]
end
def production?
@production
end
def deploy
@config[:deploy]
end
def network
@config[:network]
end
def dummy?
production? ? false : staging[:nfs][:dummy]
end
def home
user = production? ? production[:login_user] : staging[:login_user]
user == 'root' ? '/root' : File.join('/home', user)
end
def data
File.join(home, 'data')
end
def default
{
staging: {
node_num: 1,
login_user: 'mpi',
nfs: {
dummy: true,
},
},
production: {
login_user: 'mpi',
mpi: [],
},
deploy: {
ssh_opts: '',
test: true,
},
}
end
private
def config?
return true if File.exist?(config_path) || example?
puts "#{config_path} is not found."
exit 1
end
def example?
while true
print "Would you like to use #{CONFIG_FILE}.example? [y|n]:"
case STDIN.gets
when /\A[yY]/
example
return true
when /\A[nN]/
return false
end
end
end
def example
templates = File.join(File.dirname(__FILE__), 'templates')
template = File.join(templates, "#{CONFIG_FILE}.example")
unless File.exist?(template)
puts "#{template} is not found."
exit 1
end
erb = ERB.new(File.read(template))
File.write(config_path, erb.result)
end
end
end
| true |
9b7845bbf48fa28699cb15121a42aad0ced42a7a | Ruby | Bropell/launch_school_exercises | /RB100_programming_and_back_end_prep/methods_exercises/exercise1.rb | UTF-8 | 258 | 4.15625 | 4 | [] | no_license | #Write a program that prints a greeting
#message. This program should contain
#a method called 'greeting' that takes
#a 'name' as its parameter and returns
#a string
def greeting(name)
"Hello, nice to meet you " + name + "."
end
puts greeting("Brandon")
| true |
ab1e4969ed1cf9b3255f58b54033c4dfc1587555 | Ruby | tzip25/oo-kickstarter-nyc-web-career-021819 | /lib/project.rb | UTF-8 | 334 | 2.625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Project
require 'pry'
attr_reader :backers
attr_accessor :title
def initialize(title)
@title = title
@backers = []
end
def add_backer(backer)
@backers << backer
#add the projcet the project is self
#we want to push self onto backers backed_projects
backer.backed_projects << self
end
end
| true |
5e6e5fa0c40084a275a226cfef67c751ae42213f | Ruby | hanazuki/adventofcode | /src/2a.rb | UTF-8 | 129 | 2.890625 | 3 | [] | no_license | puts $<.each_line.map {|l|
l, w, h = l.chomp.split('x').map(&:to_i)
2*l*w + 2*w*h + 2*h*l + [l*w, w*h, h*l].min
}.inject(:+)
| true |
daa499ec00f1731b6db0a52a32cb0510847dfe00 | Ruby | fiosman/App-Academy | /alpha_curriculum/09_guessing_game_project/lib/play_guessing_game.rb | UTF-8 | 574 | 3.703125 | 4 | [] | no_license | # No need to change or write any code in this file.
#
# After you complete all specs, you can simulate your game by
# running this file with `ruby lib/play_guessing_game.rb` in your terminal!
require_relative "guessing_game"
print "Enter a min number: "
min = gets.chomp.to_i
print "Enter a max number: "
max = gets.chomp.to_i
puts "I'm thinking of a number between #{min} and #{max}"
guessing_game = GuessingGame.new(min, max)
until guessing_game.game_over?
guessing_game.ask_user
puts "---------------"
end
puts "You won in #{guessing_game.num_attempts} tries"
| true |
657970c903a925872523e26a61f1a9697b515a1d | Ruby | wedesoft/linalg | /lib/linalg/dmatrix/main.rb | UTF-8 | 5,526 | 3.203125 | 3 | [
"MIT"
] | permissive | #
# Copyright (c) 2004-2008 by James M. Lawrence
#
# See LICENSE
#
module Linalg
class DMatrix
include Iterators
include XData # :nodoc:
include Linalg::Exception # :nodoc:
##################################################
#
# singleton methods
#
##################################################
#
# Create a matrix by joining together a list of column vectors
#
# m == DMatrix.join_columns(m.columns.map { |x| x })
#
def self.join_columns(cols)
col_vsize = cols[0].vsize
res = DMatrix.reserve(col_vsize, cols.size)
cols.each_with_index { |col, j|
unless col.vsize == col_vsize
raise DimensionError
end
res.replace_column(j, col)
}
res
end
#
# Create a matrix by joining together a list of row vectors
#
# m == DMatrix.join_rows(m.rows.map { |x| x })
#
def self.join_rows(rows)
row_hsize = rows[0].hsize
res = DMatrix.reserve(rows.size, row_hsize)
rows.each_with_index { |row, i|
unless row.hsize == row_hsize
raise DimensionError
end
res.replace_row(i, row)
}
res
end
#
# calls DMatrix.rows with a splat (*)
#
# DMatrix[[1,2,3],[4,5,6]]
# is equivalent to
# DMatrix.rows [[1,2,3],[4,5,6]]
#
def self.[](*array)
self.rows(array)
end
#
# Create a matrix using the elements of +array+ as columns.
#
# DMatrix.columns(array)
# is equivalent to
# DMatrix.new(array[0].size, array.size) { |i,j| array[j][i] }
#
# +DimensionError+ is raised if +array+ is not rectangular.
#
def self.columns(array)
self.rows(array).transpose!
end
class << self
attr_accessor :default_epsilon
end
#
# rdoc can you see me?
#
self.default_epsilon = 1e-8
##################################################
#
# instance methods
#
##################################################
#
# Returns the singleton class of the object. Convenient for
# setting the +default_epsilon+ on a per-object basis.
# b = DMatrix.rand(4, 4)
# a = b.map { |e| e + 0.0001 }
# a.class.default_epsilon # => 1e-8
# a =~ b # => false
# a.singleton_class.default_epsilon = 0.001
# a =~ b # => true
#
def singleton_class
class << self
self
end
end
#
# True if element-wise identical values.
#
def ==(other)
self.within(0.0, other)
end
#
# Sum of diagonal elements.
#
def trace
diags.inject(0.0) { |acc, e| acc + e }
end
#
# Same as to_s but prepended with a newline for nice irb output
#
def inspect
"\n" << self.to_s
end
#
# Dump to an +eval+-able string
#
def inspect2
res = "#{self.class}["
vsize.times { |i|
res << "["
hsize.times { |j|
res << self[i,j].to_s << ","
}
res.chop!
res << "],"
}
res.chop!
res << "]"
end
#
# Dump to a readable string
#
def to_s(format = "% 10.6f")
res = ""
vsize.times { |i|
hsize.times { |j|
res << sprintf(format, self[i,j])
}
res << "\n"
}
res
end
#
# Returns <tt>m[0,0]</tt> when +m+ is a 1x1 matrix, otherwise a
# +TypeError+ is raised.
#
def to_f
if vsize == 1 and hsize == 1
self[0,0]
else
raise TypeError, "to_f called on nonscalar matrix"
end
end
#
# Implemented as
#
# m.within(epsilon, other)
#
# where
# epsilon =
# self.singleton_class.default_epsilon ||
# self.class.default_epsilon
#
def =~(other)
epsilon =
self.singleton_class.default_epsilon ||
self.class.default_epsilon
self.within(epsilon, other)
end
#
# Returns
# self.vsize == self.hsize
#
def square?
self.vsize == self.hsize
end
#
# Tests whether the matrix is symmetric within +epsilon+
#
def symmetric?(epsilon = (self.singleton_class.default_epsilon || self.class.default_epsilon))
symmetric_private(epsilon)
end
#
# Exchange the <tt>p</tt>-th row with the <tt>q</tt>-th row
#
def exchange_rows(p, q)
tmp = self.row(p)
replace_row(p, self.row(q))
replace_row(q, tmp)
end
#
# Exchange the <tt>p</tt>-th column with the <tt>q</tt>-th column
#
def exchange_columns(p, q)
tmp = self.column(p)
replace_column(p, self.column(q))
replace_column(q, tmp)
end
private
#
# Create a column vector from the array
#
def self.column_vector(array)
self.columns([array])
end
#
# Create a row vector from the array
#
def self.row_vector(array)
self.rows([array])
end
end
end
| true |
2ceafb9eb4988aa18651eb57f7c14d2f9bc6fdab | Ruby | johnfig/DBC-Challenges | /Week_1/Day_2/enumerables.rb | UTF-8 | 1,122 | 4.53125 | 5 | [] | no_license | # Print the 1st, 3rd, 5th, 7th, etc. elements of a list on separate lines.
def print_odd_indexed_integers(array)
array2 = []
array.each_with_index do |item,index|
if (item %2 == 0)
array2.push(item)
end
end
array2
end
print print_odd_indexed_integers([1,2,3,4,5,6,7,8,9])
# Return the odd numbers from a list of integers.
def odd_integers(array)
array2 = []
array.each_with_index do |item,index|
if (item %2 == 1)
array2.push(item)
end
end
array2
end
print odd_integers([1,2,3,4,5,6,7,8,9])
# Return the first number from an Array that is less than a particular number - 'limit.'
def first_under(array, limit)
array.index {|x| x < limit}
end
print first_under([13,14,9,15,16,1], 10)
# Take an Array of Strings and return a new Array with an exclamation point appended to each String.
def add_bang(array)
array.collect {|x| x + "!" }
end
print add_bang(["a", "b", "c"])
# Calculate the sum of an Array of numbers.
def sum(array)
end
# Reorganize an Array of the elements into groups of 3, and then sort each group alphabetically.
def sorted_triples(array)
end | true |
6c59c1561216200e66362cf8d65f993701d4a4f8 | Ruby | rubygitflow/thinknetica_ruby | /seventh_lesson/library.rb | UTF-8 | 385 | 2.65625 | 3 | [] | no_license | module Library
Cargo = 1
Passenger = 2
TrainTypeDescription = {
cargo: {
name: 'Грузовой'
},
passenger: {
name: 'Пассажирский'
}
}
def show_train_type_list
puts menu_cargo
puts menu_passenger
end
private
def menu_cargo
"#{Cargo}. Cargo"
end
def menu_passenger
"#{Passenger}. Passenger"
end
end
| true |
75d1e98723e7dbd9c68058e17df37f262af1e56c | Ruby | sunny-mittal/project-euler | /ruby/pandigital_prime.rb | UTF-8 | 294 | 3.140625 | 3 | [
"MIT"
] | permissive | require 'prime'
def find_largest_pandigital_prime
start = [7, 6, 5, 4, 3, 2, 1] # largest permutation
start.permutation.each do |possibility|
possibility = possibility.join.to_i
if possibility.prime?
p possibility
break
end
end
end
find_largest_pandigital_prime
| true |
c178cac724334c89165367a21b973b39927641f2 | Ruby | Kphillycat/todos | /todo8/deli.rb | UTF-8 | 412 | 3.328125 | 3 | [] | no_license | class Deli
attr_accessor :line
def initialize
@line = []
end
def take_a_number(name)
#@line.length is 3 for some reason
@line << "#{@line.length+1}. #{name}"
# @line.each_with_index do |value, index|
# @line[index] = "#{index+1}. #{name}"
# end
end
def now_serving
num_regex = /\d+. /
name_n_num = @line.delete_at(0)
name = name_n_num.sub num_regex, ''
name
end
end #end of class | true |
bab807dcb5f29e9c5c508169a1eefca720a3781b | Ruby | jpace/pvn | /lib/pvn/pct/repository_differ.rb | UTF-8 | 2,108 | 2.671875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/ruby -w
# -*- ruby -*-
require 'pvn/io/element'
require 'pvn/pct/differ'
require 'svnx/revision/range'
require 'rainbow'
module PVN::Pct
class RepositoryDiffer < Differ
def get_from_to_revisions rev
if rev.size == 1
if md = Regexp.new('(.+):(.+)').match(rev[0])
[ md[1], md[2] ]
else
[ (rev[0].to_i - 1).to_s, rev[0] ]
end
else
[ rev[0], rev[1] ]
end
end
def get_modified elmt, fromrev, torev
modified = elmt.find_entries [ fromrev + ':' + torev ], :modified
modified.collect { |m| m.name }.sort.uniq
end
def has_revisions? elmt, fromrev, torev
elmt.has_revision?(fromrev) && elmt.has_revision?(torev)
end
def directory? elmt
elmtinfo = elmt.get_info
elmtinfo.kind == 'dir'
end
def get_local_info
direlmt = PVN::IO::Element.new :local => '.'
direlmt.get_info
end
def get_line_count elmt, rev
elmt.cat(rev).size
end
def get_diff_counts path, options
revision = options.revision
info "revision: #{revision}".color('#fafa33')
# revision -r20 is like diff -c20:
fromrev, torev = get_from_to_revisions revision
elmt = PVN::IO::Element.new :local => path
modnames = get_modified elmt, fromrev, torev
info "modnames: #{modnames}"
reporoot = elmt.repo_root
svninfo = get_local_info
filter = svninfo.url.dup
filter.slice! svninfo.root
filterre = Regexp.new '^' + filter + '/'
diff_counts = Array.new
modnames.each do |mod|
fullpath = reporoot + mod
elmt = PVN::IO::Element.new :path => fullpath
info "elmt: #{elmt}"
next unless has_revisions? elmt, fromrev, torev
next if directory? elmt
from_count = get_line_count elmt, fromrev
to_count = get_line_count elmt, torev
name = mod.dup
name.slice! filterre
dc = PVN::DiffCount.new from_count, to_count, name
diff_counts << dc
end
diff_counts
end
end
end
| true |
7ec34f55ed9523c6ae88efa0250e9f5559d7b1e6 | Ruby | MichaelConner/week2_day_1_homework_classes_and_objects | /sports_team/sports_team.rb | UTF-8 | 633 | 3.234375 | 3 | [] | no_license | class SportsTeam
attr_reader :team_name, :players
attr_accessor :coach, :points
def initialize(team_name, players, coach)
@team_name = team_name
@players = players
@coach = coach
@points = 0
end
# def get_team_name
# return @team_name
# end
#
# def get_players
# return @players
# end
#
# def get_coach
# return @coach
# end
#
# def set_coach(coach)
# @coach = coach
# end
def add_player(player)
@players << player
end
def find_player(player)
@players.include?(player)
end
def update_points(result)
points_added = {
'win' => 3,
'lose' => 0,
'draw' => 1
}
@points += points_added[result]
end
end
| true |
4432d3affa8b037b28416f2535234b27eb602479 | Ruby | ilyutov/balanced-ruby | /lib/balanced/resources/bank_account.rb | UTF-8 | 1,194 | 2.75 | 3 | [
"MIT"
] | permissive | module Balanced
# A BankAccount is both a source, and a destination of, funds. You may
# create Debits and Credits to and from, this funding source.
#
# *NOTE:* The BankAccount resource does not support creating a Hold.
#
class BankAccount
include Balanced::Resource
def initialize attributes = {}
Balanced::Utils.stringify_keys! attributes
unless attributes.has_key? 'uri'
attributes['uri'] = Balanced::Marketplace.my_marketplace.send(self.class.collection_name + '_uri')
end
super attributes
end
# Creates a Debit of funds from this BankAccount to your Marketplace.
#
# @param [String] appears_on_statement_as If nil then Balanced will use
# the +domain_name+ property from your Marketplace.
# @return [Debit]
def debit amount, appears_on_statement_as=nil, meta={}, description=nil
self.account.debit(amount, appears_on_statement_as, meta, description, self.uri)
end
# Creates a Credit of funds from your Marketplace to this Account.
#
# @return [Credit]
def credit amount, description=nil, meta={}
self.account.credit(amount, description, meta, self.uri)
end
end
end
| true |
ddc7b972d61f26798d1cd29572243d887a65d8f8 | Ruby | pludlum/app_academy_projects | /w1d2/memory_puzzle/humanPlayer.rb | UTF-8 | 1,736 | 3.5625 | 4 | [] | no_license | class HumanPlayer
def prompt(board = nil)
puts "Guess a row! (between 1 and 4)"
row = gets.chomp.to_i # 1 - 4
puts "Guess a column! (between 1 and 4)"
col = gets.chomp.to_i # 1 - 4
# 0 - 15
(row - 1) * 4 + (col - 1)
end
def receive_revealed_card(something, thing)
end
end
class ComputerPlayer
def initialize
@seen = Array.new(16, nil)
end
def receive_revealed_card(face, idx)
@seen[idx] = face
end
def prompt(board)
# if 0 uniqs face up && pair exists in @seen && pair not face up
# then flip one
# if 1 uniq face up && pair exists
# => pick the other , and simultaneously turn the pair in seen to symbol
@seen.each.with_index do |face, idx|
if face.is_a?(Fixnum) && board.face_down?(idx) # if num and faceDOWN
# if we saw both (count is 2 if saw both)
if pair_exists?(face)
p '0'
p idx
p @seen
return idx
end
end
end
if board.count == 1 && pair_exists?(board.uniques.to_a[0].face) # if 1 uniq face up && pair exists
face = board.uniques.to_a[0].face
idx = @seen.index(face)
if board.cards[idx].face.nil?
p '1'
p idx
@seen[@seen.index(face)], @seen[@seen.rindex(face)] = :seen, :seen
return idx
else
p '2'
p @seen.rindex(face)
@seen[@seen.index(face)], @seen[@seen.rindex(face)] = :seen, :seen
return @seen.rindex(face)
end
else # return a random face down index
idx = rand(16)
idx = rand(16) until @seen[idx].nil?
p '3'
p idx
idx
end
end
def pair_exists?(face)
@seen.count(face) == 2
end
end
# [,,,5,,,3,,3,,,7,,,].index(3)
| true |
91c9d390b4bc1feaa43e6696c342e07b9c9c3794 | Ruby | risatronic/ruby-math-game | /question.rb | UTF-8 | 284 | 3.796875 | 4 | [] | no_license | class Question
attr_reader :answer
def initialize
@number1 = rand(1..20)
@number2 = rand(1..20)
@answer = @number1 + @number2
end
def ask_question
"What does #{@number1} + #{@number2} equal?"
end
def correct_answer?(input)
input == @answer
end
end | true |
546740874d2ed4ad8033a608850a9186700b57de | Ruby | dapawn/collections_practice-cb-000 | /collections_practice.rb | UTF-8 | 631 | 3.8125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def sort_array_asc(arr)
arr.sort
end
def sort_array_desc(arr)
arr.sort.reverse
end
def sort_array_char_count(arr)
arr.sort do |a, b|
if a.length == b.length
0
elsif a.length < b.length
-1
elsif a.length > b.length
1
end
end
end
def swap_elements(arr)
x = arr[1]
arr[1] = arr[2]
arr[2] = x
arr
end
def reverse_array(arr)
arr.reverse
end
def kesha_maker(arr)
arr.map { |e| e[2] = "$"; e}
end
def find_a(arr)
arr.select {|e| e[0] == "a"}
end
def sum_array(arr)
i = 0
arr.each {|e| i += e}
i
end
def add_s(arr)
arr.each_with_index {|e,i| e << "s" if i != 1}
end
| true |
918f873d57ee980ac0625097de7fa2dbfd3c819e | Ruby | kmsheng/kkbox-hackathon-practice | /p3/p3.rb | UTF-8 | 1,457 | 3.84375 | 4 | [] | no_license | class Sudoku
def initialize(width)
@width = width
@sqrt_width = Math.sqrt(width).to_i
@order = (0..@sqrt_width - 1).to_a
@numbers = (1..@width).to_a.shuffle
make_first_template
make_board
end
def shift_order
element = @order.shift
@order.push(element)
end
def make_board
@board = []
for i in 0..@width - 1
@board[i] = (0..@width - 1).to_a
end
end
def make_first_template
@template = []
for i in 0..@sqrt_width - 1
@template[i] = []
for j in 0..@sqrt_width - 1
@template[i][j] = @numbers.shift
end
end
end
def shift_row(index)
element = @template[index].shift
@template[index].push(element)
end
def get_answer
for k in 0..@sqrt_width - 1
for i in 0..@sqrt_width - 1
for j in 0..@sqrt_width - 1
stick_row(i, j, k)
end
shift_row(k)
end
shift_order
end
end
def stick_row(i, j, k)
start = j * @sqrt_width
stop = start + @sqrt_width - 1
row = @order[j] + i * @sqrt_width
num = 0
for index in start..stop
@board[row][index] = @template[k][num]
num += 1
end
end
def get_board_graph
str = ""
for i in 0..@width - 1
for j in 0..@width - 1
str += "#{ @board[i][j] } "
if (0 == (j + 1) % @sqrt_width)
str += " "
end
end
if (0 == (i + 1) % @sqrt_width)
str += "\n\n"
end
str += "\n\n"
end
return str
end
end
s = Sudoku.new( gets.chomp!.to_i )
s.get_answer
puts s.get_board_graph
| true |
e6ecf1614f4eaa8a091c43b3e0202c2716d04e00 | Ruby | reckenrode/advent_2019 | /lib/advent_2019.rb | UTF-8 | 1,402 | 3.03125 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
# lib/advent_2019.rb
# Copyright © 2019 Randy Eckenrode
#
# This program is distributed under the terms of the MIT license. You should
# have received a copy of this license with this program. If you did not, you
# can find a copy of this license online at https://opensource.org/licenses/MIT.
require 'advent_2019/day'
require 'advent_2019/version'
# Top-level module for Advent of Code 2019 gem
module Advent2019
class Error < StandardError; end
# Runs the Advent of Code 2019 solution indicated by the first element of
# argv. The remaining elements of argv will be parsed as that day’s
# command-line arguments.
#
# @param [Array<String>] argv the command-line arguments
def self.main(argv)
show_help if argv.empty?
Day.new
day = Day.days[argv.shift]
options = day.parse!(argv)
File.open(options.delete(:input), 'r') do |file|
day.run(file, **options)
end
end
# Displays the program’s usage message.
# @param [#to_s] msg an object that displays the program’s usage and help
def self.show_help(msg = nil)
if msg.nil?
msg = OptionParser.new do |parser|
parser.banner = 'Usage: advent_2019 <day> [options]'
parser.on('-h', '--help', 'show this help message')
parser.separator "\nAvailable Days: #{Day.days.keys.sort.join(', ')}"
end
end
puts msg
exit
end
end
| true |
81564a7cfb90fcfa43ef9aa5aab78eaac304d35c | Ruby | bhabeshagrawal/myRecipes | /test/models/recipe_test.rb | UTF-8 | 1,533 | 2.59375 | 3 | [] | no_license | require "test_helper"
class RecipeTest < ActiveSupport::TestCase
def setup
@chef = Chef.new(chefname: "Bhabesh", email: "bhabesh@gmail.com")
@recipe = @chef.recipes.build(name:"panner",summary:"this is best recipe i ever ate",description:"hi hi isdhg gsd g gsdg gsd jhdgs gsgd jag dsjj jgsdj jadgjj jajdsg hjasdg j jagd jag dj")
end
test "Recipe should be valid" do
assert @recipe.valid?
end
test "Name should be present" do
@recipe.name = " "
assert_not @recipe.valid?
end
test "name length should not be too long" do
@recipe.name = "a" * 151
assert_not @recipe.valid?
end
test "name length should not be too short" do
@recipe.name = "a" * 4
assert_not @recipe.valid?
end
test "Summary should be present" do
@recipe.summary = " "
assert_not @recipe.valid?
end
test "Chef id should be present" do
@recipe.chef_id = nil
assert_not @recipe.valid?
end
test "Summary length should not be too long" do
@recipe.summary = "a" * 151
assert_not @recipe.valid?
end
test "Summary length should not be too short" do
@recipe.summary = "a" * 9
assert_not @recipe.valid?
end
test "description should be present" do
@recipe.description = " "
assert_not @recipe.valid?
end
test "description length should not be too long" do
@recipe.description = "a" * 501
assert_not @recipe.valid?
end
test "description length should not be too short" do
@recipe.description = "a" * 19
assert_not @recipe.valid?
end
end | true |
fb79ac0817a23e44c97781926edb4bfd83d262bf | Ruby | irmercaldi/Coding-Exercises | /metaprogrammingex4.rb | UTF-8 | 369 | 2.75 | 3 | [] | no_license | class Author
genres = %w(fiction coding history)
genres.each do |genre|
define_method("#{genre}_details") do |arg|
puts "Genre: #{genre}"
puts arg
puts genre.object_id
end
end
end
author = Author.new
author.coding_details("Cal Newport")
author.fiction_details("Brandon Sanderson")
author.history_details("Audie Murphy")
p author.respond_to?(:coding_details) | true |
4b5ddec5c531e9d9f808c689a92bf1f1bd1c6b7f | Ruby | carusocr/bcast | /mech/ytvore.rb | UTF-8 | 7,395 | 2.859375 | 3 | [] | no_license | #!/usr/bin/env ruby
=begin
Name: ytvore.rb
Date Created: 10 December 2013
Author: Chris Caruso
Script to crawl YouTube and search for videos matching keywords stored in a local database.
General process:
1. We generate a list of events and associated search terms and use this information to create a database table of keywords, each associated to a particular event in ascout_event.
2. Script automatically checks database table for events+keywords and crawls youtube. Looks for videos that match search terms and checks existing urls in prescouting data table to ensure that they have not already been identified.
3. Adds found urls that match search terms to database.
4. Script crawls to video url and gets license information and duration. If both match our criteria it adds video url, event type, searchwords used (this would let us generate histograms and see which keywords are most effective on a per-event basis), license, and video duration to prescouting table.
5. Human scouts load first-pass tool, which contains a list of YouTube video urls for each event. Human views prescouted videos, makes appropriate judgments. Once this is done, the annotation is copied to the ascout_url table and continues through the pipeline as usual.
Additional notes:
YouTube won't serve more than 1000 search hits. Initial seeding
will be a lot of videos, but after that maybe search once a day for any videos.
Need to test out application of filters. We will want to use duration, upload date,
maybe license although SYL isn't listed.
*How to exclude fullnames? I would bet that video clips with someone's name in the
thumbnail description also has them using their own name in the clip itself.
* Grab additional data from search page - thumbnail, description, uploader, license info
* youtube-dl can get autocaps, but those are terrible for filtering anything.
* youtube-dl can also get:
thumbnail URL
title
ID
video description
video length
Method flow:
1. Assemble list of search terms.
2. For each search term, perform youtube page search from 1..pagemax. Push results into hash!
2a. ...or automatically update ascout_prescout with data, but push url+id to download hash?
3. Repeat for all search terms, build one huge hash. Values needed in hash are...? ID. URL.
4. Hash.each call update_prescout.
5. Go back and query prescout to get list of stuff to download.
6. Download clips.
7. Update metadata.
TO-DO LIST:
* multiple search words
=end
require 'mysql'
require 'open-uri'
require 'mechanize'
require 'nokogiri'
require 'optparse'
OptionParser.new do |o|
o.on('-s SEARCHTERM','Text search term; concatenate multiple in quotes with spaces') {|b| $searchstring = b}
o.on('-p DBPASS','Password to MySQL scouting db') {|b| $dbpass = b}
o.on('-d {hour|today|week|month}','Only get videos uploaded during the past hour/day/week/month') {|b| $date_filter = b}
o.on('-t {short|long}','Only get videos of either < 4 or > 20 minutes') {|b| $duration_filter = b}
o.on('-h','--help','Print this help text') {puts o; exit}
o.on('--no-db','Don\'t update database with found clips') {|b| $no_db_update = true}
o.on('--no-dl','Don\'t download found clips') {|b| $no_download = true}
o.on('-w','Search Wikipedia discographies') {|b| $wikisearch = b}
o.on('-l max-pages','Limit page hits, YouTube returns max 50 pages, 20 videos per page') {|b| $pagecount = b.to_i}
o.parse!
end
#nfpr = don't replace searchterm
#filter string constructor...do this less hamfistedly.
if $date_filter && $duration_filter
$search_prefix = "http://www.youtube.com/results?nfpr=1&filters=#{$date_filter},#{$duration_filter}&search_query="
elsif $date_filter && !$duration_filter
$search_prefix = "http://www.youtube.com/results?nfpr=1&filters=#{$date_filter}&search_query="
elsif !$date_filter && $duration_filter
$search_prefix = "http://www.youtube.com/results?nfpr=1&filters=#{$duration_filter}&search_query="
else
$search_prefix = "http://www.youtube.com/results?nfpr=1&search_query="
end
abort "Enter database password!" unless $dbpass || $no_db_update
$datadir = "~/projects/bcast/mech"
if !$no_db_update
puts 'databasing'
$m = Mysql.new "localhost", "root", "#{$dbpass}", "ascout"
end
$download_urls = Hash.new{|h,k| h[k] = Hash.new}
$agent = Mechanize.new
def grab_page_links(ytpage)
#add in date filters here as well, if specified
page = $agent.get(ytpage)
#get max number of pages to crawl
max_pages = 50 #youtube won't handle more than 1000 results and there are 20 per page
total_results = page.parser.xpath('//p[starts-with(@class, "num-results")]/strong').text.sub(',','').to_i/20
unless $pagecount #skip if pagecount has been specified in args
$pagecount = (total_results < max_pages) ? total_results : max_pages
end
page_hits = []
ytpage = ytpage + "&page=1"
for i in 1..$pagecount
ytpage.sub!(/page=\d+/,"page=#{i}")
page = $agent.get(ytpage)
page.parser.xpath('//div[contains(@class, "yt-lockup-content")]').each do |vid|
vid_url = vid.at('a').attr('href').sub("/watch?v=","")
duration = vid.at('span').children.text.sub(" - Duration: ","").sub(".","")
puts vid_url
page_hits.push("#{vid_url}\t#{vid_url}") # using unique vid string as filename for now
end
end
page_hits.each do |hit|
url,title = hit.split("\t")
#change single quotes to escaped quotes for sql statement, strip trailing _
#title = title.gsub(/\W/,"_").gsub(/_+/,"_").sub(/_$/,"")
update_prescout(url,uploader,duration,searchterm,title) if !$searchstring
#populate hash of hashes
$download_urls["#{url}"]['title'] = title
end
end
def scrape_wiki_albums(wikipage)
wikipage = "http://en.wikipedia.org/wiki/" + $searchstring
wikipage += "_discography"
#this depends on consistent naming conventions and existence of <artist>_discography Wikipage
doc = Nokogiri::HTML(open(wikipage))
doc.xpath('//table/caption[contains(text(),"studio album")]/..//th[@scope="row"]//a').each do |t|
puts t.attr('href')
end
end
def update_prescout(url,uploader,duration,searchterm,title)
return 0 if $no_db_update == true
begin
$m.query("insert into ascout_prescout (url, uploader, duration, searchterm, created,title) values ('#{url}','#{uploader}',time_to_sec('#{duration}'),'#{searchterm}',current_timestamp,'#{title}')")
rescue Mysql::Error => e
pp e
end
end
def update_searchterm(id)
begin
$m.query("update ascout_searchterm set updated = current_timestamp where id = '#{id}'")
rescue Mysql::Error => e
pp e
end
end
def build_searchlist()
if $searchstring
searchterm = $searchstring.gsub(" ","+")
puts "Search string is #{searchterm}!"
ytpage = $search_prefix + searchterm
puts ytpage
searchterm = 'NULL'
grab_page_links(ytpage)
return 0
end
ytq = $m.query("select id,name from ascout_searchterm where active = 1")
ytq.each_hash do |r|
ytpage = $search_prefix + "#{r['name']}"
searchterm = r['id']
grab_page_links(ytpage)
end
end
def download_clips()
$download_urls.sort_by.each do |u|
#this makes [0] the hash key, i.e. the unique url string
url = u[1]['url']
url = u[0]
title = u[1]['title']
puts "DLCMD: youtube-dl -w -f mp4 -o downloads/#{title}.mp4 #{url}\n"
# add --dateafter
unless $no_download == true
`youtube-dl -w -f mp4 -o #{$datadir}/downloads/#{title}.mp4 #{url}`
end
end
end
build_searchlist()
download_clips()
| true |
26cdb6df8b076c9f97023cdc200cc39388ebd95c | Ruby | nafnarem/ruby_activity | /confection.rb | UTF-8 | 287 | 3.0625 | 3 | [] | no_license | class Confection
def prepare
puts "Baking at 350 degrees for 25 minutes."
end
end
class BananaCake < Confection
end
class Cupcake < Confection
def prepare
super
puts "Applying Frosting"
end
end
cake1 = BananaCake.new
cake2 = Cupcake.new
cake1.prepare
cake2.prepare | true |
1f8e20bde40764d79b84deac537e69c1ff14569a | Ruby | kagd/R2D2 | /app/services/base_service.rb | UTF-8 | 157 | 2.703125 | 3 | [] | no_license | class BaseService
private #-----------------------------------
def talk(str, color=:light_blue)
puts '/'*60
puts str.colorize(color)
end
end
| true |
902d0e44c508138e4607978addc8d45e9a125e92 | Ruby | blambeau/waw | /lib/waw/tools/mail/template.rb | UTF-8 | 1,185 | 2.546875 | 3 | [
"MIT"
] | permissive | module Waw
module Tools
class MailAgent
# Allows creating WLang templates for mails easily
class Template < Mail
# The wlang dialect
attr_writer :dialect
# Returns the wlang dialect to use
def dialect
return @dialect if @dialect
case content_type
when 'text/html'
'wlang/xhtml'
when 'text/plain'
'wlang/active-string'
else
Waw.logger.warn("Unable to get wlang dialect from content-type #{content_type}")
Waw.logger.warn("Using wlang/active-string by default")
end
end
# Instantiates this template using a given wlang context.
# The date of the resulting mail is set to Time.now
def instantiate(context = {})
mail, args = self.dup, context.unsymbolize_keys
mail.subject = mail.subject.wlang(args, dialect)
mail.body = mail.body.wlang(args, dialect)
mail.date = Time.now
mail
end
alias :to_mail :instantiate
end
end # class MailAgent
end # module Tools
end # module Waw | true |
00bfc1a240ba302db12057963e501106240c6fe2 | Ruby | hiukkanen/iban-tools | /lib/iban-tools/bic.rb | UTF-8 | 1,072 | 2.859375 | 3 | [
"MIT"
] | permissive | module IBANTools
module BIC
def bic
if country_bics_mapped?(self.country_code) and IBAN.valid?(self.code)
bic_map = bic_maps[self.country_code]
return find_bic bic_map, self.code
else
return nil
end
end
def bic_maps
{"FI" => {
"1" => "NDEAFIHH",
"2" => "NDEAFIHH",
"31" => "HANDFIHH",
"33" => "ESSEFIHX",
"34" => "DABAFIHX",
"36" => "TAPIFI22",
"37" => "DNBAFIHX",
"38" => "SWEDFIHH",
"39" => "SBANFIHH",
"4" => "HELSFIHH",
"5" => "OKOYFIHH",
"6" => "AABAFI22",
"8" => "DABAFIHH"
}}
end
def country_bics_mapped? country_code
bic_maps[country_code] != nil
end
private
def find_bic bic_map, iban
(0..10).each do |i|
start_index = 4
s_key = iban[start_index..i+start_index]
i_key = s_key.to_i
bic = bic_map[i_key.to_s]
if bic
return bic
end
end
raise "Bic mapping problem"
end
end
end
| true |
42ee4306631d6c6fc30e3fdc69fc0016f9db7851 | Ruby | remind101/email-provider | /lib/email_provider/finder.rb | UTF-8 | 579 | 2.625 | 3 | [
"MIT"
] | permissive | module EmailProvider
class Finder
attr_reader :email
def self.find(*args)
new(*args).find
end
def initialize(email)
@email = email
end
def find
if from_regex?
from_regex
elsif from_mx?
from_mx
end
end
private
def from_regex
@from_regex ||= Provider.new(Lookup::Regex.lookup(email))
end
def from_mx
@from_mx ||= Provider.new(Lookup::Mx.lookup(email))
end
def from_regex?
from_regex.to_sym
end
def from_mx?
from_mx.to_sym
end
end
end
| true |
398cd2f66f2e0638e56ef1ffabdb49af87ad6b59 | Ruby | kax4/bin | /dmenu-app | UTF-8 | 2,898 | 3.296875 | 3 | [] | no_license | #!/usr/bin/ruby
# dmenu accepts a list of items, to which the user filters. The most common
# use of dmenu is to find all binaries in $PATH and select from one of those.
# This is useful if you know what the application's binary is called before hand
# but if the user does not know the binary name, but does know the application's
# name, this script should be used instead.
#
# Looping through all the desktop entries in /usr/share/applications, find all
# the applications. (avoiding those that are solely for MIME type registration)
# Then display the application's name (e.g. Okuluar, Firefox, etc). Given the
# user's choice, run the application's command.
#
# NOTE: The field codes for Exec are not supported at this time, and are
# stripped, for the time being.
# Temporary value, to avoid any calls to nil before the real value is set
@lines = []
# Given a string, find the default value.
#
# TODO: Does not support localized values yet
def find_key(key)
value = @lines.grep(/^\s*#{key.capitalize}\s*=/).last
if !!value
value.split('=')[1..-1].join("=").strip
else
""
end
end
# Simple Dir glob, recursively finding all .desktop files
# XXX: Can this be faster? Does it need to be?
desktops = Dir["/usr/share/applications/**/*.desktop"]
# The meat of this application, the application processing
applications = desktops.map do |app|
# Load the file into memory
@lines = File.readlines(app)
good = true # Optimistic thinking ftw!
# Only select appropriate applications that want to be displayed
if find_key("Type").downcase != "application"
good = false
end
if find_key("NoDisplay") == "true"
good = false
end
if good
# We want this application, so grab it's name
name = find_key("Name")
# Strip the field codes
app_exec = find_key("Exec").gsub(/(-?-\w+ )?\"?\%[fFuUick]\"?/, '').gsub(/(\s)+/, '\1').strip
# If this application needs to be ran in a terminal, call $TERMINAL
# (falling back to $TERM, or 'xterm')
if find_key("Terminal") == "true"
app_exec = "#{ENV['TERMINAL'] || ENV['TERM'] || 'xterm'} -c \"#{app_exec}\""
end
# Return an array pair, later to be converted into a hash key/value pair
[name, app_exec]
else
# nil is the default value
nil
end
# Reject all applications which did not match the criteria set above
end.reject do |app|
app.nil?
end
# Convert the array of pairs into a hash
app_hash = Hash[applications.sort]
# Open an IO channel with dmenu
dm = IO.popen('dmenu', 'w+')
# Put each application name into stdin
app_hash.keys.each do |value|
dm.puts value
end
# Wait for the user
dm.close_write
choice = dm.read
# Close & shutdown
dm.close
# Execute the application choice, if that is what the user chose.
if $? == 0
exec app_hash[choice]
end
| true |
2692c9bed2024263dfa2207174c126fc6d6dd8d0 | Ruby | DAOkiin/cryptotradingbot | /app/lib/app/parser/operations/construct_klines.rb | UTF-8 | 2,730 | 2.703125 | 3 | [] | no_license | require 'app/operation'
require 'parser/import'
require 'app/parser/entities/kline'
module App
module Parser
module Operations
# Construct App::Parser::Entities::Kline objects from array of hashes
# Need :source, :c1, :c2, interval
class ConstructKlines < App::Operation
def call(data)
case data[:source]
when 'binance.ws.kline'
result = binance_ws(data)
when 'binance.rest.kline'
result = binance_rest(data)
when 'redis'
result = from_redis(data)
end
data[:klines] = result
result.first.is_a?(App::Parser::Entities::Kline) ? Success(data) : Failure(result)
end
private
def binance_ws(data)
symbol = data[:params][:c1] + data[:params][:c2]
data[:klines].map do |kline|
k = kline['k']
App::Parser::Entities::Kline[{
open_time: k['t'],
open: BigDecimal.new(k['o']),
high: BigDecimal.new(k['h']),
low: BigDecimal.new(k['l']),
close: BigDecimal.new(k['c']),
volume: BigDecimal.new(k['v']),
close_time: k['T'],
symbol1: data[:params][:c1],
symbol2: data[:params][:c2],
pair: symbol,
interval: data[:params][:interval]
}]
end
end
def binance_rest(data)
pair = data[:params][:c1] + data[:params][:c2]
result = data[:klines].map do |k|
App::Parser::Entities::Kline[{
open_time: k[0],
open: BigDecimal.new(k[1]),
high: BigDecimal.new(k[2]),
low: BigDecimal.new(k[3]),
close: BigDecimal.new(k[4]),
volume: BigDecimal.new(k[5]),
close_time: k[6],
symbol1: data[:params][:c1],
symbol2: data[:params][:c2],
pair: pair,
interval: data[:params][:interval]
}]
end
result
end
def from_redis(data)
data[:klines].map do |k|
App::Parser::Entities::Kline[{
open_time: k['open_time'],
open: BigDecimal.new(k['open']),
high: BigDecimal.new(k['high']),
low: BigDecimal.new(k['low']),
close: BigDecimal.new(k['close']),
volume: BigDecimal.new(k['volume']),
close_time: k['close_time'],
symbol1: k['symbol1'],
symbol2: k['symbol2'],
pair: k['pair'],
interval: k['interval']
}]
end
end
end
end
end
end
| true |
ee12cd5a10bc98361886df2ca701a3e693ac0ac4 | Ruby | JonathanLoscalzo/Taller-Ruby | /Practica1/ejercicio16.rb | UTF-8 | 952 | 4.5 | 4 | [] | no_license | #
# 16. a. Dado un color expresado como una combinación RGB calcular su representación entera.
# Consideramos que un color rgb se
# expresa como un hash con las claves [:red, :green, :blue],
# y para cada una toma valores en el rango (0..255). Por ejemplo:
#
# { red: 0, green: 0, blue: 255 } =>
#
# { red: 128, green: 128, blue: 255 }
#
# La representación entera se calcula como: red + green*256 + blue*256^2
#
# b. Realizar el mismo cálculo obteniendo los coeficientes para cada componente del color de
# otro hash coefficients = { red: 256**0, green: 256**1, blue: 256**2 }
#
$hash = { red: 0, green: 1, blue: 2 }
$coefficients = { red: 256**0, green: 256**1, blue: 256**2 }
def entero_rgb(rgb)
rgb.reduce(0) { |total, (key, value) | total + value * $coefficients[key] } # => value*(256**$hash[key])
end
h1 = { red: 0, green: 0, blue: 255 }
print "#{entero_rgb(h1)}\n"
h2 = { red: 128, green: 125, blue: 255 }
print "#{entero_rgb(h2)}\n"
| true |
a1aea55e197da69f8f652e5e992d547b6ce51627 | Ruby | darrenyong/aaClasswork | /W2D4/Big O/anagrams.rb | UTF-8 | 995 | 4.15625 | 4 | [] | no_license | #anagrams
def first_anagram(string, target)
# time complexity O(n!)
combos = string.chars.permutation.to_a
combos.include?(target.chars)
end
def second_anagram(string, target)
# time complexity O(n)
chars = target.chars
string.each_char do |char|
idx = chars.index(char)
next if idx.nil?
chars.delete_at(idx)
end
chars.empty?
end
def third_anagram(string, target)
# time complexity O(n)? ot O(1)
string.chars.sort == target.chars.sort
end
def fourth_anagram(string, target)
# time complexity O(n squared)
hash1 = Hash.new(0)
hash2 = Hash.new(0)
string.chars.each do |ele|
hash1[ele] += 1
end
target.chars.each do |ele|
hash2[ele] += 1
end
hash1 == hash2
end
def bonus_anagram(string, target)
# time complexity O(n squared)
hash1 = Hash.new(0)
string.chars.each do |ele|
hash1[ele] += 1
end
target.chars.each do |ele|
hash1[ele] -= 1
end
!hash1.values.any? {|ele| ele < 0}
end | true |
6505cacd84988de864b3bc4de6da3dc0928c711b | Ruby | angel41023/ruby-design-patterns | /Builder/dates.rb | UTF-8 | 164 | 3.09375 | 3 | [] | no_license | class Dates
attr_accessor :from, :to
def initialize(from, to)
@from = from
@to = to
end
def full_date
puts "De: #{from} - A: #{to}"
end
end
| true |
de2d7a66be022c2ff41a6d910ec5cf6bd4705509 | Ruby | xithan/WRCompanyMapping | /tfidf/idf/inverse_document_frequency.rb | UTF-8 | 1,725 | 3.671875 | 4 | [] | no_license | require_relative '../../DocumentUtils/corpus'
require_relative '../../DocumentUtils/text_document'
#InverseDocumentFrequency consists the basic implementation of inverse document frequency. It is the logarithmically
#scaled inverse fraction of the documents that contain the token, obtained by dividing the total number of documents by
#the number of documents containing the token, and then taking the logarithm of that quotient.
class InverseDocumentFrequency
def initialize(corpus)
@corpus = corpus
end
#Calculates the basic Inverse Document Frequency of each token contained in a corpus of documents.
def calculate
_df = document_frequency
_idf = Hash.new
_df.each do |word, freq|
_idf[word] = Math.log(@corpus.size/freq)
end
return _idf
end
def info
"The inverse document frequency is a measure of how much "
+"information the word provides, that is, whether the term is "
+"common or rare across all documents of a corpus. It is the logarithmically "
+"scaled inverse fraction of the documents that contain the token,"
+" obtained by dividing the total number of documents by the number "
+"of documents containing the token, and then taking the logarithm "
+"of that quotient."
end
def maxIDF
return Math.log(@corpus.size * 1.0)
end
protected
#calculates the number of document occurrences of unique tokens within a corpus
def document_frequency
_df = Hash.new
@corpus.each do |doc|
_words = doc.bag_of_words.keys
_words.each do |word|
if (_df.has_key?(word))
_df[word] = _df[word]+1.0
else
_df[word] = 1.0
end
end
end
return _df
end
end
| true |
f145b5d705ec6891bf71d97766197dbba9dadb1a | Ruby | simplebunsen/mindermast-ruby | /players.rb | UTF-8 | 1,708 | 3.65625 | 4 | [] | no_license | require './helper'
# All players, human or computer, inherit common functionality from here
class BasePlayer
def initialize(humanity)
@humanity = humanity
end
# implement rate, guess and make_code in the subclasses!!!
end
# Computer Player that plays algorithmically
class CPUPlayer < BasePlayer
def initialize
@previous_guesses = []
super(false)
end
def rate(board)
# big algorithm
code = board.code
current_guess = board.current_guess
index = 0
calculated_numbers_array = current_guess.reduce({}) do |acc, el|
if el == code[index]
acc[:num_place_color] += 1
code[index] = 'X'
else
code.include?(el) ? acc[:num_color] += 1 : nil
end
index += 1
end
InputHelper.rating_processing(calculated_numbers_array[:num_place_color], calculated_numbers_array[:num_color])
end
def guess
# big algorithm
rating = [1, 0, 0, 1] # sample
end
def make_code
15 # temp, make code here
end
end
# Human Player that plays via input
class HumanPlayer < BasePlayer
def initialize
super(true)
end
def rate(*)
# TODO print code
puts 'How many pins are both the right place and the right color?'
num_place_color = gets.chomp.to_i
puts 'How many pins are the right color BUT not the right place?'
num_color = gets.chomp.to_i
InputHelper.rating_processing(num_place_color, num_color)
end
def guess
puts 'guess like so: "red,blue,brown,green"'
color_array = gets.chomp.split(',')
InputHelper.color_to_internal(color_array)
end
def make_code
puts 'Set a code like so: "red,blue,brown,green"'
gets.chomp
# TODO: do code as array!!!
end
end | true |
baf4497d67af53507f2d9132b41ae537dd29e267 | Ruby | cirediatpl/pokemon-scraper-yale-web-yss-052719 | /lib/pokemon.rb | UTF-8 | 1,297 | 3.140625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Pokemon
attr_accessor :id, :name, :type, :db
def initialize(name:, type:, db:, id:nil)
@id = id
@name = name
@type = type
@db = db
end
# def self.create(name:, type:)
# pokemon = Pokemon.new(name, type, db)
# pokemon.save
# pokemon
# end
# def self.new_from_db(array)
# pokemon = Pokemon.new("", "")
# pokemon.id = array[0]
# pokemon.name = array[1]
# pokemon.type = array[2]
# pokemon
# end
def self.save(name, type, db)
sql = <<-SQL
INSERT INTO pokemon (name, type)
VALUES (?, ?)
SQL
db.execute(sql, name, type)
@id = db.execute("SELECT last_insert_rowid() FROM pokemon")[0][0]
end
def self.find(id, db)
sql = <<-SQL
SELECT *
FROM pokemon
WHERE id = ?
LIMIT 1
SQL
row = db.execute(sql, id)[0]
Pokemon.new(name: row[1], type: row[2], db: db, id: row[0])
end
def self.create_table
sql = <<-SQL
CREATE TABLE IF EXISTS pokemon (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
type TEXT
)
SQL
db.execute(sql)
end
end
| true |
227808e06d977bc51ddc6e56b15b95e53c607fac | Ruby | rcrichton87/project_1_xwing_squad_builder | /models/squad.rb | UTF-8 | 1,384 | 3.3125 | 3 | [] | no_license | require_relative('../db/sql_runner.rb')
require_relative('./piloted_ship.rb')
class Squad
attr_reader :id
attr_accessor :name, :faction
def initialize(options)
@id = options['id'].to_i
@name = options['name']
@faction = options['faction']
end
def save
sql = "INSERT INTO squads (name, faction) VALUES ('#{@name}', '#{@faction}') RETURNING *;"
result = SqlRunner.run(sql).first
@id = result['id'].to_i
end
def self.delete_all
sql = "DELETE FROM squads;"
SqlRunner.run(sql)
end
def piloted_ships
sql = "SELECT * FROM piloted_ships WHERE squad_id = #{@id};"
piloted_ships = SqlRunner.run(sql)
results = piloted_ships.map{ |piloted_ship| PilotedShip.new(piloted_ship) }
return results
end
def total_cost
piloted_ships = self.piloted_ships
total_cost = 0
piloted_ships.each { |piloted_ship| total_cost += piloted_ship.total_cost}
return total_cost
end
def self.get_many(sql)
squads = SqlRunner.run(sql)
results = squads.map{ |squad| Squad.new(squad)}
end
def self.all
sql = "SELECT * FROM squads;"
return self.get_many(sql)
end
def delete
sql = "DELETE FROM squads WHERE id = #{@id};"
SqlRunner.run(sql)
end
def self.find(id)
sql = "SELECT * FROM squads WHERE id = #{id};"
squad = SqlRunner.run(sql).first
return Squad.new(squad)
end
end | true |
83218fecd7099fea128552d65a2682d5f7ead631 | Ruby | fl00r/monga | /lib/monga/database.rb | UTF-8 | 8,757 | 3.015625 | 3 | [
"MIT"
] | permissive | module Monga
class Database
attr_reader :client, :name
def initialize(client, name)
@client = client
@name = name
end
# Choose collection to work
#
# client = Monga:::Client.new
# db = client.get_db("dbTest")
# collection = db.get_collection("testCollection")
# # same as
# collection = db["testCollection"]
#
def get_collection(collection_name)
Monga::Collection.new(self, collection_name)
end
alias :[] :get_collection
# Run some command
#
# cmd = { getLastError: 1 }
# db.cmd(cmd){ |err, resp| ... }
#
def cmd(cmd, resp_blk = nil, &ret_blk)
if resp_blk
run_cmd(cmd, ret_blk, &resp_blk)
else
run_cmd(cmd, ret_blk)
end
end
# Evaluate some raw javascript
#
# db.eval("return('Hello World!')") do |err, resp|
# # processing
# end
#
def eval(js, &blk)
cmd = {}
cmd[:eval] = js
run_cmd(cmd, blk)
end
# You should be cearfull with this method 'cause it is importaint to know
# in wich connection you are trying to get last error information.
# So be happy to use safe_* methods and it will choose right connection for you.
# Or, if you really want to do it mannually:
#
# request = collection.insert({ title: "Test" })
# conn = request.connection
# db.get_last_error(conn){ |err, resp| ... }
# db.get_last_error(conn){ |err, resp| ... }
# # you should pass following options:
# db.get_last_error(
# conn,
# j: true,
# w: 2,
# fsync: true,
# wtimout: 100){ |err, resp| ... }
#
def get_last_error(collection, opts = {}, &blk)
raise_last_error(collection, opts, &blk)
rescue => e
return e
end
# Instead of get_last_eror this one will actually raise it.
# It is usefull for safe_* methods who should raise an error if something goes wrong
#
def raise_last_error(connection, opts = {}, &blk)
cmd = {}
cmd[:getLastError] = 1
cmd[:connection] = connection
cmd[:j] = opts[:j] if opts[:j]
cmd[:fsync] = opts[:fsync] if opts[:fsync]
cmd[:w] = opts[:w] if opts[:w]
cmd[:wtimeout] = opts[:wtimeout] if opts[:wtimeout]
run_cmd(cmd, blk)
end
# Obviously dropping collection
# There is collection#drop helper exists
#
# db.drop_collection("testCollection"){ |err, resp| ... }
# # same as
# collection = db["testCollection"]
# collection.drop{ |err, resp| ... }
#
def drop_collection(collection_name, &blk)
cmd = {}
cmd[:drop] = collection_name
run_cmd(cmd, blk)
end
# Drop current database
#
# db.drop
#
def drop(&blk)
cmd = {}
cmd[:dropDatabase] = 1
run_cmd(cmd, blk)
end
# Create collection.
#
# db.create_collection("myCollection"){ |err, resp| ... }
# db.create_collection("myCappedCollection", capped: true, size: 1024*10){ |err, resp| ... }
#
def create_collection(collection_name, opts = {}, &blk)
cmd = {}
cmd[:create] = collection_name
cmd.merge!(opts)
run_cmd(cmd, blk)
end
# Counts amount of documents in collection
#
# db.count("myCollection"){ |err, cnt| ... }
# # same as
# collection = db["myCollection"]
# collection.count{ |err, cnt| ... }
#
def count(collection_name, opts = {}, &blk)
cmd = {}
cmd[:count] = collection_name
cmd.merge!(opts)
run_cmd(cmd, blk) do |resp|
resp["n"].to_i
end
end
# Drop choosen indexes.
# There is collection#drop_index and collection#drop_indexes methods available
#
# db.drop_indexes("myCollection", { title: 1 })
# db.drop_indexes("myCollection", [{ title: 1 }, { author: 1 }])
# # drop all indexes
# db.drop_indexes("myCollection", "*")
# # same as
# collection = db["myCollection"]
# collection.drop_index(title: 1)
# # drop all indexes
# collection.drop_indexes
#
def drop_indexes(collection_name, indexes, &blk)
cmd = {}
cmd[:dropIndexes] = collection_name
cmd[:index] = indexes
run_cmd(cmd, blk)
end
# Run mapReduce command.
# Available options:
#
# * map - A JavaScript function that associates or “maps” a value with a key and emits the key and value pair.
# * reduce - A JavaScript function that “reduces” to a single object all the values associated with a particular key.
# * out - Specifies the location of the result of the map-reduce operation.
# * query - Specifies the selection criteria.
# * sort - Sorts the input documents.
# * limit - Specifies a maximum number of documents to return from the collection
# * finalize
# * scope
# * jsMode
# * verbose
#
# Inline response returned by default.
#
def map_reduce(collection_name, opts, &blk)
cmd = {}
cmd[:mapReduce] = collection_name
cmd.merge! opts
cmd[:out] ||= { inline: 1 }
run_cmd(cmd, blk)
end
# Run aggregate command.
#
def aggregate(collection_name, pipeline, &blk)
cmd = {}
cmd[:aggregate] = collection_name
cmd[:pipeline] = pipeline
run_cmd(cmd, blk)
end
# Run distinct command.
# You should pass collection_name and key.
# Query option is optional.
#
def distinct(collection_name, opts, &blk)
cmd = {}
cmd[:distinct] = collection_name
cmd.merge! opts
run_cmd(cmd, blk)
end
# Run group command.
# Available options are:
# key – Specifies one or more document fields to group
# $reduce – Specifies an aggregation function that operates on the documents during the grouping operation
# initial – Initializes the aggregation result document
# $keyf – Specifies a function that creates a “key object” for use as the grouping key
# cond – Specifies the selection criteria to determine which documents in the collection to process
# finalize – Specifies a function that runs each item in the result
#
def group(collection_name, opts, &blk)
cmd = {}
cmd[:group] = opts
cmd[:group][:ns] ||= collection_name
run_cmd(cmd, blk)
end
# Run text command.
# Available options are:
# search (string) – A string of terms that MongoDB parses and uses to query the text index
# filter (document) – A query document to further limit the results of the query using another database field
# project (document) – Allows you to limit the fields returned by the query to only those specified.
# limit (number) – Specify the maximum number of documents to include in the response
# language (string) – Specify the language that determines for the search the list of stop words and the rules for the stemmer and tokenizer
#
def text(collection_name, opts, &blk)
cmd = {}
cmd[:text] = collection_name
cmd.merge! opts
run_cmd(cmd, blk)
end
# Just helper to show all list of collections
#
# db.list_collections{ |err, list| ... }
#
def list_collections(&blk)
eval("db.getCollectionNames()", &blk)
end
private
# Underlying command sending
#
def run_cmd(cmd, ret_blk, &resp_blk)
connection = cmd.delete :connection
connection ||= @client.aquire_connection
options = {}
options[:query] = cmd
Monga::CallbackCursor.new(connection, name, "$cmd", options).first do |err, resp|
res = make_response(err, resp, ret_blk, resp_blk)
unless ret_blk
return res
end
end
end
# Helper to choose how to return result.
# If callback is provided it will be passed there.
# Otherwise error will be raised and result will be returned with a `return`
#
def make_response(err, resp, ret_blk, resp_blk)
err, resp = check_response(err, resp)
if err
if ret_blk
ret_blk.call(err, resp)
else
raise err
end
else
resp = resp_blk.call(resp) if resp_blk
if ret_blk
ret_blk.call(err, resp)
else
resp
end
end
end
# Blank result should be interpreted as an error. Ok so.
#
def check_response(err, data)
if err
[err, data]
elsif data.nil? || data.empty?
error = Monga::Exceptions::QueryFailure.new("Empty Response is not a valid Response")
[error, data]
else
[nil, data]
end
end
end
end | true |
a899c6f71c04cc4828912a5d7e2db8086965524f | Ruby | rhythm29/Bootcamp-Geometry | /lib/geometry/polygon.rb | UTF-8 | 164 | 3 | 3 | [
"MIT"
] | permissive | class Geometry::Polygon
def initialize(polygon)
@polygon = polygon
end
def perimeter
sum = 0
@polygon.each { |a| sum+=a }
return sum
end
end | true |
4461215d1bdaf97625e68572ff8c4485ae73aa1e | Ruby | h4hany/hackerrank-solution | /Service-Lane.rb | UTF-8 | 193 | 2.65625 | 3 | [] | no_license | # https://www.hackerrank.com/challenges/service-lane
(n, t) = gets.split.map{|i| i.to_i}
a = gets.split.map{|i| i.to_i}
t.times do
(i, j) = gets.split.map{|k| k.to_i}
puts a[i..j].min
end
| true |
5efceea8d91a48fa5d703f7ef253c0ad443de69a | Ruby | anthonyringoet/7-languages | /ruby/guess.rb | UTF-8 | 222 | 3.578125 | 4 | [] | no_license | $num = rand(10)
def ask
input = gets.to_i
eval(input)
end
def eval(input)
if input == $num
puts "Correct!"
return
end
if input < $num
puts "Too low"
else
puts "Too high"
end
ask
end
ask | true |
bca9f4426f54b9f33078e3bc90d172dd0908f097 | Ruby | InfinityG/myvinos-integration-api | /api/utils/rate_util.rb | UTF-8 | 366 | 2.59375 | 3 | [] | no_license | require './api/services/config_service'
module RateUtil
def self.convert_fiat_to_vin(fiat)
config = ConfigurationService.new.get_config
rate = config[:exchange_rate]
return fiat * rate
end
def self.convert_vin_to_fiat(vin)
config = ConfigurationService.new.get_config
rate = config[:exchange_rate]
return (vin / rate).to_i
end
end | true |
8fe533f66d3b515927548a7e8e3d3e74ec4cc9a9 | Ruby | snex/spiralizer | /spec/spiralizer/mover_spec.rb | UTF-8 | 1,183 | 2.90625 | 3 | [] | no_license | # frozen_string_literal: true
require 'spec_helper'
require_relative '../../lib/spiralizer/mover'
RSpec.describe Spiralizer::Mover do
subject { described_class.new(input) }
describe '#cursor_element' do
let(:input) { [%w[A B C], %w[D E F]] }
it 'is the element at the cursor' do
expect(subject.cursor_element).to eq('A')
subject.move!
expect(subject.cursor_element).to eq('B')
end
end
describe '#move!' do
let(:input) { [%w[A B C], %w[D E F]] }
it 'tries to move the cursor down' do
subject.instance_variable_set(:@cur_direction, :down!)
expect(subject).to receive(:down!)
subject.move!
end
it 'tries to move the cursor left' do
subject.instance_variable_set(:@cur_direction, :left!)
expect(subject).to receive(:left!)
subject.move!
end
it 'tries the cursor right' do
subject.instance_variable_set(:@cur_direction, :right!)
expect(subject).to receive(:right!)
subject.move!
end
it 'tries to move the cursor up' do
subject.instance_variable_set(:@cur_direction, :up!)
expect(subject).to receive(:up!)
subject.move!
end
end
end
| true |
094923583612c12ec133b3d8369c9f057ddfe043 | Ruby | cardmagic/dm-works | /lib/data_mapper/support/typed_set.rb | UTF-8 | 1,302 | 3.1875 | 3 | [
"MIT"
] | permissive | require 'set'
module DataMapper
module Support
class TypedSet
include ::Enumerable
def initialize(*types)
@types = types
@set = Array.new
end
def <<(item)
raise ArgumentError.new("#{item.inspect} must be a kind of: #{@types.inspect}") unless @types.any? { |type| type === item }
@set << item unless @set.include?(item)
return self
end
def concat(values)
[*values].each { |item| self << item }
self
end
def inspect
"#<DataMapper::Support::TypedSet#{@types.inspect}: {#{entries.inspect[1...-1]}}>"
end
def each
@set.each { |item| yield(item) }
end
def delete?(item)
@set.delete?(item)
end
def size
@set.size
end
alias length size
def empty?
@set.empty?
end
alias blank? empty?
def clear
@set.clear
end
def +(other)
x = self.class.new(*@types)
each { |entry| x << entry }
other.each { |entry| x << entry } unless other.blank?
return x
end
end
end
end
class Class
include Comparable
def <=>(other)
name <=> other.name
end
end | true |
d7ce41cf2d92531f88ccaf4f882bc09f4e7dd89d | Ruby | noisecape/Learn-Ruby-The-Hard-Way | /revenue.rb | UTF-8 | 164 | 3.375 | 3 | [] | no_license | puts "Please give me some money, I'll give you back 10""%"" of it"
money = gets.chomp.to_f
revenue = (money * 10)/100
puts "Thank you, here's your part: #{revenue}" | true |
c891db1352ca84c1dcce9dcc75f57c7526462480 | Ruby | flori/mize | /lib/mize/cache_methods.rb | UTF-8 | 1,408 | 2.625 | 3 | [
"MIT"
] | permissive | require 'mize/cache_protocol'
require 'mize/default_cache'
module Mize::CacheMethods
# Clear cached values for all methods/functions of this object.
def mize_cache_clear
__mize_cache__.clear
self
end
# Clear all cached results for the method/function +name+.
def mize_cache_clear_name(name)
name = build_key_prefix(name)
__mize_cache__.each_name do |n|
n =~ %r{\A#{Regexp.quote(name)}/} and __mize_cache__.delete(n)
end
self
end
private
# Set the cache object to +cache+.
def __mize_cache__=(cache)
Mize::CacheProtocol =~ cache
@__mize_cache__ = cache
end
# Return the cache object.
def __mize_cache__
if defined?(@__mize_cache__)
@__mize_cache__
else
self.__mize_cache__ = Mize.default_cache.prototype
end
end
# Build a key prefix for +name+.
def build_key_prefix(name)
"mize/#{name}"
end
# Build a +name+ prefixed key for the arguments +args+.
def build_key(name, *args)
"#{build_key_prefix(name)}/#{Marshal.dump(args)}"
end
# Apply the visibility of method +id+ to the wrapper method of this method.
def memoize_apply_visibility(id)
visibility = instance_eval do
case
when private_method_defined?(id)
:private
when protected_method_defined?(id)
:protected
end
end
yield
ensure
visibility and __send__(visibility, id)
end
end
| true |
08f531e06748fb0ce750aaa3fa0833adf02a1093 | Ruby | pla1207/opal | /spec/opal/core/numeric/downto_spec.rb | UTF-8 | 495 | 3.109375 | 3 | [
"MIT"
] | permissive | describe "Numeric#downto [stop] when self and stop are Fixnums" do
it "does not yield when stop is greater than self" do
result = []
5.downto(6) { |x| result << x }
result.should == []
end
it "yields once when stop equals self" do
result = []
5.downto(5) { |x| result << x }
result.should == [5]
end
it "yields while decreasing self until it is less than stop" do
result = []
5.downto(2) { |x| result << x }
result.should == [5, 4, 3, 2]
end
end | true |
b07f69331234f292cbe935ac36b91cba8be132b1 | Ruby | MargaretLangley/letting | /lib/tasks/import/import_properties.rake | UTF-8 | 1,023 | 2.640625 | 3 | [] | no_license | require 'csv'
require_relative '../../csv/csv_transform'
require_relative '../../import/file_header'
require_relative '../../import/import_property'
STDOUT.sync = true
#
# import_properties.rake
#
# Imports csv document and generates property objects.
#
# CSV files are converted into an 2D array indexed by row number
# and header symbols and passed to ImportProperty.import which
# builds and update Property objects.
#
namespace :db do
namespace :import do
desc 'Import properties data from CSV file'
task :properties, [:range] => :environment do |_task, args|
DB::ImportProperty.import staging_properties,
range: Rangify.from_str(args.range).to_i
end
# csv file => an array of arrays.
# Elements of the array are indexed by symbols taken
# from the row header.
#
def staging_properties
DB::CSVTransform.new(
file_name: 'import_data/staging/staging_properties.csv',
headers: DB::FileHeader.property).to_a
end
end
end
| true |
47eafd921e1523bfdf11d840476900bfd16622a5 | Ruby | MasatoraAtarashi/Programming-Competition | /AOJ/ALDS1/tree/BinaryTree.rb | UTF-8 | 1,628 | 3.515625 | 4 | [] | no_license | class Node
attr_accessor :id, :parent, :left, :right, :sibling, :degree, :height
def initialize()
@parent = -1
@sibling = -1
end
def set_info(id, left, right)
@id = id
@left = left
@right = right
@degree = [@left, @right].select {|c| c != -1}.count
end
def set_parent(parent_id)
@parent = parent_id
end
def set_sibling(sibling)
@sibling = sibling
end
def type?
if @parent == -1
return 'root'
elsif @left == -1 && @right == -1
return 'leaf'
else
return 'internal node'
end
end
end
n = gets.to_i
$nodes = Array.new(n).map{ Node.new() }
$depth = Array.new(n)
$height = Array.new(n, 0)
n.times do
id, left, right = gets.split.map(&:to_i)
$nodes[id].set_info(id, left, right)
if left != -1
$nodes[left].set_parent(id)
$nodes[left].set_sibling(right)
end
if right != -1
$nodes[right].set_parent(id)
$nodes[right].set_sibling(left)
end
end
def setDepth(u, d)
$depth[u] = d
if $nodes[u].right != -1
setDepth($nodes[u].right, d + 1)
end
if $nodes[u].left != -1
setDepth($nodes[u].left, d + 1)
end
end
def setHeight(u)
h1, h2 = 0, 0
if $nodes[u].right != -1
h1 = setHeight($nodes[u].right) + 1
end
if $nodes[u].left != -1
h2 = setHeight($nodes[u].left) + 1
end
$height[u] = [h1, h2].max
return [h1, h2].max
end
c = 0
while $depth.include?(nil)
setDepth(c, 0)
c += 1
end
setHeight(c - 1)
$nodes.each do |e|
puts "node #{e.id}: parent = #{e.parent}, sibling = #{e.sibling}, degree = #{e.degree}, depth = #{$depth[e.id]}, height = #{$height[e.id]}, #{e.type?}"
end
| true |
835b7538e09e8e3ff7a46da8b683c4ed7645e334 | Ruby | adparadise/rubylife | /board_spec.rb | UTF-8 | 893 | 3.203125 | 3 | [] | no_license | require 'rspec'
require_relative 'board'
require_relative 'cell'
describe Board do
let(:board) { Board.new }
it "should be able to get the cell at a location" do
cell = Cell.new 1, 1
board.add_cell cell
expect(board.get_cell_at(1, 1)).to eql(cell)
end
it "should be able to add a cell" do
cell = Cell.new 1, 1
board.add_cell cell
expect(board.cell_count).to eq(1)
end
it "should be able to count the number of cells around a location" do
cell_1 = Cell.new 1,2
cell_2 = Cell.new 1,1
cell_3 = Cell.new 1,9
board.add_cell (cell_1)
board.add_cell (cell_2)
board.add_cell (cell_3)
expect(board.number_of_cells_around(0,1)).to eq(2)
end
it "should remove a cell marked as dead" do
cell = Cell.new 1,2
board.add_cell (cell)
board.kill_cell(cell)
expect(board.get_cell_at(1, 2)).to eql(nil)
end
end
| true |
9cc4b77f7db4b5bbb617c05479401f02bde3acb1 | Ruby | nvnogomes/peuler | /179.rb | UTF-8 | 1,124 | 3.8125 | 4 | [] | no_license | require "mathn"
# Consecutive positive divisors
class Euler179
@limit
@array
@div_previous
def initialize(max=10000000)
@limit = max
@div_previous = 0
@array = Array.new
end
def solve_interval(ulimit,slimit)
counter = 0
ulimit.upto(slimit) do |x|
counter += consecutive_test(x,x.succ)
print "#{x}\n" if x.modulo(10000) == 0
end
counter
end
def solve_part1
1.upto(@limit).each do |number|
@array.push( number_of_divisors(number) )
end
return 1
end
def solve_part2
counter = 0
0.upto(@limit-1) do |index|
pair = @array[index,2]
counter += 1 if pair[0] == pair[1]
end
counter
end
def solve
counter = 0
1.upto(@limit) do |x|
counter += consecutive_test(x,x.succ)
puts x if x.modulo(100000) == 0
end
counter
end
def consecutive_test(a,b)
a_divs = @div_previous
b_divs = number_of_divisors(b)
@div_previous = b_divs
return a_divs == b_divs ? 1 : 0
end
def number_of_divisors(number)
factors = Prime.prime_division(number)
divisors = 1
factors.each do |factor,power|
divisors *= power+1
end
divisors
end
end
| true |
e678042f90b7f7a6d817e7f853cbb955307403a7 | Ruby | causes/spacecats | /lib/fixnum_ext.rb | UTF-8 | 171 | 2.859375 | 3 | [] | no_license | class Fixnum
def prime?
return false if self < 2
2.upto(Math.sqrt(self).to_i) do |div|
return false if self % div == 0
end
return true
end
end
| true |
ca0445dc8975bb3c6429afc057e352ce521c1a47 | Ruby | DesterStorm/oo-meowing-cat-online-web-ft-071519 | /lib/meowing_cat.rb | UTF-8 | 205 | 3.75 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Cat
def name=(name)
@name = name
end
def name
@name
end
attr_accessor :meow
def meow
@meow
puts"meow!"
end
end
maru = Cat.new
maru.name = "Maru"
maru.meow | true |
8a76e0189b261b1e33ec56b2ea0eacf188163d1f | Ruby | avalonmediasystem/avalon | /app/models/avalon_annotation.rb | UTF-8 | 2,929 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | # Copyright 2011-2023, The Trustees of Indiana University and Northwestern
# University. 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.
# --- END LICENSE_HEADER BLOCK ---
# An extension of the ActiveAnnotations gem to include Avalon specific information in the Annotation
# Sets defaults for the annotation using information from the master_file and includes solrization of the annotation
# @since 5.0.1
class AvalonAnnotation < ActiveAnnotations::Annotation
alias_method :title, :label
alias_method :title=, :label=
validates :master_file, :title, :start_time, presence: true
validates :start_time, numericality: {
greater_than_or_equal_to: 0,
less_than_or_equal_to: Proc.new { |a| a.max_time },
message: "must be between 0 and end of section"
}
after_initialize do
selector_default!
title_default!
end
# This function determines the max time for a masterfile and its derivatives
# Used for determining the maximum possible end time for an annotation
# @return [float] the largest end time or -1 if no durations present
def max_time
max = -1
max = master_file.duration.to_f if master_file.present? && master_file.duration.present?
if master_file.present?
master_file.derivatives.each do |derivative|
max = derivative.duration.to_f if derivative.present? && derivative.duration.present? && derivative.duration.to_f > max
end
end
max
end
# Sets the default selector to a start time of 0 and an end time of the master file length
def selector_default!
self.start_time = 0 if self.start_time.nil?
end
# Set the default title to be the label of the master_file
def title_default!
self.title = master_file.embed_title if self.title.nil? && master_file.present?
end
# Sets the class variable @master_file by finding the master referenced in the source uri
def master_file
@master_file ||= MasterFile.find(CGI::unescape(self.source.split('/').last)) rescue nil if self.source
end
def master_file=(value)
@master_file = value
self.source = @master_file
@master_file
end
# Calcuates the mediafragment_uri based on either the internal fragment value or start and end times
# @return [String] the uri with time bounding
def mediafragment_uri
"#{master_file&.rdf_uri}?#{internal.fragment_value.object}"
rescue
"#{master_file&.rdf_uri}?t=#{start_time},#{end_time}"
end
end
| true |
299eb39edd96dfdf82af89a72f997ec8471da03a | Ruby | faliev/stacked | /spec/support/matchers/within.rb | UTF-8 | 473 | 2.75 | 3 | [
"MIT"
] | permissive | module RSpec
module Matchers
class Within #:nodoc:
def initialize(receiver=nil, &block)
@receiver = receiver
# Placeholder
end
def matches?(time)
time = Time.at(time) if time.is_a?(Numeric)
@receiver.ago < time
end
def failure_message
"Expected time to be within #{@receiver.inspect}, but was not."
end
end
def be_within(receiver=nil)
Within.new(receiver)
end
end
end | true |
735063834db22213015a97559ee74af2eb82c7cc | Ruby | frograms/coolsms-rb | /test/test_send.rb | UTF-8 | 1,476 | 2.578125 | 3 | [
"MIT"
] | permissive | require 'test_helper'
require 'minitest/autorun'
module Coolsms
class TestSend < Minitest::Test
def test_single
skip('캐시가 차감되서 막아놓음')
msg = Coolsms::Message.new
msg.text = '안녕, 세계 ㅎㅎ'
result = msg.send(COOLSMS_TEST_RECEIVERS.first)
assert_equal 1, result.body['success_count']
sleep(10) # 보내는데 걸리는 시간
sent = msg.group.first
assert_equal '00', sent.result_code
end
def test_single_class_method
skip('캐시가 차감되서 막아놓음')
msg = Coolsms.message("안녕이라고\n말하지마", COOLSMS_TEST_RECEIVERS.first)
sleep(10) # 보내는데 걸리는 시간
sent = msg.group.first
assert_equal '00', sent.result_code
end
def test_wrong_number
skip('오래걸려서 스킵')
msg = Coolsms::Message.new
msg.text = '거기누구없소'
result = msg.send('01911')
assert_equal 1, result.body['success_count']
sleep(30) # 보내는데 걸리는 시간
sent = msg.group.first
assert_equal '58', sent.result_code
end
def test_long_single
msg = Coolsms::Message.new
msg.text = Forgery(:lorem_ipsum).words(3)
result = msg.send(COOLSMS_TEST_RECEIVERS.first)
assert_equal 1, result.body['success_count']
sleep(10)
sent = msg.group.first
assert_equal '00', sent.result_code
assert_equal 'LMS', sent.type
end
end
end
| true |
581f5255b4d95a441a3f36fdb15e762f8cf865ba | Ruby | buildwithaura/aura | /lib/aura/tasks/common.rb | UTF-8 | 379 | 2.53125 | 3 | [
"MIT"
] | permissive | class RakeStatus
def self.heading(what, status)
if what == :run
color = 30
puts "\033[1;#{color}m$ %s \033[0m" % [status]
return
end
puts "* %s" % [status]
end
def self.print(what, status)
color = 32
color = 31 if what == :error
what = "" if what == :info
puts "\033[1;#{color}m %-14s\033[0m %s" % [what, status]
end
end
| true |
561f1fc5d3a2f1b7660d5e765093d1fb66228e85 | Ruby | JosephBianchi/emotions | /exc1.rb | UTF-8 | 643 | 3.921875 | 4 | [] | no_license |
class Person
def initialize(name)
@name = name
@emotions = {
sad: rand(1..3),
happy: rand(1..3),
angry: rand(1..3),
fear: rand(1..3),
joy: rand(1..3),
disgust: rand(1..3)
}
end
# test initialize method
def level(num)
if num == 1
return "low"
elsif num == 2
return "medium"
else
return "high"
end
end
def display
@emotions.each do |emotion, num|
p "I am feeling a #{level(num)} amount of #{emotion}"
end
end
end
joe = Person.new("joe")
p joe
joe.display
john = Person.new("john")
p john
#
# joe = Person.new("joe", emotions)
| true |
5c97a1a7f6e05f1f191d3e5e09814856f57242c0 | Ruby | mhickman84/redex | /lib/redex/document_type.rb | UTF-8 | 922 | 2.96875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | module Redex
# Type of document to be parsed
class DocumentType
include Helper::ActsAsParent
include Helper::ActsAsType
# Unique name of the type of document containing the content to be extracted (letter, resume, etc).
attr_reader :name
# Path where this type of document is stored
attr_accessor :load_path
# Accepts a unique name
def initialize name
@name = name
yield self if block_given?
end
def level
0
end
# Retrieves a child section or content type by name (takes a symbol)
def find_type child_type_name
type_match = nil
traverse do |type|
type_match = type if type.name == child_type_name
end
type_match
end
# Returns the document type object associated with the supplied name
def self.get name
Redex.document_types[name] || raise("Document type: #{name} has not been defined")
end
end
end | true |
435c35dd53d5705d0bf0fe2c8d7b4f660ed07deb | Ruby | mfirmanakbar/hacker-rank | /06.rb | UTF-8 | 548 | 3.328125 | 3 | [] | no_license |
require 'json'
require 'stringio'
def compareTriplets(a, b)
result = []
alice = 0
bob = 0
for i in (0..2) do
if a[i] > b[i]
alice = alice + 1
elsif a[i] < b[i]
bob = bob + 1
end
end
result.push(alice)
result.push(bob)
return result
end
# fptr = File.open(ENV['OUTPUT_PATH'], 'w')
fptr = File.open('OUTPUT_PATH.txt', 'w')
a = gets.rstrip.split.map(&:to_i)
b = gets.rstrip.split.map(&:to_i)
result = compareTriplets(a, b)
puts result.join(" ")
fptr.write result.join(" ")
fptr.write "\n"
fptr.close()
| true |
4d4dcd02211b9f9addcf1942eb09c8db23529fd4 | Ruby | DanielleSucher/Greenland | /spec/input_faker.rb | UTF-8 | 359 | 2.953125 | 3 | [] | no_license | # for testing, via http://vcp.lithium3141.com/2011/04/advanced-rspec/
class InputFaker
def initialize(strings)
@strings = strings
end
def gets
next_string = @strings.shift
next_string
end
def self.with_fake_input(strings)
$stdin = new(strings)
yield
ensure
$stdin = STDIN
end
end | true |
58563b2101378063df7e6494687e85e1674c08e4 | Ruby | Lithnotep/war_or_peace | /test/turn_test.rb | UTF-8 | 11,665 | 3.03125 | 3 | [] | no_license | require 'minitest/autorun'
require 'minitest/pride'
require './lib/player'
require './lib/deck'
require './lib/card'
require './lib/turn'
require 'pry'
class TurnTest < Minitest::Test
def test_it_exists
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, '9', 9)
card4 = Card.new(:diamond, 'Jack', 11)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, 'Queen', 12)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
deck1 = Deck.new([card1, card2, card5, card8])
deck2 = Deck.new([card3, card4, card6, card7])
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
assert_instance_of Turn, turn
end
def test_it_has_players
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, '9', 9)
card4 = Card.new(:diamond, 'Jack', 11)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, 'Queen', 12)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
deck1 = Deck.new([card1, card2, card5, card8])
deck2 = Deck.new([card3, card4, card6, card7])
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
assert_equal turn.player1.name, "Megan"
assert_equal turn.player2.name, "Aurora"
end
def test_spoils_array_exists
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, '9', 9)
card4 = Card.new(:diamond, 'Jack', 11)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, 'Queen', 12)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
deck1 = Deck.new([card1, card2, card5, card8])
deck2 = Deck.new([card3, card4, card6, card7])
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
assert_equal [],turn.spoils_of_war
end
def test_turn_type_can_basic
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, '9', 9)
card4 = Card.new(:diamond, '10', 10)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, 'Queen', 12)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
deck1 = Deck.new([card1, card2, card5, card8])
deck2 = Deck.new([card3, card4, card6, card7])
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
assert_equal true, turn.player1.deck.cards[1].rank == turn.player2.deck.cards[1].rank
assert_equal false, turn.player1.deck.cards[0].rank == turn.player2.deck.cards[0].rank
assert_equal true, turn.player1.deck.rank_of_card_at(1) == turn.player2.deck.rank_of_card_at(1)
assert_equal false, turn.player1.deck.rank_of_card_at(0) == turn.player2.deck.rank_of_card_at(0)
end
def test_can_read_as_basic
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, '9', 9)
card4 = Card.new(:diamond, '10', 10)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, 'Queen', 12)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
deck1 = Deck.new([card1, card2, card5, card8])
deck2 = Deck.new([card3, card4, card6, card7])
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
assert_equal :basic, turn.type
end
def test_can_read_as_war
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, 'Jack', 11)
card4 = Card.new(:diamond, '10', 10)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, 'Queen', 12)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
deck1 = Deck.new([card1, card2, card5, card8])
deck2 = Deck.new([card3, card4, card6, card7])
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
assert_equal :war, turn.type
end
def test_can_have_winner_1
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, '9', 9)
card4 = Card.new(:diamond, 'Jack', 11)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, 'Queen', 12)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
deck1 = Deck.new([card1, card2, card5, card8])
deck2 = Deck.new([card3, card4, card6, card7])
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
assert_equal "Megan", turn.player1.name
assert_equal "Aurora", turn.player2.name
assert_equal [], turn.spoils_of_war
assert_equal :basic, turn.type
assert_equal player1, turn.winner
end
def test_can_have_winner_2
card1 = Card.new(:heart, '3', 3)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, '9', 9)
card4 = Card.new(:diamond, 'Jack', 11)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, 'Queen', 12)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
deck1 = Deck.new([card1, card2, card5, card8])
deck2 = Deck.new([card3, card4, card6, card7])
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
assert_equal "Megan", turn.player1.name
assert_equal "Aurora", turn.player2.name
assert_equal [], turn.spoils_of_war
assert_equal :basic, turn.type
assert_equal player2, turn.winner
end
def test_can_winner_war
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, 'Jack', 11)
card4 = Card.new(:diamond, 'Jack', 11)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, 'Queen', 12)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
deck1 = Deck.new([card1, card2, card5, card8])
deck2 = Deck.new([card3, card4, card6, card7])
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
assert_equal "Megan", turn.player1.name
assert_equal "Aurora", turn.player2.name
assert_equal [], turn.spoils_of_war
assert_equal :war, turn.type
assert_equal player2, turn.winner
end
def test_can_winner_war_2
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, 'Jack', 11)
card4 = Card.new(:diamond, 'Jack', 11)
card5 = Card.new(:heart, 'King', 13)
card6 = Card.new(:diamond, 'Queen', 12)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
deck1 = Deck.new([card1, card2, card5, card8])
deck2 = Deck.new([card3, card4, card6, card7])
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
assert_equal "Megan", turn.player1.name
assert_equal "Aurora", turn.player2.name
assert_equal [], turn.spoils_of_war
assert_equal :war, turn.type
assert_equal player1, turn.winner
end
def test_pile_cards
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, '9', 9)
card4 = Card.new(:diamond, 'Jack', 11)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, 'Queen', 12)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
deck1 = Deck.new([card1, card2, card5, card8])
deck2 = Deck.new([card3, card4, card6, card7])
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
assert_equal "Megan", turn.player1.name
assert_equal "Aurora", turn.player2.name
assert_equal [], turn.spoils_of_war
assert_equal :basic, turn.type
assert_equal player1, turn.winner
turn.pile_cards
assert_equal [card1, card3], turn.spoils_of_war
end
def test_mutually_assured_destruction_type
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, 'Jack', 11)
card4 = Card.new(:diamond, 'Jack', 11)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, '8', 8)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
deck1 = Deck.new([card1, card2, card5, card8])
deck2 = Deck.new([card3, card4, card6, card7])
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
assert_equal "Megan", turn.player1.name
assert_equal "Aurora", turn.player2.name
assert_equal [], turn.spoils_of_war
assert_equal :mutually_assured_destruction, turn.type
end
def test_mutually_assured_destruction_pile
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, 'Jack', 11)
card4 = Card.new(:diamond, 'Jack', 11)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, '8', 8)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
deck1 = Deck.new([card1, card2, card5, card8])
deck2 = Deck.new([card3, card4, card6, card7])
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
assert_equal "Megan", turn.player1.name
assert_equal "Aurora", turn.player2.name
assert_equal [], turn.spoils_of_war
assert_equal :mutually_assured_destruction, turn.type
assert_equal "No Winner", turn.winner
turn.pile_cards
assert_equal [card8], turn.player1.deck.cards
assert_equal [card7], turn.player2.deck.cards
end
def test_award_spoils
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, '9', 9)
card4 = Card.new(:diamond, 'Jack', 11)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, 'Queen', 12)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
deck1 = Deck.new([card1, card2, card5, card8])
deck2 = Deck.new([card3, card4, card6, card7])
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
assert_equal "Megan", turn.player1.name
assert_equal "Aurora", turn.player2.name
assert_equal [], turn.spoils_of_war
assert_equal :basic, turn.type
assert_equal player1, turn.winner
winner = turn.winner
turn.pile_cards
assert_equal [card1, card3], turn.spoils_of_war
turn.award_spoils(winner)
assert_equal 5, player1.deck.cards.count
end
def test_mutually_assured_destruction_award
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, 'Jack', 11)
card4 = Card.new(:diamond, 'Jack', 11)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, '8', 8)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
deck1 = Deck.new([card1, card2, card5, card8])
deck2 = Deck.new([card3, card4, card6, card7])
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
assert_equal [], turn.spoils_of_war
assert_equal :mutually_assured_destruction, turn.type
winner = turn.winner
turn.pile_cards
assert_equal "No Winner", turn.winner
end
end
| true |
cee35bef0abb4d85e1fd51b9e16bd6098a1c50c5 | Ruby | ravichandran1/text | /arrayprocessor.rb | UTF-8 | 618 | 3.34375 | 3 | [] | no_license | class ArrayProcessor
attr_reader :array
def initialize
@array = [20, 4, 2, 40]
end
def add_total
array.inject(:+)
end
def acending_order
array.sort
end
def descending_order
array.sort.reverse
end
def minimum_value
array.min
end
def maximum_value
array.max
end
end
array=ArrayProcessor.new
puts array.add_total.inspect
array=ArrayProcessor.new
puts array.acending_order.inspect
array=ArrayProcessor.new
puts array.descending_order.inspect
array=ArrayProcessor.new
puts array.maximum_value.inspect
array=ArrayProcessor.new
puts array.minimum_value.inspect | true |
00610154124989a06498d980b32cf09cdabc10fc | Ruby | tkameyamax/bonus-drink | /triangle.rb | UTF-8 | 1,071 | 4.46875 | 4 | [] | no_license | # コマンドライン引数
x = ARGV[0].to_i
y = ARGV[1].to_i
z = ARGV[2].to_i
class Triangle
# 三角形である |x - y| < z && z < x + y
# 正三角形判定 x == y && y == z (三辺が同じ値である)
# 二頭編三角形判定 x == y || y == z || z == y (二辺が同じ値である、三辺が同じ値である場合は正三角形であるが先に正三角形の判定をすることで条件からはずす)
# 不等辺三角形 x !=y && y != z && z != x (三辺が同じ値ではない)
# 三角形の判定をまずする falseならば => 三角形ではないです!
# 三角形ならば各種の判定をする
def self.triangle(x, y, z)
if ((x - y).abs < z) && (z < (x + y))
if (x == y) && (y == z)
"正三角形ですね!"
elsif (x == y) || (y == z) || (z == x)
"二等辺三角形ですね!"
elsif (x != y) && (y != z) && (z != x)
"不等辺三角形ですね!"
end
else
"三角形じゃないです><"
end
end
end
puts Triangle.triangle(x,y,z)
| true |
2b6036d4febd485324d5a2e3050172ae3fe8233f | Ruby | nyc-rock-doves-2016/linear_vs_binary_search | /binary_search.rb | UTF-8 | 493 | 3.296875 | 3 | [] | no_license | def find(target, dataset)
## Base case: We find the target in the dataset
midpoint = dataset.length / 2
comparitor = dataset[midpoint]
return false if comparitor.nil?
if target == comparitor
true
elsif target > comparitor
## We are too big - take the right side of the array
find(target, dataset[midpoint + 1 ... dataset.length])
elsif target < comparitor
## We are too small - take the left side of the array
find(target, dataset[0 ... midpoint])
end
end
| true |
d4701ab10d92da04c79197d44c089224bb58e94e | Ruby | igaiga/ruby266_refactoring | /be_dry2/bad.rb | UTF-8 | 373 | 2.9375 | 3 | [] | no_license | class Book
attr_accessor :author
end
class Circle
attr_accessor :radius # radius: 半径
end
def set_book_author_and_circle_radius(book, circle)
book.author = "matz"
circle.radius = 3
end
book = Book.new
circle = Circle.new
set_book_author_and_circle_radius(book, circle)
# ...
book = Book.new
circle = Circle.new
set_book_author_and_circle_radius(book, circle)
| true |
47e5a1a5cf4be25a7ea33c42b1582aa13c1b4c8e | Ruby | calamitas/savon | /lib/savon/core_ext/string.rb | UTF-8 | 1,313 | 2.8125 | 3 | [
"MIT"
] | permissive | require "savon/soap"
module Savon
module CoreExt
module String
# Returns the String in snake_case.
def snakecase
str = dup
str.gsub! /::/, '/'
str.gsub! /([A-Z]+)([A-Z][a-z])/, '\1_\2'
str.gsub! /([a-z\d])([A-Z])/, '\1_\2'
str.tr! ".", "_"
str.tr! "-", "_"
str.downcase!
str
end
# Returns the String in lowerCamelCase.
def lower_camelcase
str = dup
str.gsub!(/\/(.?)/) { "::#{$1.upcase}" }
str.gsub!(/(?:_+|-+)([a-z])/) { $1.upcase }
str.gsub!(/(\A|\s)([A-Z])/) { $1 + $2.downcase }
str
end
# Returns whether the String starts with a given +prefix+.
def starts_with?(prefix)
prefix = prefix.to_s
self[0, prefix.length] == prefix
end unless defined? starts_with?
# Returns the String without namespace.
def strip_namespace
split(":").last
end
# Translates SOAP response values to Ruby Objects.
def map_soap_response
return ::DateTime.parse(self) if Savon::SOAP::DateTimeRegexp === self
return true if self.strip.downcase == "true"
return false if self.strip.downcase == "false"
self
end
end
end
end
String.send :include, Savon::CoreExt::String
| true |
7fbcc51bd5c6453ee464f0df4f2678a079cb3489 | Ruby | mjording/prime_8 | /lib/prime_8/strategies/atkin_sieve_strategy.rb | UTF-8 | 2,717 | 3.390625 | 3 | [] | no_license | require_relative 'strategy'
module Prime8::Strategies
class AtkinSieveStrategy < Strategy
def initialize
@first_set = %w(1 13 17 29 37 41 49 53).map(&:to_i)
@second_set = %w(7 19 31 43).map(&:to_i)
@third_set = %w(11 23 47 59).map(&:to_i)
super
end
def compute_primes
max_segment_size = 1e6.to_i
max_cached_prime = @primes.last
@max_checked = max_cached_prime + 1 if max_cached_prime > @max_checked
segment_min = @max_checked
segment_max = [segment_min + max_segment_size, max_cached_prime * 2].min
((segment_min + 1) .. segment_max).step(2).each do |candidate|
remainder = candidate % 60
if @first_set.include?(remainder)
candidate_is_prime = first_quadratic_form(candidate)
elsif @second_set.include?(remainder)
candidate_is_prime = second_quadradic_form(candidate)
elsif @third_set.include?(remainder)
candidate_is_prime = third_quadradic_form(candidate)
end
if candidate_is_prime && !has_prime_divisor?(candidate)
@primes << candidate
end
end
@max_checked = segment_max
end
private
def has_prime_divisor?(candidate)
@primes.any? { |prime| candidate % prime == 0 }
end
def first_quadratic_form(n)
candidate_is_prime = false
x_limit = n >> 2
for x in (1..x_limit)
break if ((memoized_x = 4*x**2) && (memoized_x >= n))
for y in (1..n)
break if ((memoized_y = y**2) && (memoized_y >= n))
candidate = memoized_x + memoized_y
next unless (candidate == n)
if ((candidate%12 == 1) || (candidate%12 == 5))
candidate_is_prime = !candidate_is_prime
end
end
end
candidate_is_prime
end
def second_quadradic_form(n)
candidate_is_prime = false
x_limit = n >> 1
for x in (1..x_limit)
break if ((memoized_x = 3*x**2) && (memoized_x >= n))
for y in (1..n)
break if ((memoized_y = y**2) && (memoized_y >= n))
candidate = memoized_x + memoized_y
next unless (candidate == n)
if (candidate%12 == 7)
candidate_is_prime = !candidate_is_prime
end
end
end
candidate_is_prime
end
def third_quadradic_form(n)
candidate_is_prime = false
for x in (1..n)
break if (x**2 >= n)
for y in (1...x)
candidate = 3*x**2 - y**2
next unless candidate == n
if candidate > 0 && candidate%12 == 11
candidate_is_prime = !candidate_is_prime
end
end
end
candidate_is_prime
end
end
end
| true |
2d3da7d766c592a9651ff9065b3b6522ef52ea6f | Ruby | Daatwood/chesscli | /lib/chess/pieces/knight.rb | UTF-8 | 283 | 2.703125 | 3 | [] | no_license | # frozen_string_literal: true
module Chess
# Can move to positions based on an L-shape
class Knight < Piece
def movement_set
{ offset: [
[-1, 2], [1, 2],
[-2, 1], [2, 1],
[-2, -1], [2, -1],
[-1, -2], [1, -2]
] }
end
end
end
| true |
ecc710877bd69999b47d11711b7facbe9b5f47d7 | Ruby | ashitani0803/atcoder | /a_question/round_up_the_mean.rb | UTF-8 | 122 | 3.34375 | 3 | [] | no_license | a, b = gets.strip.split.map(&:to_i)
# x = (a + b) / 2.to_f
# puts x % 1 == 0 ? x.to_i : x.to_i + 1
puts (a + b + 1) / 2 | true |
4bcc27b91bb7f7f074f6208c2728a3f27e69ef3d | Ruby | JCFlores93/devops-eduonix | /scripting/ruby/ruby_essentials.rb | UTF-8 | 1,061 | 3.546875 | 4 | [] | no_license | #!/usr/bin/ruby
puts "Hello world!"
print "Hello world\n"
myname = "Jean"
puts "My name is #{myname}"
printf "My name is %s\n", myname
printf "We are learning %d languages \n", 3
# puts %q{Her pet's name is Kenzy and she loves "Drawing"}
# usernames = ['jdoe', 'peter', 'mary', 'bob']
# Hash
# usernames = {
# "name" => "jdoe",
# "age" => 31,
# "job" => "DevOps Engineer",
# }
usernames = [
{
:name => "jdoe",
:age => 31,
:job => "DevOps Engineer",
},
{
:name => "linda",
:age => 25,
:job => "sysadmin",
},
{
:name => "bob",
:age => 29,
:job => "dev",
},
{
:name => "mark",
:age => 35,
:job => "tester",
}
]
puts usernames[0][:name]
usernames.each do |u|
puts "#{u[:name]}: #{u[:age]}"
end
langs = {
:name => "compiled",
:examples => ["C", "C++", "C#", "Java"]
}
langs[:examples].each do |l|
puts "Language name is #{l}"
end
# Modules
require "./myfunctions"
require "json"
MyFunctions.sayHello
content = File.read("file.json")
info = JSON.parse(content)
puts info["name"] | true |
d302bdcbcaf68a62d7d5019af90d9c0dea437b0b | Ruby | jacob-hudson/ProjectEuler | /ruby/33-digit-cancelling.rb | UTF-8 | 591 | 3.25 | 3 | [] | no_license | #!/usr/bin/env ruby
numerator_product, denominator_product = 1, 1
(10..98).each do |n|
(n+1..99).each do |d|
next if n % 10 == 0 && d & 10 == 0
if (n.to_s[0] == d.to_s[1] && n.to_s[1] < d.to_s[0])
fraction_as_float = Float(n.to_s[1]) / Float(d.to_s[0])
elsif (n.to_s[1] == d.to_s[0] && n.to_s[0] < d.to_s[1])
fraction_as_float = Float(n.to_s[0]) / Float(d.to_s[1])
else
next
end
if (Float(n) / Float(d) == fraction_as_float)
numerator_product*=n
denominator_product*=d
end
end
end
puts denominator_product / numerator_product
| true |
bde787666926a65a4d026509ec25abe4aed607cb | Ruby | Volsunga-Saga1260/bookers3 | /ruby/hello.rb | UTF-8 | 108 | 3.484375 | 3 | [] | no_license | for i in 1..20000
if i % 3 == 0 || i.to_s.include?("3")
puts "Chanmei!"
else
puts i
end
end | true |
b25ca682c7a25123e7dbdde2778a4ef305e0ede1 | Ruby | GCHwee/The_Well_Grounded_Rubyist | /ruby_dynamics/callable_and_runnable_objects/determinations.rb | UTF-8 | 478 | 3.359375 | 3 | [] | no_license | puts
p 'Proc objects are self-contained code sequences that you can create, store, pass around as
method arguments, and, when you wish, execute with the call method. Lambdas are similar to Proc
objects. Truth be told, a lambda is a Proc object, but one with slightly special internal engineering.
The differences will emerge as we examine each in turn. Method objects represent methods extracted
into objects that you can, similarly, store, pass around, and execute.'
puts | true |
8260468e99e87ad9822fba7c0eac1db96b7a5b19 | Ruby | deshpandirolf/funnytube | /funnytube.rb | UTF-8 | 1,464 | 2.625 | 3 | [] | no_license | require "rubygems"
require "bundler/setup"
require 'youtube_g'
require 'mongo'
require 'sinatra'
include Mongo
class FunnyTube
class << self
def coll
@@coll ||= Connection.new.db('funnytube').collection('videos')
end
def youtube
@@youtube ||= YouTubeG::Client.new
end
def update_score(id, delta)
coll.update({ :_id => id }, {"$inc" => delta})
end
def upvote(id)
update_score(id, 1)
end
def downvote(id)
update_score(id, -1)
end
def id_for_url(url)
md = url.match(/youtube\.com.*\?v=([\w-]+)/)
md ||= url.match(/youtube\.com\/v\/([\w-]+)/)
begin
md[1]
rescue
raise "ERROR: Could not parse youtube video URL."
end
end
def top_videos
coll.find({}, :limit => 10, :sort => [[:score, :desc]])
end
end
end
set :views, File.dirname(__FILE__) + '/templates'
set :public, File.dirname(__FILE__) + '/static'
before do
if request.cookies["u"].nil?
response.set_cookie('u', Digest::MD5.hexdigest(Time.now.to_i.to_s + request.referer))
end
end
post '/submit' do
video_id = FunnyTube.id_for_url(params[:v])
title = FunnyTube.youtube.video_by(video_id).title
FunnyTube.coll.save({:_id => video_id,
:user_id => request.cookies["u"],
:title => title,
:score => 0})
redirect '/'
end
get '/' do
@videos = FunnyTube.top_videos
erb :index
end
| true |
34e1f97b64ad5eb48c5b193b98d048045a436789 | Ruby | isabella232/index-content-in-guide-action | /lib/record_list.rb | UTF-8 | 853 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | class RecordList
include Enumerable
def initialize(api:, logger:)
@api = api
@logger = logger
end
def each(&block)
cursor = nil
while true
@logger.debug "Fetching records starting at cursor #{cursor}"
response = @api.list_records(cursor: cursor)
response
.fetch("records")
.select {|data| data.fetch("source").fetch("id") == EXTERNAL_CONTENT_SOURCE_ID }
.select {|data| data.fetch("type").fetch("id") == EXTERNAL_CONTENT_TYPE_ID }
.map {|data| SearchRecord.new(data) }
.each(&block)
meta = response.fetch("meta")
if meta.fetch("has_more")
cursor = meta.fetch("after_cursor")
@logger.debug "More records available, cursor = #{cursor}"
else
@logger.debug "No more records available"
break
end
end
end
end
| true |
1d5c17ded169112190aa7cd37c0a53bf24de751e | Ruby | achiu8/team_violet | /source/model.rb | UTF-8 | 721 | 3.34375 | 3 | [] | no_license | class Card
attr_reader :definition, :answer
attr_accessor :attempts
def initialize(args)
@definition = args[:definition]
@answer = args[:answer]
@attempts = 0
end
end
module Model
def self.save_cards(file_path)
# returns an array of values from file [definition1, answer1, definition, answer2]
File.readlines(file_path).each do |line|
line.gsub!("\n",'') #remove line breaks
end.select{|line| line != ""} # select only non-empty lines
end
def self.get_cards(file_path)
card_objects = []
card_array = Model.save_cards(file_path)
card_array.each_slice(2).to_a.each{|pair| card_objects << Card.new(Hash[[:definition,:answer].zip(pair)])}
card_objects
end
end
| true |
d6da1353becfbd4bf0030f7f6e46984d2dd53d9d | Ruby | ElectronVector/greatest-fff | /rakefile.rb | UTF-8 | 5,177 | 2.71875 | 3 | [
"MIT"
] | permissive |
load 'test_runner.rb'
CONFIG = {
:test_dir => "test",
:source_dir => "src",
:build_dir => "build",
# Use .exe for running on windows/Cygwin, use an empty string for Linux.
:test_binary_extension => ".exe",
}
# Set this to true to echo the commands to stdout.
verbose(false)
# Extract the lists of files that we're going to work with from the configured
# directories.
TEST_FILES = FileList["#{CONFIG[:test_dir]}/**/test_*.c"]
SOURCE_FILES = FileList["#{CONFIG[:source_dir]}/**/*.c"]
# This is the path where object files go. The object files built under here
# mirror the structure of the source folder.
OBJECT_DIR = "#{CONFIG[:build_dir]}/obj"
# This is where the executable binary test files go.
BIN_DIR = "#{CONFIG[:build_dir]}/bin"
# This is where the test runners go.
RUNNER_DIR = "#{CONFIG[:build_dir]}/runners"
# For a given source file, get the corresponding object file (including the path).
def source_file_to_object_file source_file
source_file.pathmap("#{OBJECT_DIR}/%X.o")
end
# Remove the leading test folder name and the extension. The test name the full path
# to the test (below the test folder) withoug the extenstion, and with the "test_"
# prefix removed.
def get_test_name_from_full_path test_file
test_file.pathmap("%{^test,}d/%{^test_,}n").sub(/^\//, '') # Remove leading slash.
end
# Get the name of the test runner source file we will create for the test file.
def get_test_runner_source_file_from_test_file test_file
test_file.pathmap("#{RUNNER_DIR}/%{^test/,}X_runnner.c")
end
# Get the name of the test runner object file we will create for the test file.
def get_test_runner_object_file_from_test_file test_file
get_test_runner_source_file_from_test_file(test_file).ext(".o")
end
# Scan the test source file for a list of the source files under test.
def get_build_file_list_from_test test_source_file
# For now, assume the only file under test corresponds to the test name.
# TODO: Scan the test file for stuff to include.
build_file_list = "#{CONFIG[:source_dir]}/#{get_test_name_from_full_path(test_source_file)}.c"
build_file_list = source_file_to_object_file(build_file_list)
FileList[build_file_list]
end
# Create a file task for generating an object file from a source file.
def create_compile_task source_file
object_file = source_file_to_object_file source_file
desc "Build #{object_file} from #{source_file}"
file object_file => source_file do
# Compile here
mkdir_p object_file.pathmap("%d")
puts "Compiling #{source_file}..."
puts " to #{object_file}"
sh "gcc -c -I#{CONFIG[:source_dir]} -Ivendor/greatest #{source_file} -o #{object_file}"
end
end
# Create a task for running a particular test file.
def create_test_task test_file
name = get_test_name_from_full_path(test_file)
# Scan the test source file for a list of the source files under test.
build_file_list = get_build_file_list_from_test(test_file)
# The full path to the corresponding test binary.
test_binary = "#{BIN_DIR}/#{name}#{CONFIG[:test_binary_extension]}"
# Create an executable test binary by linking together the object files for the requested source files.
file test_binary => build_file_list do |task|
mkdir_p test_binary.pathmap("%d")
puts "Linking #{task.name}..."
puts " from #{task.sources.join(', ')}"
sh "gcc #{task.sources.join(' ')} -o #{task.name}"
end
# Each test binary also depends on the object file for the test itself.
file test_binary => source_file_to_object_file(test_file)
# Each test binary also depends on the test runner object file for this test.
file test_binary => get_test_runner_object_file_from_test_file(test_file)
# Each test runner object is dependent upon it source file.
file get_test_runner_object_file_from_test_file(test_file) => get_test_runner_source_file_from_test_file(test_file)
desc "Test #{name}"
task name => test_binary do | task |
# Run the compiled test binary.
puts "Executing test by running #{task.source}..."
puts %x{./#{task.source}}
end
end
# Create a test runner source file from the test file.
def create_test_runner_task test_file
test_runner_file = get_test_runner_source_file_from_test_file(test_file)
file test_runner_file => test_file do
create_test_runner(test_file, test_runner_file)
end
end
namespace :test do
# Create a task for running each test.
TEST_FILES.each do |file|
create_test_task file
create_test_runner_task file
end
end # namespace :test
# Create file tasks for creating a corresponding object file for each source file.
SOURCE_FILES.each do |file|
create_compile_task file
end
# Each of the test files needs to be compiled too.
TEST_FILES.each do |file|
create_compile_task file
end
task :clean do
rm_rf CONFIG[:build_dir]
end
task :default do
puts
puts "Test Files"
puts "------------"
puts TEST_FILES
puts
puts "Source Files"
puts "------------"
puts SOURCE_FILES
puts
end
| true |
cc6020eef7145af28de61424bf6db0ea220e9e4e | Ruby | EmC14/5calculatorprgm | /sales tax.rb | UTF-8 | 123 | 2.984375 | 3 | [] | no_license | puts "Subtotal?"
a = gets.to_f
puts "tax/intrest rate?"
b = gets.to_f
total = a*b + a
puts "Total amount in $"
puts total
| true |
38cf29356947e30911dd850bd7efafb5674aa285 | Ruby | dgsuarez/similatron | /lib/similatron/pdf_comparison_engine.rb | UTF-8 | 1,040 | 2.5625 | 3 | [
"MIT"
] | permissive | module Similatron
class PdfComparisonEngine < ComparisonEngine
def can_handle_mime?(mime_type)
mime_type =~ %r{application/pdf}
end
def compare(expected:, actual:)
jpg_comparison = jpg_compare(expected: expected, actual: actual)
Comparison.new(
expected: expected,
actual: actual,
score: jpg_comparison.score,
diff: jpg_comparison.diff
)
end
private
def image_magick_engine
ImagemagickComparisonEngine.new(
executable_path: given_executable_path,
diffs_path: diffs_path
)
end
def jpg_compare(expected:, actual:)
Dir.mktmpdir do |dir|
jpg_expected = "#{dir}/expected.jpg"
jpg_actual = "#{dir}/actual.jpg"
convert(expected, jpg_expected)
convert(actual, jpg_actual)
image_magick_engine.compare(
expected: jpg_expected,
actual: jpg_actual
)
end
end
def convert(pdf, jpg)
`convert -append #{pdf} #{jpg}`
end
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.