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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
a9f9325fcd6eef0155e365b47da906d8692e1c28 | Ruby | ug-training/learning | /rubylrn/subcl.rb | UTF-8 | 374 | 3.5625 | 4 | [] | no_license | class Contant
@@value=5
def initialize(len,width)
@len = len
@width = width
end
def area
puts @@value=@len*@width*@@value
end
def printv
puts "#{@len}\n#{@width}"
end
end
class Thin < Contant
def initialize(val)
@val = val
super(val,val)
end
def printval
puts @val
end
end
s=Thin.new(3)
r=Thin.new(2)
s.area
s.printv
s.printval
r.area
| true |
4f8eb4c862e88edbdbc8313360e35234a2729533 | Ruby | inohiro/atcoder | /beginner_023/ex2.rb | UTF-8 | 953 | 3.734375 | 4 | [] | no_license |
def main
n = gets.strip!.to_i
s = gets.strip!.to_s
if n < 1 or n > 100
puts '-1'
return
end
unless valid_s?(s, n)
puts '-1'
return
end
accessory = ['b']
return if same_name?(accessory, 0, s)
(1..n).each do |i|
case i % 3
when 1 # 3n + 1
accessory.unshift 'a'
accessory.push 'c'
return if same_name?(accessory, i, s)
when 2 # 3n + 2
accessory.unshift 'c'
accessory.push 'a'
return if same_name?(accessory, i, s)
when 0 # 3n + 0
accessory.unshift 'b'
accessory.push 'b'
return if same_name?(accessory, i, s)
end
end
puts '-1'
end
def same_name?(accessory, i, s)
if accessory.join == s
puts i
true
else
false
end
end
def valid_s?(s, n)
return false if s.length != n
ss = s.split('').uniq
return false if ss.length < 1
ss.each do |hoge|
return false unless %w(a b c).include? hoge
end
true
end
main
| true |
efebc90ec79fb9ec596e95b05ac4bfaaa756fd35 | Ruby | uddin0786/rubyPrograme | /unique.rb | UTF-8 | 186 | 3.1875 | 3 | [] | no_license | class Unique
def uniqk
numbers = [1, 4, 2, 4, 3, 1, 5]
target = []
numbers.each {
|x| target << x unless target.include?(x)
}
puts target
end
end
Unique.new.uniqk | true |
02a19086a15ceb7dc15f6908db9c1a3637ea753b | Ruby | imightbeinatree/comic_reads | /app/helpers/roles_helper.rb | UTF-8 | 3,141 | 2.875 | 3 | [] | no_license | module RolesHelper
# Creates checkboxes for a has and belongs to many relationship between ?
#
# @param obj An instance of a model with the specified field
# @param column The attribute of the obj parameter used to determine if the assignment_object is assigned to the obj parameter
# @param assignment_objects A list of objects with a habtm relationship with the obj parameter
# @param assignment_object_display_column The field on the assignment_objects used to create the label for the checkboxes
# @return [String] An html string of checkboxes for the relationship between the obj and assignment_objects
def habtm_checkboxes(obj, column, assignment_objects, assignment_object_display_column)
obj_to_s = obj.class.to_s.split("::").last.underscore
field_name = "#{obj_to_s}[#{column}][]"
html = hidden_field_tag(field_name, "")
assignment_objects.each do |assignment_obj|
cbx_id = "#{obj_to_s}_#{column}_#{assignment_obj.id}"
html += check_box_tag field_name, assignment_obj.id, obj.send(column).include?(assignment_obj.id), :id => cbx_id
html += label_tag cbx_id, h(assignment_obj.send(assignment_object_display_column))
html += content_tag(:br)
end
html
end
# Creates permission checkboxes for each type of permission and permission category.
# Permission types include manage, read, create, update, and destroy. They are hardcoded in this method.
#
# @param obj An instance of the Role model or any model with a habtm relationship with Permission
# @param column Not used
# @param controllers A list of controllers that can have permissions applied to them
# @param role_id Id that corresponds to an instance of the role model. Should refer to the same object as the obj parameter.
# @return [String] Html safe string of permissions checkboxes for each controller and action
def permissions_checkboxes(obj, column, controllers, role_id)
perms = obj.permissions
html = ""
abilities = ['manage','read','create','update','destroy']
html += content_tag(:table) do
html_table = ""
controllers.each do |controller|
controller.strip!
html_table += content_tag(:tr) do
html_tr = ""
html_tr += content_tag(:th, controller)
html_tr += content_tag(:th, "Use")
html_tr += content_tag(:th, "View")
html_tr += content_tag(:th, "Add")
html_tr += content_tag(:th, "Edit")
html_tr += content_tag(:th, "Delete")
html_tr.html_safe
end
html_table += content_tag(:tr) do
html_tr = ""
html_tr += content_tag(:td," ")
abilities.each do |ability|
p = {
:role_id => role_id,
:model => controller.singularize,
:ability => ability
}
perm = Permission.new(p)
checked = perms.include?(perm)
#checked = false
html_tr += content_tag(:td) do
check_box_tag 'role_ids[]',p.to_json,checked, {:id => "permission_#{controller}_#{ability}", :class => "permission_#{ability}"}
end
end
html_tr.html_safe
end
end
html_table.html_safe
end
html.html_safe
end
end
| true |
9e4e199dab0ff4264a6bc36084fb65838f110084 | Ruby | ingdavidjauregui/ruby | /david.rb | UTF-8 | 1,120 | 2.578125 | 3 | [] | no_license | {\rtf1\ansi\ansicpg1252\cocoartf1504\cocoasubrtf760
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
{\*\expandedcolortbl;;}
\margl1440\margr1440\vieww10800\viewh8400\viewkind0
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0
\f0\fs24 \cf0 #hola no hay tips de datos \
puts ("hola mundo") \
cadena = "esto es una cadena"\
numero = 5\
doble = 5.6\
verdadero = TRUE\
falso = false\
\
#operaciones aritmeticas\
suma = 5 + 5\
resta = 5 - 3\
multi = 5 * 5\
div = 5/3\
modulo = 10%2 \
potencia = 5**4\
\
#concatenar con .to_s\
puts suma.to_s + "suma"\
\
#interpolacion concatenar \
puts "suma #\{suma\}"\
\
puts resta\
puts multi\
puts div\
puts modulo\
puts potencia \
\
#condicionales \
\
if suma == 12\
puts "la suma es 10"\
else \
puts "no es 10"\
end\
\
# Bucles \
i = 0 \
\
while i < 10 do \
puts i \
i +=2 \
end \
\
# otra forma de for ciclo\
(1..10).each do\
puts "a"\
end \
\
#for \
for j in 1..10 do \
puts j\
end\
\
#conversiones \
\
run = "1" \
\
puts run.to_s\
puts run.to_f \
puts run.to_r \
} | true |
b954d9ba023fbbf695fa1a1d01f976eb99de633d | Ruby | Karthick-sketch/Solitare-Game | /solitare/Solitaire.rb | UTF-8 | 9,715 | 2.734375 | 3 | [] | no_license | require 'fox16'
include Fox
require 'colorize'
require 'win32/sound'
include Win32
$cardvalue = ["A",2,3,4,5,6,7,8,9,10,"J","Q","K"]
$app = FXApp.new
$app.create
def mbox(picName,caption,message)
pic=File.open("C:/Users/ajith/OneDrive/Desktop/card/#{picName}.png","rb")
pic2=FXPNGIcon.new($app, pic.read)
my=FXMessageBox.new($app, caption, message , pic2 , MBOX_OK,);
my.execute
end
class Solitaire
def initialize
@setOfCards=Array.new
end
def loadCards val
@setOfCards = val
end
def setCards(val)
@setOfCards.push(val);
end
def popedExtraCards val
@setOfCards.push(val)
end
def deleteCards val
@setOfCards.pop(val)
end
def getCards i
@setOfCards[i]
end
def getAllCards
@setOfCards
end
def deleteAllCards
len=self.getAllCards.length
while(len!=0)
@setOfCards.delete_at((len=len-1))
end
end
def setoneCard val
@setOfCards.push(val)
end
end
$card = Array.new(10) {|i| Solitaire.new}
$arrangedCards
$extracards=Array.new
$indexval = { "A" => 0 , "B" => 1 , "C" => 2 , "D" => 3 , "E" => 4, "F" => 5 , "G" => 6 ,"H" => 7 , "I" => 8 , "J" => 9 }
$invisiblecard = Array.new(10)
load 'hintpatter.rb'
load 'pushandpop.rb'
load 'functions.rb'
load 'help.rb'
#main
win=false
tabspace="\t\t\t\t\t\t\t\t\t\t\t"
nextline=""
20.times { nextline+="\n" }
begin
loop do
$arrangedCards=0
$invisiblecard = [5,5,5,5,4,4,4,4,4,4,4]
startselection=Array.new #starting
startselection[0]="New Game"
option=3
play="" #use to get row and coloumn from user
if(File.readable?("savefile.txt"))
startselection[1] = "Continue"
startselection[2] = "Help"
startselection[3] = "exit"
option=4
else
startselection[1] = "Help"
startselection[2] = "exit"
end
#display the option to user
system("cls")
puts nextline
for i in (0..option)
puts(tabspace + " #{(i!=option)?i+1:"\n"} #{startselection[i]}")
end
print(tabspace , " >>>>> ")
useroption=gets.to_i
if(useroption.to_s.length != 1)
Dir.chdir "audio"
Sound.play('Vampire Bite.wav')
mbox("game_shop-128","Error","Warning! Invalid input...Give correct input")
Dir.chdir ".."
redo
end
color = nextline # user after select the color the selection one in terminel(just for visible)
for i in (0..option)
color+=tabspace
if(useroption-1==i)
color+=" #{(i!=option)?i+1:"\n"} #{startselection[i]}\n".green
else
color+=" #{(i!=option)?i+1:"\n"} #{startselection[i] }\n"
end
end
color+=tabspace + " >>>>> #{useroption}"
if(useroption<1 or useroption>option)
Dir.chdir "audio"
Sound.play('Vampire Bite.wav')
mbox("game_shop-128","Error","Warning! Invalid input...Give correct input")
Dir.chdir ".."
elsif(startselection[useroption-1]=="exit")
system("cls")
puts color
Dir.chdir "audio"
Sound.play('GunCock.wav')
Dir.chdir ".."
sleep(2)
system("cls")
break;
elsif (startselection[useroption-1]=="Help")
help();
else
system("cls")
puts color
Dir.chdir "audio"
Sound.play('GunCock.wav')
Dir.chdir ".."
sleep(1)
system("cls")
if(startselection[useroption-1]=="Continue")
loadSavedFile()
else
loop do
system('cls')
puts "#{ nextline}#{tabspace} 1.Easy\n#{tabspace} 2.Medium\n#{tabspace} 3.Hard"
print("\n",tabspace , " >>>>> ")
level=gets.to_i
if(level==1)
load'EasyLevel.rb'
system('cls')
puts "#{ nextline}#{tabspace}#{' 1.Easy'.green}\n#{tabspace} 2.Medium\n#{tabspace} 3.Hard"
print("\n",tabspace , " >>>>> 1")
elsif(level==2)
load'MediumLevel.rb'
system('cls')
puts "#{ nextline}#{tabspace} 1.Easy\n#{tabspace}#{' 2.Medium'.green}\n#{tabspace} 3.Hard"
print("\n",tabspace , " >>>>> 2")
elsif(level==3)
load'HardLevel.rb'
system('cls')
puts "#{ nextline}#{tabspace} 1.Easy\n#{tabspace} 2.Medium\n#{tabspace} #{'3.Hard'.green}"
print("\n",tabspace , " >>>>> 3z")
else
Dir.chdir "audio"
Sound.play('Vampire Bite.wav')
mbox("game_shop-128","Error","Invalid input")
Dir.chdir ".."
redo
end
Dir.chdir "audio"
Sound.play('GunCock.wav')
Dir.chdir ".."
sleep(2)
break
end
suffleAndDistrubute()
end
display() #display the cards what now
Dir.chdir "audio"
Sound.play('shuffling-cards-6.wav')
Dir.chdir ".."
if(option==3)
File.delete("savefile.txt")
end
loop do
begin
if($arrangedCards != 8) #if not win the game
check_invisibleCards() #any invisible card need visible now
if(play!='T')
system("cls")
display() #display the cards what now
end
if(!isgameover()) #check the game is finish
print("Where to drag/exit/extracard/Hint(T)/help ")
play=gets.chomp.upcase;
if(play=="EXIT")
save()
break;
elsif(play=="HELP")
help()
elsif(play=="X")
if(!($extracards.empty?) and setExtraCardsInBoard())
Dir.chdir "audio"
Sound.play('shuffling-cards-6.wav')
Dir.chdir ".."
col=['A','B','C','D','E','F','G','H','I','J']
for x in (0..9) # check any card may be arranged
if(isCardArranged(col[x]))
$arrangedCards+=1
#sound
end
end
else
if(!($extracards.empty?))
Dir.chdir "audio"
Sound.play('Vampire Bite.wav')
mbox("playing-cards","Error","You cannot deal a new row while any columns are empty")
Dir.chdir ".."
else
Dir.chdir "audio"
Sound.play('Vampire Bite.wav')
mbox("playing-cards","Error","! Extra cards all are used")
Dir.chdir ".."
end
end
elsif play=="T"
isgameover(true)
elsif(play.length<=3)
cols=$card[$indexval[play[0]]].getAllCards.length()-1
if(play>="A" and play<="J" and cols>=0)
check=true
if(play.length == 1)
col=cols
while(check)
play=play[0]+col.to_s
check=popCheck(play[0],play[1..2].to_i)
col-=1
end
play=play[0]+((col+2).to_s)
check=true
else
check=false
end
if(check or (play[1..2].to_i >= $invisiblecard[$indexval[play[0]]]-1 and play[1..2].to_i <=cols and popCheck(play[0],play[1..2].to_i)))
Dir.chdir "audio"
Sound.play("Pop Cork.wav")
Dir.chdir ".."
c=play[0]
r=play[1..2].to_i
print("Where to join ")
play=gets.chomp.upcase
if(play>="A" and play<="J" and pushCheckAndSet(c,r,play,true))
Dir.chdir "audio"
Sound.play("Cupboard Door Close.wav")
Dir.chdir ".."
if(isCardArranged(play))
$arrangedCards+=1
mbox("reward",'setCards',"#{$arrangedCards}/8")
end
else
Dir.chdir "audio"
Sound.play('Vampire Bite.wav')
mbox("playing-cards","Error"," You can only put a card on another card if it is in the next card sequence.\n The order is: K(King),Q(Queen),J(Jack),10,9,8,7,6,5,4,3,2,A(Ace).")
Dir.chdir ".."
end
else
Dir.chdir "audio"
Sound.play('Vampire Bite.wav')
mbox("playing-cards","Error","You can only put a card on another card if it is in the next card sequence.\n The order is: K(King),Q(Queen),J(Jack),10,9,8,7,6,5,4,3,2,A(Ace).")
Dir.chdir ".."
end
else
Dir.chdir "audio"
Sound.play('Vampire Bite.wav')
mbox("playing-cards","Error","You can only put a card on another card if it is in the next card sequence.\n The order is: K(King),Q(Queen),J(Jack),10,9,8,7,6,5,4,3,2,A(Ace).")
Dir.chdir ".."
end
else
Dir.chdir "audio"
Sound.play('Vampire Bite.wav')
mbox("playing-cards","Error","You can only put a card on another card if it is in the next card sequence.\n The order is: K(King),Q(Queen),J(Jack),10,9,8,7,6,5,4,3,2,A(Ace).")
Dir.chdir ".."
end
else
Dir.chdir "audio"
Sound.play('Vampire Bite.wav')
mbox("playing-cards","NO MORE MOVES!"," \n You have run out of moves.\n Well Played!")
Dir.chdir ".."
gets.chomp
break
end
else
display
mbox("game_shop-128","! You Won","Congratulation!...\n You set all the cards")
$arrangedCards=0
break
end
if(play=="EXIT")
break
end
rescue Exception => e
if(e.message == "")
save()
play="EXIT"
break
else
Dir.chdir "audio"
Sound.play('Vampire Bite.wav')
mbox("playing-cards","Error","You can only put a card on another card if it is in the next card sequence.\n The order is: K(King),Q(Queen),J(Jack),10,9,8,7,6,5,4,3,2,A(Ace).")
Dir.chdir ".."
redo
end
end
end
end
if(play=="EXIT")
break
end
0.upto(9){|i| $card[i].deleteAllCards }
end
rescue Exception=>e
if(e.message!="")
retry
end
end | true |
aa01709493acc2b0dcac245d17b76f60255bc9b7 | Ruby | AdrianPardo99/metaheuristics | /actividadP1/tspRMHC.rb | UTF-8 | 1,250 | 2.6875 | 3 | [] | no_license | cities={(i,[j,c])_0,(i,[j,c])_1,...,(i,[j,c])_n}
# Conjunto de ciudades donde
# => i es el indice del grafo (ciudad)
# donde entre parentesis son
# => => j es el indice del siguiente grafo (ciudad)
# => => c es el costo de trasladarse de i a j
i_city=cities[random%cities.lenght]
path=[i_city]
lim_iterator=M
iterator=0
all_cities=cities.lenght-1
c_cities=0
use_index=[]
stuck_city=false
while (c_cities<all_cities || iterator<lim_iterator) && !stuck_city do
vecino=i_city.get_vecinos()
index=random%vecino.lenght
if index not in use_index && use_index.lenght<vecino.lenght-1
# Verifica si el indice no es repetitivo con respecto al arreglo
# y verifica si la ciudad a viajar no rebasa el limite, en cualquier caso
# esto genera que el viajero se quedo atascado ya viajo a todas
# las ciudades j
use_index.push(index)
city=vecino[use_index.last].city
if city not in path
# Verifica si la ciudad no esta en el camino del viajero
i_city=city
path.push(city)
c_cities=c_cities+1
use_index=[]
end
else
stuck_city=true
end
iterator=iterator+1
end
showPath(path)
# Muestra el camino recorrido del viajero
# y a su vez muestra el costo total en el cual se desea sea poco
| true |
ce68a11705f6a4ea1e75f1b7879669e1dceb8680 | Ruby | JingfZhang/math-game | /game.rb | UTF-8 | 1,175 | 3.8125 | 4 | [] | no_license | require "./player"
require "./question"
class Game
def initialize
p1 = Player.new("player1")
p2 = Player.new("player2")
@players = [p1, p2]
end
def play
round_count = 0
while (!game_over?)
round_count += 1
turn = Turn.new(@players[0], round_count, Question.new)
puts "============ Turn #{round_count} ============"
puts
puts "Question #{round_count}: #{turn.question.question}"
puts
print "#{turn.player.name}: "
turn_answer = gets.chomp.to_i
puts
if !turn.correct?(turn_answer)
puts ">>>>>>Wrong!!"
turn.player.life -= 1
else
puts ">>>>>>Correct!!"
turn.player.score += 1
end
puts
puts "--------- SUMMARY ---------"
puts turn_summary
puts
@players.rotate!
end
puts">>>>>>#{alive_player[0].name} IS SMARTER!!!<<<<<<"
end
def turn_summary
sorted_players = @players.sort {|a, b| a.name <=> b.name}
sorted_players.map {|player| player.summary}.join("\n")
end
def alive_player
@players.select {|player| player.life > 0}
end
def game_over?
alive_player.count == 1
end
end | true |
0871dea5adf9bbd3e29b11b105584b0da461abf5 | Ruby | tonnybrito/ruby | /carro/pessoa/cadastro.rb | UTF-8 | 583 | 2.515625 | 3 | [] | no_license |
require 'net/http'
require 'date'
require 'time'
require './pessoa'
# Cadastro
class Cadastro
attr_accessor :autocode, :dado_pessoal, :especialidade,
:plantao, :horarios
def initialize(cadastro = {})
@autocode = cadastro [:autocode]
@dado_pessoal = cadastro [:dado_pessoal]
@especialidade = cadastro [:especialidade]
@plantao = cadastro [:plantao]
@horarios = Cadastro [:horarios]
end
def autocode
end
def dado_pessoal
end
def especialidade
end
def plantao
end
def horarios
end
end
| true |
6f201f16be7530a932bea0f15439f1156a8b68e9 | Ruby | thorrsson/Monitoring | /write_to_graphite.rb | UTF-8 | 1,620 | 3.203125 | 3 | [] | no_license | #!/usr/bin/env ruby
#
# Writes a passed value to the graphite server of your choosing.
# * *Arguments:
# host <h>
# port<p>
# tree(Structure to create in Graphite) <t>
# value (to be written to graphite <v>
#
# Examples:
# +require './write_to_graphite'+
# +graphite = Write_To_Graphite::Graph.new('graphite.yourdomain.com', 2003, 'Data.To.Log')+
# +graphite.write_out(value)+
#
# @author Tim Hunter
require 'rubygems'
require 'socket'
require 'logger'
module Write_To_Graphite
class Graph
def initialize (h,p,t)
@log = Logger.new('/var/log/write_out.log', 'daily') #//TODO: path should be dynamic based on OS so that this can be run from Win too
@log.level = Logger::DEBUG
@graphite_host = h
@graphite_port = p
time = Time.new
@epoch = time.to_i #get me an epoch time to write to graphite
@tree = t #Tree is the structure in graphite
end #end Init
def write_out(v) #v = passed value to be written to graphite
value = v
begin#open my socket
socket = TCPSocket.open("#{@graphite_host}", "#{@graphite_port}")
rescue#log out errors and close the socket and log nicely
@log.error "error #{$!}"
socket.close
@log.close
else#write a log entry for this transaction and then write the data to graphite, then clean up after ourselves
@log.info "writing #{@tree} #{value} #{@epoch} to #{@graphite_host}:#{@graphite_port}"
socket.write("#{@tree} #{value} #{@epoch}\n") #write out to graphite
socket.close
@log.close
end
end #end write_out
end #end Graph
end #end Module | true |
b2ba3c7d649ad371f74b168380dd9da06436d9d8 | Ruby | julesnuggy/oystercard_challenge_2 | /spec/oystercard_spec.rb | UTF-8 | 3,412 | 2.921875 | 3 | [] | no_license | require 'oystercard'
describe Oystercard do
#oystercard = Oystercard.new
subject(:oystercard) {described_class.new}
subject(:oystercard_min) {described_class.new}
subject(:oystercard_empty) {described_class.new}
let(:station_dbl) { double(:station_dbl, name: "Paddington") }
let(:station_dbl_2) { double(:station_dbl, name: "Waterloo") }
before do
oystercard.top_up(10)
oystercard_min.top_up(1)
end
describe "check balance and enforce limits" do
it 'should have a balance of 0 when initialized' do
expect(oystercard_empty.balance).to eq 0
end
it 'should respond to #top_up by adding money to the balance' do
expect { oystercard.top_up(10) }.to change {oystercard.balance}.by(10)
end
it 'should raise an error when exceed the limit' do
expect { oystercard.top_up(100) }.to raise_error("Sorry, you've reached the limit of £#{Oystercard::DEFAULT_LIMIT}")
end
it 'should raise an error when below minimum balance' do
expect { oystercard_empty.touch_in(station_dbl) }.to raise_error("Sorry, not enough credit in balance (£#{oystercard_empty.balance})")
end
it 'should NOT raise an error when at minimum balance' do
expect { oystercard_min.touch_in(station_dbl) }.not_to raise_error
end
it 'should reduce the balance by minimum fare when touch_out' do
expect { oystercard.touch_out(station_dbl) }.to change {oystercard.balance}.by(-1)
end
end
describe "check and change card_status" do
it "should start the journey when touch in" do
oystercard.touch_in(station_dbl)
expect(oystercard.in_journey?).to be_truthy
end
it 'should end the journey when touch out' do
oystercard.touch_in(station_dbl)
oystercard.touch_out(station_dbl)
expect(oystercard.in_journey?).to be_falsey
end
it 'should be false when card_status is not_in_use' do
expect(oystercard.in_journey?).to be_falsey
end
it 'should be true when card_status is in_use' do
oystercard.touch_in(station_dbl)
expect(oystercard.in_journey?).to be_truthy
end
end
describe 'keep track of journey history' do
it 'logs the entry station' do
oystercard.touch_in(station_dbl)
expect(oystercard.entry_station).to eq "Paddington"
end
it 'logs the exit station' do
oystercard.touch_out(station_dbl_2)
expect(oystercard.exit_station).to eq "Waterloo"
end
it 'entry station is nil once you exit station' do
oystercard.touch_out(station_dbl_2)
expect(oystercard.entry_station).to eq nil
end
it 'starts empty by default' do
expect(oystercard.history).to eq []
end
it 'returns a single journey history' do
oystercard.touch_in(station_dbl)
oystercard.touch_out(station_dbl_2)
expect(oystercard.history).to eq [{entry: "Paddington", exit: "Waterloo"}]
end
it 'returns multiple journey history' do
oystercard.touch_in(station_dbl)
oystercard.touch_out(station_dbl_2)
oystercard.touch_in(station_dbl_2)
oystercard.touch_out(station_dbl)
expect(oystercard.history).to eq [{entry: "Paddington", exit: "Waterloo"}, {entry: "Waterloo", exit: "Paddington"}]
end
end
end
| true |
008b26756f79523c27e5dfad80c7cdbdfb0f8687 | Ruby | cheokman/code_lab_2016 | /entity_relational_mapping/lib/erm/attribute/accessor.rb | UTF-8 | 785 | 2.671875 | 3 | [
"MIT"
] | permissive | module ERM
class Attribute
module Accessor
attr_reader :name
attr_reader :instance_variable_name
def self.extended(base)
super
name = base.options.fetch(:name).to_sym
base.instance_variable_set('@name', name)
base.instance_variable_set('@instance_variable_name', "@#{name}")
end
def defined?(instance)
instance.instance_variable_defined?(instance_variable_name)
end
def get(instance)
instance.instance_variable_get(instance_variable_name)
end
def set(instance, value)
instance.instance_variable_set(instance_variable_name, value)
end
def set_default_value(instance)
set(instance, default_value.call(instance, self))
end
end
end
end | true |
9d5474c4c5e62a316a81f610e9280984a725d92f | Ruby | ianwhite/dummy_player | /players/player.rb | UTF-8 | 207 | 3.203125 | 3 | [] | no_license | require 'ian_hangman'
class Player
def name
"Ian White"
end
def take_turn(state, guesses)
@hangman = IanHangman.new(state.length) if guesses.empty?
@hangman.answer(state, guesses)
end
end
| true |
be5e5d3c93c50b091e413ad2e1fba0522c591f92 | Ruby | Artoria/CocoDK | /coco.rb | UTF-8 | 4,153 | 2.546875 | 3 | [] | no_license | ENV['path'] = "#{ENV['path']};C:\\railsinstaller\\DevKit\\mingw\\bin"
class Expr
attr_accessor :obj, :scope
def initialize(obj, scope = nil)
@obj = obj
@scope = scope
end
alias to_s obj
[:+, :-, :*, :/, :==, :!=, :%, :^, :&, :|].each{|x|
define_method(x){|obj|
a = obj.is_a?(Expr) ? obj.obj : obj
self.class.new("(#{@obj} #{x} #{a})", @scope)
}
}
def get(obj)
a = obj.is_a?(Expr) ? obj.obj : obj
self.class.new("(#{@obj}.#{a})", @scope)
end
def rget(obj)
a = obj.is_a?(Expr) ? obj.obj : obj
self.class.new("(#{@obj}->#{a})", @scope)
end
alias [] rget
def if(falsepart = nil, &block)
If.new(@scope) do |x|
x.cond << @obj
Scope.new(x.truepart).instance_eval &block
Scope.new(x.falsepart).instance_eval &falsepart if falsepart
end
self
end
def while
While.new(@scope) do |x|
x.cond << @obj
Scope.new(x.yieldpart).instance_eval &block
end
self
end
def call(*args)
#Funcall.new(@scope).call(@obj, *args)
self.class.new "#{@obj}(#{args.map{|x| Translate[x]}.join(',')})", @scope
end
def ret
@scope << "return #{@obj}; \n"
end
def put
@scope << @obj
self
end
def putendl
put
endl
end
def endl
@scope << ';'
self
end
end
class Scope < BasicObject
def writer
@writer
end
def initialize(writer)
@writer = writer
end
def method_missing(sym, *args)
if args == []
sym.to_s.to_expr(self)
else
sym.to_s.to_expr(self).call(*args).putendl
end
end
def <<(text)
@writer << text
end
def expr(x)
x.to_expr(self)
end
def ret(x)
expr(x).ret
end
def endl
@writer << ";"
self
end
end
class Object
def to_expr(scope)
Expr.new(self, scope)
end
end
class Text
CC = "gcc"
CXX = "g++"
CFLAGS = ""
CXXFLAGS = ""
LDFLAGS = ""
def initialize(filename)
@filename = filename
open(@filename, 'w'){|f| f.write header}
@scopes = []
end
def header
"#include <cstdio>\n"
end
def <<(text)
open(@filename, 'a'){|f| f.write text}
self
end
def compile(output = nil)
system "#{self.class.const_get :CXX} #{self.class.const_get :CXXFLAGS} #{@filename} -o #{output || @filename + ".exe"} #{self.class.const_get :LDFLAGS}"
end
alias output <<
end
class Writer
def self.textpart(*syms)
syms.each{|sym|
class_eval %{
def #{sym}
Writer.new(@#{sym}||= "")
end
}
}
end
def initialize(obj)
@obj = obj
init
if block_given?
yield self
close
end
end
def close
end
def init
end
def <<(text)
@obj << text
self
end
def endl
output ';'
self
end
alias output <<
end
class Function < Writer
def init
end
def start(signature)
output signature
output "{\n"
end
def close
output "}"
end
def endl
output ";"
end
end
class Translate
def self.[](x)
case x
when Symbol
x.to_s
else
x.inspect
end
end
end
class Control < Writer
def call(sym, *args)
output "#{sym} #{args.map{|x| Translate[x]}.join(' ')}"
self
end
alias method_missing call
end
class Funcall < Writer
def call(sym, *args)
output "#{sym}(#{args.map{|x| Translate[x]}.join(',')})"
self
end
alias method_missing call
end
class Block < Writer
textpart :sig, :block
def close
output "#{@sig}{\n#{@block}\n}"
end
end
class If < Writer
textpart :cond, :truepart, :falsepart
def close
output "if (#{@cond}){
#{@truepart}
}else{
#{@falsepart}
}"
end
end
class While < Writer
textpart :cond, :yieldpart
def close
output "while (#{@cond}){
#{@yieldpart}
}"
end
end
$: << "."
ARGV.each{|x|
require x
}
| true |
fd57df291d9c0022dd294583d457ba2f758a8992 | Ruby | ddmaness/app-academy-exercises | /ruby-exercises/data-structures/skeleton/lib/00_tree_node.rb | UTF-8 | 1,412 | 3.765625 | 4 | [] | no_license | class PolyTreeNode
def initialize(value)
@value = value
@parent = nil
@children = Array.new()
end
def parent
return @parent
end
def children
return @children
end
def value
return @value
end
def parent=(node)
unless @parent == nil
@parent.children.filter! {|child| child != self}
end
@parent = node
unless @parent == nil || @parent.children.include?(self)
@parent.children << self
end
end
def add_child(child_node)
child_node.parent = self
end
def remove_child(child_node)
if child_node.parent == nil
raise 'This node is not a child'
else
child_node.parent = nil
end
end
def dfs(target_value)
if @value == target_value
return self
end
children.each do |child|
result = child.dfs(target_value)
return result unless result.nil?
end
nil
end
def bfs(target_value)
queue = Array.new()
queue << self
until queue.length == 0
current_node = queue.shift()
if current_node.value == target_value
return current_node
else
current_node.children.each {|child| queue << child}
end
end
end
end | true |
f2879a7cf8f521050396b96db0980566465c9eb4 | Ruby | LisaLouAEH/mercredi_s1 | /full_pyramide.rb | UTF-8 | 750 | 3.875 | 4 | [] | no_license | =begin
Faire une pyramide complete.
=end
def pyramide
puts "HI ! how many floor do you want (only between 1 to 25) ?"
print "-->"
number = gets.to_i
hash = 1
spaces = number
floor = 0
if number < 1
puts "We said more than 1 floor min..."
elsif number > 25
puts "Hey ! we said not more than 25 floors !!"
else
puts "here we are : "
while floor < number
spaces.times {print " "}
hash.times {print "#"}
puts "\n"
hash += 2
spaces -= 1
floor = floor + 1
end
end
end
pyramide
| true |
8284a786b381cc133a31fba15c19d177e43c58fa | Ruby | trevorsmith1667/aa-classwork | /W4D4/TDD/spec/array_spec.rb | UTF-8 | 2,072 | 3.765625 | 4 | [] | no_license | require "rspec"
require "array"
describe Array do
let(:my_arr) {[1, 2, 1, 3, 3]}
let(:my_neggy) {[-1, 1, 2, -2, 3,-3]}
let(:my_bupkis) {[-1, 0, 80, -75, 4, 10]}
let(:my_grill) {[
[0, 1, 2],
[0, 1, 2],
[0, 1, 2]
]}
let(:my_enron_stock) {[2, 1, 100, 4, 209 ]}
describe "#my_uniq" do
it "checks array validity" do
expect(my_arr).to be_a(Array)
end
it "removes duplicates" do
expect(my_arr).to contain_exactly(1, 2, 1, 3, 3)
expect(my_uniq(my_arr).uniq).to eq([1, 2, 3])
end
end
describe "#two_sum" do
it "when given any 2 elements whose sum amounts to 0, returns pairs in a inner array of 2D array" do
expect(two_sum(my_neggy)).to eq([[-1,1], [-2,2], [-3,3]])
end
it "should return an empty array when no pairs's sum equals zero" do
expect(two_sum(my_bupkis)).to eq([])
end
end
describe "#my_transpose" do
it "should return a transposed grid where rows and columns are reversed" do
expect(my_transpose(my_grill)).to eq([[0,0,0],[1,1,1],[2,2,2]])
end
end
describe "#stock_picker" do
it "should return a pair of indices representing days that maximizes stock profit" do
expect(stock_picker(my_enron_stock)).to eq([1,4])
end
end
describe "#hanoi_tower" do
subject(:towers){[[10,8,6,4,2],[],[]]}
let(:length){towers[0].length}
it "should take in 3 arrays, the first containing all the elements" do
expect(towers[0].length).to eq(length)
end
it "the other two are empty" do
expect(towers[1].empty?).to be(true)
expect(towers[2].empty?).to be(true)
end
it "should take in 2D array with 3 subarrays and return the same" do
expect(hanoi_tower(towers).length).to eq(3)
end
# it "should return 3 arrays such that all elements from 1st array have moved to the 2nd or 3rd" do
# end
end
end
| true |
a491414702d3781018ed1cfe73a7d5c1c385c979 | Ruby | alf-tool/alf-core | /lib/alf/aggregator/sum.rb | UTF-8 | 674 | 3.078125 | 3 | [
"MIT"
] | permissive | module Alf
class Aggregator
#
# Defines a `sum()` aggregation operator.
#
# Example:
#
# # direct ruby usage
# Alf::Aggregator.sum{ qty }.aggregate(...)
#
# # lispy
# (summarize :supplies, [:sid], :total => sum{ qty })
#
class Sum < Aggregator
# Returns 0 as least value.
#
# @see Aggregator::InstanceMethods#least
def least()
0
end
# Aggregates on a tuple occurence through `memo + val`
#
# @see Aggregator::InstanceMethods#_happens
def _happens(memo, val)
memo + val
end
end # class Sum
end # class Aggregator
end # module Alf
| true |
0bdc98ad1b1fc51a5c118ff9fcc34929b6cebf8f | Ruby | VladDaImpaler18/anagram-detector-onl01-seng-pt-032320 | /lib/anagram.rb | UTF-8 | 295 | 3.546875 | 4 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'pry'
class Anagram
attr_accessor :word
def initialize(word)
@word = word
end
def match(list_of_words)
output = []
list_of_words.each do |word|
output << word if word.split("").sort == @word.split("").sort
#binding.pry
end
output
end
end | true |
9c47f36e75975fd034d2be046ac9e9453a75a18d | Ruby | bebbs/takeaway-challenge | /lib/menu.rb | UTF-8 | 582 | 3.640625 | 4 | [] | no_license | class Menu
require 'csv'
def initialize(restaurant)
@dishes = []
@name = restaurant
load_menu(restaurant)
end
attr_reader :name, :dishes
def load_menu(restaurant)
CSV.foreach("#{restaurant}.csv", {col_sep: ','}) do |line|
populate_dish(line)
end
end
def populate_dish(item)
new_dish = Dish.new(item[0], item[1])
dishes << new_dish
end
def dish_count
dishes.length
end
def exists?(dish)
dishes.any? { |d| d.name == dish }
end
def fetch_by_name(dish)
dishes.select { |d| d.name == dish }.first
end
end | true |
6670864b1c77b4af5beeb05528dd1249ae371f1a | Ruby | MarshaAnnon/the-best-botanical-gardens-USA | /lib/scraper.rb | UTF-8 | 516 | 2.6875 | 3 | [
"MIT"
] | permissive | class Scraper
TheActiveTimes_URL = "https://www.theactivetimes.com/travel/best-botanical-gardens-us-gallery"
def self.scrape_TheActiveTimes
html = open(TheActiveTimes_URL)
doc = Nokogiri::HTML(html)
doc.css(".slide-main").each do |garden_info|
title = garden_info.css("div.image-title.slide-title h2").text
body = garden_info.css("div.image-description.slide-description p").text
garden = Garden.new(title, body)
end
end
end | true |
89dc7b739b8a041aa6cba9144278907f0100d155 | Ruby | producthunt/ShareMeow | /app/image.rb | UTF-8 | 747 | 2.71875 | 3 | [
"MIT"
] | permissive | require 'securerandom'
module ShareMeow
class Image
# Zooming in makes text more crisp
DEFAULT_OPTIONS = { zoom: 2 }
attr_reader :template
def initialize(params)
@template = template_class(params['template']).send(:new, params)
end
def to_jpg
options = DEFAULT_OPTIONS.merge(width: template.image_width, quality: template.image_quality)
image_kit = IMGKit.new(template.to_html, options)
image_kit.stylesheets << template.css_stylesheet
image_kit.to_img(:jpg)
end
private
def template_class(template_name)
ImageTemplates.const_get template_name
rescue NameError
raise NotImplementedError, "You must implement a #{template_name} template"
end
end
end
| true |
67ffd806b822c6b7737c8c66f4c16a7eed394496 | Ruby | jsiny/101_programming_foundations | /exercises/03_easy_2/ex_9.rb | UTF-8 | 416 | 3.9375 | 4 | [] | no_license | name = "Bob"
save_name = name
name.upcase!
puts name, save_name
# This program prints out:
# BOB
# BOB
# The reason behind this is that String#upcase! is a destructive method.
# As such, it mutated the caller (name), which means that the space in
# memory was changed.
# As save_name points to the same space in memory than name, a change in name
# is impacted on save_name
# That's why now save_name returns BOB. | true |
3afb06af87b403741cb9b27a456524af49ab9aed | Ruby | saranderson13/keys-of-hash-online-web-prework | /lib/keys_of_hash.rb | UTF-8 | 275 | 3.28125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Hash
def keys_of(*arguments)
# returns an array of every key with a value that matches an argument
array_of_keys = []
arguments.each do |arg|
keys.each { |key| array_of_keys << key if arg == self[key] }
end
array_of_keys
end
end
| true |
019bbb60506552863344e0af6181c694c7b3d87c | Ruby | taylorfinnell/kayvee | /lib/kayvee/store.rb | UTF-8 | 2,329 | 2.96875 | 3 | [
"MIT"
] | permissive | module Kayvee
# Represents a simple key value store. Provides multiple backing stores.
#
# @example Basic Useage
# store = Kayvee::Store.new(:s3, aws_access_key: '', ... )
# key = store.set('hello', 'world')
# key.read
# => 'world'
#
# store = Kayvee::Store.new(:redis, host: 'redis://locahost')
# key = store.set('hello', 'world')
# key.read
# => 'world'
#
# @see Kayvee::Clients::S3
# @see Kayvee::Clients::Redis
# @see Kayvee::Clients::Memory
# @see Kayvee::Clients::Test
class Store
# Raised when a client implementation can not be found.
ClientNotFound = Class.new(Exception)
# The internal client driving the store
attr_reader :client
# @param [Symbol] client the symbol representing the client to use. :s3, :redis, :memory, :test
# @param [Options] options the config for the client implementation
#
# @see Kayvee::Clients::S3
# @see Kayvee::Clients::Redis
# @see Kayvee::Clients::Memory
# @see Kayvee::Clients::Test
def initialize(client = :s3, options = {})
load_client(client)
@client = instantiate_client(client, options)
end
# Sets a given key to a given value
#
# @param [String] path the path to set
# @param [String] value the value to set
#
# @return [Key] the newly created or modified key object
def set(path, value)
key = Kayvee::Key.new(@client, path)
key.write(value)
key
end
alias :[]= :set
# Gets a given keys value
#
# @param [String] path the path to set
#
# @return [Key] the value of the key
def get(path)
Kayvee::Key.new(@client, path)
end
alias :[] :get
# Clear the underlying store
def clear
@client.clear
end
def size
@client.size
end
private
def instantiate_client(client, options)
begin
klass = "Kayvee::Clients::#{client.capitalize}".constantize
klass.new(options)
rescue NameError
raise ClientNotFound.new
end
end
def load_client(client)
begin
require "kayvee/clients/#{client}"
rescue LoadError => load_error
raise LoadError.new("Cannot find Kayvee::Clients::#{client.capitalize} adapter '#{client}' (#{load_error.message})")
end
end
end
end
| true |
5216e0770f085f1183c018340a73371dc9c505c7 | Ruby | RudiBoshoff/ruby-exercises | /procExample.rb | UTF-8 | 537 | 4.53125 | 5 | [] | no_license | # Passing a Proc in a method
def action someProc
someProc.call
end
hello = Proc.new do
puts "Hello World!"
end
# Passing a Proc that has a parameter in a method
def action2 (someProc, name)
someProc.call(name) # have to pass the name to the call function
end
bye = Proc.new do |name|
puts "Ewwww that is a terrible name. Goodbye #{name}!" # a proc with a parameter being passed to a method
end
action(hello)
puts "Enter your name"
name = gets.chomp
action2(bye, name) # passes the Proc and the Proc's_Argument to the method
| true |
e2c71a8e8d7276fa316b306675e0bb7706c62adf | Ruby | darkelv/lessons | /Lesson_1/area_of_a_triangle.rb | UTF-8 | 256 | 3.328125 | 3 | [] | no_license | puts "Введите основание треугольника"
base = gets.to_f
puts "Введите высоту треугольника"
height = gets.to_f
area = 0.5 * base * height
puts "Площадь треугольника #{area.round(2)}"
| true |
ef53e81275f66fffa9b9037561411fcb014eaaf7 | Ruby | Eractus/data_structures | /QuickSort/lib/quick_select.rb | UTF-8 | 1,086 | 3.765625 | 4 | [] | no_license | #Write an in-place instance method on the Array class that will find the 'kth' smallest element in 'O(n)' time. You will likely want to use a partition method similar to that of QuickSort! For a bous, how can we eliminate any extra space cost.
class Array
def quick_select(array, k)
left = 0
right = self.length - 1
loop do
return self[left] if left == right
pivot_idx = Array.partition(self, left, right-left+1)
end
if k - 1 == pivot_idx
return self[k - 1]
elsif k - 1 < pivot_idx
right = pivot_idx - 1
else
left = pivot_idx + 1
end
end
def self.partition(array, start, length, &prc)
prc ||= Proc.new { |num1, num2| num1 <=> num2 }
barrier = start
i = start
while i < (length + start)
if i == barrier
i += 1
next
end
if prc.call(array[i], array[start]) <= 0
array[barrier + 1], array[i] = array[i], array[barrier + 1]
barrier += 1
end
i += 1
end
array[start], array[barrier] = array[barrier], array[start]
barrier
end
end
| true |
be4d8568ae81f17ff211ffc65a7de995a3660d8d | Ruby | jaredm-ibm/ibm-cloud-sdk-ruby | /lib/ibm/cloud/sdk_http/base_collection.rb | UTF-8 | 4,437 | 2.703125 | 3 | [
"Apache-2.0"
] | permissive | # typed: true
# frozen_string_literal: true
require_relative 'base_http_mixin'
require_relative 'has_child'
module IBM
module Cloud
module SDKHTTP
# Container that encapsulates the VPC API.
# This class is used as a base for collection APIs.
# @param parent [Object] The parent instance in the API chain.
# @param endpoint [string] A path from the parent to the desired endpoint. In most cases is should be 1 word.
# @param array_key [string] The key that the API response holds the endpoint data. When nil the endpoint will be used.
# @param child_class [Object] The Object to be used when instanciating the single instance for this class.
class BaseCollection
include BaseHTTPMixin
def initialize(parent, endpoint, array_key: nil, child_class: nil, child_id: 'id')
# Setup empty base instance variables.
@params = {}
@token = parent.token
array_key ||= endpoint
# Set the array key and child class.
@array_key ||= array_key
@instance ||= child_class
@instance_id ||= child_id
@connection = parent.connection
(class << self; include ChildMixin; end) if child_class
@endpoint = parent.url(endpoint)
@logger = parent.logger
end
attr_reader :logger, :endpoint, :token, :connection
# In a Child base class add the possible query parameters for the API and return self to make it chainable.
# When implemented usage would be Collection.params(limit: 2).get
# @return [BaseCollection] The instanticated class.
def params(limit: nil)
raise NotImplementedError('Sample only. The params method needs to be customized in child class.')
# rubocop:disable Lint/UnreachableCode
@params[:limit] = limit if limit
self
# rubocop:enable Lint/UnreachableCode
end
def reset_params
@params.clear
end
# Retrieve the collection from the cloud.
# @return [IBM::Cloud::SDK::VPC::Response] The http response object.
def fetch
@data ||= get
end
# Get an iterable for the resource collection.
# @return [Enumerator] Use standard each, next idioms.
def all
each_resource(url)
end
# Fetch all data and return in an array.
# @return [Array] Hashes of the returned data.
def data
all.to_a
end
# A generic post method to create a resource on the collection.
# @param payload [Hash] A hash of parameters to send to the server.
# @param payload_type [String] One of the following options json, form, or body.
# @return [IBM::Cloud::SDK::VPC::Response] The http response object.
def create(payload, payload_type = 'json')
adhoc(method: 'post', payload_type: payload_type, payload: payload)
end
private
# Return a wrapped instance if set.
# @param value [Hash] The hash returned from server.
def hash_instance(value)
return @instance.new(self, data: value, id_key: @instance_id) if @instance
value
end
# Create a generator that removes the need for pagination.
# @param url [String] Full URL to send to server.
# @return [Enumerator] Object to page through results.
# @yield [BaseInstance] An instance of the instance class.
# @yield [Hash] When no BaseInstance set.
def each_resource(url, &block)
raise NotImplementedError('Sample only. The each_resource method needs to be customized in child class.')
# rubocop:disable Lint/UnreachableCode
# Sample implementation based on VPC.
return enum_for(:each_resource, url) unless block_given?
return unless url
response = get(path: url)
resources = response.fetch(@array_key.to_sym)
resources&.each { |value| yield hash_instance(value) }
# VPC has a next key that holds the next URL.
return unless response.key?(:next)
# The next data structure is a hash with a href member.
next_url = response.dig(:next, :href)
return unless next_url
each_resource(next_url, &block)
# rubocop:enable Lint/UnreachableCode
end
end
end
end
end
| true |
f76abf9f52625a89bc3c0d844a099e94d5b000cd | Ruby | sobopla/placeholder | /app/helpers/spotify_helper.rb | UTF-8 | 2,660 | 2.890625 | 3 | [] | no_license | require 'net/http'
require 'json'
module SpotifyHelper
def self.get_token
encode = (Base64.encode64(ENV["SPOTIFY_ID"] + ':' + ENV["SPOTIFY_SECRET"])).gsub("\n",'')
uri = URI.parse("https://accounts.spotify.com/api/token")
request = Net::HTTP::Post.new(uri)
request["Authorization"] = "Basic #{encode}"
request.set_form_data(
"grant_type" => "client_credentials",
)
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
hash = JSON.parse(response.body)
ENV["ACCESS_TOKEN"] = hash["access_token"]
return hash["access_token"]
end
def self.api_call(artist)
formatted_artist = artist.gsub(/ /, "+")
uri = URI.parse("https://api.spotify.com/v1/search?q=#{formatted_artist}&type=artist")
request = Net::HTTP::Get.new(uri)
request["Authorization"] = "Bearer #{ENV["ACCESS_TOKEN"]}"
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
return response
end
def self.genre_check(artists_array, user_genre)
artists = []
access_token = SpotifyHelper.get_token
artists_array.each do |artist|
found_artist = Artist.find_by(name: artist) # return nil or first item
if found_artist
artists << found_artist if found_artist.has_genre?(user_genre)
else # need to make a Spotify API call to get the Spotify ID
new_artist = Artist.new(name: artist)
next if new_artist == ""
next if new_artist.has_weird_characters # skip if artist has funky characters
results = JSON.parse(api_call(new_artist.name).body)["artists"]
next if results == nil
spotify_artist_info = results["items"] # something might be broken here?
next if spotify_artist_info.empty? # skip artists with no information
update_new_artist(new_artist, spotify_artist_info)
artists << new_artist if new_artist.has_genre?(user_genre)
end
end
return artists
end
def self.update_new_artist(new_artist, spotify_artist_info)
new_artist.image = spotify_artist_info[0]["images"][0]["url"] if !spotify_artist_info[0]["images"].empty? # skip if bands do not have image (from Spotify)
new_artist.spotify = spotify_artist_info[0]["id"]
genre_array = spotify_artist_info[0]["genres"]
genre_array.each do |specific_genre|
genre = Genre.find_or_create_by(genre: specific_genre)
new_artist.genres << genre
end
new_artist.save
end
end
| true |
88e76664c454d2bfc06257660b910a358c4c316e | Ruby | hackershare/hackershare | /db/migrate/20200928161133_add_fuzzywuzy.rb | UTF-8 | 1,667 | 2.6875 | 3 | [
"MIT"
] | permissive | class AddFuzzywuzy < ActiveRecord::Migration[6.0]
def change
enable_extension :fuzzystrmatch
execute(<<~SQL)
CREATE OR REPLACE FUNCTION ratio(l text, r text) RETURNS int
LANGUAGE plpgsql IMMUTABLE
AS $$
DECLARE
diff int; -- levenshtein编辑距离
l_len int := length(l);
r_len int := length(r);
short_len int;
long_len int;
match_len int;
result int;
BEGIN
IF (l IS NULL) OR (r IS NULL) OR (l = '') OR (r = '') THEN
result := 0;
ELSE
SELECT levenshtein(l, r) INTO diff;
SELECT GREATEST(l_len, r_len) INTO long_len;
SELECT LEAST(l_len, r_len) INTO short_len;
-- match长度为:最长字符串减去编辑距离
match_len := long_len - diff;
-- 基于fuzzywuzzy公式
-- Return a measure of the sequences’ similarity as a float in the range [0, 100].
-- Where T is the total number of elements in both sequences, and M is the number of matches, this is 2.0*M / T.
-- Note that this is 100 if the sequences are identical, and 0 if they have nothing in common.
-- https://docs.python.org/3/library/difflib.html#difflib.SequenceMatcher.ratio
-- https://github.com/seatgeek/fuzzywuzzy
result := ((2.0 * match_len * 100) / (long_len + short_len));
END IF;
RETURN(result);
END;
$$;
SQL
end
end
| true |
680bed2fdb13a0871c494104b1cb8d751b65709a | Ruby | neilmarion/qtest | /lib/word_helper.rb | UTF-8 | 543 | 2.75 | 3 | [] | no_license | module WordHelper
def self.tally(some_string)
words = some_string.split(' ')
frequency = Hash.new(0)
words.each { |word| frequency[word.downcase.to_sym] += 1 }
return frequency
end
def self.filter(phrase, black_list)
black_list.split.each {|replacement|
phrase.gsub!(/(#{replacement})/i, '*' * replacement.length)
}
phrase
end
def self.link_to_users(phrase, black_list)
phrase.gsub!(/[@]\w+/) do |match|
"<a href='http://github.com/#{match.gsub('@','')}'>#{match}</a>"
end
end
end
| true |
156257ac7e990119defe67b930c1b2b1ebc1b582 | Ruby | alexandru-calinoiu/simple_delegator_example | /burger_decorator.rb | UTF-8 | 252 | 2.8125 | 3 | [] | no_license | require_relative 'burger'
require 'delegate'
class BurgerDecorator < SimpleDelegator
def initialize(burger)
@burger = burger
super
end
end
burgerDecorator = BurgerDecorator.new(Burger.new)
puts burgerDecorator.cost
puts burgerDecorator.calories | true |
39d65b3fcbb73822f43cfa820e26e643a909357f | Ruby | Balaraju/Task | /task66.rb | UTF-8 | 351 | 4.03125 | 4 | [] | no_license |
#Below method is Block method
name1=lambda do
|name|
puts "Hello #{name} Welcome to Ruby on Rails"
end
puts "HELLO PLZ ENTER YOUR NAME :"
#using Below Method we can read entered name
enter_name=gets.chomp
#uisng Below Method we can pass the enterd variable into Block Method
name1.call(enter_name)
| true |
fee9b85291b1102e2a3b2916c6bfc60b498574c5 | Ruby | quartzmo/butterfly_net | /test/test_case_test.rb | UTF-8 | 6,539 | 2.546875 | 3 | [
"MIT"
] | permissive | require "test/unit"
$: << File.expand_path(File.dirname(__FILE__))
$: << File.join(File.expand_path(File.dirname(__FILE__)), File.join("..", "lib"))
require "butterfly_net/file_writer"
require "butterfly_net/definitions"
require "butterfly_net/test_unit_method"
require "butterfly_net/test_unit_adapter"
require "butterfly_net/rails_test_unit_adapter"
require "butterfly_net/test_case"
class TestCaseTest < Test::Unit::TestCase
include ButterflyNet
def setup
@test_case = TestCase.new('temp_test.rb')
end
def teardown
File.delete 'temp_test.rb' if File.exists? 'temp_test.rb' # delete old in test, since impl should append, not overwrite
end
def test_expression_eval
# assert eval("assert_equal(2, 1 + 1)") todo figure out how to eval assertions here
end
def test_test_methods_single
@test_case.add_command("1 + 1", 2)
expected = " def test_1\n assert_equal(2, 1 + 1)\n end\n\n"
assert_equal expected, @test_case.test_methods.first
end
def test_test_methods_2_assertions_1_method
@test_case.add_command("1 + 1", 2)
@test_case.add_command("1 + 2", 3)
expected = " def test_1\n assert_equal(2, 1 + 1)\n assert_equal(3, 1 + 2)\n end\n\n"
assert_equal expected, @test_case.test_methods.last
end
def test_test_methods_variable_in_assertion
@test_case.add_command("a = 1", 1)
@test_case.add_command("a + 2", 3)
expected = " def test_1\n a = 1\n assert_equal(3, a + 2)\n end\n\n"
assert_equal expected, @test_case.test_methods.last
end
def test_test_methods_require
@test_case.add_command("require 'bigdecimal'", true)
@test_case.add_command("BigDecimal(\"1.0\") - 0.5", 0.5) # result class really is Float
expected = " def test_1\n require 'bigdecimal'\n assert_equal(0.5, BigDecimal(\"1.0\") - 0.5)\n end\n\n"
assert_equal expected, @test_case.test_methods.last
end
def test_test_methods_numbering_first_method
@test_case.add_command("1 + 1", 2)
@test_case.close_assertion_set
@test_case.add_command("1 + 2", 3)
assert_equal " def test_1\n assert_equal(2, 1 + 1)\n end\n\n", @test_case.test_methods.first
end
def test_test_methods_numbering_second_method
@test_case.add_command("1 + 1", 2)
@test_case.close_assertion_set
@test_case.add_command("1 + 2", 3)
assert_equal " def test_2\n assert_equal(3, 1 + 2)\n end\n\n", @test_case.test_methods.last
end
def test_test_methods_naming
@test_case.add_command("1 + 1", 2)
@test_case.close_assertion_set 'test_one_plus_one'
assert_equal " def test_one_plus_one\n assert_equal(2, 1 + 1)\n end\n\n", @test_case.test_methods.first
end
def test_test_methods_bad_input
@test_case.add_command("BADCOMMAND", nil, NameError.new("exception message"))
@test_case.close_assertion_set
assert_equal " def test_1\n # BADCOMMAND # NameError: exception message\n end\n\n", @test_case.test_methods.first
end
def test_empty_false
@test_case.add_command("1 + 1", 2)
assert !@test_case.empty?
end
def test_create_file
@test_case.add_command("1 + 1", 2)
expected = <<-EOF
require "test/unit"
# IRB test capture courtesy of butterfly_net (butterflynet.org)
class MyTest < Test::Unit::TestCase
def test_1
assert_equal(2, 1 + 1)
end
end
EOF
@test_case.create_file('temp_test.rb') # todo: write to memory instead of file...
assert_equal expected, File.open('temp_test.rb').readlines.join('')
end
def test_create_file_with_2_methods
@test_case.add_command("1 + 1", 2)
@test_case.close_assertion_set('first')
@test_case.add_command("1 + 2", 3)
expected = <<-EOF
require "test/unit"
# IRB test capture courtesy of butterfly_net (butterflynet.org)
class MyTest < Test::Unit::TestCase
def test_1
assert_equal(2, 1 + 1)
end
def test_2
assert_equal(3, 1 + 2)
end
end
EOF
@test_case.create_file('temp_test.rb') # todo: write to memory instead of file...
assert_equal expected, File.open('temp_test.rb').readlines.join('')
end
def test_create_file_single_test_method_two_lines
@test_case.add_command("a = 1", 1)
@test_case.add_command("a + 2", 3)
expected = <<-EOF
require "test/unit"
# IRB test capture courtesy of butterfly_net (butterflynet.org)
class MyTest < Test::Unit::TestCase
def test_1
a = 1
assert_equal(3, a + 2)
end
end
EOF
@test_case.create_file('temp_test.rb') # todo: write to memory instead of file...
assert_equal expected, File.open('temp_test.rb').readlines.join('')
end
def test_create_file_definitions
@test_case.add_command("class Mine\nend", nil)
@test_case.add_command("Mine.new.class.to_s", "Mine")
expected = <<-EOF
require "test/unit"
# IRB test capture courtesy of butterfly_net (butterflynet.org)
class MyTest < Test::Unit::TestCase
def test_1
assert_equal("Mine", Mine.new.class.to_s)
end
end
# definitions
class Mine
end
EOF
@test_case.create_file('temp_test.rb') # todo: write to memory instead of file...
assert_equal expected, File.open('temp_test.rb').readlines.join('')
end
def test_create_file_def_method_single_inline
@test_case.add_command("def timestwo(i); i * 2; end", nil)
@test_case.add_command("timestwo(4)", 8)
expected = <<-EOF
require "test/unit"
# IRB test capture courtesy of butterfly_net (butterflynet.org)
class MyTest < Test::Unit::TestCase
def test_1
assert_equal(8, timestwo(4))
end
end
# definitions
def timestwo(i); i * 2; end
EOF
@test_case.create_file('temp_test.rb') # todo: write to memory instead of file...
assert_equal expected, File.open('temp_test.rb').readlines.join('')
end
def test_create_file_def_methods_two_inline
@test_case.add_command("def timestwo(i); i * 2; end", nil)
@test_case.add_command("def timesfour(i); timestwo(i) * timestwo(i); end", nil)
@test_case.add_command("timestwo(1)", 2)
@test_case.add_command("timesfour(1)", 4)
expected = <<-EOF
require "test/unit"
# IRB test capture courtesy of butterfly_net (butterflynet.org)
class MyTest < Test::Unit::TestCase
def test_1
assert_equal(2, timestwo(1))
assert_equal(4, timesfour(1))
end
end
# definitions
def timestwo(i); i * 2; end
def timesfour(i); timestwo(i) * timestwo(i); end
EOF
@test_case.create_file('temp_test.rb') # todo: write to memory instead of file...
assert_equal expected, File.open('temp_test.rb').readlines.join('')
end
end | true |
98efe6f780f5b3e48d90251b950d34e595671b64 | Ruby | lilliealbert/pine_ruby_exercises | /pine_ch05s6b--better_fav_number.rb | UTF-8 | 545 | 4.34375 | 4 | [] | no_license | #and here's my one-upping favorite number machine
puts "Hey, so what's your favorite number?"
fav_number = gets.chomp.to_i + 1
puts "Really? Because you might get a lot further in life with a favorite number like " + fav_number.to_s + " . But that's just my opinion. What do I know? I'm just a passive-aggressive computer program."
#So. I learned/was reminded that you can't add a string to a number. Turning the input from a string into an integer back into a string feels a bit cumbersome -- wondering if others had more elegant solutions.
| true |
8c59a507a1dfe66294c2dc927863b81c13520a1b | Ruby | Nicholas-Maxwell/array-CRUD-lab-v-000 | /lib/array_crud.rb | UTF-8 | 989 | 3.8125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def create_an_empty_array
[]
end
def create_an_array
fruits = [ "orange" , "apples" , "coconut" , "mangos"]
end
def add_element_to_end_of_array(array, element)
fruits = [ "orange" , "apples" , "coconut" , "mangos"]
fruits.push("arrays!")
end
def add_element_to_start_of_array(array, element)
fruits = [ "orange" , "apples" , "coconut" , "mangos"]
fruits.unshift("wow")
end
def remove_element_from_end_of_array(array)
fruits = [ "orange" , "apples" , "coconut" , "arrays!"]
arrays = fruits.pop
end
def remove_element_from_start_of_array(array)
fruits = [ "wow" , "apples" , "coconut" , "mangos"]
wow = fruits.shift
end
def retrieve_element_from_index(array, index_number)
fruits = ["orange", "coconut", "am"]
fruits[0]
fruits[1]
fruits[2]
end
def retrieve_first_element_from_array(array)
fruits = ["wow", "coconut", "mangos"]
fruits.first
end
def retrieve_last_element_from_array(array)
fruits = ["orange", "coconut", "arrays!"]
fruits.last
end
| true |
37a73397f844df61a1ff4df5e27894fdffaad7f5 | Ruby | rerack-me/rerack.me | /test/models/group_test.rb | UTF-8 | 1,727 | 2.65625 | 3 | [] | no_license | require 'test_helper'
class GroupTest < ActiveSupport::TestCase
def setup
setup_players_and_global
end
test "add player to group by username" do
gr = FactoryGirl.create(:group)
gr.add_player_by_username(@a.username)
assert gr.players.include? @a
assert !gr.add_player_by_username(@a.username), 'added duplicate username'
assert !gr.add_player_by_username('not a username'), 'added non-existant user'
end
test "player usernames for group" do
gr = FactoryGirl.create(:group)
gr.add_player_by_username(@a.username)
gr.add_player_by_username(@b.username)
assert_equal [@a.username, @b.username], gr.player_usernames
gr.add_player_by_username("not a username")
assert_equal [@a.username, @b.username], gr.player_usernames
end
test "rankings not updated if players not in group" do
g = FactoryGirl.create(:group)
g.players << [@a, @b, @c]
g.save
assert g.players.include?(@a), 'Group does not include player.'
assert !g.players.include?(@d), "Group includes player it shouldn't"
game = Game.new
game.winners << [@a, @b]
game.losers << [@c, @d]
game.confirm
game.save!
assert @a.points_in(g) == 1000.0, 'Player group rating updated'
end
test "rankings should be updated if players in group" do
g = FactoryGirl.create(:group)
g.players << [@a, @b, @c, @d]
g.save
assert g.players.include?(@a), 'Group does not include player.'
game = Game.new
game.winners << [@a, @b]
game.losers << [@c, @d]
game.confirm
game.save!
assert @a.points_in(g) > 1000.0, 'Player group rating not improved'
assert @c.points_in(g) < 1000.0, 'Player group rating not decreased'
end
end
| true |
0f14991520be826dcb582c1ac6fce74de8154a86 | Ruby | bglusman/s10-mod | /lib/poker_help/card.rb | UTF-8 | 4,583 | 3.4375 | 3 | [] | no_license | module PokerHelp
# FORKED FROM RUBY-POKER GEM by Rob Olson
# Copyright (c) 2008, Robert Olson
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the distribution.
# * Neither the name of the author nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
class Card
SUITS = ['c', 'd', 'h', 's']
FACES = ('2' .. '9').to_a + [ 'T', 'J', 'Q', 'K', 'A' ]
DECK = SUITS.product(FACES)
def Card.face_value(face)
face.upcase!
FACES.include?(face) ? face : nil
end
private
def build_from_face_suit(face, suit)
suit.downcase!
face.upcase!
raise ArgumentError, "Invalid suit: \"#{suit}\"" unless SUITS.include?(suit)
raise ArgumentError, "Invalid face: \"#{face}\"" unless FACES.include?(face)
@suit = suit
@face = face
end
def build_from_face_suit_values(face, suit)
build_from_face_suit(FACES[face], SUITS[suit])
end
def build_from_value(value)
build_from_face_suit_values(value % FACES.size(), value / FACES.size())
end
def build_from_string(card)
build_from_face_suit(card[0,1], card[1,1])
end
# Constructs this card object from another card object
def build_from_card(card)
@suit = card.suit
@face = card.face
end
public
def initialize(*value)
if (value.size == 1)
if (value[0].respond_to?(:to_card))
build_from_card(value[0])
elsif (value[0].respond_to?(:to_str))
build_from_string(value[0])
elsif (value[0].respond_to?(:to_int))
build_from_value(value[0])
end
elsif (value.size == 2)
if (value[0].respond_to?(:to_str) &&
value[1].respond_to?(:to_str))
build_from_face_suit(value[0], value[1])
elsif (value[0].respond_to?(:to_int) &&
value[1].respond_to?(:to_int))
build_from_face_suit_values(value[0], value[1])
end
end
end
attr_reader :suit, :face
include Comparable
# Returns a string containing the representation of Card
#
# Card.new("7c").to_s # => "7c"
def to_s
@face + @suit
end
# If to_card is called on a `Card` it should return itself
def to_card
self
end
# Subtraction only makes sense when comparing face values
def - card2
# If subtracting an Ace, treat it as a low Ace
if (card2.face == 'A')
FACES.index(@face) - (-1)
else
FACES.index(@face) - FACES.index(card2.face)
end
end
# Compare the face value of this card with another card. Returns:
# -1 if self is less than card2
# 0 if self is the same face value of card2
# 1 if self is greater than card2
def <=> card2
FACES.index(@face) <=> FACES.index(card2.face)
end
# Returns true if the cards are the same card. Meaning they
# have the same suit and the same face value.
def == card2
@face == card2.face and @suit == card2.suit
end
alias :eql? :==
# Compute a hash-code for this Card. Two Cards with the same
# content will have the same hash code (and will compare using eql?).
def hash
DECK.index([@face, @suit]).hash
end
end
end
| true |
f0edae555639dc2e041bb19f055b2afdef4aef79 | Ruby | nickklesaris/propertymgt | /spec/features/add_a_building_spec.rb | UTF-8 | 1,677 | 2.6875 | 3 | [] | no_license | require 'spec_helper'
feature 'add a building', %Q{
As a real estate associate
I want to record a building
So that I can refer back to pertinent information
} do
#Acceptance Criteria:
# I must specify a street address, city, state, and postal code
# Only US states can be specified
# I can optionally specify a description of the building
# If I enter all of the required information in the required format, the building is recorded.
# If I do not specify all of the required information in the required formats, the building is not recorded and I am presented with errors
# Upon successfully creating a building, I am redirected so that I can record another building.
scenario 'create a valid building' do
prev_count = Building.count
visit 'buildings/new'
fill_in 'building_address',
with: '101 Huntington AVE'
fill_in 'building_city',
with: 'Boston'
fill_in 'building_state',
with: 'MA'
fill_in 'building_postcode',
with: '02199'
fill_in 'building_description',
with: ''
click_button 'Add Building'
expect(page).to have_content('Building created.')
expect(Building.count).to eql(prev_count +1)
end
scenario 'create an invalid building' do
prev_count = Building.count
visit 'buildings/new'
fill_in 'building_address',
with: '202 Western AVE'
fill_in 'building_city',
with: 'Boston'
fill_in 'building_state',
with: 'ZZ'
fill_in 'building_postcode',
with: '02199'
fill_in 'building_description',
with: ''
click_button 'Add Building'
expect(page).to have_content('Building not created. Check form for errors.')
expect(Building.count).to eql(prev_count)
end
end
| true |
fb19c830baf8997737b556189b6ed77651e81f4d | Ruby | Cleyrauz/Functions_Lab-1 | /ruby_functions_practice.rb | UTF-8 | 877 | 3.59375 | 4 | [] | no_license | require ( 'Date' )
def return_10
return 10
end
def add(num1,num2)
return num1+num2
end
def subtract(num1, num2)
return num1 - num2
end
def multiply(num1, num2)
return num1*num2
end
def divide(num1, num2)
return num1/num2
end
def length_of_string(string)
return string.length
end
def join_string(string1, string2)
return string1 + string2
end
def add_string_as_number(string_1, string_2)
return string_1.to_i + string_2.to_i
end
def number_to_full_month_name(month_number)
return Date::MONTHNAMES[month_number]
end
def number_to_short_month_name(month_number)
short_month_name = Date::MONTHNAMES[month_number]
return short_month_name[0..2]
end
def volume_of_cube(length)
return length**3
end
def volume_of_sphere(radius)
return radius**3 *4 / 3 *Math::PI
end
def fahrenheit_to_celsius(degrees)
return ((degrees - 32) *0.5556).round
end
| true |
085bc9ce3ff8e1feeb2ae8b5e3c9905ff5b56ae2 | Ruby | guacamobley/caesar-cipher-webapp | /caesar-cipher.rb | UTF-8 | 882 | 3.5625 | 4 | [] | no_license | CAPITAL_A = 65
CAPITAL_Z = 90
LOWERCASE_A = 97
LOWERCASE_Z = 122
def normalize_shift shift
if shift > 0
shift %= 26
else
shift *= -1
shift %= 26
shift *= -1
end
return shift
end
def shift_letter (code,shift)
if code >= CAPITAL_A && code <= CAPITAL_Z
new_code = code + shift
if new_code > CAPITAL_Z
new_code -= 26
elsif new_code < CAPITAL_A
new_code += 26
end
elsif code >= LOWERCASE_A && code <= LOWERCASE_Z
new_code = code + shift
if new_code > LOWERCASE_Z
new_code -= 26
elsif new_code < LOWERCASE_A
new_code +=26
end
else
new_code = code
end
return new_code.chr
end
def caesar_cipher (input,shift)
return input if shift == 0
normalized_shift =normalize_shift shift
output_array = input.bytes.map do |c| shift_letter c, normalized_shift end
return output_array.join ""
end | true |
34f2a22b0ca08ddf2cfe39267bb7abab46b79ca6 | Ruby | ITGGOT-Eric-Bratt/standard-biblioteket | /lib/max_of_two.rb | UTF-8 | 335 | 4 | 4 | [] | no_license | # Public: Decide the biggest of two numbers
#
# siffra1, siffra 2 - The integers being compared
#
# Examples
#
# max_of_two(1, 2)
# # => 2
#
# Returns the biggest of the two integers.
def max_of_two(siffra1, siffra2)
if siffra1 > siffra2
output = siffra1
else
output = siffra2
end
return output
end | true |
0a475998f834b9f7a07e57a6771bc501d95844f3 | Ruby | larsonkonr/sales_engine | /lib/sales_engine.rb | UTF-8 | 1,080 | 2.546875 | 3 | [] | no_license | require_relative 'repositories/merchant_repository'
require_relative 'repositories/item_repository'
require_relative 'repositories/invoice_repository'
require_relative 'repositories/invoice_item_repository'
require_relative 'repositories/customer_repository'
require_relative 'repositories/transaction_repository'
class SalesEngine
attr_reader :merchant_repository,
:invoice_repository,
:item_repository,
:invoice_item_repository,
:customer_repository,
:transaction_repository,
:filepath
def initialize(filepath)
@filepath = filepath
end
def startup
@customer_repository = CustomerRepository.new(self, filepath)
@merchant_repository = MerchantRepository.new(self, filepath)
@invoice_repository = InvoiceRepository.new(self, filepath)
@item_repository = ItemRepository.new(self, filepath)
@invoice_item_repository = InvoiceItemRepository.new(self, filepath)
@transaction_repository = TransactionRepository.new(self, filepath)
end
end
| true |
f1eee18bd7619e2b3f3a412874d3eec72893015a | Ruby | prusswan/euler-rails | /code/euler068.rb | UTF-8 | 634 | 3.09375 | 3 | [] | no_license | (1..10).to_a.permutation.each do |p|
# next unless p[0] == 9
next unless [p[2],p[4],p[6],p[8]].include? 10
# numerically lowest external node
next if p[0] > p[2]
next if p[0] > p[4]
next if p[0] > p[6]
next if p[0] > p[8]
s1 = p[0] + p[1] + p[3]
s2 = p[2] + p[3] + p[5]
next if s2 != s1
s3 = p[4] + p[5] + p[7]
next if s3 != s2
s4 = p[6] + p[7] + p[9]
next if s4 != s3
s5 = p[8] + p[9] + p[1]
next if s5 != s4
s = "#{p[0]}#{p[1]}#{p[3]}#{p[2]}#{p[3]}#{p[5]}" +
"#{p[4]}#{p[5]}#{p[7]}#{p[6]}#{p[7]}#{p[9]}" +
"#{p[8]}#{p[9]}#{p[1]}"
puts s
# puts "#{s1} #{s2} #{s3} #{s4} #{s5}"
end
| true |
d678b0611ae180f19dbcc2469a8a9b07ca7083f2 | Ruby | james-cape/sweater_weather | /spec/models/forecast_spec.rb | UTF-8 | 980 | 2.578125 | 3 | [] | no_license | require 'rails_helper'
describe Forecast do
it 'has attributes' do
dark_sky_forecast = File.read('./spec/fixtures/dark_sky_response.rb')
response = Forecast.new(dark_sky_forecast, 'denver,co', 'United States')
expect(response.citystate).to eq('denver,co')
expect(response.country).to eq('United States')
expect(response.forecast).to eq(dark_sky_forecast)
end
#
it 'generates risk profiles based on uv_index' do
forecast = Forecast.new("1", "2", "3")
expect(forecast.uv_risk(0)).to eq('Low')
expect(forecast.uv_risk(1)).to eq('Low')
expect(forecast.uv_risk(3)).to eq('Moderate')
expect(forecast.uv_risk(5)).to eq('Moderate')
expect(forecast.uv_risk(6)).to eq('High')
expect(forecast.uv_risk(7)).to eq('High')
expect(forecast.uv_risk(8)).to eq('Very High')
expect(forecast.uv_risk(10)).to eq('Very High')
expect(forecast.uv_risk(11)).to eq('Extreme')
expect(forecast.uv_risk(13)).to eq('Extreme')
end
end
| true |
76ea148b2cad760ae9290761f75825281b96bbf5 | Ruby | shoyan/git_find_committer | /lib/git_find_committer/filter.rb | UTF-8 | 328 | 2.625 | 3 | [
"MIT"
] | permissive | module GitFindCommitter
class Filter
def initialize(config)
@config = config
end
def select_committer(committer)
unless @config.available_committer_names.nil?
committer.select {|c| @config.available_committer_names.include?(c[:name]) }
else
committer
end
end
end
end
| true |
0f07b218357f1764a62caf5a13a0540ac0ba71a0 | Ruby | ankane/barkick | /test/barkick_test.rb | UTF-8 | 1,261 | 2.515625 | 3 | [
"MIT"
] | permissive | require_relative "test_helper"
class BarkickTest < Minitest::Test
def test_gtin
gtin = Barkick::GTIN.new("016000275263")
assert gtin.valid?
assert_equal "00016000275263", gtin.gtin14
assert_equal "0016000275263", gtin.gtin13
assert_equal "016000275263", gtin.gtin12
assert_equal "0016000275263", gtin.ean13
assert_equal "016000275263", gtin.upc
assert_equal "001", gtin.prefix
assert_equal "GS1 US", gtin.prefix_name
end
def test_invalid
assert !Barkick::GTIN.new("1").valid?
assert !Barkick::GTIN.new(" 016000275263").valid?
end
def test_variable
gtin = Barkick::GTIN.new("299265108631")
assert gtin.valid?
assert gtin.variable?
assert gtin.restricted?
assert_equal 8.63, gtin.price
assert_equal "00299265000003", gtin.base_gtin14
assert Barkick::GTIN.new(gtin.base_gtin14).valid?
end
def test_no_type
assert_raises(ArgumentError) do
Barkick::GTIN.new("03744806")
end
end
def test_upc_e
gtin = Barkick::GTIN.new("03744806", type: :upc_e)
assert gtin.valid?
assert_equal "00037000004486", gtin.base_gtin14
end
def test_ean8
gtin = Barkick::GTIN.new("00511292", type: :ean8)
assert_equal "00000000511292", gtin.gtin14
end
end
| true |
5a3f053e02ba41bf8ff10b1c905a380ff018ca80 | Ruby | 00mjk/dnsdiff | /lib/dnsdiff/query.rb | UTF-8 | 1,371 | 2.875 | 3 | [] | no_license | require 'dnsruby'
require 'colorize'
require_relative './logging'
module DNSDiff
class Query
include Logging
attr_accessor :record, :type
def initialize(opts)
@record = opts[:record]
@type = opts[:type]
end
def colors
{ :Pass => :green, :Fail => :red }
end
def responses_equal?
@responses.all? { |x| x == @responses[0] }
end
def print_response
@result = self.responses_equal? ? :Pass : :Fail
print "QUERY: #{@record.upcase} #{@type.upcase}\n"
print "STATUS: #{@result}\n".colorize(colors[@result])
@responses.each do |response|
print " "
print "#{response.short_answer}"
print "\n"
end
print "==========================================\n"
self
end
# execute requires an associated resolver so we're not constantly
# opening and closing dns connections.
def execute(resolvers)
@responses = []
resolvers.each do |name, resolver|
response = Response.new(:name => name)
begin
message = resolver.query(@record, Dnsruby::Types.send(@type))
response.parse_message(message)
rescue Dnsruby::NXDomain
response.answertext = "NXDOMAIN"
end
@responses << response
end
end
def to_s
# something clever here
end
end
end
| true |
6893f6300624b02b3a7e0ec60ba4a0a7771be138 | Ruby | eoogbe/todo-sinatra | /spec/support/object_mother.rb | UTF-8 | 686 | 2.859375 | 3 | [] | no_license | module ObjectMother
def new_item attrs = {}
text = attrs[:text] || 'The text'
user = attrs[:user] || create_user
Item.new text: text, user: user
end
def create_item attrs = {}
create_model new_item(attrs), ItemMapper
end
def new_user attrs = {}
email = attrs[:email] || "user#{new_user_counter}@example.com"
password = attrs[:password] || "foobarfoobar"
User.new email: email, password: password
end
def create_user attrs = {}
create_model new_user(attrs), UserMapper
end
private
def create_model model, mapper
mapper.insert model
model
end
def new_user_counter
@new_user_counter ||= 0
@new_user_counter += 1
end
end
| true |
a9a4158134ba0dc910b6096e92e5d8c03c5bc616 | Ruby | moosan63/my-scheme-in-ruby | /lib/my-scheme-in-ruby/expression.rb | UTF-8 | 1,056 | 2.96875 | 3 | [] | no_license | module MySchemeInRuby
class Expression
attr_reader :value
def initialize(expression)
@value = expression
end
def cons(a, b)
end
def car
if self.is_list?
Expression.new(@value[0])
else
self
end
end
def cdr
if self.is_list?
Expression.new(@value[1..-1])
else
self
end
end
def return_list(*list)
Expression.new(list)
end
## bools
def is_list?
@value.is_a?(Array)
end
def is_immediate_val?
is_num?
end
def is_special_form?
self.is_lambda? or
self.is_let? or
self.is_letrec? or
self.is_if?
end
def is_primitive_fun?
@value[0] == :prim
end
def is_lambda?
@value[0] == :lambda
end
def is_laterc?
@value[0] == :letrec
end
def is_let?
@value[0] == :let
end
def is_if?
@value[0] == :if
end
private
def is_num?
@value.is_a?(Numeric)
end
end
end
| true |
0af64cfa6cfbb4d591af894dd255479b92f65e64 | Ruby | goeunpark/string_reverse | /lib/string_reverse.rb | UTF-8 | 400 | 3.96875 | 4 | [] | no_license | # A method to reverse a string in place.
def string_reverse(my_string)
if my_string == [] || my_string == nil
return my_string
end
my_string.chars
length = my_string.length
low = 0
high = length-1
while low < high
x = my_string[low]
my_string[low] = my_string[high]
my_string[high] = x
low += 1
high -= 1
end
return my_string
end
| true |
7868209d9f8d499fd3637469336fbebf2bed5150 | Ruby | topickering/chitter-challenge | /spec/peep_spec.rb | UTF-8 | 532 | 2.515625 | 3 | [] | no_license | require 'peep'
describe Peep do
describe '#all' do
it 'returns all bookmarks' do
connection = PG.connect(dbname: 'chitter_test')
connection.exec("INSERT INTO peeps (text) VALUES('this is a test') RETURNING id, text;")
connection.exec("INSERT INTO peeps (text) VALUES('this is also a test') RETURNING id, text;")
peeps = Peep.all
expect(peeps.first).to be_a Peep
expect(peeps.first.text).to eq 'this is a test'
expect(peeps.last.text).to eq 'this is also a test'
end
end
end
| true |
c4f1e7e8c7a118f51abfa9c075c98feb5391febe | Ruby | toshimaru/ProjectEuler | /002/problem2.rb | UTF-8 | 366 | 3.75 | 4 | [] | no_license | def fibo(n)
a, b = 1, 2
while a < n do
yield a
a, b = b, a + b
end
end
sum = 0
fibo(4000000) {|f|
if f % 2 == 0
sum += f
end
}
puts "answer: " + sum.to_s
=begin
sum = 2
a = 1
b = 2
c = 0
while c < 4000000
c = a + b
a = b
b = c
if c % 2 == 0
sum += c
end
end
puts 'answer:' + sum.to_s
=end
| true |
ea984c0e1dbb02ae6f88cc15a5b2505c253074a5 | Ruby | apetlock/parchment | /lib/parchment/formats/txt/document.rb | UTF-8 | 753 | 2.890625 | 3 | [
"MIT"
] | permissive | require 'parchment/document'
require_relative 'paragraph'
require_relative 'style'
module Parchment
module TXT
class Document < Parchment::Document
def initialize(file)
@text = file
@styles = []
set_paragraphs
end
private
# These methods parse and add the Document's children and defaults.
#
def set_paragraphs
set_default_paragraph_style
# double quotes matter here
@paragraphs = @text.gsub("\r", '').split("\n").map { |line| Parchment::TXT::Paragraph.new(line, self) }
end
def set_default_paragraph_style
@default_paragraph_style = Parchment::TXT::Style.new
end
end
end
end
| true |
c8c9fd1fdb8928e6e3b04fd28d61ad737a7b393d | Ruby | mainglis/haley_house | /ruby_scripts/data_clean_up_script.rb | UTF-8 | 9,217 | 3.171875 | 3 | [] | no_license | #in Terminal: cd Dropbox/Database\ Files/Shared\ Database\ Files/Overall\ Files/
#in Terminal: irb
#must require csv
require 'csv'
#must define people variable, even though empty
people = []
#Creates a ruby file out of the existing csv file, right?
CSV.open('mailingList.csv', 'r', ?,, ?\r) { |row| people << row }
#can define CSV.open as a variable "x" if you want it to be easier to use x.count or x.each?
x=CSV.open('mailingList.csv', 'r', ?,, ?\r)
#___________________________________________________________________________________________
#
Creates a ruby file out of the existing csv file, right?
CSV.open('newList21.csv', 'r', ?,, ?\r) { |row| people << row }
#can define CSV.open as a variable "x" if you want it to be easier to use x.count or x.each?
x=CSV.open('newList21.csv', 'r', ?,, ?\r)
#___________________________________________________________________________________________
#
#Defining our people dictionary
people_dict = []
header = people.first
people.each do |row|
person = {}
i = 0
row.each do |col|
person[header[i]] = row[i]
i += 1
end
people_dict << person
end
#___________________________________________________________________________________________
#
#take out the first row of people (the header row) before you clean it up
header = people.first
people.delete(header)
#___________________________________________________________________________________________
#
#Original, which works: Skipping over the duplicate addresses
people_cleaned_up = {}
duplicates = []
people_dict.each do |person|
k = person["Street Address Proper"] #make this the address
v = person #make this be everything else
next if k.nil?
k.gsub!(/St\.?$/, 'Street')
k.gsub!(/Ave\.?$/, 'Avenue')
k.gsub!(/Ct\.?$/, 'Court')
k.gsub!(/Pl\.?$/, 'Place')
k.gsub!(/Terr\.?$/, 'Terrace')
k.gsub!(/W\.?$/, 'West')
k.gsub!(/E\.?$/, 'East')
k.gsub!(/Dr\.?$/, 'Drive')
k.gsub!(/Ln\.?$/, 'Lane')
k.gsub!(/Sq\.?$/, 'Square')
#look for existing entries, if the same you won't put them in the dictionary.
unless people_cleaned_up.keys.include?(k)
people_cleaned_up[k] = v
else
duplicates << v
end
end
#1. Didn't like the 11 arguments/parameters for v
people_cleaned_up = {}
duplicates = []
people_dict.each do |person|
k = person["Street Address Proper"] #make this the address
v = person["First Name", "Last Name", "Address 2", "Organization", "City Proper", "State", "Type of Person", "HH reference", "Update Options", "Volunteer","Volunteer Interest"]
next if k.nil?
k.gsub!(/St\.?$/, 'Street')
k.gsub!(/Ave\.?$/, 'Avenue')
k.gsub!(/Ct\.?$/, 'Court')
k.gsub!(/Pl\.?$/, 'Place')
k.gsub!(/Terr\.?$/, 'Terrace')
k.gsub!(/W\.?$/, 'West')
k.gsub!(/E\.?$/, 'East')
k.gsub!(/Dr\.?$/, 'Drive')
k.gsub!(/Ln\.?$/, 'Lane')
k.gsub!(/Sq\.?$/, 'Square')
#look for existing entries, if the same you won't put them in the dictionary.
unless people_cleaned_up.keys.include?(k)
people_cleaned_up[k] = v
else
duplicates << v
end
end
#Only resulted in the k and v values
people_cleaned_up = {}
duplicates = []
people_dict.each do |person|
k = person["Street Address Proper"] #make this the address
v = person["First Name"]
a = person["Last Name"]
b = person["Address 2"]
c = person["Organization"]
d = person["City Proper"]
e = person["State"]
f = person["Type of Person"]
g = person["HH reference"]
h = person["Update Options"]
i = person["Volunteer"]
j = person["Volunteer Interest"]
next if k.nil?
k.gsub!(/St\.?$/, 'Street')
k.gsub!(/Ave\.?$/, 'Avenue')
k.gsub!(/Ct\.?$/, 'Court')
k.gsub!(/Pl\.?$/, 'Place')
k.gsub!(/Terr\.?$/, 'Terrace')
k.gsub!(/W\.?$/, 'West')
k.gsub!(/E\.?$/, 'East')
k.gsub!(/Dr\.?$/, 'Drive')
k.gsub!(/Ln\.?$/, 'Lane')
k.gsub!(/Sq\.?$/, 'Square')
#look for existing entries, if the same you won't put them in the dictionary.
unless people_cleaned_up.keys.include?(k)
people_cleaned_up[k] = v
else
duplicates << v
end
end
#Only resulted in the k value and the last v value
people_cleaned_up = {}
duplicates = []
people_dict.each do |person|
k = person["Street Address Proper"] #make this the address
v = person["First Name"]
v = person["Last Name"]
v = person["Address 2"]
v = person["Organization"]
v = person["City Proper"]
v = person["State"]
v = person["Type of Person"]
v = person["HH reference"]
v = person["Update Options"]
v = person["Volunteer"]
v = person["Volunteer Interest"]
next if k.nil?
k.gsub!(/St\.?$/, 'Street')
k.gsub!(/Ave\.?$/, 'Avenue')
k.gsub!(/Ct\.?$/, 'Court')
k.gsub!(/Pl\.?$/, 'Place')
k.gsub!(/Terr\.?$/, 'Terrace')
k.gsub!(/W\.?$/, 'West')
k.gsub!(/E\.?$/, 'East')
k.gsub!(/Dr\.?$/, 'Drive')
k.gsub!(/Ln\.?$/, 'Lane')
k.gsub!(/Sq\.?$/, 'Square')
#look for existing entries, if the same you won't put them in the dictionary.
unless people_cleaned_up.keys.include?(k)
people_cleaned_up[k] = v
else
duplicates << v
end
end
#Only resulted in the k and v values
people_cleaned_up = {}
duplicates = []
people_dict.each do |person|
k = person["Street Address Proper"] #make this the address
v = person["First Name"]
a = person["Last Name"]
b = person["Address 2"]
c = person["Organization"]
d = person["City Proper"]
e = person["State"]
f = person["Type of Person"]
g = person["HH reference"]
h = person["Update Options"]
i = person["Volunteer"]
j = person["Volunteer Interest"]
next if k.nil?
k.gsub!(/St\.?$/, 'Street')
k.gsub!(/Ave\.?$/, 'Avenue')
k.gsub!(/Ct\.?$/, 'Court')
k.gsub!(/Pl\.?$/, 'Place')
k.gsub!(/Terr\.?$/, 'Terrace')
k.gsub!(/W\.?$/, 'West')
k.gsub!(/E\.?$/, 'East')
k.gsub!(/Dr\.?$/, 'Drive')
k.gsub!(/Ln\.?$/, 'Lane')
k.gsub!(/Sq\.?$/, 'Square')
#look for existing entries, if the same you won't put them in the dictionary.
unless people_cleaned_up.keys.include?(k)
people_cleaned_up[k] = v, a, b, c, d, e, f, g, h, i, j
else
duplicates << v, a, b, c, d, e, f, g, h, i, j
end
end
#TRY THIS NEW ONE Skipping over the duplicate addresses - only took the k and v values
people_cleaned_up = {}
duplicates = []
people_dict.each do |person|
k = person["Street Address Proper"] #make this the address
v = person["First Name"]
v = person["Last Name"]
v = person["Address 2"]
v = person["Organization"]
v = person["City Proper"]
v = person["State"]
v = person["Type of Person"]
v = person["HH reference"]
v = person["Update Options"]
v = person["Volunteer"]
v = person["Volunteer Interest"]
next if k.nil?
k.gsub!(/St\.?$/, 'Street')
k.gsub!(/Ave\.?$/, 'Avenue')
k.gsub!(/Ct\.?$/, 'Court')
k.gsub!(/Pl\.?$/, 'Place')
k.gsub!(/Terr\.?$/, 'Terrace')
k.gsub!(/W\.?$/, 'West')
k.gsub!(/E\.?$/, 'East')
k.gsub!(/Dr\.?$/, 'Drive')
k.gsub!(/Ln\.?$/, 'Lane')
k.gsub!(/Sq\.?$/, 'Square')
#look for existing entries, if the same you won't put them in the dictionary.
unless people_cleaned_up.keys.include?(k)
people_cleaned_up[k] = v, a, b, c, d, e, f, g, h, i, j
else
duplicates << v, a, b, c, d, e, f, g, h, i, j
end
end
#___________________________________________________________________________________________
#
#this did not work
HEADERS = [:titles, :identifier, ...]
def end_document
# with ruby 1.8.7
File.open("mailingList.csv", "ab") do |f|
csv = CSV.generate_line(HEADERS.map { |h| @mailingList[h] })
csv << "\n"
f.write(csv)
end
end
#this worked
CSV.open("newList2.csv", "w") do |csv|
csv << ["people_cleaned_up"]
end
#To create a multi-row, multi-col. csv you'd do something like this:
CSV.open("newList2.csv", "w") do |csv|
csv << ["row1 col1", "row1 col2, etc..."]
csv << ["row2 col1", "row2 col2, etc..."]
end
#For lots of rows, you'd want to use a loop:
CSV.open("newList2.csv", "w") do |csv|
[1,2,3,4].each do |i|
csv << ["row#{i} col1", "row#{i} col2, etc..."]
end
end
#USE THIS need to figure out grabbing data from "people_cleaned_up", not just the name value
people_cleaned_up.each do |k, v|
puts k, v
end
#tried and didn't work
CSV.open("newList3.csv", "w") do |csv|
people_cleaned_up.each do |k, v|
puts k, v
end
end
#LAST USE THIS: this worked!!! after using the .each do block
CSV.open("newList11.csv", "w") do |csv|
people_cleaned_up.each do |k, v|
csv << [k, v] #this only grabbed k and then the last value of v that we listed out
end
end
#NEW and maybe working
people_cleaned_up.each do |k, v, a, b, c, d, e, f, g, h, i, j|
puts k, v, a, b, c, d, e, f, g, h, i, j
end
CSV.open("newList4.csv", "w") do |csv|
people_cleaned_up.each do |k, v, a, b, c, d, e, f, g, h, i, j|
csv << [k, v, a, b, c, d, e, f, g, h, i, j]
end
end #This only grabbed the k and the v value
| true |
e598d3618ad614f5ce44d8f127fcd779f11f4278 | Ruby | drewbee736/PA2 | /MovieTest.rb | UTF-8 | 2,261 | 3.5 | 4 | [] | no_license | class MovieTest
def initialize()
require_relative 'MovieData'
@m = MovieData.new("ml-100k", "u1");
stddev = stddev()
rmse = rms()
puts "Average Prediction Error: #{@mean}. Standard Deviation: #{stddev}. Root Mean Square Error: #{rmse}."
return to_a()
end
def mean()
@datalist = []
i = 0
prediction_error = 0
while i < @m.get_training_set().length
# gets the predicted rating for a specific movie
predicted = @m.predict(@m.get_training_set()[i], @m.get_training_set()[i+1]).to_i
# gets the rating for that specific movie
rating = @m.rating(@m.get_training_set()[i], @m.get_training_set()[i+1])
# calculates the prediction error
prediction_error = prediction_error + predicted + rating
# puts the user, movie, rating, and predicted rating into an array
@datalist.push(@m.get_training_set()[i], @m.get_training_set()[i+1], rating, predicted)
i += 4
end
# calculates the avg_prediction_error and returns it
avg_prediction_error = prediction_error / (@m.get_training_set().length / 4)
return avg_prediction_error
end
def mse()
i = 2
@mse = 0
# loops through the data and finds the difference between the rating and the predicted rating
# it will then square the difference
while i < @m.get_training_set().length
@mse += ((@m.get_training_set()[i].to_i - @m.get_training_set()[i+1].to_i)**2)
i += 4
end
# This then calculates the final mse and returns it
@mse = @mse / (@m.get_training_set().length / 4)
return @mse
end
def variance()
# calls mean() and gets the average prediction error
@mean = mean()
i = 2
@variance = 0
# gets the difference from the rating and the average error for predicted ratings
# it will then square the difference
while i < @m.get_training_set().length
@variance += ((@m.get_training_set()[i].to_i - @mean)**2)
i += 4
end
# calculates the variance and returns it
@variance = @variance / (@m.get_training_set().length / 4)
return @variance
end
def stddev()
standard_deviation = Math.sqrt(variance())
return standard_deviation
end
def rms()
root_mean_square_error = Math.sqrt(mse())
return root_mean_square_error
end
def to_a()
return @datalist
end
end
| true |
99c9f6c8dfe1044bc899dbf128ce4f45737fb94f | Ruby | NekoQ/social | /app/models/list.rb | UTF-8 | 257 | 2.609375 | 3 | [] | no_license | class List < ApplicationRecord
def add_people(array)
array.each do |name|
p = Person.find_by(name: name)
p.lists.append(self.name)
p.save
end
people.concat array
self.save
end
end
| true |
0349f8215a44f3dd9eddaa3b8caca87bfb2d2064 | Ruby | AlfredBryan/smartupapi | /app/models/assessment_result.rb | UTF-8 | 1,405 | 2.53125 | 3 | [] | no_license | class AssessmentResult < ApplicationRecord
belongs_to :assessment
belongs_to :user
STATUSES = %w(started completed)
STATUSES.each do |state|
define_method "#{state}?" do
self.status == state
end
end
GRADES = {
(0..49).to_a => "F",
(50..59).to_a => "E",
(60..69).to_a => "D",
(70..79).to_a => "C",
(80..89).to_a => "B",
(90..100).to_a => "A"
}
validates :status, presence: true, inclusion: { in: STATUSES }
def answers
user.answers.where(question_id: assessment.question_ids, assessment_id: assessment_id)
end
def questions
assessment.questions
end
def choice_score
((choice_pct.to_f/questions.choice.count)*answers.choice.passed.count).round
rescue
0
end
def choice_pct
(100 - theory_pct).abs
end
def theory_pct
answers.theory.collect(&:max_score).sum
end
def theory_score
answers.theory.sum(:score)
end
def total_score
choice_score + theory_score
end
def grade
AssessmentResult::GRADES.select { |scores, grade| scores.include?(total_score.to_i) }.values.first
end
def completed?
questions.count == answers.marked.count
end
def mark!
answers.each(&:mark!)
update_score!
complete!
end
def complete!
update_column(:status, 'completed') if completed?
end
def update_score!
update_column(:score, total_score)
end
end
| true |
52daaf64881b5ad227c0173d84af1e7d31a00781 | Ruby | neonmind/skillcrush | /rubylove.rb | UTF-8 | 116 | 3.609375 | 4 | [] | no_license | puts "Do I love you? What day is it?"
day = gets
while (day[0] != "S")
puts "Why yes, I do love you!"
break
end | true |
245b8a458c9f5e1034247f093a805bba8ec28c10 | Ruby | donatasm/saas-class | /hw1/part1/part1.rb | UTF-8 | 482 | 3.4375 | 3 | [] | no_license |
def palindrome?(string)
if string
downcaseWord = string.gsub(/\W/, "").downcase
if downcaseWord.length > 0
return downcaseWord.eql? downcaseWord.reverse
end
return false
end
end
def count_words(string)
count = {}
if string
words = string.downcase.split(/\b/)
words.each do |w|
if /\w/ =~ w
if count[w]
count[w] = count[w] + 1
else
count[w] = 1
end
end
end
end
return count
end
| true |
92c3b4d13f00e07e478399e9206091feb285ac7d | Ruby | mstanielewicz/reminders | /app/use_cases/check_assignments/create.rb | UTF-8 | 898 | 2.546875 | 3 | [
"MIT"
] | permissive | module CheckAssignments
class Create
attr_reader :checker, :assignments_repository, :project_check,
:contact_person
private :checker, :assignments_repository, :project_check,
:contact_person
def initialize(checker:, project_check:, assignments_repository: nil,
contact_person:)
@checker = checker
@project_check = project_check
@assignments_repository = assignments_repository ||
CheckAssignmentsRepository.new
@contact_person = contact_person
end
def call
create_assignment
end
private
def create_assignment
assignments_repository.add(prepare_attributes)
end
def prepare_attributes
{
user_id: checker.id,
project_check_id: project_check.id,
contact_person_id: contact_person.id,
}
end
end
end
| true |
db4eb32b115abaf507f8c1aaa38d9ce3cbeb3817 | Ruby | furuya-tomoki/stdin_sample | /gets_practice.rb | UTF-8 | 188 | 2.921875 | 3 | [] | no_license | line = gets.split(' ')
# splitメソッド = 文字列を分割して配列として格納するメソッド
# 分割するための区切り文字は第一引数に指定します
p line
| true |
a72945262e018b329729f314789c2184ebe36028 | Ruby | devlab-oy/sepa | /lib/sepa/error_messages.rb | UTF-8 | 3,390 | 2.53125 | 3 | [
"MIT"
] | permissive | module Sepa
# Contains error messages used in this gem
module ErrorMessages
# Error message which is shown when {Client#customer_id} validation fails
CUSTOMER_ID_ERROR_MESSAGE =
'Customer Id needs to be present and needs to have a length of less than 17 characters'.freeze
# Error message which is shown when {Client#environment} validation fails
ENVIRONMENT_ERROR_MESSAGE = 'Environment needs to be either production or test'.freeze
# Error message which is shown when {Client#target_id} validation fails
TARGET_ID_ERROR_MESSAGE = 'Target Id needs to be present and under 80 characters'.freeze
# Error message which is shown when {Client#file_type} validation fails
FILE_TYPE_ERROR_MESSAGE = 'File type needs to be present and under 35 characters'.freeze
# Error message which is shown when {Client#content} validation fails
CONTENT_ERROR_MESSAGE = 'Content needs to be present for this command'.freeze
# Error message which is shown when {Client#signing_csr} validation fails
SIGNING_CERT_REQUEST_ERROR_MESSAGE = 'Invalid signing certificate request'.freeze
# Error message which is shown when {Client#encryption_csr} validation fails
ENCRYPTION_CERT_REQUEST_ERROR_MESSAGE = 'Invalid encryption certificate request'.freeze
# Error message which is shown when {Client#pin} validation fails
PIN_ERROR_MESSAGE =
'Pin needs to be present for this command and cannot be more than 20 characters'.freeze
# Error message which is shown when {Client#bank_encryption_certificate} validation fails
ENCRYPTION_CERT_ERROR_MESSAGE = 'Invalid encryption certificate'.freeze
# Error message which is shown when {Client#status} validation fails
STATUS_ERROR_MESSAGE =
'Status is required for this command and must be either NEW, DOWNLOADED or ALL'.freeze
# Error message which is shown when {Client#file_reference} validation fails
FILE_REFERENCE_ERROR_MESSAGE =
'File reference is required for this command and must be under 33 characters'.freeze
# Error message which is shown when {Client#encryption_private_key} validation fails
ENCRYPTION_PRIVATE_KEY_ERROR_MESSAGE =
'Encryption private key is needed for this bank and this command'.freeze
# Error message which is shown when {Response#response_code} validation fails
NOT_OK_RESPONSE_CODE_ERROR_MESSAGE =
'The response from the bank suggested there was something wrong with your request, check ' \
'your parameters and try again'.freeze
# Error message which is shown when the response got from the bank cannot be decrypted with the
# private key that is given to the client
DECRYPTION_ERROR_MESSAGE =
'The response could not be decrypted with the private key that you gave. Check that the ' \
'key is the private key of your own encryption certificate'.freeze
# Error message which is shown when the hash embedded in the {Response} soap doesn't match the
# locally calculated one.
HASH_ERROR_MESSAGE =
'The hashes in the response did not match which means that the data in the response is not ' \
'intact'.freeze
# Error message which is shown when the signature in {Response} cannot be verified.
SIGNATURE_ERROR_MESSAGE =
'The signature in the response did not verify and the response cannot be trusted'.freeze
end
end
| true |
b8ae7bde499f6fa38f223a1bfb8791aec987e9ed | Ruby | VictorArd/Calendar_Ruby | /lib/user.rb | UTF-8 | 253 | 2.703125 | 3 | [] | no_license | require "pry"
require "rb-readline"
class User
attr_accessor :email, :name
@@all_users = []
def initialize(email_to_save)
@email = email_to_save
@@all_users << self
end
def self.all
return @@all_users
end
end
#binding.pry
| true |
9b0152312e628646b38483cb79609de3a1e6a485 | Ruby | DaveWexler/todo-ruby-basics-001-prework-web | /lib/ruby_basics.rb | UTF-8 | 312 | 3.40625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def division(num1, num2)
total = num1 / num2
total
end
def assign_variable(value)
name = value
end
def argue(argument)
argument
end
def greeting(one, two)
end
def return_a_value
return "Nice"
end
def last_evaluated_value
return "expert"
end
def pizza_party(topping = "cheese")
topping
end
| true |
f420ff4a58078bd8014f7c2dcdf6e5d4f7872e24 | Ruby | bilfar/oyster_card | /lib/station.rb | UTF-8 | 214 | 3.078125 | 3 | [] | no_license | class Station
attr_reader :name, :zone
def initialize(station)
@name = station[:station_name]
@zone = station[:zone]
end
def station_zone
@zone
end
def station_name
@name
end
end
| true |
cfd0b7e0633f3dad16d1cbc48b4862b1f8b532bf | Ruby | wwchen/FootTraffic | /app/jobs/yelp_search_job.rb | UTF-8 | 897 | 2.625 | 3 | [] | no_license | require 'yelp_request'
class YelpSearchJob < Struct.new(:location_id)
def perform
puts "[ YelpSearchJob ] (#{location_id}) Starting..."
loc = Location.find_by_id(location_id)
# Normally I'd split the search and the details requests
# into two separate jobs, but in this case we don't have to.
# After all, we're mimicing the behavior of a real user.
url = YelpRequest.search(location_id)
if url
data = YelpRequest.details(url)
# Add the data to our Location model
# The focus of Yelp data is adding extra metadata to
# improve our results from Solr
loc.tag_list << data[:cats]
loc.tag_list << data[:ngrams]
loc.save!
end
end
#def error(job, exception)
# logger.error(job)
# logger.error(exception)
#end
#def failure
# logger.fatal('[ YelpSearchJob ] Something terrible has happened...')
#end
end
| true |
40571be2a61f14ba9ac1a9d1d57d9edfbc83a590 | Ruby | enspirit/bmg | /lib/bmg/summarizer/percentile.rb | UTF-8 | 1,940 | 3.15625 | 3 | [
"MIT"
] | permissive | module Bmg
class Summarizer
#
# Percentile summarizer.
#
# Example:
#
# # direct ruby usage
# Bmg::Summarizer.percentile(:qty, 50).summarize(...)
#
class Percentile < Summarizer
DEFAULT_OPTIONS = {
:variant => :continuous
}
def initialize(*args, &bl)
@nth = args.find{|a| a.is_a?(Integer) } || 50
functor = args.find{|a| a.is_a?(Symbol) } || bl
options = args.select{|a| a.is_a?(Hash) }.inject(DEFAULT_OPTIONS){|memo,opts|
memo.merge(opts)
}.dup
super(functor, options)
end
# Returns [] as least value.
def least()
[]
end
# Collects the value
def _happens(memo, val)
memo << val
end
# Finalizes the computation.
def finalize(memo)
return nil if memo.empty?
index = memo.size.to_f * (@nth.to_f / 100.0)
floor, ceil = index.floor, index.ceil
ceil +=1 if floor == ceil
below = [floor - 1, 0].max
above = [[ceil - 1, memo.size - 1].min, 0].max
sorted = memo.sort
if options[:variant] == :continuous
(sorted[above] + sorted[below]) / 2.0
else
sorted[below]
end
end
end # class Avg
def self.percentile(*args, &bl)
Percentile.new(*args, &bl)
end
def self.percentile_cont(*args, &bl)
Percentile.new(*(args + [{:variant => :continuous}]), &bl)
end
def self.percentile_disc(*args, &bl)
Percentile.new(*(args + [{:variant => :discrete}]), &bl)
end
def self.median(*args, &bl)
Percentile.new(*(args + [50]), &bl)
end
def self.median_cont(*args, &bl)
Percentile.new(*(args + [50, {:variant => :continuous}]), &bl)
end
def self.median_disc(*args, &bl)
Percentile.new(*(args + [50, {:variant => :discrete}]), &bl)
end
end # class Summarizer
end # module Bmg
| true |
949a012b81f63edd25fa6b51c467a1d72d51dc1a | Ruby | supremebeing7/ruby_dictionary | /spec/word_spec.rb | UTF-8 | 2,691 | 3.171875 | 3 | [] | no_license | require 'rspec'
require 'word'
describe Word do
before do
Word.clear
end
it 'initializes an instance of the word class' do
test_word = Word.new('boat',"English")
test_word.should be_an_instance_of Word
end
it 'initializes with a language' do
test_word = Word.new("boat", "English")
test_word.language.should eq "English"
end
describe ".create" do
it "creates an instance of the Word Class" do
test_word = Word.create("boat", "English")
test_word.word.should eq "boat"
test_word.language.should eq "English"
end
it "saves the word instance into the words array" do
test_word = Word.create("boat", "English")
Word.all.should eq [test_word]
end
end
describe ".all" do
it "starts with an empty array" do
Word.all.should eq []
end
it "contains all word instances" do
test_word1 = Word.create("boat", "English")
test_word2 = Word.create("casa", "Spanish")
Word.all.should eq [test_word1, test_word2]
end
end
describe ".clear" do
it "clears the all_words array" do
Word.clear.should eq []
end
end
describe '#edit_word' do
it 'edits a terms word' do
test_word = Word.create("ZZebra", "english")
test_term = Term.create(test_word, "A striped horse")
test_term.word.edit_word("Zebra")
test_term.word.word.should eq "Zebra"
end
it 'edits a terms word anywhere inside the all_terms array' do
test_word1 = Word.create("ZZebra", "english")
test_term1 = Term.create(test_word1, "A striped horse")
test_word2 = Word.create("DDoe", "english")
test_term2 = Term.create(test_word2, "deer")
test_term2.word.edit_word("Doe")
test_term2.word.word.should eq "Doe"
end
# NEED TO FIX ADD WORD FIRST
# it 'edits any word in a term' do
# test_word1 = Word.create("ZZebra", "english")
# test_term1 = Term.create(test_word1, "A striped horse")
# test_term1.word.edit_word("Zebra")
# test_term1.word.word.should eq "Zebra"
# end
end
# describe "add_words" do
# it "should add a new word object to the existing all_words array" do
# test_word1 = Word.create("zebra", "english")
# test_term = Term.create(test_word1, "a striped horse")
# test_term.edit_word("cebra", "Spanish")
# test_term.word.should eq (test_word1, test_word2)
# end
# end
# describe "#find_word_index" do
# it "will find the index of the word array" do
# test_term = Term.create("Zebra", "A striped horse")
# # test_term.multi_words('Black n white horse')
# test_term.find_word_index('Zebra', 0).should eq 0
# end
# end
end
| true |
1611bbf541d250a12434ece80e992ea71cf68e60 | Ruby | kdonovan/bizsearch | /lib/repayment_projection.rb | UTF-8 | 2,933 | 2.953125 | 3 | [] | no_license | class RepaymentProjection
attr_reader :listing, :kali, :ruth, :sba, :sources
def initialize(listing)
@listing = listing
@sources = [
@kali = MoneySource.new(max: 20_000, rate: 0.01, years: 5, price: listing.price),
@ruth = MoneySource.new(max: 300_000, rate: 0.03, years: 5, price: listing.price - kali.amount_covering),
@sba = SBAMoneySource.new(owner_contributions: @kali.max + @ruth.max, rate: 0.06, years: 10, price: listing.price - kali.amount_covering - ruth.amount_covering),
]
end
def monthly
sources.sum(&:monthly)
end
def yearly
sources.sum(&:yearly)
end
def loan_cost
sources.sum(&:loan_cost)
end
def cashflow_after_repayment
return unless listing.cashflow && listing.price < sources.sum(&:max)
listing.cashflow - yearly
end
def cashflow_post_tax_and_repayment
return unless listing.cashflow && listing.price < sources.sum(&:max)
((1 - tax_rate) * listing.cashflow) - yearly
end
def tax_rate
base = 0.33
# ROUGH ESTIMATES! http://www.money-zine.com/financial-planning/tax-shelter/state-income-tax-rates/
state = case listing&.state
when %w(AK FL NV SD TX WA WY) then 0
when 'CA' then 0.10
when 'OR' then 0.09
when 'HI' then 0.08
when 'CO' then 0.047
else 0.08 # rough guess for the others
end
base + state
end
end
module ProjectionCalculations
def monthly_payment(principal, years, annual_rate)
rate_per_period = annual_rate / 12.0
number_of_periods = years * 12
denom = ((1 + rate_per_period) ** number_of_periods) - 1
exact = principal * (rate_per_period + (rate_per_period / denom))
exact.ceil
end
end
class MoneySource
include ProjectionCalculations
attr_reader :max, :rate, :years, :price
# rate = annual percentage rate (e.g. 0.05 = 5% per year)
def initialize(price:, max: nil, rate:, years:)
@price, @rate, @years, @max = [price, rate, years, max]
end
def amount_covering
max ? [max, price].min : price
end
def monthly
monthly_payment(amount_covering, years, rate)
end
def yearly
monthly * 12
end
def loan_cost
(yearly * years) - amount_covering
end
end
class SBAMoneySource < MoneySource
attr_accessor :owner_contributions
def initialize(price:, rate:, years:, owner_contributions:, max: nil)
@owner_contributions = owner_contributions
super(price: price, rate: rate, years: years, max: max)
end
# SBA loan maxes out at 5k, and will require 10-25% owner downpayment.
# I find 25 with less experience, but may be able to do small seller note
# to count for some (only if it's held in abeyance until the SBA is paid off),
# so using 20% here for projections (Kali can probably go closer to 15 for some web,
# but don't want to rely on convincing them of that when running the numbers).
def max
[5_000_000, owner_contributions * 0.2].min
end
end | true |
9eb22bc3a3a1b271223692754850b5471a960b94 | Ruby | bfontaine/BUP7_API | /search.rb | UTF-8 | 3,199 | 2.546875 | 3 | [] | no_license | #! /usr/bin/ruby1.9.1
# -*- coding: UTF-8 -*-
require 'uri'
require 'yaml'
require 'net/http'
require 'nokogiri'
CONFIG = begin
YAML.load(File.read('config.yaml'))
rescue Errno::ENOENT
{}
end
require_relative './query'
class BUP7
class Book
def initialize(d)
@attrs = {}
self.set(d)
end
def set(k, v=nil)
if (k.is_a? Hash)
@attrs.update(k)
else
@attrs[k] = v
end
end
def to_hash
@attrs
end
def to_s
@attrs.inspect
#@attrs['title']
end
end
class SearchResult #FIXME parsing methods
@@Res_nb_regex = /Notices?\s(\d+)\s+sur\s+(\d+)/i
@@No_result_regex = /<h\d>Aucun r.sultat trouv.<h\d>/i
def initialize(http_resp)
@html = http_resp.body
@noko = Nokogiri::HTML(@html)
end
def parse()
return [] if !@@No_result_regex.match(@html).nil?
res_nb, res_total = @@Res_nb_regex.match(@html).captures.map(&:to_i)
return [_parse_one_book(@noko.css('.outertable')[0])] if res_nb == 1
# TODO multiple books
end
def to_html
@html
end
def to_nokogiri
@noko
end
private
def _translate_labels(attrs)
attrs2 = {}
# labels:
# keys: good labels
# values: parsed labels
c_pars_keys = CONFIG[:parsing].keys
c_pars_values = CONFIG[:parsing].values
c_pars_values.push(nil)
attrs.map do |k,v|
attrs2[c_pars_values[c_pars_keys.index(k) || -1]] = v
end
attrs2
end
def _parse_book_from_trs(trs)
nodes_attrs = {}
trs.map do |n|
lab, val = n.children # only 2 nodes
lab = lab.children[0].to_s.strip
val = val.children[0].to_s.strip
nodes_attrs[lab] ||=[]
nodes_attrs[lab].push(val)
end
Book.new(_translate_labels(nodes_attrs))
end
def _parse_one_book(noko_el)
return nil if noko_el.nil?
trs = noko_el.css('tr')
# keep only usefull information
trs.shift
trs.shift
trs.pop
_parse_book_from_trs(trs)
end
end
class SearchEngine
def SearchEngine::query(q)
uri = URI(CONFIG[:url] + q)
headers = CONFIG[:headers]
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Get.new(uri.request_uri)
headers.each do |k,v|
req.add_field(k.to_s, v.to_s)
end
resp = http.start do |h|
h.request(req)
end
SearchResult.new(resp)
end
end
class SearchQuery
def send()
SearchEngine::query(self.to_url)
end
end
end
# TODO
#
# add headers, like Referer, User-Agent, etc
#
| true |
edb5b98d0610b3063affa94b99a65da3afc5070f | Ruby | cernanb/blog_cli | /lib/blog_cli/cli.rb | UTF-8 | 723 | 3.46875 | 3 | [
"MIT"
] | permissive | class BlogCLI::CLI
attr_reader :last_input
def call
puts "Welcome to your CLI Blog!"
menu
end
def menu
puts "What would you like to do?"
puts "1. Write a post"
main_menu_loop
end
def main_menu_loop
while user_input != "exit"
case last_input.to_i
when 1
post_new
else
menu
break
end
end
end
def post_new
params = {}
puts "Please enter the title of your new post:"
params[:title] = user_input
puts "Please enter the content of your new post:"
params[:content] = user_input
post = BlogCLI::Post.new(params)
post.save
end
private
def user_input
@last_input = gets.strip
end
end
| true |
51e434b3f4976f5ee7e6d4dc41edb3e5a9bfa483 | Ruby | haracane/kajax | /lib/hash_extensions.rb | UTF-8 | 795 | 2.859375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | module HashExtensions
module Hash
module MultiDimensionAccess
def fetch_with_keys(key_list)
ret = self
key_list.each do |key|
ret = ret[key]
return nil if ret == nil
end
return ret
end
def store_with_keys(key_list, val)
last_index = key_list.size - 1
target_hash = self
key_list.each_index do |i|
key = key_list[i]
if i == last_index then
target_hash[key] = val
else
target_hash = (target_hash[key] ||= {})
end
end
# puts "store [#{key_list.join(', ')}], #{self.fetch_with_keys key_list}"
return val
end
end
end
end
class Hash
include HashExtensions::Hash::MultiDimensionAccess
end
| true |
7a3eb42ac6e9fda857f6bd91c2d7caabc312aa24 | Ruby | borovsky/project-euler | /p34.rb | UTF-8 | 210 | 3 | 3 | [] | no_license | require 'lib'
MAX = 7 * factorial(9)
r = []
FAC = (0..9).map{|i| factorial(i)}
(10..MAX).each do |i|
if i.digits.map{|d| FAC[d]}.sum == i
p i
r << i
end
puts " #{i}" if i % 100000 == 0
end
| true |
1bf8daebc4bf13be3f8b22a8a1ab6092ff049479 | Ruby | wesabe/bouncer | /tasks/deploy.rb | UTF-8 | 2,210 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | require "robot-army"
require "highline/import"
class Deploy < RobotArmy::TaskMaster
def app
return "bouncer"
end
def root
return "/opt/#{app}"
end
def deploy_path(jar_location)
return File.join(root, File.basename(jar_location))
end
def current_link
return File.join(root, "current.jar")
end
def clean_installed
installed = sudo do
Dir[File.join(root, "bouncer-*.jar")]
end - [current_filename]
cleanable = installed.sort[0..-6]
if cleanable.any?
say "Removing old installed versions: "
for filename in cleanable
puts " * #{filename}"
end
sudo do
for filename in cleanable
FileUtils.rm(filename)
end
end
else
say "No cleanable versions installed."
end
end
def print_installed_versions
say "Installed versions:"
current_version = convert_to_version(current_filename)
versions = remote do
%x{ ls #{root}/bouncer-*.jar }
end.split("\n")
versions.each do |filename|
version = convert_to_version(filename)
if current_version == version
puts " #{HighLine.new.color("*", :bold)} #{HighLine.new.color(version, :underline, :bold)}"
else
puts " #{version}"
end
end
end
def convert_to_version(filename)
filename =~ /bouncer-(.*)\.jar/
return $1
end
def current_filename
remote do
File.readlink(current_link)
end
rescue
raise "expected #{current_link} to point to a file, but it didn't -- wtf"
end
def stage(jar_location)
say "Staging #{app} into #{root} (takes about two minutes)"
cptemp(jar_location, :user => :bouncer) do |path|
FileUtils.cp(path, root)
path
end
end
def install(jar_location)
say "Installing new #{app} into #{current_link}"
sudo do
FileUtils.rm_f(current_link)
FileUtils.ln_sf(deploy_path(jar_location), current_link)
end
end
def restart
say "Restarting #{app} (takes less than a minute)"
sudo do
%x{ /etc/init.d/#{app} restart }
end
end
def run(jar_location)
stage(jar_location)
install(jar_location)
restart
end
end
| true |
b96168b7028cbc965e1ff446c5c0f1a78f646e2d | Ruby | lukehaines2/HW_wk5d3_PROTEIN | /app.rb | UTF-8 | 1,203 | 2.671875 | 3 | [] | no_license | class Powder < Sinatra::Base
# General route actions
get '/' do
erb :home
end
get '/about' do
erb :about
end
# RESTful Protein Controller Actions
# index
get '/proteins' do
@proteins = Protein.all
erb(:"proteins/index")
end
# new
get '/proteins/new' do
@proteins = Protein.new
erb(:"proteins/new")
end
# create
post '/proteins' do
@protein = Protein.new(params[:protein])
if @protein.save
redirect("/proteins/#{@protein.id}")
else
erb(:"proteins/new")
end
end
# show
get '/proteins/:id' do
@protein = Protein.find(params[:id])
erb(:"proteins/show")
end
# edit
get '/proteins/:id/edit' do
@protein = Protein.find(params[:id])
erb(:"proteins/edit")
end
# update
post '/proteins/:id' do
@protein = Protein.find(params[:id])
if @protein.update_attributes(params[:protein])
redirect("/proteins/#{@protein.id}")
else
erb(:"proteins/edit")
end
end
# delete
post '/proteins/:id/delete' do
@protein = Protein.find(params[:id])
if @protein.destroy
redirect('/proteins')
else
redirect("/proteins/#{@protein.id}")
end
end
end
| true |
7f2f73d20bc49f37f5c05d2bb4386fbdbf869647 | Ruby | rcallen89/battleship | /lib/print.rb | UTF-8 | 1,655 | 3.328125 | 3 | [] | no_license | # A module that can be used in other classes as a way to clean up some other methods.
# :nocov:
#No coverage because console printout
module Print
def player_ship_print(ship, ship_length)
print "The #{ship} is #{ship_length} units long.\n\n"
puts "Please enter the coordinates placement (ex. A1 A2 A3): "
end
def player_invalid_coords_prompt(ship, user_coords)
print "Your placement for #{ship} at #{user_coords} was invalid.\n"
print "Please enter new valid coordinates (ex. A1 A2 A3): "
end
def player_placement_confirm(ship, user_coords)
print "You placed your #{ship} at #{user_coords}.\n\n"
end
def player_invalid_shot_coord
print "Please enter a valid coordinate: "
end
def menus
print "Welcome to BATTLESHIP\n".colorize(:yellow)
print "Enter " + "P".colorize(:yellow) + " to play. Enter " + "Q".colorize(:yellow)+ " to quit.\n"
user_in = gets.chomp.downcase
until user_in == "p" or user_in == "q"
print "Please input a valid selection: "
user_in = gets.chomp.strip.downcase
puts ""
end
if user_in == "p"
p "What game type would you like to play? (Game defaults to 1)"
print " 1. ".colorize(:yellow) +"Default Battleship Board (4x4)\n"
print " 2. ".colorize(:yellow) + "Custom Ships on the Big Battleship Board (9x9)\n"
game_type = gets.chomp.strip
game_type = "1" if game_type != "2"
game_setup(game_type)
elsif user_in.downcase == "q"
exit
end
end
def cpu_confirm_placement
puts "I have placed my ships on the grid"
print "You now need to lay out your two ships.\n\n"
end
end
# :nocov:
| true |
cf9ada5ab4237004b5ec4482c46c3fdbc241c6f4 | Ruby | KakinumaMiki/ruby | /Comprehension_Test/04_Hash.rb | UTF-8 | 967 | 4.15625 | 4 | [] | no_license | # 4. 配列内のハッシュ情報を表示してみよう
fruits = [
{name: "バナナ", price: 200},
{name: "リンゴ", price: 200},
{name: "イチゴ", price: 500},
{name: "オレンジ", price: 250},
{name: "モモ", price: 350}
]
# - 4-1. priceが300以上のものだけ、nameの情報を出力(puts)してみよう。
puts '4-1 300以上のnameの出力'
fruits.each do |fruit|
if fruit[:price] >= 300
puts fruit[:name]
end
end
# - 4-2. priceの合計を出力してみよう。
puts '4-2 priceの合計'
sum = 0
fruits.each do |fruit|
sum += fruit[:price]
end
puts sum
# - 4-3. nameの文字数を出力してみよう。
puts '4-3 nameの文字数'
fruits.each do |fruit|
puts "#{fruit[:name]}: #{fruit[:name].size}"
end
# - 4-4. priceの消費税を計算して出力してみよう。
puts '4-4 priceの消費税'
tax_rate = 0.10
fruits.each do |fruit|
puts "#{fruit[:price]}の消費税:#{fruit[:price] * tax_rate}"
end
| true |
ec52deba1e3ea638490da38d2fd5e088ea167942 | Ruby | joelbarton-io/rb130_139 | /exercises/regex/regex_book.rb | UTF-8 | 1,731 | 3.671875 | 4 | [] | no_license | def url?(str)
str.match(/\Ahttps?:\/\/\S+\z/) ? true : false
end
def fields(str)
str.split(/[ \t,]+/)
end
def mystery_math(str)
str.sub(/[+\-*\/]/, '?')
end
def danish(str)
str.sub(/\b(apple|cherry|blueberry)\b/, 'danish')
end
def format_date(str)
if str.match(/\A\d{4}-\d{2}-\d{2}/)
str.gsub(/(\d{4})-(\d{2})-(\d{2})/, '\3.\2.\1')
else
str
end
end
def format_date2(str)
str.gsub(/\A(\d{4})([\-\/])(\d{2})\2(\d{2})\z/, '\4.\3.\1')
end
puts "===== 1 ====="
p url?('http://launchschool.com') == true
p url?('https://example.com') == true
p url?('https://example.com hello') == false
p url?(' https://example.com') == false
puts
puts "===== 2 ====="
p fields("Pete,201,Student") == ["Pete", "201", "Student"]
p fields("Pete \t 201 , TA") == ["Pete", "201", "TA"]
p fields("Pete \t 201") == ["Pete", "201"]
p fields("Pete \n 201") == ["Pete", "\n", "201"]
puts
puts "===== 3 ====="
p mystery_math('4 + 3 - 5 = 2') == '4 ? 3 - 5 = 2'
p mystery_math('(4 * 3 + 2) / 7 - 1 = 1') == '(4 ? 3 + 2) / 7 - 1 = 1'
puts
puts "===== 4 ====="
p danish('An apple a day keeps the doctor away') == 'An danish a day keeps the doctor away'
p danish('My favorite is blueberry pie') == 'My favorite is danish pie'
p danish('The cherry of my eye') == 'The danish of my eye'
p danish('apple. cherry. blueberry.') == 'danish. cherry. blueberry.'
p danish('I love pineapple') == 'I love pineapple'
puts
puts "===== 5 ====="
p format_date('2016-06-17') == '17.06.2016'
p format_date('2016/06/17') == '2016/06/17' #(no change)
puts
puts "===== 6 ====="
p format_date2('2016-06-17') == '17.06.2016'
p format_date2('2017/05/03') == '03.05.2017'
p format_date2('2015/01-31') == '2015/01-31' #(no change)
| true |
38dd42da8bc78c0c82700698092dcd2f8ad743eb | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/saddle-points/855fd39423cf4147bf3e5c995b6a7e7f.rb | UTF-8 | 1,324 | 3.28125 | 3 | [] | no_license | class Matrix
attr_accessor :rows , :columns
def initialize(args)
self.rows = []
self.columns = []
args.split("\n").each_with_index do |row, row_i|
self.rows[row_i] = []
row.split(" ").each_with_index do |col,col_i|
self.rows[row_i] << col.to_i
if self.columns[col_i] then
self.columns[col_i] << col.to_i
else
self.columns[col_i] =[col.to_i]
end
end
end
end
def saddle_points
find_max_in_rows & find_min_in_cols # array intersect
end
def find_min_in_cols
min_col = []
self.columns.each_with_index do |c, col_i|
min = Float::INFINITY
min_index = []
c.each_with_index do |r, row_i|
if r < min then
min = r
min_index = [row_i]
elsif r == min then
min_index.push(row_i)
end
end
min_index.map { |mi| min_col.push([mi,col_i])}
end
min_col
end
def find_max_in_rows
max_rows = []
self.rows.each_with_index do |r, row_i|
max = - Float::INFINITY
max_index = nil
r.each_with_index do |c, col_i|
if c > max then
max = c
max_index = col_i
end
end
max_rows.push([row_i, max_index])
end
max_rows
end
end
| true |
1d7862546669995864544382bc139b09a18951c2 | Ruby | adamwong246/x_and_o | /spec/models/game_spec.rb | UTF-8 | 753 | 2.578125 | 3 | [] | no_license | require 'spec_helper'
describe Game do
describe "win_cat_or_else" do
it "should know a win" do
game = Game.new(board: 'xxxoxoxox')
game.win_cat_or_else.should eq({win: :x})
end
it "should know a win" do
game = Game.new(board: 'xx oooxx ')
game.win_cat_or_else.should eq({win: :o})
end
it "should know a stalemate" do
game = Game.new(board: 'xxoooxxox')
game.win_cat_or_else.should eq( :cat )
end
it "should know to continue" do
game = Game.new(board: 'x ')
game.win_cat_or_else.should eq({continue: :o})
end
it "should know to continue" do
game = Game.new(board: 'xo ')
game.win_cat_or_else.should eq({continue: :x})
end
end
end
| true |
201e4dc320b3a9e5c17c27251a8269891e0c7192 | Ruby | Docworld/social-notifier | /lib/messenger/tcp.rb | UTF-8 | 3,212 | 3.03125 | 3 | [] | no_license | require 'socket'
require_relative 'base'
module SocialNotifier
module Messenger
class Tcp < SocialNotifier::Messenger::Base
#
# Initialize the Class
#
# @param notifier_engine [SocialNotifier::Engine]
# @param is_listener [Boolean]
# @raise [ArgumentError]
# @return [Void]
#
def initialize(notifier_engine, is_listener)
raise ArgumentError, "Notifier Object must be instance of SocialNotifier::Engine" unless notifier_engine.is_a? SocialNotifier::Engine
@notifier_engine = notifier_engine
listen if is_listener
end
#
# Unload anything that needs to be unload
# @return [Void]
def unload
end
#
# Sends a message to the listener instance
#
# @param message [Array<String>]
# @return [String] The response from the listener instance
#
def send_message(message)
message = message.join("\t")
begin
server = TCPSocket.open('localhost', 3456)
rescue Exception => e
@notifier_engine.log "Could not connect to SocialNotifier server process"
@notifier_engine.log "Message Sender Exception: #{e.class}: #{e.message}"
end
# send message
server.puts message
# get response (ALL LINES (until connection closed by other side))
response = server.read
#close the connection
server.close
#return the response
response
end
####################################################################################
private
####################################################################################
#
# Starts the listener thread
#
# @return [Void]
#
def listen
@message_queue = Thread.new do
begin
server = TCPServer.open(3456)
done = false
until done
sleep 0.001
Thread.start(server.accept) do |client|
# retrieve ONE LINE message (don't wait for connection close)
message = client.gets.chomp
@notifier_engine.log "MESSAGE RECEIVED BY SERVER: #{message}"
client.puts handle_request message
client.close
done = true if message.chomp === 'quit'
end
end
@notifier_engine.log 'Finished Message Queue'
rescue Exception => e
@notifier_engine.log "Message Listener Exception: #{e.class}: #{e.message}"
end
end
end
#
# Parses a request retrieved via retrieve_messages() and sends the response back to the requester instance
#
# @param request [String]
# @return [Void]
#
def handle_request(request)
request = request.split("\t")
request_method = request.shift
begin
request_response = @notifier_engine.process_input request_method.to_sym, request
rescue => exc
request_response = "Messenger: Error handling input: #{exc.class}: #{exc.message}"
end
request_response
end
end
end
end | true |
425d9c5efda14c8ae3a0a438dc7d2228a725ebd4 | Ruby | justonemorecommit/puppet | /lib/puppet/pops/parser/code_merger.rb | UTF-8 | 1,356 | 2.65625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive |
class Puppet::Pops::Parser::CodeMerger
# Concatenates the logic in the array of parse results into one parse result.
# @return Puppet::Parser::AST::BlockExpression
#
def concatenate(parse_results)
# this is a bit brute force as the result is already 3x ast with wrapped 4x content
# this could be combined in a more elegant way, but it is only used to process a handful of files
# at the beginning of a puppet run. TODO: Revisit for Puppet 4x when there is no 3x ast at the top.
# PUP-5299, some sites have thousands of entries, and run out of stack when evaluating - the logic
# below maps the logic as flatly as possible.
#
children = parse_results.select {|x| !x.nil? && x.code}.reduce([]) do |memo, parsed_class|
case parsed_class.code
when Puppet::Parser::AST::BlockExpression
# the BlockExpression wraps a single 4x instruction that is most likely wrapped in a Factory
memo + parsed_class.code.children.map {|c| c.is_a?(Puppet::Pops::Model::Factory) ? c.model : c }
when Puppet::Pops::Model::Factory
# If it is a 4x instruction wrapped in a Factory
memo + parsed_class.code.model
else
# It is the instruction directly
memo << parsed_class.code
end
end
Puppet::Parser::AST::BlockExpression.new(:children => children)
end
end
| true |
7f8ed05114f627818752de9bc33af5041b91d1c4 | Ruby | RDeckard/color-blocks | /main.rb | UTF-8 | 1,534 | 3.09375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
# SETTINGS
X = 100
Y = 100
COLORS = %w[R G B].freeze
# DATA STRUCTURES
TILES =
X.times.map do
Y.times.map do
{ color: COLORS.sample, group_id: nil }
end.freeze
end.freeze
COUNTS_BY_GROUP_ID = Hash.new(1)
# EXPLORATION ALGORITHM
explore =
lambda do |x, y, origin_point_color, current_group_id|
((x - 1)..(x + 1)).map do |i|
next if i.negative? || i >= X
((y - 1)..(y + 1)).map do |j|
next if j.negative? || j >= Y
next unless (i == x) ^ (j == y)
TILES[i][j] in { color: target_point_color, group_id: target_point_group_id }
next unless target_point_group_id.nil?
next unless target_point_color == origin_point_color
TILES[i][j][:group_id] = format('%05<group_nb>d', group_nb: current_group_id)
COUNTS_BY_GROUP_ID[format('%05<group_nb>d', group_nb: current_group_id)] += 1
explore.call(i, j, origin_point_color, current_group_id)
end
end
end
# PROGRAM
puts 'DATA:'
TILES.each(&method(:p))
current_group_id = 1
(0..(X - 1)).map do |x|
(0..(Y - 1)).map do |y|
TILES[x][y] in { color: origin_point_color, group_id: origin_point_group_id }
next unless origin_point_group_id.nil?
TILES[x][y][:group_id] = format('%05<group_nb>d', group_nb: current_group_id)
explore.call(x, y, origin_point_color, current_group_id)
current_group_id += 1
end
end
puts "\nRESULT:"
TILES.each(&method(:p))
puts "\nCOUNTS BY GROUP_ID:"
p(COUNTS_BY_GROUP_ID.sort_by { _2 }.to_h)
| true |
700cfc78ab5d5b96827141f698efd52602aa86a9 | Ruby | samsarge/recognition-cam | /recognition/object_detector.rb | UTF-8 | 1,110 | 2.828125 | 3 | [] | no_license | # frozen_string_literal: true
module Recognition
class ObjectDetector
def initialize(dataset = 'datasets/haarcascade_frontalface_alt.xml.gz')
@classifier = OpenCV::CvHaarClassifierCascade.load(dataset)
@objects_detected = 0
@frames_objects_detected_for = 0
end
attr_reader :frames_objects_detected_for, :objects_detected
def call(img)
cv_seq = @classifier.detect_objects(img) do |rect|
@frames_objects_detected_for += 1
draw_rectangle_around_recognised_objects(image: img, rect: rect)
end
@objects_detected = cv_seq.length
self
end
def objects_detected?
return true if @objects_detected > 0
@frames_objects_detected_for = 0
false
end
def objected_detected_for_frame_threshold?
return false unless objects_detected?
(@frames_objects_detected_for % Recognition::Constants::FRAME_THRESHOLD) == 0
end
private
def draw_rectangle_around_recognised_objects(image:, rect:)
image.rectangle!(rect.top_left, rect.bottom_right, color: OpenCV::CvColor::Red)
end
end
end
| true |
a3a2911e95b4a70b81de006d14ee6bc9a31432be | Ruby | cronkllr/health_cards | /lib/health_cards/key_set.rb | UTF-8 | 2,186 | 2.84375 | 3 | [
"Apache-2.0"
] | permissive | # frozen_string_literal: true
require 'forwardable'
module HealthCards
# A set of keys used for signing or verifying HealthCards
class KeySet
extend Forwardable
def_delegator :keys, :empty?
# Create a KeySet from a JWKS
#
# @param jwks [String] the JWKS as a string
# @return [HealthCards::KeySet]
def self.from_jwks(jwks)
jwks = JSON.parse(jwks)
keys = jwks['keys'].map { |jwk| HealthCards::Key.from_jwk(jwk) }
KeySet.new(keys)
end
# Create a new KeySet
#
# @param keys [HealthCards::Key, Array<HealthCards::Key>, nil] the initial keys
def initialize(keys = nil)
@key_map = {}
add_keys(keys) unless keys.nil?
end
# The contained keys
#
# @return [Array]
def keys
@key_map.values
end
# Returns the keys as a JWK
#
# @return JSON string in JWK format
def to_jwk
{ keys: keys.map(&:to_jwk) }.to_json
end
# Retrieves a key from the keyset with a kid
# that matches the parameter
# @param kid [String] a Base64 encoded kid from a JWS or Key
# @return [HealthCard::Key] a key with a matching kid or nil if not found
def find_key(kid)
@key_map[kid]
end
# Add keys to KeySet
#
# Keys are added based on the key kid
#
# @param new_keys [HealthCards::Key, Array<HealthCards::Key>, HealthCards::KeySet] the initial keys
def add_keys(new_keys)
if new_keys.is_a? KeySet
add_keys(new_keys.keys)
else
[*new_keys].each { |new_key| @key_map[new_key.kid] = new_key }
end
end
# Remove keys from KeySet
#
# Keys are remove based on the key kid
#
# @param new_keys [HealthCards::Key, Array<HealthCards::Key>, HealthCards::KeySet] the initial keys
def remove_keys(removed_keys)
if removed_keys.is_a? KeySet
remove_keys(removed_keys.keys)
else
[*removed_keys].each { |removed_key| @key_map.delete(removed_key.kid) }
end
end
# Check if key is included in the KeySet
#
# @param key [HealthCards::Key]
# @return [Boolean]
def include?(key)
!@key_map[key.kid].nil?
end
end
end
| true |
781aa46d91c9aebec293b596499beead4764590b | Ruby | hbarradah/sample_app | /spec/models/user_spec.rb | UTF-8 | 3,774 | 2.703125 | 3 | [] | no_license | require 'spec_helper'
describe User do
before(:each) do
@attr = {
:name => "Example User",
:email => "user@example.com",
:password => "foobar",
:password_confirmation => "foobar"
}
end
it "should create a new instance given valid attributes" do
User.create! (@attr)
end
it "should require a name" do
no_name_user = User.new(@attr.merge(:name => ""))
no_name_user.should_not be_valid
end
it "should require an email" do
no_email_user = User.new(@attr.merge(:email => ""))
no_email_user.should_not be_valid
end
it "should reject names that are too long" do
long_name = "a" * 51
long_name_user = User.new (@attr.merge(:name => long_name))
long_name_user.should_not be_valid
end
it "should accept valid email addresses" do
addresses = %w[user@info.com user@foo.bar.org first.last@foo.org]
addresses.each do |address|
valid_email_address = User.new(@attr.merge(:email => address))
valid_email_address.should be_valid
end
end
it "should reject invalid email addresses" do
addresses = %w[user@info,com user_foo_bar.org first.last@foo]
addresses.each do |address|
valid_email_address = User.new(@attr.merge(:email => address))
valid_email_address.should_not be_valid
end
end
it "should reject duplicate email addresses" do
User.create!(@attr)
user_with_duplicate_email = User.new(@attr)
user_with_duplicate_email.should_not be_valid
end
it "should reject identical email addresses up to case" do
upcased_email = @attr[:email].upcase
User.create!(@attr.merge(:email => upcased_email))
user_with_duplicate_email = User.new(@attr)
user_with_duplicate_email.should_not be_valid
end
describe "password validations"do
it "should require a password" do
empty_password_user = User.new(@attr.merge(:password => "", :password_confirmation => ""))
empty_password_user.should_not be_valid
end
it "should require matching password" do
User.new(@attr.merge(:password_confirmation => "invalid password")).should_not be_valid
end
it "should reject short passwords" do
short_password_user = User.new(@attr.merge(:password => "bo", :password_confirmation => "bo"))
short_password_user.should_not be_valid
end
it "should reject long passwords" do
long_password_user = User.new(@attr.merge(:password => "a" * 41, :password_confirmation => "a" * 41))
long_password_user.should_not be_valid
end
end
describe "password encryption" do
before(:each) do
@user = User.create!(@attr)
end
it "should have an encrypted password attribute" do
@user.should respond_to(:encrypted_password)
end
it "should set the encrypted password" do
@user.encrypted_password.should_not be_blank
end
describe "has_password?" do
it "should return true if has password" do
@user.has_password?(@attr[:password]).should be_true
end
it "should return false if has password" do
@user.has_password?("invalid").should be_false
end
end
describe "Authenticate" do
it "should return nil if user email/password mismatch" do
wrong_password_user = User.authenticate(@attr[:mail], "wrongPassword")
wrong_password_user.should be_nil
end
it "should return nil if user with supplied email doesn't exist" do
wrong_password_user = User.authenticate("boo.com", @attr[:password])
wrong_password_user.should be_nil
end
it "should return correct user when matching email/password are supplied"do
matching_user = User.authenticate(@attr[:email], @attr[:password])
matching_user.should == @user
end
end
end
end
| true |
85da3efbd9d99f8980a443545d2e62150e9f5bfb | Ruby | corrirc/pub_lab | /customer.rb | UTF-8 | 402 | 3.453125 | 3 | [] | no_license | class Customer
attr_reader :name, :wallet, :age, :drunkness_level
def initialize(name, wallet, age)
@name = name
@wallet = wallet
@age = age
@drunkness_level = 0
end
def buy_drink(drink)
@wallet -= drink.price
@drunkness_level += drink.alchol_level
end
def buy_food(food)
@drunkness_level -= food.rejuvenation_level
@wallet -= food.price
end
end
| true |
0b955d0a642b42996346898db58ae6e724cc53b0 | Ruby | Xiawpohr/ac-exercise-tictactoe | /tic_tag_toe.rb | UTF-8 | 2,533 | 4.1875 | 4 | [] | no_license | class TicTagToe
attr_reader :board, :win_condition, :turn
attr_accessor :player
def initialize
@board = [1,2,3,4,5,6,7,8,9]
@win_condition = [
[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]
]
@turn = 0
@player = {'O' => [], 'X' => []}
end
def launch!
introduction
#action loop
result = nil
until result == :quit
puts "two_player or one_player or quit ?"
print "> "
user_response = gets.chomp
result = do_action(user_response)
end
conclusion
end
def do_action(action)
case action
when 'two_player'
play(human_input,human_input)
when 'one_player'
play(human_input,computer_input)
when 'quit'
return :quit
else
puts "Do you want to play or quit?"
end
end
def play(first, last)
@turn = 0
game_check = nil
until game_check == :end
@turn += 1
if @turn % 2 == 1
pos = first
@player['O'] << pos
@board.insert(pos-1,O)
else
pos = last
@player['X'] << pos
@board.insert(pos-1,X)
end
game_display
game_check = who_wins(@player)
end
puts "Do you want to play again ?"
end
def who_wins(player)
if @turn == 9
puts "No one wins the game."
return :end
end
for i in 0...win_condition.size do
if @player['O'] & win_condition[i] == win_condition[i]
puts "O wins the game."
return :end
elsif @player['X'] & win_condition[i] == win_condition[i]
puts "X wins the game."
return :end
else
return nil
end
end
end
def human_input
position = nil
until @board.include?(position)
puts "pick a number (position) to start"
print "> "
position_s = gets.chomp
position = position_s.to_i
@board.delete(position)
end
reutrn position
end
def computer_input
# like an AI
end
def game_display
puts "#{@board[0]} | #{@board[1]} | #{@board[2]}"
puts "---------------------------------------"
puts "#{@board[3]} | #{@board[4]} | #{@board[5]}"
puts "---------------------------------------"
puts "#{@board[6]} | #{@board[7]} | #{@board[8]}"
end
def introduction
puts "<< welcome to tic-tag-toe >>"
puts "The object of Tic Tac Toe is to get three in a row."
puts "You play on a three by three game board."
puts "The first player is known as O and the second is X."
puts "Players alternate placing Xs and Os on the game board"
puts "until either oppent has three in a row or all nine squares are filled."
game_display
end
def conclusion
puts "<< good bye >>"
end
end
game = TicTagToe.new
game.launch! | true |
545171cd82e30f8366d0c6607561fb5d0c743744 | Ruby | baezanat/Launch_School_bootcamp | /RB_109/prep_videos/substrings.rb | UTF-8 | 2,524 | 4.53125 | 5 | [] | no_license | =begin
Write a method that will return a substring based on specified indices.
substring('honey', 0, 2) == 'hon'
substring('honey', 1, 2) == 'on'
substring('honey', 3, 9) == 'ey'
substring('honey', 2) == 'n'
INPUT: string, num1(index1), num2(index2)
OUTPUT: string
RULES:
- return a string slice from index1 to index2 (inclusive)
- if index2 >= string.size, return slice to end of string (no errors, no nil)
- if only one number is specified, use it also as second numeric argument
DATA STRUCTURE= strings and arrays
ALGORITHM:
-return string[index1..index2]
-set the second numeric parameter to default to the same value as the first if no value is entered
=end
def substring(str, index1, index2 = index1)
str[index1..index2]
end
# p substring('honey', 0, 2) == 'hon'
# p substring('honey', 1, 2) == 'on'
# p substring('honey', 3, 9) == 'ey'
# p substring('honey', 2) == 'n'
# Write a method that finds all the substrings in a string. No 1 letter words.
# INPUT: string
# OUTPUT: array of strings
# RULES:
# - no 1 letter words
# - strings can be repeated
# ALGORITHM:
# - initiate an empty result string
# - initiate a counter1 and set it to 0
# - manual loop
# - break if counter1 >= str.size
# - set counter2 = 0
# - loop
# - break if counter2 >= str.size
# - result << str[counter1..counter2]
# - counter2 += 1
# - end
# counter1 +=1
# - end loop
# - return result array
def substrings(str)
result = []
counter1 = 0
loop do
break if counter1 >= str.size
counter2 = counter1
loop do
break if counter2 >= str.size
result << str[counter1..counter2]
counter2 += 1
end
counter1 += 1
end
result.select { |str| str.size > 1 }
end
# Another algorithm:
# - initiate an empty result array
# - set counter = 0
# loop do
# - break if counter >= str.size
# - new_str = str[counter..-1]
# - new_str.size.times do |i|
# - result << str[counter..i]
# -counter += 1
# - return result
def substrings2(str)
result = []
counter = 0
p str
loop do
break if counter == str.size - 1
new_string = str[counter..-1]
(new_string.size - 1).times do |i|
result << new_string[0..i + 1]
end
counter += 1
end
p result
result
end
p substrings2('band')# == ['ba', 'ban', 'band', 'an', 'and', 'nd']
p substrings2('world') == ['wo', 'wor', 'worl', 'world', 'or', 'orl', 'orld', 'rl', 'rld', 'ld']
p substrings2('ppop')# == ['pp', 'ppo', 'ppop', 'po', 'pop', 'op']
| true |
1051b401c35c16790a7ac18d9779b07216f273c1 | Ruby | ViralSeq/viral_seq | /lib/viral_seq/pid.rb | UTF-8 | 719 | 3.203125 | 3 | [
"MIT"
] | permissive |
module ViralSeq
module PID
# generate all Primer ID combinations given the length of Primer ID
# @param l [Integer] the length of the Primer ID.
# @example generate a pool of Primer IDs with length of 10
# primer_id_pool = ViralSeq::PID.generate_pool(10) # 10 is the length of Primer ID
# puts primer_id_pool.size #should be 4^10
# => 1048576
def self.generate_pool(l=8)
nt = ['A','T','C','G']
pid_pool = ['A','T','C','G']
(l-1).times do
pid_pool = pid_pool.product(nt)
pid_pool.collect! do |v|
v.join("")
end
end
return pid_pool
end # end of .generate_primer_id_pool
end # end of Pid
end # end of ViralSeq
| true |
b6710f1fdf547426c1e59063e377456fd0da4d64 | Ruby | ytjmt/at_coder | /abc/abc142/a/logic.rb | UTF-8 | 49 | 3.125 | 3 | [] | no_license | n = gets.chomp.to_i
puts ((n + 1) / 2) / n.to_f
| true |
e2301ec1caddff0490984b804c9cba9dc761c7c5 | Ruby | arjamizo/tieto_decode_2012-solved | /src/q21.rb | UTF-8 | 263 | 3.03125 | 3 | [] | no_license | def nFirstFibbNrs n
fibb=[1,1]
p1,p2=fibb[1],fibb[0]
(n-2).times{
newfib=p1+p2
p2=p1
p1=newfib
fibb<<newfib
}
fibb
end
fibs=nFirstFibbNrs(1000)
fexpects=fibs.keep_if{|n|
[2,3,5,7].count{|i| n%i==0}==4
}
puts fibs.to_s
puts fexpects.to_s
puts fexpects.length | true |
3b121e0201854f69104200854974dd82356f9acd | Ruby | kfili/codewars | /8kyu-difficulty-level/rock-paper-scissors/problem.rb | UTF-8 | 240 | 3.546875 | 4 | [] | no_license | # Rock Paper Scissors
#
# Let's play! You have to return which player won! In case of a draw return Draw!.
#
# Examples:
#
# rps('scissors','paper') // Player 1 won!
# rps('scissors','rock') // Player 2 won!
# rps('paper','paper') // Draw!
| true |
ee2a9b35110eaf81c30edae0ad1d8de77cdc771b | Ruby | amancevice/pooler | /lib/pooler/user.rb | UTF-8 | 1,286 | 2.625 | 3 | [
"MIT"
] | permissive | require 'bcrypt'
module Pooler
class User < ActiveRecord::Base
include BCrypt
validates :username, presence:true, uniqueness:true, :length => { :in => 2..20 }
validates :email, presence:true, uniqueness:true, format: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
has_many :picks
has_many :payments
def score
picks.decided.collect(&:points).sum
end
def max_score
score + picks.undecided.collect(&:points).sum
end
def password= password
salt = BCrypt::Engine.generate_salt
hash = BCrypt::Engine.hash_secret password, salt
update! salt:salt, password_hash:hash
end
def login password
password_hash == BCrypt::Engine.hash_secret(password, salt)
end
def lock!
update! locked:true
end
def pay!
update! paid:true
end
def locked?
locked
end
def paid?
paid
end
class << self
def signup username, email, password
password_salt = BCrypt::Engine.generate_salt
password_hash = BCrypt::Engine.hash_secret password, password_salt
User.create(
username: username,
email: email,
salt: password_salt.to_s,
password_hash: password_hash.to_s)
end
end
end
end
| true |
b75044b5a073161f73bd61bcda6163f8a996802d | Ruby | wendelscardua/dotini | /spec/dotini/key_value_pair_spec.rb | UTF-8 | 2,760 | 2.640625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module Dotini
RSpec.describe KeyValuePair do
describe 'to_s' do
context 'when there is no key' do
context 'when there is no comment' do
subject(:pair) do
described_class.new
end
it 'returns an empty string' do
expect(pair.to_s).to eq ''
end
end
context 'when there are some prepended comments' do
subject(:pair) do
described_class.new.tap do |pair|
pair.prepended_comments = [
'; first comment',
'; second comment'
]
end
end
it 'returns a string with just the comments' do
expect(pair.to_s).to eq "; first comment\n; second comment\n"
end
end
end
context 'when there is a key' do
context 'when there is no comment' do
subject(:pair) do
described_class.new.tap do |pair|
pair.key = 'some-key'
pair.value = 'some-value'
end
end
it 'returns a valid key-pair string' do
expect(pair.to_s).to eq "some-key = some-value\n"
end
end
context 'when there is an inline comment' do
subject(:pair) do
described_class.new.tap do |pair|
pair.key = 'some-key'
pair.value = 'some-value'
pair.inline_comment = '; some-inline-comment'
end
end
it 'returns a valid key-pair string' do
expect(pair.to_s).to eq "some-key = some-value ; some-inline-comment\n"
end
end
context 'when there are some prepended comments' do
subject(:pair) do
described_class.new.tap do |pair|
pair.key = 'some-key'
pair.value = 'some-value'
pair.prepended_comments = [
'; first comment',
'; second comment'
]
end
end
it 'returns a valid key-pair string' do
expect(pair.to_s).to eq "; first comment\n; second comment\nsome-key = some-value\n"
end
end
context 'when there are both inline and prepended comments' do
subject(:pair) do
described_class.new.tap do |pair|
pair.key = 'some-key'
pair.value = 'some-value'
pair.prepended_comments = ['; foo']
pair.inline_comment = '; bar'
end
end
it 'returns a valid key-pair string' do
expect(pair.to_s).to eq "; foo\nsome-key = some-value ; bar\n"
end
end
end
end
end
end
| true |
1c96bdedc891a6013637b131a97eb7d4956b78e3 | Ruby | gabdelaun/dotfiles | /wishlist.rb | UTF-8 | 2,057 | 3.9375 | 4 | [] | no_license | # TODO:
# Build a gift wishlist, where you can:
# List products in your wishlist
# Add a new product to your list (e.g. "Jeans", "Socks", etc..)
# Delete an item you don't want in your list anymore
# Mark any item as "checked" when you've bought it
# It's like a basic todolist with products instead of tasks.
def list_products(wishlist)
wishlist.each_with_index do |product, index|
if product[:checked]
puts "#{index + 1} - #{product[:name]} - £#{product[:price]} - [X]"
else
puts "#{index + 1} - #{product[:name]} - £#{product[:price]} - [ ]"
end
end
end
wishlist = []
action = ""
puts "WELCOME TO YOUR WISHLIST"
until action == "exit"
puts "What do you want to do (add/list/remove/update/mark_checked/mark_unchecked). Type exit if you want to leave the wishlist."
action = gets.chomp
case action
when "add"
puts "What product do you want to add?"
product_name = gets.chomp
puts "What is the price of this product?"
product_price = gets.chomp
wishlist << { name: product_name,
checked: false,
price: product_price.to_i }
list_products(wishlist)
when "list"
list_products(wishlist)
when "remove"
puts "What is the number of the item you want to remove?"
number = gets.chomp.to_i
wishlist.delete_at(number - 1)
list_products(wishlist)
when "update"
puts "What is the number of the item you want to update?"
number = gets.chomp.to_i
puts "Please enter the new name!"
new_name = gets.chomp
product = wishlist[number - 1]
product[:name] = new_name
list_products(wishlist)
when "mark_checked"
puts "What is the number of the item you want to check?"
number = gets.chomp.to_i
product = wishlist[number - 1]
product[:checked] = true
list_products(wishlist)
when "mark_unchecked"
puts "What is the number of the item you want to uncheck?"
number = gets.chomp.to_i
product = wishlist[number - 1]
product[:checked] = false
list_products(wishlist)
end
end
| true |
05484e3beee7e7b4935e6fc83da74da6c03e2c08 | Ruby | jammb/sockoramma | /db/seeds.rb | UTF-8 | 1,356 | 2.640625 | 3 | [] | no_license | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
require 'csv'
require 'pry'
file_name = 'sockorama_inventorys.csv'
def parse_data( body )
puts "Starting Seed"
products = []
CSV.foreach(body, :headers => true, :header_converters => :symbol) do |row|
product = row.to_hash
products << product
end
products.each do |product|
# binding.pry
material = Material.find_or_create_by(name: product[:material])
color = Color.find_or_create_by(name: product[:color])
style = Style.find_or_create_by(name: product[:style])
item = Item.find_or_create_by(
title: product[:title],
description: product[:description],
picture: product[:photo],
price: product[:price],
material_id: material.id,
color_id: color.id,
style_id: style.id
)
size = Size.find_or_create_by(
name: product[:size]
)
Quantity.create(
item_id: item.id,
size_id: size.id,
quantity: product[:quantity]
)
end
puts "Seeding Complete"
end
parse_data(file_name)
| true |
d2330f1930a4dee907617945a585e126490833d1 | Ruby | the-night-shift/testing | /change_machine.rb | UTF-8 | 1,864 | 3.640625 | 4 | [] | no_license | require 'rspec'
# 1 [1]
# 2 [1,1]
# 3 [1,1,1]
# 4 [1,1,1,1]
# 5 [5]
# 6 [5,1]
# 7 [5,1,1]
# 8 [5,1,1,1]
# 9
# 10 [10]
# 11
# 12
# 13
# 14
# 15
class ChangeMachine
def change(money)
coins = []
denominations = [25,10,5,1]
denominations.each do |denomination|
while money >= denomination
coins << denomination
money -= denomination
end
end
return coins
end
end
RSpec.describe ChangeMachine do
describe '#change' do
it 'should return [1] when given 1' do
machine = ChangeMachine.new
expect(machine.change(1)).to eq([1])
end
it 'should return [1,1] when given 2' do
machine = ChangeMachine.new
expect(machine.change(2)).to eq([1,1])
end
it 'should return [1,1,1] when given 3' do
machine = ChangeMachine.new
expect(machine.change(3)).to eq([1,1,1])
end
it 'should return [5] when given 5' do
machine = ChangeMachine.new
expect(machine.change(5)).to eq([5])
end
it 'should return [5,1] when given 6' do
machine = ChangeMachine.new
expect(machine.change(6)).to eq([5,1])
end
it 'should return [10] when given 10' do
machine = ChangeMachine.new
expect(machine.change(10)).to eq([10])
end
it 'should return [10,10] when given 20' do
machine = ChangeMachine.new
expect(machine.change(20)).to eq([10,10])
end
it 'should return [10,5,1,1,1] when given 18' do
machine = ChangeMachine.new
expect(machine.change(18)).to eq([10,5,1,1,1])
end
it 'should return [25] when given 25' do
machine = ChangeMachine.new
expect(machine.change(25)).to eq([25])
end
it 'should return [25,25,25,25,10,5,1,1,1,1] when given 119' do
machine = ChangeMachine.new
expect(machine.change(119)).to eq([25,25,25,25,10,5,1,1,1,1])
end
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.