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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
0089f38d59d01eb6464fc9e6df6ec4fc886abb99
|
Ruby
|
joshwalsh/Toroid
|
/app/services/persist_state.rb
|
UTF-8
| 762
| 2.703125
| 3
|
[] |
no_license
|
class PersistState
def initialize(current_state)
@current_state = current_state
end
def save(new_content)
@current_state.write new_content
@current_state.rewind
end
def load
@current_state.read.tap { @current_state.rewind }
end
def self.save(game)
File.open(self.file_path, "w+") do |file|
new_content = YAML::dump(game)
new(file).save(new_content)
end
end
def self.load
content = nil
if not File.exists?(self.file_path)
File.open(self.file_path, "w+")
end
File.open(self.file_path, "r") do |game_content|
p = PersistState.new game_content
content = YAML::load(p.load)
end
content
end
def self.file_path
"#{Rails.root}/db/#{Rails.env}.yml"
end
end
| true
|
42614861d42154073cbceb35b987465a9751cce8
|
Ruby
|
wellavelino/image-comparable
|
/lib/image_comparable/image_diff.rb
|
UTF-8
| 1,316
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
class ImageDiff
def initialize(baseline, screenshot, acceptant_criteria)
@baseline = baseline.image
@screenshot = screenshot.image
@diff = []
@baseline.height.times do |y|
@baseline.row(y).each_with_index do |pixel, x|
@diff << [x, y] unless pixel == @screenshot[x, y]
end
end
@x = @diff.map { |xy| xy[0] }
@y = @diff.map { |xy| xy[1] }
@acceptant_criteria = acceptant_criteria
end
def save
Dir.mkdir(path) unless Dir.exist?(path)
draw.save(File.join(path, file_name))
calculate_score(@diff, @screenshot, @acceptant_criteria)
end
def calculate_score(diff, screenshot, acceptant_criteria)
raise 'Acceptant criteria cannot be null' if acceptant_criteria.nil?
acceptant_criteria = acceptant_criteria.to_f
result = (diff.length.to_f / screenshot.pixels.length) * 100
return unless result > acceptant_criteria
raise "The score result: #{result}%, is bigger then " \
"acceptant_criteria: #{acceptant_criteria}%"
end
def draw
@screenshot.rect(@x.min, @y.min, @x.max, @y.max, ChunkyPNG::Color::BLACK)
end
def path
@path ||= File.join(FileUtils.pwd, 'diff_images')
end
def file_name
"#{Time.now.strftime('%Y%m%d')}_diff.png"
end
end
| true
|
69e4312f8046beb7e70781b7e564f52aa39442ba
|
Ruby
|
MustafaTaha15/ttt-10-current-player-re-coded-000
|
/lib/current_player.rb
|
UTF-8
| 200
| 3.234375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def turn_count(board)
count=0
board.each do |mt|
if mt=="X" || mt=="O"
count+=1
end
end
count
end
def current_player(board)
if turn_count(board) % 2 == 0
return "X"
else
return "O"
end
end
| true
|
7a41b1ebb1dd1bae6a49249a62b0d2de3fc2a665
|
Ruby
|
Svischev/my_blog
|
/app/helpers/blogs_helper.rb
|
UTF-8
| 1,248
| 2.6875
| 3
|
[] |
no_license
|
module BlogsHelper
# Вывести все посты блога пользователя, который смотрим
def get_blogs()
user_id_which_created_blog = get_user_id_which_created_blog()
if !user_id_which_created_blog.blank?
user = User.find(get_user_id_which_created_blog())
blogs = user.blogs #Blog.where(user_id: user.id)
end
return blogs
end
# Записать id пользователя, чем блог смотрим
def set_user_id_which_created_blog(user_id_which_created_blog)
cookies.permanent[:user_id_which_created_blog] = user_id_which_created_blog
end
#Создатель блога?
def created_blog?()
if signed_in?()
current_user().id.to_i == cookies[:user_id_which_created_blog].to_i #blog.user_id
end
end
def get_user_which_created_blog()
user_id_which_created_blog = get_user_id_which_created_blog()
if !user_id_which_created_blog.blank?
user = User.find(get_user_id_which_created_blog())
end
return user
end
def get_user_id_which_created_blog()
blog_user_id = cookies[:user_id_which_created_blog] #узнаем, чем блог сейчас мы смотрим
if !blog_user_id.blank?
blog_user_id = blog_user_id.to_i
end
return blog_user_id
end
end
| true
|
57f7f18da27af24764c5b8a958d0b9fb4af8e0c4
|
Ruby
|
JuanitoFatas/OJAD
|
/lib/ojad/result.rb
|
UTF-8
| 644
| 2.890625
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require_relative "verbs"
module OJAD
class Result
def initialize(response)
@response = response
end
def to_human
if response.success?
verbs_for_human
else
error_message
end
end
private
attr_reader :response
LINE = "-"*80 + "\n"
def html
response.html
end
def verbs_for_human
verbs.map(&:to_human).join(LINE)
end
def verbs
Verbs.new(html).to_a
end
def error_message
"An error occurred. Please try again later.\n\n" \
"Response body:\n\n#{response.body.to_s}"
end
end
end
| true
|
1ea5d8474f1b976a952532918b2688302a6ea410
|
Ruby
|
mgriffin/mikegriffin
|
/script/bookmark
|
UTF-8
| 846
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
require 'date'
require 'mechanize'
date = DateTime.now.strftime("%Y-%m-%dT%H:%MZ")
link = ARGV[0]
title = Mechanize.new.get(link).title
tags = ARGV[1..-1]
slug = DateTime.now.strftime("%Y-%m-%d-") + title .gsub(/\s+/, "-") # replace spaces with -
.gsub(/&/, "-and-") # replace & with -and-
.gsub(%r{[^\w\-/]+}, "") # remove all non-word chars except - and /
.gsub(%r{/}, "-") # replace / with -
.gsub(/\-\-+/, "-") # replace multiple - with single -
.gsub(/^-/, "") # remove leading -
.gsub(/-$/, "") # remove trailing -
.downcase
body = <<~TEXT
---
date: #{date}
link: #{link}
title: #{title}
tags: #{tags.join(' ')}
---
TEXT
File.open(File.absolute_path(File.join(__dir__, "/../_links/#{slug}.md")), "w") do |f|
f.puts body
end
| true
|
2c3d9c63c2cd8ab1581782d84f17747d9bda442f
|
Ruby
|
rec0de/obdd-gen
|
/benchmark/bdd-gen/formula-gen.rb
|
UTF-8
| 1,263
| 3.296875
| 3
|
[
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
class MockFormula
@@varCount = 4
@@vars = "abcdefghijklmnop"
def genFormula()
generatePureExpr()
end
def generatePureExpr()
generateImpl()
end
def generateImpl()
if chance(0.3)
op = ["->", "<=>", "=>", "<->"].sample
return "#{generateOr()} #{op} #{generateOr()}"
else
return generateOr()
end
end
def generateOr()
if chance(0.35)
op = ["|", "|", "^"].sample
return "#{generateAnd()} #{op} #{generateOr()}"
else
return generateAnd()
end
end
def generateAnd()
if chance(0.35)
return "#{generateNot()} & #{generateAnd()}"
else
return generateNot()
end
end
def generateNot()
if chance(0.3)
return "!#{generateAtom()}"
else
return generateAtom()
end
end
def generateAtom()
if chance(0.2)
"(#{generatePureExpr()})"
elsif chance(0.85)
@@vars.split('').sample
else
["true", "false"].sample
end
end
def chance(prob)
Random::rand() < prob
end
def exponentialRandomValue(lambda)
(-Math.log(Random::rand())) / lambda
end
def exponentialRandomInt(expected)
exponentialRandomValue(1.to_f/expected).ceil.to_i
end
end
gen = MockFormula.new()
500.times do
formula = gen.genFormula()
while(formula.length < 6)
formula = gen.genFormula()
end
puts formula
end
| true
|
c9edb3078bddee53f7432c294844b79b0589d670
|
Ruby
|
need47/fselector
|
/lib/fselector/algo_discrete/Specificity.rb
|
UTF-8
| 888
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
#
# FSelector: a Ruby gem for feature selection and ranking
#
module FSelector
#
# Specificity (SP)
#
# TN D
# SP = ------- = -----
# TN+FP B+D
#
# ref: [Wikipedia](http://en.wikipedia.org/wiki/Sensitivity_and_specificity)
#
class Specificity < BaseDiscrete
# this algo outputs weight for each feature
@algo_type = :filter_by_feature_weighting
private
# calculate contribution of each feature (f) for each class (k)
def calc_contribution(f)
each_class do |k|
b, d = get_B(f, k), get_D(f, k)
s = 0.0
x = b+d
s = d/x if not x.zero?
set_feature_score(f, k, s)
end
end # calc_contribution
end # class
# shortcut so that you can use FSelector::SP instead of FSelector::Specificity
SP = Specificity
end # module
| true
|
049497ca781841a6140300128b9201c07df59051
|
Ruby
|
Terry814/Ruby-project3
|
/lib/rubyrems/emailmatcher.rb
|
UTF-8
| 5,961
| 2.6875
| 3
|
[] |
no_license
|
# process the emails to customers, enquiries etc
# Finds all email where source is not 'python', parsed is true, matched is false and ignore_match is false
# Calls the email.parse_cust_name function for all, sets ignore_match if no customer email
# handle 'in' and 'out' differently
# 'in' - find or create customer, find or create enquiry by customer, property and received_at
# 'out' - find or create customer, find or create enquiry by customer and property,
# split agents into found and not_found, create agent enquiry if not already there
# save not found for further work if not already there
# set matched
# 25/5/10
# 9/10/10 added update of cust_last_enq_date
# 21/10/10 amended to handle ones sent to customer with agent in bcc
# 1/12/10 added line to use cc_addr for clientemail if its an out email
class ProcessEmails
attr_reader :n, :matched, :unmatched, :new_cust, :new_enq, :in, :out, :custpres,
:inenqpres, :outenqpres, :no_cust
def initialize
@no_cust = 0
@in = 0
@out = 0
@n = 0
@matched = 0
@unmatched= 0
@new_cust = 0
@new_enq = 0
@custpres = 0
@inenqpres = 0
@outenqpres = 0
end
def run
recs = Email.find(:all,
:conditions => ['source != "python" and matched = 0 and ignore_match = 0 and parsed = 1'],
:order => 'id')
@n = recs.size
puts "Found #{@n} emails to match"
recs.each {|@rec|
@rec.parse_cust_name
@dir = @rec.direction
if @dir == 'out'
match_out_email
elsif @dir == 'in'
match_in_email
else
puts 'Unknown mail direction'
end
}
end
# find or create customer
# set ignore match if no customer email
def handle_cust
email = @rec.clientemail
# if email is nil and this is an out email try cc_addr for email
if email == nil and @dir == 'out'
email = @rec.cc_addr
end
# ignore if no customer email
if email == nil
@rec.ignore_match = true
@rec.error_str = 'No customer email address'
@rec.save
@no_cust += 1
return nil
end
email.strip!
if email == ''
@rec.ignore_match = true
@rec.error_str = 'No customer email address'
@rec.save
@no_cust += 1
return nil
end
# find customer or add
cust = Customer.find_by_email(email)
if cust == nil
if @rec.clientphone != nil
home = @rec.clientphone
mobile = nil
if home[0..1] == '07'
mobile = home
home = nil
end
else
home = nil
mobile = nil
end
cust = Customer.create(
:email => email,
:title => @rec.cust_tl,
:firstname => @rec.cust_fs,
:lastname => @rec.cust_ls,
:phone_home => home,
:phone_mobile => mobile,
:active => true,
:gets_fu => true
)
@new_cust += 1
else
@custpres += 1
end
return cust
end
def update_cust_last_enq(cust, enqdate)
if cust.last_enq_date == nil or enqdate > cust.last_enq_date
cust.last_enq_date = enqdate
cust.save
end
end
def match_in_email
@in += 1
cust = handle_cust
return if cust == nil
# look for an enquiry for this customer, property and date
# if found then nothing to do
enq = Enquiry.find_by_customer_id_and_property_and_received_at(cust.id(), @rec.property, @rec.sent_at)
if enq == nil
enq = Enquiry.create(
:customer_id => cust.id(),
:in_email_id => @rec.id(),
:property => @rec.property,
:region => @rec.region,
:info => @rec.info,
:viewing => @rec.viewreq,
:mortgage => @rec.mortgage_info,
:currency => @rec.currency_info,
:received_at => @rec.sent_at
)
@new_enq += 1
else
@inenqpres += 1
end
update_cust_last_enq(cust, @rec.sent_at) if @rec.sent_at != nil
@rec.matched = true
@rec.save
end
def match_out_email
@out += 1
agt_str = ""
# look for customer
cust = handle_cust
return if cust == nil
# look for relevant enquiry - if found just add out email info else create enquiry
# watch for the same one already processed
enq = nil
enqs = Enquiry.find_all_by_customer_id_and_property(cust.id(), @rec.property, :order => 'received_at desc')
if enqs.size > 0
enq = enqs[0]
enq.out_email_id = @rec.id() if enq.out_email_id == nil or enq.out_email_id == 0
enq.save
@outenqpres += 1
else
enq = Enquiry.create(
:customer_id => cust.id(),
:out_email_id => @rec.id(),
:property => @rec.property,
:region => @rec.region,
:info => @rec.info,
:viewing => @rec.viewreq,
:mortgage => @rec.mortgage_info,
:currency => @rec.currency_info,
:received_at => @rec.sent_at
)
@new_enq += 1
end
update_cust_last_enq(cust, @rec.sent_at) if @rec.sent_at != nil
# now match agents
# pick up agents to search for
if @rec.to_addr == cust.email
agt_str = @rec.bcc_addr
else
agt_str = @rec.to_addr + ';' + @rec.bcc_addr
end
# find agents checks for blank or nil
agents, nf = Agent.find_agents(agt_str)
# dont create if already there
agents.each {|ag|
age = AgentEnquiry.find_by_enquiry_id_and_agent_id_and_sent_at(enq.id(), ag.id(), @rec.sent_at)
if age == nil
AgentEnquiry.create(
:enquiry_id => enq.id(),
:agent_id => ag.id(),
:sent_at => @rec.sent_at
)
@matched += 1
end
}
# dont create if already there
nf.each {|s|
umr = UnmatchedRecipient.find_by_enquiry_id_and_recipient_str(enq.id(), s)
if umr == nil
UnmatchedRecipient.create(
:enquiry_id => enq.id(),
:recipient_str => s
)
@unmatched += 1
end
}
@rec.matched = true
@rec.save
end
end
| true
|
bfcc3830c51465acb1c421e85215b9c389ff9dfc
|
Ruby
|
arturcp/arenah-rails
|
/lib/legacy/importers/characters_importer.rb
|
UTF-8
| 913
| 2.59375
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require 'legacy/legacy_character'
require 'legacy/legacy_user'
module Legacy
module Importers
class CharactersImporter
INACTIVE_NAMES_LIST = [
'Guest',
'??'
].freeze
def self.import(characters, users)
puts '3. Creating characters...'
bar = RakeProgressbar.new(characters.count)
characters.each do |character|
user = users.find { |user| user.id == character.user_id }
character.create!(user.arenah_user)
character.arenah_character.update(status: 0) if INACTIVE_NAMES_LIST.include?(character.name)
bar.inc
end
bar.finished
puts "#{Character.count} characters created"
puts "#{Character.where(status: 1).count} active characters"
puts "#{Character.where(status: 0).count} inactive characters"
puts ''
end
end
end
end
| true
|
77a6ade72c6a4d64b98ba78cc43bedc71bce637d
|
Ruby
|
Xabier-Casan-Abia/oo-relationships-practice-london-web-career-040119
|
/app/models/airbnb/listing.rb
|
UTF-8
| 854
| 3.328125
| 3
|
[] |
no_license
|
class Listing
attr_reader :city
@@all = []
def initialize(city)
@city = city
@@all << self
end
def self.all
@@all
end
def trips
Trip.all.select { |trip| trip.listing == self }
# - returns an array of all trips at a listing
end
def guests
trips.collect { |trip| trip.guest }.uniq
# - returns an array of all guests who have stayed at a listing
end
def trip_count
trips.length
# - returns the number of trips that have been taken to that listing
end
def self.find_all_by_city(city)
@@all.select { |listing| listing.city == city}
# - takes an argument of a city name (as a string) and returns all the listings for that city
end
def self.most_popular
@@all.max_by { |listing| listing.trip_count} #self.all = @@all in this case
# - finds the listing that has had the most trips
end
end
| true
|
2125143f034ebedd4b540cb33db3747c24334675
|
Ruby
|
schmee3spades/Ruby-Quizes-New
|
/quiz10/Crosswords.rb
|
UTF-8
| 6,981
| 3.015625
| 3
|
[] |
no_license
|
module RubyQuiz
class Crosswords
attr_reader :crossword, :cell_height, :cell_width, :clue_number, :row_separators, :column_separators, :output_string;
def initialize( filename )
@crossword = Array.new()
@row_separators = Array.new()
@column_separators = Array.new()
load_file( filename )
@cell_height = 2
@cell_width = 4
@clue_number = 1
@output_string = String.new()
end
def load_file( filename )
file = File.open(filename, "rb");
contents = file.read
lines = contents.split(/\n/)
lines.each { |line|
line.gsub!(/\r/, '')
line.gsub!(/\s+/, '')
@crossword.push(line.split(//))
}
make_stars_for_blanks
define_separators
end
def make_stars_for_blanks()
0.upto(@crossword.length() - 1) do |row|
line = @crossword[row]
if(row == 0 || row == (@crossword.length() - 1)) then
0.upto(line.length() - 1) do |column|
should_be_star(row, column)
end
else
should_be_star(row, 0)
should_be_star(row, line.length() - 1)
end
end
end
def should_be_star(row, column)
if( (row < 0) || (column < 0) || (row > @crossword.length() - 1) || (column > @crossword[@crossword.length() - 1].length - 1)) then
return 0
end
if((@crossword[row][column] == '_') || (@crossword[row][column] == '*')) then
return 0
end
if( (row == 0) || (column == 0) || (row == @crossword.length() - 1) || (column == @crossword[@crossword.length() - 1].length - 1) ) then
@crossword[row][column] = '*'
-1.upto(1) do |row_offset|
-1.upto(1) do |column_offset|
should_be_star(row + row_offset, column + column_offset)
end
end
end
-1.upto(1) do |row_offset|
-1.upto(1) do |column_offset|
if(!(row_offset == 0) && !(column_offset == 0)) then
next
end
if(defined? @crossword[row+row_offset][column+column_offset]) then
if(@crossword[row+row_offset][column+column_offset] == '*') then
@crossword[row][column] = '*'
-1.upto(1) do |row_offset_inner|
-1.upto(1) do |column_offset_inner|
if((defined? @crossword[row+row_offset_inner][column+column_offset_inner]) && (@crossword[row+row_offset_inner][column+column_offset_inner] == 'X')) then
should_be_star(row + row_offset_inner, column + column_offset_inner)
end
end
end
end
end
end
end
end
def define_separators
line = Array.new()
0.upto(@crossword.length() - 1) do |row|
line = @crossword[row]
@row_separators[row] = Array.new()
@column_separators[row] = Array.new()
0.upto(line.length() - 1) do |column|
(is_star(row-1,column) && is_star(row,column)) ?
@row_separators[row].push(0) : @row_separators[row].push(1)
(is_star(row,column - 1) && is_star(row,column)) ?
@column_separators[row].push(0) : @column_separators[row].push(1)
end
is_star(row,line.length() - 1) ?
@column_separators[row].push(0) : @column_separators[row].push(1)
end
@row_separators[@crossword.length()] = Array.new()
0.upto(@crossword[@crossword.length() - 1].length - 1) do |column|
is_entry(@crossword.length() - 1,column) ?
@row_separators[@crossword.length()].push(1) : @row_separators[@crossword.length()].push(0)
end
end
def is_entry(row, column)
if((row < 0) || (column < 0)) then return false end
if(row > @crossword.length - 1) then return false end
if(column > @crossword[row].length - 1) then return false end
if(@crossword[row][column].eql?('_')) then return true end
return false
end
def is_star(row, column)
if((row < 0) || (column < 0)) then return true end
if(row > @crossword.length - 1) then return true end
if(column > @crossword[row].length - 1) then return true end
if(@crossword[row][column].eql?('*')) then return true end
return false
end
def print_crossword()
0.upto(@row_separators.length - 2) do |row|
column_seps = @column_separators[row]
0.upto(@row_separators[row].length - 1) do |column|
#@output_string += ( @row_separators[row][column] == 1 || column_seps[column] == 1) ? '#' : ' '
@output_string += (( @row_separators[row][column] == 1 || column_seps[column] == 1) ||
( (row > 0) && (@row_separators[row-1][column] == 1))) ? '#' : ' '
@output_string += ( @row_separators[row][column] == 1 ) ? '#' * @cell_width : ' ' * @cell_width
end
@output_string += (@row_separators[row][@row_separators[row].length-1] == 1 || column_seps[column_seps.length-1] == 1) ? '#' : ' '
@output_string += "\n"
number_string = ''
body_string = ''
0.upto(@row_separators[row].length - 1) do |column|
body_string += column_seps[column] == 1 ? '#' : ' '
number_string += column_seps[column] == 1 ? '#' : ' '
if(((!is_entry(row - 1, column) && is_entry(row + 1, column)) ||
(!is_entry(row, column - 1) && is_entry(row, column + 1))) &&
(@crossword[row][column] == '_')) then
body_string += ' ' * @cell_width
number_string += sprintf("%-#{@cell_width}d", @clue_number);
@clue_number += 1
else
body_string += @crossword[row][column] == 'X' ? '#' * @cell_width : ' ' * @cell_width
number_string += @crossword[row][column] == 'X' ? '#' * @cell_width : ' ' * @cell_width
end
end
body_string += column_seps[column_seps.length-1] == 1 ? "#\n" : " \n"
number_string += column_seps[column_seps.length-1] == 1 ? "#\n" : " \n"
1.upto(cell_height) do |print_iter|
print_iter == 1 ? @output_string += number_string : @output_string += body_string
end
end
0.upto(@row_separators[@row_separators.length - 1].length - 1) do |column|
@output_string += ( @row_separators[@row_separators.length - 1][column] == 1 ) ? '#' : ' '
@output_string += ( @row_separators[@row_separators.length - 1][column] == 1 ) ? '#' * @cell_width : ' ' * @cell_width
end
@output_string += @row_separators[@row_separators.length - 1][@row_separators[@row_separators.length - 1].length-1] == 1 ? '#' : ' '
@output_string += "\n"
print @output_string
end
end
end
| true
|
3313c07f5c9942f35d1d3a815fd02207adeda02d
|
Ruby
|
FreddieR96/negotiator-timetable
|
/app/helpers/main_helper.rb
|
UTF-8
| 212
| 2.65625
| 3
|
[] |
no_license
|
module MainHelper
class Result
attr_reader :arrive_at, :label, :leave_at
def initialize(arrival, label, leave = 30)
@arrive_at = arrival
@label = label
@leave_at = @arrive_at + leave.minutes
end
end
end
| true
|
915e671507f7e341eb4b07a1b97f77ce743e5636
|
Ruby
|
tkbeili/august_2016_fundamentals
|
/ruby_3/cat.rb
|
UTF-8
| 293
| 4.03125
| 4
|
[] |
no_license
|
require "./animal.rb"
class Cat < Animal
def catch(bird)
@bird = bird
puts "The cat #{@name} caught bird #{bird.name}"
end
def eat
if @bird
puts "The car #{@name} ate the bird #{@bird.name}"
@bird = nil
else
puts "No bird to eat!"
end
end
end
| true
|
4658d75d6b7a8b286d39bc3b6aa7b8ae6f500ef5
|
Ruby
|
dbrewster42/Ruby
|
/Project TDD/project_spec.rb
|
UTF-8
| 1,374
| 3.390625
| 3
|
[] |
no_license
|
require_relative 'project'
# include our Project class in our spec file
RSpec.describe Student do
before(:each) do
@project1 = Student.new('Project 1', 'description 1')
@project2 = Student.new('Project 2', 'description 2')
# create a new project and make sure we can set the name attribute
end
it 'has a method elevator_pitch to explain name and description' do
expect(@project1.elevator_pitch).to eq("Project 1, description 1")
expect(@project2.elevator_pitch).to eq("Project 2, description 2")
end
it 'has a getter and setter for name attribute' do
@project1.name = "Changed Name"
# this line would fail if our class did not have a setter method
expect(@project1.name).to eq("Changed Name")
# this line would fail if we did not have a getter or if it did not change the name successfully in the previous line.
end
it 'testing owner' do
@project2.owner = "George Washington"
expect(@project1.owner).to eq(nil)
expect(@project2.owner).to eq("George Washington")
end
it 'testing tasks' do
@project1.add_tasks("do the laundry")
@project1.add_tasks("wash the car")
@project1.add_tasks("make money")
expect(@project1.show_tasks).to eq(["do the laundry", "wash the car", "make money"])
expect{@project1.print_tasks}.to output(["do the laundry", "wash the car", "make money"])
end
end
| true
|
15b0d398a52318cd07724a60d10b4a12396d977f
|
Ruby
|
NguyenTuanLong/Rails
|
/app/models/post.rb
|
UTF-8
| 1,030
| 2.71875
| 3
|
[] |
no_license
|
class Post < ApplicationRecord
belongs_to :user
before_destroy :check_if_has_line_item
validate :check_if_price_and_cost
validates :title, :body, :price, :cost, :quantity, presence: true
validates :price, numericality: {greater_than_or_equal_to: 1000}
validates :cost, numericality: {greater_than_or_equal_to: 1000}
validates :quantity, numericality: {greater_than_or_equal_to: 0}
validates :title, uniqueness: {scope: :user_id}
has_many :line_items, dependent: :destroy
has_one_attached :image, dependent: false
def self.search(search)
if search
where('body LIKE ? OR title LIKE ?', "%#{search}%", "%#{search}%")
else
all
end
end
private
def check_if_has_line_item
if line_items.any?
errors.add(:base, 'This product has a LineItem')
throw(:abort)
end
end
def check_if_price_and_cost
errors.add(:cost, "cost can't be larger than price") unless price > cost
end
end
| true
|
f6a989b2cd1ee6dbcbccd0a0a7aa184be867080c
|
Ruby
|
juanmaberrocal/game-scoreboard
|
/app/helpers/slash_command_action_service_picker.rb
|
UTF-8
| 637
| 2.671875
| 3
|
[] |
no_license
|
class SlashCommandActionServicePicker
attr_reader :action, :model
def initialize(action, model)
@action = action
@model = model
end
def select(params)
service_string = "#{SLASH_COMMAND_ACTIONS_PREFIX}"\
"#{model}_#{action}"\
"#{SLASH_COMMAND_ACTIONS_SUFIX}".classify
service_klass = service_string.constantize
service = service_klass.new(params)
rescue => e
raise InvalidSlashCommand.new("#{action}:#{model} #{params}")
end
private
SLASH_COMMAND_ACTIONS_PREFIX = 'slash_command_actions/'.freeze
SLASH_COMMAND_ACTIONS_SUFIX = '_service'.freeze
end
| true
|
c5b84ae05921c8346a17ad1d02b1dabe2dd1fd58
|
Ruby
|
fytzzz/easy-blog
|
/app/models/setting.rb
|
UTF-8
| 3,178
| 2.59375
| 3
|
[] |
no_license
|
# encoding: utf-8
# renfences Redmine - project management software
class Setting < ActiveRecord::Base
DATE_FORMATS = [
'%Y-%m-%d',
'%d/%m/%Y',
'%d.%m.%Y',
'%d-%m-%Y',
'%m/%d/%Y',
'%d %b %Y',
'%d %B %Y',
'%b %d, %Y',
'%B %d, %Y'
]
TIME_FORMATS = [
'%H:%M',
'%I:%M %p'
]
cattr_accessor :available_settings
@@available_settings = YAML::load(File.open("#{Rails.root}/config/settings.yml"))
validates_uniqueness_of :name
validates_inclusion_of :name, :in => @@available_settings.keys
validates_numericality_of :value, :only_integer => true, :if => Proc.new { |setting| @@available_settings[setting.name]['format'] == 'int' }
# Hash used to cache setting values
@cached_settings = {}
@cached_cleared_on = Time.now
def value
v = read_attribute(:value)
# Unserialize serialized settings
v = YAML::load(v) if @@available_settings[name]['serialized'] && v.is_a?(String)
v = v.to_sym if @@available_settings[name]['format'] == 'symbol' && !v.blank?
v
end
def value=(v)
v = v.to_yaml if v && @@available_settings[name] && @@available_settings[name]['serialized']
write_attribute(:value, v.to_s)
end
# Returns the value of the setting named name
def self.[](name)
v = @cached_settings[name]
v ? v : (@cached_settings[name] = find_or_default(name).value)
end
def self.[]=(name, v)
setting = find_or_default(name)
setting.value = (v ? v : "")
@cached_settings[name] = nil
setting.save
setting.value
end
# Defines getter and setter for each setting
# Then setting values can be read using: Setting.some_setting_name
# or set using Setting.some_setting_name = "some value"
@@available_settings.each do |name, params|
src = <<-END_SRC
def self.#{name}
self[:#{name}]
end
def self.#{name}?
self[:#{name}].to_i > 0
end
def self.#{name}=(value)
self[:#{name}] = value
end
END_SRC
class_eval src, __FILE__, __LINE__
end
# Helper that returns an array based on per_page_options setting
def self.per_page_options_array
per_page_options.split(%r{[\s,]}).collect(&:to_i).select { |n| n > 0 }.sort
end
def self.openid?
Object.const_defined?(:OpenID) && self[:openid].to_i > 0
end
# Checks if settings have changed since the values were read
# and clears the cache hash if it's the case
# Called once per request
def self.check_cache
settings_updated_at = Setting.maximum(:updated_at)
if settings_updated_at && @cached_cleared_on <= settings_updated_at
@cached_settings.clear
@cached_cleared_on = Time.now
logger.info "Settings cache cleared." if logger
end
end
private
# Returns the Setting instance for the setting named name
# (record found in database or new record with default value)
def self.find_or_default(name)
name = name.to_s
raise "There's no setting named #{name}" unless @@available_settings.has_key?(name)
setting = find_by_name(name)
setting ||= new(:name => name, :value => @@available_settings[name]['default']) if @@available_settings.has_key? name
end
end
| true
|
d2864ebb8c5ea1f512986ace04248d116269fcb4
|
Ruby
|
vdpham326/Ruby_Intro
|
/conditionals_arrays/doubler.rb
|
UTF-8
| 215
| 3.765625
| 4
|
[] |
no_license
|
def doubler(number)
new_arr = []
i = 0
while i < number.length
new_arr << number[i] * 2
i += 1
end
return new_arr
end
print doubler([1, 2, 3, 4])
puts
print doubler([7, 1, 8])
| true
|
b53bb6ede065cf1fc41433ea850131bec86e37f2
|
Ruby
|
sjbach/lusty
|
/src/lusty/buffer-grep.rb
|
UTF-8
| 5,981
| 2.65625
| 3
|
[] |
no_license
|
# Copyright (C) 2007 Stephen Bach
#
# Permission is hereby granted to use and distribute this code, with or without
# modifications, provided that this copyright notice is copied with it. Like
# anything else that's free, this file is provided *as is* and comes with no
# warranty of any kind, either expressed or implied. In no event will the
# copyright holder be liable for any damages resulting from the use of this
# software.
# TODO:
# - some way for user to indicate case-sensitive regex
# - add slash highlighting back to file name?
module LustyM
class BufferGrep < Explorer
public
def initialize
super
@display.single_column_mode = true
@prompt = Prompt.new
@buffer_entries = []
@matched_strings = []
# State from previous run, so you don't have to retype
# your search each time to get the previous entries.
@previous_input = ''
@previous_grep_entries = []
@previous_matched_strings = []
@previous_selected_index = 0
end
def run
return if @running
@prompt.set! @previous_input
@buffer_entries = GrepEntry::compute_buffer_entries()
@selected_index = @previous_selected_index
super
end
private
def title
'LustyExplorer--BufferGrep'
end
def set_syntax_matching
VIM::command 'syn clear LustyGrepFileName'
VIM::command 'syn clear LustyGrepLineNumber'
VIM::command 'syn clear LustyGrepContext'
# Base syntax matching -- others are set on refresh.
VIM::command \
'syn match LustyGrepFileName "^\zs.\{-}\ze:\d\+:" ' \
'contains=NONE ' \
'nextgroup=LustyGrepLineNumber'
VIM::command \
'syn match LustyGrepLineNumber ":\d\+:" ' \
'contained ' \
'contains=NONE ' \
'nextgroup=LustyGrepContext'
VIM::command \
'syn match LustyGrepContext ".*" ' \
'transparent ' \
'contained ' \
'contains=LustyGrepMatch'
end
def on_refresh
if VIM::has_syntax?
VIM::command 'syn clear LustyGrepMatch'
if not @matched_strings.empty?
sub_regexes = @matched_strings.map { |s| VIM::regex_escape(s) }
syntax_regex = '\%(' + sub_regexes.join('\|') + '\)'
VIM::command "syn match LustyGrepMatch \"#{syntax_regex}\" " \
"contained " \
"contains=NONE"
end
end
end
def highlight_selected_index
VIM::command 'syn clear LustySelected'
entry = @current_sorted_matches[@selected_index]
return if entry.nil?
match_string = "#{entry.short_name}:#{entry.line_number}:"
escaped = VIM::regex_escape(match_string)
VIM::command "syn match LustySelected \"^#{match_string}\" " \
'contains=NONE ' \
'nextgroup=LustyGrepContext'
end
def current_abbreviation
@prompt.input
end
def compute_sorted_matches
abbrev = current_abbreviation()
grep_entries = @previous_grep_entries
@matched_strings = @previous_matched_strings
@previous_input = ''
@previous_grep_entries = []
@previous_matched_strings = []
@previous_selected_index = 0
if not grep_entries.empty?
return grep_entries
elsif abbrev == ''
@buffer_entries.each do |e|
e.label = e.short_name
end
return @buffer_entries
end
begin
regex = Regexp.compile(abbrev, Regexp::IGNORECASE)
rescue RegexpError => e
return []
end
max_visible_entries = Display.max_height
# Used to avoid duplicating match strings, which slows down refresh.
highlight_hash = {}
# Search through every line of every open buffer for the
# given expression.
@buffer_entries.each do |entry|
vim_buffer = entry.vim_buffer
line_count = vim_buffer.count
(1..line_count). each do |i|
line = vim_buffer[i]
match = regex.match(line)
if match
matched_str = match.to_s
grep_entry = entry.clone()
grep_entry.line_number = i
grep_entry.label = "#{grep_entry.short_name}:#{i}:#{line}"
grep_entries << grep_entry
# Keep track of all matched strings
unless highlight_hash[matched_str]
@matched_strings << matched_str
highlight_hash[matched_str] = true
end
if grep_entries.length > max_visible_entries
return grep_entries
end
end
end
end
return grep_entries
end
def open_entry(entry, open_mode)
cleanup()
LustyM::assert($curwin == @calling_window)
number = entry.vim_buffer.number
LustyM::assert(number)
cmd = case open_mode
when :current_tab
"b"
when :new_tab
# For some reason just using tabe or e gives an error when
# the alternate-file isn't set.
"tab split | b"
when :new_split
"sp | b"
when :new_vsplit
"vs | b"
else
LustyM::assert(false, "bad open mode")
end
# Open buffer and go to the line number.
VIM::command "silent #{cmd} #{number}"
VIM::command "#{entry.line_number}"
end
def cleanup
@previous_input = @prompt.input
@previous_grep_entries = @current_sorted_matches
@previous_matched_strings = @matched_strings
@previous_selected_index = @selected_index
super
end
end
end
| true
|
302869c36753941618aa9fe33ef8c6435f4d7cef
|
Ruby
|
PhilippaElliott/intro_to_ruby
|
/chapter_4/all_caps.rb
|
UTF-8
| 171
| 3.53125
| 4
|
[] |
no_license
|
def all_caps(string)
if string.length > 10
string.upcase!
else
string
end
end
puts all_caps("I think this is wrong")
puts all_caps("maybe not")
| true
|
c8531166f7ac185c983879b4c4b54f0843e7ddf9
|
Ruby
|
Atar97/W2D1-projects
|
/chess/display.rb
|
UTF-8
| 506
| 3.109375
| 3
|
[] |
no_license
|
require 'colorize'
require_relative 'board'
require_relative 'cursor'
class Display
attr_reader :cursor
def initialize(board=Board.new)
@board = board
@cursor = Cursor.new([0,0],@board)
end
def render
system('clear to start')
puts @board.render(@cursor.cursor_pos)
end
def move_cursor
@cursor.get_input
end
end
if __FILE__== $PROGRAM_NAME
b = Board.new
d = Display.new(b)
d.render
while d.cursor.go
d.move_cursor
d.render
end
end
| true
|
f1fbf6cdfd8a063519a04e2a4a6ca988a76d7f3c
|
Ruby
|
tannerwelsh/code-training
|
/ruby/Learn to Program/ages.rb
|
UTF-8
| 447
| 3.734375
| 4
|
[
"MIT"
] |
permissive
|
hours = 24 * 365
puts 'There are ' + hours.to_s + ' hours in a year'
minutes = 60 * 24 * ((365 * 8) + (366 * 2))
alt_minutes = 60 * 24 * 365 * 10
puts "There are #{minutes} minutes in a decade. Or is it #{alt_minutes}? I'm not sure."
my_age_in_seconds = 24 * 365 * 24 * 60 * 60
puts "I am #{my_age_in_seconds} seconds old."
authors_age_in_seconds = 1025000000 / (365 * 24 * 60 * 60)
puts "The author is #{authors_age_in_seconds} years old."
| true
|
e99d050c1cc3fafcca19ba341e2d682f91156eb5
|
Ruby
|
ygorxds/RUBY-BASIC-COMMANDS
|
/case.rb
|
UTF-8
| 196
| 3.578125
| 4
|
[] |
no_license
|
puts ("Insira a idade:")
idade = gets.chomp.to_i
case idade
when 0..2
puts("bebe")
when 3..12
puts ("Criança")
when 13..18
puts "adolescente"
else
puts "adulto"
end
| true
|
4492fe19a766e6beb76512f17fc96505714c2c43
|
Ruby
|
felipernb/project-euler
|
/euler_45.rb
|
UTF-8
| 354
| 3.546875
| 4
|
[] |
no_license
|
def is_triangle?(tn)
n = (-1 + Math.sqrt(1+8*tn))/2
n == n.to_i
end
def triangle(n)
n*(n+1)/2
end
def is_pentagonal?(n)
p = (Math.sqrt(1+24*n)+1)/6
p == p.to_i
end
def is_hexagonal?(hn)
n = (1+Math.sqrt(1+8*hn))/4
n == n.to_i
end
n = 286
i = triangle(n)
while not (is_pentagonal?(i) and is_hexagonal?(i)) do
n+=1
i = triangle(n)
end
puts i
| true
|
203f321101d92a03390b991376098ccecba029e8
|
Ruby
|
kuroneko995/cosc480-hw2
|
/part2.rb
|
UTF-8
| 1,393
| 3.71875
| 4
|
[] |
no_license
|
require 'date'
class Numeric
@@currencies = {'yen' => 0.0065, 'euro' => 1.15, 'rupee' => 0.016}
def method_missing(method_id, *args)
singular_currency = method_id.to_s.gsub( /s$/, '')
if @@currencies.has_key?(singular_currency)
self * @@currencies[singular_currency]
else
super
end
end
def in(currency)
singular_currency = currency.to_s.gsub(/s$/, '')
self / @@currencies[singular_currency]
end
end
class String
def palindrome?
str = self.gsub(/\W/,'').downcase
return str == str.reverse
end
end
class DateTime
def humanize
hour_str = {0=>'midnight', 1=>'one', 2=>'two', 3=>'three', 4=>'four',\
5=>'five', 6=>'six', 7=>'seven', 8=>'eight', 9=>'nine', \
10=>'ten', 11=>'eleven', 12=>'twelve'}
minute_str = {30 => 'half past', 15=> 'a quarter past', \
45=> 'a quarter till'}
hour = self.strftime(format='%H').to_i
minute = self.strftime(format='%M').to_i
result = ''
result << 'about' << ' ' unless minute % 15 == 0 # Precise time
minute = minute - minute % 15
result << minute_str[minute] << ' ' unless minute == 0
if minute == 45 then hour = (hour + 1)% 24 end
result << hour_str[hour]
result.capitalize
end
end
| true
|
5dc5f43d62843bd4f3293687640850fe307e358f
|
Ruby
|
fragkakis/advent_of_code
|
/2021/day8/part1.rb
|
UTF-8
| 315
| 3.5
| 4
|
[
"MIT"
] |
permissive
|
module Day8
class Part1
def solve(input)
output_signals = input.split("\n").map{|line| line.split(" | ")[1].split(" ")}.flatten
output_signals.select{|signal| digit_of_interest?(signal)}.size
end
def digit_of_interest?(signal)
[2, 3, 4, 7].include?(signal.length)
end
end
end
| true
|
2f1184714d93bd3ae8ef6cb61218156452b6fb57
|
Ruby
|
progpyftk/learn_to_code_with_ruby_udemy
|
/Section 9/challenge_2_each_index.rb
|
UTF-8
| 303
| 3.671875
| 4
|
[] |
no_license
|
# print the product of element x its index, only if index pos is greater than the element
fives = [-1, 1, 2, 3, 5, 7, 3, 4, 8, 9]
fives.each_with_index do |each, index|
if index > each
puts "Element: #{each} Index: #{index}"
puts "Element x Index = #{each * index}"
end
end
| true
|
522a6e0f2ac6b9f49808ae00dec07c9f69745f61
|
Ruby
|
peterckim/basketball-statistics-app
|
/lib/tasks/get_game_data.rake
|
UTF-8
| 2,496
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
task :get_game_data do
require 'nokogiri'
require 'open-uri'
page = Nokogiri::HTML(open(url))
gameDate = page.css('.scorebox').css('.scorebox_meta > div')[0].text
parseGameDate = gameDate.split(", ")
actualGameDate = "#{parseGameDate[1]}, #{parseGameDate[2]}"
player_game_hash = {
game: {
home: page.css('.scorebox').css('[itemprop="performer"]')[0].css('[itemprop="name"]').text,
away: page.css('.scorebox').css('[itemprop="performer"]')[1].css('[itemprop="name"]').text,
home_score: page.css('.scorebox').css('.score')[0].text,
away_score: page.css('.scorebox').css('.score')[1].text,
date: actualGameDate
},
players: []
}
tableArray = page.css('table').to_a
tableArray.select! do |table|
table.attribute("id").text.include? "basic"
end
tableArray.each do |table|
playerArray = table.css('tbody').css('tr').to_a
playerArray.delete_at(5)
playerArray.each do |playerObject|
playerName = playerObject.css('[data-stat="player"]').text.split(" ")
player_game_attribute_hash = {
player: {
first_name: playerName[0],
last_name: playerName[1]
},
player_game: {
field_goal_made: playerObject.css('[data-stat="fg"]').text.to_i,
field_goal_attempted: playerObject.css('[data-stat="fga"]').text.to_i,
free_throw_made: playerObject.css('[data-stat="ft"]').text.to_i,
free_throw_attempted: playerObject.css('[data-stat="fta"]').text.to_i,
three_point_made: playerObject.css('[data-stat="fg3"]').text.to_i,
three_point_attempted: playerObject.css('[data-stat="fg3a"]').text.to_i,
points: playerObject.css('[data-stat="pts"]').text.to_i,
rebounds: playerObject.css('[data-stat="trb"]').text.to_i,
assists: playerObject.css('[data-stat="ast"]').text.to_i,
steals: playerObject.css('[data-stat="stl"]').text.to_i,
blocks: playerObject.css('[data-stat="blk"]').text.to_i,
turnovers: playerObject.css('[data-stat="tov"]').text.to_i
}
}
player_game_hash[:players] << player_game_attribute_hash
end
end
return player_game_hash
end
| true
|
8b3c788c4665d6d677b92d226b8d8695397ab00f
|
Ruby
|
customink/ft2-ruby
|
/examples/test_ft2.rb
|
UTF-8
| 655
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
require 'ft2'
puts FT2::version
puts FT2::VERSION
face = FT2::Face.new 'fonts/yudit.ttf'
puts "glyphs: #{face.glyphs}",
"charmaps: #{face.num_charmaps}",
"horiz: #{face.horizontal?}",
"vert: #{face.vertical?}"
# cycle through default charmap
puts 'listing character codes with first_char/next_char'
c_code, g_idx = face.first_char
while g_idx != 0
puts "#{c_code} => " << face.glyph_name(g_idx)
c_code, g_idx = face.next_char c_code
end
puts 'listing charcodes with current_charmap'
cmap = face.current_charmap
cmap.keys.sort.each { |c_code|
puts "#{c_code} => " << face.glyph_name(cmap[c_code])
}
| true
|
8618b8c71071bad0e7e1dad10a16bf878e633e65
|
Ruby
|
siphomsiza/platform45-mars-rover-assessment
|
/app/helpers/rover_platos_helper.rb
|
UTF-8
| 431
| 2.578125
| 3
|
[] |
no_license
|
module RoverPlatosHelper
def rover_plato_position(x, y)
if @rover_plato.position[[x, y]]
rover_image
else
"fa fa-times fa-3x"
end
end
def rover_image
image_rules = {'E' => "fa fa-arrow-right fa-3x",
'N' => "fa fa-arrow-up fa-3x",
'W' => "fa fa-arrow-left fa-3x",
'S' => "fa fa-arrow-down fa-3x"}
image_rules[@rover.direction]
end
end
| true
|
64feb79fdb47b5470570f8884ac0fed48ddca65b
|
Ruby
|
rudyoyen/cStore
|
/spec/scenario_spec.rb
|
UTF-8
| 667
| 2.671875
| 3
|
[] |
no_license
|
require 'spec_helper'
require 'config'
describe 'Scenario' do
before {
@scenario = Scenario.new
@count_symbol = Config::ITEM_COUNT_SYMBOL
}
# additional tests related to the scenario run inside store, orders, and promo classes
describe '#run' do
it 'returns an output as a Hash' do
order = @scenario.run({"cash"=>12, "price"=>2, "wrappers needed"=>5, "type"=>"milk"})
expect(order.is_a? Hash).to eq(true)
end
it 'returns an order with the item requested' do
order = @scenario.run({"cash"=>12, "price"=>2, "wrappers needed"=>5, "type"=>"milk"})
expect(order['milk'][@count_symbol]).to be > 0
end
end
end
| true
|
e6b51b6d5ae4d0c64e121237853afb31cbae3440
|
Ruby
|
MarcinCebula/github-services
|
/services/crisply_api.rb
|
UTF-8
| 4,796
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
require 'rubygems'
require 'rest_client'
require 'nokogiri'
class CrisplyApi
def self.post_activity options
##Don't like something about this. Think about it later
resource = CrisplyApi.new(options)
resource.override_defaults_with options
project_id = resource.get_project_id_by_name options[:project]
params = resource.override_defaults_with({:project_id => project_id})
activity_item = resource.build_xml_request params
resource.create_new_activity activity_item
end
def self.get(uri, key)
## Remainder: Way too much shit happening!!!
url = URI.parse uri
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = (url.scheme == 'https')
http.instance_eval { @ssl_context = OpenSSL::SSL::SSLContext.new(:TLSv1) }
request = Net::HTTP::Get.new(url.path)
CrisplyApi.headers.each { |key, value| request.add_field(key, value) }
request.add_field("X-Crisply-Authentication", key)
response = http.start {|http| http.request(request) }
XmlSimple.xml_in(response.body)
end
def self.post(uri, key, xml)
## Remainder: Way too much shit happening!!!
url = URI.parse uri
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = (url.scheme == 'https')
http.instance_eval { @ssl_context = OpenSSL::SSL::SSLContext.new(:TLSv1) }
request = Net::HTTP::Post.new(url.path)
CrisplyApi.headers.each { |key, value| request.add_field(key, value) }
request.add_field("X-Crisply-Authentication", key)
request.content_type = 'text/xml'
request.body = xml
response = http.start {|http| http.request(request) }
end
def self.defaults
defaults = {}
defaults[:account] = ""
defaults[:author] = ""
defaults[:key] = defaults[:token] = ""
defaults[:text] = ""
defaults[:date] = Time.now
defaults[:guid] = 'post-activity-' + Time.now.to_f.to_s + "-" + Kernel.rand(2**64).to_s
defaults[:project_id] = ""
defaults[:duration] = '1'
defaults[:type] = "task"
defaults[:deployment_domain] = "crisply.com"
# defaults[:verbose] = "--[no-]verbose"
# defaults[:tag] = list
defaults
end
def self.headers
{
'Content-Type' => 'application/xml',
'Accept' => 'application/xml; charset=utf-8'
}
end
## CrisplyApi should do data calls like POST, GET, PUT, DELETE and be
## a public API for what the resource classes are doing.
## Even better if POST, GET, PUT, DELETE were in a base class.
## No need for the programmer to worry about how the calls are being made
##
##----------------------------------------------------------------------------------------------
## This should be its own class or classes
## Projects and Activities or something like that
##
## It might be a good idea to wrap all the @params in function for easier testing mocking/stubing
##
##
## If this code didn't live inside this project I would change how these function interact.
## There is absolutally no reason why get_projects should be a function. It should be part
## of the Projects resource. I hate writing bad code and knowing it's bad. I WILL REFACTOR THIS LATER
def initialize options
@defaults = CrisplyApi.defaults
@params = override_defaults_with options
end
def get_projects
CrisplyApi.get(projects_url, @params[:token])
end
def create_new_activity(activity_item)
CrisplyApi.post(activity_items_url, @params[:token], activity_item)
end
def account_url
"https://#{@params[:account]}.crisply.com/timesheet/api"
end
def projects_url
"#{account_url}/projects.xml"
end
def activity_items_url
"#{account_url}/activity_items.xml"
end
def override_defaults_with options
@defaults.each do |key, value|
if options[key]
@defaults[key] = options[key]
end
end
end
def get_project_id_by_name(project_name)
projects = (CrisplyApi.get(projects_url, @defaults[:token]))['project']
projects.each do |project|
if project['name'].first == project_name
return project['id']
end
end
raise 'Incorrect project name'
end
def build_xml_request options
options[:date] = options[:date].xmlschema if options[:date]
builder = Nokogiri::XML::Builder.new do |xml|
xml.send('activity-item',
'xmlns' => 'http://crisply.com/api/v1') {
[:guid, :text, :date, :type, :author, :duration, :project_id].each do |attr|
value = options[attr]
unless value.nil?
xml.send((attr.to_s.gsub('_','-') + '_').to_sym, value)
end
end
if options[:tag]
xml.tags {
options[:tag].each do |tag|
xml.tag tag
end
}
end
}
end
xml = builder.to_xml
end
end
| true
|
2ec0975e1d6ee0751fea2217c7c71a3899e83ee4
|
Ruby
|
LinglingChen/aa_projects
|
/chess_project/game.rb
|
UTF-8
| 1,244
| 3.46875
| 3
|
[] |
no_license
|
require_relative 'board'
require_relative 'human_player'
require_relative 'computer_player'
class Game
attr_reader :board,:players,:display,:current_player
def initialize
@board=Board.new
@display=Display.new(@board)
@players={
:white => HumanPlayer.new(:white,@display),
:black => ComputerPlayer.new(:black,@display)
}
@current_player=:white
end
def play
until board.checkmate?(current_player)
begin
start_pos,end_pos=players[current_player].make_move(board)
board.move_piece(current_player,start_pos,end_pos)
swap_turn
notify_players
rescue StandardError => e
@display.notifications[:error]=e.message
retry
end
end
display.render
puts "#{current_player} is checked!"
nil
end
private
def notify_players
if board.in_check?(current_player)
display.set_check
else
display.uncheck
end
end
def swap_turn
@current_player= (current_player==:white) ? :black : :white
end
end
if $PROGRAM_NAME == __FILE__
Game.new.play
end
| true
|
53bc8ee18d8ba058d09bb667df20a939d4837f2f
|
Ruby
|
Su0414/sinatra-nested-forms-v-000
|
/app/models/pirate.rb
|
UTF-8
| 353
| 3.109375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Pirate
attr_accessor :name, :weight, :height
@@pirate = []
def initialize(name, weight, height)
@name = name
@weight = weight
@height = height
save
end
def self.ships
@ships
end
def save
@@pirate << self
@@pirate
end
def self.all
@@pirate
end
def self.clear
@@pirate.clear
end
end
| true
|
4fe698999d42bd4f69f7021add15400b31df06ca
|
Ruby
|
danbriechle/calculator
|
/app/models/calc.rb
|
UTF-8
| 735
| 3.328125
| 3
|
[] |
no_license
|
class Calc
def self.calculate(math_string)
result = 0
# multiply
math_string.scan(/(\d*)([*])(\d*)/).each do |array|
result += array[0].to_f * array[2].to_f
math_string.sub!(array.join,"")
end
#divide
math_string.scan(/(\d*)([\/])(\d*)/).each do |array|
result += array[0].to_f / array[2].to_f
math_string.sub!(array.join,"")
end
#add
math_string.scan(/(\d*)([+])(\d*)/).each do |array|
result += array[0].to_f + array[2].to_f
math_string.sub!(array.join,"")
end
#subtract
math_string.scan(/(\d*)([-])(\d*)/).each do |array|
result += array[0].to_f - array[2].to_f
math_string.sub!(array.join,"")
end
result.round(2)
end
end
| true
|
3312e6c924513c145a929f5424f41b8371eaafd4
|
Ruby
|
EthWorks/ethereum.rb
|
/lib/ethereum/transaction.rb
|
UTF-8
| 994
| 2.84375
| 3
|
[
"MIT",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
module Ethereum
class Transaction
DEFAULT_TIMEOUT = 300.seconds
DEFAULT_STEP = 5.seconds
attr_accessor :id, :mined, :connection, :input, :input_parameters
def initialize(id, connection, data, input_parameters = [])
@mined = false
@connection = connection
@id = id
@input = data
@input_parameters = input_parameters
end
def address
@id
end
def mined?
return true if @mined
tx = @connection.eth_get_transaction_by_hash(@id)
@mined = !tx.nil? && !tx["result"].nil? && tx["result"]["blockNumber"].present?
end
def wait_for_miner(timeout: DEFAULT_TIMEOUT, step: DEFAULT_STEP)
start_time = Time.now
loop do
raise Timeout::Error if ((Time.now - start_time) > timeout)
return true if self.mined?
sleep step
end
end
def self.from_blockchain(address, connection = IpcClient.new)
Transaction.new(address, connection, nil, nil)
end
end
end
| true
|
acdffa4b3dc5108930586646cf2faca2986be633
|
Ruby
|
zhangsu/seal
|
/demo/reverb.rb
|
UTF-8
| 1,052
| 2.828125
| 3
|
[
"WTFPL"
] |
permissive
|
require 'seal'
include Seal
Seal.startup
EFFECT = ARGV[0] || 'FOREST'
def print_constants(mod, level = 0)
mod.constants.each do |const_key|
const_val = mod.const_get(const_key)
puts ' ' * level + const_key.to_s
print_constants(const_val, level + 4) if const_val.is_a? Module
end
end
puts 'Available reverb presets:'
print_constants(Reverb::Preset)
puts 'Currently rendering: '
puts EFFECT
wolf = Source.new
wolf.buffer = Buffer.new('audio/wolf.ogg')
wolf.position = -5, 5, 0
crow = Source.new
crow.buffer = Buffer.new('audio/crow.ogg')
crow.position = 6, 3, 0
reverb = Reverb.new(Reverb::Preset.module_eval(EFFECT))
slot = EffectSlot.new(reverb)
[wolf, crow].each do |source|
source.feed(slot, 0)
Thread.new do
loop do
source.play if source.state != Source::State::PLAYING
sleep rand(3) + 5
end
end
end
puts "Hit enter to toggle reverb effect"
while $stdin.gets
if slot.effect
puts "Reverb off"
slot.effect = nil
else
puts "Reverb on"
slot.effect = reverb
end
end
Seal.cleanup
| true
|
fce0e319406ffda01c49a508ab96e89e6235034b
|
Ruby
|
henry-doan/sti-scaffolding-intro
|
/app/models/animal.rb
|
UTF-8
| 544
| 2.71875
| 3
|
[] |
no_license
|
class Animal < ActiveRecord::Base
# BASE CLASS
belongs_to :zoo
# Tell rails about STI column since we didn't use type
self.inheritance_column = :race
validates_presence_of :name
def self.races
%w(Lion Bear Elephant Ape Cat)
end
# Scopes
def self.lions
where(race: 'Lion')
end
def self.bears
where(race: 'Bear')
end
def self.elephants
where(race: 'Elephant')
end
def self.apes
where(race: 'Ape')
end
def self.cats
where(race: 'Cat')
end
def talk
raise "This must be overwritten in a child class"
end
end
| true
|
2e34691695e3d110772855b9f5a18472aa476fc6
|
Ruby
|
kieran-lockyer/challenges
|
/ruby/banking_app.rb
|
UTF-8
| 3,930
| 3.5625
| 4
|
[] |
no_license
|
begin
users = eval(File.open("balance.txt", 'a+') { |file| file.readline})
rescue EOFError => e
users = Hash.new
end
def authenticate(users)
attempts = 3
while attempts > 0
puts "#{attempts} attempts remaining"
print "Please enter your username: "
username = gets.chomp
print "Please enter your password: "
password = gets.chomp
if users.keys.include?(username)
if users[username]["password"] == password
puts "Welcome #{username}"
return username, users[username]["balance"], users[username]["history"]
else
puts "Your password is invalid"
attempts -= 1
end
else
puts "Your username is invalid"
attempts -= 1
end
end
puts "You have used all available attempts. Please try again later"
return false, false, false
end
def signup(users)
print "Please enter a username: "
username = gets.chomp
print "Please enter a password: "
password = gets.chomp
users[username] = {"password" => password,
"balance" => 0,
"history" => []}
return users, username
end
def display_balance(balance)
puts "Your balance is $#{balance}"
end
def deposit(balance, history)
print "How much would you like to depost: "
deposit_amount = gets.chomp.to_i
balance += deposit_amount
history.push("Deposited $#{deposit_amount}")
puts "Your new balance is #{balance}"
return balance, history
end
def withdraw(balance, history)
print "How much would you like to withdraw: "
withdraw_amount = gets.chomp.to_i
if balance >= withdraw_amount
balance -= withdraw_amount
history.push("Withdrew $#{withdraw_amount}")
puts "Your new balance is #{balance}"
return balance, history
else
puts "Insufficient funds!"
end
end
def history(history)
history.each { |transaction|
puts transaction
}
end
def exit(users, username, balance, history)
File.open("balance.txt", 'w') {|file| file.write(users)}
end
def main(users, username, balance, history)
running = true
while running
puts "What would you like to do? (Options: balance, deposit, withdraw, history, exit)"
options = gets.chomp
case options
when "balance"
display_balance(balance)
when "deposit"
balance, history = deposit(balance, history)
when "withdraw"
balance, history = withdraw(balance, history)
when "history"
history(history)
when "exit"
users[username]["balance"] = balance
users[username]["history"] = history
running = false
exit(users, username, balance, history)
break
else
puts "Invalid selection!"
end
print "Would you like to return to the main menu? (Y/N): "
if gets.chomp == "N"
users[username]["balance"] = balance
users[username]["history"] = history
exit(users, username, balance,)
running = false
break
else
print %x{clear}
end
end
return balance, history
end
running = true
while running
print %x{clear}
puts "Welcome to the banking app!"
print "Log In(l) or Sign Up(s) or Exit(e): "
choice = gets.chomp
case choice
when "l"
username, balance, history = authenticate(users)
if balance
balance, history = main(users, username, balance, history)
end
when "s"
users, username = signup(users)
balance, history = main(users, username, 0, [])
when "e"
exit(users, username, balance, history)
running = false
break
else
puts "Invalid selection!"
end
end
| true
|
0ace4fdae304eb8f968cfe19e3d0d07e52fa2cec
|
Ruby
|
hfitton/rubyexamples
|
/calc.rb
|
UTF-8
| 579
| 3.984375
| 4
|
[] |
no_license
|
puts 'Hi, what\'s your name?'
name = gets.chomp
puts 'Your first name is '+ name + '? What\'s your surname?'
surname = gets.chomp
puts 'So your name is ' + name + ' '+ surname + '. Got any middle names?'
middle = gets.chomp
puts 'Wow! ' + middle + ' ' +'is fabulous! Hello there, ' + name + ' ' + middle + ' ' + surname + ', I\'m Kitty, pleased to meet you!'
puts '15'.to_f
puts '99.999'.to_f
puts '99.999'.to_i
puts ''
puts '5 is my favorite number!'.to_i
puts 'Who asked you about 5 or whatever?'.to_i
puts 'Your momma did.'.to_f
puts ''
puts 'stringy'.to_s
puts 3.to_i
| true
|
2511323db66a61d5b4348ca5ea807a27d25516bc
|
Ruby
|
mocklerlab/genomics
|
/lib/genomics/io/blast/e_value.rb
|
UTF-8
| 1,253
| 3.171875
| 3
|
[] |
no_license
|
module Genomics
module IO
module BLAST
# This class represets an E-value, which formats itself properly for printing and limits the floating point effects of extremely
# small values. It effectively sub classes a Numeric by defering all numerical computation to the float class.
class EValue
attr_accessor :coefficient, :exponent
def initialize(coefficient, exponent = 0)
value = coefficient.to_f * 10 ** exponent
@coefficient, @exponent = ("%.5e" % value).split('e').map(&:to_f)
@exponent = @exponent.to_i
end
def <=>(other)
exponent_comparison = @exponent <=> other.exponent
return exponent_comparison unless exponent_comparison == 0
@coefficient <=> other.coefficient
end
def to_s(options = {})
options = { precision: 2 }.merge(options)
"%.#{options[:precision]}e" % to_f
end
def to_f
@coefficient.to_f * 10 ** @exponent
end
def method_missing(name, *args, &block)
ret = to_f.send(name, *args, &block)
ret.is_a?(Numeric) ? EValue.new(ret) : ret
end
end
end
end
end
| true
|
dcf4173bf4dca8ff4b19235a7ff8766632a0be4f
|
Ruby
|
scootcho/ctci_exercises
|
/3.4_tower_of_hanoi.rb
|
UTF-8
| 4,726
| 3.921875
| 4
|
[] |
no_license
|
# ### Problem:
# In the classic problem of the Towers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of an even larger one). You have the following constraints:
# (1) Only one disk can be moved at a time.
# (2) A disk is slid off the top of one tower onto the next rod.
# (3) A disk can only be placed on top of a larger disk.
# Write a program to move the disks from the first tower to the last using Stacks.
# ### Clarification:
# Is there a difference between Tower2 or Tower3? Or can we move the disks to either one as long as it's completed?
# Can we use Tower1 (the starting tower as buffer?
# ### Assumption:
# No difference between Tower2(T2) & Tower3(T3) as destination tower as long as disks are moved and stacked in ascending order.
# Use Tower1 as buffer
# ### Design Algorithm:
# This problem sounds like a good candidate for the Base Case and Build approach.
# Start with the smallest example and build on top of the previous.
# one of the towers acts as a buffer, as long as tower is completed on T2 or T3 is the same.
# Case n = 1; move D1 from T1 to T3. (D1 on T3)
# Case n = 2; continue form n = 1, move D2 from T1 to T2, D1 from T3 to T2. (D1,D2 on T2)
# Case n = 3; continue from n = 2; move D3 from T1 to T3, D1 from T2 to T1, D2 from T2 to T3, D1 from T2 to T3. (D1,D2,D3 on T3)
# Case n = 4; continue from n = 3; move D4 from T1 to T2, D1 from T3 to T2, D2 from T3 to T1, D1 from T2 to T1, D3 from T3 to T2, D1 from T1 to T3, D2 from T1 to T2, D1 from T3 to T2. (D1,D2,D3,D4 on T2)
# Once we start to see a pattern emerge we can work on the solution.
# In order to stack size n to destination, we have to stack n - 1 completely in the buffer. E.g., In order to move tower of 4 disks, we must first stack 1,2,3 in buffer first and move disk 4 to destination.
# ### Solution:
require_relative './lib/stack'
class Tower
attr_accessor :origin, :destination, :buffer
def initialize(num_disks)
raise ArgumentError, "Please supply a number greater than 1 for the disks in Tower" unless num_disks.is_a?(Fixnum)
@num_disks = num_disks
@origin = Stack.new()
@buffer = Stack.new()
@destination = Stack.new()
disks = (1..@num_disks).to_a.reverse
disks.each { |disk| @origin.push(disk) }
puts "Initialized Tower with #{@num_disks} disks"
@origin
end
def add(destination, disk)
if !destination.is_empty? && destination.peek <= disk
puts "Error placing disk #{disk}"
else
destination.push(disk)
puts "***** Result:"
puts destination
end
end
# move top from origin to destination
def move_top(origin, destination)
disk = origin.pop.data
add(destination, disk)
end
def move_disks(num_disks, origin, destination, buffer)
raise ArgumentError, "sorry you cannot move more disks than you have in the towers" if num_disks > @num_disks
if num_disks == 1
puts "***** Move Disc from:"
p origin
puts "***** To:"
p destination
move_top(origin, destination)
else
move_disks(num_disks - 1, origin, buffer, destination) # move top n - 1 disks from origin to buffer, using destination * as a buffer.
move_disks(1, origin, destination, buffer)
move_disks(num_disks - 1, buffer, destination, origin) # move top n - 1 disks from buffer to destination, using * origin as a buffer.
end
end
end
# ### Sample Output:
towers = Tower.new(5)
towers.move_disks(5, towers.origin, towers.destination, towers.buffer)
p towers
# => #<Tower:0x007fc0b29ba508 @num_disks=5, @origin=#<Stack:0x007fc0b29ba4e0 @top=#<Element:0x007fc0b29ba4b8 @data=nil, @next=nil>, @bottom=#<Element:0x007fc0b29ba4b8 @data=nil, @next=nil>>, @buffer=#<Stack:0x007fc0b29ba490 @top=#<Element:0x007fc0b29ba468 @data=nil, @next=nil>, @bottom=#<Element:0x007fc0b29ba468 @data=nil, @next=nil>>, @destination=#<Stack:0x007fc0b29ba440 @top=#<Element:0x007fc0b29b97e8 @data=1, @next=#<Element:0x007fc0b29b9860 @data=2, @next=#<Element:0x007fc0b29b9900 @data=3, @next=#<Element:0x007fc0b29b9a40 @data=4, @next=#<Element:0x007fc0b29ba418 @data=5, @next=nil>>>>>, @bottom=#<Element:0x007fc0b29ba418 @data=5, @next=nil>>>
# ### Additional Resources:
# http://codereview.stackexchange.com/questions/73400/towers-of-hanoi?newreg=c261754c1ce34906a9d351922a9623b8
# http://www.skorks.com/2010/03/solving-the-towers-of-hanoi-mathematically-and-programmatically-the-value-of-recursion/
# http://www.thelearningpoint.net/computer-science/introduction-to-ruby---towers-of-hanoi-an-example-of-recursion
# http://www.math.harvard.edu/computing/ruby/hanoi.rb
| true
|
4fdc012a070571c09b55c52fdfad6367f8f98fd4
|
Ruby
|
urbanquakers/pantograph
|
/Dangerfile
|
UTF-8
| 1,092
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
# We generally try to avoid big PRs
warn("Big PR") if git.lines_of_code > 500
# Show a warning for PRs that are Work In Progress
if (github.pr_body + github.pr_title).include?("WIP")
warn("Pull Request is Work in Progress")
end
# Contributors should always provide a changelog when submitting a PR
if github.pr_body.length < 5
warn("Please provide a changelog summary in the Pull Request description @#{github.pr_author}")
end
# PRs being made on a branch from a different owner should warn to allow maintainers access to modify
head_owner = github.pr_json["head"]["repo"]["owner"]["login"]
base_owner = github.pr_json["base"]["repo"]["owner"]["login"]
if !github.pr_json["maintainer_can_modify"] && head_owner != base_owner
warn("If you would allow the maintainers access to make changes to your branch that would be 💯 " \
"This allows maintainers to help move pull requests through quicker if there are any changes that they can help with 😊 " \
"See more info at https://help.github.com/en/articles/allowing-changes-to-a-pull-request-branch-created-from-a-fork")
end
| true
|
1967ba2d446705e775d9db3b695c6c80312dd5f3
|
Ruby
|
juliocesar/shining
|
/bin/shine
|
UTF-8
| 2,310
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
$:.unshift File.join(File.dirname(__FILE__), '..', 'lib')
require 'shining'
require 'stringex'
include Shining::FileMethods
ACTIONS = {
:new_on! => ['build'],
:new_slide! => ['slide'],
:help_and_exit! => ['help', '-h', '--help'],
:deploy => ['deploy'],
:remove => ['remove', 'delete', 'rm'],
:version => ['version', '-v'],
:start => ['go', 'start']
}
def bail! reason
Shining.error reason
exit -2
end
def figure_what_to_do!
help_and_exit! if ARGV.empty?
if ACTIONS.values.flatten.include? ARGV.first
action = ACTIONS.select { |action, args| args.include? ARGV.first }.flatten.first
send action, *ARGV[1..(ARGV.length - 1)]
else
new_on! ARGV.first
end
end
def help_and_exit!
STDERR.puts <<-HELP
Shine - Generates a new Shining presentation.
Usage:
shine <directory>
Example:
shine mycoolpreso
Other commands you can run:
help shows this menu
version shows the current version of Shining you have installed
Commands you can run from inside a presentation directory:
slide takes 1 argument with the slide name and optionally the format,
as in:
$ shine slide pretty
The above will create a HTML slide called "pretty".
deploy deploys the presentation to Heroku
remove takes a slide name as argument. Removes the slide. Example:
$ shine remove pretty
HELP
exit -1
end
def new_on! dir
Shining::Preso.new dir
end
def new_slide! name, format = 'html'
preso = Shining::Preso.open Dir.pwd
name, extension = name_and_extension(name)
extension = format if extension.blank?
preso.new_slide "#{name}.#{extension}"
end
def deploy name = nil
preso = Shining::Preso.open(Dir.pwd)
heroku = Shining::Heroku.new preso
name ||= preso.name.to_url
heroku.deploy name
end
def remove slide
preso = Shining::Preso.open Dir.pwd
preso.remove_slide slide
end
def version
Shining.say Shining::VERSION
end
def start port = 4567
preso = Shining::Preso.open Dir.pwd
raise "Cannot find the rackup command in your path. Make sure Rack is installed!" if `which rackup`.empty?
puts "Shining started on port #{port}."
`rackup -p #{port}`
end
figure_what_to_do!
| true
|
563d241b3b05bff55f486bf8f483f66019158fae
|
Ruby
|
wInevitable/Chess
|
/chess.rb
|
UTF-8
| 2,592
| 3.515625
| 4
|
[] |
no_license
|
#encoding: utf-8
require 'pry'
require 'yaml'
require_relative 'pieces/piece'
require_relative 'pieces/stepping_piece'
require_relative 'pieces/sliding_piece'
require_relative 'pieces/pawn'
require_relative 'pieces/bishop'
require_relative 'pieces/king'
require_relative 'pieces/queen'
require_relative 'pieces/rook'
require_relative 'pieces/knight'
require_relative 'invalid_move_error'
require_relative 'board'
class Chess
attr_reader :board, :current_player, :players
def initialize
@board = Board.new
@players = { :white => HumanPlayer.new(:white),
:black => HumanPlayer.new(:black) }
@current_player = :white
end
def play
until over?
if board.in_check?(current_player)
puts "#{current_player.to_s.capitalize} is in check."
end
begin
start, end_pos = players[current_player].play_turn(self)
board.move(start, end_pos, current_player)
rescue IOError, InvalidMoveError => e
puts e.message
retry
end
switch_turn
end
board.display
puts "#{:current_player} is checkmated."
nil
end
def save(filename)
File.open(filename, 'w') do |f|
f.puts to_yaml
end
end
def self.load(filename)
YAML::load_file(filename)
end
private
def switch_turn
@current_player = (current_player == :white) ? :black : :white
end
def over?
@board.checkmate?(:white) || @board.checkmate?(:black)
end
#remember to flip board
end
class HumanPlayer
attr_reader :color
def initialize(color)
@color = color
end
def play_turn(game)
game.board.display
puts "Current player: #{color}"
from_pos = get_pos('From pos:')
to_pos = get_pos('To pos:')
#get_move = gets.chomp.split(",")
if from_pos == "save"
game.save(to_pos)
return play_turn(game)
elsif from_pos == "flipboard"
system("open http://i.imgur.com/wYkU5Yn.gif")
abort("!!!")
else
parse_coords(from_pos, to_pos)
end
end
private
def get_pos(prompt)
puts prompt
coords = gets.chomp
end
def parse_coords(from, to)
coords = [from, to]
coords.map do |cor|
unless /[a-h][1-8]/ === cor
raise IOError.new("Enter Coordinates between A0-H8 OR
save and 'filename'")
end
[8 - cor[1].to_i, ('a'..'h').to_a.index(cor[0])]
end
end
end
g = Chess.new
b = Board.new
b.move([6,5],[5,5], :white)
b.move([1,4],[3,4], :black)
b.move([6,6],[4,6], :white)
b.move([0,3],[4,7], :black)
b.display
pry
| true
|
c73fef57f239a408be04df491090da5b06088c8c
|
Ruby
|
quotha/Huffwork
|
/lib/auction.rb
|
UTF-8
| 803
| 3.171875
| 3
|
[] |
no_license
|
require 'json'
class Auction
attr_accessor :item
attr_accessor :reserve
attr_accessor :started
attr_accessor :called
attr_accessor :bid
def initialize(args)
@item = args[:item]
@reserve = args[:reserve]
@started = args[:started] || false
@called = args[:called] || false
@bid = args[:bid] || 0
end
def status
{:reserve => reserve, :started => started, :called => called, :bid => bid}
end
def start
@started = true
end
def started?
started
end
def new_bid amount
if started? and amount > @bid
@bid = amount
end
end
def call
@called = true
end
def called?
called
end
def sold?
if called? and bid > reserve
true
else
false
end
end
end
| true
|
832b62366e4d6a879a04cd80b0f0de719df96c1a
|
Ruby
|
synergychen/leetcode-ruby
|
/closest_binary_search_tree_value.rb
|
UTF-8
| 460
| 3.5625
| 4
|
[] |
no_license
|
# BST: left_value < root_value < right_value
class TreeNode
attr_accessor :val, :left, :right
def initialize(val)
@val = val
@left, @right = nil, nil
end
end
def closest_value(root, target)
return nil unless root
root_val = root.val
sub_root = root_val < target ? root.left : root.right
return root_val unless sub_root
sub_root_val = closest_value(sub_root, target)
[root_val, sub_root_val].min_by { |v| (v - target).abs }
end
| true
|
07369ec3cc0cb6af1de4dbf290329154e4d856b0
|
Ruby
|
squiggle-lang/squiggle-lang.org
|
/_plugins/table_of_contents.rb
|
UTF-8
| 2,244
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
module TableOfContents
class Generator < Jekyll::Generator
# Chapter files are stored in /tutorial/chapter/NUM/index.md
SEC_REGEXP = %r{/tutorial/chapter/(\d+)}
def generate(site)
pairs = site
.pages
.select {|page| page.basename == "index" }
.map {|page| [page, page.dir.match(SEC_REGEXP)] }
.select {|pair| pair[1] }
.map {|pair|
page, match = pair
chapter = match[1].to_i
toc_data = {
"title" => page.data["title"],
"chapter" => chapter,
}
[page, toc_data]
}
.sort_by {|pair| pair[1]["chapter"] }
# Grab just the chapter array for use later.
toc = pairs.map {|p| p[1] }
# Find the page with the table of contents in it and inject the
# chapters array as page data.
site
.pages
.select {|p|
p.dir.start_with?("/tutorial") &&
p.basename == "index"
}
.each {|p| p.data["toc"] = toc }
# Inject various metadata used for chapters to render correctly.
pairs.each {|pair|
page, n = pair
i = toc.index(n)
n_prev = _chapter_plus_n(toc, i, -1)
n_next = _chapter_plus_n(toc, i, +1)
chapter = toc[i]["chapter"]
old_title = page.data["title"]
new_title = format("%d. %s", chapter, old_title)
page.data.merge!({
"layout" => "chapter",
"title" => new_title,
"chapter" => chapter.to_s,
"next" => n_next,
"previous" => n_prev,
})
}
end
# Tries to return the next/previous chapter or nil.
def _chapter_plus_n(toc, i, mod)
return nil if i == nil
j = i + mod
return nil if j < 0 || j >= toc.length
toc[j]["chapter"]
end
end
end
| true
|
c448ad77b77185d9f44dcf39d3965e0d24652e9a
|
Ruby
|
pahihu/syx
|
/plugins/x11/x11.rb
|
UTF-8
| 1,373
| 2.71875
| 3
|
[
"MIT",
"FSFUL"
] |
permissive
|
class X11Extract
def X11Extract.parse(file)
lines = File.readlines(file)
funcs = {}
func = []
lines.each do |line|
line.strip!
case line
when /^extern[ \t]+.*[ \t]+([^ \t]+)[ \t]*\($/
fn = $1
fname = fn.gsub(/[*]+/,'').strip
func = []
funcs[fname] = func
when /\/\*(.*)\*\//
func << $1.strip if func
when /^\);/
func = nil
when /^extern[ \t]+.*[ \t]+([^ \t]+)[ \t]*\([ \t]*void[ \t]*\)[ \t]*;[ \t]*$/
fn = $1
fname = fn.gsub(/[*]+/,'').strip
funcs[fname] = []
func = nil
end
end
return funcs
end
end
class X11Parser
def X11Parser.mangle(name)
return name.strip.gsub(/^[a-zA-Z0-9]/) { |s|
if s.length > 1
s.capitalize
else
s
end
}.gsub(/_[a-zA-Z0-9]/){|s| s[1..-1].upcase}
end
def X11Parser.run(funcs)
f = {}
funcs.keys.each do |func|
args = funcs[func]
argdef = []
args.each do |a|
argdef << mangle(a)
end
f["prim#{mangle(func)}"] = argdef
end
return f
end
end
| true
|
098cfc3a77edbe3c4fa2a0e4bd73d185ec34c3c4
|
Ruby
|
TAdP-Grupo3/Tp1-Metaprogramacion
|
/src/filters/negation_filter.rb
|
UTF-8
| 544
| 2.8125
| 3
|
[] |
no_license
|
require_relative '../../src/filters/abstract_filter'
require_relative '../../src/exceptions/no_arguments_given'
class NegationFilter<AbstractFilter
def initialize(filters)
raise NoArgumentsGivenError if filters.empty?
@filters = filters
end
private
def matching_methods(selectors)
matchs = @filters.map { |filter| filter.call(@origin) }.flatten.map{|wrapper| wrapper.method}
super(selectors).select{ |wrappedMethod| !matchs.include?(wrappedMethod.method) }
end
def matching_selectors
all_selectors
end
end
| true
|
08cd82bfe2f11b87957f2771b6e6cbee3f312c1f
|
Ruby
|
jrom/resque-insist
|
/spec/resque_insist_spec.rb
|
UTF-8
| 2,278
| 2.5625
| 3
|
[] |
no_license
|
require File.dirname(__FILE__) + '/spec_helper'
class Job
extend Resque::Plugins::Insist
@queue = :job
@insist = 2
def self.perform(success)
raise 'Not gonna work' unless success
end
end
describe Resque::Plugins::Insist do
describe "compliance of Resque Plugins guidelines" do
it "should be valid" do
lambda{ Resque::Plugin.lint(Resque::Plugins::Insist) }.should_not raise_error
end
end
describe "config" do
it "should take the insist_times value from the @insist ivar" do
Job.insist_times.should == 2
end
it "shoult default insist_times to 3" do
class JobWithoutCustomInsist
extend Resque::Plugins::Insist
@queue = :job
def self.perform; end
end
JobWithoutCustomInsist.insist_times.should == 3
end
end
describe "a succeeding Job" do
it "should be executed on the first attempt and not be enqueued again" do
Resque.enqueue Job, true
pending.should == 1
processed.should == 0
failed.should == 0
work_jobs
pending.should == 0
processed.should == 1
failed.should == 0
end
end
describe "a failing Job" do
it "should should quietly die and be enqueued back the first time it's executed" do
Resque.enqueue Job, false # enqueue a failing job
work_job # try to work it for the first time
pending.should == 1
failed.should == 0
time_before = Time.now
work_jobs # try to work it for the second and last time
elapsed_time = Time.now - time_before
elapsed_time.should > 7 # We wait aprox 8 seconds
elapsed_time.should < 9
pending.should == 0
failed.should == 1 # the job is marked as failed after 2 attempts
Resque::Failure.all['error'].should == 'Not gonna work' # we get the original error
end
end
# Defines pending, failed, processed, queues, environment, workers and servers
Resque.info.keys.each do |key|
define_method(key) { Resque.info[key] }
end
# Starts a worker to work off queue
def work_jobs(queue = :job)
Resque::Worker.new(queue).work(0)
end
# Performs the first job available from queue
def work_job(queue = :job)
worker = Resque::Worker.new(queue)
worker.perform(worker.reserve)
end
end
| true
|
89d3a21de7739899c0892939ad7eefad471cecc7
|
Ruby
|
IngramCapa/makersbnb
|
/lib/requests.rb
|
UTF-8
| 3,654
| 3.25
| 3
|
[] |
no_license
|
require 'pg'
require 'date'
class Requests
CONNECTION = PG.connect(dbname: 'makersbnb')
def initialize(user_id)
@user_id = user_id
end
def user
@user_id
end
def display_requests
all_bookings = CONNECTION.exec("SELECT * FROM bookings")
all_bookings.map { |booking|
"#{return_property_name(booking['prop_id'])[0]["prop_name"]}
#{display_confirmation(confirmed?(booking['id'])[0]["confirmation"])}
#{date_converter(start_date(booking['id'])[0]["startdate"])} - #{date_converter(@requests.end_date(booking['id'])[0]["enddate"])}"
}
end
# Return booking request list where your user ID is equal to the owner ID on the booking = Other users requesting your space.
def my_space_requests
my_space_requests = CONNECTION.exec("SELECT id FROM bookings WHERE owner_id='#{@user_id}'")
return my_space_requests
end
# Return booking request list where your user ID is equal to the client ID on the booking = Requests you've made on spaces.
def my_booking_requests
my_booking_requests = CONNECTION.exec("SELECT id FROM bookings WHERE client_id='#{@user_id}'")
return my_booking_requests
end
def my_selected_space_requests(booking_id)
prop_id = CONNECTION.exec("SELECT prop_id FROM bookings WHERE id='#{booking_id}'")
my_selected_space_requests = CONNECTION.exec("SELECT id FROM bookings WHERE prop_id='#{prop_id[0]["prop_id"]}'")
return my_selected_space_requests
end
def property_name(booking_id)
property_id = CONNECTION.exec("SELECT prop_id FROM bookings WHERE id='#{booking_id}'")
property_name = CONNECTION.exec("SELECT prop_name FROM properties WHERE id='#{property_id[0]["prop_id"]}'")
return property_name
end
def property_description(booking_id)
property_id = CONNECTION.exec("SELECT prop_id FROM bookings WHERE id='#{booking_id}'")
property_description = CONNECTION.exec("SELECT prop_description FROM properties WHERE id='#{property_id[0]["prop_id"]}'")
return property_description
end
def confirmed?(booking_id)
true_or_false = CONNECTION.exec("SELECT Confirmation FROM bookings WHERE id='#{booking_id}'")
return true_or_false
end
def confirmation(confirmed)
return "Confirmed" if confirmed == "t"
return "Not Confirmed" if confirmed == "f"
end
def confirmation_yes(booking_id)
CONNECTION.exec("UPDATE bookings SET Confirmation = 'TRUE' WHERE id='#{booking_id}'")
end
def confirmation_no(booking_id)
CONNECTION.exec("UPDATE bookings SET Confirmation = 'FALSE' WHERE id='#{booking_id}'")
end
def start_date(booking_id)
start_date = CONNECTION.exec("SELECT startdate FROM bookings WHERE id='#{booking_id}'")
return start_date[0]["startdate"]
end
def end_date(booking_id)
end_date = CONNECTION.exec("SELECT enddate FROM bookings WHERE id='#{booking_id}'")
return end_date[0]["enddate"]
end
def client_name(booking_id)
client_id = CONNECTION.exec("SELECT client_id FROM bookings WHERE id='#{booking_id}'")
user_name = CONNECTION.exec("SELECT user_name FROM users WHERE id='#{client_id[0]["client_id"]}'")
return user_name
end
def number_of_bookings(booking_id)
client_id = CONNECTION.exec("SELECT client_id FROM bookings WHERE id='#{booking_id}'")
booking_count = CONNECTION.exec("SELECT COUNT(id) FROM bookings WHERE id='#{client_id[0]["client_id"]}'")
return booking_count[0]["count"].to_i
end
def date_converter(date)
# Convert the Date to a DateTime Object
date_obj = DateTime.strptime(date,'%Y-%m-%d')
format = date_obj.strftime('%d/%m/%Y')
# Output the Date
return format.to_s
end
end
| true
|
751cd8fcfe8e5a6f7a472a6f48d6b064a64b9462
|
Ruby
|
HirokiTachiyama/armyknife_old
|
/src/pomodoro/pomodoro.rb
|
UTF-8
| 3,944
| 2.59375
| 3
|
[
"Apache-2.0"
] |
permissive
|
# coding: utf-8
require 'tk'
#require 'C:\Ruby26-x64\lib\ruby\gems\2.6.0\gems\tk-0.2.0\lib\tk'
# https://illyasviel.wiki.fc2.com/wiki/Ruby%E3%81%A7%E3%83%A9%E3%83%BC%E3%83%A1%E3%83%B3%E3%82%BF%E3%82%A4%E3%83%9E%E3%83%BC
Tk.root.title("POMODORO Timer")
Tk.root.width(800) # window幅、効いてない
Tk.root.height(1000) # windows高さ、効いてない
Tk.root.resizable(0, 0) # windowsのサイズを変更不可にする
class Time
# format文字列に従って現在時刻を返す
def tNow
self.strftime("%Y-%m-%d %H:%M:%S")
end
end
$itimer = nil # タイマー
$work_minutes = 50 # 作業時間
$break_minutes = 10 # 休憩時間
$work_times = 0 # 作業した回数
$break_times = 0 # 休憩した回数
$isWorkStartTime = true # 作業中か否か
$isRunning = true
# プログレスバー
$progress = nil
# 作業回数のラベル
$lbl_work = TkLabel.new(
text: "Work ##{$work_times}"
).grid( row: 1, column: 0 ,padx: 5, pady: 5)
$lbl_work.font(size: 18)
# 休憩回数のラベル
$lbl_break = TkLabel.new(
text: "Break ##{$break_times}"
).grid( row: 1, column: 1, padx: 5, pady: 5)
$lbl_break.font(size: 18)
# ボタン
$tkb = TkButton.new{
text "StartUP" # ランダムで顔文字つけたい
command {pushed}
bind 'Button-2', proc { print "Click!\n" }
}.grid( row: 1, column: 3, padx: 3, pady:3)
$tkb.font(size: 18)
$lbl_work.configure( fg: 'black', bg: 'gray')
$lbl_break.configure(fg: 'black', bg: 'gray')
# 引数はTimerのループ周期(ミリ秒)
$tktimer = TkTimer.new
TkTimer.start(1000){
if $itimer != nil
t1 = ($itimer - Time.now).to_i
if t1 < 0
$itimer = nil
$progress.stop
if $isWorkStartTime
$isWorkStartTime = false
#$lbl_timer.text = "Work##{$break_times + 1} is done."
$tkb.text = "Work##{$break_times + 1} is done."
message_box_break
$itimer = Time.now + ($break_minutes * 60)
$break_times = $break_times + 1
$lbl_break.text = "Break ##{$break_times}"
$progress.configure(maximum: ($itimer - Time.now).to_i + 1)
$lbl_work.configure(fg: 'black', bg: 'gray', underline: -1)
$lbl_break.configure(fg: 'yellow', bg: 'lightblue', underline: $lbl_break.text.size - 1)
else
$isWorkStartTime = true
$tkb.text = "Break##{$break_times} is done."
message_box_work
$itimer = Time.now + ($work_minutes * 60)
$work_times = $work_times + 1
$lbl_work.text = "Work ##{$work_times}"
$progress.configure(maximum: ($itimer - Time.now).to_i + 2)
$lbl_work.configure(fg: 'green', bg: 'white', underline: $lbl_work.text.size - 1)
$lbl_break.configure(fg: 'black', bg: 'gray', underline: -1)
end
elsif t1 < 60
$tkb.text = "#{t1} sec"
$progress.step(1)
else
$tkb.text = "#{t1/60} min #{t1%60} sec"
$progress.step(1)
end
end
}
def pushed
$itimer = Time.now + ($work_minutes * 60)
$work_times = $work_times + 1
$lbl_work.text = "Work ##{$work_times}"
$lbl_work.configure(fg: 'green', bg: 'white', underline: $lbl_work.text.size - 1)
$lbl_break.configure(fg: 'black', bg: 'gray')
$isRunning = true
# プログレスバー
$progress =
Tk::Tile::Progressbar.new(nil,
mode: 'determinate',
orient: 'horizontal',
# orient: 'vertical',
maximum: ($itimer - Time.now).to_i + 2
).grid(row: 0, column: 0)
p ($itimer - Time.now).to_i
end
def message_box_work
p Tk.messageBox(icon: 'info',
title: 'WorkStart',
message: "Let's work, #{$work_minutes} minutes.")
end
def message_box_break
p Tk.messageBox(icon: 'info',
title: 'Intermission',
message: "take a break, #{$break_minutes} minutes.")
end
Tk.mainloop
| true
|
4b9e81ddf689e195a2274919d56b1fa33060a354
|
Ruby
|
Edderic/pgit
|
/lib/pgit/helpers/query_methods.rb
|
UTF-8
| 1,647
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
module PGit
module Helpers
module QueryMethods
def set_attr(attribute)
unless instance_variable_get("@#{attribute}")
instance_variable_set("@#{attribute}", @query_hash[attribute.to_s] || yield)
end
end
def not_given(attribute)
"no_#{attribute}_given".to_sym
end
def ensure_given_queries
given_attrs.each {|attr| ensure_given_attr(attr) }
end
def ensure_given_attr(attribute)
attr = send(attribute)
raise PGit::Error::User.new(attr.to_s) if attr == not_given(attribute)
end
def attr_query(*args)
attr_has(args)
attr_given(args)
end
def set_default_attr(attribute)
set_attr(attribute) { not_given(attribute) }
end
def set_default_queries
given_attrs.each {|attr| set_default_attr(attr) }
end
# attributes that have been set to default values
def defaulted_attrs
given_attrs.reject {|attr| send("given_#{attr}?")}
end
# attributes that have corresponding #given_attr? methods
def given_attrs
methods.grep(/^given_.+\?$/).map { |m| m.to_s.gsub(/^given_/, '').gsub(/\?$/, '')}
end
def attr_has(args)
args.each do |method_name|
define_method "has_#{method_name}?" do |val|
instance_variable_get("@#{method_name}") == val
end
end
end
def attr_given(args)
args.each do |item|
define_method "given_#{item}?" do
instance_variable_get("@#{item}") != not_given(item)
end
end
end
end
end
end
| true
|
b0f8c64a33196e90c0b8cc02922cd98e3272df6b
|
Ruby
|
Somniloquist/building_blocks
|
/spec/caesar_spec.rb
|
UTF-8
| 686
| 2.8125
| 3
|
[] |
no_license
|
require "./lib/caesar.rb"
describe Caesar do
include Caesar
describe "#caesar_cipher" do
it "shifts a single word" do
expect(caesar_cipher("Hello", 1)).to eql("Ifmmp")
end
it "shifts multiple words" do
expect(caesar_cipher("Hello There", 1)).to eql("Ifmmp Uifsf")
end
it "shifts with negative number" do
expect(caesar_cipher("Hello There", -1)).to eql("Gdkkn Sgdqd")
end
it "loops when large number is given" do
expect(caesar_cipher("Hello There", 26)).to eql("Hello There")
end
it "loops when large negative number is given" do
expect(caesar_cipher("Hello There", -26)).to eql("Hello There")
end
end
end
| true
|
08acf69eb79fca8da65d8c5652f8a5c9f60fe610
|
Ruby
|
ndelforno/1---Reinforcement-Exercises-Data-Types-Variables-Conditionals
|
/exercise2.rb
|
UTF-8
| 1,369
| 3.640625
| 4
|
[] |
no_license
|
documentary = "bowling for colombine"
drama = "The Godfather"
comedy = "Hangover"
dramedy = "Titanic"
puts "how much do you like documentaries from 1 to 5 ?"
user_answer1 = gets.chomp.to_i
puts "how much do you like dramas from 1 to 5 ?"
user_answer2 = gets.chomp.to_i
puts "how much do you like comedies from 1 to 5 ?"
user_answer3 = gets.chomp.to_i
puts "---------------------"
puts user_answer1
puts user_answer2
puts user_answer3
puts "----------------------"
if user_answer1 >= 4
puts "you should watch #{documentary}"
elsif user_answer1 <= 3 && user_answer2 >=4 && user_answer3 >= 4
puts "you should wath #{dramedy}"
elsif user_answer2 >= 4 && user_answer1 < 4 && user_answer3 < 4
puts "you should watch #{drama}"
elsif user_answer3 >=4 && user_answer2 < 4 && user_answer1 < 4
puts "you should watch #{comedy}"
elsif user_answer1 <= 3 && user_answer2 <= 3 && user_answer3 <= 3 && user_answer1 > user_answer2 && user_answer1 > user_answer3
puts "you should watch #{documentary}"
elsif user_answer1 <= 3 && user_answer2 <= 3 && user_answer3 <= 3 && user_answer2 > user_answer1 && user_answer2 > user_answer3
puts "you should watch #{drama}"
elsif user_answer1 <= 3 && user_answer2 <= 3 && user_answer3 <= 3 && user_answer3 > user_answer1 && user_answer3 > user_answer2
puts "you should watch #{comedy}"
else
puts "you should read a book !"
end
| true
|
16733d310a7aba9433d866a5a6cd03d37b588016
|
Ruby
|
byrage/algorithm
|
/src/main/ruby/q10869.rb
|
UTF-8
| 103
| 3.203125
| 3
|
[] |
no_license
|
class Q10869
x, y = gets.split.map(&:to_i)
puts x+y
puts x-y
puts x*y
puts x/y
puts x%y
end
| true
|
dc680d6d8b1a69cab46c66a7703adb0a8bdc8cf0
|
Ruby
|
pgharts/trusty-cms
|
/app/models/status.rb
|
UTF-8
| 818
| 2.96875
| 3
|
[
"MIT"
] |
permissive
|
class Status
attr_accessor :id, :name
def initialize(options = {})
options = options.symbolize_keys
@id = options[:id]
@name = options[:name]
end
def symbol
@name.to_s.downcase.intern
end
def self.[](value)
@@statuses.find { |status| status.symbol == value.to_s.downcase.intern }
end
def self.find(id)
@@statuses.find { |status| status.id.to_s == id.to_s }
end
def self.find_all
@@statuses.dup
end
def self.selectable
find_all - [self['Scheduled']]
end
def self.selectable_values
selectable.map(&:name)
end
@@statuses = [
Status.new(id: 1, name: 'Draft'),
Status.new(id: 50, name: 'Reviewed'),
Status.new(id: 90, name: 'Scheduled'),
Status.new(id: 100, name: 'Published'),
Status.new(id: 101, name: 'Hidden'),
]
end
| true
|
586835ffe5b08943c48d4f458dbc1c41df983a3e
|
Ruby
|
prashanth-sams/page-object-pattern
|
/GoogleDriver.rb
|
UTF-8
| 2,298
| 2.640625
| 3
|
[
"Apache-2.0"
] |
permissive
|
require 'rspec'
require 'selenium-webdriver'
include RSpec::Expectations
class GoogleDriver
@driver = nil
def initialize (driver)
@driver = driver
@driver.manage.timeouts.implicit_wait = 10
end
def visit
@driver.navigate.to('https://www.google.co.in/')
@driver.manage.timeouts.page_load = 10
@driver.manage.window.move_to(0, 0)
@driver.manage.window.resize_to(1800, 1800)
return GoogleDriver.new(@driver)
end
def navigate
return NavBar.new(@driver)
end
def quit
@driver.quit
end
def title
return @driver.title
end
def find(how, what)
@driver.find_element(how, what)
end
def wait_for(how, what)
Selenium::WebDriver::Wait.new(:timeout => 5).until { @driver.find_element(how, what) }
end
def script_timeout
@driver.manage.timeouts.script_timeout = 15
end
def implicit_wait
@driver.manage.timeouts.implicit_wait = 15
end
def page_load
@driver.manage.timeouts.page_load = 15
end
def element_present?(how, what)
@driver.find_element(how, what)
true
rescue Selenium::WebDriver::Error::NoSuchElementError
raise 'The Element ' + what + ' is not available'
end
def element_not_present?(how, what)
@driver.find_element(how, what)
raise 'The Element ' + what + ' is available'
rescue Selenium::WebDriver::Error::NoSuchElementError
true
end
def click_on(how, what)
@driver.find_element(how, what).click
end
def clear(locator)
find(locator).clear
end
def type(locator, input)
find(locator).send_keys input
end
def displayed?(locator)
@driver.find_element(locator).displayed?
true
rescue Selenium::WebDriver::Error::NoSuchElementError
false
end
def text_of(locator)
find(locator).text
end
def alert_present?()
@driver.switch_to.alert
true
rescue Selenium::WebDriver::Error::NoAlertPresentError
false
end
def verify(&blk)
yield
rescue ExpectationNotMetError => ex
@verification_errors << ex
end
def close_alert_and_get_its_text(how, what)
alert = @driver.switch_to().alert()
alert_text = alert.text
if (@accept_next_alert) then
alert.accept()
else
alert.dismiss()
end
alert_text
ensure
@accept_next_alert = true
end
end
| true
|
e2baa592ab384b384226954939add88aeaa49ae4
|
Ruby
|
matpalm/audioscrobbler-experiments
|
/path/visited_graph_writer.rb
|
UTF-8
| 562
| 2.765625
| 3
|
[] |
no_license
|
require 'dot_writer'
class VisitedGraphWriter < DotWriter
def initialize(filename)
@dot_file = File.open(filename,'w')
@dot_file.write preamble
@flush_freq = 0
end
def flush_if_required
@flush_freq +=1
if @flush_freq > 20
@dot_file.flush
@flush_freq = 0
end
end
def new_edge(from, to)
@dot_file. write %Q{"#{from.name}" -> "#{to.name}" [label="} + sprintf("%.2f",from.weight_to_node(to)) + '"];' + "\n"
flush_if_required
end
def close
@dot_file.write postfix
@dot_file.close
end
end
| true
|
69d0494abae84f50c2cf1552b69b8f2c866d7d86
|
Ruby
|
Estebandelaciudad/jour_7_ruby
|
/exo_02.rb
|
UTF-8
| 235
| 3.421875
| 3
|
[] |
no_license
|
puts "Bonjour, Monde ! "
puts "Et avec une voix sexy, ça donne : Bonjour, monde !"
# La différence principale réside dans le fait que puts revient a la ligne après l'éxécution de sa commande et print ne revient pas à la ligne
| true
|
838b5dc453f5a08c12088a6e0a0e9d73ccad320b
|
Ruby
|
Katee/certificates
|
/lib/cache_strategy.rb
|
UTF-8
| 678
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
# encoding:UTF-8
require 'fileutils'
# Decides which cache to use based on a given path
module CacheStrategy
def self.build_from(path = nil)
if path
PDFCache.new(path)
else
NoCache.new
end
end
# Caches PDFs into a cache folder
class PDFCache
def initialize(cache_path)
@path = cache_path
end
def cache(certificate)
FileUtils.mkdir_p @path unless Dir.exist?(@path)
certificate_path = File.expand_path(certificate.filename, @path)
File.open(certificate_path, 'w') { |f| f.write certificate.pdf }
end
end
# Does not cache certificates at all
class NoCache
def cache(certificate); end
end
end
| true
|
c41319d281e1090603f716ffd36914c0cebfa877
|
Ruby
|
saifulAbu/ProgrammingRuby
|
/9/break-redo-next.rb
|
UTF-8
| 508
| 3.296875
| 3
|
[] |
no_license
|
# break - exits current block, runs next statement after current block
# redo - begins execution without reevaluating loop condition
# next - starts a new iteration of loop
while line = gets
next if line =~ /~\s#/
break if line =~ /^END/
redo if line.gsub!(/`(,*?)`/) {eval ($1)}
#process line
end
i = 0
loop do
i += 1
next if i < 3
print i
break if i > 4
end
# break can return a value
result = while line = gets
break(line) if line =~ /answer/
end
process_answer(result) if result
| true
|
9f950cdeb5f7d7420af16f47d2a9e0593e193837
|
Ruby
|
PattyGeorgi/Torti
|
/app/controllers/pie_controller.rb
|
UTF-8
| 1,407
| 2.8125
| 3
|
[] |
no_license
|
require 'chunky_png'
class PieController < ApplicationController
def drawLine(x,y,x2,y2,image)
w = x2 - x
h = y2 - y
dx1 = 0
dy1 = 0
dx2 = 0
dy2 = 0
if (w<0)
dx1 = -1
elsif (w>0)
dx1 = 1
end
if (h<0)
dy1 = -1
elsif (h>0)
dy1 = 1
end
if (w<0)
dx2 = -1
elsif (w>0)
dx2 = 1
end
longest = w.abs
shortest = h.abs
if (!(longest>shortest))
longest = h.abs
shortest =w.abs
if (h<0)
dy2 = -1
elsif (h>0)
dy2 = 1
end
dx2 = 0
end
numerator = longest >> 1
for i in 0...longest
image.set_pixel(x,y, ChunkyPNG::Color.parse(ChunkyPNG::Color.rgb(0,0,0)))
numerator += shortest ;
if (!(numerator<longest))
numerator -= longest
x += dx1
y += dy1
else
x += dx2
y += dy2
end
end
end
def genPie
if(params[:a] != nil && params[:b] != nil)
@a = params[:a].to_i
@b = params[:b].to_i
@g = @a+@b;
@w1 = (Math::PI * 2) * @a / @g
@xEnd = Math.cos(@w1)*50;
@yEnd = Math.sin(@w1)*50;
image = ChunkyPNG::Image.from_file('in.png')
drawLine(50,50,100,50,image)
drawLine(50,50,@xEnd.round+50,@yEnd.round+50,image)
send_data image.to_blob, :type => 'image/jpeg', :disposition => 'inline'
end
end
end
| true
|
f525d113b29b7da6eb0a7e2a40d16e049dfe81fc
|
Ruby
|
aknighttran/lunch_lady
|
/lunch_lady.rb
|
UTF-8
| 1,034
| 3.75
| 4
|
[] |
no_license
|
require "pry"
$VERBOSE = nil
@@main = [
{ dish: "Meatloaf", price: 5.00 },
{ dish: "Mystery Meat", price: 3.00 },
{ dish: "Slop", price: 1.00 }
]
@@side = [
{ dish: "Carrots", price: 1.75 },
{ dish: "Mystery Yogurt", price: 1.00 },
{ dish: "Beef Jerkey", price: 0.50 }
]
@@final = []
class Meal
def initialize
request
end
def request
puts "What main dish would you like?"
# binding.pry
dish(@@main)
puts "You can pick 2 side dishes. What is your 1st choice?"
dish(@@side)
puts "what is your 2nd choice?"
dish(@@side)
total
end
def dish(food)
food.each_with_index do |item, i|
puts "#{i + 1}) #{item[:dish]} - #{item[:price]}"
end
print ">"
choice = gets.to_i
@@final << food[choice - 1]
end
def total
puts "Your order consists of:"
@@final.each do |item|
puts "#{item [:dish]}"
end
total = @@final.sum { |h| h[:price]}
puts "Your order total is $#{total}"
exit
end
end
meal = Meal.new
meal.request
| true
|
3ee6461e9c9b23a7cde3e9285057c8e04af68f0f
|
Ruby
|
Micaonthego/cartoon-collections-nyc-web-career-010719
|
/cartoon_collections.rb
|
UTF-8
| 651
| 3.390625
| 3
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
def roll_call_dwarves(dwarves)
dwarves.each_with_index do |dwarf, index|
puts "#{index + 1}. #{dwarf}"
end
end
def summon_captain_planet(planeteer_calls)# code an argument here
planeteer_calls.map { |call| call.capitalize + '!'}# Your code here
end
def long_planeteer_calls(planeteer_calls)# code an argument here
planeteer_calls.any? { |call| call.length > 4}# Your code here
end
def find_the_cheese(potentially_cheesy_items)
cheese_types = ["cheddar", "gouda", "camembert"]# code an argument here
potentially_cheesy_items.find do |maybe_cheese|
cheese_types.include?(maybe_cheese)
end
end# the array below is here to help
| true
|
23e69a3e32547560eb533b431faf157e703af4fa
|
Ruby
|
kawausokun/qiita-sample
|
/dsa/elgamal.rb
|
UTF-8
| 2,405
| 3.0625
| 3
|
[] |
no_license
|
require './base.rb'
module MyExample
class ElgamalEncryptionEngine
attr_accessor :debug_enable
attr_reader :gamma,:n,:ft,:ftinv
def initialize(gamma,n,ft,ftinv,debug_enable=true)
raise ArumentError.new("gamma**n should be equal to epsilon") if gamma**n!=gamma.class.epsilon
@gamma,@n,@debug_enable=gamma,n,debug_enable
@ft,@ftinv=ft,ftinv
if @debug_enable
puts " ** debug: initialize",
" Elgamal Encryption engine initialized with;",
" gamma=#{gamma}, n=#{n}",
""
end
end
def create_key_pair(rval=nil)
x = rval||rand(0...n)
chi = @gamma**x
if @debug_enable
puts " ** debug: create_key_pair",
" created private key x: #{x},",
" public key chi=gamma**x: #{chi}",
""
end
[x,chi]
end
def encrypt(msg,chi,rval=nil)
# temporarily disable debug output
save,@debug_enable = @debug_enable
# message to a G-element translation
mu = @ft[msg] rescue
raise(ArgumentError.new("failed to convert message #{msg} ( #{$!} )"))
# Diffie-Hellman private shared value calculation
r,zeta1 = create_key_pair(rval)
kappa = chi**r
# conversion
zeta2 = mu*kappa
if @debug_enable = save
puts " ** debug: encrypt",
" translate msg = #{msg} to mu = #{mu},",
" created random number (private key) r = #{r},",
" generated cipher #1 (public key) zeta1 = #{zeta1},",
" using DH shared value kappa = #{kappa},",
" generated cipher #2 (main value) zeta2 = #{zeta2}",
""
end
[zeta1,zeta2]
end
def decrypt(zeta1,zeta2,x)
# Diffie-Hellman private shared value calculation
kappa = zeta1**x
# inversion
kinv = kappa.inv
mu = zeta2*kinv
# get message
msg = @ftinv[mu]
if @debug_enable
puts " ** debug: decrypt",
" cipher 1 / DH public key zeta1 = #{zeta1},",
" cipher 2 / main value zeta2 = #{zeta2},",
" DH shared value kappa = #{kappa}, and its inverse value = #{kinv},",
" inverse to mu = #{mu},",
" translate inverse to decrypted message = #{msg}",
""
end
msg
end
end
end
| true
|
8b1beed50a3c9b7759fbf4d346c715e5e2f63b1d
|
Ruby
|
TrevorAbram/Exercism_exercises
|
/ruby/gigasecond/gigasecond.rb
|
UTF-8
| 366
| 3.046875
| 3
|
[] |
no_license
|
class Gigasecond
# Using tests, we can see that the "time" argument needs to accept the info from tests.
# We can then create a variable called new_time that equals our time argument plus
# the gigaseconds formula (10**9 or 10^9). Then we print the solution and run tests accuracy.
def self.from(time)
new_time = time + 10**9
p new_time
end
end
| true
|
e673b6a241074b0d7068a8fcb38df4463a1574c9
|
Ruby
|
teoucsb82/pokemongodb
|
/lib/pokemongodb/pokemon/electabuzz.rb
|
UTF-8
| 1,319
| 2.75
| 3
|
[] |
no_license
|
class Pokemongodb
class Pokemon
class Electabuzz < Pokemon
def self.id
125
end
def self.base_attack
198
end
def self.base_defense
160
end
def self.base_stamina
130
end
def self.buddy_candy_distance
3
end
def self.capture_rate
0.24
end
def self.cp_gain
31
end
def self.description
"When a storm arrives, gangs of this Pokémon compete with each other to scale heights that are likely to be stricken by lightning bolts. Some towns use Electabuzz in place of lightning rods."
end
def self.egg_hatch_distance
10
end
def self.flee_rate
0.09
end
def self.height
1.1
end
def self.max_cp
2119.17
end
def self.moves
[
Pokemongodb::Move::LowKick,
Pokemongodb::Move::ThunderShock,
Pokemongodb::Move::Thunder,
Pokemongodb::Move::ThunderPunch,
Pokemongodb::Move::Thunderbolt
]
end
def self.name
"electabuzz"
end
def self.types
[
Pokemongodb::Type::Electric
]
end
def self.weight
30.0
end
end
end
end
| true
|
fa42d3c5d695fcc75fe524a7474984faf4fe8495
|
Ruby
|
camisoul/atcoder
|
/ABC/060/C/ruby/test.rb
|
UTF-8
| 224
| 2.640625
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
# frozen_string_literal: true
n, t = gets.split.map(&:to_i)
ts = gets.split.map(&:to_i)
if n == 1
p t
else
p n * t - ts.each_cons(2).map { |i| i[1] - i[0] }.map { |i| [t - i, 0].max }.inject(:+)
end
| true
|
b92878a6888683d7cc1bf79fea25b58b01a14b32
|
Ruby
|
uhlarmd/NBody
|
/Challenge2.rb
|
UTF-8
| 1,637
| 3.96875
| 4
|
[] |
no_license
|
puts "We're trying to write a farily tale, but we could use a litle bit of help. Give us a hand by filling out a few words:"
puts " "
puts "Type in a girl's name and press enter"
girl_name = gets.chomp
puts "Type in a living thing and press enter"
living_thing = gets.chomp
puts "Type in an adjective (big, cold, smelly) and press enter"
adj = gets.chomp
puts "Type in another adjective and press enter"
adj_2 = gets.chomp
puts "Type in a noun (book, cup, muffin) and press enter"
noun = gets.chomp
puts "Type in a verb (smile, punch, sniff) and press enter"
verb = gets.chomp
puts "Type in another verb and press enter"
verb_2 = gets.chomp
puts "Type in a past-tense verb and press enter"
past_verb = gets.chomp
puts "phew! Thanks, we couldn't have done it without you. Here's the finished story:"
puts " "
puts "THE FAIRLY TALE"
puts "---------------"
puts "Once upon a time there was a poor little girl named " + girl_name + " who lived in the forest with a(n) " + adj + " " + living_thing + ". She was forced to " + verb + " all day while the " + living_thing + " sat around " + verb_2 + "ing."
puts ""
puts "But then one day the little girl found a magic " + noun + ". When " + girl_name +" picked up the " + noun + ", she found that anything she imagined came true. Soon, " + girl_name + " was making the " + living_thing + " " + verb + " while she choose to sit around and " + verb_2 +"."
puts ""
puts "After a while, the girl realized this was not a very " + adj_2 + " thing to do and released the " + living_thing + " from her spell. They became best friends and " + past_verb + " every day, living happily ever after."
| true
|
e42d0235ec1fb36e958ade6dc803a13ca43c8b63
|
Ruby
|
krohrbaugh/dotfiles
|
/ruby/irb.d/01-usage.rb
|
UTF-8
| 550
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
# -*- ruby -*-
# Original author: Jim Weirich - http://github.com/jimweirich/irb-setup
unless Object.const_defined?("HELP")
Object.const_set("HELP", [])
end
def usage(method_name=nil, comment=nil)
if method_name.nil?
width = HELP.collect { |pair| pair[0].size }.max
HELP.sort.each do |name, desc|
printf "%-#{width}s -- %s\n", name, desc
end
elsif comment.nil?
puts "Usage: usage 'method_name', 'comment'"
else
HELP << [method_name, comment]
end
nil
end
usage "h", "Display help"
alias h usage
| true
|
ae906b9491ac10a95a9c112dbad5c9ef4e195d9c
|
Ruby
|
yokolet/tranquil-beach-ruby
|
/spec/graph_spec.rb
|
UTF-8
| 3,942
| 3.078125
| 3
|
[] |
no_license
|
require 'rspec'
Dir["./lib/graph/*.rb"].each {|file| require file }
describe 'Graph' do
context NumberOfIslands do
let(:obj) { NumberOfIslands.new }
it 'should count islands, 1' do
grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]
expected = 1
expect(obj.num_islands(grid)).to eq(expected)
end
it 'should count islands, 3' do
grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]
expected = 3
expect(obj.num_islands(grid)).to eq(expected)
end
end
context Alien do
let(:obj) { Alien.new }
it 'returns wertf' do
words = [
"wrt",
"wrf",
"er",
"ett",
"rftt"
]
expected = "wertf"
expect(obj.alien_order(words)).to eq(expected)
end
it 'returns zx' do
words = [
"z",
"x"
]
expected = "zx"
expect(obj.alien_order(words)).to eq(expected)
end
it 'returns wertf' do
words = [
"z",
"x",
"z"
]
expected = ""
expect(obj.alien_order(words)).to eq(expected)
end
end
context Bipartite do
let(:obj) { Bipartite.new }
it 'returns true' do
graph = [[1,3], [0,2], [1,3], [0,2]]
expect(obj.is_bipartite(graph)).to be_truthy
end
it 'returns false' do
graph = [[1,2,3], [0,2], [0,1,3], [0,2]]
expect(obj.is_bipartite(graph)).to be_falsey
end
end
context Itinerary do
let(:obj) { Itinerary.new }
it 'returns route1' do
tickets = [["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]]
expected = ["JFK", "MUC", "LHR", "SFO", "SJC"]
expect(obj.find_itinerary(tickets)).to eq(expected)
end
it 'returns route2' do
tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
expected = ["JFK","ATL","JFK","SFO","ATL","SFO"]
expect(obj.find_itinerary(tickets)).to eq(expected)
end
it 'returns route3' do
tickets = [["JFK","KUL"],["JFK","NRT"],["NRT","JFK"]]
expected = ["JFK","NRT","JFK","KUL"]
expect(obj.find_itinerary(tickets)).to eq(expected)
end
end
context ShortestDistance do
let(:obj) { ShortestDistance.new }
it 'returns 7' do
grid = [[1,0,2,0,1],[0,0,0,0,0],[0,0,1,0,0]]
expected = 7
expect(obj.shortest_distance(grid)).to eq(expected)
end
end
context Maze do
let(:obj) { Maze.new }
it 'returns true for prob1' do
maze = [
[0,0,1,0,0],
[0,0,0,0,0],
[0,0,0,1,0],
[1,1,0,1,1],
[0,0,0,0,0]
]
start, destination = [0,4],[4,4]
expect(obj.has_path(maze, start, destination)).to be_truthy
end
it 'returns false for prob2' do
maze = [
[0,0,1,0,0],
[0,0,0,0,0],
[0,0,0,1,0],
[1,1,0,1,1],
[0,0,0,0,0]
]
start, destination = [0,4],[3,2]
expect(obj.has_path(maze, start, destination)).to be_falsey
end
end
context FloodFill do
let(:obj) { FloodFill.new }
it 'changes image given 1, 1, 2' do
image = [
[1,1,1],
[1,1,0],
[1,0,1]
]
sr, sc, new_color = 1, 1, 2
expected = [
[2,2,2],
[2,2,0],
[2,0,1]
]
expect(obj.flood_fill(image, sr, sc, new_color)).to eq(expected)
end
it 'changes image given 0, 0, 2' do
image = [[0,0,0],[0,0,0]]
sr, sc, new_color = 0, 0, 2
expected = [[2,2,2],[2,2,2]]
expect(obj.flood_fill(image, sr, sc, new_color)).to eq(expected)
end
it 'changes image given 1, 1, 1' do
image = [[0,0,0],[0,1,1]]
sr, sc, new_color = 1, 1, 1
expected = [[0,0,0],[0,1,1]]
expect(obj.flood_fill(image, sr, sc, new_color)).to eq(expected)
end
end
end
| true
|
18bf26f835bbaa19e859da460c9a8f11b243b9cd
|
Ruby
|
itiswhatitisio/rb101
|
/small_problems/easy_3/counting.rb
|
UTF-8
| 261
| 3.640625
| 4
|
[] |
no_license
|
def prompt(message)
puts message
end
def count_words(string)
string.delete(' ').size
end
# Main program
prompt('Please write word or multiple words')
user_words = gets.chomp
prompt("There are #{count_words(user_words)} characters in \"#{user_words}\".")
| true
|
f1007931ee622696afc21249dd0d3f6fd6531e5f
|
Ruby
|
Justo84/ruby_blackjack
|
/card.rb
|
UTF-8
| 223
| 3.234375
| 3
|
[] |
no_license
|
class Card
attr_reader :value, :rank
def initialize(value, rank)
@value = value
@rank = rank
end
def to_string
"#{rank} #{value}"
end
def face_card?
['J', 'K', 'Q'].include?(value)
end
end
| true
|
e999c372b99d09cb509abeb6ef756ed852f64c86
|
Ruby
|
corinneling/apprentice-notes
|
/Ruby Exercises/whys-poignant-guide/hannah.rb
|
UTF-8
| 197
| 3.09375
| 3
|
[] |
no_license
|
final-verb = 'rescued'
['sedated', 'sprinkled', 'electrocuted'].each do |poop|
puts "Dr. Cham " + poop + " his niece Hannah."
end
puts "Finally, Dr. Cham " + final-verb + " his niece Hannah."
| true
|
ad25d0239c4871e7ff4ef18cf18a8d2ac95d51a6
|
Ruby
|
thuyihan1206/contact-management
|
/spec/requests/api_helper.rb
|
UTF-8
| 694
| 2.671875
| 3
|
[] |
no_license
|
module ApiHelper
# parsed body (expecting json format)
def parsed_body
JSON.parse(response.body)
end
# automates the passing of payload bodies as json
['post', 'put', 'patch', 'get', 'head', 'delete'].each do |http_method_name|
define_method("j#{http_method_name}") do |path, params = {}, headers = {}|
if ['post', 'put', 'patch'].include? http_method_name
headers = headers.merge('content-type' => 'application/json') unless params.empty?
params = params.to_json
end
send(http_method_name, path, params, headers)
end
end
# check if two arrays contain the same contents
def same_set?(a, b)
((a - b) + (b - a)).blank?
end
end
| true
|
8438b9e418f67370c4496c20d880cc1fc616f2f7
|
Ruby
|
katrpilar/ttt-with-ai-project-v-000
|
/lib/game.rb
|
UTF-8
| 2,421
| 3.765625
| 4
|
[] |
no_license
|
class Game
attr_accessor :board, :player_1, :player_2
WIN_COMBINATIONS = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [6,4,2] ]
def initialize (player_1=Players::Human.new("X"),player_2=Players::Human.new("O"),board=Board.new)
@player_1 = player_1
@player_2 = player_2
@board = board
end
def current_player
if self.board.turn_count.odd?
@player_2
else
@player_1
end
end
def over?
if self.won? || self.draw?
return true
elsif self.board.full? == false
return false
end
end
def won?
cell = self.board.cells
brd = self.board
WIN_COMBINATIONS.any?{|combo|
if (brd.taken?(combo[0] + 1) && brd.taken?(combo[1] + 1) && brd.taken?(combo[2] + 1)) && (cell[combo[0]] == cell[combo[1]]) && (cell[combo[0]] == cell[combo[2]])
return combo
end
}
return false
end
def draw?
if self.board.full? == true && self.won? == false
return true
else
return false
end
end
def winner
if self.draw? == false && self.won? != false
return self.board.cells[self.won?[0]]
else
return nil
end
end
def turn
puts "#{current_player.token} choose your next move:"
choice = self.current_player.move(@board)
while self.board.taken?(choice) == true || self.board.valid_move?(choice) == false
choice = self.current_player.move(@board)
end
self.board.update(choice, self.current_player)
return choice
end
def play
while self.over? == false && self.draw? == false
self.turn
self.board.display
end
if self.won?.kind_of?(Array)
puts "Congratulations #{self.winner}!"
elsif self.draw? == true
return puts "Cat's Game!"
end
end
def self.start
choice = gets.strip
if choice == "0"
ai = Game.new(Players::Computer.new("X"),Players::Computer.new("O"))
#binding.pry
while ai.over? == false
ai.play
ai.board.display
end
elsif choice == "1"
one = Game.new
one.player_2 = Players::Computer.new("O")
while one.over? == false
one.play
one.board.display
end
else
two = Game.new
two.board.display
two.play
end
end
end
| true
|
9cc3766d527877a9f2a847cf66b95c832daf2550
|
Ruby
|
GuettnerBianca/bio2rdf-scripts
|
/toxkb/toxnet/archival2rdf.rb
|
UTF-8
| 10,585
| 2.78125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
require 'rubygems'
require 'rdf'
require 'rdf/ntriples'
require 'nokogiri'
require 'digest/md5'
require 'cgi'
require 'ostruct'
require 'optparse'
require 'logger'
include RDF
class Archival
def initialize(args)
@arguments = args
@options = OpenStruct.new()
@log = Logger.new(STDOUT)
end
def run
@log.info "Running program"
if(process_arguments && valid_arguments?)
@log.info "Processing: \n\t#{@options.file}"
@log.info "Output to : \n \t\t #{@options.output}"
@reader = Nokogiri::XML::Reader(File.open(@options.file))
@output = File.new(@options.output,"w+")
@archival = RDF::Vocabulary.new("http://bio2rdf.org/archival:")
@archival_resource = RDF::Vocabulary.new("http://bio2rdf.org/archival_resource:")
@cas = RDF::Vocabulary.new("http://bio2rdf.org/cas:")
parse()
end
end
# Process the arguments on the command line
def process_arguments
opts_parse = OptionParser.new do |opts|
opts.on('-f','--file FILE') {|f|@options.file = File.expand_path(f)}
opts.on('-o','--output FILE'){|f|@options.output = File.expand_path(f)}
end
opts_parse.parse!(@arguments) rescue return false
return true
end
# check the arguments to make sure they are valid.
def valid_arguments?
begin
if(@options.file)
raise LoadError,"The file you specified doesn't exist: #{@options.file}" if File.exist?(@options.file) == false
else
@log.error "Select a file using -f or --file FILE"
end
if(@options.output)
# not going to worry about this one.
else
@log.error "No output was specified select using -o or --output"
end
rescue LoadError => bam
@log.error bam
exit
end
return true
end
def parse()
@graph = RDF::Graph.new()
@reader.each do |node|
if(node.name.include?("archival")&& node.node_type == 1)
node.read
node.read
end
if(node.name.include?("DOC") && node.node_type ==1 )
@doc = @archival["archival_#{Digest::MD5.hexdigest(node.inner_xml)}"]
@graph << [@doc, RDF.type, @archival_resource.DOC]
end
if(node.name == "DOCNO" && node.node_type == 1)
elsif(node.name == "ArticleTitle" && node.node_type == 1)
node.read
r = @archival["archival_#{Digest::MD5.hexdigest("ArticleTitle" + node.value + @doc.to_s)}"]
@graph << [r,RDF.type,@archival_resource.ArticleTitle]
@graph << [r,RDF.value,RDF::Literal.new("\"#{CGI.escape(node.value)}\"")]
@graph << [@doc,@archival_resource.hasArticleTitle,r]
elsif(node.name == "AbstractTitle" && node.node_type == 1)
node.read
r = @archival["archival_#{Digest::MD5.hexdigest("AbstractTitle" + node.value + @doc.to_s)}"]
@graph << [r,RDF.type,@archival_resource.AbstractTitle]
@graph << [r,RDF.value,RDF::Literal.new("\"#{CGI.escape(node.value)}\"")]
@graph << [@doc,@archival_resource.hasAbstractTitle,r]
elsif(node.name == "Affiliation" && node.node_type == 1)
node.read
r = @archival["archival_#{Digest::MD5.hexdigest("Affiliation" + node.value + @doc.to_s)}"]
@graph << [r,RDF.type,@archival_resource.Affiliation]
@graph << [r,RDF.value,RDF::Literal.new("\"#{CGI.escape(node.value)}\"")]
@graph << [@doc,@archival_resource.hasAffiliation,r]
elsif(node.name == "Author" && node.node_type == 1)
node.read
r = @archival["archival_#{Digest::MD5.hexdigest("Author" + node.value + @doc.to_s)}"]
@graph << [r,RDF.type,@archival_resource.Author]
@graph << [r,RDF.value,RDF::Literal.new("\"#{CGI.escape(node.value)}\"")]
@graph << [@doc,@archival_resource.hasAuthor,r]
elsif(node.name == "CASRegistryNumber" && node.node_type == 1)
node.read
cas = /\d{3,5}-\d{2,4}-\d{1,2}/.match(node.value)
if(cas != nil)
r = @cas[cas]
@graph << [r,RDF.type,@archival_resource.CASRegistryNumber]
@graph << [r,RDF.value,RDF::Literal.new("\"#{cas}\"")]
@graph << [@doc,@archival_resource.hasCASRegistryNumber,r]
end
elsif(node.name == "Coden" && node.node_type == 1)
node.read
r = @archival["archival_#{Digest::MD5.hexdigest("Coden" + node.value + @doc.to_s)}"]
@graph << [r,RDF.type,@archival_resource.Coden]
@graph << [r,RDF.value,RDF::Literal.new("\"#{CGI.escape(node.value)}\"")]
@graph << [@doc,@archival_resource.hasCoden,r]
elsif(node.name == "Keyword" && node.node_type == 1)
node.read
r = @archival["archival_#{Digest::MD5.hexdigest("Keyword" + node.value + @doc.to_s)}"]
@graph << [r,RDF.type,@archival_resource.Keyword]
@graph << [r,RDF.value,RDF::Literal.new("\"#{CGI.escape(node.value)}\"")]
@graph << [@doc,@archival_resource.hasKeyword,r]
elsif(node.name == "Language" && node.node_type == 1)
node.read
if(node.value !=nil)
r = @archival["archival_#{Digest::MD5.hexdigest("Language" + node.value + @doc.to_s)}"]
@graph << [r,RDF.type,@archival_resource.Language]
@graph << [r,RDF.value,RDF::Literal.new("\"#{CGI.escape(node.value)}\"")]
@graph << [@doc,@archival_resource.hasLanguage,r]
end
elsif(node.name == "PestabPubCode" && node.node_type == 1)
node.read
r = @archival["archival_#{Digest::MD5.hexdigest("PestabPubCode" + node.value + @doc.to_s)}"]
@graph << [r,RDF.type,@archival_resource.PestabPubCode]
@graph << [r,RDF.value,RDF::Literal.new("\"#{CGI.escape(node.value)}\"")]
@graph << [@doc,@archival_resource.hasPestabPubCode,r]
elsif(node.name == "PublicationType" && node.node_type == 1)
node.read
r = @archival["archival_#{Digest::MD5.hexdigest("PublicationType" + node.value + @doc.to_s)}"]
@graph << [r,RDF.type,@archival_resource.PublicationType]
@graph << [r,RDF.value,RDF::Literal.new("\"#{CGI.escape(node.value)}\"")]
@graph << [@doc,@archival_resource.hasPublicationType,r]
elsif(node.name == "SecondarySourceID" && node.node_type == 1)
node.read
r = @archival["archival_#{Digest::MD5.hexdigest("SeconardarySourceID" + node.value + @doc.to_s)}"]
@graph << [r,RDF.type,@archival_resource.SecondarySourceID]
@graph << [r,RDF.value,RDF::Literal.new("\"#{CGI.escape(node.value)}\"")]
@graph << [@doc,@archival_resource.hasSecondarySourceID,r]
elsif(node.name == "Source" && node.node_type == 1)
node.read
r = @archival["archival_#{Digest::MD5.hexdigest("Source" + node.value + @doc.to_s)}"]
@graph << [r,RDF.type,@archival_resource.Source]
@graph << [r,RDF.value,RDF::Literal.new("\"#{CGI.escape(node.value)}\"")]
@graph << [@doc,@archival_resource.hasSource,r]
elsif(node.name == "SponsoringAgency" && node.node_type == 1)
node.read
r = @archival["archival_#{Digest::MD5.hexdigest("SponsoringAgency" + node.value + @doc.to_s)}"]
@graph << [r,RDF.type,@archival_resource.SponsoringAgency]
@graph << [r,RDF.value,RDF::Literal.new("\"#{CGI.escape(node.value)}\"")]
@graph << [@doc,@archival_resource.hasSponsoringAgency,r]
elsif(node.name == "EntryMonth" && node.node_type == 1)
node.read
r = @archival["archival_#{Digest::MD5.hexdigest("EntryMonth" + node.value + @doc.to_s)}"]
@graph << [r,RDF.type,@archival_resource.EntryMonth]
@graph << [r,RDF.value,RDF::Literal.new("\"#{CGI.escape(node.value)}\"")]
@graph << [@doc,@archival_resource.hasEntryMonth,r]
elsif(node.name == "Year" && node.node_type == 1)
node.read
r = @archival["archival_#{Digest::MD5.hexdigest("Year" + node.value + @doc.to_s)}"]
@graph << [r,RDF.type,@archival_resource.Year]
@graph << [r,RDF.value,RDF::Literal.new("\"#{CGI.escape(node.value)}\"")]
@graph << [@doc,@archival_resource.hasYear,r]
elsif(node.name == "DOC" && node.node_type != 1)
@graph.each_statement do |statement|
@output.puts statement.to_s
end
@graph.clear
end
end
end
end
Archival.new(ARGV).run
| true
|
37793bb482ba48b8a22cb07d58f6567b7233513c
|
Ruby
|
DougMG/my_Playlist
|
/app/services/spotify_service.rb
|
UTF-8
| 775
| 2.796875
| 3
|
[] |
no_license
|
require 'base64'
require 'rest-client'
require 'json'
class SpotifyService
AUTHORIZE_URI = 'https://accounts.spotify.com/authorize'.freeze
TOKEN_URI = 'https://accounts.spotify.com/api/token'.freeze
def initialize(client_id, client_secret)
@client_id = client_id
@client_secret = client_secret
end
def authenticate
begin
request_body = { grant_type: 'client_credentials' }
response = RestClient.post(TOKEN_URI, request_body, auth_header)
JSON.parse(response) ['access_token']
rescue RestClient::ExceptionWithResponse => e
e.response
end
end
private
def auth_header
authorization = Base64.strict_encode64("#{@client_id}:#{@client_secret}")
{ 'Authorization' => "Basic #{authorization}" }
end
end
| true
|
bc89e78a53aa3d6437a1079579000b7edc8fddbe
|
Ruby
|
fsladkey/Freddit
|
/app/models/vote.rb
|
UTF-8
| 718
| 2.515625
| 3
|
[] |
no_license
|
# == Schema Information
#
# Table name: votes
#
# id :integer not null, primary key
# value :integer not null
# user_id :integer not null
# votable_id :integer
# votable_type :string
# created_at :datetime not null
# updated_at :datetime not null
#
class Vote < ActiveRecord::Base
validates :votable, :user, :value, presence: true
validates :user_id, :uniqueness => { :scope => [:votable_type, :votable_id] }
after_initialize :ensure_value
belongs_to :user
belongs_to :votable, polymorphic: :true
def upvote
value = 1
end
def downvote
value = -1
end
private
def ensure_value
value ||= 0
end
end
| true
|
2e7b69ed177a75c9a804633614ff8908268318ba
|
Ruby
|
judo2000/RB101_Programming_Foundations
|
/lesson_4/loops_2/stop_counting.rb
|
UTF-8
| 212
| 3.890625
| 4
|
[] |
no_license
|
# The method below counts from 0 to 4. Modify
# the block so that it prints the current
# number and stops iterating when the current
# number equals 2.
5.times do |index|
puts index
break if index == 2
end
| true
|
29e26b7900d6375a49746d022b05b7e80d4eb667
|
Ruby
|
oeyiowuawi/lekanmastermind
|
/bin/CLI/set_player.rb
|
UTF-8
| 743
| 3.390625
| 3
|
[] |
no_license
|
require 'lekanmastermind/player'
class SetPlayer
def initialize(message)
@message = message
end
def player_collection
loop do
puts @message.number_of_players
@number_of_players = gets.chomp
break if check_input(@number_of_players)
puts @message.error_input
end
generate_players(@number_of_players)
end
def check_input(input)
true if input =~ /\A[-+]?[0-9]*\.?[0-9]+\Z/
end
def generate_players(number_of_players)
number_of_players = number_of_players.to_i
players = []
(0..(number_of_players - 1)).each do |i|
puts "Enter your name player#{(i + 1).to_s}"
input = gets.chomp
players << Lekanmastermind::Players.new(input)
end
players
end
end
| true
|
0f8aa6fc29f61010870968d9c2eba8a669a40748
|
Ruby
|
aagooden/ultimate_tictactoe
|
/minitest_files/random_tests.rb
|
UTF-8
| 1,128
| 3.109375
| 3
|
[] |
no_license
|
require "minitest/autorun"
require "./classes/game.rb"
require "./classes/human.rb"
require "./classes/board.rb"
require "./classes/random.rb"
require "./classes/sequential.rb"
require "./classes/unbeatable.rb"
require "./classes/player.rb"
class Tictactoe_test < Minitest::Test
def test_random_level_1
board = Board.new(3)
type1 = Random.new
type2 = Random.new
player1 = Player.new("Aaron", type1, "X")
player2 = Player.new("Fred", type2, "O")
game = Game.new("player1", player1, player2)
board.state = ["O","O","X","O","X","X",6,"X",8]
possible = [6,8]
actual = game.current_player.choose_move(game,board)
contain = possible.include?(actual)
assert_equal(true, contain)
end
def test_random_level_2
board = Board.new(3)
type1 = Random.new
type2 = Random.new
player1 = Player.new("Aaron", type1, "X")
player2 = Player.new("Fred", type2, "O")
game = Game.new("player1", player1, player2)
board.state = [0,1,"X","X","O",5,"O",7,8]
possible = [0,1,5,7,8]
actual = game.current_player.choose_move(game,board)
contain = possible.include?(actual)
assert_equal(true, contain)
end
end
| true
|
5ca2655953f86535ec29562c7f02aa761ea7b60b
|
Ruby
|
tmtmtmtm/capitani-reggenti-wikipedia-scraper
|
/scraper.rb
|
UTF-8
| 1,562
| 2.828125
| 3
|
[] |
no_license
|
#!/bin/env ruby
# frozen_string_literal: true
require 'pry'
require 'scraped'
require 'scraperwiki'
require 'wikidata_ids_decorator'
require_relative 'lib/unspan_all_tables'
require 'open-uri/cached'
OpenURI::Cache.cache_path = '.cache'
class HoldersPage < Scraped::HTML
decorator WikidataIdsDecorator::Links
decorator UnspanAllTables
field :holders do
semesters.flat_map do |semester|
[
semester.slice(:name, :id, :start_date, :end_date),
semester.slice(:name2, :id2, :start_date, :end_date).transform_keys { |k| k.to_s.chomp('2').to_sym },
]
end
end
private
def semester_rows
noko.xpath('//table[.//th[contains(.,"Semestre")]]//tr[td]')
end
def semesters
semester_rows.map { |tr| fragment(tr => SemesterRow).to_h }
end
end
class SemesterRow < Scraped::HTML
field :name do
tds[2].text.tidy
end
field :id do
tds[2].xpath('.//a/@wikidata').text
end
field :name2 do
tds[3].text.tidy
end
field :id2 do
tds[3].xpath('.//a/@wikidata').text
end
field :start_date do
Date.new(year, start_month, 1)
end
field :end_date do
start_date >> 6
end
private
def tds
noko.css('td')
end
def year
tds[0].text.tidy.to_i
end
def semester
tds[1].text.tidy
end
def start_month
return 4 if semester == 'aprile'
return 10 if semester == 'ottobre'
raise "Unknown semester: #{semester}"
end
end
url = 'https://it.wikipedia.org/wiki/Capitani_reggenti_dal_2001'
Scraped::Scraper.new(url => HoldersPage).store(:holders)
| true
|
27ad84e098bdb83eb2c67cd1b424755c73089e42
|
Ruby
|
kmcd/refactoring_ruby
|
/simple_queue/simple_queue.rb
|
UTF-8
| 275
| 2.71875
| 3
|
[] |
no_license
|
require 'forwardable'
class SimpleQueue
extend Forwardable
def initialize
@elements = []
end
def_delegator :@elements, :shift, :remove_front
def_delegator :@elements, :push, :add_rear
def_delegators :@elements, :clear, :first, :length
end
| true
|
dfd99ae30f5902568fd716dd7dfaf3b1a50c63f2
|
Ruby
|
AlekseyZmitrykevich/tic_tac_toe
|
/lib/player.rb
|
UTF-8
| 197
| 3.484375
| 3
|
[] |
no_license
|
class Player
attr_reader :name, :mark
def initialize(name,mark)
@name=name
@mark=mark
@winner=false
end
def winner!
@winner=true
end
def winner?
@winner
end
end
| true
|
3087d49555e64039258d3061ece9d83b25302c77
|
Ruby
|
mugwump/rotten_tomatoes_api
|
/lib/rotten_tomatoes_api.rb
|
UTF-8
| 1,006
| 2.6875
| 3
|
[] |
no_license
|
require 'rotten_tomatoes_api/version'
require 'httparty'
require 'recursive_open_struct'
module RottenTomatoesApi
API_KEY = "sesenwn6zqegzseyhfw2bg49"
MOVIES_SEARCH ='http://api.rottentomatoes.com/api/public/v1.0/movies.json'
def self.version_string
"RottenTomatoesApi version #{RottenTomatoesApi::VERSION}"
end
class Movie < RecursiveOpenStruct
include HTTParty
format :json
def details
RecursiveOpenStruct.new HTTParty.get(links.self, :query => {:apikey => API_KEY})
end
end
class MovieList
include HTTParty
format :json
attr_accessor :total, :movies, :raw
def self.search(query)
options = {apikey: API_KEY, q: query}
results = get(RottenTomatoesApi::MOVIES_SEARCH, :query => options)
list = MovieList.new
list.total = results["total"]
list.raw = results
movies = []
results["movies"].each do |movie|
movies << Movie.new(movie)
end
list.movies = movies
list
end
end
end
| true
|
e12e22530e2dbed3b68f3533aa83cd7cafce398d
|
Ruby
|
david-ricketts/programming-univbasics-4-array-methods-lab-nyc-web-012720
|
/lib/array_methods.rb
|
UTF-8
| 443
| 3.65625
| 4
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
def using_include(array, element)
array.include?(element)
end
def using_sort(array)
sorted_array = array.sort
sorted_array
end
def using_reverse(array)
reversed_array = array.reverse
return reversed_array
end
def using_first(array)
first_element = array.first
return first_element
end
def using_last(array)
last_element = array.last
return last_element
end
def using_size(array)
size = array.size
return size
end
| true
|
401d556a851f432126dcd020e11aee0cfa712d31
|
Ruby
|
encoreshao/china_regions
|
/lib/tasks/china_regions.rake
|
UTF-8
| 3,627
| 2.75
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
# frozen_string_literal: true
namespace :china_regions do
desc 'Download and import regions into tables'
task all: :environment do
Rake::Task['china_regions:download'].invoke
Rake::Task['china_regions:import'].invoke
end
desc 'Download regions from `Administrative-divisions-of-China`'
task download: :environment do
ChinaRegions::Download.all
end
desc 'Import provinces and cities and areas to database'
task import: :environment do
ChinaRegions::Import.all
end
end
module ChinaRegions
module Download
require "down"
module_function
def all(filename = 'pca-code.json')
detect_folder
downloading(filename)
end
def downloading(filename)
down(filename)
move_to(filename)
end
def down(filename)
Down.download(
github_url(filename),
destination: File.join(Rails.root, 'db', 'regions')
)
end
def detect_folder
FileUtils.mkdir_p File.join(Rails.root, 'db', 'regions')
end
def github_url(filename)
[
'https://raw.githubusercontent.com',
'encoreshao',
'Administrative-divisions-of-China',
'master',
'dist',
filename
].join('/')
end
def move_to(filename)
src_file = Dir.glob(File.join(Rails.root, 'db', 'regions', "*.json")).max_by { |f| File.mtime(f) }
FileUtils.mv src_file, File.join(Rails.root, 'db', 'regions', filename)
end
end
module Import
require 'json'
require 'ruby-pinyin'
module_function
def all(filename = 'pca-code.json')
data_hash(filename).each { |province_hash| creating_province(province_hash) }
puts "Imported done!"
puts ''
puts " Total of #{Province.count} provinces."
puts " Total of #{City.count} cities."
puts " Total of #{District.count} districts."
end
def creating_province(prov_hash)
province = Province.find_or_create_by(name: prov_hash['name'])
province.update(build_params(prov_hash['name'], prov_hash['code']))
prov_hash["children"].each { |city_hash| creating_city(province, city_hash) }
end
def creating_city(province, city_hash)
city = City.find_or_create_by(province: province, name: city_hash['name'])
city_params = build_params(city_hash['name'], city_hash['code'])
.merge(city_level(city_hash['name']))
city.update(city_params)
city_hash['children'].each { |district| creating_district(city, district) }
end
def city_level(city_name)
{
level: municipalities.include?(city_name) ? 1 : 4
}
end
def creating_district(city, district_hash)
district = District.find_or_create_by(city: city, name: district_hash['name'])
district.update(build_params(district_hash['name'], district_hash['code']))
end
def build_params(full_name, code)
new_name = convert_pinyin(to_decorate(full_name))
name_en = new_name.join
name_abbr = new_name.map { |e| e[0] }.join
{
code: code,
name_en: name_en,
name_abbr: name_abbr
}
end
def convert_pinyin(text)
PinYin.of_string(text)
end
def to_decorate(text)
text.gsub(/市|自治州|地区|特别行政区|区|县|自治县/, '')
end
def municipalities
%w[北京市 天津市 重庆市 上海市]
end
def data_hash(filename)
@data_hash ||= JSON.parse File.read(latest_file_path(filename))
end
def latest_file_path(filename)
File.join(Rails.root, 'db', 'regions', filename)
end
end
end
| true
|
75d4df50e7320ebb3fd5464b69e252c964f905e0
|
Ruby
|
henrygarciaospina/challengers-ruby
|
/hashes_more.rb
|
UTF-8
| 702
| 3.890625
| 4
|
[] |
no_license
|
system("clear")
hash = {"one" => "Uno", 2 => "dos", :three => "tres", true => "cuatro"}
puts "*" * 60
puts hash
puts
puts "*" * 60
puts hash["one"]
puts hash[2]
puts hash[:three]
puts hash[true]
puts
#Adicionar elementos al hash
puts "*" * 60
hash["five"] = "cinco"
hash["six"] = "seis"
hash[:seven] = "siete"
puts hash
puts
#Modificar elementos del hash
puts "*" * 60
hash["five"] = "Cinco"
hash["six"] = "Seis"
hash[:seven] = "Siete"
puts hash
puts
#Definición de hashes mediante símbolos
dictionary = {word: "palabra", hello: "hola", developer: "desarrollador"}
puts "*" * 60
puts dictionary
puts
puts "*" * 60
puts dictionary[:word]
puts dictionary[:hello]
puts dictionary[:developer]
puts
| true
|
ea9474bd44c2ff6a8a1a5c9cdd6076ac533a6047
|
Ruby
|
Aeon/spree-dropdown-variants
|
/app/models/variant_decorator.rb
|
UTF-8
| 593
| 2.546875
| 3
|
[] |
no_license
|
Variant.class_eval do
def self.find_by_option_types_and_product(option_types, product)
join_clause = ''
and_clause = ''
option_types.each_with_index do |option_type, i|
join_clause << " INNER JOIN option_values_variants ovv#{i}
ON v.id = ovv#{i}.variant_id "
and_clause << " AND ovv#{i}.option_value_id = #{option_type.last} "
end
Variant.find_by_sql("SELECT v.* FROM variants v
#{join_clause}
WHERE v.product_id = #{product}
#{and_clause};").first
end
end
| true
|
3d9305dee98c3a3ecb41494a64f78bddb994bbb6
|
Ruby
|
botanicus/logging4hackers
|
/lib/logging/logger.rb
|
UTF-8
| 3,201
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
# encoding: utf-8
require_relative 'io'
require_relative 'formatters'
module Logging
# Main class. Instantiate it to start logging.
# In reality all this class does is to provide
# convenience proxy to {file:lib/logging/io.rb io objects}
# and {file:lib/logging/formatters.rb formatters}.
class Logger
# Log levels. At the moment adding new log levels
# isn't supported. This might or might not change.
LEVELS ||= [:error, :warn, :info]
# Label is required only when you use the default
# {file:lib/logging/io.rb io object}.
attr_reader :label
# Create a new logger.
#
# @param label [String, nil] Label. For instance `logs.myapp.db`.
# @param block [Proc] Block with the newly created instance.
#
# @yield [logger] The logger instance which just has been created.
#
# @example
# # Create logger with default values, specifying
# # only the label (mandatory when not specifying io).
# logger = Logging::Logger.new('logs.my_app.db')
#
# # Create a logger specifying a custom formatter and io.
# logger = Logging::Logger.new('logs.my_app.db') do |logger|
# logger.io = Logging::IO::Pipe.new(logger.label, '/var/mypipe')
# logger.formatter = Logging::Formatters::Colourful.new
# end
def initialize(label = nil, &block)
@label = label
block.call(self) if block
end
# The cached io instance. If there's none, one will be created.
#
# @raise [RuntimeError] If the label isn't specified (when creating new deafult io).
def io
@io ||= begin
if self.label
IO::Raw.new(self.label)
else
raise "You have to provide label in Logger.new if you want to use the default io object!"
end
end
end
attr_writer :io
# The cached formatter instance. If there's none, one will be created.
def formatter
@formatter ||= Formatters::Default.new
end
attr_writer :formatter
# @!method error(*messages)
# Log an error message.
# @param messages [Array<#to_s>] Messages to be logged.
# @api public
#
# @!method warn(*messages)
# Log a warning message.
# @param messages [Array<#to_s>] Messages to be logged.
# @api public
#
# @!method info(*messages)
# Log an info message.
# @param messages [Array<#to_s>] Messages to be logged.
# @api public
LEVELS.each do |level|
define_method(level) do |*messages|
log(level, *messages)
end
end
# Underlaying function for logging any kind of message.
# The actual functionality is delegated to {#io}.
#
# @param level [Symbol] Log level.
# @param messages [Array<#to_s>] Messages to be logged.
def log(level, *messages)
if messages.length == 1
self.io.write_single_message(self.formatter, level, messages.first)
else
self.io.write_multiple_messages(self.formatter, level, messages)
end
end
# Delegate to `self.io#write.
#
# @param args [Array] Arguments for `write` method of current `io` object.
def write(*args)
self.io.write(*args)
end
end
end
| true
|
d3680922d0d40fc0462ef4fa29acccfbe20d4630
|
Ruby
|
mneedham/neo4j-1
|
/example/imdb/batch_insert.rb
|
UTF-8
| 1,799
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
require 'movie'
# Remove old database if there is one
FileUtils.rm_rf Neo4j::Config[:storage_path] # this is the default location of the database
IMDB_FILE = 'data/test-actors.list'
movies = {}
current_actor = nil
actors = 0
no_films = 0
inserter = Neo4j::Batch::Inserter.new
File.open(IMDB_FILE).each_line do |line|
next if line.strip.empty?
tab_items = line.split("\t")
unless tab_items.empty?
if !tab_items[0].empty?
actor_name = tab_items.shift.strip
current_actor = inserter.create_node({'name' => actor_name}, Actor)
actors += 1
puts "Parse new actor no. #{actors} '#{actor_name}' actor_id=#{current_actor}"
end
tab_items.shift
film = tab_items.shift.strip
# already created film ?
movie = movies[film]
if (movie.nil?)
movie_title = film
movie_year = /\((\d+)(\/.)?\)/.match(film)[1]
movie = inserter.create_node({'title' => movie_title, 'year' => movie_year}, Movie)
movies[film] = movie
no_films += 1
puts "Created #{no_films} film '#{film}'"
end
role = tab_items.shift
#roleNode = current_actor.acted_in.new(movie)
role_props = {}
unless (role.nil?)
role.strip!
# remove []
role.slice!(0)
role.chop!
title, character = role.split('-')
role_props['title'] = title.strip unless title.nil?
role_props['character'] = character.strip unless character.nil?
end
inserter.create_rel(Actor.acted_in, current_actor, movie, role_props, Role)
# puts "Actor: '#{current_actor}' Film '#{movie}' Year '#{movie_year}' Title '#{role_props['title']}' Character '#{role_props['character']}'"
end
end
inserter.shutdown
puts "created #{actors} actors and #{no_films} films"
| true
|
debfc728fce8fae11831299f3218802b23f0f4d2
|
Ruby
|
elipinska/codeclan_wk2_day2_bus_lab
|
/specs/bus_stop_spec.rb
|
UTF-8
| 411
| 2.9375
| 3
|
[] |
no_license
|
require("minitest/autorun")
require_relative("../bus_stop")
require_relative("../person")
class BusStopTest < MiniTest::Test
def setup
@bus_stop = BusStop.new("Princes St")
@ewa = Person.new("Ewa", 27)
end
def test_bus_stop_has_name
assert_equal("Princes St", @bus_stop.name)
end
def test_add_to_queue
@bus_stop.add_to_queue(@ewa)
assert_equal(1, @bus_stop.queue.count)
end
end
| true
|
c7272073bfb79b95c1f6c9896044407dc876e219
|
Ruby
|
jhnegbrt/aA_Classwork
|
/w4d1/skeleton/lib/tic_tac_toe_node.rb
|
UTF-8
| 790
| 3.359375
| 3
|
[] |
no_license
|
require_relative 'tic_tac_toe'
class TicTacToeNode
attr_reader :board, :next_mover_mark
def initialize(board, next_mover_mark, prev_move_pos = nil)
@board = board
@next_mover_mark = next_mover_mark
@prev_mov_pos = prev_mov_pos
end
def losing_node?(evaluator)
end
def winning_node?(evaluator)
end
# This method generates an array of all moves that can be made after
# the current move.
def children
array = []
(0..2).each do |row|
(0..2).each do |col|
if @board[row][col].empty?
array << @board[row][col]
end
end
end
array.each do |pos|
new_board = @board.dup
new_board[pos] = @next_mover_mark
prev_mov_pos = pos
node = TicTacToeNode.new(new_board, pos)
end
end
end
| true
|
a5649580947e0c194ae809e66a18647abbecb69a
|
Ruby
|
domtriola/nim-game
|
/ruby/lib/game.rb
|
UTF-8
| 1,162
| 3.859375
| 4
|
[] |
no_license
|
require_relative 'board'
require_relative 'human_player'
require_relative 'computer_player'
class Game
attr_accessor :board, :player_one, :player_two,
:current_player, :last_move
def initialize(rows = [3, 4, 5])
@board = Board.new(rows)
@player_one = HumanPlayer.new
@player_two = ComputerPlayer.new
@current_player = player_one
@last_move = nil
end
def play
until over?
system('clear')
play_turn
end
if winner == player_one
puts "You win!"
else
puts "You lose"
end
end
def play_turn
current_player.display(board)
unless last_move.nil? || current_player.class == ComputerPlayer
puts "The computer took #{last_move[1]} bean(s) from row #{(last_move[0] + 97).chr}"
end
@last_move = current_player.get_move
board.remove_from_row(last_move)
switch_players!
end
def switch_players!
if current_player == player_one
@current_player = player_two
else
@current_player = player_one
end
end
def over?
board.rows.all? { |row| row == 0 }
end
def winner
return current_player if over?
nil
end
end
| true
|
d6237135602629ed0833ee3464cfdfb933d6a296
|
Ruby
|
cha63506/googlecodejam2014
|
/old/2012/round1a/q1/q1.rb
|
UTF-8
| 599
| 2.640625
| 3
|
[] |
no_license
|
require 'bundler'
Bundler.require(:default)
file = File.new('q1data.txt', 'r')
n = file.gets.to_i
n.times.each do |cas|
a, b = file.gets.split.map(&:to_i)
ps = file.gets.split.map(&:to_f)
expected = []
p = 1
(0..a).each do |i|
p*= ps[i-1] if i > 0
nb_right = b-a +2*(a-i)+1
nb_wrong = nb_right+b+1
next if nb_right > b
p0 = p
p0 = 0 if i ==0
#puts "bnb: #{nb_right} #{nb_wrong} --p #{p}"
e = (p0)*nb_right.to_f+(1-p0)*nb_wrong.to_f
expected << e
end
#Press enter now
expected << 2+b
puts "Case ##{cas+1}: #{expected.min}"
end
file.close
| true
|
54155620816518fa6ec8f4c0d1758258403f31eb
|
Ruby
|
tbonesteak/the_url_shortener
|
/app/models/url.rb
|
UTF-8
| 600
| 2.734375
| 3
|
[] |
no_license
|
class Url < ActiveRecord::Base
attr_accessible :long_url, :short_code
validates :long_url, presence: true, format: { with: URI::regexp}
before_create :short_code_generator
def short_code_generator
logger.info { "BEFORE SHORT CODE GENERATOR:"}
logger.info { self.short_code }
self.short_code = (0...9).map{ ('a'..'z').to_a[rand(26)] }.join
logger.info { "AFTER SHORT CODE GENERATOR:"}
logger.info { self.short_code }
end
end
# class Foo
# attr_accessor :bar
# def print_bar
# self.bar
# end
# def assign_bar
# self.bar = 'baz'
# end
# end
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.