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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
72774fba6c53ac93922eec9421fd8be8f622ca22 | Ruby | macZombie/R-PiPanTilt | /I2C/gpio.rb | UTF-8 | 2,323 | 2.671875 | 3 | [] | no_license | class GPIO < I2CExpander
def initialize(name,channel,address)
super(name,channel,address)
return
end
end ; # end of class GPIO
class GPIOA < GPIO
IODIR = 0
IPOL = 2
GPINTEN = 4
DEFVAL = 6
INTCON = 8
IOCON = 10
GPPU = 12
INTF = 14
INTCAP = 16
GPIO = 18
OLAT = 20
def initialize(name,channel,address)
super(name,channel,address)
return
end
def enable
write(IODIR,0)
return
end
def disable
write(IODIR,255)
return
end
def set(value)
write(GPIO,value)
return
end
def get
result = read(GPIO)
return result
end
def pullupsOn
write(GPPU,255)
return
end
def pullupsOff
write(GPPU,0)
return
end
end ; # of class GPIOA
class GPIOB < GPIO
IODIR = 1
IPOL = 3
GPINTEN = 5
DEFVAL = 7
INTCON = 9
IOCON = 11
GPPU = 13
INTF = 15
INTCAP = 17
GPIO = 19
OLAT = 21
def initialize(name,channel,address)
super(name,channel,address)
return
end
def enable
write(IODIR,0)
return
end
def disable
write(IODIR,255)
return
end
def set(value)
write(GPIO,value)
return
end
def get
result = read(GPIO)
return result
end
def pullupsOn
write(GPPU,255)
return
end
def pullupsOff
write(GPPU,0)
return
end
end ; # of class GPIOB
| true |
a983d6a8693e7eb146261afde94bc831826704bf | Ruby | jonathancadepowers/filmnutonrails | /app/helpers/fasts_helper.rb | UTF-8 | 438 | 2.53125 | 3 | [] | no_license | # frozen_string_literal: true
module FastsHelper
def title_fast(timestamp, time_fasted)
title_values = { timestamp.to_date.strftime("%a, %b") => " ",
timestamp.to_date.day.ordinalize => ", ",
timestamp.to_date.strftime("%Y") => " - ",
ChronicDuration.output(time_fasted, format: :short) => "" }
title_values.inject("") { |title, i| title + i[0] + i[1] }
end
end
| true |
90c940adf114aacba324f583c4bb604e4855657c | Ruby | RKB1923/homework_assignments | /numbers_letters_and_variables/number_of_seconds.rb | UTF-8 | 1,039 | 3.921875 | 4 | [] | no_license | #!/usr/bin/env ruby
seconds_in_a_minute=60
minutes_in_an_hour=60
hours_in_a_day=24
days_in_a_week=7
weeks_in_a_year=52
puts "There are #{seconds_in_a_minute} seconds in a minute"
puts "There are #{minutes_in_an_hour} minutes in an hour"
puts "There are #{hours_in_a_day} hours in a day"
puts "There are #{days_in_a_week} days in a week"
puts "That means there are:"
puts " " + (seconds_in_a_minute * minutes_in_an_hour).to_s + " seconds in an hour,"
puts " " + (seconds_in_a_minute * minutes_in_an_hour * hours_in_a_day).to_s + " seconds in an day,"
puts " " + (seconds_in_a_minute * minutes_in_an_hour * hours_in_a_day * days_in_a_week).to_s + " seconds in a day"
puts "That means when you turn 20, you've been alive for " + (seconds_in_a_minute * minutes_in_an_hour * hours_in_a_day * days_in_a_week * weeks_in_a_year * 20).to_s + " seconds, \nand if you make it to 100, you will have lived " + (seconds_in_a_minute * minutes_in_an_hour * hours_in_a_day * days_in_a_week * weeks_in_a_year * 100).to_s + " seconds. Make them count!"
| true |
a1ea4c7bdd33bbb1f267f8b9f99033b91105d5bc | Ruby | dgokman/advent_of_code_2018 | /aoc_2018_16.rb | UTF-8 | 3,762 | 3.234375 | 3 | [] | no_license | def number_of_registers(before, instructions, after)
count = []
opcode, a, b, c = instructions
ra, rb, rc = before[a], before[b], before[c]
if (after[c] == 1 && a > rb) || (after[c] == 0 && a <= rb)
count << "gtir"
end
if (after[c] == 1 && ra > b) || (after[c] == 0 && ra <= b)
count << "gtri"
end
if (after[c] == 1 && ra > rb) || (after[c] == 0 && ra <= rb)
count << "gtrr"
end
if (after[c] == 1 && a == rb) || (after[c] == 0 && a != rb)
count << "eqir"
end
if (after[c] == 1 && ra == b) || (after[c] == 0 && ra != b)
count << "eqri"
end
if (after[c] == 1 && ra == rb) || (after[c] == 0 && ra != rb)
count << "eqrr"
end
if after[c] == ra + b
count << "addi"
end
if after[c] == ra + rb
count << "addr"
end
if after[c] == ra*rb
count << "mulr"
end
if after[c] == ra*b
count << "muli"
end
if after[c] == ra & rb
count << "banr"
end
if after[c] == ra & b
count << "bani"
end
if after[c] == ra | rb
count << "borr"
end
if after[c] == ra | b
count << "bori"
end
if after[c] == ra
count << "setr"
end
if after[c] == a
count << "seti"
end
[opcode, count]
end
def add_to_register(opcode, a, b, c, register)
ra, rb, rc = register[a], register[b], register[c]
if @opcode[opcode] == "gtir"
register[c] = 1 if a > rb
register[c] = 0 if a <= rb
end
if @opcode[opcode] == "gtri"
register[c] = 1 if ra > b
register[c] = 0 if ra <= b
end
if @opcode[opcode] == "gtrr"
register[c] = 1 if ra > rb
register[c] = 0 if ra <= rb
end
if @opcode[opcode] == "eqir"
register[c] = 1 if a == rb
register[c] = 0 if a != rb
end
if @opcode[opcode] == "eqri"
register[c] = 1 if ra == b
register[c] = 0 if ra != b
end
if @opcode[opcode] == "eqrr"
register[c] = 1 if ra == rb
register[c] = 0 if ra != rb
end
if @opcode[opcode] == "addi"
register[c] = ra+b
end
if @opcode[opcode] == "addr"
register[c] = ra+rb
end
if @opcode[opcode] == "mulr"
register[c] = ra*rb
end
if @opcode[opcode] == "muli"
register[c] = ra*b
end
if @opcode[opcode] == "banr"
register[c] = ra&rb
end
if @opcode[opcode] == "bani"
register[c] = ra&b
end
if @opcode[opcode] == "borr"
register[c] = ra|rb
end
if @opcode[opcode] == "bori"
register[c] = ra|b
end
if @opcode[opcode] == "setr"
register[c] = ra
end
if @opcode[opcode] == "seti"
register[c] = a
end
register
end
# 1
A = File.read('aoc_2018_16_A.txt')
arrs = A.split("\n").reject {|x| x.strip.empty?}.each_slice(3).to_a.map {|a,b,c| [a.sub("Before: ", ""), b.split(" ").join(",").insert(0,"[").insert(-1, "]"), c.sub("After: ", "")]}
total = 0
arrs.each do |before, instructions, after|
if number_of_registers(eval(before), eval(instructions), eval(after))[1].length >= 3
total += 1
end
end
p total
# 2
require 'set'
hash = {}
set = Set.new
total = 0
arrs.each do |before, instructions, after|
opcode, count = number_of_registers(eval(before), eval(instructions), eval(after))
hash[opcode] ||= Set.new
hash[opcode] += count
end
new_hash = hash.clone
until hash.all? {|k,v| v.length == 1}
hash.each do |k,v|
if v.length == 1
(new_hash.keys - [k]).each do |l|
new_hash[l].delete(v.first)
end
end
end
hash = new_hash.clone
end
@opcode = {}
hash.each do |k,v|
@opcode[k] = v.first
end
B = File.read('aoc_2018_16_B.txt')
register = [0,0,0,0]
B.split("\n").map {|a| a.split(" ").map(&:to_i)}.each do |opcode, a, b, c|
register = add_to_register(opcode, a, b, c, register)
end
p register.first
| true |
34a87d088c4398ccf65d8fb1926480d67a1c7de2 | Ruby | dasilva1b/RubyLengs | /Codigo/main.rb | UTF-8 | 821 | 3.25 | 3 | [] | no_license | #!/usr/bin/ruby
load 'Planta.rb'
#
# Implementacion del sistema de creacion de la cerveza glaciar brebaje Stolz
#
class Main
def main
#Obtengo los 5 elementos del terminal
if ARGV.length != 5
abort "Argumentos: <numero de ciclos> <cantidad cebada>
<cantidad mezcla arroz/maiz> <cantidad de levadura>
<cantidad de lúpulo>"
end
num_ciclos = Integer(ARGV[0])
cant_cebada = Integer(ARGV[1])
cant_arroz_maiz = Integer(ARGV[2])
cant_levadura = Integer(ARGV[3])
cant_lupulo = Integer(ARGV[4])
puts "num_ciclos #{num_ciclos} cant_lupulo #{cant_lupulo}"
#Inicializo la planta
planta=Planta.new(num_ciclos,cant_cebada,cant_arroz_maiz,cant_levadura,cant_lupulo)
planta.activar()
end
# Main principal
#print "CERVECERIA GLACIAR\n"
t = Main.new
t.main
end
#END main.rb
| true |
8e02bc49d065343ff85ac9360b54891bc8999380 | Ruby | melnock/ruby-objects-has-many-through-lab-web-012918 | /lib/song.rb | UTF-8 | 193 | 2.90625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Song
attr_reader :name, :genre
attr_accessor :artist
def initialize(name, genre)
@name = name
@genre = genre
genre.add_songs(self)
end
def add_to_genre
end
end
| true |
43c18dca6b61242b84717ab6c25bdb04b215b34b | Ruby | erichwelz/ruby_fundamentals1 | /exercise2.rb | UTF-8 | 249 | 3.484375 | 3 | [] | no_license | puts (55 * 0.2) # return to screen amount of 20% tip
puts (55 * 0.2).to_i #syntax error occurs when mixing str and int/floats in output
puts "The answer is: #{45628*7839}"
puts (true && false) || (false && true) || !(false && false)
#returns true | true |
3b79cab3242db66abbae459823836720ca2fd003 | Ruby | niktexnik/FindGitName-Rails- | /lib/name_generator.rb | UTF-8 | 374 | 3.140625 | 3 | [] | no_license | # frozen_string_literal: true
class NameGenerator
def self.process(name, numeric = false)
firstname, lastname = name.split
num = %w[1 2 3 4 5 6 7 8 9 0]
freename = []
i = 0
while i < name.length
i += 1
str = firstname[0...i] + lastname[0...i]
str += num.shuffle[i].to_s if numeric
freename << str
end
freename
end
end
| true |
3272cb8d62a32204b93751b88acff7ea712afd09 | Ruby | lg901127/final_project | /app/services/game_character_stat_calculator.rb | UTF-8 | 1,128 | 2.953125 | 3 | [] | no_license | class GameCharacterStatCalculator
attr_reader :game_character
def initialize(game_character)
@game_character = game_character
end
def parse_strength
game_character_strength = game_character.game_character_attributes.find_by_stat_id(13).value
game_character_item_strength = 0
game_character.game_character_items.each do |item|
game_character_item_strength = game_character_item_strength + ItemStat.where(item_id: item.item_id).find_by_stat_id(13).value if ItemStat.where(item_id: item.item_id).find_by_stat_id(13)
end
game_character_strength + game_character_item_strength
end
def parse_constitution
game_character_constitution = game_character.game_character_attributes.find_by_stat_id(14).value
game_character_item_constitution = 0
game_character.game_character_items.each do |item|
game_character_item_constitution = game_character_item_constitution + ItemStat.where(item_id: item.item_id).find_by_stat_id(14).value if ItemStat.where(item_id: item.item_id).find_by_stat_id(14)
end
game_character_constitution + game_character_item_constitution
end
end
| true |
eb517d37d41d7aaa846d917d463f348a3e926216 | Ruby | Katherine-Bishop/my_mint | /app/models/transaction.rb | UTF-8 | 1,651 | 2.609375 | 3 | [] | no_license | class Transaction < ActiveRecord::Base
has_one :budget
# validates_presence_of :description
validates_presence_of :date, :unless => proc { new_record? }
def self.import(file)
CSV.foreach(file, headers: true) do |row|
#skips credit card payments
next if row[5] == 'Credit Card Payment'
#converts credits to negative numbers
if row[4] == 'credit'
row[3] = '-'+row[3]
end
#converts date from month/day/year format
row[0] = row[0].nil? ? nil : DateTime.strptime(row[0], "%m/%d/%Y").strftime("%Y/%m/%d")
if row[6] == 'Southwest Card'
row[3] = (row[3].to_f/2).round(2)
end
#if a budget with the category name exists, add the budget id to this
#transaction
budget_category = BudgetCategory.where(:category => row[5])
if budget_category.length > 0
row[7] = budget_category[0][:budget_id]
elsif row[5] == 'Uncategorized'
row[7] = nil
else
misc_budget = Budget.where(:name => 'Misc')
logger.debug "Misc budget id: #{misc_budget}"
row[7] = misc_budget[0][:id]
end
# Transaction.create! row.to_hash
Transaction.create(
:date => row[0],
:description => row[1],
:original_decription => row[2],
:amount => row[3],
:transaction_type => row[4],
:category => row[5],
:account_name => row[6],
:budget_id => row[7]
)
end
end
def budget_name
budget = Budget.where(:id => budget_id)
if budget.length > 0
budget_name = budget.first.name
else
budget_name = ''
end
logger.debug "Budget name is: #{budget_name}"
"#{budget_name}"
end
end
| true |
fdeb59ae6061fbb0aef5323dd99442e76cf97253 | Ruby | SiamKing/looping-loop-v-000 | /looping.rb | UTF-8 | 88 | 2.625 | 3 | [] | no_license | def looping
puts "Wingardium Leviosa"
looping #your code here
end
#call your method here
looping
| true |
521b1c2cf4463cccc3375750a8b143835b46ec56 | Ruby | Tinend/FantasyKarte | /lib/NuetzlicheFunktionen/berechneEntfernung.rb | UTF-8 | 2,220 | 3.078125 | 3 | [
"MIT"
] | permissive | # coding: utf-8
require "RandPixel"
def berechneEntfernung(bild)# berechnet für jeden Pixel, wie weit er von Transparenten Pixeln oder dem Rand entfernt ist
richtungen = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]
distanz = 0
randPixel = []
entfernungen = Array.new(bild.height) {Array.new(bild.width, 0)}
bild.height.times do |y|
bild.width.times do |x|
next if bild[x,y] == ChunkyPNG::Color::TRANSPARENT
if x == 0 or y == 0 or x == bild.width - 1 or y == bild.height - 1
entfernungen[y][x] = 1
randPixel.push(RandPixel.new(x, y, 1))
elsif (x > 0 and bild[x - 1, y] == ChunkyPNG::Color::TRANSPARENT) or (y > 0 and bild[x, y - 1] == ChunkyPNG::Color::TRANSPARENT) or (x < bild.width - 1 and bild[x + 1, y] == ChunkyPNG::Color::TRANSPARENT) or (y < bild.height - 1 and bild[x, y + 1] == ChunkyPNG::Color::TRANSPARENT)
entfernungen[y][x] = 1
randPixel.push(RandPixel.new(x, y, 1))
elsif (x > 0 and y > 0 and bild[x - 1, y - 1] == ChunkyPNG::Color::TRANSPARENT) or (x < bild.width - 1 and y > 0 and bild[x + 1, y - 1] == ChunkyPNG::Color::TRANSPARENT) or (x < bild.width - 1 and y < bild.height - 1 and bild[x + 1, y + 1] == ChunkyPNG::Color::TRANSPARENT) or (x > 0 and y < bild.height - 1 and bild[x - 1, y + 1] == ChunkyPNG::Color::TRANSPARENT)
entfernungen[y][x] = 2 ** 0.5
randPixel.push(RandPixel.new(x, y, 2 ** 0.5))
end
end
end
until randPixel.length == 0
if distanz != randPixel[0].distanz
randPixel.sort!
distanz = randPixel[0].distanz
end
pixel = randPixel.shift()
next if pixel.distanz > entfernungen[pixel.y][pixel.x] and entfernungen[pixel.y][pixel.x] != 0
neuPixel = richtungen.map {|r| RandPixel.new(pixel.x + r[0], pixel.y + r[1], pixel.distanz + (r[0] ** 2 + r[1] ** 2) ** 0.5)}
neuPixel.select! {|np| np.x >= 0 and np.y >= 0 and np.x < bild.width and np.y < bild.height}
neuPixel.select! {|np| (entfernungen[np.y][np.x] == 0 or entfernungen[np.y][np.x] > np.distanz) and bild[np.x, np.y] != ChunkyPNG::Color::TRANSPARENT}
randPixel += neuPixel
neuPixel.each {|np| entfernungen[np.y][np.x] = np.distanz}
end
entfernungen
end
| true |
80631f19748d27add548c879dc759163d47b3462 | Ruby | pieterjongsma/tournament-system | /lib/tournament_system/voetlab.rb | UTF-8 | 2,533 | 2.703125 | 3 | [
"MIT"
] | permissive | require 'tournament_system/algorithm/swiss'
require 'tournament_system/swiss/dutch'
require 'tournament_system/swiss/accelerated_dutch'
module TournamentSystem
# Robust implementation of the swiss tournament system
module Voetlab
extend self
# Generate matches with the given driver.
#
# @param driver [Driver]
# @option options [Pairer] pairer the pairing system to use, defaults to
# {Dutch}
# @option options [Hash] pair_options options for the chosen pairing system,
# see {Dutch} for more details
# @return [nil]
def generate(driver, _options = {}) # rubocop:disable Metrics/MethodLength, Metrics/AbcSize
teams = Algorithm::Util.padd_teams_even(driver.ranked_teams)
all_matches = all_matches(driver).to_a
played_matches = driver.matches.map { |m| driver.get_match_teams(m).to_set }
rounds = match_teams(driver, teams).lazy.select do |round|
remaining_matches = all_matches - played_matches - round
Algorithm::RoundRobin.matches_form_round_robin(remaining_matches)
end
pairings = rounds.first
if pairings.nil?
raise 'No valid rounds found'
# pairings = match_teams(driver, teams).first # Just take the first round as a fallback
end
driver.create_matches(pairings.map(&:to_a))
end
def minimum_rounds(_driver)
1
end
# private
def match_teams(driver, teams = driver.ranked_teams) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
return [[]] if teams.empty?
teams = teams.clone
# Assuming `teams` is ranked in order of preferred matching
team = teams.shift
matches = driver.get_team_matches(team)
played_teams = matches.map { |m| driver.get_match_teams(m) }.flatten
remaining_opponents = teams - played_teams
Enumerator.new do |enum|
remaining_opponents.each do |opponent|
match = Set[team, opponent]
other_teams = teams - match.to_a
match_teams(driver, other_teams).each do |other_matches|
enum.yield [match] + other_matches
end
end
end
end
def all_matches(driver)
teams = Algorithm::Util.padd_teams_even(driver.seeded_teams)
Enumerator.new do |enum|
teams.each_with_index do |team, index|
teams[(index + 1)..].each do |opponent|
enum.yield Set[team, opponent]
end
end
end
end
end
end
| true |
46484c4205ee835f0358e8772cbc849a81843c32 | Ruby | dalalsunil1986/algorithms_ruby | /stacks/min_max_stack.rb | UTF-8 | 977 | 3.8125 | 4 | [] | no_license | class MinMaxStack
def initialize
@stack = []
@min_max_stack = []
end
def push(val)
new_min_max = [val, val]
if @min_max_stack.any?
last_min_max = @min_max_stack.last
new_min_max[0] = [last_min_max[0], new_min_max[0]].min
new_min_max[1] = [last_min_max[1], new_min_max[1]].max
end
@min_max_stack << new_min_max
@stack << val
end
def get_min
@min_max_stack.last[0] if @min_max_stack.any?
end
def get_max
@min_max_stack.last[1] if @min_max_stack.any?
end
def peek
@stack[-1] if @stack.any?
end
def pop
if @stack.any?
@min_max_stack.pop
@stack.pop
end
end
end
stack = MinMaxStack.new
stack.push 5
puts stack.get_min
puts stack.get_max
puts stack.peek
stack.push 7
puts stack.get_min
puts stack.get_max
puts stack.peek
stack.push 2
puts stack.get_min
puts stack.get_max
puts stack.peek
puts stack.pop
puts stack.pop
puts stack.get_min
puts stack.get_max
puts stack.peek
| true |
27b8dbf74bd7c0e12521894227c5686795a4b769 | Ruby | VIKO-eif-RoR/ThirdTask | /SimpsonFormula/simpsonformulamain.rb | UTF-8 | 368 | 3.03125 | 3 | [] | no_license | # frozen_string_literal: true
require_relative 'simpsonformula.rb'
n = 4
startingpoint = 2
endingpoint = 50
value = SimpsonsFormula.new.simpson_formula_calculator(startingpoint, endingpoint, n)
if startingpoint < endingpoint
if n.even?
puts(value)
else
puts('Enter lyginis intervalas')
end
else
puts('Start point must be greater than end point')
end
| true |
bf01c4869726653ca4740629c1aefb155a815bd5 | Ruby | SADIAMALIK1980/ruby | /if_else.rb | UTF-8 | 918 | 4.09375 | 4 | [] | no_license | //simple math equation
if 1+1 == 2
puts "1 and 1 does indeed equal 2"
end
//string
my_name ='Skillcrush'
if my_name == 'Skillcrush'
puts "Hellooooo, Skillcrush!"
end
//if else statement
my_name = 'Sadia'
if my_name == 'Skillcrush'
puts "Hellooooo, Skillcrush!"
else
puts "oops, I thought your name was Skillcrush. Sorry about that, #{my_name}!"
end
//if else script
fav_color = 'green'
if (fav_color == 'red')
puts "Red like fire!"
elsif (fav_color == 'orange')
puts "Orange like, well... an orange."
elsif (fav_color == 'yellow')
puts "Yellow daffodils are so pretty in the spring!"
elsif (fav_color == 'green')
puts "Have you been to the Emrald city of Oz!"
elsif (fav_color == 'blue')
puts "Blue like sky!"
elsif (fav_color == 'purple')
puts "Purple plums are the tastiest."
else
puts "Hmm, well I don;t know what the color is!"
end
| true |
d2c095bbf8196a8497587128fbf1934b3c5f626f | Ruby | tiffany-simionescu/ruby-course | /arrays.rb | UTF-8 | 395 | 3.71875 | 4 | [] | no_license | friends = Array["Kevin", "Karen", "Oscar", "Andy"]
puts friends
puts friends[0]
puts friends[-1]
puts friends[-2]
# index 0 and 1 not 2
puts friends[0, 2]
friends[0] = "Dwight"
puts friends[0]
puts friends.length()
puts friends.include? "Karen"
puts friends.reverse()
# must be same type in order to sort
puts friends.sort()
# want to declare an array without values
my_array = Array.new
| true |
f20c0932becab4889dda30bad64a47e4201f0c80 | Ruby | tommetge/impersonator | /lib/impersonator/markov.rb | UTF-8 | 1,775 | 3.375 | 3 | [] | no_license | # http://www.rubyquiz.com/quiz74.html
class MarkovChain
attr_reader :order, :beginnings, :freq
def initialize(text, order = 2, max = 22)
@order = order
@max = max
@beginnings = []
@freq = {}
add_text(text)
end
def add_text(text)
# make sure each paragraph ends with some sentence terminator
text.gsub!(/\n\s*\n/m, ".")
text << "."
seps = /([.!?])/
sentence = ""
text.split(seps).each { |p|
if seps =~ p
add_sentence(sentence, p)
sentence = ""
else
sentence = p
end
}
end
def generate_sentence(seed = nil)
res = nil
if seed
possibles = @beginnings.map {|b| b if b.include?(seed.split.first)}
res = possibles[rand(possibles.size)]
end
if !res
res = @beginnings[rand(@beginnings.size)]
end
loop {
unless nw = next_word_for(res[-order, order])
return res[0..-2].join(" ") + res.last
end
res << nw
return res[0..-2].join(" ") if should_stop(res, nw)
}
end
private
def should_stop(sentence, word)
return true if sentence.length >= @max
@beginnings.each do |v|
return true if v.include?(word) && rand(20) == 0
end
false
end
def add_sentence(str, terminator)
words = str.scan(/[\w']+/)
return unless words.size > order # ignore short sentences
words << terminator
buf = []
words.each { |w|
buf << w
if buf.size == order + 1
(@freq[buf[0..-2]] ||= []) << buf[-1]
buf.shift
end
}
@beginnings << words[0, order]
end
def next_word_for(words)
arr = @freq[words]
return nil unless arr
arr && arr[rand(arr.size)]
end
end | true |
8a48b18a384aa01f894b5c817dfa28f6ea359e33 | Ruby | MichaelWales/Pub-Lab | /specs/customer_spec.rb | UTF-8 | 679 | 2.625 | 3 | [] | no_license | require("minitest/autorun")
require('minitest/reporters')
require_relative("../customer")
Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new
class CustomerTest < MiniTest::Test
def setup
@customer1 = Customer.new("Ali G", 50, 32, 0)
end
def test_get_name()
assert_equal("Ali G", @customer1.name())
end
def test_wallet_amount()
assert_equal(50, @customer1.wallet())
end
def test_spend_cash()
@customer1.spend_cash(2)
assert_equal(48, @customer1.wallet())
end
def test_customer_age()
assert_equal(32, @customer1.age())
end
def test_customer_drunkeness()
assert_equal(0, @customer1.drunkeness())
end
end
| true |
eb6cada10b7c222456cc5f16fbcb1855a1b595f3 | Ruby | CarterNelms/blueberry-cal | /spec/cal_month_integration_spec.rb | UTF-8 | 1,460 | 3.015625 | 3 | [] | no_license | RSpec.describe "Cal's full month integration" do
it "should correctly print July 2017" do
expected = <<EOS
July 2017
Su Mo Tu We Th Fr Sa
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
EOS
actual = `./cal 07 2017`
actual.should == expected
end
it "should correctly print December 2014" do
expected = <<EOS
December 2014
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
EOS
actual = `./cal 12 2014`
actual.should == expected
end
it "should accept either numbers or strings to specify a month" do
expected = <<EOS
September 2016
Su Mo Tu We Th Fr Sa
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30
EOS
actual_with_number1 = `./cal 9 2016`
actual_with_number2 = `./cal 09 2016`
actual_with_string1 = `./cal september 2016`
actual_with_string2 = `./cal sep 2016`
actual_with_string3 = `./cal sept 2016`
actual_with_string4 = `./cal sEpteMber 2016`
actual_with_number1.should == expected
actual_with_number2.should == expected
actual_with_string1.should == expected
actual_with_string2.should == expected
actual_with_string3.should == expected
actual_with_string4.should == expected
end
end
| true |
169ce51a8ee0ffdf681c5b107a60aa871130a388 | Ruby | nickcbrierley/sep-assignments | /02-algorithms-and-complexity/03-algorithms-sorting/heap_sort.rb | UTF-8 | 966 | 3.703125 | 4 | [] | no_license | require 'benchmark'
def heap_sort(array)
buildMaxHeap(array)
lastElement = array.length - 1
while(lastElement > 0)
swap(array, 0, lastElement)
heapify(array, 0, lastElement)
lastElement -= 1
end
end
def buildMaxHeap(array)
i = (array.length / 2 - 1).floor
while(i >= 0)
heapify(array, i, array.length)
i -= 1
end
end
def heapify(heap, i, max)
while(i < max)
index = i
leftChild = 2 * i + 1
rightChild = leftChild + 1
index = leftChild if (leftChild < max && heap[leftChild] > heap[index])
index = rightChild if (rightChild < max && heap[rightChild] > heap[index])
return if index === i
swap(heap, i, index)
i = index
end
end
def swap(array, firstItemIndex, lastItemIndex)
temp = array[firstItemIndex]
array[firstItemIndex] = array[lastItemIndex]
array[lastItemIndex] = temp
end
testarray = Array.new(50){rand(-10..100)}
puts 'Heap Sort'
puts Benchmark.measure{heap_sort(testarray)} | true |
511ada2a376d3dec29d67da500975d3bdf2b25c5 | Ruby | arthurljones/junkrig-calc | /src/engineering/material.rb | UTF-8 | 1,124 | 2.71875 | 3 | [] | no_license | require "options_initializer"
module Engineering
class Material
include OptionsInitializer
@@materials_cache = nil
attr_reader :name
options_initialize(
:yield_strength => { :units => "psi" },
:density => { :units => "lbs/in^3" },
:modulus_of_elasticity => { :units => "psi" },
:shear_strength => { :units => "psi", :required => false },
)
def self.get(name)
cache[name]
end
def self.list
cache.keys
end
def shear_strength
@shear_strength || yield_strength * 0.577
end
def strength_to_density_ratio
((yield_strength / density) / 1e5).scalar
end
def to_s
name
end
def inspect
to_s
end
private
def self.cache
unless @@materials_cache
materials_data = load_yaml_data_file("materials.yml")
@@materials_cache = materials_data.inject({}) do |cache, (name, data)|
raise "Duplicate material definition for #{name}" if cache[name].present?
cache[name] = new(data)
cache
end
end
@@materials_cache
end
end
end
| true |
6eb4064f495726d6de6e5e03af7fee46f90e15d1 | Ruby | coreyjuliandavis/101 | /lesson_2/mortgage.rb | UTF-8 | 941 | 3.875 | 4 | [] | no_license | def prompt(message)
puts("=> #{message}")
end
loan_amt = ''
apr = ''
apr_mo = ''
duration = ''
duration_mo = ''
prompt("I hear you're in the market for a home!")
prompt("How much of the cost will be financed?")
loop do
loan_amt = gets.chomp
loan_amt = loan_amt.to_f
if loan_amt == 0.0
prompt("Please put in a valid principal amount")
else
break
end
end
prompt("What is your anticipated annual interest rate? IE - 5.2%")
loop do
apr = gets.chomp
apr_mo = (apr.to_f / 12) / 100
if apr == 0.0
prompt("Please put in a valid annual interest rate. IE - 5.2%")
else
break
end
end
prompt("How many years is the loan?")
loop do
duration = gets.chomp
duration_mo = duration.to_f * 12
if duration_mo == 0.0
prompt("Please put in the number of years financed")
else
break
end
end
m = loan_amt * (apr_mo / (1 - (1 + apr_mo)**(-duration_mo)))
prompt("Your monthly payment will be #{m}")
| true |
3f4814b6702323ae89266c42887a8e4d49b807cb | Ruby | hamdans1/diplomacy | /lib/random_data.rb | UTF-8 | 678 | 3.234375 | 3 | [] | no_license | module RandomData
def self.random_sentence
strings = []
rand(3..5).times do
strings << random_word
end
sentence = strings.join(" ")
sentence.capitalize << "."
end
def self.random_word
letters = ("a".."z").to_a
letters.shuffle!
letters[0, rand(3..8)].join
end
def self.random_year
rand(1950..2050)
end
def self.random_scoring
scoring_array = [
"classic",
"dixieland",
"modern",
"modified classic"
]
scoring_array[rand(0...3)]
end
def self.random_style
styles = [
"Anonymous",
"Gunboat",
"Random",
"Selected"
]
styles[rand(0...3)]
end
end
| true |
48ba93705d9bd74425c2743ede4dfa0b88e9e5a0 | Ruby | medical-tribune-polska/streaming | /app/forms/stream/import_form.rb | UTF-8 | 464 | 2.65625 | 3 | [
"MIT"
] | permissive | module Stream
class ImportForm
attr_reader :accesses
def initialize(accesses)
@accesses = accesses
end
def process
@accesses.each(&:save)
end
def check_accesses
accesses.each_with_object({}).with_index do |(access, errors), i|
errors[i] = check_access(access)
end.compact
end
private
def check_access(access)
access.errors.try(:messages) unless access.valid?
end
end
end
| true |
a558cefde9b1eea104a8a7fe4f41971c5f52fbe7 | Ruby | bpieck/rubyx | /lib/risc/block_compiler.rb | UTF-8 | 1,662 | 2.734375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | module Risc
# A BlockCompiler is much like a Mehtodcompiler, exept for blocks
#
class BlockCompiler < CallableCompiler
attr_reader :block , :risc_instructions , :constants
alias :block :callable
def initialize( block , method)
@method = method
super(block)
end
def source_name
"#{@method.self_type.name}.init"
end
# resolve the type of the slot, by inferring from it's name, using the type
# scope related slots are resolved by the compiler by method/block
#
# This mainly calls super, and only for :caller adds extra info
# Using the info, means assuming that the block is not passed around (FIXME in 2020)
def slot_type( slot , type)
new_type = super
if slot == :caller
extra_info = { type_frame: @method.frame_type ,
type_arguments: @method.arguments_type ,
type_self: @method.self_type}
end
return new_type , extra_info
end
# determine how given name need to be accsessed.
# For blocks the options are args or frame
# or then the methods arg or frame
def slot_type_for(name)
if @callable.arguments_type.variable_index(name)
slot_def = [:arguments]
elsif @callable.frame_type.variable_index(name)
slot_def = [:frame]
elsif @method.arguments_type.variable_index(name)
slot_def = [:caller , :caller ,:arguments ]
elsif @method.frame_type.variable_index(name)
slot_def = [:caller ,:caller , :frame ]
elsif
raise "no variable #{name} , need to resolve at runtime"
end
slot_def << name
end
end
end
| true |
329c77077cc9ff93128b95c2c7e54f06d812bc7b | Ruby | darthschmoo/epubforge | /lib/epubforge/core_extensions/kernel.rb | UTF-8 | 911 | 2.59375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | module EpubForge
module CoreExtensions
module Kernel
# yields an alternate reality block where instance methods
# are different from what they were. At the end of the block
# it resets the initial values of the instance variables.
def with_locals locals = {}, &block
old_local_vars = {}
for k, v in locals
var = :"@#{k}"
old_local_vars[k] = instance_variable_get(var)
instance_variable_set( var, v )
end
yield
ensure # make all as it once was
for k, v in old_local_vars
var = :"@#{k}"
instance_variable_set( var, v )
end
end
# Runs a block of code without warnings.
def silence_warnings(&block)
warn_level = $VERBOSE
$VERBOSE = nil
result = block.call
$VERBOSE = warn_level
result
end
end
end
end | true |
b6b118979e8bf75fea6073c344b4bf794f726f8b | Ruby | rhys117/LaunchSchoolCurriculum | /Backend/120/lesson4/easy2.rb | UTF-8 | 5,083 | 4.25 | 4 | [] | no_license | =begin
1.
You are given the following code: What is the result of calling
oracle = Oracle.new
oracle.predict_the_future
--
The result will be a return string value of "You will " and one of the
elements from the array in the choice method.
=end
class Oracle
def predict_the_future
"You will " + choices.sample
end
def choices
["eat a nice lunch", "take a nap soon", "stay at work late"]
end
end
class Oracle
def predict_the_future
"You will " + choices.sample
end
def choices
["eat a nice lunch", "take a nap soon", "stay at work late"]
end
end
oracle = Oracle.new
oracle.predict_the_future
=begin
2.
We have an Oracle class and a RoadTrip class that inherits from the Oracle
class. What is the result of the following:
trip = RoadTrip.new
trip.predict_the_future
--
The return of a string with 'You will ' and one of the elements from the
choices array in the RoadTrip class as it 'overrides' the choices method in the
Oracle class.
=end
class Oracle
def predict_the_future
"You will " + choices.sample
end
def choices
["eat a nice lunch", "take a nap soon", "stay at work late"]
end
end
class RoadTrip < Oracle
def choices
["visit Vegas", "fly to Fiji", "romp in Rome"]
end
end
=begin
3.
How do you find where Ruby will look for a method when that method is called?
How can you find an object's ancestors? What is the lookup chain for Orange and
HotSauce?
--
We could use HoSauce.ancestors to find out. In this case..
HotSauce, Taste, Object, Kernal, BasicObject
=end
module Taste
def flavor(flavor)
puts "#{flavor}"
end
end
class Orange
include Taste
end
class HotSauce
include Taste
end
=begin
4.
What could you add to this class to simplify it and remove two methods from
the class definition while still maintaining the same functionality?
=end
class BeesWax
def initialize(type)
@type = type
end
def type
@type
end
def type=(t)
@type = t
end
def describe_type
puts "I am a #{@type} of Bees Wax"
end
end
# Simplified
class BeesWax
attr_accessor :type
def initialize(type)
@type = type
end
def describe_type
puts "I am a #{type} of Bees Wax"
end
end
=begin
5.
There are a number of variables listed below. What are the different types
and how do you know which is which?
excited_dog = "excited dog"
@excited_dog = "excited dog"
@@excited_dog = "excited dog"
--
a local variable, an instance variable and a class variable. we can tell this
because of the lack or addition fo the @ symbol before the name of the
variable.
=end
=begin
6.
If I have the following class: Which one of these is a class method (if any)
and how do you know? How would you call a class method?
--
A method that starts with self is a class method. So in this case the
manufacturer method. A class method can be called by the Class the name
followed by the method.. eg. Television.manufacturer
=end
class Television
def self.manufacturer
# method logic
end
def model
# method logic
end
end
=begin
7.
If we have a class such as the one below: Explain what the @@cats_count
variable does and how it works. What code would you need to write to test your
theory?
--
When a new cat object is initialized the class variable cats_count will
increase by one. To test this we can create a few cat objects and then call
the Class method cats_count to see how many Cat objects there are.
=end
class Cat
@@cats_count = 0
def initialize(type)
@type = type
@age = 0
@@cats_count += 1
end
def self.cats_count
@@cats_count
end
end
#
rocky = Cat.new('turtese_shell')
p Cat.cats_count
sleepy = Cat.new('persian')
p Cat.cats_count
=begin
8.
If we have this class:
class Game
def play
"Start the game!"
end
end
And another class:
class Bingo
def rules_of_play
#rules of play
end
end
What can we add to the Bingo class to allow it to inherit the play method
from the Game class?
--
We can make the Game class the Parent Class to Bingo as demonstrated below..
=end
class Game
def play
"Start the game!"
end
end
class Bingo < Game
def rules_of_play
#rules of play
end
end
=begin
9.
If we have this class: What would happen if we added a play method to the Bingo
class, keeping in mind that there is already a method of this name in the Game
class that the Bingo class inherits from.
--
It would override the play method in Game and therefore no longer use it. This
is because of the chain in finding the method.. Ruby will look in Bingo before
before it looks in Game.
=end
class Game
def play
"Start the game!"
end
end
class Bingo < Game
def rules_of_play
#rules of play
end
end
=begin
10.
What are the benefits of using Object Oriented Programming in Ruby? Think of as
many as you can.
- Makes larger programs more managable and helps to stop a 'ripple' effect of
breaking code when you're changing small things.
- Allows the programmer to think more abstractly about the problem.
- Allows us to use previous libraries or code to make coding faster.
=end
| true |
96a4f1cdaf2fc335501f265a45df546c36dab1b5 | Ruby | naoto/animemap | /bin/animemap | UTF-8 | 139 | 2.609375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
require 'animemap'
Animemap.location(ARGV.first).each do |data|
puts "#{data.week} #{data.time} #{data.title}"
end
| true |
3891f5c5e9e76dc623eb118e8def289dc96f9f19 | Ruby | emartech/ezlog | /lib/ezlog/logging_layout.rb | UTF-8 | 1,575 | 2.625 | 3 | [
"MIT"
] | permissive | require 'time'
require 'oj'
module Ezlog
class LoggingLayout < ::Logging::Layout
def initialize(context = {}, options = {})
@initial_context = context
@level_formatter = options.fetch(:level_formatter, ->(numeric_level) { ::Logging::LNAMES[numeric_level] })
end
def format(event)
log_entry = basic_information_for event
add_initial_context_to log_entry
add_logging_context_to log_entry
add_event_information_to log_entry, event
::Oj.dump(log_entry, mode: :json) + "\n"
end
private
def basic_information_for(event)
{
'logger' => event.logger,
'timestamp' => event.time.iso8601(3),
'level' => @level_formatter.call(event.level),
'hostname' => Socket.gethostname,
'pid' => Process.pid
}
end
def add_initial_context_to(log_entry)
log_entry.merge! @initial_context
end
def add_logging_context_to(log_entry)
log_entry.merge! ::Logging.mdc.context
end
def add_event_information_to(log_entry, event)
log_entry.merge! hash_from(event.data)
end
def hash_from(obj)
case obj
when Exception
exception_message_by(obj)
when Hash
obj
else
{ 'message' => obj }
end
end
def exception_message_by(exception)
{
'message' => exception.message,
'error' => {
'class' => exception.class.name,
'message' => exception.message,
'backtrace' => exception.backtrace&.first(20)
}
}
end
end
end
| true |
474ed18f22469c9db7e352ecf15265a0d84a87b9 | Ruby | salysm/ruby-enumerables-cartoon-collections-lab-dc-web-012720 | /cartoon_collections.rb | UTF-8 | 965 | 3.375 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive |
dwarves = ["Doc", "Dopey", "Bashful", "Grumpy", "Sneezy", "Sleepy", "Happy"]
def roll_call_dwarves(dwarves)
dwarves.each_with_index do |dwarf, index|
puts "#{index + 1}. #{dwarf}"
end
end
planeteer_calls = ["earth", "wind", "fire", "water", "heart"]
def summon_captain_planet(planeteer_calls)
planeteer_calls.map {|call| call.capitalize! + '!'}
end
def long_planeteer_calls(planeteer_calls)
planeteer_calls.any? {|call| call.length > 4}
end
# snacks = ["crackers", "gouda", "thyme"]
# soup = ["tomato soup", "cheddar", "oyster crackers", "gouda"]
# def find_the_cheese(array)
# cheese = %w[gouda cheddar camembert]
# array.find do |ingredient|
# ingredient.include?(cheese)
# end
# end
potentially_cheesy_items = %w[umbrella spinach cheddar helicopter]
def find_the_cheese(potentially_cheesy_items)
cheeses = %w[gouda cheddar camembert]
potentially_cheesy_items.find do |maybe_cheese|
cheeses.include?(maybe_cheese)
end
end | true |
6643e756a480ac5c66b41ad7949be57b9a02bc0c | Ruby | TooColline/Cryptarithm | /script.rb | UTF-8 | 2,585 | 3.71875 | 4 | [
"MIT"
] | permissive | # frozen_string_literal: true
# This class in an example of the cryparithmic solution
class Example
include Enumerable
# Instantiate global empty arrays and range
@@global_range = Array(100..999)
@@bbg = []
@@fun = []
@@stn = []
def listoffunpossibilities
# FUN values should meet the criteria below:
# 1. 3 digit value
# 2. All are unique
@@global_range.each do |i|
@@fun.push(i) unless /([0-9]).*?\1/.match?(i.to_s)
end
@@fun
end
def listofbbgpossibilities
# BBG values should meet the criteria below:
# 1. 3 digit value
# 2. First 2 digits are similar
@@global_range.each do |i|
digits = i.to_s.split(//).map(&:to_i)
@@bbg.push(i) if digits[0] == digits[1] && digits[1] != digits[2]
end
@@bbg
end
def checkifsolutionsconformtopattern(solution, funvalue)
# Function ensures that the final solution conforms to the rules below:
# 1. 6 digit value
# 2. The third and the fourth digit are similar
# 3. No other digits are similar
# 4. Second digit is similar to the second digit of the FUN value
# 5. First digit of solution should not be similar to first digit(F) of FUN
solution_digits = solution.to_s.split(//).map(&:to_i)
fundigits = funvalue.to_s.split(//).map(&:to_i)
if solution_digits.length == 6 &&
solution_digits[1] == fundigits[1] &&
solution_digits[0] != fundigits[0] &&
solution_digits[2] != fundigits[2] &&
solution_digits[2] == solution_digits[3] &&
solution_digits[0] != solution_digits[1] &&
solution_digits[0] != solution_digits[2] &&
solution_digits[0] != solution_digits[4] &&
solution_digits[0] != solution_digits[5] &&
solution_digits[1] != solution_digits[2] &&
solution_digits[1] != solution_digits[4] &&
solution_digits[1] != solution_digits[5] &&
solution_digits[2] != solution_digits[4] &&
solution_digits[2] != solution_digits[5] &&
solution_digits[4] != solution_digits[5]
return !@@stn.include?(solution)
end
end
def calcpossiblestns
funvaluelist = listoffunpossibilities
bbgvaluelist = listofbbgpossibilities
funvaluelist.each do |funvalue|
bbgvaluelist.each do |bbgvalue|
solution = funvalue * bbgvalue
if checkifsolutionsconformtopattern(solution, funvalue)
puts "#{funvalue} * #{bbgvalue} = #{solution}"
@@stn.push(solution)
end
end
end
puts "There are #{@@stn.length} unique solutions"
end
end
a = Example.new
a.calcpossiblestns
| true |
ef1cfb67b827af13b8d2ae3fe0e22a002a77a9b4 | Ruby | pedro/autoroku | /lib/autoroku/cli.rb | UTF-8 | 1,637 | 2.765625 | 3 | [
"MIT"
] | permissive | require "netrc"
class Autoroku::CLI
def self.start(*args)
new.run(args)
end
def initialize
@key = fetch_api_key
@api = Autoroku::Lib.new(:api_key => @key)
end
def fetch_api_key
netrc["api.heroku.com"][1]
end
def run(*args)
cmd = args.first.first
method = cmd.gsub(":", "_")
if cmd == "help"
display "Usage: autoroku [command]"
(@api.public_methods - Object.methods).sort.each do |method|
cmd = method.to_s.gsub("_", ":")
display " #{cmd}"
end
exit 0
end
unless @api.respond_to?(method)
display "Unknown command: #{cmd}"
end
if @api.respond_to?(method)
response = @api.send(method)
if response.is_a?(Array)
response.each do |element|
render(element)
end
else
render(response)
end
end
end
def render(element)
element.keys.sort.each do |key|
display "#{key}: #{element[key]}"
end
end
def display(line)
puts line
end
def netrc_path
default = Netrc.default_path
encrypted = default + ".gpg"
if File.exists?(encrypted)
encrypted
else
default
end
end
def netrc # :nodoc:
@netrc ||= begin
File.exists?(netrc_path) && Netrc.read(netrc_path)
rescue => error
if error.message =~ /^Permission bits for/
perm = File.stat(netrc_path).mode & 0777
abort("Permissions #{perm} for '#{netrc_path}' are too open. You should run `chmod 0600 #{netrc_path}` so that your credentials are NOT accessible by others.")
else
raise error
end
end
end
end
| true |
e1b7be882fa5e7c24128c92b6b8c8301578a5050 | Ruby | gazeldx/call-web | /lib/core_ext/date_time_ext.rb | UTF-8 | 2,476 | 3.03125 | 3 | [] | no_license | class DateTime
def self.from_hash_with_hour(hash)
civil_from_format(:local, hash[:year].to_i, hash[:month].to_i, hash[:day].to_i, hash[:hour].to_i, 0)
end
def self.from_hash_with_day(hash)
civil_from_format(:local, hash[:year].to_i, hash[:month].to_i, hash[:day].to_i, 0, 0)
end
def self.transfer_string_to_date(date_string)
unless date_string.to_s.blank? || date_string.to_s.size < 8
date_string.gsub!(/(年|月|\/)/, '-')
date_string.gsub!(/日/, ' ')
if date_string.include?('-')
value = date_string.split(' ')[0] # 只保留第一个空格前的内容。
else
if date_string.size == 8
value = date_string[0..3] + '-' + date_string[4..5] + '-' + date_string[6..7]
end
end
date = value.split('-')
begin
if (date[0].to_i > 1400 && date[0].to_i < 2250) && (date[1].to_i > 0 && date[1].to_i <= 12) && (date[2].to_i > 0 && date[2].to_i <= 31)
civil_from_format(:local, date[0].to_i, date[1].to_i, date[2].to_i, 0, 0)
end
rescue Exception => exception
# puts exception.inspect
end
end
end
def self.left_days_this_month
Time.days_in_month(Date.today.month, Date.today.year) - Date.today.day
end
def self.days_include_today_remain_current_month
left_days_this_month + 1
end
def self.left_days_this_month_ratio
(self.left_days_this_month.to_f / Time.days_in_month(Date.today.month, Date.today.year))
end
def self.days_include_today_remain_current_month_ratio
(self.days_include_today_remain_current_month.to_f / Time.days_in_month(Date.today.month, Date.today.year))
end
def self.seconds_to_words(seconds)
seconds = seconds.to_i
if seconds >= 3600
return "#{seconds / 3600}#{I18n.t(:hour)}#{(seconds % 3600) / 60}#{I18n.t(:minute)}#{seconds % 60}#{I18n.t(:second)}"
elsif seconds >= 60
return "#{(seconds % 3600) / 60}#{I18n.t(:minute)}#{seconds % 60}#{I18n.t(:second)}"
else
return "#{seconds}#{I18n.t(:second)}"
end
end
def self.seconds_to_words_global(seconds)
seconds = seconds.to_i
if seconds >= 3600
return "#{seconds / 3600}:#{((seconds % 3600) / 60).to_s.with_zero_prefix}:#{(seconds % 60).to_s.with_zero_prefix}"
elsif seconds >= 60
return "0:#{((seconds % 3600) / 60).to_s.with_zero_prefix}:#{(seconds % 60).to_s.with_zero_prefix}"
else
return "0:00:#{(seconds).to_s.with_zero_prefix}"
end
end
end | true |
33fc273fd3d38b8dddc4a039d367b02e4ed396d3 | Ruby | Juan1808/EjerciciosRails | /CursoRuby/src/HolaMundo.rb | UTF-8 | 2,122 | 3.703125 | 4 | [] | no_license | puts "Hola Mundo!!"
# Esto es un comentario en Ruby
=begin
Esto serua un comentario
de varias líneas
podemos poner todas las que queramos, los comentarios son muy importantes para el código
=end
#variable es una buena prática declarar siempre las variables en Ruby
#no empiezan con ninguna palabra reservada
#son totalmente arbitrarias, aunque deben empezar por '_' o por una letra
variable1 = 1
puts variable1
variable1= 2
puts variable1
sVariable = "Variable de texto"
iVariable = 3
puts sVariable
puts iVariable
puts "El valor de la variable sVariable es: " + sVariable
#Debemos convertir el tipo Fixnum a String
puts "El valor de la variable iVariable es: " + iVariable.to_s
puts "El valor de la variable sVariable es : #{sVariable}"
#podemos declarar strings con comillas simples
puts "El valor de la variable iVariable es : #{iVariable}"
#Con commillas simples, las variables no se expanden mostrando su contenido
puts 'El valor de la variable sVariable es: #{sVariable}'
variable = nil
#cuando queremos inicializar una variable y no le queremos dar valor, apuntamos a nulo, nil en ruby
puts "El valor de la variable iVariable es : #{variable}"
#Por convenciones el nombre de las variable se suele poner en camel case (la primera letra va en minuscula y las siguientes en mayuscula
#o en snake case (todas las letras de una declaración van en minusculas con guiones bajos entre palabras)
#camel case
estoEsUnaVariable = "variable"
#snake case
esto_es_una_variable = "variable"
#Constantes
#Se declaran poniendo la primera letra en mayúscula
#Ruby es un lenguaje case sensitive
EstoEsUnaConstante = "Juan"
Constante = "Ramon"
Otraconstante = "Pepe"
#Normalmente por convencion de código, las constantes van en mayuscula y en snake case
CONSTANTE = "Isabel"
OTRA_CONSTANTE = "Marta"
puts CONSTANTE
puts "La constante #{OTRA_CONSTANTE}"
#Las constantes en Ruby se pueden cambiar la referencia aunque nos daria un warning. En otros lenguajes no se puede cambiar
#Tenemos también algunas pseudo variables que son varibales predefinidas
#Nos dice la ruta del fichero donde está
puts __FILE__
| true |
d8ca717e145ff03ce599337b2fc55b341f7d1d0c | Ruby | charlottebrf/57-shades-of-ruby | /08_pizza_party.rb | UTF-8 | 4,306 | 4.46875 | 4 | [
"MIT"
] | permissive | # Problem: Write a program to evenly describe pizzas.Prompt for the number of people, the number of pizzas, and the number of slices per pizza. Ensure that the number of pieces comes out even. Display the number of pieces of pizza each person should get. If there are leftovers. show the number of leftover pieces.
#
# Example Output:
# How many people? 8
# How many pizzas do you have? 2
#
# 8 people with 2 pizzas
# Each person gets 2 pieces of pizza.
# There are 0 leftover pieces.
# pseudocode:
# number of people
# prompt "How many people?"
# store number of people
#
# number of pizzas
# prompt "How many pizzas do you have?"
# store number of pizzas
#
# Store gets.chomp data for programme
# def main()
# people = numbger_of_people()
# pizzas = number_of_pizzas()
# do_stuff(people, pizzas)
# end
#
# check for digits(n)
# if digits true
# else false
#
# check for integer
# if integer true
# if float false
#
# confirm number of people & pizzas
# puts "#{number_of_people} with #{number_of_pizzas}"
#
# calculates number of slices(number_of_people, number_of_pizzas)
# number_of_people / number_of_pizzas
# *do I use / or %?
# *"Ensure that the number of pieces comes out even"- even number & even division
#
# rounds number of slices(number_of_slices) ?
# calculates number of slices.to_i
# *Double check how to ensure number of slices is rounded to a whole number*
#
# calculates number of left over slices
# *calculates the remainder*
#
# displays the number of left over slices(remainder)
# puts "There are #{remainder} leftover pieces."
#
# do_stuff main programme
# calls methods in correct order to display
class Calculator
SLICES = 8
def calculates_total_pizza_slices(pizzas)
total_slices = pizzas * SLICES
total_slices
end
#error message if there's 0
def calculates_number_of_pizza_slices_per_person(people, pizzas)
slice_per_person = calculates_total_pizza_slices(pizzas) / people
slice_per_person = slice_per_person.round
if slice_per_person.even?
slice_per_person
else
slice_per_person - 1
end
end
def calculates_number_of_left_over_slices(people, pizzas)
remainder = calculates_number_of_pizza_slices_per_person(people, pizzas) * people
calculates_total_pizza_slices(pizzas) - remainder
end
end
RSpec.describe "evenly divides people between people for a pizza party" do
it "returns true if the string contains digits" do
expect(contains_digits?("123")).to eq (true)
end
it "returns false if the string is 0" do
expect(contains_digits?("0")).to eq (false)
end
it "returns false if the string contains a float" do
expect(contains_digits?("1.1")).to eq (false)
end
it "returns false if the string contains letters or characters" do
expect(contains_digits?("abc")).to eq (false)
end
it "returns false if either of the strings are not a number" do
expect(are_valid?(1.1, 1)).to eq (false)
end
it "returns false if either of the strings are not a number" do
expect(are_valid?(1.1, 3.1)).to eq (false)
end
it "converts a string to a number" do
expect(convert_to_number("12")).to eq (12)
end
it "confirms number of people and pizzas" do
expect{ confirms_people_and_pizzas(4, 2) }.to output(/4 people with 2 pizzas/).to_stdout
end
it "calculates total number of pizza slices for given number of pizzas" do
expect(calculates_total_pizza_slices(2)).to eq (16)
end
it "calculates number of slices per person for an even number of people" do
expect(calculates_number_of_pizza_slices_per_person(8, 2)).to eq (2)
end
it "calculates the number of slices per person for an odd number of people" do
expect(calculates_number_of_pizza_slices_per_person(5, 2)).to eq (2)
end
it "displays the number of slices per person" do
expect{ displays_number_of_slices_per_person(2) }.to output(/2 pieces/).to_stdout
end
it "calculates the number of left over slices for an even number of people" do
expect(calculates_number_of_left_over_slices(8, 2)).to eq (0)
end
it "calculates the number of left over slices for an odd number of people" do
expect(calculates_number_of_left_over_slices(5, 2)).to eq (6)
end
it "displays the number of slices left over" do
expect{ displays_number_of_left_over_slices(6) }.to output(/6 leftover/).to_stdout
end
end
| true |
525c6d2615078c82e260b453c222e1342447e10c | Ruby | greciaro/LeetCode | /1002.rb | UTF-8 | 583 | 3.796875 | 4 | [] | no_license | Given an array A of strings made only from lowercase letters, return a list of all characters that show up in all strings within the list (including duplicates). For example, if a character occurs 3 times in all strings but not 4 times, you need to include that character three times in the final answer.
You may return the answer in any order.
Example 1:
Input: ["bella","label","roller"]
Output: ["e","l","l"]
Example 2:
Input: ["cool","lock","cook"]
Output: ["c","o"]
Note:
1 <= A.length <= 100
1 <= A[i].length <= 100
A[i][j] is a lowercase letter | true |
150702e8bc435c2402558da9b0c4b952e5ee3002 | Ruby | rodrigoruas/food-delivery-01-with-base-repo | /app/views/meals_view.rb | UTF-8 | 455 | 3.375 | 3 | [] | no_license | class MealsView
def initialize
end
def ask_for_name_and_price
puts "What is the name of the meal?"
name = gets.chomp
puts "What is the price of the meal?"
price = gets.chomp.to_i
{name: name, price: price}
end
def display_all(meals)
meals.each_with_index do |meal, index|
puts "#{meal.id} - #{meal.name} - #{meal.price}"
end
end
def ask_for_id
puts "What is id of the meal?"
gets.chomp
end
end
| true |
bad6993d1c0eb49b809cfd983832a04ccb23c884 | Ruby | Edward4j/grape-simple-app | /api/c.rb | UTF-8 | 462 | 2.90625 | 3 | [] | no_license | # module GrapeSampleApp
# def c_constant
# "Hello from module GrapeSampleApp - c_constant!"
# end
class C < Grape::API
puts caller
version 'v1', using: :header, vendor: 'geek.co.il'
format :json
# helpers do
def C.c_constant
"Hello from C c_constant!"
end
# end
desc "Says hello from class C"
get :say_c do
p C.c_constant
"Response from C get :say_c - Hello from C!!!"
end
end
# end
| true |
9c7df76829f6be51157fd890feff7399f1f3bb52 | Ruby | alf-tool/alf-core | /lib/alf/engine/to_array.rb | UTF-8 | 1,695 | 3.09375 | 3 | [
"MIT"
] | permissive | module Alf
module Engine
#
# Ensures an order of tuples, recursing on relation value attributes, that are
# converted as arrays as well.
#
# Example:
#
# res = [
# {:price => 12.0, :rva => Relation(...)},
# {:price => 10.0, :rva => Relation(...)}
# ]
# ToArray.new(res, [:price, :asc]).to_a
# # => [
# # {:price => 10.0, :rva => [...] },
# # {:price => 12.0, :rva => [...] }
# # ]
#
class ToArray
include Cog
# @return [Enumerable] The operand
attr_reader :operand
# @return [Ordering] The ordering info
attr_reader :ordering
# Creates an ToArray instance
def initialize(operand, ordering = nil, expr = nil, compiler = nil)
super(expr, compiler)
@operand = operand
@ordering = ordering
end
# (see Cog#each)
def _each(&block)
operand = ordering ? Sort.new(self.operand, ordering) : self.operand
operand.each do |tuple|
yield recurse(tuple)
end
end
def arguments
[ ordering ]
end
private
def recurse(tuple)
case tuple
when Hash
Hash[tuple.map{|k,v| [ k, reorder(k,v) ] }]
when Tuple
tuple.remap{|k,v| reorder(k, v) }.to_hash
end
end
def reorder(key, value)
if RelationLike===value
subordering = ordering ? ordering.dive(key) : nil
ToArray.new(value, subordering).to_a
elsif TupleLike===value
value.to_hash
else
value
end
end
end # class ToArray
end # module Engine
end # module Alf | true |
19e24bd68982396b32f555a7999105a4bdcfdcf9 | Ruby | the-color-bliu/futbol | /test/game_team_manager_test.rb | UTF-8 | 4,473 | 2.515625 | 3 | [] | no_license | require 'minitest/autorun'
require 'minitest/pride'
require 'mocha/minitest'
require 'Pry'
require './lib/game_team'
require './lib/game_team_manager'
class GameTeamManagerTest < MiniTest::Test
def setup
game_team_path = './data/game_teams_dummy.csv'
@game_team_manager = GameTeamManager.new(game_team_path, 'tracker')
end
def test_it_exists
assert_instance_of GameTeamManager, @game_team_manager
end
def test_create_underscore_game_teams
@game_team_manager.game_teams.each do |game_team|
assert_instance_of GameTeam, game_team
end
end
def test_it_can_find_average_win_percentage
assert_equal 0.88, @game_team_manager.average_win_percentage('6')
end
def test_it_can_get_team_with_best_offense
@game_team_manager.tracker.stubs(:get_team_name).returns('Real Salt Lake')
assert_equal 'Real Salt Lake', @game_team_manager.best_offense
end
def test_it_can_get_team_with_worst_offense
@game_team_manager.tracker.stubs(:get_team_name).returns('Atlanta United')
assert_equal 'Atlanta United', @game_team_manager.worst_offense
end
def test_can_find_most_accurate_team
@game_team_manager.tracker.stubs(:get_season_game_ids).returns(%w[2016030171 2016030172 2016030173 2016030174])
@game_team_manager.tracker.stubs(:get_team_name).returns('Real Salt Lake')
assert_equal 'Real Salt Lake', @game_team_manager.most_accurate_team('20162017')
end
def test_can_find_least_accurate_team
@game_team_manager.tracker.stubs(:get_season_game_ids).returns(%w[2016030171 2016030172 2016030173 2016030174])
@game_team_manager.tracker.stubs(:get_team_name).returns('Toronto FC')
assert_equal 'Toronto FC', @game_team_manager.least_accurate_team('20162017')
end
def test_can_find_team_with_most_tackles
@game_team_manager.tracker.stubs(:get_season_game_ids).returns(%w[2016030171 2016030172 2016030173 2016030174])
@game_team_manager.tracker.stubs(:get_team_name).returns('Toronto FC')
assert_equal 'Toronto FC', @game_team_manager.most_tackles('20162017')
end
def test_can_find_team_with_fewest_tackles
@game_team_manager.tracker.stubs(:get_season_game_ids).returns(%w[2016030171 2016030172 2016030173 2016030174])
@game_team_manager.tracker.stubs(:get_team_name).returns('Real Salt Lake')
assert_equal 'Real Salt Lake', @game_team_manager.fewest_tackles('20162017')
end
def test_can_find_winningest_coach
game_ids = %w[2012020225 2012020577 2012020510 2012020511 2012030223 2012030224 2012030225 2012030311 2012030312 2012030313 2012030314]
assert_equal 'Bruce Boudreau', @game_team_manager.find_winningest_coach(game_ids)
end
def test_can_find_worst_coach
game_ids = %w[2016030171 2016030172 2016030173 2016030174]
assert_equal 'Glen Gulutzan', @game_team_manager.find_worst_coach(game_ids)
end
def test_it_can_find_all_games
@game_team_manager.find_all_games('24').each do |game|
assert_instance_of GameTeam, game
end
assert_equal 5, @game_team_manager.find_all_games('24').length
end
def test_it_can_find_most_goals_scored
assert_equal 4, @game_team_manager.most_goals_scored('6')
end
def test_it_can_find_fewest_goals_scored
assert_equal 0, @game_team_manager.fewest_goals_scored('5')
end
def test_it_can_find_game_ids
assert_equal %w[2012030221 2012030222 2012020577 2012030224 2012030311 2012030312 2012030313 2012030314], @game_team_manager.find_game_ids('6')
end
def test_it_has_a_favorite_team_to_beat
@game_team_manager.tracker.stubs(:get_team_name).returns('Sky Blue FC')
assert_equal 'Sky Blue FC', @game_team_manager.favorite_opponent('6')
end
def test_it_has_a_team_it_hates
@game_team_manager.tracker.stubs(:get_team_name).returns('FC Dallas')
assert_equal 'FC Dallas', @game_team_manager.rival('3')
end
def test_game_and_win_count
game_ids = @game_team_manager.find_game_ids('3')
expected = @game_team_manager.game_and_win_count(game_ids, :team_id, 'WIN', '3')
expected_array = [{ '6' => 3 }, { '6' => 3 }]
assert_equal Array, expected.class
assert_equal Hash, expected[0].class
assert_equal 2, expected.length
assert_equal expected_array, expected
end
def test_sort_accuracy_by_team_id
@game_team_manager.tracker.stubs(:get_season_game_ids).returns(%w[2016030171 2016030172 2016030173 2016030174])
assert_equal [['20', 7.0], ['24', 12.0]], @game_team_manager.sort_accuracy_by_team_id('20162017')
end
end
| true |
ff814f8c848064d3c543933d87bff51eb267a0e8 | Ruby | GeorgieGirl24/sweater-weather | /app/poros/image.rb | UTF-8 | 391 | 2.6875 | 3 | [] | no_license | class Image
attr_reader :image,
:credit
def initialize(image_data, location)
@image = {
location: location,
image_url: image_data[:urls][:regular],
link: image_data[:links][:html],
}
@credit = {
source: 'https://unsplash.com/',
artist: image_data[:user][:name],
artist_link: image_data[:user][:links][:html]
}
end
end
| true |
349e4aa46a89d801de93d2825c1ade079b870079 | Ruby | lintci/laundromat | /lib/command_service.rb | UTF-8 | 600 | 2.59375 | 3 | [] | no_license | # Simple abstraction of common functionality from services
class CommandService
class << self
def call(*args)
new(*args).call
end
def callback(*names)
names.each do |name|
define_method name do |*args, &block|
@_callbacks ||= Hash.new(->(*){})
if block
@_callbacks[__callee__] = block
else
@_callbacks[__callee__].call(*args)
end
end
end
end
end
def transaction
ActiveRecord::Base.transaction(&Proc.new)
end
def call
transaction do
perform
end
end
end
| true |
776da681bc1834af50743f6392d9cfab5832acd0 | Ruby | kyle-baker/tealeaf_precourse | /final_exercises/exercise5.rb | UTF-8 | 128 | 3.703125 | 4 | [] | no_license | # exercise5.rb
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
# Remove from end of array
a.pop
# Append
a.push(3)
p a | true |
d728ae2f122b7a30d42d0f287d55d4908af87f1c | Ruby | yourgirlfriend/Fight-for-the-Skys | /ship.rb | UTF-8 | 2,259 | 2.75 | 3 | [] | no_license | class Ship
attr_reader :x, :y, :height, :width
attr_reader :x, :y, :width, :height, :dead, :iswallleft, :iswallright
attr_accessor :image, :x_velocity, :x, :y
def initialize()
@x = 400
@y = 800
@y_velocity = 10
@width = 71
@height = 120
@dead = false
@frameshipanimcounter = 0
@framer = 0
@image_array = Gosu::Image.load_tiles("f18.png", 71, 120)
@image = @image_array[@framer]
@iswallright = false
@iswallleft = false
#@deathsound = Gosu::Sample.new("ded.ogg")
@dedlay = false
@frameshipdeadcounter = 0
@deadframer = 0
@fflfblarg = false
@dodraw == true
@counter = 0
@angle = 0
end
def draw
if @dead != true
@frameshipanimcounter += 1
if @frameshipanimcounter == 6 && @framer % 2 == 0
@framer += 1
@image = @image_array[@framer % 2]
@image.draw(@x, @y, 2)
@frameshipanimcounter = 0
elsif @frameshipanimcounter == 6 && @framer % 2== 1
@framer += 1
@image = @image_array[@framer % 2]
@image.draw(@x, @y, 2)
@frameshipanimcounter = 0
else
@image.draw(@x, @y, 2)
end
elsif @dead == true
@image = @image_array[@deadframer]
@frameshipdeadcounter += 1
if @frameshipdeadcounter == 5
@frameshipdeadcounter = 0
@deadframer += 1 unless @fflfblarg == true
if @deadframer == @image_array.length - 1
@fflfblarg = true
@dodraw = false
end
end
end
@image.draw(@x, @y, 2) unless @dodraw == false
end
def die(the_window)
@frameshipanimcounter = -10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
@image_array = Gosu::Image.load_tiles("Explosion.png", 157, 229)
@x_velocity = 0
@dead = true
#@deathsound.play unless @dedlay == true
#muse.stop
@dedlay = true
end
def moveleft
@x -= 8
if @x <= 0
@x = 0
end
end
def moveright
@x += 8
if @x >= 730
@x = 730
end
end
def moveup
@y -= 8
if @y <= 0
@y = 0
end
end
def movedown
@y += 8
if @y >= 950
@y = 950
end
end
end | true |
61b9f3e5cecbe7e796d2126ad6e68b34564544f5 | Ruby | DIcove/ror_beginner | /Lesson_5/route.rb | UTF-8 | 836 | 3.328125 | 3 | [] | no_license | # frozen_string_literal: true
# Route
class Route
include InstanceCounter
attr_reader :stations
def initialize(first_station, last_station)
@stations = [first_station, last_station]
register_instance
end
def add_station(station)
return if stations.include?(station)
stations << station
end
def remove_station(station)
return if [first_station, last_station].include? station
stations.delete(station)
end
def name
"#{first_station.name}-#{last_station.name}"
end
private #потому, что юзеру нет необходимости в использовании этих методов, однако он нужны для выполнения публичных методов
def first_station
stations.first
end
def last_station
stations.last
end
end
| true |
c85622ca74b554144ffdc7c1bb8255b24a530ad3 | Ruby | JonathanTrEs/MatricesDensasYDispersas | /lib/MatrizDSL.rb | UTF-8 | 1,193 | 3.265625 | 3 | [
"MIT"
] | permissive | require 'matriz.rb'
class MatrizDSL < Matriz
attr_accessor :resultado
def initialize(tipo_operacion, &block)
@operandos = []
@resultado = nil
@tipo_resultado = :densa
@operacion = :nada
case tipo_operacion
when "suma"
@operacion = :suma
when "resta"
@operacion = :resta
when "multiplicacion"
@operacion = :multiplicacion
else
puts "Tipo de operacion inválido", tipo_operacion
end
if block_given?
if block.arity == 1
yield self
else
instance_eval &block
end
end
end
def operando(mat)
@operandos << Densa.new(mat)
end
def ejecutar
case @operacion
when :suma
@resultado = @operandos[0]+@operandos[1]
@resultado.matriz
when :resta
@resultado = @operandos[0]-@operandos[1]
@resultado.matriz
when :multiplicacion
@resultado = @operandos[0]*@operandos[1]
@resultado.matriz
else
puts "Tipo de operacion incorrecta", @operacion
end
end
end
| true |
cda8d32321d031193ccc01ab7759479c4c569cc1 | Ruby | edyoda/ruby-course | /myGem/lib/mygem.rb | UTF-8 | 96 | 2.890625 | 3 | [] | no_license | class MyGem
def sum(*args)
x = *args
return x.map {| i | i.to_i}.inject(:+)
end
end
| true |
6a45b09fce28c0d4db6937af4349fc6421b5cc92 | Ruby | dgraham/yajl-ffi | /lib/yajl/ffi/parser.rb | UTF-8 | 10,307 | 3.015625 | 3 | [
"MIT"
] | permissive | module Yajl
module FFI
# Raised on any invalid JSON text.
ParserError = Class.new(RuntimeError)
# A streaming JSON parser that generates SAX-like events for state changes.
#
# Examples
#
# parser = Yajl::FFI::Parser.new
# parser.key { |key| puts key }
# parser.value { |value| puts value }
# parser << '{"answer":'
# parser << ' 42}'
class Parser
BUF_SIZE = 4096
CONTINUE_PARSE = 1
FLOAT = /[\.eE]/
# Parses a full JSON document from a String or an IO stream and returns
# the parsed object graph. For parsing small JSON documents with small
# memory requirements, use the json gem's faster JSON.parse method instead.
#
# json - The String or IO containing JSON data.
#
# Examples
#
# Yajl::FFI::Parser.parse('{"hello": "world"}')
# # => {"hello": "world"}
#
# Raises a Yajl::FFI::ParserError if the JSON data is malformed.
#
# Returns a Hash.
def self.parse(json)
stream = json.is_a?(String) ? StringIO.new(json) : json
parser = Parser.new
builder = Builder.new(parser)
while (buffer = stream.read(BUF_SIZE)) != nil
parser << buffer
end
parser.finish
builder.result
ensure
stream.close
end
# Create a new parser with an optional initialization block where
# we can register event callbacks.
#
# Examples
#
# parser = Yajl::FFI::Parser.new do
# start_document { puts "start document" }
# end_document { puts "end document" }
# start_object { puts "start object" }
# end_object { puts "end object" }
# start_array { puts "start array" }
# end_array { puts "end array" }
# key { |k| puts "key: #{k}" }
# value { |v| puts "value: #{v}" }
# end
def initialize(&block)
@listeners = {
start_document: [],
end_document: [],
start_object: [],
end_object: [],
start_array: [],
end_array: [],
key: [],
value: []
}
# Track parse stack.
@depth = 0
@started = false
# Allocate native memory.
@callbacks = callbacks
@handle = Yajl::FFI.alloc(@callbacks.to_ptr, nil, nil)
@handle = ::FFI::AutoPointer.new(@handle, method(:release))
# Register any observers in the block.
instance_eval(&block) if block_given?
end
def start_document(&block)
@listeners[:start_document] << block
end
def end_document(&block)
@listeners[:end_document] << block
end
def start_object(&block)
@listeners[:start_object] << block
end
def end_object(&block)
@listeners[:end_object] << block
end
def start_array(&block)
@listeners[:start_array] << block
end
def end_array(&block)
@listeners[:end_array] << block
end
def key(&block)
@listeners[:key] << block
end
def value(&block)
@listeners[:value] << block
end
# Pass data into the parser to advance the state machine and
# generate callback events. This is well suited for an EventMachine
# receive_data loop.
#
# data - The String of partial JSON data to parse.
#
# Raises a Yajl::FFI::ParserError if the JSON data is malformed.
#
# Returns nothing.
def <<(data)
result = Yajl::FFI.parse(@handle, data, data.bytesize)
error(data) if result == :error
if @started && @depth == 0
result = Yajl::FFI.complete_parse(@handle)
error(data) if result == :error
end
end
# Drain any remaining buffered characters into the parser to complete
# the parsing of the document.
#
# This is only required when parsing a document containing a single
# numeric value, integer or float. The parser has no other way to
# detect when it should no longer expect additional characters with
# which to complete the parse, so it must be signaled by a call to
# this method.
#
# If you're parsing more typical object or array documents, there's no
# need to call `finish` because the parse will complete when the final
# closing `]` or `}` character is scanned.
#
# Raises a Yajl::FFI::ParserError if the JSON data is malformed.
#
# Returns nothing.
def finish
result = Yajl::FFI.complete_parse(@handle)
error('') if result == :error
end
private
# Raise a ParserError for the malformed JSON data sent to the parser.
#
# data - The malformed JSON String that the yajl parser rejected.
#
# Returns nothing.
def error(data)
pointer = Yajl::FFI.get_error(@handle, 1, data, data.bytesize)
message = pointer.read_string
Yajl::FFI.free_error(@handle, pointer)
raise ParserError, message
end
# Invoke all registered observer procs for the event type.
#
# type - The Symbol listener name.
# args - The argument list to pass into the observer procs.
#
# Examples
#
# # Broadcast events for {"answer": 42}
# notify(:start_object)
# notify(:key, 'answer')
# notify(:value, 42)
# notify(:end_object)
#
# Returns nothing.
def notify(type, *args)
@started = true
@listeners[type].each do |block|
block.call(*args)
end
end
# Build a native Callbacks struct that broadcasts parser state change
# events to registered observers.
#
# The functions registered in the struct are invoked by the native yajl
# parser. They convert the yajl callback data into the expected Ruby
# objects and invoke observers registered on the parser with
# `start_object`, `key`, `value`, and so on.
#
# The struct instance returned from this method must be stored in an
# instance variable. This prevents the FFI::Function objects from being
# garbage collected while the parser is still in use. The native function
# bindings need to be collected at the same time as the Parser instance.
#
# Returns a Yajl::FFI::Callbacks struct.
def callbacks
callbacks = Yajl::FFI::Callbacks.new
callbacks[:on_null] = ::FFI::Function.new(:int, [:pointer]) do |ctx|
notify(:start_document) if @depth == 0
notify(:value, nil)
notify(:end_document) if @depth == 0
CONTINUE_PARSE
end
callbacks[:on_boolean] = ::FFI::Function.new(:int, [:pointer, :int]) do |ctx, value|
notify(:start_document) if @depth == 0
notify(:value, value == 1)
notify(:end_document) if @depth == 0
CONTINUE_PARSE
end
# yajl only calls on_number
callbacks[:on_integer] = nil
callbacks[:on_double] = nil
callbacks[:on_number] = ::FFI::Function.new(:int, [:pointer, :string, :size_t]) do |ctx, value, length|
notify(:start_document) if @depth == 0
value = value.slice(0, length)
number = (value =~ FLOAT) ? value.to_f : value.to_i
notify(:value, number)
notify(:end_document) if @depth == 0
CONTINUE_PARSE
end
callbacks[:on_string] = ::FFI::Function.new(:int, [:pointer, :pointer, :size_t]) do |ctx, value, length|
notify(:start_document) if @depth == 0
notify(:value, extract(value, length))
notify(:end_document) if @depth == 0
CONTINUE_PARSE
end
callbacks[:on_start_object] = ::FFI::Function.new(:int, [:pointer]) do |ctx|
@depth += 1
notify(:start_document) if @depth == 1
notify(:start_object)
CONTINUE_PARSE
end
callbacks[:on_key] = ::FFI::Function.new(:int, [:pointer, :pointer, :size_t]) do |ctx, key, length|
notify(:key, extract(key, length))
CONTINUE_PARSE
end
callbacks[:on_end_object] = ::FFI::Function.new(:int, [:pointer]) do |ctx|
@depth -= 1
notify(:end_object)
notify(:end_document) if @depth == 0
CONTINUE_PARSE
end
callbacks[:on_start_array] = ::FFI::Function.new(:int, [:pointer]) do |ctx|
@depth += 1
notify(:start_document) if @depth == 1
notify(:start_array)
CONTINUE_PARSE
end
callbacks[:on_end_array] = ::FFI::Function.new(:int, [:pointer]) do |ctx|
@depth -= 1
notify(:end_array)
notify(:end_document) if @depth == 0
CONTINUE_PARSE
end
callbacks
end
# Convert the binary encoded string data passed out of the yajl parser
# into a UTF-8 encoded string.
#
# pointer - The FFI::Pointer containing the ASCII-8BIT encoded String.
# length - The Fixnum number of characters to extract from `pointer`.
#
# Raises a ParserError if the data contains malformed UTF-8 bytes.
#
# Returns a String.
def extract(pointer, length)
string = pointer.get_bytes(0, length)
string.force_encoding(Encoding::UTF_8)
unless string.valid_encoding?
raise ParserError, 'Invalid UTF-8 byte sequence'
end
string
end
# Free the memory held by a yajl parser handle previously allocated
# with Yajl::FFI.alloc.
#
# It's not sufficient to just allow the handle pointer to be freed
# normally because it contains pointers that must also be freed. The
# native yajl API provides a `yajl_free` function for this purpose.
#
# This method is invoked by the FFI::AutoPointer, wrapping the yajl
# parser handle, when it's garbage collected by Ruby.
#
# pointer - The FFI::Pointer that references the native yajl parser.
#
# Returns nothing.
def release(pointer)
Yajl::FFI.free(pointer)
end
end
end
end
| true |
48745d621ec472fc23e59b363cf1466659ae6f28 | Ruby | AaronRodrigues/lrthw | /ex15.rb | UTF-8 | 621 | 3.671875 | 4 | [] | no_license | filename = ARGV.first #takes in the first argument when running the rb file
txt = open(filename) #opens the file and assigns it to txt
puts "Here's your file #{filename}:" #prints the filename as a string
print txt.read #prints the contents of the file
print "Type the filename again: " #Reuests the file name only a string
file_again = $stdin.gets.chomp # takes the filename and stores it in file_again
txt_again = open(file_again) #opens the file and assigns it to a variable txt_again
print txt_again.read #prints the contents of txt_again
| true |
4e7e4bdc2aeda4109171a2e4c5dadc1ab8c76324 | Ruby | tedconf/graphite_client | /lib/graphite_client.rb | UTF-8 | 631 | 2.625 | 3 | [
"MIT"
] | permissive | require 'socket'
class GraphiteClient
# "host" or "host:port"
def initialize(host)
@host, @port = host.split ':'
@port = 2003 if ! @port
@port = @port.to_i
end
def socket
return @socket if @socket && !@socket.closed?
@socket = TCPSocket.new(@host, @port)
end
def report(key, value, time = Time.now)
begin
socket.write("#{key} #{value.to_f} #{time.to_i}\n")
rescue Errno::EPIPE, Errno::EHOSTUNREACH, Errno::ECONNREFUSED
@socket = nil
nil
end
end
def close_socket
@socket.close if @socket
@socket = nil
end
end
require 'graphite_client/event_reporter'
| true |
0758656998255a30cb049ac7afdc3bcc36a07b1e | Ruby | libkazz/aix_message_delivery-textris | /lib/aix_message_delivery.rb | UTF-8 | 2,527 | 2.890625 | 3 | [
"MIT"
] | permissive | require 'textris'
require 'uri'
require 'net/http'
require 'aix_message_test_delivery'
class AixMessageDelivery < Textris::Delivery::Base
VERSION = '0.1.0'.freeze
API_BASE_URL = 'https://qpd-api.aossms.com/'.freeze
ENDPOINT = "#{API_BASE_URL}/p11/api/mt.json".freeze
SHORTEN_URL_ENDPOINT = "#{API_BASE_URL}/p1/api/shortenurl.json".freeze
MAX_MESSAGE_LENGTH = 70
SPLITTED_MESSAGE_SEND_INTERVAL = 3 # SMS分割時に順序がおかしくなる場合は増やす
class MessageTooLong < StandardError; end
class SMSDeliveryFailed < StandardError; end
class URLShorteningFailed < StandardError; end
def deliver(phone)
contents = shorten_urls_in_message(message.content)
.split('<!-- separator -->')
raise MessageTooLong, "Too Long Message Exists: #{contents.map { |c| [c, c.size] }}" \
if contents.any? { |c| c.size > MAX_MESSAGE_LENGTH }
contents.each do |c|
send_message!(phone, c)
sleep SPLITTED_MESSAGE_SEND_INTERVAL
end
end
private
def send_message!(phone, message)
res = post_request(ENDPOINT, params("+#{phone}", message))
raise SMSDeliveryFailed, res.inspect unless res.is_a?(Net::HTTPOK)
parsed = JSON.parse(res.body)
raise SMSDeliveryFailed, parsed['responseMessage'] if parsed['responseCode'] > 0
parsed
end
def post_request(url, params)
uri = URI.parse(url)
uri.query = URI.encode_www_form(params)
Net::HTTP.post_form(uri, {})
end
def base_params
{
token: ENV['AIX_MESSAGE_ACCESS_TOKEN'],
clientId: ENV['AIX_MESSAGE_CLIENT_ID']
}
end
def params(phone_number, message)
base_params.merge(
smsCode: ENV['AIX_MESSAGE_SMS_CODE'],
phoneNumber: phone_number,
message: message
)
end
def shorten_url!(url)
no_short_regex = /[\?\&]no_short\=true/
return url.remove(no_short_regex) if url =~ no_short_regex
params = base_params.merge(longUrl: url)
res = post_request(SHORTEN_URL_ENDPOINT, params)
raise URLShorteningFailed, res.inspect unless res.is_a?(Net::HTTPOK)
parsed = JSON.parse(res.body)
raise URLShorteningFailed, parsed['responseMessage'] if parsed['responseCode'] > 0
parsed['shortUrl']
end
def shorten_url(url)
shorten_url!(url)
rescue URLShorteningFailed
url
end
def shorten_urls_in_message(message)
URI.extract(message)
.map { |url| [url, shorten_url(url)] }.to_h
.each do |long, short|
message = message.sub(long, short)
end
message
end
end
| true |
f18fc3638b5ff064d577c43d07912764272ba4d5 | Ruby | smithcole264/hw-ruby-intro | /lib/ruby_intro.rb | UTF-8 | 1,095 | 3.875 | 4 | [] | no_license | # When done, submit this entire file to the autograder.
# Part 1
def sum arr
sum = 0
arr.each do |i|
sum += i
end
return sum
end
def max_2_sum arr
sum_2 = 0
sum_2 = arr.sort.last(2).sum
end
def sum_to_n? arr, n
!!arr.uniq.combination(2).detect { |a, b| a + b == n }
end
# Part 2
def hello(name)
greeting = "Hello, "
greeting_name = greeting + name
return greeting_name
end
def starts_with_consonant? s
if /\A(?=[^aeiouAEIOU])(?=[a-z])(?=[A-Z])/i.match(s)
return true
else
return false
end
end
def binary_multiple_of_4? s
if s == "0"
return true
end
if /^[01]*(00)$/.match(s)
return true
else
return false
end
end
# Part 3
class BookInStock
attr_accessor :isbn, :price
def initialize(isbn, price)
raise ArgumentError.new("ISBN must not be empty.") if isbn.nil? || isbn.empty?
raise ArgumentError.new("Price must be greater than 0.") if price <= 0
@isbn = isbn
@price = price
end
def price_as_string
s = '%.2f' % @price
sign = "$"
format = sign + s
return format
end
end
| true |
4a8477d8cdae49387739cd3850ccca3ba58af25f | Ruby | Gurpartap/cognizant | /lib/cognizant/shell.rb | UTF-8 | 3,827 | 2.671875 | 3 | [
"MIT"
] | permissive | require "logger"
require "optparse"
require "readline"
require "shellwords"
require "cognizant/client"
module Cognizant
class Shell
def initialize(options = {})
@app = ""
@app = options[:app] if options.has_key?(:app) and options[:app].to_s.size > 0
@path_to_socket = "/var/run/cognizant/cognizantd.sock"
@path_to_socket = options[:socket] if options.has_key?(:socket) and options[:socket].to_s.size > 0
@@is_shell = true
@@is_shell = options[:shell] if options.has_key?(:shell)
@autocomplete_keywords = []
connect
end
def run(&block)
Signal.trap("INT") do
Cognizant::Shell.emit("\nGoodbye!")
exit(0)
end
emit("Enter 'help' if you're not sure what to do.")
emit
emit("Type 'quit' or 'exit' to quit at any time.")
setup_readline(&block)
end
def setup_readline(&block)
Readline.completion_proc = Proc.new do |input|
case input
when /^\//
# Handle file and directory name autocompletion.
Readline.completion_append_character = "/"
Dir[input + '*'].grep(/^#{Regexp.escape(input)}/)
else
# Handle commands and process name autocompletion.
Readline.completion_append_character = " "
(@autocomplete_keywords + ['quit', 'exit']).grep(/^#{Regexp.escape(input)}/)
end
end
while line = Readline.readline(prompt, true).to_s.strip
if line.size > 0
command, args = parse_command(line)
return emit("Goodbye!") if ['quit', 'exit'].include?(command)
run_command(command, args, &block)
end
end
end
def prompt
@app.to_s.size > 0 ? "(#{@app})> " : "> "
end
def run_command(command, args, &block)
command = command.to_s
begin
response = @client.command({'command' => command, 'args' => args, 'app' => @app})
rescue Errno::EPIPE => e
emit("cognizant: Error communicating with cognizantd: #{e} (#{e.class})")
exit(1)
end
@app = response["use"] if response.is_a?(Hash) and response.has_key?("use")
if block
block.call(response, command)
elsif response.kind_of?(Hash)
puts response['message']
else
puts "Invalid response type #{response.class}: #{response.inspect}"
end
fetch_autocomplete_keywords
end
def parse_command(line)
command, *args = Shellwords.shellsplit(line)
[command, args]
end
def connect
begin
@client = Cognizant::Client.for_path(@path_to_socket)
rescue Errno::ENOENT => e
# TODO: The exit here is a biit of a layering violation.
Cognizant::Shell.emit(<<EOF, true)
Could not connect to Cognizant daemon process:
#{e}
HINT: Are you sure you are running the Cognizant daemon? If so, you
should pass cognizant the socket argument provided to cognizantd.
EOF
exit(1)
end
ehlo if interactive?
fetch_autocomplete_keywords
end
def ehlo
response = @client.command('command' => '_ehlo', 'user' => ENV['USER'], 'app' => @app)
@app = response["use"] if response.is_a?(Hash) and response.has_key?("use")
emit(response['message'])
end
def fetch_autocomplete_keywords
return unless @@is_shell
@autocomplete_keywords = @client.command('command' => '_autocomplete_keywords', 'app' => @app)
end
def self.emit(message = nil, force = false)
$stdout.puts(message || '') if interactive? || force
end
def self.interactive?
# TODO: It is not a tty during tests.
# $stdin.isatty and @@is_shell
@@is_shell
end
def emit(*args)
self.class.emit(*args)
end
def interactive?
self.class.interactive?
end
end
end
| true |
bb788c235a203cacb97834ab10b5f565ebfcddad | Ruby | sangamkaushik/AlgorithmsPractice | /recursion_exercises.rb | UTF-8 | 4,035 | 3.953125 | 4 | [] | no_license | require 'byebug'
# Binary Search
def binary_search arr, target
return nil if arr.length <= 1 && arr[0] != target
middle_idx = arr.length/2
return middle_idx if arr[middle_idx] == target
if target > arr[middle_idx]
right = arr[middle_idx+1..-1]
right_target = binary_search(right, target)
right_target += middle_idx + 1 if right_target
else
left = arr[0...middle_idx]
left_target = binary_search(left, target)
end
target_idx = right_target || left_target
return target_idx if target_idx
nil
end
# Fibonacci - return nth fib
def fibonacci n
return nil if n < 1
return 0 if n == 1
return 1 if n == 2
x = fibonacci(n-1)
y = fibonacci(n-2)
return x+y
end
# Fibonacci - return an array of n fibs
def fibs_list n
return nil if n < 1
return [0] if n==1
return [0,1] if n==2
prev_array = fibs_list(n-1)
current_fib = prev_array[-1] + prev_array[-2]
return (prev_array + [current_fib])
end
# Factorial
def factorial n
return nil if n<0
return 1 if n == 0
return 1 if n == 1
n * factorial(n-1)
end
# Subsets
def subsets arr
return [[]] if arr.length == 0
return [[],[arr[0]]] if arr.length == 1
last_el = arr.dup.pop
prev_subsets = subsets(arr[0...-1])
new_sets = prev_subsets.map do |el|
el + [last_el]
end
prev_subsets + new_sets
end
# Permutations
def permutations str
return [str] if str.length == 1
first_char = str[0]
prev_perms = permutations(str[1..-1])
resultant = []
prev_perms.each do |perm|
(0..perm.length).each do |idx|
resultant << perm.dup.insert(idx,first_char)
end
end
resultant
end
# Arithmetic Permutations
# [1,2] => 2+1, 2-1, 2*1, 2/1, 1-2, 1/2
# [1,2,3] => 2+1+3, 2-1+3, 2*1+3, 2/1+3,
# 2+1-3, 2-1-3, 2*1-3, 2/1-3,
# 2+1*3, 2-1*3, 2*1*3, 2/1*3,
# 2+1/3, 2-1/3, 2*1/3, 2/1/3
# nums is an array of numbers in string format
def arithmetic_permutations nums
return nums if nums.length <= 1
last_char = nums[-1]
prev_perms = arithmetic_permutations(nums[0...-1])
resultant = []
prev_perms.each do |perm|
resultant << (perm + ' + ' + last_char)
resultant << (perm + ' - ' + last_char)
resultant << (perm + ' * ' + last_char)
resultant << (perm + ' / ' + last_char)
end
resultant
end
# def arithmetic_permutations num
# return [""] if num <= 1
# return ['+', '-', '*', '/'] if num == 2
# prev_perms = arithmetic_permutations(num-1)
# resultant = []
# prev_perms.each do |perm|
# resultant << (perm + '+')
# resultant << (perm + '-')
# resultant << (perm + '*')
# resultant << (perm + '/')
# end
# resultant
# end
#num_subsets finds all subsets of the number and returns an array of them.
#num is in string format.
#It essentially inserts spaces at different spots of the string to find all possible subsets.
def num_subsets num
return [num] if num.length <= 1
last_char = num[-1]
prev_subsets = num_subsets(num[0...-1])
resultant = []
prev_subsets.each do |subset|
resultant << subset + last_char
resultant << subset + " " + last_char
end
resultant
end
def triple_byte num,target
subsets = num_subsets(num.to_s) #Covert the number to string, then send it to num_subsets to get all possible subsets.
nums_array = subsets.map{|x| x.split(" ")} #Turn it into better format. Take the spaces out to form numbers.
matches = []
nums_array.map! do |nums|
permutations = arithmetic_permutations(nums) #Insert arithmetic operators at each space to find all permutations possible.
permutations.each do |expression|
puts expression + " = #{target}" if eval(expression) == target
end
end
end
# subsets
# [] => [[]]
# [1] => [[],[1]]
# [1,2] => [[],[1], [2], [1,2]]
# def num_subsets nums
# return [nums] if nums.length <= 1
# last_el = nums[-1]
# prev_subsets = num_subsets(nums[0...-1])
# resultant = []
# new_sets = prev_subsets.map do |subset|
# resultant << subset
# resultant << subset + [last_el]
# end
#
# return resultant
# end
| true |
ebcd68128da058e002e99464fd7c49499653b4c3 | Ruby | klaszcze/codility_lessons | /3_tape_equilibrium.rb | UTF-8 | 297 | 3.25 | 3 | [] | no_license | def solution(a)
right_sum = a.inject(:+) - a[0]
left_sum = a[0]
min_diff = (right_sum - left_sum).abs
1.upto(a.length - 1) do |i|
right_sum -= a[i]
left_sum += a[i]
min_diff = (right_sum - left_sum).abs if (right_sum - left_sum).abs < min_diff
end
return min_diff
end | true |
b7bab41e07aa7a03d6e01f4af9dcd6c4e4f399ee | Ruby | dshue20/interview-prep | /ruby/binary_tree_next.rb | UTF-8 | 1,596 | 3.90625 | 4 | [] | no_license | # You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
# struct Node {
# int val;
# Node *left;
# Node *right;
# Node *next;
# }
# Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
# Initially, all next pointers are set to NULL.
# Follow up:
# You may only use constant extra space.
# Recursive approach is fine, you may assume implicit stack space does not
# count as extra space for this problem.
# Example 1:
# Input: root = [1,2,3,4,5,6,7]
# Output: [1,#,2,3,#,4,5,6,7,#]
# Explanation: Given the above perfect binary tree (Figure A), your function
# should populate each next pointer to point to its next right node, just
# like in Figure B. The serialized output is in level order as connected by
# the next pointers, with '#' signifying the end of each level.
# Constraints:
# The number of nodes in the given tree is less than 4096.
# -1000 <= node.val <= 1000
def connect(root)
queue = [root]
idx = 0
until idx == queue.length do
node = queue[idx]
queue << node.left if node && node.left
queue << node.right if node && node.right
idx += 1
end
skip = 0
level = 1
queue.each_with_index do |node, idx|
if idx == skip
level *= 2
skip += level
else
node.next = queue[idx+1]
end
end
root
end | true |
3954d83d0518cc42464f66d15b380f5dcb6ef967 | Ruby | ztaylorpossible/DailyProg | /Ruby/7e.rb | UTF-8 | 1,732 | 4.0625 | 4 | [] | no_license | # Daily Programmer Easy Challenge #7 June 17, 2013
# Summary:
# Write a program that can translate Morse code in the format of ...---...
# A space and a slash will be placed between words. ..- / --.-
# For bonus, add the capability of going from a string to Morse code.
# Super-bonus if your program can flash or beep the Morse.
# This is your morse to translate: [moved to morse.txt included in folder]
morse_hash = {".-" => 'a', "-..." => 'b', "-.-." => 'c', "-.." => 'd',
"." => 'e', "..-." => 'f', "--." => 'g', "...." => 'h',
".." => 'i', ".---" => 'j', "-.-" => 'k', ".-.." => 'l',
"--" => 'm', "-." => 'n', "---" => 'o', ".--." => 'p',
"--.-" => 'q', ".-." => 'r', "..." => 's', "-" => 't',
"..-" => 'u', "...-" => 'v', ".--" => 'w', "-..-" => 'x',
"-.--" => 'y', "--.." => 'z', ".----" => '1', "..---" => '2',
"...--" => '3', "....-" => '4', "....." => '5', "-...." => '6',
"--..." => '7', "---.." => '8', "----." => '9', "-----" => '0'}
encode_hash = morse_hash.invert
puts "Would you like to translate, or encode to Morse code?"
puts "1) Decode"
puts "2) Write as Morse code"
menu = gets.chomp
puts "Please enter the source file: "
file = gets.chomp
puts "Please enter the output file: "
output_file = gets.chomp
code = IO.binread(file)
text = ""
if menu == '1'
code = code.split(" ")
code.each do |x|
if x != "/"
text << morse_hash[x]
else
text << " "
end
end
elsif menu == '2'
code.each_char do |x|
if x != " "
text << encode_hash[x] << " "
else
text << "/ "
end
end
end
IO.binwrite(output_file, text)
puts text
| true |
67e4b5d8593476ed5f41d9d412feec6fb8b8514d | Ruby | Jaybraum/black_thursday | /spec/invoice_spec.rb | UTF-8 | 2,704 | 2.5625 | 3 | [] | no_license | require './lib/invoice'
RSpec.describe Invoice do
describe 'instantiation' do
it '::new' do
mock_repo = double('InvoiceRepo')
invoice = Invoice.new({:id => 6,
:customer_id => 7,
:merchant_ir => 8,
:status => 'pending',
:created_at => Time.now,
:updated_at => Time.now}, mock_repo)
expect(invoice).to be_an_instance_of(Invoice)
end
it 'has attributes' do
mock_repo = double('InvoiceRepo')
invoice = Invoice.new({:id => 6,
:customer_id => 7,
:merchant_id => 8,
:status => 'pending',
:created_at => Time.now,
:updated_at => Time.now}, mock_repo)
expect(invoice.id).to eq(6)
expect(invoice.customer_id).to eq(7)
expect(invoice.merchant_id).to eq(8)
expect(invoice.status).to eq(:pending)
expect(invoice.created_at).to be_an_instance_of(Time)
expect(invoice.updated_at).to be_an_instance_of(Time)
end
end
describe '#methods' do
it '#updates status' do
mock_repo = double('InvoiceRepo')
invoice = Invoice.new({:id => 6,
:customer_id => 7,
:merchant_id => 8,
:status => 'pending',
:created_at => Time.now,
:updated_at => Time.now}, mock_repo)
invoice.update_status({:status => :shipped})
expect(invoice.status).to eq(:shipped)
end
it '#updates updated at time' do
mock_repo = double('InvoiceRepo')
invoice = Invoice.new({:id => 6,
:customer_id => 7,
:merchant_id => 8,
:status => 'pending',
:created_at => Time.now,
:updated_at => Time.now}, mock_repo)
invoice.update_updated_at({:updated_at => Time.now})
expect(invoice.updated_at).to be_an_instance_of(Time)
end
it '#updates id' do
mock_repo = double('ItemRepo')
invoice = Invoice.new({:id => 6,
:customer_id => 7,
:merchant_id => 8,
:status => 'pending',
:created_at => Time.now,
:updated_at => Time.now}, mock_repo)
new_id = 10000
invoice.update_id(10000)
expect(invoice.id).to eq 10001
end
end
end | true |
551153dd72c9b0c43cbae4b9ed7cfffa352db606 | Ruby | jezman/qna | /app/models/concerns/likable.rb | UTF-8 | 377 | 2.640625 | 3 | [] | no_license | module Likable
extend ActiveSupport::Concern
included do
has_many :likes, dependent: :destroy, as: :likable
end
def vote_up(user)
vote(user, 1)
end
def vote_down(user)
vote(user, -1)
end
def rating_sum
likes.sum(:rating)
end
private
def vote(user, rate)
likes.create!(user: user, rating: rate) unless user.liked?(self)
end
end
| true |
251bea9340ed511ec5f371ac27e8872541a72507 | Ruby | gumgl/project-euler | /67/67.rb | UTF-8 | 489 | 3.375 | 3 | [
"MIT"
] | permissive | def maximum_path_sum(filename)
lines = File.readlines(filename)
triangle = lines.map {|string| string.split(' ').map {|n| Integer(n, 10)}}
(triangle.length-2).downto(0).each {|row|
for col in 0..row
triangle[row][col] = triangle[row][col] + [triangle[row+1][col], triangle[row+1][col+1]].max
end
}
return triangle[0][0]
end
puts "Problem 18 solution: %d" % maximum_path_sum("../18/triangle.txt")
puts "Problem 67 solution: %d" % maximum_path_sum("triangle.txt")
| true |
5f0dfda94e1c3acbfe5c0756748e697ffd5c7133 | Ruby | kristianmandrup/geo_units | /lib/geo_units/core_ext.rb | UTF-8 | 2,254 | 3.203125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'sugar-high/numeric'
module GeoUnitExt
::GeoUnits.units.each do |unit_type|
define_method "#{unit_type}_to" do |unit|
unit = GeoUnits.normalized(unit)
self.to_f * GeoUnits::Maps::Meters.from_unit[unit_type] * GeoUnits::Maps::Meters.to_unit[unit]
end
end
include NumberDslExt # from sugar-high
def to_rad
GeoUnits::Converter.to_rad self
end
alias_method :to_radians, :to_rad
alias_method :degrees_to_rad, :to_radians
alias_method :deg_to_rad, :to_radians
end
class Numeric
include GeoUnitExt
include ::GeoUnits::Numeric
include ::GeoUnits::Numeric::Dms
include ::GeoUnits::Numeric::Normalizer
end
class String
def parse_dms options = {}
GeoUnits::Converter::Dms.parse_dms self, options
end
def to_lng
self.match(/[E|W]/) ? self.to_i : nil
end
def to_lat
self.match(/[N|S]/) ? self.to_i : nil
end
end
class Array
def to_dms direction = nil
lng, lat = extract_coords(direction)
res = direction == :lat_lng ? [lat.to_lat_dms, lng.to_lng_dms] : [lng.to_lng_dms, lat.to_lat_dms]
res.join(', ')
end
def parse_dms direction = nil
lng, lat = extract_coords(direction)
direction == :lat_lng ? [lat.parse_dms, lng.parse_dms] : [lng.parse_dms, lat.parse_dms]
end
protected
def extract_coords direction = nil
direction ||= GeoUnits.default_coords_order
unless [:lng_lat, :lat_lng].include? direction
raise ArgumentError, "Direction must be either :lng_lat or :lat_lng, was: #{direction}. You can also set the default direction via GeoUnits#default_direction="
end
lat_index = direction == :reverse ? 0 : 1
lng_index = direction == :reverse ? 1 : 0
lat = self.to_lat if self.respond_to?(:to_lat)
lat ||= self[lat_index] if self[lat_index].respond_to?(:to_lat) && self[lat_index].to_lat
lat ||= self[lng_index] if self[lng_index].respond_to?(:to_lat) && self[lng_index].to_lat
lat ||= self[lat_index]
lng = self.to_lng if self.respond_to?(:to_lng)
lng ||= self[lng_index] if self[lng_index].respond_to?(:to_lng) && self[lng_index].to_lng
lng ||= self[lat_index] if self[lat_index].respond_to?(:to_lng) && self[lat_index].to_lng
lng ||= self[lng_index]
[lng, lat]
end
end
| true |
395211acb46f9e0d94983761c4ea47b91d7b83b1 | Ruby | t-kot/bungakuhub | /features/step_definitions/branch_steps.rb | UTF-8 | 1,076 | 2.859375 | 3 | [] | no_license | #coding: utf-8
#language: ja
もし /^以下のブランチが存在している:$/ do |table|
table.rows.each do |repo, branch|
Repository.find_by_name(repo).branches.create(name:branch)
end
end
もし /^以下のブランチを作成する:$/ do |table|
table.rows.each do |repo, branch|
Repository.find_by_name(repo).branches.create(name:branch)
end
end
もし /^"(.*)"の"(.*)"ブランチから"(.*)"ブランチを作成する$/ do |repo, orig_branch, new_branch|
orig_branch = Repository.find_by_name(repo).branches.find_by_name(orig_branch)
new_branch = orig_branch.checkout({name:new_branch})
new_branch.save
end
もし /^"(.*)"という名前でブランチを作成する$/ do |name|
fill_in "ブランチ名", with: name
click_button("Save")
end
ならば /^"(.*)"ブランチが存在すること$/ do |branch_name|
step %Q["#{branch_name}"と表示されていること]
end
ならば /^正常にブランチが作成されていること$/ do
step %Q["ブランチが作成されました"と表示されていること]
end
| true |
a2d2a8f07fa734973d5cb23aefc0dbbb0ea10e03 | Ruby | brady-robinson/launchschool-introRuby | /loopsiterators/each_with_index.rb | UTF-8 | 101 | 3.515625 | 4 | [] | no_license | x = ["Do", "Go", "My", "Love"]
x.each_with_index do |item, index|
puts "#{index + 1}. #{item}"
end | true |
6609f085df1a2d7a438c2a76df64a6efef4529ab | Ruby | das11706/happy_plastics | /lib/happy_plastics/plastic.rb | UTF-8 | 381 | 2.8125 | 3 | [
"MIT"
] | permissive | class HappyPlastics::Plastic
attr_accessor :num, :name, :facts
@@all = []
def initialize(num, name)
@num = num
@name = name
@facts = []
save
end
def self.all
HappyPlastics::Scraper.scrape_plastic if @@all.empty?
@@all
end
def get_fact
HappyPlastics::Scraper.scrape_fact(self)
end
def save
@@all << self
end
end | true |
31e4d6b97e771c551f0474cfc9b3133d3c53e881 | Ruby | fuadsaud/uniTunes | /app/interactions/purchase_medium.rb | UTF-8 | 1,635 | 2.75 | 3 | [] | no_license | class PurchaseMedium
def call(user:, medium_id:)
wallet = find_wallet(user)
medium = find_medium(medium_id)
purchase = Purchase.new(split_shares(medium.price).merge(
wallet: wallet,
medium: medium,
amount: medium.price
))
if purchase.valid?
begin
response = ActiveRecord::Base.transaction do
perform_purchase_transaction(purchase)
end
purchase = response.purchase
rescue PerformTransaction::NotEnoughFundsError => e
purchase.errors.add(:wallet, e.message)
end
end
Response.new(medium: medium, purchase: purchase)
end
private
attr_reader :user
def split_shares(amount)
SplitShareStrategy.default.call(amount)
end
def perform_purchase_transaction(purchase)
PerformTransaction.new.call(purchase: purchase)
end
def find_wallet(user)
user.wallet
end
def find_medium(medium_id)
medium_scope.find(medium_id)
end
def medium_scope
Medium.all
end
class SplitShareStrategy
def self.default
new(author_share: 0.9, admin_share: 0.1)
end
def initialize(author_share:, admin_share:)
raise ArgumentError unless (author_share + admin_share) == 1
@author_share = author_share
@admin_share = admin_share
end
def call(amount)
{ author_amount: amount * author_share, admin_amount: amount * admin_share }
end
private
attr_reader :author_share, :admin_share
end
Response = ImmutableStruct.new(:medium, :purchase) do
def success?
purchase.persisted?
end
def failed?
!success?
end
end
end
| true |
31e86e13ed5475c72f57f5bea367ffba1cf35715 | Ruby | yourkarma/daemonic | /lib/daemonic/pool.rb | UTF-8 | 1,750 | 2.9375 | 3 | [
"MIT"
] | permissive | # Stolen from RubyTapas by Avdi Grimm, episode 145.
module Daemonic
class Pool
class StopSignal
def inspect
"[STOP SIGNAL]"
end
alias_method :to_s, :inspect
end
STOP_SIGNAL = StopSignal.new
attr_reader :producer
def initialize(producer)
@producer = producer
@jobs = SizedQueue.new(producer.queue_size)
@threads = producer.concurrency.times.map {|worker_num|
Thread.new do
dispatch(worker_num)
end
}
end
def enqueue(job)
logger.debug { "Enqueueing #{job.inspect}" }
@jobs.push(job)
end
alias_method :<<, :enqueue
def stop
@threads.size.times do
enqueue(STOP_SIGNAL)
end
@threads.each(&:join)
end
private
def dispatch(worker_num)
logger.debug { "T#{worker_num}: Starting" }
loop do
job = @jobs.pop
if STOP_SIGNAL.equal?(job)
logger.debug { "T#{worker_num}: Received stop signal, terminating." }
break
end
begin
logger.debug { "T#{worker_num}: Consuming #{job.inspect}" }
worker.consume(job)
Thread.pass
rescue Object => error
if error.is_a?(SystemExit) # allow app to exit
logger.warn { "T#{worker_num}: Received SystemExit, shutting down" }
producer.stop
else
logger.warn { "T#{worker_num}: #{error.class} while processing #{job}: #{error}" }
logger.info { error.backtrace.join("\n") }
end
Thread.pass
end
end
logger.debug { "T#{worker_num}: Stopped" }
end
def worker
producer.worker
end
def logger
producer.logger
end
end
end
| true |
31d57151b46a570098f9308f157d872bb29ab2cc | Ruby | sebastianmendo1995/aA-classwork | /W2D4/Sebastian_Mendo_more_problems.rb | UTF-8 | 6,529 | 3.640625 | 4 | [] | no_license | def no_dupes?(arr)
ans = []
(0...arr.length).each do |i|
temp = arr[0...i] + arr[i+1..-1]
if !temp.include?(arr[i])
ans << arr[i]
end
end
ans
end
p no_dupes?([1, 1, 2, 1, 3, 2, 4]) # => [3, 4]
p no_dupes?(['x', 'x', 'y', 'z', 'z']) # => ['y']
p no_dupes?([true, true, true]) # => []
p '------------------------------------'
def no_consecutive_repeats?(arr)
(0...arr.length-1).each { |idx| return false if arr[idx] == arr[idx+1] }
true
end
p no_consecutive_repeats?(['cat', 'dog', 'mouse', 'dog']) # => true
p no_consecutive_repeats?(['cat', 'dog', 'dog', 'mouse']) # => false
p no_consecutive_repeats?([10, 42, 3, 7, 10, 3]) # => true
p no_consecutive_repeats?([10, 42, 3, 3, 10, 3]) # => false
p no_consecutive_repeats?(['x']) # => true
p '------------------------------------'
def char_indices(str)
hash = Hash.new {|k,v| k[v]= []}
str.split("").each_with_index do |char, idx|
hash[char] << idx
end
hash
end
p char_indices('mississippi') # => {"m"=>[0], "i"=>[1, 4, 7, 10], "s"=>[2, 3, 5, 6], "p"=>[8, 9]}
p char_indices('classroom') # => {"c"=>[0], "l"=>[1], "a"=>[2], "s"=>[3, 4], "r"=>[5], "o"=>[6, 7], "m"=>[8]}
p '------------------------------------'
def longest_streak(str)
letter = ""
(0...str.length).each do |i|
count = 1
(i+1...str.length).each do |j|
if str[i] == str[j]
count += 1
else
break
end
end
if count >= letter.length
letter=""
count.times do
letter += str[i]
end
end
end
letter
end
p longest_streak('a') # => 'a'
p longest_streak('accccbbbbaaa')# => 'bbbb'
p longest_streak('aaaxyyyyyzz') # => 'yyyyy
p longest_streak('aaabbb') # => 'bbb'
p longest_streak('abc') # => 'c'
p '------------------------------------'
def bi_prime?(num)
return false if num < 2
primes = get_primes(num)
primes.each do |prime1|
primes.each do |prime2|
return true if prime1*prime2 == num
end
end
false
end
def get_primes(num)
arr = []
(2...num).each do |n|
arr << n if is_prime?(n)
end
arr
end
def is_prime?(num)
return false if num < 2
(2...num).each do |factor|
return false if num % factor == 0
end
true
end
p bi_prime?(14) # => true
p bi_prime?(22) # => true
p bi_prime?(25) # => true
p bi_prime?(94) # => true
p bi_prime?(24) # => false
p bi_prime?(64) # => false
p '------------------------------------'
def vigenere_cipher(str,keys)
alpha = ('a'..'z').to_a
start = 0
(0...str.length).each do |i|
index = alpha.index(str[i]) + keys[start%keys.length]
str[i] = alpha[index % 26]
start += 1
end
str
end
p vigenere_cipher("toerrishuman", [1]) # => "upfssjtivnbo"
p vigenere_cipher("toerrishuman", [1, 2]) # => "uqftsktjvobp"
p vigenere_cipher("toerrishuman", [1, 2, 3]) # => "uqhstltjxncq"
p vigenere_cipher("zebra", [3, 0]) # => "ceerd"
p vigenere_cipher("yawn", [5, 1]) # => "dbbo"
p '------------------------------------'
def vowel_rotate(str)
vowels = "aeiou"
arr_vowels = []
str.each_char {|char| arr_vowels << char if vowels.include?(char)}
last = arr_vowels.pop
arr_vowels.unshift(last)
replace = 0
str.each_char.with_index do |char, idx|
if vowels.include?(char)
str[idx] = arr_vowels[replace]
replace += 1
end
end
end
p vowel_rotate('computer') # => "cempotur"
p vowel_rotate('oranges') # => "erongas"
p vowel_rotate('headphones') # => "heedphanos"
p vowel_rotate('bootcamp') # => "baotcomp"
p vowel_rotate('awesome') # => "ewasemo"
p '------------------------------------'
class String
def select(&prc)
prc ||= Proc.new{}
str = ""
self.each_char {|char| str += char if prc.call(char)}
str
end
def map!(&prc)
self.each_char.with_index do |char, idx|
self[idx] = prc.call(char)
end
end
end
p "app academy".select { |ch| !"aeiou".include?(ch) } # => "pp cdmy"
p "HELLOworld".select { |ch| ch == ch.upcase } # => "HELLO"
p "HELLOworld".select # => ""
p '------------------------------------'
word_1 = "Lovelace"
word_1.map! do |ch|
if ch == 'e'
'3'
elsif ch == 'a'
'4'
else
ch
end
end
p word_1 # => "Lov3l4c3"
# word_2 = "Dijkstra"
# word_2.map! do |ch, i|
# if i.even?
# ch.upcase
# else
# ch.downcase
# end
# end
# p word_2 # => "DiJkStRa"
p '------------------------------------'
#Recursion Problemsdef multiply(a, b)
def multiply(a, b)
return a if b == 1
return a if b == -1
sum = 0
b > 0 ? b-=1 : b+= 1
sum += a + multiply(a,b)
end
p multiply(3, 5) # => 15
p multiply(5, 3) # => 15
p multiply(2, 4) # => 8
p multiply(0, 10) # => 0
p multiply(-3, -6) # => 18
p multiply(3, -6) # => -18
p multiply(-3, 6) # => -18
p '------------------------------------'
def lucas_sequence(num)
return [] if num == 0
return [2] if num == 1
return [2,1] if num == 2
lucas_sequence(num-1) << lucas_sequence(num-1)[-1] + lucas_sequence(num-2)[-1]
end
p lucas_sequence(0) # => []
p lucas_sequence(1) # => [2]
p lucas_sequence(2) # => [2, 1]
p lucas_sequence(3) # => [2, 1, 3]
p lucas_sequence(6) # => [2, 1, 3, 4, 7, 11]
p lucas_sequence(8) # => [2, 1, 3, 4, 7, 11, 18, 29]
p '------------------------------------'
def prime_factorization(num)
return [num] if is_prime?(num)
ans = []
(0...num).each do |i|
if is_prime?(i) && num % i == 0
ans << i
num = num / i
break
end
end
ans += prime_factorization(num).flatten
ans
end
def is_prime?(num)
return false if num < 2
(2...num).each {|factor| return false if num%factor==0}
true
end
p prime_factorization(12) # => [2, 2, 3]
p prime_factorization(24) # => [2, 2, 2, 3]
p prime_factorization(25) # => [5, 5]
p prime_factorization(60) # => [2, 2, 3, 5]
p prime_factorization(7) # => [7]
p prime_factorization(11) # => [11]
p prime_factorization(2017) # => [2017]
p prime_factorization(288) | true |
dc5f4dd8bea5f2ac8bf551a21c77105180b29eaa | Ruby | ElContreh/curalito | /main.rb | UTF-8 | 4,553 | 2.828125 | 3 | [] | no_license | require 'telegram/bot'
require 'i18n'
require_relative 'dependencies/gen-dep.rb'
I18n.load_path << Dir[File.expand_path("text") + "/*.yml"]
#Methods
#Funciones
def set_user(users, message)
#Comprobar si ya ha escrito y ver su estado
#Check if the user has written something already, and see their status.
v = -1 #Index of the found (or created) user. It's in -1 because it's an impossible number, so I take it as a nil / Index del usuario encontrado (o creado) en el array. Esta en -1 porque es un numero que es imposible que se encuentre en la array
users.each do |userLoop|
#Encontrar al usuario entre el array de usuarios. Si el la id del usuario y la id del chat del usuario en el array coinciden con el autor del mensaje actual, entonces encontramos al usuario en el array.
#Find de user in the array of users. If the id of the chat and the id of the user match with the author of the current message, then we have found the user in the array.
if (userLoop.message.from.id == message.from.id) && (userLoop.message.message.chat.id == message.message.chat.id)
v = users.find_index(userLoop)
break
end
end
#Si no encuentra, crear un usuario en la posición 0.
#If we don't find it, we create it in position 0.
if v == -1
users.unshift(User.new(message))
v = 0
end
#Regresar el usuario en el array.
#Return the user in the array.
return users[v]
end
def multim(user)
message = user.message
configm_path = "userconfig/#{message.from.id.to_s}/chatm.txt"
userconfig_dir = "userconfig/#{message.from.id.to_s}"
if !File.exists?(configm_path)
BOT.api.send_message(chat_id: message.chat.id, text: I18n.t('m.notconfigured'))
return
end
begin
if !message.photo.empty?
BOT.api.send_photo(chat_id: File.read(configm_path).to_i, photo: message.photo.last.file_id)
elsif message.sticker != nil
BOT.api.send_sticker(chat_id: File.read(configm_path).to_i, sticker: message.sticker.file_id)
elsif message.video != nil
BOT.api.send_video(chat_id: File.read(configm_path).to_i, video: message.video.file_id)
elsif message.voice != nil
BOT.api.send_voice(chat_id: File.read(configm_path).to_i, voice: message.voice.file_id)
elsif message.video_note != nil
BOT.api.send_video_note(chat_id: File.read(configm_path).to_i, video_note: message.video_note.file_id)
end
rescue
BOT.api.send_message(chat_id: message.chat.id, text: I18n.t('m.error'))
end
end
def set_locale(user)
locale = :en
locale = File.read("userconfig/#{user.message.from.id}/locale.txt").chomp.to_sym if File.exists?("userconfig/#{user.message.from.id}/locale.txt")
return locale
end
def check_status(user)
if !user.command.nil?
state(user)
end
end
#Main program.
#Programa principal.
def main()
Dir.mkdir "chats" if !File.directory? "chats"
Dir.mkdir "userconfig" if !File.directory? "userconfig"
#Crear una array de usuarios donde guardarlos a todos.
#Create an array of users to store them all
users = Array.new
#Loop principal que escucha nuevos mensajes.
#Main loop that listens to new messages.
BOT.listen do |message|
#Crear una variable user para tener un acceso mas comodo al usuario en si.
#Create the user variable to access the user easier in the code.
user = set_user(users,message)
user.message = message
I18n.locale = set_locale(user)
case message
when Telegram::Bot::Types::Message
if message.text != nil
if message.text[0] == '/'
#Commmand
Dir[File.expand_path("commands") + "/*/*.rb"].each do |path|
if "#{message.text.stop_at_space}.rb" == "/#{File.basename(path)}"
load path
run(user)
user.command = message.text.stop_at_space.sub("/","")
end
end
elsif message.reply_to_message != nil && message.reply_to_message.from.username == NAME
#Reply
check_status(user)
end
elsif message.chat.type == 'private'
multim(user)
user.dump = true
else
user.dump = true
end
when Telegram::Bot::Types::CallbackQuery
check_status(user)
end
if user.dump == true
users.delete(user)
end
end
end
log = Logger.new('log.txt')
loop do
begin
main()
rescue Faraday::ConnectionFailed => err
puts err
rescue StandardError => err
log.fatal(err)
puts err
exit
end
end
| true |
ffad1100be009db48803b9aff698fda71fb9a2ee | Ruby | geczirebeka/w1_d2_functions_lab | /ruby_functions_practice.rb | UTF-8 | 1,054 | 3.9375 | 4 | [] | no_license | def return_10()
return 10
end
def add(add_one, add_two)
return add_one + add_two
end
def subtract(sub_1, sub_2)
return sub_1 - sub_2
end
def multiply(mult_1, mult_2)
return mult_1 * mult_2
end
def divide(divi_1, divi_2)
return divi_1 / divi_2
end
def length_of_string(string)
return string.length
end
def join_string(string_1, string_2)
return string_1 + string_2
end
def add_string_as_number(str_1, str_2)
return str_1.to_i + str_2.to_i
end
def number_to_full_month_name(month)
case month
when 1
"January"
when 3
"March"
when 9
"September"
else
"invalid"
end
end
def number_to_short_month_name(names)
case names
when 1
"Jan"
when 4
"Apr"
when 10
"Oct"
else
"invalid"
end
end
def volume(volume_1, volume_2, volume_3)
return volume_1 * volume_2 * volume_3
end
def sphere(n_1, n_2, n_3, n_4, n_5)
return n_1 * n_2 * n_3 * n_4 * n_5
end
def celsius(c_1, c_2, c_3, c_4)
result = (c_1 - c_2) * c_3 / c_4
return result
end | true |
b2c732bd3cc31ab28ce86d3a162d74141eaecc82 | Ruby | styd/smart_kv | /lib/smart_kv/core.rb | UTF-8 | 1,865 | 2.671875 | 3 | [
"MIT"
] | permissive | require 'set'
require_relative "errors"
require_relative "helper"
module SmartKv::Core
include SmartKv::Helper
def required(*args)
init_required
@required += args
@optional -= @required if @optional
@required
end
def required_keys
init_required
@required.to_a
end
def init_required
@required ||= superclass == SmartKv ? ::Set.new : superclass.required.dup
end
def optional(*args)
init_optional
@optional += args
@required -= @optional if @required
@optional
end
def optional_keys
init_optional
@optional.to_a
end
def init_optional
@optional ||= superclass == SmartKv ? ::Set.new : superclass.optional.dup
end
def keys
init_required; init_optional
@required + @optional
end
def check(kv={})
prevent_direct_usage
object_class = callable_class || kv.class
kv = kv.dup
unless SmartKv::Helper.production?
hash = kv.to_h
missing_keys = required_keys - hash.keys
unless missing_keys.empty?
raise SmartKv::KeyError, "missing required key(s): #{missing_keys.map{|k| k.to_sym.inspect }.join(', ')} in #{self.class}"
end
unrecognized_keys = hash.keys - keys.to_a
unless unrecognized_keys.empty?
key = unrecognized_keys.first
raise SmartKv::KeyError.new("unrecognized key: #{key.inspect} in #{self}.", key: key, receiver: (keys - hash.keys).map {|k| [k, nil] }.to_h)
end
end
return to_callable_object(object_class, kv)
end
alias_method :new, :check
def callable_as(klass)
@callable_as = superclass == SmartKv ? klass : superclass.callable_class
end
def callable_class
@callable_as
end
private
def prevent_direct_usage
if self == SmartKv
raise SmartKv::DirectUsageError, "only subclass of SmartKv is meant to be used".freeze
end
end
end
| true |
33da813c8c7c6582e8be3195fdeec5338e4fcd04 | Ruby | ICC4103-202010-WebTech/lab5-lab5-figueroa-izquierdo | /lib/tasks/model_queries.rake | UTF-8 | 1,972 | 2.703125 | 3 | [] | no_license | namespace :db do
task :populate_fake_data => :environment do
# If you are curious, you may check out the file
# RAILS_ROOT/test/factories.rb to see how fake
# model data is created using the Faker and
# FactoryBot gems.
puts "Populating database"
# 10 event venues is reasonable...
create_list(:event_venue, 10)
# 50 customers with orders should be alright
create_list(:customer_with_orders, 50)
# You may try increasing the number of events:
create_list(:event_with_ticket_types_and_tickets, 10)
end
task :model_queries => :environment do
# Sample query: Get the names of the events available and print them out.
# Always print out a title for your query
puts("Query 0: Sample query; show the names of the events available")
result = Event.select(:name).distinct.map { |x| x.name }
puts(result)
puts("EOQ") # End Of Query -- always add this line after a query.
end
task :task_2 => :environment do
puts "Total number of different events a customer has attended"
result = Customer.select(:name).group(:orders).count
puts(result)
puts("EOQ")
end
task :task_1 => :environment do
puts(" total number bought by given customer")
result = Customer.include(:tickets).count(:tickets)
puts(result)
puts("EOQ")
end
task :task3 => :environment do
puts(" name of hte event assisted by a given customer")
result = Event.select(:name).group(:name).where(customer.id = 001)
puts(result)
puts("EOQ")
end
task :task5 => :environment do
puts(" total sold by an event")
result = Ticket.group.includes(:event.name).sum(ticket_price)
puts(result)
puts("EOQ")
end
task :task7 => :environment do
puts(" event most attended by men of 18 to 30")
result = event.select(:name).where("customer.age >= 18 AND customer.age <= 30", {Customer.age, params[:customer.age]}).group(:event.name)
puts(result)
puts("EOQ")
end
end | true |
6af807f16c5c0686fba4e8aaad05444abf000c4d | Ruby | captproton/scooter_on_rails | /lib/tasks/mqtt_publish.thor | UTF-8 | 2,481 | 2.65625 | 3 | [] | no_license | require "thor"
require 'mqtt' # gem install mqtt ; https://github.com/njh/ruby-mqtt
class MqttPublication < Thor
ADAFRUIT_THROTTLE_PUBLISHES_PER_SECOND = 2 # limit to N requests per second
# Required
require "./config/environment"
ADAFRUIT_USER = ENV['ADAFRUIT_USER'].freeze
ADAFRUIT_IO_KEY = ENV['ADAFRUIT_IO_KEY'].freeze
# Optional
ADAFRUIT_HOST = (ENV['ADAFRUIT_HOST'] || 'io.adafruit.com').freeze
ADAFRUIT_PORT = (ENV['ADAFRUIT_PORT'] || 1883).freeze
ADAFRUIT_FORMAT = ENV['ADAFRUIT_FORMAT'].freeze
# ---
# Allow filtering to a specific format
#ADAFRUIT_DOCUMENTED_FORMATS = %w( csv json xml ).freeze
# Adafruit-MQTT doesn't support XML 160619
ADAFRUIT_MQTT_FORMATS = %w( csv json ).freeze
FORMAT_REGEX_PATTERN = %r{/(csv|json)$}
FILTER_FORMAT = if ADAFRUIT_FORMAT.nil?
nil
elsif ADAFRUIT_MQTT_FORMATS.include?(ADAFRUIT_FORMAT)
"/#{ADAFRUIT_FORMAT}".freeze
else
$stderr.puts("Unsupported format (#{ADAFRUIT_FORMAT})")
exit 1
end
ADAFRUIT_CONNECT_INFO = {
username: ADAFRUIT_USER,
password: ADAFRUIT_IO_KEY,
host: ADAFRUIT_HOST,
port: ADAFRUIT_PORT
}.freeze
## thor methods
desc "hello NAME", "say hello to NAME"
def hello(name)
option :from, :required => true
option :yell, :type => :boolean
output = []
output << "from: #{options[:from]}" if options[:from]
output << "Hello #{name}"
output = output.join("\n")
puts options[:yell] ? output.upcase : output
end
desc "send feed_name [value or payload]/[format if any]", "publish to a subscription"
def send(feed_name, value_arg)
MQTT::Client.connect(ADAFRUIT_CONNECT_INFO) do |client|
feed = feed_name
value = value_arg # arg is frozen and MQTT wants to force encode
topic = if ADAFRUIT_FORMAT.nil? || feed.end_with?(ADAFRUIT_FORMAT)
"#{ADAFRUIT_USER}/f/#{feed}"
else
"#{ADAFRUIT_USER}/f/#{feed}/#{ADAFRUIT_FORMAT}"
end
$stderr.puts "Publishing #{value} to #{topic} @ #{ADAFRUIT_HOST}"
client.publish(topic, value)
sleep(1.0 / ADAFRUIT_THROTTLE_PUBLISHES_PER_SECOND)
end
exit 0
end
end
# MqttSubscription.start(ARGV) | true |
ed1810af604e3432f9854e244d65ab7b9f1809ec | Ruby | keynmol/octane | /lib/octane/network.rb | UTF-8 | 2,137 | 2.6875 | 3 | [
"MIT"
] | permissive |
module Octane
class LayerDelegator
include Enumerable
def initialize(net, layer)
@layer=net.layers[layer]
@net=net
@layer_number=layer
end
def each
@layer.each {|u| yield u}
end
def unit(unit_number)
return @layer[unit_number]
end
def disable(units)
@net.disable_unit(@layer_number, units)
end
def enable(units)
@net.enable_unit(@layer_number,units)
end
def enable_all
@net.enable_unit(@layer_number,(0...@layer.size).to_a)
end
def size
@layer.size
end
end
class Network
attr_accessor :layers
attr_accessor :verbose
attr_accessor :input_transformation
include Dropout
include Backpropagation
include Test
include Training
include Plotting
include Construct
def initialize(opts={})
@layers=[]
@learning_rate=opts[:learning_rate]|| 0.001
@weight_decay=opts[:weight_decay] || 0.0
@weight_norm=opts[:weight_norm] || 0.0
@bias=opts[:bias].nil? ? true : opts[:bias]
@pruning=opts[:pruning]||0.0
end
def add_bias
@bias
end
def forward_pass(input)
previous_layer=nil
@layers.each_with_index{ |layer, layer_number|
if layer_number==0
previous_layer=@layers[0].each_with_index.map{|input_neuron, input_neuron_number| input_neuron.set_squashed(input[input_neuron_number]); input_neuron.disabled ? 0.0 : input[input_neuron_number] }
else
cl=previous_layer.clone
cl+=[0.0] if add_bias
layer_outputs=layer.each_with_index.map{|neuron, index|
outp=neuron.output(cl)
puts "Calculating output of neuron #{index} on layer #{layer_number}. Inputs: #{cl}. Output: #{outp}" if @verbose;
outp
}
previous_layer=layer_outputs
end
}
previous_layer
end
def get_activations(data, squashed=false, layer=nil)
layer=@layers.size-1 unless layer
data.map{|example,output| forward_pass(example); @layers[layer].map{|neuron| squashed ? neuron.last_squashed : neuron.last_activity}}
end
def eval(example)
forward_pass(example)
end
def copy
Marshal.load(Marshal.dump(self))
end
end
end | true |
ca0576d9a4fabd985e6128b101e43400e134b671 | Ruby | Quarkex/beatroot_challenge | /lib/beatroot.rb | UTF-8 | 1,804 | 2.90625 | 3 | [] | no_license | require 'net/http'
require 'net/https'
require 'uri'
require 'json'
require_relative 'track'
require_relative 'release'
class Beatroot
attr_accessor :token, :api_base_url, :user
def initialize(api_base_url, user, token)
@api_base_url = api_base_url
@user = user
@token = token
end
def track(id)
res = _get("tracks/#{id}")
if res.code == "200" then
Track.new(JSON.parse(res.body)["track"])
else
raise "Error downloading track. Response code: #{res.code}"
end
end
def tracks(page=1, limit=50)
res = _get("tracks?page=#{page}&per_page=#{limit}")
if res.code == "200" then
body = JSON.parse(res.body)
body["tracks"].map!{ |t| Track.new(t) }
body
else
raise "Error downloading tracks. Response code: #{res.code}"
end
end
def release(id)
res = _get("releases/#{id}")
if res.code == "200" then
model = JSON.parse(res.body)["release"]
model["tracks"].map!{|t| track t["id"] }
Release.new(model)
else
raise "Error downloading track. Response code: #{res.code}"
end
end
def releases(page=1, limit=50)
res = _get("releases?page=#{page}&per_page=#{limit}")
if res.code == "200" then
body = JSON.parse res.body
body["releases"].map!{|model|
model["tracks"].map!{|t| track t["id"] }
Release.new(model)
}
body
else
raise "Error downloading tracks. Response code: #{res.code}"
end
end
private
def _get(target)
uri = URI.parse(@api_base_url + '/accounts/' + @user + '/' + target)
req = Net::HTTP::Get.new(uri)
req['Authorization'] = 'Token token="' + @token + '"'
Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http|
http.request(req)
}
end
end
| true |
ab771dcbec98e8bb5fc447bd801753e7c5838e3e | Ruby | hannahsquier/blackjack | /lib/deck.rb | UTF-8 | 463 | 3.421875 | 3 | [] | no_license | class Deck
attr_reader :deck_arr
def initialize(deck_arr = nil)
@deck_arr = make_deck(deck_arr)
end
def deal
@deck_arr.pop
end
private
def make_deck(deck_arr)
if deck_arr.nil?
deck_arr = (1..13).to_a * 4
suits = %w(s) * 13 + %w(h) * 13 + %w(c) * 13 + %w(d) * 13
deck_arr.map!.with_index do |card, index|
card.to_s << suits[index]
end
deck_arr = deck_arr.shuffle
end
deck_arr
end
end | true |
12d09816defbf32d0104a51c116103064aecfd08 | Ruby | Attamusc/rumbrl | /lib/rumbrl/formatter.rb | UTF-8 | 686 | 2.90625 | 3 | [] | no_license | require 'logger'
require 'rumbrl/smash'
module Rumbrl
# Log4r formatter
class Formatter < ::Logger::Formatter
def call(_severity, _timestamp, _prog, msg)
return '' if omit_empty? && empty?(msg)
"#{format_msg(msg)}\n"
end
def omit_empty(switch)
if [TrueClass, FalseClass].include? switch.class
@omit_empty = switch
else
@omit_empty = false
end
end
def omit_empty?
@omit_empty.nil? || @omit_empty
end
# overwrite this to format objects that are passed in
def format_msg(msg)
"#{msg}"
end
private
def empty?(obj)
obj.respond_to?(:empty?) && obj.empty?
end
end
end
| true |
b64019269d933b301993e3bde28c93900d943879 | Ruby | MooreJesseB/gluten_free | /person_class.rb | UTF-8 | 838 | 4 | 4 | [] | no_license | class Person
attr_reader :name, :stomach, :allergies
def initialize(name)
@name = name
@stomach = []
@allergies = []
end
def add_allergy(allergy)
@allergies.push(allergy)
puts "You now have an allergy to #{allergy}"
puts "You are now have food allergies to the following: #{@allergies.join(", ")}"
end
def eat_foods(foods)
foods.each do |food|
unless @allergies.include? food
@stomach.push(food)
puts "You have just ingested a moderate quantity of #{food}"
puts "It is now in your stomach."
puts "The contents of your stomach currently are: #{@stomach.join(", ")}"
else
puts "Allergy Error"
puts "You have had a severe allergic reaction. Your stomach is now empty and it's contents are spread out in front of you:"
puts @stomach.join(", ")
@stomach = []
end
end
end
end | true |
c056d80f8c4d426e7810180e78abd85a97cd0ab9 | Ruby | bpainter/frankenstein | /commands/example.rb | UTF-8 | 652 | 2.875 | 3 | [] | no_license | # Used to extend commands in Nanoc and depreciates the need for a separate Rakefile.
# Based on Cri, http://rubydoc.info/gems/cri/2.0.0/file/README.md
usage 'dostuff [options]'
aliases :ds, :stuff
summary 'does stuff'
description 'This command does a lot of stuff. I really mean a lot.'
flag :h, :help, 'show help for this command' do |value, cmd|
puts cmd.help
exit 0
end
flag :m, :more, 'do even more stuff'
option :s, :stuff, 'specify stuff to do', :argument => :optional
run do |opts, args, cmd|
stuff = opts[:stuff] || 'generic stuff'
puts "Doing #{stuff}!"
if opts[:more]
puts 'Doing it even more!'
end
end | true |
9a740add0069578284cc22583c2c58b4637dc332 | Ruby | martinbjeldbak/p3-project | /program/foodl/app/helpers/search_helper.rb | UTF-8 | 1,117 | 2.84375 | 3 | [
"MIT"
] | permissive | module SearchHelper
#Formats a value nicely, with fractions
def format_quantity( value )
#Remove everything below .##
value = (value * 100).round() / 100.0;
#Check for common fractions
fracs = Hash[ 0.25=>"1/4", 0.33=>"1/3", 0.5=>"1/2", 0.66=>"2/3", 0.75=>"3/4" ]
if fracs.has_key?( value )
return fracs[ value ]
else
#find amount of decimals to display
decimal0 = value.round();
decimal1 = (value * 10 ).round();
if( decimal0 == value )
return decimal0.to_s.gsub( ".", "," );
elsif( decimal1 == value )
return decimal1.to_s.gsub( ".", "," );
else
return value.to_s.gsub( ".", "," );
#TODO: hide decimal if large numbers?
end
end
end
def has_favour?( id )
if logged_in?
return id_match?( current_user.favorites, id )
else
return session[:favored].nil? ? false : session[:favored].include?( id.to_s )
end
end
def plural( number, singular, plural )
return number == 1 ? singular : plural
end
def id_match?( array, id )
if array
array.each do |a|
if a.id == id
return true
end
end
end
return false
end
end
| true |
10ba9e27ff033641941e77d983d3e96334241edc | Ruby | nard-tech/atcoder-crystal | /contests/abc143/d.rb | UTF-8 | 666 | 3.296875 | 3 | [] | no_license | # ABC 143 D - Triangles
# https://atcoder.jp/contests/abc143/tasks/abc143_d
# 1607 ms, 1912 KB
# https://atcoder.jp/contests/abc143/submissions/12697559
n = gets.chomp.to_i
l = gets.chomp.split(/ /).map(&:to_i).sort
# puts sticks.inspect
# puts ""
count = 0
0.upto(n - 3) do |i|
a = l[i]
(i + 1).upto(n - 2) do |j|
b = l[j]
c_candidates = l[(j + 1)..(n - 1)]
t = a + b
# puts "--------"
# puts c_candidates.inspect
# puts "a: #{a}, b: #{b}, a + b: #{t}"
c_over_index = c_candidates.bsearch_index { |c| c >= t }
if c_over_index.nil?
count += (n - 1) - j
else
count += c_over_index
end
end
end
puts count
| true |
5720fe323fb3e01f5abdb4ee136d99ca1a730703 | Ruby | AakashOfficial/licensee | /lib/licensee/content_helper.rb | UTF-8 | 4,834 | 2.703125 | 3 | [
"MIT",
"BSD-3-Clause",
"BSD-3-Clause-Clear",
"LGPL-3.0-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"BSD-2-Clause",
"LGPL-2.0-or-later",
"LGPL-2.1-only",
"GPL-3.0-only"
] | permissive | require 'set'
require 'digest'
module Licensee
module ContentHelper
DIGEST = Digest::SHA1
END_OF_TERMS_REGEX = /^[\s#*_]*end of terms and conditions\s*$/i
HR_REGEX = /[=\-\*][=\-\*\s]{3,}/
ALT_TITLE_REGEX = License::ALT_TITLE_REGEX
ALL_RIGHTS_RESERVED_REGEX = /\Aall rights reserved\.?$/i
WHITESPACE_REGEX = /\s+/
MARKDOWN_HEADING_REGEX = /\A\s*#+/
VERSION_REGEX = /\Aversion.*$/i
MARKUP_REGEX = /[#_*=~\[\]()`|>]+/
# A set of each word in the license, without duplicates
def wordset
@wordset ||= if content_normalized
content_normalized.scan(/[\w']+/).to_set
end
end
# Number of characteres in the normalized content
def length
return 0 unless content_normalized
content_normalized.length
end
# Number of characters that could be added/removed to still be
# considered a potential match
def max_delta
@max_delta ||= (length * Licensee.inverse_confidence_threshold).to_i
end
# Given another license or project file, calculates the difference in length
def length_delta(other)
(length - other.length).abs
end
# Given another license or project file, calculates the similarity
# as a percentage of words in common
def similarity(other)
overlap = (wordset & other.wordset).size
total = wordset.size + other.wordset.size
100.0 * (overlap * 2.0 / total)
end
# SHA1 of the normalized content
def content_hash
@content_hash ||= DIGEST.hexdigest content_normalized
end
# Content with the title and version removed
# The first time should normally be the attribution line
# Used to dry up `content_normalized` but we need the case sensitive
# content with attribution first to detect attribuion in LicenseFile
def content_without_title_and_version
@content_without_title_and_version ||= begin
string = content.strip
string = strip_markdown_headings(string)
string = strip_hrs(string)
string = strip_title(string) while string =~ ContentHelper.title_regex
strip_version(string).strip
end
end
# Content without title, version, copyright, whitespace, or insturctions
#
# wrap - Optional width to wrap the content
#
# Returns a string
def content_normalized(wrap: nil)
return unless content
@content_normalized ||= begin
string = content_without_title_and_version.downcase
while string =~ Matchers::Copyright::REGEX
string = strip_copyright(string)
end
string = strip_all_rights_reserved(string)
string, _partition, _instructions = string.partition(END_OF_TERMS_REGEX)
string = strip_markup(string)
strip_whitespace(string)
end
if wrap.nil?
@content_normalized
else
Licensee::ContentHelper.wrap(@content_normalized, wrap)
end
end
# Wrap text to the given line length
def self.wrap(text, line_width = 80)
return if text.nil?
text = text.clone
text.gsub!(/([^\n])\n([^\n])/, '\1 \2')
text = text.split("\n").collect do |line|
if line.length > line_width
line.gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1\n").strip
else
line
end
end * "\n"
text.strip
end
def self.format_percent(float)
"#{format('%.2f', float)}%"
end
def self.title_regex
licenses = Licensee::License.all(hidden: true, psuedo: false)
titles = licenses.map(&:title_regex)
# Title regex must include the version to support matching within
# families, but for sake of normalization, we can be less strict
without_versions = licenses.map do |license|
next if license.title == license.name_without_version
Regexp.new Regexp.escape(license.name_without_version), 'i'
end
titles.concat(without_versions.compact)
/\A\s*\(?(the )?#{Regexp.union titles}.*$/i
end
private
def strip_title(string)
strip(string, ContentHelper.title_regex)
end
def strip_version(string)
strip(string, VERSION_REGEX)
end
def strip_copyright(string)
strip(string, Matchers::Copyright::REGEX)
end
# Strip HRs from MPL
def strip_hrs(string)
strip(string, HR_REGEX)
end
# Strip leading #s from the document
def strip_markdown_headings(string)
strip(string, MARKDOWN_HEADING_REGEX)
end
def strip_whitespace(string)
strip(string, WHITESPACE_REGEX)
end
def strip_all_rights_reserved(string)
strip(string, ALL_RIGHTS_RESERVED_REGEX)
end
def strip_markup(string)
strip(string, MARKUP_REGEX)
end
def strip(string, regex)
string.gsub(regex, ' ').squeeze(' ').strip
end
end
end
| true |
896717fd1c4f8045ac6d712e6eb41a2aca8a4bc5 | Ruby | kleinmann/personal-homepage | /lib/blog/blog_post.rb | UTF-8 | 741 | 3.21875 | 3 | [] | no_license | class BlogPost
attr_reader :title, :text, :created_at, :index, :teaser
def initialize(text, created_at, index)
@title = text.lines.to_a[0]
@created_at = Date.strptime(created_at, "%Y%m%d")
@index = index
@teaser = create_teaser(text.lines.to_a[1..-1].join)
@text = create_text(text.lines.to_a[1..-1].join)
end
private
def create_text(text)
if @teaser != text
text_1 = text[0...(text =~ /^\^+$/)]
text_2 = text[((text =~ /^\^+$/) + 1)..(text.length - 1)]
text_2 = text_2.lines.to_a[1..-1].join
return text_1 + text_2
end
return text
end
def create_teaser(text, end_string = "\n[...]")
if text =~ /^\^+$/
teaser = text[0...(text =~ /^\^+$/)] + end_string
else
teaser = text
end
end
end
| true |
0149ec6ba965cdd21bf68beb05f13ebcf1d4ecda | Ruby | JustinData/GA-WDI-Work | /w01/d03/Justin/MTA.rb | UTF-8 | 3,267 | 3.875 | 4 | [] | no_license |
#Arrays and Hashes predefine
n = ['ts', '34th', '28th-n', '23rd-n', 'us', '8th']
l = ['8th', '6th', 'us', '3rd', '1st']
s = ['gc', '33rd', '28th-s', '23rd-s', 'us', 'astor']
mta = {}
mta[:n] = n
mta[:l] = l
mta[:s] = s
#=====================
#Start of methods
#takes in starting and ending points
def which_station(stops)
puts "The stops on this line are:"
puts stops
puts " "
puts "Please choose a station."
station = gets.chomp.downcase
end
#Determines the number of stops between two stations by array index
def stops_to_location(start_index, stop_index)
if start_index < stop_index
stops = stop_index - start_index
elsif start_index > stop_index
stops = start_index - stop_index
else
stops = 0
end
end
#End of methods
#=========================
puts "Welcome to the subway!"
puts "What line is your starting location on? (N/L/S):"
starting_line = gets.chomp.downcase
#Determines which rail line the user is starting at
case starting_line
when "n"
starting_station = which_station(n)
when "l"
starting_station = which_station(l)
when "s"
starting_station = which_station(s)
end
puts "On which line is your destination? (N/L):"
destination_line = gets.chomp.downcase
#Determines which rail line the user is going to
case destination_line
when "n"
destination_station = which_station(n)
when "l"
destination_station = which_station(l)
when "s"
destination_station = which_station(s)
end
#Finds the array index of the starting station in the array for that rail line
case starting_line
when "n"
index_of_start = n.index(starting_station)
when "l"
index_of_start = l.index(starting_station)
when "s"
index_of_start = s.index(starting_station)
end
#Finds the array index of the starting station in the array for that rail line
case destination_line
when "n"
index_of_destination = n.index(destination_station)
when "l"
index_of_destination = l.index(destination_station)
when "s"
index_of_destination = s.index(destination_station)
end
n_index_of_us = n.index("us")
l_index_of_us = l.index("us")
s_index_of_us = s.index("us")
#Determines if the starting location and destinations are on the same rail line
if starting_line == destination_line
same_line = true
else
same_line = false
end
if same_line == true
num_stops = stops_to_location(index_of_start, index_of_destination)
end
if same_line == false
case starting_line
when "n"
start_to_us = stops_to_location(index_of_start, n_index_of_us)
when "l"
start_to_us = stops_to_location(index_of_start, l_index_of_us)
when "s"
start_to_us = stops_to_location(index_of_start, s_index_of_us)
end
case destination_line
when "n"
destination_to_us= stops_to_location(index_of_destination, n_index_of_us)
when "l"
destination_to_us = stops_to_location(index_of_destination, l_index_of_us)
when "s"
destination_to_us = stops_to_location(index_of_destination, s_index_of_us)
end
num_stops = start_to_us.to_i + destination_to_us.to_i
end
# num_stops = stops_to_location(index_of_start, index_of_destination)
if num_stops != 0
puts "Starting at #{starting_station} station and getting off at #{destination_station} station"
puts "Your trip will be #{num_stops} stops."
else
puts "You are already there fool."
end
| true |
2516d1fa94e5054791c7633f9ac741e1597b463e | Ruby | SpencerB3/launch_school | /precourse_ruby/intro_to_programming_with_ruby/09_exercises/exercise_9.rb | UTF-8 | 96 | 3.234375 | 3 | [] | no_license | h = {a:1, b:2, c:3, d:4}
puts h[:b]
h[:e] = 5
puts h
h.select! do |k, v|
v > 3.5
end
p h | true |
55dc24c99656d959ab03fa669c54a7bf047b5da2 | Ruby | matlex/thinknetica_ror | /Lesson 7/train.rb | UTF-8 | 2,907 | 3.375 | 3 | [] | no_license | require_relative 'instance_counter'
require_relative 'custom_errors'
class Train
include InstanceCounter
include CustomErrors
attr_reader :type, :number, :wagons, :current_speed
POSSIBLE_TRAIN_TYPES = ['Passenger', 'Cargo']
NUMBER_FORMAT_PATTERN = /^[a-z0-9]{3}-?[a-z0-9]{2}$/i
TRAIN_NUMBER_LENGTH = 5
@@trains = {}
def initialize(number, type)
@number = number
@type = type
@wagons = []
@current_speed = 0
@@trains[number] = self
validate!
register_instance
end
def self.find(number)
@@trains.fetch(number, nil)
end
def valid?
begin
validate!
rescue
false
end
end
def speed_up(speed)
@current_speed += speed
end
def speed_down(speed)
@current_speed -= speed if (@current_speed - speed) >= 0
end
def stop
@current_speed = 0
end
def add_wagon(wagon)
if @current_speed == 0 && correct_type?(wagon)
@wagons << wagon
end
end
def remove_wagon
if @current_speed == 0 && !@wagons.empty?
@wagons.pop
end
end
def wagons_count
@wagons.size
end
def current_station
@route.stations[@current_station_index]
end
def add_route(route)
@route = route
@current_station_index = 0
# Добавим в первую станцию маршрута наш поезд
current_station.add(self)
end
def move_to_next_station
if next_station
current_station.remove(self)
@current_station_index += 1
current_station.add(self)
end
end
def move_to_previous_station
if previous_station
current_station.remove(self)
@current_station_index -= 1
current_station.add(self)
end
end
def iterate_wagons
@wagons.each.with_index(1) { |wagon, index| yield(wagon, index) } if @wagons.any?
end
protected
# Выносим методы т.к. они не будут вызываться клиентом, а используются только внутри текущего класса и его наследников
def next_station
@route.stations[@current_station_index + 1] if @route
end
def previous_station
if @route && current_station != @route.stations.first
@route.stations[@current_station_index - 1]
end
end
def correct_type?(wagon)
wagon.is_a?(correct_wagon_type)
end
def correct_wagon_type
raise NotImplementedError
end
def correct_train_type
raise NotImplementedError
end
def validate!
raise ValidationError, "Number can't be nil" if number.nil?
raise ValidationError, "Train number should be #{ TRAIN_NUMBER_LENGTH } symbols" if number.length < TRAIN_NUMBER_LENGTH
raise ValidationError, "Train number has invalid format" if number !~ NUMBER_FORMAT_PATTERN
raise ValidationError, "Wrong train type: \"#{@type}\"" unless POSSIBLE_TRAIN_TYPES.include?(correct_train_type)
true
end
end
| true |
cde3701fb7821aff15d1c33ad844b6b31dc3aa87 | Ruby | Byambaa0325/ruby-object-initialize-lab-cb-gh-000 | /lib/dog.rb | UTF-8 | 105 | 2.65625 | 3 | [] | no_license | class Dog
def initialize(_name, _breed="Mutt")
@name= _name
@breed= _breed
end
end | true |
cb30c98837b8186086aad4256ac3f7afdfd21c8d | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/accumulate/7a69069c237d4031873d7a35b5afb164.rb | UTF-8 | 132 | 3.46875 | 3 | [] | no_license | class Array
def accumulate
result = []
i = 0
while self[i]
result << (yield self[i])
i += 1
end
result
end
end
| true |
d64414b6dad50ad5be36d85923d511122ba6d832 | Ruby | ellebaum/weekendpuzzles | /2020-07-05.rb | UTF-8 | 3,120 | 3.421875 | 3 | [] | no_license | #Think of an eight-letter word for something we all crave now. It consists of three consecutive men's nicknames. What are they?
#Answer: normalcy
dictionary_file = File.read "/usr/share/dict/words"
dictionary_hash = {}
dictionary_file.lines.each do |line|
if line.gsub(/[^a-zA-Z]/, '').chomp.downcase.length == 8
dictionary_hash.store(line.gsub(/[^a-zA-Z]/, '').chomp.downcase, line.gsub(/[^a-zA-Z]/, '').chomp.downcase.sum)
end
end
dictionary_hash.uniq.sort!
name_file = File.read "./commonMaleNames.txt"
name_hash = {}
name_file.lines.each do |line|
#assuming all of the names are > 1 letter long, 4 is the max length
if line.gsub(/[^a-zA-Z]/, '').chomp.downcase.length <= 4 && line.gsub(/[^a-zA-Z]/, '').chomp.downcase.length >= 2
name_hash.store(line.gsub(/[^a-zA-Z]/, '').chomp.downcase, line.gsub(/[^a-zA-Z]/, '').chomp.downcase.sum)
end
end
name_hash.uniq.sort!
#puts dictionary_hash.length
# -> 13457
#words that don't start with one of the names can be removed from the dictionary hash
dictionary_hash.each do |word_key, word_value|
starts_with = false
name_hash.each do |name_key, name_value|
if word_key.start_with?(name_key)
starts_with = true
end
end
if !starts_with
dictionary_hash.delete(word_key)
end
end
#puts dictionary_hash.length
# -> 1848
=begin
The only possible name length combiations are:
4 2 2
2 2 4
2 4 2
3 3 2
3 2 3
2 3 3,
=end
#this could probably be optimized by comparing hash values instead but it runs fast enough as-is
name_hash.each do |name_key, name_value|
temp_name_hash = name_hash.dup
if name_key.length == 4
temp_name_hash.each do |name2_key, name2_value|
if name2_key.length != 2
temp_name_hash.delete(name2_key)
end
end
temp_name_hash.each do |name2_key, name2_value|
dictionary_hash.each do |word_key, word_value|
if word_key.start_with?(name_key + name2_key)
temp_name_hash.each do |name3_key, name3_value|
if word_key == (name_key + name2_key + name3_key)
puts word_key
end
end
end
end
end
elsif name_key.length == 3
temp_name_hash.each do |name2_key, name2_value|
if name_key.length == 4
temp_name_hash.delete(name2_key)
end
end
temp_name_hash.each do |name2_key, name2_value|
dictionary_hash.each do |word_key, word_value|
if word_key.start_with?(name_key + name2_key)
temp_name_hash.each do |name3_key, name3_value|
if word_key == (name_key + name2_key + name3_key)
puts word_key
end
end
end
end
end
else
temp_name_hash.each do |name2_key, name2_value|
dictionary_hash.each do |word_key, word_value|
if word_key.start_with?(name_key + name2_key)
temp_name_hash.each do |name3_key, name3_value|
if word_key == (name_key + name2_key + name3_key)
puts word_key
end
end
end
end
end
end
end
=begin
-> altamira
bartered
chemical
curtsied
cylinder
dickered
gibbered
hankered
jonathan
londoner
lonelier
mattered
normalcy
paterson
roberson
salaried
seesawed
tempered
timelier
tuckered
urinated
valerian
waterway
'salaried' sort of works, but the best answer is 'normalcy'
=end | true |
55064486ca55ae4de9d0d1b530ef62461ea4617c | Ruby | internetee/auction_center | /lib/messente/sending_error.rb | UTF-8 | 559 | 2.765625 | 3 | [
"MIT"
] | permissive | module Messente
class SendingError < StandardError
attr_reader :response_code
attr_reader :response_body
attr_reader :message
attr_reader :request_body
def initialize(response_code, response_body, request_body)
@response_code = response_code
@response_body = response_body
@request_body = request_body
@message = <<~TEXT.squish
Sending a message failed.
Request: #{request_body}.
Response code: #{response_code}. Body: #{response_body}"
TEXT
super(message)
end
end
end
| true |
7a236487923746dafc5cf51da4f4e3c50828eaf0 | Ruby | ryanflach/headcount | /lib/enrollment.rb | UTF-8 | 1,694 | 3.109375 | 3 | [] | no_license | require_relative 'calculations'
class Enrollment
include Calculations
attr_accessor :enrollment_data
def initialize(enrollment_data)
@enrollment_data = enrollment_data
end
def name
@enrollment_data[:name].upcase
end
def kindergarten_participation
enrollment_data[:kindergarten_participation]
end
def high_school_graduation
return enrollment_data[:high_school_graduation] if hs_grad_data_existing?
@enrollment_data[:high_school_graduation] = {}
end
def hs_grad_data_existing?
enrollment_data.has_key?(:high_school_graduation)
end
def kinder_participation_floats
floats_for_all_years(kindergarten_participation)
end
def graduation_year_floats
floats_for_all_years(high_school_graduation)
end
def floats_for_all_years(grade_level)
grade_level.map do |key, value|
[key, value.to_f]
end.sort_by {|year, percent| year}.to_h
end
def data_by_year(grade_level)
@enrollment_data[grade_level].map do |year, percent|
[year, truncate_float(percent.to_f)]
end.sort_by {|year, percent| year}.to_h
end
def data_in_year(query_year, grade_level)
data = enrollment_data[grade_level].find do |year, percent|
year == query_year
end
truncate_float(data[1].to_f) unless data.nil?
end
def kindergarten_participation_by_year
data_by_year(:kindergarten_participation)
end
def kindergarten_participation_in_year(query_year)
data_in_year(query_year, :kindergarten_participation)
end
def graduation_rate_by_year
data_by_year(:high_school_graduation)
end
def graduation_rate_in_year(query_year)
data_in_year(query_year, :high_school_graduation)
end
end
| true |
53cee4d9ec28c880609310e676639bab2a8c8371 | Ruby | TAEB/RubyTAEB | /ai/taskhandler.rb | UTF-8 | 2,155 | 3.3125 | 3 | [] | no_license | #!/usr/bin/ruby
$:.push('ai/task/')
require 'door.rb'
require 'eatfood.rb'
require 'elbereth.rb'
require 'ensure.rb'
require 'explore.rb'
require 'fight.rb'
require 'fixhunger.rb'
require 'randomwalk.rb'
require 'search.rb'
class TaskHandler
def initialize()
@tasks =
[
[99999, TaskEnsure.new() ], # takes 0 time
[10000, TaskElbereth.new() ], # <50% HP
[ 2000, TaskFixHunger.new() ], # 1600 Weak, 2000 Fainting
[ 1900, TaskEatFood.new() ], # 1520 Hungry, 1710 Weak, 1900 Fainting
[ 1000, TaskFight.new() ], # adjacent monster
[ 200, TaskDoor.new() ], # adjacent door
[ 100, TaskExplore.new() ],
[ 50, TaskSearch.new() ],
[ 1, TaskRandomWalk.new()],
]
end
# This runs the task with the highest priority. If that task's run returns a
# false value, run the next-highest-priority task, and so on.
# Warning: some tasks depend on having priority called each tick, so you can't
# stop processing early (a possible optimization) unless priority is separated
# from update
def next_task()
@tasks.map {|task| [task[0] * task[1].priority(), task[1]] }.
sort {|a, b| b[0] <=> a[0]}.
each do |task_array|
debug("Running #{task_array[1].class.to_s} which has priority #{task_array[0]}")
result = task_array[1].run()
clear_screen()
break if result
end
end
def clear_screen()
if $controller.vt.row(0) =~ /^Do you want your possessions identified\?/ or
$controller.vt.row(0) =~ /^Do you want to see what you had when you died\?/
debug("Oh no! We died!")
$controller.send("y")
while 1 # let the Disconnect exception break the loop
$controller.send(" ")
sleep 1
end
end
if $controller.vt.row(0) =~ /^ *Things that are here: *$/ or
$controller.vt.row(2) =~ /^ *Things that are here: *$/
debug("Things that are here menu")
$controller.send(" ")
clear_screen()
end
if $controller.vt.to_s =~ /--More--/
debug("I see a --More--!")
$controller.send(" ")
clear_screen()
end
end
end
| true |
650e24a569f5122facc5a3778cbc7ceaa22f4bc2 | Ruby | Terry-Thompson/collections_practice-v-000 | /collections_practice.rb | UTF-8 | 719 | 3.5625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def sort_array_asc(array)
array.sort { |a, b| a <=> b }
end
def sort_array_desc(array)
array.sort { |a, b| b <=> a }
end
def sort_array_char_count(array)
array.sort { |a, b| a.length <=> b.length }
end
def swap_elements(array)
c = []
c << array[0]
c << array[2]
c << array[1]
c
end
def swap_elements_from_to(array, from, to)
end
def reverse_array(array)
array.reverse
end
def kesha_maker(array)
c = []
array.each do |name|
name[2] = "$"
c << name
end
c
end
def find_a(array)
array.select {|string| string.start_with?("a")}
end
def sum_array(array)
array.inject(&:+)
end
def add_s(array)
array.each_with_index.collect {|item, index| index != 1? item << "s": item << ""}
end | true |
f5ccb4aa84d646b4a16088cd056a1a1d089f84e5 | Ruby | joshwlewis/unitwise | /test/unitwise/unit_test.rb | UTF-8 | 2,316 | 3 | 3 | [
"MIT"
] | permissive | # encoding: UTF-8
require 'test_helper'
describe Unitwise::Unit do
let(:ms2) { Unitwise::Unit.new("m/s2") }
let(:kg) { Unitwise::Unit.new("kg") }
let(:psi) { Unitwise::Unit.new("[psi]")}
let(:deg) { Unitwise::Unit.new("deg")}
describe "#terms" do
it "must be a collection of terms" do
_(ms2).must_respond_to :terms
_(ms2.terms).must_be_kind_of Enumerable
_(ms2.terms.first).must_be_instance_of Unitwise::Term
end
end
describe "#root_terms" do
it "must be an array of Terms" do
_(ms2).must_respond_to :terms
_(ms2.root_terms).must_be_kind_of Array
_(ms2.root_terms.first).must_be_instance_of Unitwise::Term
end
end
describe "#scalar" do
it "must return value relative to terminal atoms" do
_(ms2).must_respond_to :scalar
_(ms2.scalar).must_equal 1
_(psi.scalar).must_almost_equal 6894757.293168361
_(deg.scalar).must_almost_equal 0.0174532925199433
end
end
describe "#composition" do
it "must be a multiset" do
_(ms2).must_respond_to :terms
_(ms2.composition).must_be_instance_of SignedMultiset
end
end
describe "#dim" do
it "must be a string representing it's dimensional makeup" do
_(ms2.dim).must_equal 'L.T-2'
_(psi.dim).must_equal 'L-1.M.T-2'
end
end
describe "#*" do
it "should multiply units" do
mult = kg * ms2
_(mult.expression.to_s).must_match(/kg.*\/s2/)
_(mult.expression.to_s).must_match(/m.*\/s2/)
end
end
describe "#/" do
it "should divide units" do
div = kg / ms2
_(div.expression.to_s).must_match(/kg.*\/m/)
_(div.expression.to_s).must_match(/s2.*\/m/)
end
end
describe "#frozen?" do
it "should be frozen" do
kg.scalar
_(kg.frozen?).must_equal true
end
end
describe "#to_s" do
it "should return an expression in the same mode it was initialized with" do
['meter','m', 'mm', '%'].each do |name|
_(Unitwise::Unit.new(name).to_s).must_equal(name)
end
end
it "should accept an optional mode to build the expression with" do
temp_change = Unitwise::Unit.new("degree Celsius/hour")
_(temp_change.to_s(:primary_code)).must_equal("Cel/h")
_(temp_change.to_s(:symbol)).must_equal("°C/h")
end
end
end
| true |
626a2532c297d24d714c0c0acbaef07919c2e27d | Ruby | JoseGomez247/codeacamp | /newbie/semana1/Martes/firstl.rb | UTF-8 | 261 | 3.5625 | 4 | [] | no_license | def first_letters(word)
r= []
word.split.each { |w| r << w.chars.first}
r
end
p first_letters("Hoy es miércoles y hace sol") == ["H", "e", "m", "y", "h", "s"]
p first_letters("tienes ocho candados indios nuevos omega") == ["t", "o", "c", "i", "n", "o"]
| true |
3516e699c7e3a3b4b46a25851ec89fc074b3b319 | Ruby | tpinto/panda | /app/models/clipping.rb | UTF-8 | 3,220 | 2.53125 | 3 | [
"MIT"
] | permissive | # Clipping for a given encoding or parent video.
#
class Clipping
include LocalStore
def initialize(video, position = nil)
@video = video
@_position = position
end
def filename(size, opts = {})
raise "Invalid size: choose :thumbnail or :screenshot" unless [:thumbnail, :screenshot].include?(size)
name = [@video.filename]
name << position unless opts[:default]
name << 'thumb' if size == :thumbnail
return name.join('_') + '.jpg'
end
# URL of clipping on store. If clipping was initialized without a position
# then the default filename is used (without position) to generate the url
def url(size)
if @_position
Store.url(self.filename(size.to_sym))
else
Store.url(self.filename(size.to_sym, :default => true))
end
end
# URL on the panda instance (before it has been uploaded)
def tmp_url(size)
public_url(@video.filename, size, position, '.jpg')
end
def capture
raise RuntimeError, "Video must exist to call capture" unless File.exists?(@video.tmp_filepath)
t = RVideo::Inspector.new(:file => @video.tmp_filepath)
t.capture_frame("#{position}%", tmp_path(:screenshot))
end
def resize
constrain_to_height = Panda::Config[:thumbnail_height_constrain].to_f
height = constrain_to_height
width = (@video.width.to_f/@video.height.to_f) * height
GDResize.new.resize \
tmp_path(:screenshot),
tmp_path(:thumbnail),
[width.to_i, height.to_i]
end
# Uploads this clipping to the default clipping locations on store (default
# url does not contain position)
#
# TODO: Refactor. It's complicated because you're not sure whether the
# clipping is available locally before you start.
def set_as_default
actual_operation = lambda {
Store.set \
filename(:screenshot, :default => true),
tmp_path(:screenshot)
Store.set \
filename(:thumbnail, :default => true),
tmp_path(:thumbnail)
}
if File.exists?(tmp_path(:screenshot))
actual_operation.call
else
self.fetch_from_store
actual_operation.call
self.delete_locally
end
end
# Upload this clipping to store (with position info in the url)
def upload_to_store
Store.set \
filename(:screenshot),
tmp_path(:screenshot)
Store.set \
filename(:thumbnail),
tmp_path(:thumbnail)
end
def fetch_from_store
Store.get(filename(:screenshot), tmp_path(:screenshot))
Store.get(filename(:thumbnail), tmp_path(:thumbnail))
end
def delete_locally
FileUtils.rm(tmp_path(:screenshot))
FileUtils.rm(tmp_path(:thumbnail))
end
def delete_from_store
Store.delete(filename(:screenshot))
Store.delete(filename(:thumbnail))
rescue AbstractStore::FileDoesNotExistError
false
end
def changeable?
Panda::Config[:choose_thumbnail] != false
end
private
def original_video
@video.parent? ? @video : @video.parent_video
end
def tmp_path(size)
public_filepath(@video.filename, size, position, '.jpg')
end
def position
@_position || original_video.thumbnail_position || 50
end
end
| true |
97361148544dc0bc4b4a7972c7fc66f080c43df5 | Ruby | AdamClemons/cartoon-collections-online-web-sp-000 | /cartoon_collections.rb | UTF-8 | 683 | 3.28125 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | def roll_call_dwarves(dwarves)# code an argument here
# Your code here
dwarves.each_with_index {|dude, index| puts "#{index+1}. #{dude}"}
end
def summon_captain_planet(calls)# code an argument here
# Your code here
summon = calls.collect {|dude| dude.capitalize!.insert(-1, "!")}
end
def long_planeteer_calls(calls)# code an argument here
# Your code here
long = calls.collect {|dude| dude.length > 4}
long.include?(true)? true : false
end
def find_the_cheese(snacks)# code an argument here
# the array below is here to help
cheese_types = ["cheddar", "gouda", "camembert"]
snacks.each do |food|
return food if cheese_types.include?(food)
end
nil
end
| true |
a03261f738b61a5e100f9109514a1b886c1d5bee | Ruby | wallaby-rails/wallaby-core | /lib/wallaby/class_array.rb | UTF-8 | 1,852 | 3.375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module Wallaby
# This is a constant-safe array that stores Class value as String.
class ClassArray
include Classifier
# @param [Array] array
def initialize(array = [])
@internal = array || []
return if @internal.blank?
@internal.map!(&method(:to_class_name)).compact!
end
# @!attribute [r] internal
# @return [Array] The array to store Class values as String.
attr_reader :internal
# @!attribute [r] origin
# @return [Array] The original array.
def origin
# NOTE: DO NOT cache it by using instance variable!
@internal.map(&method(:to_class)).compact
end
# Save the value to the {#internal} array at the given index, and convert the Class value to String
def []=(index, value)
@internal[index] = to_class_name value
end
# Return the value for the given index
def [](index)
to_class @internal[index]
end
# @param other [Array]
# @return [Wallaby::ClassArray] new Class array
def concat(other)
self.class.new origin.concat(other.try(:origin) || other)
end
# @param other [Array]
# @return [Wallaby::ClassArray] new Class array
def -(other)
self.class.new origin - (other.try(:origin) || other)
end
# @return [Wallaby::ClassArray] self
def each(&block)
origin.each(&block)
self
end
# @!method ==(other)
# Compare #{origin} with other.
delegate :==, to: :origin
# @!method blank?
delegate :blank?, to: :internal
# @!method each_with_object(object)
delegate :each_with_object, to: :origin
# @!method to_sentence
delegate :to_sentence, to: :origin
# Ensure to freeze the {#internal}
# @return [Wallaby::ClassArray] self
def freeze
@internal.freeze
super
end
end
end
| true |
2dd59af9ad04629d0a0361e3aab55b1c3933b107 | Ruby | guang-zh/Ruby | /Code/2021_07/06_hashes_and_symbols.rb | UTF-8 | 3,751 | 4.46875 | 4 | [] | no_license | # Hashes and Symbols - Module 6
# 1. HASHES RECAP
# C.R.U.D:
# C. Create
# R. Read
# U. Update
# D. Delete
# C. Create a hash:
new_hash = {}
# or
new_hash = Hash.new
#or
meals = {
"breakfast" => "bacon and eggs",
"lunch" => "pasta",
"snack" => "dill pickle chips",
"dinner" => "Steak and salad"
}
# R. Read a hash
puts meals["breakfast"]
# U. Update an element from a hash
meals["breakfast"] = "Muesli"
# D. Delete an element from a hash
meals.delete("snack")
################################
# 2. CONVERT SYMBOL TO STRING
my_symbol = :breakfast
my_string = my_symbol.to_s
p my_string
# => "breakfast"
my_string = "Hello"
my_symbol = my_string.to_sym
p my_symbol
# => :Hello
################################
# 3. SYMBOLS AS KEYS
# String as keys:
meals = {
"breakfast" => "bacon and eggs",
"lunch" => "chicken soup",
"snack" => "chocolate cookies",
"dinner" => "lasagna"
}
#Symbols as keys (old way):
meals = {
:breakfast => "bacon and eggs",
:lunch => "chicken soup",
:snack => "chocolate cookies",
:dinner => "lasagna"
}
# RUBY NEW SYNTAX:
#Symbols as keys (correct way):
meals = {
breakfast: "bacon and eggs",
lunch: "chicken soup",
snack: "chocolate cookies",
dinner: "lasagna"
}
# R. Read
puts breakfast_food = meals[:breakfast]
# U. Update
meals[:breakfast] = "muesli"
# D. Delete
meals.delete(:snack)
################################
# 4. SETTING DEFAULT VALUES
meals = Hash.new("Eat whatever you want!")
meals[:breakfast] = "Cereal"
meals[:lunch] = "Pasta"
p meals
# => {:breakfast=>"Cereal", :lunch=>"Pasta"}
p meals[:late_night_snack]
# => "Eat whatever you want!"
################################
# 5. SELECTING FROM HASH
grades = {
jessica: 98,
peter: 30,
john: 99,
sarah: 86
}
high_grades = grades.select do |student, grade|
grade > 90
end
puts high_grades
# => {:jessica=>98, :john=>99}
################################
#6. ITERATING OVER ONLY KEYS OR ONLY VALUES
my_hash = {
one: 1,
two: 2,
three: 3
}
my_hash.each_key { |k| puts k }
# => one two three
# Same as:
# my_hash.each_key do | k |
# puts k
# end
my_hash.each_value { |v| puts v }
# => 1 2 3
# Same as:
# my_hash.each_value do |v|
# puts v
# end
grades = {
jessica: 98,
nirali: 98,
peter: 30,
john: 99,
sarah: 86
}
grades.each_key do |student|
puts student
end
# => jessica nirali peter john sarah
grades.each_value do |grade|
puts grade
end
# => 98 98 30 99 86
# If we wanted both keys and values we already know the drill:
grades.each do |student, grade|
puts "#{student} grade is: #{grade}"
end
# Change the value of each grade in a .each iteration
grades = {
jessica: 98,
nirali: 98,
peter: 30,
john: 99,
sarah: 86
}
grades.each do |student, grade|
grades[student] = grade + 1
end
# Add a new key-value pair to the hash
grades = {
jessica: 98,
peter: 30,
john: 99,
sarah: 86
}
puts "What is the name of the student?"
student = gets.chomp.to_sym
puts "What is the grade?"
grade = gets.chomp.to_i
grades[student] = grade
################################
# Codecademy exercise, line by line:
# We have an array of strings we’d like to later use as hash keys, but we’d rather they be symbols.
strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
# Create a new variable, symbols, and store an empty array in it.
symbols = []
# Use .each to iterate over the strings array.
# For each s in strings, use .to_sym to convert s to a symbol and use .push to add that new symbol to symbols.
strings.each do |s| # 's' here will represent each language included in the 'strings' array
symbols.push(s.to_sym) # we push/add the value of 's', converted to a symbol, to the symbols array
end
# Print the symbols array.
print symbols
| true |
7ead4ed6a437bd04e10098f936ff75309cb0312e | Ruby | HubSpot/sample-apps-leaky-bucket | /ruby/cli.rb | UTF-8 | 1,140 | 2.703125 | 3 | [
"Apache-2.0"
] | permissive | require_relative 'config'
class Cli
def run
self.emails = (1..3).map { |i| "leaky_bucket_app#{i}@hubspot.com" }
200.times { start_worker }
end
private
attr_accessor :api, :ids, :emails
def start_worker
puts 'Sleep 1 second to avoid 429 error'
sleep 1
api_client = ::Hubspot::Crm::Contacts::ApiClient.new
self.api = ::Hubspot::Crm::Contacts::BatchApi.new(api_client)
response = create_contacts
self.ids = response.results.map(&:id)
remove_contacts
end
def create_contacts
puts "Create contacts: #{emails}"
api.create(contacts_object, auth_names: 'hapikey')
end
def contacts_object
::Hubspot::Crm::Contacts::BatchInputSimplePublicObjectInput.new(
inputs: contacts
)
end
def contacts
emails.map do |email|
::Hubspot::Crm::Contacts::SimplePublicObjectInput.new(
properties: { email: email }
)
end
end
def remove_contacts
puts ("Remove contacts: #{ids}")
api.archive(ids_object, auth_names: 'hapikey')
end
def ids_object
::Hubspot::Crm::Contacts::BatchInputSimplePublicObjectId.new(
inputs: ids
)
end
end
Cli.new.run
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.