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 |
---|---|---|---|---|---|---|---|---|---|---|---|
6f8d6abfb72f8dff6454e3ff31cf935b7c80d0d5
|
Ruby
|
larsjoakimgrahn/advent-of-code
|
/2022/09/part_1.rb
|
UTF-8
| 1,311 | 3.28125 | 3 |
[] |
no_license
|
Move = Struct.new('Move', :direction, :distance)
Point = Struct.new('Point', :x, :y)
$input = File.readlines('input.txt').map{|line| line.gsub("\n", '')}
.map{|line| Move.new(line.split(' ')[0], line.split(' ')[1].to_i) }
$visited_points = {[0,0]=>1}
$head_position = Point.new(0,0)
$tail_position = Point.new(0,0)
def tail_position(head, tail)
x_touching = tail.x == head.x || tail.x == (head.x - 1) || tail.x == (head.x + 1)
y_touching = tail.y == head.y || tail.y == (head.y - 1) || tail.y == (head.y + 1)
if x_touching && y_touching then
return tail
end
if x_touching then
return Point.new(head.x, tail.y < head.y ? tail.y + 1 : tail.y - 1)
elsif y_touching then
return Point.new(tail.x < head.x ? tail.x + 1 : tail.x - 1, head.y)
end
end
def do_move(move)
move.distance.times {
$head_position.x = $head_position.x + 1 if move.direction == "R"
$head_position.x = $head_position.x - 1 if move.direction == "L"
$head_position.y = $head_position.y - 1 if move.direction == "U"
$head_position.y = $head_position.y + 1 if move.direction == "D"
$tail_position = tail_position($head_position, $tail_position)
$visited_points.store([$tail_position.x, $tail_position.y], 1)
}
end
$input.each {|move| do_move(move) }
puts $visited_points.size
| true |
72786853a28eee84bdad80d961026431ec14c3f5
|
Ruby
|
Ralst0n/The-Odin-Project
|
/Ruby/Building_Blocks_Projects/word_frequency.rb
|
UTF-8
| 276 | 3.25 | 3 |
[] |
no_license
|
#histogram of word frequency in a string. redundant, I know.
def word_count(str)
str_arr = str.split(' ')
word_total = {}
str_arr.each do |word|
if word_total.include?word
word_total[word] +=1
else
word_total[word] = 1
end
end
word_total
end
| true |
06838bbe99144c7f84a88aa05e31e019e0ca70f7
|
Ruby
|
15Dkatz/agile-ruby
|
/chapter5/Trip.rb
|
UTF-8
| 582 | 3.296875 | 3 |
[] |
no_license
|
class Trip
attr_reader :bicycles, :customers, :vhicle
def prepare(preparers)
preparers.each {|preparer|
# prepare_trip is the method implemented through the duck type
preparers.prepare_trip(self)}
end
end
# Preparers are an interface and duck type
class Mechanic
def prepare_trip(trip)
trip.bicycles.each{|bicycle|
prepare_bicycle(bicycle)}
end
def prepare_bicycle(bicycle)
puts bicycle
end
end
class TripCoordinator
def prepare_trip(trip)
buy_food(trip.customers)
end
def buy_food(customers)
puts customers
end
end
| true |
e1cbcaea7373931816034478d06c2f52357e3447
|
Ruby
|
Kighway/rspec-fizzbuzz-web-1116
|
/fizzbuzz.rb
|
UTF-8
| 158 | 3.46875 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def fizzbuzz(number)
output = ""
output += number%3 == 0 ? "Fizz" : ""
output += number%5 == 0 ? "Buzz" : ""
output = output == "" ? nil : output
end
| true |
df4e4df0d0d0b8bbca59477ca3ec000e8174d8c1
|
Ruby
|
ericgj/rubekah
|
/test/dummy_server.rb
|
UTF-8
| 1,462 | 2.6875 | 3 |
[] |
no_license
|
require 'rubygems'
require 'eventmachine'
module EchoIRC
attr_accessor :nick
def post_init
@@connections ||= []
@regstate = 0
send_registration
end
def receive_data data
(@buffer ||= BufferedTokenizer.new).extract(data).each do |line|
receive_line(line)
end
end
def receive_line line
$stdout.puts "<< #{line}"
$stdout.flush
if registered?
case line
when /^QUIT/
send_quit line
else
send_echo line
end
else
case line
when /^PASS\s(\w+)/
when /^NICK\s(\w+)/
@nick = $1
send_registration
when /^USER\s(\w+)/
send_registration
send_registration
end
end
end
def registered?
@@connections.include? self
end
def send_registration
data = ":localhost 00#{@regstate += 1}\r\n"
$stdout.puts ">> #{data}"
$stdout.flush
send_data data
@@connections << self if @regstate == 4
end
def send_echo cmd
@@connections.each do |conn|
data = ":#{nick}! #{cmd}\r\n"
$stdout.puts " >> #{data}"
$stdout.flush
conn.send_data data
end
end
def send_quit cmd
send_echo "#{cmd.chomp} (quit)"
close_connection_after_writing
end
def unbind
@@connections.delete_if {|c| c == self}
end
end
EM.run {
$stdout.puts "Starting IRC dummy server on localhost:6667..."
EM.start_server "127.0.0.1", 6667, EchoIRC
}
| true |
96ac1741425b34dcb29a25f768a236f03c4e4982
|
Ruby
|
voxmedia/rich-text-ruby
|
/lib/rich-text/iterator.rb
|
UTF-8
| 912 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
module RichText
# @api private
class Iterator
def initialize(ops)
@ops = ops
reset
end
def each(size = 1)
return enum_for(:each, size) unless block_given?
yield self.next(size) while next?
end
def peek
if op = @ops[@index]
op.slice(@offset)
else
Op.new(:retain, Float::INFINITY)
end
end
def next?
peek.length < Float::INFINITY
end
def next(length = Float::INFINITY)
next_op = @ops[@index]
offset = @offset
if next_op
if length >= next_op.length - offset
length = next_op.length - offset
@index += 1
@offset = 0
else
@offset += length
end
next_op.slice(offset, length)
else
return Op.new(:retain, Float::INFINITY)
end
end
def reset
@index = 0
@offset = 0
end
end
end
| true |
6f201ed55645ea9242e26a32a903c06e3df5889c
|
Ruby
|
Hareramrai/parking_lot
|
/spec/supports.rb
|
UTF-8
| 379 | 2.9375 | 3 |
[] |
no_license
|
def run_command(pty, command)
stdout, stdin, _pid = pty
stdin.puts command
sleep(0.3)
stdout.readline
end
def fetch_stdout(pty)
stdout, _stdin, _pid = pty
res = []
while true
begin
Timeout.timeout 0.5 do
res << stdout.readline
end
rescue EOFError, Errno::EIO, Timeout::Error
break
end
end
res.join('').gsub(/\r/, '')
end
| true |
00e2ed10a49beb888164583d218971f608af13d5
|
Ruby
|
kennethcalamay/shinkyokushin
|
/db/seeds.rb
|
UTF-8
| 2,318 | 2.59375 | 3 |
[] |
no_license
|
puts 'Cleaning up...'
%w{ Instructor Member Dojo AdminUser }.each do |model|
model.constantize.delete_all
end
puts 'Creating instructor...'
james = Instructor.new(
is_active: true,
first_name: 'James',
last_name: 'Dela Cruz',
email: '[email protected]',
password: 'password')
rose = Instructor.new(
is_active: true,
first_name: 'Rose',
last_name: 'Dela Cruz',
email: '[email protected]',
password: 'password')
juan = Instructor.new(
is_active: true,
first_name: 'Juan',
last_name: 'Dela Cruz',
email: '[email protected]',
password: 'password')
puts 'Creating dojos...'
james_attrs = %w{ Manila QC }.reduce([]) do |attrs, name|
attrs << {
name: name,
description: "#{name}-description",
avatar: File.open(Rails.root.join('app/assets/images', "#{name}.jpg"))
}
end
rose_attrs = %w{ Caloocan Makati }.reduce([]) do |attrs, name|
attrs << {
name: name,
description: "#{name}-description",
avatar: File.open(Rails.root.join('app/assets/images', "#{name.downcase}.jpg"))
}
end
juan_attrs = %w{ Pasay }.reduce([]) do |attrs, name|
attrs << {
name: name,
description: "#{name}-description",
avatar: File.open(Rails.root.join('app/assets/images', "#{name}.jpg"))
}
end
james.dojos_attributes = james_attrs
james.save!
rose.dojos_attributes = rose_attrs
rose.save!
juan.dojos_attributes = juan_attrs
juan.save!
puts 'Creating student...'
james.dojos.first.members.create(
first_name: 'charlie',
last_name: 'Dela Cruz',
email: '[email protected]',
password: 'password')
rose.dojos.first.members.create(
first_name: 'Carl',
last_name: 'Dela Cruz',
email: '[email protected]',
password: 'password')
juan.dojos.first.members.create(
first_name: 'Peter',
last_name: 'Dela Cruz',
email: '[email protected]',
password: 'password')
puts "Creating belt..."
%w{ No 10th 9th 8th 7th 6th 5th 4th 3rd 2nd 1st}.each do |belt|
Belt.create!(
name: "#{belt} kyu",
description: "update me..")
end
puts 'Creating admin...'
AdminUser.create!(:email => "[email protected]", :password => "password")
puts 'All done!'
| true |
f5146d3f646238f1889cde4d3b089c915ef77224
|
Ruby
|
ErikDeBruijn/rdw
|
/lib/rdw/configuration.rb
|
UTF-8
| 768 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
module RDW
class Configuration
# Configure a cache to be used. Leave nil if no cache should be used.
attr_accessor :cache
# If you are using the cache you can set a custom prefix for cache keys.
# Default value: rdw_
attr_accessor :cache_prefix
# If set to true, Dutch values will be translated to english.
# This applies to colors, fuel types and unregistered values
# For example:
# - 'ROOD' will be translated to 'red'
# - 'Benzine' will be translated to 'gasoline'
# - 'Niet geregistreerd' will be translated to 'unregistered'
# Default value: false
attr_accessor :translate_values
def initialize
@cache = nil
@cache_prefix = 'rdw_'
@translate_values = false
end
end
end
| true |
792b06073517c338ee3fb043d8bcc8ea715d273f
|
Ruby
|
ray-curran/phase-0
|
/week-5/pad-array/my_solution.rb
|
UTF-8
| 4,213 | 4.59375 | 5 |
[
"MIT"
] |
permissive
|
# Pad an Array
# I worked on this challenge with Karen Ball
# I spent 2 hours on this challenge.
# Complete each step below according to the challenge directions and
# include it in this file. Also make sure everything that isn't code
# is commented in the file.
# 0. Pseudocode
# What is the input? an array, a minimum size (integer), and an optional placeholder value
# What are the steps needed to solve the problem?
# check length of our array
# compare length of array to minimum size integer
# IF length of array is less than minimum size
# add placeholder value or values until length equals minimum size
# return array
# ELSE
#return array
# What is the output? (i.e. What should the code return?) array
=begin
# 1. Initial Solution
def pad!(array, min_size, value = nil)
# Your code here
while array.length < min_size
array.push(value)
end
return array
end
original_array = [1,2,3]
pad!(original_array, 5, 'apple')
print original_array
=end
# 3. Refactored Solution
def pad!(array,min_size,value = nil)
array.fill(value,array.length,(min_size - array.length))
end
# 4. Reflection
=begin
- Were you successful in breaking the problem down into small steps?
Yes, we did a nice job in the pseudocode (and at times probably a little overboard) breaking the problem into as small steps as we could. This made it a lot easier when it came to actually doing the coding.
- Once you had written your pseudocode, were you able to easily translate it into code? What difficulties and successes did you have?
Yes, we did. The one issue we had was trying to figure out what steps would be different for a desctructive vs a non-destructive method. We didn't put that anywhere in the pseudocode since we weren't quite sure, and this ended up taking up most of our time later in the challenge.
- Was your initial solution successful at passing the tests? If so, why do you think that is? If not, what were the errors you encountered and what did you do to resolve them?
The first solution for our destructive method was successful. It seemed too easy until we had to figure out how to make the same type of method but have it be non-destructive. Eventually we just needed to troubleshoot a bit and try new things since we weren't able to find a solid answer during research.
- When you refactored, did you find any existing methods in Ruby to clean up your code?
Yes, we were able to find the fill method to pad our array.
- How readable is your solution? Did you and your pair choose descriptive variable names?
It's pretty readable. My pair had had some experience naming variables with names that weren't as descriptive in her GPS, so she was good at making sure we were careful with our names.
- What is the difference between destructive and non-destructive methods in your own words?
A destructive method actually changes the inputs. So in our example, the destructive method took an array as an input and actually returned the value back to the same array. So when you try to access that same array later, you're working on the changed array. In a non-destructive method, you can perform the same actions, but it leaves the original input alone. You can save the changes to your inputs to a new variable instead.
=end
# 0. Pseudocode
# What is the input? an array, a minimum size (integer), and an optional placeholder value
# What are the steps needed to solve the problem?
# reassign value of array to new variable
# compare length of array to minimum size integer
# WHILE length of array is less than minimum size integer
# add placeholder value(s) until length is minimum size
# What is the output? (i.e. What should the code return?) array of new variable
# 1. Initial Solution
=begin
def pad(array, min_size, value = nil) #non-destructive
new_array = []
new_array += array
while new_array.length < min_size
new_array.push(value)
end
return new_array
end
original_array = [1,2,3]
pad(original_array, 5, 'apple')
print original_array
=end
# 3. Refactored Solution
def pad(array, min_size, value = nil) #non-destructive
new_array = []
new_array += array
new_array.fill(value,array.length,(min_size - array.length))
end
| true |
2162e48e7005e04f4ebbe419f308616410f95ab3
|
Ruby
|
Coredump-FHP/chess
|
/spec/models/bishop_spec.rb
|
UTF-8
| 1,592 | 2.71875 | 3 |
[] |
no_license
|
require 'rails_helper'
RSpec.describe Bishop, type: :model do
def create_bishop(x, y)
FactoryGirl.create(:bishop, x_coordinate: x, y_coordinate: y)
end
describe '#valid_move?' do
it 'should move diagonally lt-bottom to rt-top any number of steps on the board' do
bishop = create_bishop(0, 0)
(1..7).each do |dist|
expect(bishop.valid_move?(dist, dist)).to eq true
end
end
it 'should move diagonally lt-top to rt-bottom any number of steps on the board' do
bishop = create_bishop(0, 7)
(1..7).each do |dist|
expect(bishop.valid_move?(dist, 7 - dist)).to eq true
end
end
it 'should move diagonally rt-top to lt-bottom any number of steps on the board' do
bishop = create_bishop(7, 7)
(6..0).each do |dist|
expect(bishop.valid_move?(dist, dist)).to eq true
end
end
it 'should move diagonally rt-bottom to lt-top any number of steps on the board' do
bishop = create_bishop(7, 0)
(7..0).each do |dist|
expect(bishop.valid_move?(7 - dist, dist)).to eq true
end
end
it 'should not move outside diagonal pattern' do
bishop = create_bishop(6, 1)
# test vertically
expect(bishop.valid_move?(6, 0)).to eq false
expect(bishop.valid_move?(6, 2)).to eq false
# test horizontally
expect(bishop.valid_move?(5, 1)).to eq false
expect(bishop.valid_move?(7, 1)).to eq false
# test other
expect(bishop.valid_move?(3, 1)).to eq false
expect(bishop.valid_move?(4, 0)).to eq false
end
end
end
| true |
6ba66542939f5c85926f54f530854ee85ed2e7e3
|
Ruby
|
onebusjenny/countdown-to-midnight-online-web-prework
|
/countdown.rb
|
UTF-8
| 96 | 3.09375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
#write your code here
def countdown
x = 10
while x > 0
puts "#{x} SECONDS!"
x -= 1
end
| true |
7b492ae541ec849ed7c2ec7baf5a2e7a4c4efd35
|
Ruby
|
LewisYoul/ruby-kickstart
|
/session3/challenge/17_hashes.rb
|
UTF-8
| 587 | 4.3125 | 4 |
[
"MIT"
] |
permissive
|
# Print to stdout, each element in a hash based linked list, in reverse.
# If you don't know what that is, go check out the previous problem.
#
# EXAMPLES:
# head = {:data => 1, :next => nil}
# head = {:data => 2, :next => head}
#
# print_list_in_reverse head # >> "1\n2\n"
=begin
head = {:data => 1, :next => nil}
head = {:data => 2, :next => head}
head = {:data => 3, :next => head}
=end
def print_list_in_reverse(list)
rtn_array = []
while list
rtn_array << list[:data]
list = list[:next]
end
rtn_array.reverse.each { |n| puts n }
end
#print_list_in_reverse head
| true |
589e0b7bb1aba596725c2b04136448467e2224ba
|
Ruby
|
demonsheepgit/demonasimov
|
/plugins/lib/dj/requests.rb
|
UTF-8
| 4,064 | 2.765625 | 3 |
[
"Apache-2.0"
] |
permissive
|
require 'date'
require 'open-uri'
require 'pp'
require 'redis'
require 'json'
require_relative '../logging'
require_relative 'song'
require_relative 'amazonSong'
require_relative 'spotifySong'
require_relative 'spotifyPlaylist'
class Requests
include Logging
SATURDAY = 6
DEADLINE_HOUR = 9
attr_reader :show_date
def initialize(*args)
super
logger.debug("#{self.class.name}::#{__method__}")
@redis = Redis.new
@lock = Mutex.new
@show_date = next_show_date
@requests = load_requests(@show_date)
@roller_status = nil
start_show_date_roller
end
# @param nick [String] user nick
# @param song [Song] the song to be added
#
# @return [int] the int id of the song added
# nil otherwise
def add(nick, song)
@requests[nick] = [] unless @requests.key?(nick)
@requests[nick] << song
save_requests
@requests[nick].length
end
# @param nick [String] user nick
# @param index [int] the song to be removed
#
# @return void
def remove(nick, index)
return if @requests[nick].nil?
return if @requests[nick][index.to_i].nil?
@requests[nick].delete(index.to_i)
save_requests
end
def remove_all(nick)
@requests[nick] = []
save_requests
end
# Fetch the requested song
# @param nick [String] user nick
# @param index [int] the request to be modified
#
# @return [Song]
def get(nick, index)
return nil if @requests[nick].nil?
return nil if @requests[nick][index.to_i].nil?
@requests[nick][index.to_i]
end
# Replace/update the song identified by id
# This allows updating the remarks, adding an
# album title, etc
# @param nick [String] user nick
# @param index [int] the request to be modified
# @param song [Song] the updated song
#
# @return void
def update(nick, index, song)
return if @requests[nick].nil?
return if @requests[nick][index.to_i].nil?
@requests[nick][index.to_i] = song
end
# @param nick [String] user's nick or nil for all users
#
# @return [int] the number of songs in the user's request queue
# or the total request count if nil
# nil otherwise
def count(nick=nil)
return 0 if @requests[nick].nil?
count_request = 0
if nick.nil?
@requests.each do |nick|
count_request += @requests[nick].length
end
else
count_request = @requests[nick].length
end
count_request
end
# List the songs requested for the nick
# @param nick [String] user's nick
#
# @return [Hash] of the user's requests
def list(nick)
return [] if @requests[nick].nil?
@requests[nick]
end
# Write the data out to the persistence layer (ie redis)
# @return void
def save_requests
@redis.set("requests-#{@show_date}", @requests.to_json)
end
# Retrieve the data from the persistence layer (ie redis)
# @param load_show_date [Date]
#
# @return [Hash]
def load_requests(load_show_date)
request_json = @redis.get("requests-#{load_show_date}")
if request_json.nil?
{}
else
JSON.parse(request_json, :create_additions => true)
end
end
# Calculate the next/upcoming show date
#
# @return [Date] date of the upcoming Saturday
def next_show_date
interval = SATURDAY - Date.today().wday
interval = SATURDAY if (interval < 0)
Date.today + interval
end
def past_deadline?
Date.today >= @show_date && Time.now.hour >= DEADLINE_HOUR
end
# If necessary, roll @show_date to the next week
# @return void
def start_show_date_roller
if @roller_status == 'run' || @roller_status == 'sleep'
raise("Error in #{__method__}: roller thread already running!")
end
# do not join this thread, we don't care about it finishing
Thread.new do
@roller_status = Thread.current.status
while true do
sleep 600
if Date.today > @show_date
@lock.synchronize do
save_requests
@requests = {}
end
@show_date = next_show_date
end
end
end
end
end
| true |
7989239bcb4f476cc10fc5927f91143e62f30bbf
|
Ruby
|
maowaw/mini_jeu_POO
|
/lib/player.rb
|
UTF-8
| 2,880 | 3.875 | 4 |
[] |
no_license
|
class Player
attr_accessor :name, :life_points #read&write attributes
def initialize (name) #allows to create a player. we only have to type the name in
@name = name
@life_points = 10 #every player has 10 points at the beginning. without coma so it knows it's an integer
end
def show_state #allows to show the state of the player
puts "#{@name} a #{@life_points} points de vie"
end
def gets_damage (damage) #when the player undergoes an attack
@life_points = @life_points - damage #to_i in case a petit malin wants to put a float
#announce the death :
if @life_points <= 0
puts "Oh damnnn, #{@name} a été anéanti.."
end
end
def compute_damage #assigning a random damage
return rand(1..6)
end
def attacks(player_2) #announce who's attacking who
puts "Le joueur #{@name} attaque le joueur #{player_2.name}"
damage_attack = compute_damage #stock the random number in a var called damage_attack
player_2.gets_damage(damage_attack) #applies the function gets_damage
if player_2.life_points <= 0 #important for exo app_2.rb so that it doesn't display negative life points
player_2.life_points = 0
else
puts "Il lui inflige #{damage_attack} points de dommage ! "
end
end
end
#Exo app_2.rb
class HumanPlayer < Player
attr_accessor :weapon_level #adding the attribute
def initialize(name)
super(name) #fait appel au initialize de la classe player
@weapon_level = 1 #initialize the var
@life_points = 100 #initialize the var
end
def show_state
puts "Bonsoiiir ! Tu t'appelles #{@name}, tu as #{@life_points} points de vie et une arme sacrément puissante de #{weapon_level}"
end
def compute_damage #new compute_damage taking in account the weapon level
return rand(1..6) * @weapon_level
end
def search_weapon #allows the player to get a better weapon
new_weapon = rand(1..6)
puts "Waw, tu as trouvé une arme de niveau #{new_weapon}"
if new_weapon > @weapon_level #changes the weapon only if it's better
puts "Youhou, cette arme est meilleure que la tienne ! Tu la prends."
@weapon_level = new_weapon
else
puts "M@*#$... elle n'est pas mieux que ton arme actuelle..."
end
end
def search_health_pack #allows the player to increase his life points
health_pack = rand(1..6)
if health_pack == 1
puts "Tu n'as rien trouvé.. Ta vie reste à #{@life_points}"
elsif health_pack >= 2 && health_pack <= 5
puts "Bravo, tu as trouvé 50 petits coeurs"
@life_points = @life_points + 50
if @life_points > 100
@life_points = 100
end
puts "Ta vie est maintenant à #{@life_points}"
else
puts "La classe, tu as trouvé 80 petits coeurs !!"
@life_points = @life_points + 80
if @life_points > 100
@life_points = 100
end
puts "Ta vie est maintenant à #{@life_points}"
end
end
end
| true |
93e9d996154374af8b68a7512a8eceb60441b22a
|
Ruby
|
marissa-a/kwk-l1-instance-methods-lab-ruby-kwk-students-l1-la-070918
|
/lib/dog.rb
|
UTF-8
| 112 | 3.46875 | 3 |
[] |
no_license
|
class Dog
def bark
puts "Woof!"
end
def sit
puts "The Dog is sitting"
end
end
puts Dog
| true |
2be874be4552da2c8bc4c6bebe19cc32c1a82768
|
Ruby
|
aronsonben/School-Projects
|
/CMSC330/p4_SmallCInterpreter/p4a_SmallCParser/testing/framework/TestConfig.rb
|
UTF-8
| 525 | 2.546875 | 3 |
[] |
no_license
|
require "yaml"
class TestConfig
@@NAME = "name"
@@TYPE = "type"
@@RESOURCES = "resources"
@@LOCAL_RESOURCES = "local_resources"
@@MODULES = "modules"
def initialize(filename)
@config = YAML::load_file(filename)
end
def name
@config[@@NAME]
end
def type
@config[@@TYPE]
end
def modules
@config[@@MODULES]
end
def resources
@config[@@RESOURCES]
end
def local_resources
@config[@@LOCAL_RESOURCES]
end
end
| true |
8543cf01822d97cb134cc0a05d9890e6a9ea6761
|
Ruby
|
nfisher/FBomb
|
/test/request_test.rb
|
UTF-8
| 1,200 | 2.546875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
# To change this template, choose Tools | Templates
# and open the template in the editor.
$:.unshift File.join(File.dirname(__FILE__),'..','lib')
require 'test/unit'
require 'request'
require 'digest/md5'
module Facebook
class RequestTest < Test::Unit::TestCase
def setup
@instance = Facebook::Request.new
end
def teardown
@instance = nil
end
def cba_params
{:c => 'c', :b => 'b', :a => 'a'}
end
def test_instantiated
assert_instance_of(Facebook::Request, @instance)
end
def test_cat_with_three_parameter_hash
expected = 'a=ab=bc=c'
actual = @instance.cat( cba_params )
assert_equal(expected, actual)
end
def test_signature
secret = '123'
expected = Digest::MD5.hexdigest("a=ab=bc=c#{secret}")
actual = @instance.signature(cba_params, secret)
assert_equal(expected, actual)
end
def test_single_prepare
call_at = 1
secret = '123'
expected = cba_params.merge({:method => 'dog', :call_at => call_at, :sig => Digest::MD5.hexdigest("a=ab=bc=ccall_at=#{call_at}method=dog#{secret}")})
actual = @instance.prepare( cba_params.merge(:method => 'dog'), secret, call_at )
assert_equal(expected, actual)
end
end
end
| true |
895d63c2d258023f0b79e51ac0855f8806f8a5f3
|
Ruby
|
nick-stebbings/ruby-rb101-109
|
/OOP/ruby_OOP_small_problems/Easy_1/09_complete_the_program_-_cats!.rb
|
UTF-8
| 1,414 | 4.09375 | 4 |
[] |
no_license
|
class Pet
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
end
class Cat < Pet
attr_reader :color
def initialize(name, age, col)
super(name, age)
@color = col
end
def to_s
"My cat #{name} is #{age} years old and has #{color} fur."
end
end
pudding = Cat.new('Pudding', 7, 'black and white')
butterscotch = Cat.new('Butterscotch', 10, 'tan and white')
puts pudding, butterscotch
## FE
#An alternative approach to this problem would be to modify the Pet class to accept a colors parameter. If we did this, we wouldn't need to supply an initialize method for Cat.
#
#Why would we be able to omit the initialize method? Would it be a good idea to modify Pet in this way? Why or why not? How might you deal with some of the problems, if any, that might arise from modifying Pet?
# we could omit the initialize method because when a Cat object was instantiated, Ruby would look up the class heirarchy to find a method called 'initialize' and would find it in the superclass, Pet.
# It mightn't be a good idea to give a colour attribute to every element of the Pet class (e.g. pet lizards are difficult to assign a color attribute to). You could create initialize methods for any Pet subclasses that didn't have a color, and use a more specific implementation for Lizard instantiation that didn't call on Pet#initialize.
| true |
f7b910d513114f87845164fc2ede0a54c5e3816e
|
Ruby
|
shanghuifu/medi-chart
|
/app/models/reservation.rb
|
UTF-8
| 697 | 2.671875 | 3 |
[] |
no_license
|
class Reservation < ApplicationRecord
with_options presence: true do
validates :date
end
belongs_to :patient
belongs_to :schedule
def rsv_date_check(days)
none = ""
if self.date == Date.today + days
return self.patient.name
else
return none
end
end
def rsv_time_check(schedule_id)
if self.schedule_id == schedule_id
return self.patient.name
else
return nil
end
end
def self.rsv_time_sort(schedules)
sorted_ary = []
schedules.times do |i|
sorted_ary << Reservation.where(schedule_id: i + 1,
date: Date.today..Date.today + 13)
end
return sorted_ary
end
end
| true |
36e6dc60dc11850180673a9ebecc58f55328519c
|
Ruby
|
meeke198/W2D3
|
/battleship_project/lib/board.rb
|
UTF-8
| 3,380 | 3.609375 | 4 |
[] |
no_license
|
# require "byebug"
# class Board
# attr_reader :size
# def initialize(n)
# # debugger
# @grid = Array.new(n){Array.new(n, :N)}
# @size = n * n
# end
# def [](pos)
# # debugger
# row, col = pos
# @grid[row][col]
# end
# def []=(pos, value)
# # debugger
# row, col = pos
# @grid[row][col] = value
# end
# def num_ships
# num_ships = 0
# ([email protected]).each do |row|
# ([email protected]).each do |col|
# if @grid[row][col] == :S
# num_ships += 1
# end
# end
# end
# num_ships
# end
# def attack(pos)
# if self[pos] == :S
# self[pos] = :H
# puts 'You sunk my battleship!'
# return true
# else
# self[pos] = :X
# return false
# end
# end
# def place_random_ships
# total_ship = @size * 0.25
# while self.num_ships < total_ship
# rand_r = rand([email protected])
# rand_c = rand([email protected])
# pos = [rand_r, rand_c]
# self[pos] = :S
# end
# end
# def hidden_ships_grid
# @grid.map do |subarray|
# subarray.map do |ele|
# if ele == :S
# :N
# else
# ele
# end
# end
# end
# end
# def self.print_grid(another_grid)
# another_grid.each do |row|
# puts row.join(" ")
# end
# end
# def cheat
# Board.print_grid(@grid)
# end
# def print
# Board.print_grid(self.hidden_ships_grid)
# end
# end
class Board
attr_reader :size
def initialize(n)
@grid = Array.new(n) { Array.new(n, :N) }
@size = n * n
end
def [](pos)
row, col = pos
@grid[row][col]
end
def []=(pos, value)
row, col = pos
@grid[row][col] = value
end
def num_ships
count = 0
([email protected]).each do |row|
([email protected]).each do |col|
if @grid[row][col] == :S
count += 1
end
end
end
count
end
def attack(pos)
if self[pos] == :S
self[pos] = :H
puts "you sunk my battleship!"
return true
else
self[pos] = :X
return false
end
end
def place_random_ships
total_ship = size / 4.00
while self.num_ships < total_ship
random_r = rand([email protected])
random_c = rand([email protected])
pos = [random_r, random_c]
self[pos] = :S
end
end
def hidden_ships_grid
@grid.map do |subarray|
subarray.map do |ele|
if ele == :S
ele = :N
else
ele
end
end
end
end
def self.print_grid(another_grid)
another_grid.each do |row|
puts row.join(" ")
end
end
def cheat
Board.print_grid(@grid)
end
def print
Board.print_grid(self.hidden_ships_grid)
end
end
| true |
bfb26123da21f9928a64b8c15aceeeb0cc1b78da
|
Ruby
|
shimoal/ruby-tests
|
/03_simon_says/simon_says.rb
|
UTF-8
| 966 | 3.90625 | 4 |
[] |
no_license
|
def echo (string)
string
end
def shout (string)
string.upcase
end
def repeat (words, a=2)
repeats = ' '
repeats = words.to_s + ' ' + words.to_s
while a > 2
repeats = repeats + ' ' + words.to_s
a -= 1
end
repeats
end
def start_of_word (word, a)
x = 0
start = ''
while x < a
start = start + word[x].to_s
x += 1
end
return start
end
def first_word (sentence)
word_array = sentence.split
return word_array[0]
end
def titleize (original)
words = original.split
x = 1
title = words[0].capitalize.to_s
while x < words.length
if words[x] == 'over' then
title = title + ' ' + words[x]
elsif words[x] == 'and' then
title = title + ' ' + words[x]
elsif words[x] == 'the' then
title = title + ' ' + words[x]
elsif words[x] == 'of' then
title = title + ' ' + words[x]
elsif words[x] == 'for' then
title = title + ' ' + words[x]
else
title = title + ' ' + words[x].capitalize
end
x +=1
end
return title
end
| true |
26400aad326ac72f9dd862c2879510e1986f320a
|
Ruby
|
hoshito/AtCoder
|
/diverta 2019 Programming Contest/main_b.rb
|
UTF-8
| 221 | 3.15625 | 3 |
[] |
no_license
|
r,g,b,n=gets.chomp.split(" ").map(&:to_i)
count = 0
(0..3000).each do |r_i|
(0..3000).each do |g_i|
tmp = n - r * r_i - g * g_i
if tmp >= 0 && tmp % b == 0 then
count += 1
end
end
end
puts count
| true |
223e61555ef8666e27d6c09970ea618d66b4d8e8
|
Ruby
|
kopylovvlad/vc_reader
|
/lib/vc_reader/config.rb
|
UTF-8
| 1,766 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
module VcReader
# here is only logic how to manipulate with data
class Config
attr_reader :vc_client, :link_repository
def initialize
@vc_client = VcClient.new
@link_repository = LinkRepository.new
end
def current_links
link_repository.current_links.map(&:render)
end
def first_fetch
html_body = @vc_client.first_fetch
find_links(html_body, '.news_widget a.news_item__title')
find_last_id(html_body)
nil
end
def load_prev_news
link_repository.cursor_to_prev
nil
end
def load_news
json = @vc_client.load_news(link_repository.last_id)
link_repository.last_id = json['last_id']
find_links(json['html'], 'a.news_item__title')
nil
end
# @return [String]
def get_link_url(index)
link_repository.find_by_index_and_mark(index).href
end
# @param index [Integer]
# @return [String]
def read_news(index)
link = link_repository.find_by_index_and_mark(index)
html_body = vc_client.get_page_body(link.href)
# html to markdown
converter = VcArticleToMarkdown.new(html_body)
converted_markdown = converter.call
MarkdownToTty.new(converted_markdown).call
end
def before_exit
@link_repository.save_data
nil
end
private
# @return [Array]
def find_links(html_body, links_class)
html_doc = Nokogiri::HTML(html_body)
link_repository.fill_links(html_doc.css(links_class))
nil
end
def find_last_id(html_body)
# or take from last links element
link_repository.last_id = Nokogiri::HTML(html_body).css('.news_widget.l-island-bg').first.attr('data-last_id')
nil
end
end
end
| true |
ed4310e98075a83d183517941f62e957a628eb92
|
Ruby
|
simeonwillbanks/mygists
|
/app/helpers/profile/tags_helper.rb
|
UTF-8
| 610 | 2.53125 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
module Profile::TagsHelper
# Public: By default, all requests are not considered a profile. However,
# the Profile::TagsHelper is mixed into profile requests, so we
# override the ApplicationHelper.profile? definition.
#
# Returns a TrueClass.
def profile?
true
end
# Public: Builds HTML title tag text from current tag and profile username
# for tags views.
#
# Examples
#
# page_title
# # => "Rails | simeonwillbanks | My Gists"
#
# Returns a String of the page title.
def page_title
super(current_tag.name, profile.username)
end
end
| true |
7ec6126141535d2c76e4e4020f6e312108b603cd
|
Ruby
|
vcavallo/dopa_core
|
/spec/models/dopa_core/leaderboard_spec.rb
|
UTF-8
| 2,545 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
require 'spec_helper'
module DopaCore
describe Leaderboard do
context "World Leaderboard" do
let!(:player_one) { FactoryGirl.create(:player_for_leaderboard, name: "Player One") }
let!(:player_two) { FactoryGirl.create(:player_for_leaderboard, name: "Player Two") }
let!(:player_three) { FactoryGirl.create(:player_for_leaderboard, name: "Player Three") }
player_one_points = [10]
let!(:player_one_action_one) {
FactoryGirl.create(:leaderboard_player_action, player: player_one, points_earned: player_one_points[0])
}
player_two_points = [20, 20, 35, 50]
let!(:player_two_action_one) {
FactoryGirl.create(:leaderboard_player_action, player: player_two, points_earned: player_two_points[0])
}
let!(:player_two_action_two) {
FactoryGirl.create(:leaderboard_player_action, player: player_two, points_earned: player_two_points[1])
}
let!(:player_two_action_three) {
FactoryGirl.create(:leaderboard_player_action, player: player_two, points_earned: player_two_points[2])
}
let!(:player_two_action_four) {
FactoryGirl.create(:leaderboard_player_action, player: player_two, points_earned: player_two_points[3])
}
player_three_points = [10, 10]
let!(:player_three_action_one) {
FactoryGirl.create(:leaderboard_player_action, player: player_three, points_earned: player_three_points[0])
}
let!(:player_three_action_two) {
FactoryGirl.create(:leaderboard_player_action, player: player_three, points_earned: player_three_points[1])
}
let(:board) { Leaderboard.world_leaderboard }
it "determines a global leaderboard of players" do
expect(board.first[:player_name]).to eq player_two.name
end
it "orders all players by total score" do
expect(
(board.first[:total_score] > board.second[:total_score]) \
&& (board.first[:total_score] > board.last[:total_score])
).to eq true
expect(
(board.last[:total_score] < board.second[:total_score]) \
&& (board.last[:total_score] < board.first[:total_score])
).to eq true
end
it "returns player scores along with player names" do
expect(board[0][:total_score]).to eq(player_two_points.inject{ |sum, x| sum + x} )
end
it "ascribes a rank to each player in the leaderboard" do
expect(board[0][:rank]).to eq 1
expect(board[2][:rank]).to eq 3
end
end
end
end
| true |
ec9859a9c1c6e651f80c9a0980444262eb0cc8fe
|
Ruby
|
joshuaneedham/ruby-learn
|
/test-area/lib/testing.rb
|
UTF-8
| 184 | 3.3125 | 3 |
[] |
no_license
|
def testing
empty_array = []
test_array = [1,2,3,4,5]
test_array.select do |number|
empty_array << number.even?
end
puts test_array
puts empty_array
end
| true |
3ac2a9059b344e485fc3571466479979923f2de7
|
Ruby
|
AlecR/coursegen
|
/lib/coursegen/cli.rb
|
UTF-8
| 1,435 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
require 'thor'
require 'coursegen/templates'
require 'nanoc'
require './cg_config.rb' if File.exist? 'cg_config.rb'
module CourseGen
class CLI < Thor
include Thor::Actions
desc "new COURSE", "Create a new course by calling nanoc. Argument is name of the COURSE"
def new(course)
run("nanoc create-site #{course}")
end
desc "prepare", "Update with the latest coursegen code and templates."
def prepare
check_valid_directory
tplt = CourseGen::Templates.new
tplt.generate_all
end
desc "compile", "build the course and put resultant site into output directory"
def compile
run("nanoc compile")
end
desc "serve", "start local web server to test the course web site"
def serve
run("nanoc view")
end
desc "reset", "reset all generated content to bring the course back to a base state."
def reset
run "rm -frd tmp"
run "rm -frd output"
end
desc "view", "view course site locally in browser"
def view
run "open http://0.0.0.0:3000"
end
desc "deploy", "Deploy course to S3"
def deploy
run "s3cmd sync --delete-removed output/ s3://#{AWS_BUCKET}/"
end
no_commands do
def check_valid_directory
if CourseGen::Templates.new.valid_cg_directory?
say("Valid cg directory")
else
error("Invalid cg directory")
end
end
end
end
end
| true |
b79ccccacaa9bddcfb15ac9be6232a43f8f3c7d4
|
Ruby
|
fanjieqi/LeetCodeRuby
|
/601-700/687. Longest Univalue Path.rb
|
UTF-8
| 537 | 3.359375 | 3 |
[
"MIT"
] |
permissive
|
# Definition for a binary tree node.
# class TreeNode
# attr_accessor :val, :left, :right
# def initialize(val)
# @val = val
# @left, @right = nil, nil
# end
# end
def depth(root, val)
root&.val != val ? 0 : [depth(root.left, val), depth(root.right, val)].max+1
end
# @param {TreeNode} root
# @return {Integer}
def longest_univalue_path(root)
return 0 if root.nil?
[depth(root.left, root.val) + depth(root.right, root.val), longest_univalue_path(root.left), longest_univalue_path(root.right)].max
end
| true |
363ec8c68b6e4f29e624f384c2e55fe35eaeab9a
|
Ruby
|
trivett/BEWD-NYC
|
/nikhita_kamath/class6/animals/main.rb
|
UTF-8
| 802 | 3.578125 | 4 |
[] |
no_license
|
require_relative 'lib/Dog'
require_relative 'lib/Cat'
require_relative 'lib/module'
dog1 = Dog.new(3,"a lot","bark at the mailman","spayed","super friendly","super cute","fierce")
dog2 = Dog.new(2,"a little","bark rarely","not spayed","not so friendly","uglyyy","not so fierce")
dog3 = Dog.new(1,"not at all","bark incessantly","spayed","antisocial","pretty","fierce")
cat1 = Cat.new("Trevor","persian",3,"spayed","charmer","beautiful","fierce")
cat2 = Cat.new("Katie","siamese",4,"not spayed","bookworm","gross","not so fierce")
cat3 = Cat.new("Eliza","manecoon",6,"spayed","hates everyone","gorgeous","fierce")
dogs = [dog1,dog2,dog3]
cats = [cat1, cat2, cat3]
dogs.each do |arf|
puts arf.ferocity
puts arf.talk
end
cats.each do |prr|
puts prr.name
puts prr.talk
puts prr.evilness
end
| true |
ec5e2eecd0f001573e07fde121f67f2e4f448241
|
Ruby
|
Msegun/hello-rspec-Msegun
|
/CodeQuizzes/spec/questionThirteen_spec.rb
|
UTF-8
| 337 | 3.28125 | 3 |
[] |
no_license
|
require_relative '../lib/questionThirteen'
class String
def alliteration?
letter = self[0]
self.split.all? do |w|
w[0] == letter
end
end
end
describe "#to_money" do
it "converts float to money format" do
expect(12.991.to_money).to eq '$12.99'
end
it "correctly rounds zeros" do
expect(9.0.to_money).to eq '$9.00'
end
end
| true |
50cb28d0a4f0ed4bd32927057718cfc3c723c11e
|
Ruby
|
tanyeun/scripts
|
/translate.rb
|
UTF-8
| 3,166 | 3 | 3 |
[] |
no_license
|
require 'optparse'
require 'ostruct'
require 'fileutils'
require 'pp'
options = OpenStruct.new
options.filename = ""
options.foldername = ""
options.str = ""
options.dst = ""
options.lang = ""
options.case = 0
OptionParser.new do |opts|
opts.banner = "Usage: translate.rb [options]"
opts.on("-f", "--file FILENAME", "Translate File") do |v|
options.case = 0
options.filename = v
end
opts.on("-F", "--Folder FOLDERNAME", "Translate Folder") do |v|
options.case = 1
options.foldername = v
end
opts.on("-s", "--string string", "Translate string") do |v|
options.case = 2
options.str = v
end
opts.on("-s", "--string string", "Translate string") do |v|
options.case = 2
options.str = v
end
opts.on("-l", "--language code", "Translate to what language, default is English") do |v|
options.lang = v
end
opts.on("-d", "--destination Folder", "Destination folder") do |v|
options.dst = v
end
# No argument, shows at tail. This will print an options summary.
# Try it and see!
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
end.parse!
if ( options.case == 0 )
# If no dst specified, save in current directory
if( options.dst == "")
current_dir = `pwd`.delete!("\n")
path = current_dir+"/output/"
else
path = options.dst+"/output/"
end
puts "Translate file: " + options.filename
unless File.directory?(path)
FileUtils.mkdir_p(path)
end
out = File.open(path+options.filename, "w")
File.open(options.filename, "r") do |f|
f.each_line do |line|
str = line.delete!("\n")
words = str.split(' ')
words.each do |x|
if ( x.match(/[[:alnum:]]/))
#puts x +" --valid"
cmd = "trans -id \""+x+"\""
output = `#{cmd} 2>/dev/null` # Ignore error msg
if ( output == "" )
lang = "Unknown"
else
lang = output.lines[1].split(' ')[1]
end
if ( lang == "\e[1mKorean\e[22m" )
cmd2 = "trans -b -no-auto "+":"+options.lang+" "+x
output2 = `#{cmd2}`
#puts x + " -- " + lang + " -- " + output2 #DEBUG
print output2.delete!("\n")
out.write output2
else
#puts x + " -- " + lang #DEBUG
print x+ ' '
out.write x+ ' '
end
else
#print x #DEBUG
print x+ ' '
out.write x+ ' '
end
end
puts ""
out.write "\n"
end
end
out.close
elsif ( options.case == 2 )
puts "Translate string: \n" + options.str
words = options.str.split(' ')
print "Result: \n"
words.each do |x|
if ( x.match(/[[:alnum:]]/))
puts x +" --valid"
Timeout::timeout(5) {
cmd = "trans -id \""+x+"\""
}
output = `#{cmd} 2>/dev/null` # Ignore error msg
if ( output == "" )
lang = "Unknown"
else
lang = output.lines[1].split(' ')[1]
end
if ( lang == "\e[1mKorean\e[22m" )
cmd2 = "trans -b "+":"+options.lang+" "+x
Timeout::timeout(5) {
output2 = `#{cmd2}`
}
print output2
#puts x + " -- " + lang + " -- " + output2
else
#puts x + " -- " + lang
print x+ ' '
end
else
print x+ ' '
end
end
puts ""
else
puts "Translate folder: " + options.foldername
end
| true |
6db77195cb6ebc0de77ca1707d5dc444afae5c1f
|
Ruby
|
pofystyy/codewars
|
/7 kyu/maximum_length_difference.rb
|
UTF-8
| 853 | 3.78125 | 4 |
[] |
no_license
|
# https://www.codewars.com/kata/5663f5305102699bad000056
# Details:
# You are given two arrays a1 and a2 of strings. Each string is composed with letters from a to z. Let x be any string in the first array and y be any string in the second array.
# Find max(abs(length(x) − length(y)))
# If a1 and/or a2 are empty return -1 in each language except in Haskell (F#) where you will return Nothing (None).
# #Example:
# a1 = ["hoqq", "bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"]
# a2 = ["cccooommaaqqoxii", "gggqaffhhh", "tttoowwwmmww"]
# mxdiflg(a1, a2) --> 13
# Bash note:
# input : 2 strings with substrings separated by ,
# output: number as a string
def mxdiflg(a1, a2)
return -1 if a1.empty? || a2.empty?
a2.product(a1).map { |i| (i[0].length - i[1].length).abs }.max
end
| true |
f744eedde7561e7f0b36d325897755ef09a548fb
|
Ruby
|
EthanGould/wdi_2_ruby_lab_rspec_geometry
|
/spec/triangle_spec.rb
|
UTF-8
| 723 | 3.328125 | 3 |
[] |
no_license
|
require 'spec_helper'
require_relative '../lib/triangle.rb'
describe Triangle do
before do
@triangle = Triangle.new(a: 10, b: 10, c: 10)
@second_triangle = Triangle.new(a: 7, b: 5, c: 10)
@third_triangle = Triangle.new(a: 8, b: 7, c: 20)
end
it 'calculates the perimeter of the triangle' do
expect(@triangle.perimeter).to eq 30
expect(@second_triangle.perimeter).to eq 22
end
it 'calculates the area of the triangle' do
expect(@triangle.area).to be_within(0.01).of (43.30)
expect(@second_triangle.area).to be_within(0.01).of (16.25)
end
it 'checks the triangle for validity' do
expect(@triangle.valid?).to eq true
expect(@third_triangle.valid?).to eq false
end
end
| true |
5b06753a96fc87ed12c2c0cac25498856210c04d
|
Ruby
|
ajth-work/ODIN
|
/practice-docs/ruby/BasicDataTypes/preparation.rb
|
UTF-8
| 125 | 2.53125 | 3 |
[] |
no_license
|
# preparation.rb
require "pry"
a = [1,2,3]
a << 4
binding.pry # execution should pause here for inspection purposes
puts a
| true |
fe4fa21797eb9e4ea30c2fe5d1d6acb017f4f82e
|
Ruby
|
dowlmic/AStar
|
/board.rb
|
UTF-8
| 5,598 | 3.40625 | 3 |
[] |
no_license
|
require_relative "cell"
class Board
attr_reader :board, :board_size, :start, :end
def initialize(length: 0, width: 0, with_random_barriers: true, percent_barriers: 25)
l, w = validate_parameters(length, width, percent_barriers)
@board_size = { length: l+2, width: w+2, num_cells: (l+2) * (w+2) }
initialize_board
@random_num_generator = Random.new
if with_random_barriers
randomize_barriers(percent_barriers)
end
@start = get_random_cell
@end = get_random_cell
calculate_distances
end
def to_s
@board.each_index do |i|
cell = @board[i]
if cell == @start
print "S"
elsif cell == @end
print "E"
elsif !cell.blocked
print " "
else
print "X"
end
if (i % (@board_size[:width]) == @board_size[:width] - 1)
print "\n"
end
end
end
def get_cell(row, col)
if row >= @board_size[:length] || row < 0 ||
col >= @board_size[:width] || col < 0
nil
else
@board[row*@board_size[:width] + col]
end
end
def get_random_row
@random_num_generator.rand(1...@board_size[:length] - 1)
end
def get_random_col
@random_num_generator.rand(1...@board_size[:width] - 1)
end
def get_random_cell
cell = nil
while !cell || cell.blocked || cell == @start || cell == @end
start_row = get_random_row
start_col = get_random_col
cell = get_cell(start_row, start_col)
end
cell
end
def find_cell(cell)
(0...@board_size[:length]).each do |row|
(0...@board_size[:width]).each do |col|
if get_cell(row, col) == cell
return row, col
end
end
end
nil
end
private
def validate_parameters(length, width, percent_barriers)
if length < 10
puts "Length cannot be less than 10... setting length to 10"
length = 10
end
if width < 10
puts "Width cannot be less than 10... setting width to 10"
width = 10
end
if percent_barriers >= 30
puts "Warning: algorithm to randomize barriers may not be able to" +
" find enough random cells to create barriers"
end
return length, width
end
def initialize_board
length = @board_size[:length]
width = @board_size[:width]
@board = Array.new(length*width);
@board.each_index do |i|
if (i % width == 0 || i % width == (width - 1) || (0..width).include?(i) ||
((@board.length - width - 1)[email protected]).include?(i))
@board[i] = Cell.new(blocked: true)
else
@board[i] = Cell.new(blocked: false)
end
end
end
def block_cell(row, col)
if row != 0 && row != (@board_size[:length] - 1) &&
col != 0 && col != (@board_size[:width] - 1) &&
blocking_cell_valid?(row, col)
get_cell(row, col).blocked = true
end
end
def blocking_cell_valid?(row, col)
blocked_neighbors = 0
if get_cell(row+1, col).blocked
blocked_neighbors += 1
end
if get_cell(row, col+1).blocked
blocked_neighbors += 1
end
if get_cell(row+1, col+1).blocked
blocked_neighbors += 1
end
if get_cell(row-1, col).blocked
blocked_neighbors += 1
end
if get_cell(row, col-1).blocked
blocked_neighbors += 1
end
if get_cell(row-1, col-1).blocked
blocked_neighbors += 1
end
if blocked_neighbors > 1
false
else
true
end
end
def randomize_barriers(percent_barriers)
num_cells = (@board_size[:width] - 2) * (@board_size[:length] - 2)
num_cells_to_block = (num_cells * percent_barriers / 100).ceil
length = @board_size[:length] - 2
width = @board_size[:width] - 2
max_cells_to_block = 0
if length < width
max_cells_to_block = length - 1
else
max_cells_to_block = width - 1
end
num_blocked_cells = 0
while num_blocked_cells < num_cells_to_block
if (num_cells_to_block - num_blocked_cells < max_cells_to_block)
max_cells_to_block = num_cells_to_block - num_blocked_cells
end
if (max_cells_to_block < 2)
num_cells = max_cells_to_block
else
num_cells = @random_num_generator.rand(1..max_cells_to_block)
end
which_blockage = @random_num_generator.rand(2)
row = 0
col = 0
while get_cell(row, col).blocked
row = get_random_row
col = get_random_col
end
if which_blockage == 0
blocked_cells = horizontal_bar_block(num_cells, row, col)
else
blocked_cells = vertical_bar_block(num_cells, row, col)
end
num_blocked_cells += blocked_cells
end
end
def horizontal_bar_block(num_cells, row, col)
num_blocked_cells = 0
can_continue_in_direction = true
count = 0
while num_blocked_cells < num_cells
if can_continue_in_direction
if get_cell(row, col+count).blocked || !block_cell(row, col+count)
count = 1
can_continue_in_direction = false
else
count += 1
num_blocked_cells += 1
end
else
if get_cell(row, col-count).blocked || !block_cell(row, col-count)
break
else
count += 1
num_blocked_cells += 1
end
end
end
num_blocked_cells
end
def vertical_bar_block(num_cells, row, col)
num_blocked_cells = 0
can_continue_in_direction = true
count = 0
while num_blocked_cells < num_cells
if can_continue_in_direction
if get_cell(row+count, col).blocked || !block_cell(row+count, col)
count = 1
can_continue_in_direction = false
else
count += 1
num_blocked_cells += 1
end
else
if get_cell(row-count, col).blocked || !block_cell(row-count, col)
break
else
count += 1
num_blocked_cells += 1
end
end
end
num_blocked_cells
end
def calculate_distances
end_row, end_col = find_cell(@end)
@board.each do |cell|
row, col = find_cell(cell)
cell.distance = (row - end_row).abs + (col - end_col).abs
end
end
end
| true |
0e020c495457662fbd72295b28d52dc06e65f2a1
|
Ruby
|
var114/Episode6
|
/models/vehicle.rb
|
UTF-8
| 599 | 3.453125 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
class Vehicle
@@vehicle = [] #can be used anywhere.
attr_reader :color, :make, :model, :year, :model
def initialize(hash={})
@@vehicle << self
@color = hash.fetch(:color)
@make = hash.fetch(:make)
@model = hash.fetch(:model)
@year = hash.fetch(:year)
end
def self.wheels
@wheels = nil
end
def self.vehicles
@@vehicle
end
def self.favorite_car
@@vehicle.select { |i| i.color == 'Blue' && i.model == 'Accord'} #select returns the ary that's true to the conditon
end
def to_s
"#{color}, #{make}, #{model}, #{year}"
end
end
| true |
bf4a9345b91df98347fb26f05c7592828fc3d1b5
|
Ruby
|
terryq/ruby-import-export-tools
|
/RubyExportImportTool/export_cards.rb
|
UTF-8
| 2,619 | 2.796875 | 3 |
[] |
no_license
|
require 'rally_rest_api'
require 'stuff'
class ExportCards
STORY_FIELDS = %w{Type Name Parent Owner Status Blocked Release Iteration PlanEstimate TaskEstimate TaskToDo TaskActuals Rank
Description Notes}
protected
# Should share with ExportStories class
def ExportCards.write_task(story_csv, task)
print " Task: ", task.name, "\n"
#Filter out deleted users
owner = task.owner ? task.owner : ""
owner = check_user(owner)
data = []
data << "Task"
data << task.name
data << nil
data << owner
data << task.state
data << task.blocked
data << nil #Release
data << nil #Iteration
data << nil #PlanEstimate
data << task.estimate ? task.estimate : ""
data << task.to_do ? task.to_do : ""
data << task.actuals ? task.actuals : ""
data << nil #Rank
data << task.description ? task.description : ""
data << task.notes ? task.notes : ""
story_csv << FasterCSV::Row.new(STORY_FIELDS, data)
end
def ExportCards.write_card(story_csv, card)
print "Story: ", card.work_product.name, "\n"
#Filter out deleted users
owner = card.owner ? card.owner : ""
owner = check_user(owner)
data = []
data << "Story"
data << card.work_product.name
data << nil
data << owner
data << card.state
data << card.blocked
data << (card.release ? card.release.name : "")
data << (card.iteration ? card.iteration.name : "")
data << card.plan_estimate
data << nil
data << nil
data << nil
data << card.rank
data << (card.description ? card.description : "")
data << (card.notes ? card.notes : "")
story_csv << FasterCSV::Row.new(STORY_FIELDS, data)
# breaks if there are duplicate task names.. I think
if card.tasks
card.tasks.each {|name, task| write_task(story_csv, task)}
# cards.tasks.values.flatten.each {|name, task| write_task(story_csv, task)}
end
end
public
# Only Works for UC Workspace
# Dumb for now, iterates through each Card and exports a Story
# Will even export a Story for a Card that is attached to a Defect - that is bad
def ExportCards.export(stuff, filename)
query_result = stuff.slm.find_all(:card, :project => stuff.project)
print "Exporting ", query_result.total_result_count, " Cards\n"
story_csv = FasterCSV.open(filename, "w")
story_csv << STORY_FIELDS
query_result.each {|card| write_card(story_csv, card)}
end
end
| true |
56c121fe53d36a32b221b91005aa8ea16c471b1a
|
Ruby
|
natalya-patrikeeva/ruby
|
/love.rb
|
UTF-8
| 126 | 3.234375 | 3 |
[] |
no_license
|
# Awww Love Note!
inf = (+1.0/0)
time = Time.new.hour
love = "\33[31mlove\33[0m"
while time < inf
puts "I #{love} you"
end
| true |
81c542a1ccb0faeeb28d81afb694afbe7d6e2736
|
Ruby
|
Brendaneus/the_odin_project
|
/ruby_on_rails/flight-booker/app/models/flight.rb
|
UTF-8
| 1,125 | 2.90625 | 3 |
[] |
no_license
|
class Flight < ApplicationRecord
belongs_to :origin, class_name: 'Airport',
inverse_of: :departing_flights
belongs_to :destination, class_name: 'Airport',
inverse_of: :arriving_flights
has_many :bookings
validates_presence_of :origin, :destination, :departure, :duration
validates :duration, numericality: { greater_than_or_equal_to: 30 }
validate :origin_is_not_destination
def departure_formatted
departure.strftime("%m/%d/%Y AT %H:%M%p")
end
def departure_date_formatted
departure.strftime("%m/%d/%Y")
end
# Credit to https://stackoverflow.com/a/1224769
def duration_in_words
minutes = (duration / 60).round
hours = minutes / 60
minutes = minutes - (hours * 60)
words = ""
words << "#{hours} #{ (hours == 1) ? 'hour' : 'hours' }" if hours > 0
words << ", " if hours > 0 && minutes > 0
words << "#{minutes} #{ (minutes == 1) ? 'minute' : 'minutes' }" if minutes > 0
words
end
private
# Validators
def origin_is_not_destination
if origin == destination
errors.add( :destination, "can't be Origin")
end
end
end
| true |
ce6b9560f3b3f50036e07e9cfd1e94902e620c47
|
Ruby
|
IceDragon200/edst-writing
|
/lib/edst/catalogue/relation_leaf.rb
|
UTF-8
| 2,111 | 2.984375 | 3 |
[
"Apache-2.0"
] |
permissive
|
require 'set'
module EDST
module Catalogue
class RelationLeaf
# the current character
attr_reader :character
GROUPS = [
:grand_parents,
:grand_children,
:biological_parents,
:adopted_parents,
:parents,
# parent siblings (aunts, uncles)
:piblings,
:biological_siblings,
:half_siblings,
:twin_siblings,
:adopted_siblings,
:siblings,
:biological_children,
:adopted_children,
:children,
# nephews, nieces
:chiblings,
:cousins,
:friends,
:spouses
]
GROUPS.each do |sym|
define_method sym do
@group_by_name[sym]
end
end
def initialize(character)
@character = character
@character.relation_leaf = self if @character
@groups = []
@group_by_name = {}
GROUPS.each do |group|
add_group group
end
end
def name
@character.name
end
def display_name
@character.display_name
end
private def add_group(name)
#result = Set.new
result = []
@group_by_name[name] = result
@groups << [name, result]
end
def ancestors
parents.inject([]) { |acc, parent| acc.concat(parent.ancestors) }
end
def descendants
children.inject([]) { |acc, child| acc.concat(child.descendants) }
end
def each(&block)
return to_enum :each unless block_given?
@groups.each do |_, values|
values.each(&block)
end
end
def each_relation
return to_enum :each_relation unless block_given?
@groups.each do |key, values|
yield key, values
end
end
def display_relations
puts "`#{name}` Relations"
each_relation do |key, values|
unless values.empty?
puts ":#{key}"
values.each do |v|
puts "\t#{v.name}"
end
end
end
end
end
end
end
| true |
75b2e2ee4c2c7a4345078861ea04f2aedacf4b2e
|
Ruby
|
felipekari/r06_ciclos
|
/lorem_generator.rb
|
UTF-8
| 581 | 2.796875 | 3 |
[] |
no_license
|
n = ARGV[0].to_i
i = 0
lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non molestie urna. Mauris dictum justo tempor erat mattis porttitor. Ut dignissim sodales lorem, vel tempor lectus gravida non. In libero erat, tempor congue aliquam quis, imperdiet quis dolor. Duis suscipit nisl accumsan risus rhoncus commodo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Integer congue neque efficitur, luctus ligula et, placerat mauris. Curabitur molestie lacinia augue in euismod."
while i < n
puts lorem
i += 1
end
| true |
76bdeff54a011a91e9bef7a24c294f8a2331d00f
|
Ruby
|
goneflyin/stockinfo
|
/lib/stock.rb
|
UTF-8
| 809 | 3.296875 | 3 |
[] |
no_license
|
require 'json'
class Stock
attr_reader :symbol, :name, :market_cap, :ipo_year, :sector, :industry
class << self
def add(data)
@stocks ||= []
@by_symbol ||= {}
stock = Stock.new(data)
@by_symbol[data[:symbol]] = stock
@stocks << stock
end
def find(symbol)
@by_symbol[symbol]
end
def search(symbol, limit = 10)
results = []
@stocks.each do |stock|
if stock.name.starts_with? symbol
results << stock
end
return results if results.length >= limit
end
results
end
end
def initialize(data)
@symbol = data[:symbol]
@name = data[:name]
@market_cap = data[:market_cap]
@ipo_year = data[:ipo_year]
@sector = data[:sector]
@industry = data[:industry]
end
end
| true |
c976104fcb39450c75cbf70357f2c5f7383eeb71
|
Ruby
|
jenmccarthy/artist_search
|
/spec/artist_spec.rb
|
UTF-8
| 1,623 | 3.078125 | 3 |
[] |
no_license
|
require 'rspec'
require 'artist.rb'
require 'work.rb'
describe Artist do
before do
Artist.clear
end
describe Artist.all do
it 'provides a place to hold all artist objects' do
expect(Artist.all).to eq []
end
end
it 'is initialized with a name and style' do
test_artist = Artist.new({'name' => 'Mary Cassatt', 'style' => 'Impressionism'})
expect(test_artist).to be_an_instance_of Artist
end
it 'lets you read out the name and style of an artist' do
test_artist = Artist.new({'name' => 'Mary Cassatt', 'style' => 'Impressionism'})
expect(test_artist.name).to eq 'Mary Cassatt'
expect(test_artist.style).to eq 'Impressionism'
end
it 'saves artist information into the collection' do
test_artist = Artist.new({'name' => 'Mary Cassatt', 'style' => 'Impressionism'})
expect(test_artist.save).to eq [test_artist]
end
it 'adds a work to a specific artist' do
test_artist = Artist.new({'name' => 'Mary Cassatt', 'style' => 'Impressionism'})
test_work = Work.new({'name' => 'Summertime', 'year' => '1894'})
test_artist.add_work(test_work)
expect(test_artist.works).to eq [test_work]
end
it 'searches an artist to return his/her works' do
test_artist = Artist.new({'name' => 'Mary Cassatt', 'style' => 'Impressionism'})
test_artist.save
test_work = Work.new({'name' => 'Summertime', 'year' => '1894'})
test_artist.add_work(test_work)
another_test_work = Work.new({'name' => 'At The Theater', 'year' => '1880'})
test_artist.add_work(another_test_work)
expect(test_artist.search).to eq [test_work, another_test_work]
end
end
| true |
2160e2093fb670f3f68592badd53bb7596c8c6fd
|
Ruby
|
HassanTC/Simple_web_projects
|
/Twitter-Spambot/micro_blogger.rb
|
UTF-8
| 2,129 | 2.828125 | 3 |
[] |
no_license
|
require 'jumpstart_auth'
require 'bitly'
Bitly.use_api_version_3
class MicroBlogger
attr_reader :client
# to initialize your Tweeter account
def initialize
puts "MicroBlogger is get Start in"
@client = JumpstartAuth.twitter
end
def shorten(original_url)
bitly = Bitly.new('hungryacademy', 'R_430e9f62250186d2612cca76eee2dbc6')
puts "Shortening this URL: #{original_url}"
bitly.shorten(original_url).short_url
end
# the function to post your tweets
def tweet(message)
if message.length <= 140
@client.update(message)
else
puts "Your Message Must be less than or equal 140 char"
end
end
# let's gets statet in any make a chooce
def run
puts "Welcome to the JSL Twitter Client!"
printf "enter command: (t)weet , (q)uit ,(dm)DirectMessage "
command = ""
command = gets.chomp
case command
when 't' then printf "Entre your Tweet."
t = gets.chomp
tweet(t)
puts "Your Tweet Succefully Published"
when 'q' then puts "Goodbye!"
when 'dm' then printf"Enter Your Target:- "
target = gets.chomp
puts ""
printf "Enter Your Message :- "
message = gets.chomp
dm(target,message)
else
puts "Sorry, I don't know how to #{command}"
end
end
#what about Direct Message
def dm(target, message)
puts "Trying to send #{target} this direct message:"
puts message
if is_there.include?(target)
str = "d #{target} #{message}"
tweet(str)
else
puts "You can only DM your followers!"
end
end
# check for valid follwer
def is_there
screen_names = @client.followers.collect{|follower| follower.screen_name}
end
def spam_my_followers(message)
followers = is_there
followers.each { |f| dm(f, message) }
end
# my frineds is tweets
def everyones_last_tweet
friends = @client.friends
friends.each do |friend|
tstamp = friend.status.created_at
puts "#{friend.screen_name} said the following on #{tstamp.strftime("%A, %b %d")}... #{friend.status.text}"
puts " "
end
end
end
blogger = MicroBlogger.new
blogger.run
| true |
8fa55b8b5aea5b180066af1fb99419bf7d26eddd
|
Ruby
|
joseph-jalbert/learn-to-program
|
/ask.rb
|
UTF-8
| 494 | 3.078125 | 3 |
[] |
no_license
|
def ask question
while true
puts question
reply = gets.chomp.downcase
if (reply == 'yes' || reply == 'no')
if reply == 'yes'
return true
else
return false
end
else
puts 'please answer "yes" or "no".'
end
end
end
puts "hell and blah blah"
puts
ask 'do u like tacos?'
ask 'do u like burritos?'
wets_bed = ask 'do you wet bed?'
ask ' u like chimichanga?'
puts
puts'thanks! thats will be all'
puts
puts wets_bed
| true |
993e722aeb4dbd291e47d3b74ddbfa4358130eb0
|
Ruby
|
pwnall/igor
|
/app/models/role.rb
|
UTF-8
| 1,663 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
# == Schema Information
#
# Table name: roles
#
# id :integer not null, primary key
# user_id :integer not null
# name :string(8) not null
# course_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# A privilege granted to an user.
class Role < ApplicationRecord
include RoleBase
before_destroy :preserve_site_bot
before_destroy :preserve_one_site_admin
# The auto-grading feature relies on a bot account to post grades.
def preserve_site_bot
throw :abort if name == 'bot'
end
private :preserve_site_bot
# There is no way to create an admin from an admin-less state through the UI.
def preserve_one_site_admin
throw :abort if (name == 'admin') && (Role.where(name: 'admin').count == 1)
end
private :preserve_one_site_admin
# Checks if a user has a privilege.
def self.has_entry?(user, role_name, course = nil)
self.where(user: user, name: role_name, course: course).count > 0
end
# Ensures that a user has a privilege.
#
# This creates a new Role if one doesn't already exist.
def self.grant(user, role_name, course = nil)
self.where(user: user, name: role_name, course: course).first_or_create!
end
# Ensures that a does not have a privilege.
#
# This deletes a Role if necessary.
def self.revoke(user, role_name, course = nil)
course_id = course.nil? ? nil : course.id
self.where(user_id: user.id, name: role_name, course_id: course_id).
destroy_all
end
# True if the given user can revoke this role.
def can_destroy?(user)
self.user == user || can_edit?(user)
end
end
| true |
12a93e9cc0536069f23c6b73d56c5295257bbdcf
|
Ruby
|
Patrick-Duvall/backend_prework
|
/day_4/ex3.rb
|
UTF-8
| 974 | 4.15625 | 4 |
[] |
no_license
|
#Binds input_file to first argument given when ex3.rb is run
input_file = ARGV.first
#Defines a method for printing a file (better than f.each {|x| puts x})??
def print_all(f)
puts f.read
end
#Defines a method to go to position 0 in a given file
def rewind(f)
f.seek(0)
end
#Defines a method to print a given line from a given file
def print_a_line(line_count, f)
puts "#{line_count}, #{f.gets.chomp}"
end
#Binds current_file to open input_file
current_file = open(input_file)
puts "First let's print the whole file:\n"
#Prints current_file
print_all(current_file)
puts "Now let's rewind, kind of like a tape."
#Calls rewind to go to position 0 in current_file
rewind(current_file)
puts "Let's print three lines:"
#Calls print_a_line 3 times incrementing current_line after each calling
current_line = 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
| true |
4ea4263b1acff1bc317f373e014caa1693ffd4fe
|
Ruby
|
kennyfrc/puzzlenode-solutions-1
|
/12_secret_messages/lib/secrets/caesar_cracker.rb
|
UTF-8
| 510 | 3.265625 | 3 |
[] |
no_license
|
require 'secrets/ciphers/caesar'
# XXX: Use something like Ruby-Wordnet to look for an English word
module Secrets
class CaesarCracker
def initialize(enc)
@enc = enc
end
def crack
puts "Which of these look right?"
cipher = Ciphers::Caesar.new
cipher.valid_shifts.each do |shift|
cipher.shift = shift
puts "%3s: #{cipher.decrypt(@enc)}" % shift
end
print "> "
cipher.shift = $stdin.gets.to_i
cipher.decrypt(@enc)
end
end
end
| true |
41e87adbbb4e772220ffe12c86e0d1ca603be279
|
Ruby
|
karenhunter01/MyFavsHTML
|
/ruby/chapter1Game.rb
|
UTF-8
| 449 | 3.9375 | 4 |
[] |
no_license
|
#!/usr/bin/ruby
n = rand(10);
puts "\nPlease enter your name: "
username = gets
username = username.chomp
max=10
min=0
puts username + ", guess a number from 1 - 10\n";
while min <= 10
guess = gets;
if guess.to_i == n
print "\nGood Job, You got it!!";
print "\nRandom number is " + n.to_s;
min = 11;
elsif guess.to_i < n
print "\nToo LOW, try again";
else
print "\nToo HI, try again";
end
min += 1;
puts
end
puts "\n\n"
| true |
b56c34806c6de3617bf5dd4af0c182e6be154d18
|
Ruby
|
GitHubAdmin/MDS3Builder
|
/app/models/fields/n2001.rb
|
UTF-8
| 751 | 2.703125 | 3 |
[] |
no_license
|
class N2001
attr_reader :options, :name, :field_type, :node
def initialize
@name = "Drug Regimen Review: Did a complete drug regimen review identify potential clinically significant medication issues? (N2001)"
@field_type = RADIO
@node = "N2001"
@options = []
@options << FieldOption.new("0", "No - No issues found during review -> Skip to O0100, Special Treatments, Procedures, and Programs")
@options << FieldOption.new("1", "Yes - Issues found during review -> Continue to N2003, Medication Follow-up")
@options << FieldOption.new("9", "NA - Resident is not taking any medications -> Skip to O0100, Special Treatments, Procedures, and Programs")
end
def set_values_for_type(klass)
return "9"
end
end
| true |
86490392867d11eb064a13201e6c63fc825b5da0
|
Ruby
|
a6ftcruton/literipsum
|
/test/ipsum_test.rb
|
UTF-8
| 1,063 | 3.09375 | 3 |
[] |
no_license
|
require 'test_helper'
require 'ipsum'
class IpsumTest < ActiveSupport::TestCase
# book = "Tom Sawyer"
# my_ipsum = Ipsum.new(book)
#
# my_ipsum.header_words(3)
# my_ipsum.sentences(3)
# my_ipsum.paragraphs(3)
# First step -> a gem that creates a yaml file (in the root dir) of the book being used
# -fork repo
# -create "db" (hash with (k,v) = title, identifier)
# -use this hash in formatter to create full url
# usage : my_ipsum = Ipsum.new("some title") => in the def book method, use Formater.normalize(input)
#
# Next step
# -scraping
# -error handling...what if the book isn't in the ProjGutenberg
def test_it_is_initialized_with_a_single_string
ipsum = Ipsum.new("Tom Sawyer")
assert_equal ipsum.book, "Tom Sawyer"
end
def test_it_raises_argument_error_when_initialized_with_no_args
assert_raises(ArgumentError) { Ipsum.new }
end
def test_it_raises_argument_error_when_initialized_with_more_than_one_arg
assert_raises(ArgumentError) { Ipsum.new.("firsbook", "secondbook") }
end
end
| true |
7d7e09295d95d751b395e309413f4e91cfae0594
|
Ruby
|
mawaldne/exercism_solutions
|
/ruby/hexadecimal/hexadecimal.rb
|
UTF-8
| 388 | 3.546875 | 4 |
[] |
no_license
|
class Hexadecimal
HEX_CHARS = { 'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15 }
def initialize(hex)
@hex = hex
end
def to_decimal
return 0 if @hex =~ /[g-z]/
@hex.reverse.chars.each_with_index.map do |ch, i|
if ch =~ /[0-9]/
ch.to_i * 16**i
elsif ch =~ /[a-f]/
HEX_CHARS[ch.to_sym] * 16**i
end
end.reduce(:+)
end
end
| true |
55d57ee8dad0b0970f7e311bf2b3c2c0b6bceaec
|
Ruby
|
Kunal8208/ruby_assignments
|
/day_3/day_3.rb
|
UTF-8
| 923 | 3.625 | 4 |
[] |
no_license
|
#Accept student detials with marks and display the same detais with percentage
class Student
attr_accessor :roll, :name, :percentage, :marks
def initialize
@marks=Array.new
end
def getDetails
print "Enter Roll No: "
@roll=gets.chomp.to_i
print "Enter Name: "
@name=gets.chomp
(0...5).each do |index|
print "Enter mark-#{index}: "
@marks << gets.chomp.to_i
end
end
def calc_percentage
sum=0
@marks.each{|a| sum+=a}
@percentage=((sum/500).to_f)*100
end
def displayDetails
calc_percentage
puts "Roll No: #{@roll}, Name: #{@name}, Percentage #{@percentage}"
end
end
students=Array.new
print "Enter no. of students: "
n=gets.chomp.to_i
n.times{|i| puts i}
n.times do |i|
puts "Enter Student-#{i+1} details: "
s=Student.new
s.getDetails
students << s
puts
end
puts "--------------Students Details with percentage are--------------"
n.times{|i| students[i].displayDetails}
| true |
7e63eba345c2174052847e76532f90a630bde707
|
Ruby
|
aqingsao/subway
|
/line.rb
|
UTF-8
| 733 | 3.546875 | 4 |
[] |
no_license
|
require File.join(File.dirname(__FILE__), 'station.rb')
class Line
attr_reader :name, :stations
def initialize(name, stations = [])
@name = name
@stations = []
stations.each{|station|add_station(station)}
end
def add_station(station)
@stations.push station
station.lines << self unless station.lines.include? self
end
def station_by_name(station_name)
@stations.detect {|station| station.name == station_name}
end
def max_station_number
result = @stations.collect{|station| station.number}.max
result.nil? ? 0 : result
end
def transferable_lines
lines = []
@stations.each do |station|
lines = lines + station.lines
end
lines.uniq - [self]
end
def ==(other)
self.name == other.name
end
end
| true |
418b13772d540516b3183f1799d104972776d04f
|
Ruby
|
arizuk/programming-contest-solutions
|
/gcj/2019/b/main.rb
|
UTF-8
| 1,069 | 3.15625 | 3 |
[] |
no_license
|
require 'logger'
logger = Logger.new('logfile.log')
def output(msg)
puts msg
STDOUT.flush
end
def init_rem
rem = {}
for c in 'A'..'E'
rem[c] = 24
end
rem
end
def resolve(rems)
ans = Array.new(4)
5.times do
rems.each_with_index do |rs, i|
rs = rs.reject { |c| ans.include?(c) }
if rs.size == 1
ans[i] = rs[0]
end
end
end
for c in 'A'..'E'
if !ans.include?(c)
ans.push(c)
return ans.join("")
end
end
end
t,f = STDIN.gets.strip.split.map(&:to_i)
t.times do
i = 0
base = 0
rem = init_rem
rems = []
f.times do
i += 1
if i == 119
i = 1
base += 1
rems << rem.keys
rem = init_rem
end
nth = base + 1 + (5*(i-1))
output nth
letter = STDIN.gets.strip
logger.info([i, base, nth, rem, letter])
rem[letter] -= 1
if rem[letter] == 0
rem.delete(letter)
end
end
ans = resolve(rems)
logger.info([rems, ans])
output resolve(ans)
STDOUT.flush
result = STDIN.gets.strip
if result != 'Y'
break
end
end
| true |
5d0fc8cc1f38a3ea13438548fe84534e6641cd85
|
Ruby
|
chrismay/warwick-sso-ruby
|
/lib/sso/client.rb
|
UTF-8
| 4,719 | 2.5625 | 3 |
[] |
no_license
|
require 'uri'
require 'net/http'
require 'net/https'
require 'yaml'
require 'sso/user'
require 'sso/memory_cache'
# Performs old-mode SSO against Websignon (i.e.
# checks the WarwickSSO cookie and sends a requestType=1
# to the Websignon sentry to get back user attributes.
#
# Include this module in your ApplicationController.
module SSO
module Client
OriginHost = 'websignon.warwick.ac.uk'
OriginPath = '/origin'
# cache SSO config in memory for 10 minutes
ConfigCacheSeconds = 600
def sso_filter
@memcache = MemoryCache.new(:sso_client) unless @memcache
@sso_config = @memcache.cached("sso_config",ConfigCacheSeconds) do
YAML.load_file(File.join(RAILS_ROOT,'config/sso_config.yml'))
end
@goduserlist = @memcache.cached("goduserlist",ConfigCacheSeconds) do
YAML.load_file(File.join(RAILS_ROOT,'config/godusers.yml'))
end
# WarwickSSO cookie has gone, so no more logged in for YOU
if not sso_cookie
logger.debug "SSO: No cookie, not signed in"
session[:sso_user] = nil;
elsif not session[:sso_user]
logger.debug "SSO: Cookie: #{sso_cookie}"
http = Net::HTTP.new(OriginHost, 443)
http.use_ssl = true
path = "#{OriginPath}/sentry?requestType=1&token=#{sso_cookie}"
resp, data = http.get(path,nil)
properties = parse_properties(data)
process_properties(properties)
end
end
def force_login_filter
if not logged_in?
logger.debug "force_login_filter redirecting to Websignon"
access_denied
end
end
def access_denied
if logged_in?
redirect_to login_url + "&error=permdenied"
else
redirect_to login_url + "&error=notloggedin"
end
end
def logged_in?
not current_user.nil?
end
def current_user
session[:sso_user]
end
def god_user?
@goduserlist.any? {|user| user==current_user.user_name }
end
def login_url
provider = URI.escape(@sso_config['provider_id'])
target = URI.escape(current_location)
"https://#{OriginHost}#{OriginPath}/slogin?providerId=#{provider}&target=#{target}"
end
def logout_url
target = URI.escape(current_location)
"https://#{OriginHost}#{OriginPath}/logout?target=#{target}"
end
def validate_user(username)
user = get_user(username)
!user.nil? and !user.disabled? and !user.email.nil?
end
def get_user(username)
if Rails.cache.exist? "user_properties_" + username
p = Rails.cache.read "user_properties_" + username
User.new(p)
else
path = "#{OriginPath}/sentry?requestType=4&user=#{username}"
http = Net::HTTP.new(OriginHost, 443)
http.use_ssl = true
resp, data = http.get(path,nil)
properties = parse_properties(data)
if properties[:returnType] == '4' and properties[:user]
Rails.cache.write("user_properties_" + username, properties)
User.new(properties)
else
User.new({:logindisabled=>"true",:user=>username,:name=>"Unknown user",:email=>"[email protected]"})
end
end
end
def find_users(f_name,s_name)
path = "#{OriginPath}/api/userSearch.htm?f_givenName=#{f_name}&f_sn=#{s_name}"
http = Net::HTTP.new(OriginHost, 443)
http.use_ssl = true
resp, data = http.get(path,nil)
users = Hash.from_xml(data)["users"]["user"]
if users.is_a? Array
users.collect {|u|
result = {}
u["attribute"].each {|f|
result[f["name"]] = f["value"]
}
result
}
elsif users.nil?
[]
else
result = {}
users["attribute"].each {|f|
result[f["name"]] = f["value"]
}
[result]
end
end
protected
def process_properties(p)
if p[:returnType] == '1' and p[:user]
session[:sso_user] = User.new(p)
logger.info "SSO: Signed in #{current_user.user_name}"
else
logger.info "SSO: Sign in failed, token wasn't valid (or no username returned)"
session[:sso_user] = nil
clear_sso_cookie
end
end
def current_location
@sso_config['uri_prefix'] + request.request_uri
end
# Get the WarwickSSO cookie
def sso_cookie
cookies['WarwickSSO']
end
def clear_sso_cookie
end
# parse properties format into a hash
def parse_properties(text)
properties = {}
text.each_line do |line|
line.scan(/^\s*(.+?)=(.+)\s*$/) {|key,val| properties[key.to_sym] = val }
end
properties
end
end
end
| true |
bb9a4555eb34ec8b562269ccb0b1e9329e834091
|
Ruby
|
bryanteng/algorithms
|
/ruby/graph_edges.rb
|
UTF-8
| 554 | 3.8125 | 4 |
[] |
no_license
|
# Count the number of different edges in a given undirected graph with no loops and multiple edges.
# For
#
# matrix = [[false, true, true],
# [true, false, false],
# [true, false, false]]
# the output should be graphEdges(matrix) = 2.
#
# [execution time limit] 4 seconds (rb)
def graphEdges(matrix)
matrix.uniq.length == 1 ? 0 : matrix.uniq.length
end
puts graphEdges([[false,true,true],
[true,false,false],
[true,false,false]]) == 2
puts graphEdges([[false,false,false],
[false,false,false],
[false,false,false]]) == 0
| true |
64732ddd2e86d6add4f3716352f8708fea73d145
|
Ruby
|
tommottom/ruby
|
/hello_class3.rb
|
UTF-8
| 434 | 4.15625 | 4 |
[] |
no_license
|
class HelloWorld
attr_accessor :name
def initialize(myname = "Ruby")
@name = myname
end
def hello
puts "Hello, world. I am #{@name}"
end
end
ruby = HelloWorld.new
bob = HelloWorld.new("Bob")
alice = HelloWorld.new("Alice")
#1番目のnameメソッドを実行しています。
p ruby.name
#2番目のname(value)メソッドを実行しています。(アクセスメソッドです)
p ruby.name = "Robert"
| true |
c61cf4172fa7396dbd03380e867b4bc20cda6784
|
Ruby
|
unepwcmc/pp-live-report
|
/app/serializers/chapter_dates_serializer.rb
|
UTF-8
| 498 | 2.890625 | 3 |
[] |
no_license
|
class ChapterDatesSerializer
def initialize(dates)
@dates = dates
end
def serialize
@dates.keys.each do |chapter|
['last_updated', 'next_updated'].each do |date_type|
chapter_dates = @dates[chapter]
date = Date.strptime(chapter_dates[date_type], '%b-%y')
chapter_dates[date_type] = date.strftime('%B %Y')
chapter_dates["#{date_type}_year"] = date.strftime('%Y')
end
end
@dates['home'] = @dates['chapter_3']
@dates
end
end
| true |
d39a2681fcdccef49582ed6fdd9174515c52b9d9
|
Ruby
|
Chux/viper-wiki
|
/RubyOnRails/Viper/app/helpers/application_helper.rb
|
UTF-8
| 1,546 | 2.546875 | 3 |
[] |
no_license
|
module ApplicationHelper
def wikiToHtml ( inputString )
rules = [
{:regex => /(\n[ ]*[^#* ][^\n]*)\n(([ ]*[#]([^\n]*)\n)+)/x, :replace => '\1<ol>' + "\n" + '\2' + '</ol>' + "\n"},
{:regex => /(\n[ ]*[^#* ][^\n]*)\n(([ ]*[*]([^\n]*)\n)+)/x, :replace => '\1<ul>' + "\n" + '\2' + '</ul>' + "\n"},
{:regex => /\n[ ]*[\*#]+([^\n]*)/x, :replace => '<li>\1</li>'},
{:regex => /[=]{6,6}([^=]+?)[=]{6,6}/,:replace => '<h6>\1</h6>'},
{:regex => /[=]{5,5}([^=]+?)[=]{5,5}/,:replace => '<h5>\1</h5>'}, # After h6...
{:regex => /[=]{4,4}([^=]+?)[=]{4,4}/,:replace => '<h4>\1</h4>'}, # After h5 and so on...
{:regex => /[=]{3,3}([^=]+?)[=]{3,3}/,:replace => '<h3>\1</h3>'},
{:regex => /[=]{2,2}([^=]+?)[=]{2,2}/,:replace => '<h2>\1</h2>'},
{:regex => /\[\[(.+?)\]\]/, :replace => '<a href="' + '\1' + '" rel="internal">' + '\1' + '</a>'}, # After _..._.
{:regex => /(http:\/\/+[\w.]*)/, :replace => '<a href="\1" rel="external">\1</a>'}, # After [[...]]
{:regex => /[\']{5}(.+?)[\']{5}/,:replace => '<strong><i>\1</i></strong>'},
{:regex => /[\']{3}(.+?)[\']{3}/, :replace => '<strong>\1</strong>' },
{:regex => /[\']{2}(.+?)[\']{2}/, :replace =>'<i>\1</i>' }
]
rules.each do |rule|
inputString = inputString.gsub(rule[:regex],rule[:replace])
end
return inputString
end
def urlizeTitle ( s )
s = s.gsub(/ /,'-')
return s
end
def deUrlizeTitle ( s )
s = s.gsub(/-/,' ')
return s
end
end
| true |
61092f169125cca068a32bbfbb052bd7d1535e50
|
Ruby
|
ypylypenko/algorithmable
|
/lib/algorithmable/cups/stacks_and_queues/stack_sorter.rb
|
UTF-8
| 551 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
module Algorithmable
module Cups
module StacksAndQueues
class StackSorter
include Algorithmable::DataStructs
def self.sort(stack)
new.sort(stack)
end
def sort(stack)
local_stack = new_lifo_queue
until stack.empty?
temp = stack.pop
while !local_stack.empty? && local_stack.peek < temp
stack.push local_stack.pop
end
local_stack.push temp
end
local_stack
end
end
end
end
end
| true |
a7adbc4c4278e82a1ce7b1361a43fcdf5878ca60
|
Ruby
|
camihayes/ruby_class_projects
|
/homework_project_one.rb
|
UTF-8
| 852 | 3.765625 | 4 |
[] |
no_license
|
#create dictionary hash with 10 city names
dial_book = {
"newyork" => "212",
"newbrunswick" => "732",
"tampa" => "727",
"denver" => "303",
"shreveport" => "318",
"knoxville" => "865",
"arizona" => "928",
"juneau" => "907",
"modesto" => "213",
"honolulu" => "808"
}
def get_city_names(somehash)
somehash.each{|k, v| puts k}
end
def get_area_code(somehash, key)
somehash[key]
end
loop do
puts "Do you want to look up an area code based on city name?(Y/N)"
answer = gets.chomp
if answer != "Y"
break
end
puts "Which city do you want the area code for?"
get_city_names(dial_book)
puts "Enter your selection"
prompt = gets.chomp
if dial_book.include?(prompt)
puts "The area code for #{prompt} is #{get_area_code(dial_book, prompt)}"
else
puts "You entered a name not in the dialbook."
end
end
| true |
e7118e37e05cd072262c2ddb3ed273fc48405c5a
|
Ruby
|
LewisYoul/ruby-kickstart
|
/session3/challenge/3_hashes.rb
|
UTF-8
| 581 | 4.375 | 4 |
[
"MIT"
] |
permissive
|
# Write a method that takes a string and returns a hash
# whose keys are all the downcased words in the string,
# and values are the number of times these words were seen.
#
# No punctuation will appear in the strings.
#
# Example:
# word_count "The dog and the cat" # => {"the" => 2, "dog" => 1, "and" => 1, "cat" => 1}
def word_count(str)
rtn_hash = Hash.new { |hash, key| hash[key] = 1 }
str.downcase.split(' ').each do |v|
if rtn_hash.has_key? v
rtn_hash[v] += 1
else
rtn_hash[v]
end
end
rtn_hash
end
#puts word_count "split me me up up up"
| true |
f8e1ea6eb57d89603fbfccf6a621371a8127f707
|
Ruby
|
birbalds/ride-share-two
|
/lib/driver.rb
|
UTF-8
| 1,430 | 3.1875 | 3 |
[] |
no_license
|
require 'csv'
module RideShare
class Driver
DRIVER_INFO = CSV.read('support/drivers.csv')
attr_accessor :driver_id, :name, :vin
def initialize(id)
raise ArgumentError, "#{id} is not a valid ID number, only positive whole numbers are accepted" unless id.is_a?(Integer) && id >= 1
raise ArgumentError, "#{id} Cannot be found" unless (DRIVER_INFO.map { |line| line[0].to_i }).include? id
DRIVER_INFO.each do |line|
next unless line[0].to_i == id
@driver_id = id
@name = line[1]
@vin = line[2]
end
raise ArgumentError, "#{vin} is an invalid VIN number" unless @vin.length == 17
end
def trips
Trip.driver_trips(@driver_id)
end
def avg_rating
@driver_trips = trips
avg_rating = (@driver_trips.map { |trip| trip.trip_rating.to_f }).reduce(:+) / @driver_trips.length
end
def self.all
@all_drivers = DRIVER_INFO.drop(1).map { |line| Driver.new(line[0].to_i) }
end
def self.find(id)
raise ArgumentError, "#{id} is not a valid ID number" unless id.is_a?(Integer) && id > 0
all
driver_found = (@all_drivers.map { |driver| driver if driver.driver_id == id }).compact!
end
end
end
# print RideShare::Driver.new(726_175)
| true |
e11d964f30e8abef023bc777176a129838397aaf
|
Ruby
|
jakolehm/ruby-packer
|
/ruby/benchmark/bm_vm1_blockparam_yield.rb
|
UTF-8
| 95 | 2.703125 | 3 |
[
"BSD-2-Clause",
"GPL-2.0-only",
"CC0-1.0",
"GPL-2.0-or-later",
"GPL-1.0-or-later",
"Autoconf-exception-generic",
"Artistic-1.0",
"Zlib",
"LicenseRef-scancode-unicode-mappings",
"dtoa",
"MIT",
"ISC",
"BSD-3-Clause",
"LicenseRef-scancode-unicode",
"FSFUL",
"BSD-4-Clause-UC",
"OFL-1.1",
"LicenseRef-scancode-warranty-disclaimer",
"Ruby",
"LicenseRef-scancode-public-domain",
"Bison-exception-2.2",
"LicenseRef-scancode-other-permissive",
"HPND-Markus-Kuhn",
"Artistic-1.0-Perl"
] |
permissive
|
def bp_yield &b
yield
end
i = 0
while i<30_000_000 # while loop 1
i += 1
bp_yield{}
end
| true |
a9bac081956d76503426097906480a7582ac18f8
|
Ruby
|
trikey/game_blackjack
|
/models/deck.rb
|
UTF-8
| 382 | 3.515625 | 4 |
[] |
no_license
|
class Deck
SUITS = ["\u2665", "\u2666", "\u2663", "\u2660"]
FACES = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'A', 'K', 'Q', 'J']
def initialize
@deck = Array.new(self.class.deck)
@deck.shuffle!
end
def take_card
@deck.pop
end
def self.deck
@deck ||= SUITS.map do |suit|
FACES.map { |face| Card.new(face, suit) }
end.flatten
end
end
| true |
b64e431081d53d73edfc84acd271b33203dd0299
|
Ruby
|
njpa/launchschool-ruby-basics
|
/06_user_input/06_passwords.rb
|
UTF-8
| 1,038 | 4.75 | 5 |
[] |
no_license
|
# EX 6
# ====
# Write a program that displays a welcome message, but only after the user
# enters the correct password, where the password is a string that is defined
# as a constant in your program. Keep asking for the password until the user
# enters the correct password.
# ANSWER
# ======
# 1) instantiate a variable named `password` and assign it to the string
# `"abracadabra"`.
# 2) create a `loop` skeleton directly underneath.
# 3) inside of the loop, ask the user for the password using `puts`
# 4) obtain the text using `gets`. Invoke `chomp` on the result.
# Instantiate a variable `password_entered` and assign it to the text
# obtained above.
# 5) insert a `break` statement with an `if` statement that checks that
# the entered text is equal to the `password` variable
# 6) outside of the `loop`, output a welcome message with `puts`.
PASSWORD = "abracadabra"
loop do
puts ">> Enter password: "
entered_password = gets.chomp
break if entered_password == password
puts "Invalid password!"
end
puts "Welcome!"
| true |
821edf64bc519c4ab50eb84fcc12bd5bbc39d220
|
Ruby
|
nabetani/yokohama.rb
|
/ruby_by_ruby/5.1.1.rb
|
UTF-8
| 1,408 | 3.296875 | 3 |
[
"Apache-2.0"
] |
permissive
|
require "minruby"
require "pp"
require "stringio"
def ppp(x)
PP.pp( x, $stdout, 20 )
end
def evaluate(tree)
case tree[0]
when "lit"
tree[1]
when "+"
left = evaluate(tree[1])
right = evaluate(tree[2])
left + right
when "-"
left = evaluate(tree[1])
right = evaluate(tree[2])
left - right
when "*"
left = evaluate(tree[1])
right = evaluate(tree[2])
left * right
when "/"
left = evaluate(tree[1])
right = evaluate(tree[2])
left / right
when "func_call"
p(evaluate(tree[2]))
else
raise "unknown tree item: #{tree[0]}"
end
end
def test_arithmetic_op(x, expected)
tree = minruby_parse(x)
ppp tree
value = evaluate( tree )
if value==expected
puts "value is #{value}, okay."
else
puts "value is #{value}, want #{expected}."
end
end
def output
io = StringIO.new
prev = $stdout
$stdout = io
val = nil
begin
val = yield
ensure
$stdout = prev
end
[io.string, val]
end
def test_p( x, exp_out, exp_value )
tree = minruby_parse(x)
ppp tree
out, value = output{ evaluate( tree ) }
p [ out, value ]
if exp_out==out && exp_value==value
puts "value is #{value}, out is #{out.inspect}, okay."
else
puts "value is #{value}, want #{exp_value}."
puts "out is #{out.inspect}, want #{exp_out.inspect}."
end
end
test_arithmetic_op( "(1+2)*3+4", 13 )
test_p( "p(1+2)", "3\n", 3 )
| true |
7101bb268b36f428efeef750d41a4a9618b9dafa
|
Ruby
|
coryodaniel/MerbMax
|
/lib/merb_max/meta.rb
|
UTF-8
| 1,794 | 2.875 | 3 |
[] |
no_license
|
module Merb
class Controller
class << self
alias :orig_inherited :inherited
# Default any subclasses meta tags to that of the parent
def inherited(klass)
orig_inherited(klass)
klass.meta(self.meta)
end
# Setter/Getter for meta Tags
#
# @param tags [Hash|Symbol|Nil]
# Hash => Sets the given meta tags
# NilClass => Returns the full hash of meta tags
# Symbol => Returns the specific meta tag
#
# @api public
def meta(tags = nil)
@meta_tags ||={}
if tags.is_a? Hash
@meta_tags.merge!(tags)
elsif tags.is_a? Symbol
return @meta_tags[tags]
end
@meta_tags
end
end
# Getter/Setter for a controller instance's meta tags
#
# @param tags [Hash|NilClass|Symbol]
# Hash => Sets the given meta tags
# NilClass => Outputs the HTML
# Symbol => Returns the specific meta tag
#
# @returns [Hash|String]
#
# @api public
def meta(tags = nil)
@meta_tags ||= self.class.meta.clone
if tags.is_a? Hash
@meta_tags.merge!(tags)
@meta_tags
elsif tags.is_a? Symbol
return @meta_tags[tags]
else
output_meta_tags @meta_tags
end
end
protected
# Outputs meta tags
#
# @param meta_data [Hash]
# Meta Tags to output
#
# @api private
def output_meta_tags(meta_data)
_meta_data = meta_data.clone
meta_title = _meta_data.delete :title
markup = meta_title ? %{<title>#{meta_title}</title>} : ''
_meta_data.each{|name,content|
markup << %{<meta name="#{name}" content="#{content}" />}
}
markup
end
end
end
| true |
56d6dd176f01379b6dbf4ab0056748e197936139
|
Ruby
|
copilotroadtrip/CoPilotBackend
|
/app/services/poi_service.rb
|
UTF-8
| 4,155 | 3.03125 | 3 |
[] |
no_license
|
class PoiService
# Eventually this should have the encoded coordinate string passed in
attr_reader :steps, :poi_info, :coord_info, :nested_poi, :places, :legs
def initialize(steps)
@steps = steps
@poi_info, @coord_info, @nested_poi = traverse_steps
@places = filter_poi
@legs = build_legs
end
def build_legs
legs = []
(1..(places.length-1)).each do |index|
poi_start = find_poi_info(places[index]).start_coord
prev_poi_start = find_poi_info(places[(index -1)]).start_coord
seconds = inter_coord_time(poi_start, prev_poi_start)
meters = inter_coord_dist(poi_start, prev_poi_start)
legs << LegInfo.new({"duration"=>{"value"=>seconds}, "distance"=>{"value"=>meters}})
end
return legs
end
def find_poi_info(poi)
poi_info.find{|info| info.poi == poi}
end
def inter_coord_dist(coord1, coord2)
coord_subset = find_coord_subset(coord1, coord2)
coord_subset.sum{ |coord_info| coord_info.meter_distance}
end
def inter_coord_time(coord1, coord2)
coord_subset = find_coord_subset(coord1, coord2)
coord_subset.sum{ |coord_info| coord_info.travel_time}
end
def find_coord_subset(coord1, coord2)
c1_idx = coord_info.index{ |c| c.coord == coord1}
c2_idx = coord_info.index{ |c| c.coord == coord2}
start, last = [c1_idx, c2_idx].sort
coord_info[(start+1)..last]
end
def filter_poi
unique_poi = nested_poi.flatten.uniq
major_poi = remove_overlapped(unique_poi)
major_poi = sort_by_appearance(major_poi)
# Add more filters
major_poi
end
def sort_by_appearance(major_poi)
major_poi.sort_by do |poi|
info = find_poi_info(poi)
index = coord_info.index{ |c| c.coord == info.start_coord}
# puts index
index
end
end
def remove_overlapped(unique_poi)
major_poi = []
poi_by_pop = unique_poi.sort_by{ |poi| poi.population}.reverse!
poi_by_pop.each do |poi|
poi_lists = all_including_poi(poi)
if always_largest(poi, poi_lists)
major_poi << poi
end
end
major_poi
end
def always_largest(poi, poi_nests)
poi_nests.all?{ |poi_list| poi.population == max_population(poi_list)}
end
def max_population(poi_list)
poi_list.max_by{ |poi| poi.population}.population
end
def all_including_poi(poi)
nested_poi.select{ |poi_list| poi_in_list?(poi, poi_list)}
end
def poi_in_list?(target_poi, poi_list)
poi_list.any?{ |poi| poi == target_poi}
end
def traverse_steps
### This needs to be fixed: correct step info not associated with each segment
### Also look into "normalizing" step speeds / distances with returned info
poi_info = []
coord_info = []
nested_poi = []
step_info = StepInfo.new(steps[0])
steps.each_with_index do |step, step_index|
coordinates = step_coordinates(step)
prev_coord = []
coordinates.each_with_index do |raw_coord, segment_index|
if segment_index == 1
step_info = StepInfo.new(step)
end
coord = Coordinate.new(raw_coord)
poi_list = Poi.poi_at_location(coord.lat, coord.lng)
nested_poi = update_nested_poi(poi_list, nested_poi)
poi_info = update_poi_info(poi_list, poi_info, coord)
coord_info = update_coord_info(coord, prev_coord, step_info, step_index, coord_info)
prev_coord = coord
end
end
return [poi_info, coord_info, nested_poi]
end
def update_coord_info(coord, prev_coord, step_info, step_index, coord_info)
coord_info << CoordInfo.new(coord, prev_coord, step_info, step_index)
coord_info
end
def update_nested_poi(poi_list, nested_poi)
if poi_list.length != 0
nested_poi << poi_list
end
return nested_poi
end
def update_poi_info(poi_list, poi_info, coord)
poi_list.each do |poi|
info = poi_info.find{ |i| i.poi == poi}
if info
info.update_end(coord)
else
poi_info << PoiInfo.new(poi, coord)
end
end
return poi_info
end
def step_coordinates(step)
Polylines::Decoder.decode_polyline(step['polyline']['points'])
end
end
| true |
6bf28e022e246bf9d22ea25ee5ba38d2bb087110
|
Ruby
|
xavier/exercism-assignments
|
/ruby/queen-attack/queens.rb
|
UTF-8
| 1,320 | 3.90625 | 4 |
[] |
no_license
|
class ChessBoard
SIZE = 8
COLUMN_SEPARATOR = " "
ROW_SEPARATOR = "\n"
def render
(0...SIZE).map do |row|
(0...SIZE).map do |col|
yield row, col
end.join(COLUMN_SEPARATOR)
end.join(ROW_SEPARATOR)
end
end
class Queens
DEFAULT_POSITIONS = {
white: [0, 3],
black: [7, 3]
}
attr_reader :white, :black
def initialize(positions = {})
start_positions = DEFAULT_POSITIONS.merge(positions)
@white = start_positions[:white]
@black = start_positions[:black]
raise ArgumentError, "cannot occupy same space" if same_space?
end
def attack?
same_row? || same_column? || diagonal?
end
def to_s
ChessBoard.new.render do |row, col|
render_board_item(row, col)
end
end
private
def same_space?
same_row? && same_column?
end
def same_row?
@white[0] == @black[0]
end
def same_column?
@white[1] == @black[1]
end
def diagonal?
dy = (@white[0] - @black[0]).abs
dx = (@white[1] - @black[1]).abs
dx == dy
end
BOARD_ITEM_WHITE = "W"
BOARD_ITEM_BLACK = "B"
BOARD_ITEM_EMPTY = "O"
def render_board_item(row, col)
case [row, col]
when @white then BOARD_ITEM_WHITE
when @black then BOARD_ITEM_BLACK
else BOARD_ITEM_EMPTY
end
end
end
| true |
3ee9fe6319e6e5eca408c66c6e4e298a153c0e17
|
Ruby
|
avineshwar/LicenseFinder
|
/lib/license_finder/license.rb
|
UTF-8
| 1,629 | 2.671875 | 3 |
[
"LicenseRef-scancode-unknown",
"MIT",
"GPL-1.0-only",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later"
] |
permissive
|
# frozen_string_literal: true
require 'license_finder/license/text'
require 'license_finder/license/template'
require 'license_finder/license/matcher'
require 'license_finder/license/header_matcher'
require 'license_finder/license/any_matcher'
require 'license_finder/license/none_matcher'
require 'license_finder/license/definitions'
module LicenseFinder
class License
class << self
def all
@all ||= Definitions.all
end
def find_by_name(name)
name ||= 'unknown'
all.detect { |l| l.matches_name? l.stripped_name(name) } || Definitions.build_unrecognized(name)
end
def find_by_text(text)
all.detect { |l| l.matches_text? text }
end
end
def initialize(settings)
@short_name = settings.fetch(:short_name)
@pretty_name = settings.fetch(:pretty_name, short_name)
@other_names = settings.fetch(:other_names, [])
@url = settings.fetch(:url)
@matcher = settings.fetch(:matcher) { Matcher.from_template(Template.named(short_name)) }
end
attr_reader :url
def name
pretty_name
end
def stripped_name(name)
name.sub(/^The /i, '')
end
def matches_name?(name)
names.map(&:downcase).include? name.to_s.downcase
end
def matches_text?(text)
matcher.matches_text?(text)
end
def eql?(other)
name == other.name
end
def hash
name.hash
end
private
attr_reader :short_name, :pretty_name, :other_names
attr_reader :matcher
def names
([short_name, pretty_name] + other_names).uniq
end
end
end
| true |
fad06c093fe17051fa69c53a4ba8cb457daa013f
|
Ruby
|
bandzoogle/mail_dump
|
/app/models/logged_mail.rb
|
UTF-8
| 1,303 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
require 'mail/fields/common/address_container'
class LoggedMail < ActiveRecord::Base
# attr_accessible :body, :from, :html, :raw, :subject, :to, :reply_to
serialize :from
serialize :reply_to
serialize :to
serialize :body
serialize :html
def has_text?
self.body.present?
end
def has_html?
self.html.present?
end
def from_addresses
from.respond_to?(:join) ? from.join(',') : from
end
def to_addresses
to.respond_to?(:join) ? to.join(',') : to
end
#
# implement #delivered_mail observer to log mail after the fact
#
def self.delivered_email(message)
# firgure out if the body is html or text
if message.multipart?
html = message.html_part
text = message.text_part
else
if message.content_type =~ /text\/html/
html = message.body
text = nil
else
text = message.body
html = nil
end
end
::LoggedMail.create(
:to => message.to,
:reply_to => message.reply_to,
:from => message.from,
:subject => message.subject,
:body => text,
:html => html,
:raw => message.to_s
)
end
end
| true |
5ad1ca11c629c27db8e544967a7846cdb07415ff
|
Ruby
|
eglital/prep_ruby_challenges
|
/factorial.rb
|
UTF-8
| 116 | 3.765625 | 4 |
[] |
no_license
|
def factorial(number)
result = 1
(1..number).each { |num| result *= num }
return result
end
puts factorial(5)
| true |
c6a2190bc7b4cf36a53d6210e807d6c51bb25178
|
Ruby
|
renewablefunding/spectifly-sequel
|
/lib/spectifly/sequel/model.rb
|
UTF-8
| 2,020 | 2.515625 | 3 |
[] |
no_license
|
module Spectifly
module Sequel
class Model
attr_accessor :table_name, :display_name, :model_name,
:single_value_fields, :multiple_value_fields,
:has_and_belong_to_many, :name_as_foreign_key,
:foreign_keys
def initialize(entity, fields)
@display_name = entity.root
@model_name = Spectifly::Support.camelize(display_name)
@table_name = Spectifly::Support.tokenize(ActiveSupport::Inflector.pluralize(display_name))
@single_value_fields = fields.select { |f| !f.multiple? }
@multiple_value_fields = fields.select { |f| f.multiple? }
@name_as_foreign_key = Spectifly::Support.tokenize(display_name) + '_id'
get_relationships(entity)
end
def get_relationships(entity)
@foreign_keys = []
@has_and_belong_to_many = []
entity.relationships.each do |relationship_type, rels|
camelized_type = Spectifly::Support.camelize(relationship_type)
rels.each do |name, attributes|
if %w(BelongsTo HasOne HasA).include? camelized_type
relation = create_relation(camelized_type, name, attributes, entity)
@foreign_keys << relation
elsif %(BelongsToMany HasAndBelongsToMany HasMany).include?(camelized_type)
relation = create_relation(camelized_type, name, attributes, entity)
# as long as the has_many has a coinciding belongs_to_many and the association table makes sense...
if relation.multiple_related_entity? && !(@name_as_foreign_key == relation.field_name && @table_name == relation.table_name)
@has_and_belong_to_many << relation
end
end
end
end
end
def create_relation(type, name, attributes, entity)
relationship_class = ActiveSupport::Inflector.constantize('Spectifly::Sequel::Relationship::%s' % type)
relation = relationship_class.new(name, attributes, entity)
end
end
end
end
| true |
02e22ac741ad378657f66431bf00f75683c90824
|
Ruby
|
nimalwyd/cpp
|
/src-rb/led_sign_server.rb
|
UTF-8
| 1,692 | 2.6875 | 3 |
[] |
no_license
|
# Base class
require 'webrick'
require 'webrick/https'
require 'json'
class LedSignServer < WEBrick::HTTPServlet::AbstractServlet
# Not meant to be used
def do_GET( request, response )
puts "#{__method__}"
HTTPAuth.basic_auth( request, response, "VPCRealm" ) {|user,pass|
user == 'locomobi' && pass == '70canuck'
}
response.body = "Authenticated OK"
status, content_type, body = handle_request( request )
response = set_response( response, status, content_type, body )
end
# This does the real work
def do_POST( request, response )
puts "#{__method__}"
# This next block does the authentication. If the authentication fails,
# then the code does not continue past the authentication part.
HTTPAuth.basic_auth( request, response, "VPCRealm" ) { |user, pass|
user == 'locomobi' && pass == 'firefighters'
}
status = handle_request( request )
response = set_response( response, status.status, status.content_type, status.body );
end
private
def handle_request( request )
$logger.write1 "#{__method__}::request looks like: \n\*****\n#{request}\n******"
@parsed_request = JSON.parse( request.body )
$logger.write1 "#{__method__}::parsed request: \"#{@parsed_request}\""
end
def set_response( response, status, content_type, body )
response.status = status
response[ 'Content-Type' ] = content_type
response[ 'Access-Control-Allow-Origin' ] = '*'
response[ 'Access-Control-Request-Method' ] = '*'
response.body = body
return response
end
end
| true |
66bddda94d3c4f02f8fd6011a1738c0e71d8becb
|
Ruby
|
vvj5/rails_todo
|
/app/controllers/todos_controller.rb
|
UTF-8
| 853 | 2.765625 | 3 |
[] |
no_license
|
class TodosController < ApplicationController
def index
render json: Todo.all
end
def new
render json: Todo.new
end
def create
render json: Todo.create(entry: params[:entry])
end
def show
begin
render json: Todo.find(params[:id])
rescue ActiveRecord::RecordNotFound => error
render json: { error: error.message }, status: 422
end
end
def delete
todo = Todo.find(params[:id])
todo.destroy
render json: { message: "Todo Detroyed" }
end
end
# Sending a DELETE request to http://localhost:3000/todos/1
# should delete that todo from the database and return
# the message “deleted” as json (Using Postman)
# Sending a POST request to http://localhost:3000/todos with the params of { "body": "Finish Homework" }
# I should see my todo returned to me as json (Using Postman)
| true |
ce70e18e31124d635ebae4f472f47ede968de33b
|
Ruby
|
BovvyBoy/OO-Get-Swole-london-web-051319
|
/tools/console.rb
|
UTF-8
| 613 | 3.03125 | 3 |
[] |
no_license
|
# You don't need to require any of the files in lib or pry.
# We've done it for you here.
require_relative '../config/environment.rb'
# test code goes here
dan = Lifter.new("Danny B", 180)
chris = Lifter.new("Chrissy A", 150)
ben = Lifter.new("Benny Boy", 120)
andy = Lifter.new("Andy Son", 100)
david_lloyds = Gym.new("David Lloyd")
virgin = Gym.new("Virgin Active")
gym = Gym.new("The Gym")
new = Membership.new(60, dan, virgin)
old = Membership.new(30, chris, gym)
maybe = Membership.new(80, ben, david_lloyds)
bonus = Membership.new(75, andy, virgin)
another = Membership.new(80, dan, gym)
binding.pry
puts "Gains!"
| true |
3b0ac450fa5149f4ea4b935341b67a5a38b00030
|
Ruby
|
smoline/codewars
|
/ruby/7kyu_regexp_basics_is_it_8bit_unsigned_number.rb
|
UTF-8
| 1,607 | 3.46875 | 3 |
[] |
no_license
|
# https://www.codewars.com/kata/regexp-basics-is-it-a-eight-bit-unsigned-number/train/ruby
require 'awesome_print'
class String
def eight_bit_number?
match(/^([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$/) ? true : false
end
end
answer = "".eight_bit_number?
ap answer
# false
answer = "0".eight_bit_number?
ap answer
# true
answer = "00".eight_bit_number?
ap answer
# false
answer = "55".eight_bit_number?
ap answer
# true
answer = "042".eight_bit_number?
ap answer
# false
answer = "123".eight_bit_number?
ap answer
# true
answer = "255".eight_bit_number?
ap answer
# true
answer = "256".eight_bit_number?
ap answer
# false
answer = "999".eight_bit_number?
ap answer
# false
answer = "2 55".eight_bit_number?
ap answer
# false
answer = "-255".eight_bit_number?
ap answer
# false
answer = "+255".eight_bit_number?
ap answer
# false
# Another Way
class String
def eight_bit_number2?
/\A(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\z/ === self
end
end
answer = "".eight_bit_number2?
ap answer
# false
answer = "0".eight_bit_number2?
ap answer
# true
answer = "00".eight_bit_number2?
ap answer
# false
answer = "55".eight_bit_number2?
ap answer
# true
answer = "042".eight_bit_number2?
ap answer
# false
answer = "123".eight_bit_number2?
ap answer
# true
answer = "255".eight_bit_number2?
ap answer
# true
answer = "256".eight_bit_number2?
ap answer
# false
answer = "999".eight_bit_number2?
ap answer
# false
answer = "2 55".eight_bit_number2?
ap answer
# false
answer = "-255".eight_bit_number2?
ap answer
# false
answer = "+255".eight_bit_number2?
ap answer
# false
| true |
d775d46b29f500be6813f75e040d9dba437eea9c
|
Ruby
|
AlistairTait12/makers_learning_notes
|
/week_4/calculator_exercise.rb
|
UTF-8
| 653 | 4.75 | 5 |
[] |
no_license
|
# Refactor the methods in the Calculator example into two classes as you see fit.
#
# class Calculator
# def add(number_1, number_2)
# number_1 + number_2
# end
# def subtract(number_1, number_2)
# number_1 - number_2
# end
# def print_answer(answer)
# "The Answer is: #{ answer }"
# end
# end
class Addition
def initialize(*numbers)
@numbers = numbers
end
def answer
@numbers.sum
end
def print_answer
"The Answer is: #{answer}"
end
end
class Subtraction
def initialize(a, b)
@a = a
@b = b
end
def answer
@a - @b
end
def print_answer
"The Answer is: #{answer}"
end
end
| true |
6c9b4829bdd2a97513e47d87632f59d3437e5425
|
Ruby
|
katiekeel/classroom-exercises
|
/week4/modules/student_2.rb
|
UTF-8
| 144 | 2.890625 | 3 |
[] |
no_license
|
module Student
class Hufflepuff
def cast_spell
puts "Expelliarmus!"
end
def speak
puts "I'm a Hufflepuff! Potato."
end
end
end
| true |
6fa099793fbf2f7537eb7ae0dc191d15a7a26fe2
|
Ruby
|
fiteclub/2020_advent
|
/day_01/report_repair_00.rb
|
UTF-8
| 664 | 3.84375 | 4 |
[] |
no_license
|
#!/usr/bin/ruby
require 'pry'
target_sum = 2020
file = "input.txt"
input_data = File.read("input.txt")
integer_array = input_data.split.map { |string| string.to_i }
def find_sum_pair(input_array, target)
sum_pair = [nil, nil]
input_array.each do |entry|
difference = (target.to_i - entry.to_i)
puts "Trying #{entry}, difference of #{difference}"
if input_array.include?(difference)
sum_pair[0] = entry
sum_pair[1] = difference
puts "Match found! #{sum_pair[0]} and #{sum_pair}[1]"
end
p sum_pair
end
sum_pair
end
binding.pry
answer = find_sum_pair(integer_array, target_sum)
puts answer[0] * answer[1]
puts "end"
| true |
c0dd00b176a39984eb151c7eaa1c4a66d1c2e5a9
|
Ruby
|
IonatanMocan/ruby-word-generator
|
/modules/words_importer_module.rb
|
UTF-8
| 233 | 2.71875 | 3 |
[] |
no_license
|
module WordsImporterModule
def words_importer_module(file_name)
result = []
file = File.read(@from_file)
file.each_line do |line|
result << line.downcase.chomp if line.chomp.length > 0
end
result
end
end
| true |
682f3a10d25e3fbd461c1a271b1ed697c68beba7
|
Ruby
|
ealwafai/war_or_peace
|
/spec/deck_spec.rb
|
UTF-8
| 1,993 | 3.078125 | 3 |
[] |
no_license
|
require 'rspec'
require '../lib/card'
require '../lib/deck'
describe Deck do
it 'deck setup' do
card1 = Card.new(:diamond, 'Queen', 12)
card2 = Card.new(:space, '3', 3)
card3 = Card.new(:heart, 'Ace', 14)
cards = [card1, card2, card3]
deck = Deck.new(cards)
expect(deck).to be_an_instance_of(Deck)
expect(deck.cards).to eq(cards)
end
it 'rank of cards' do
card1 = Card.new(:diamond, 'Queen', 12)
card2 = Card.new(:space, '3', 3)
card3 = Card.new(:heart, 'Ace', 14)
cards = [card1, card2, card3]
deck = Deck.new(cards)
expect(deck.rank_of_card_at(0)).to eq(12)
expect(deck.rank_of_card_at(2)).to eq(14)
end
it 'high ranking cards setup' do
card1 = Card.new(:diamond, 'Queen', 12)
card2 = Card.new(:space, '3', 3)
card3 = Card.new(:heart, 'Ace', 14)
cards = [card1, card2, card3]
deck = Deck.new(cards)
expected = [card1, card3]
expect(deck.high_ranking_cards).to eq(expected)
expect(deck.percent_high_ranking).to eq(66.67)
end
it 'remove card' do
card1 = Card.new(:diamond, 'Queen', 12)
card2 = Card.new(:space, '3', 3)
card3 = Card.new(:heart, 'Ace', 14)
cards = [card1, card2, card3]
deck = Deck.new(cards)
expected = [card2, card3]
remaining_high_ranking_cards = [card3]
expect(deck.remove_card).to eq(card1)
expect(deck.cards).to eq(expected)
expect(deck.high_ranking_cards).to eq(remaining_high_ranking_cards)
expect(deck.percent_high_ranking).to eq(50.0)
end
it 'add card' do
card1 = Card.new(:diamond, 'Queen', 12)
card2 = Card.new(:space, '3', 3)
card3 = Card.new(:heart, 'Ace', 14)
cards = [card1, card2, card3]
deck = Deck.new(cards)
deck.remove_card
card4 = Card.new(:club, '5', 5)
deck.add_card(card4)
expect(deck.cards).to eq([card2, card3, card4])
expected = [card3]
expect(deck.high_ranking_cards).to eq(expected)
expect(deck.percent_high_ranking).to eq(33.33)
end
end
| true |
960829d45fee61cab3f63c7c87e8c2cc6bef9aca
|
Ruby
|
repohoarder/UrlShortener
|
/app/models/url_datum.rb
|
UTF-8
| 734 | 2.609375 | 3 |
[] |
no_license
|
require 'uri'
class UrlDatum
include Mongoid::Document
include Mongoid::Timestamps
field :long_url, type: String
field :short_url, type: String
field :hits, type: Integer, default: 0
index({long_url: 1, short_url: 1})
index({short_url: 1})
before_save :create_short_url
def create_short_url
charset = Array('A'..'Z') + Array('0'..'9') + Array('a'..'z') + Array('0'..'9') + Array('A'..'Z') + Array('0'..'9')
self.short_url = Array.new(6) { charset.sample }.join
end
def get_complete_url
final_url = ''
if long_url =~ /https/
final_url = long_url
elsif long_url =~ /http/
final_url = long_url
else
final_url = 'http://' + long_url
end
final_url
end
end
| true |
3f9e82e61cf20364866d66f8373991d5e384f426
|
Ruby
|
deniznida/flatiron-bnb-methods-ruby-007-public
|
/app/models/city.rb
|
UTF-8
| 911 | 2.734375 | 3 |
[] |
no_license
|
class City < ActiveRecord::Base
has_many :neighborhoods
has_many :listings, :through => :neighborhoods
has_many :reservations, :through => :listings
def city_openings(checkin, checkout)
self.neighborhoods.collect do |neighborhood|
neighborhood.neighborhood_openings(checkin, checkout)
end.flatten
end
def reservations_count
listings.joins(:reservations).count
end
def listing_count
listing.count
end
def self.highest_ratio_res_to_listings
#self.joins(:listings).max_by {|city| city.reservations.count/city.listings.count.to_f}
self.joins(:listings).max_by {|city| city.reservations_count/city.listings.count.to_f}
end
def self.most_res
highest_city = ""
count = 0
self.all.each do |city|
if city.reservations.count > count
count = city.reservations.count
highest_city = city
end
end
highest_city
end
end
| true |
c031d735ec643a2815af2c7d72849f52068a1965
|
Ruby
|
Podenniy/falconmotors
|
/app/models/cart.rb
|
UTF-8
| 578 | 2.59375 | 3 |
[] |
no_license
|
class Cart < ActiveRecord::Base
has_many :line_items, dependent: :destroy
def total_price
line_items.to_a.sum { |item| item.total_price}
end
def add_price_part(price_part_id)
current_item = line_items.find_by_spare_part_id(price_part_id)
if current_item
current_item.quantity +=1
else
current_item = line_items.build(price_part_id: price_part_id)
current_item.price = current_item.price_part.price
end
current_item
end
def not_add_line_item
current_item = line_items.find_by_price_part_id(price_part_id)
end
end
| true |
7b6875c8d620c9fe6f84e1dab238d634192bbf30
|
Ruby
|
neontapir/lendr
|
/ruby/lib/domain/person.rb
|
UTF-8
| 236 | 2.5625 | 3 |
[] |
no_license
|
# frozen_string_literal: true
require_relative 'entity.rb'
require_relative '../events/author_created_event.rb'
class Person < Entity
attr_reader :name
private
def initialize(name = nil)
super()
@name = name
end
end
| true |
46f4b0009f9879f0e0b0c04965d899ebd220af77
|
Ruby
|
helmedeiros/ruby_bits
|
/level_4/3_dates/game.rb
|
UTF-8
| 206 | 3.03125 | 3 |
[
"Apache-2.0"
] |
permissive
|
require 'active_support/all'
def anniversary(game, years)
game[:release].advance(years: years)
end
game = {
name: 'Contra',
release: DateTime.new(1987, 2, 20, 0, 0, 0)
}
puts anniversary(game, 20)
| true |
ebff11c8a2d02f8250baac58992094cb9eafc3e9
|
Ruby
|
nathansobo/piston
|
/lib/piston/svn/revision.rb
|
UTF-8
| 1,904 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
require "piston/revision"
require "fileutils"
module Piston
module Svn
class Revision < Piston::Revision
def client
@client ||= Piston::Svn::Client.instance
end
def svn(*args)
client.svn(*args)
end
def name
"r#{revision}"
end
def checkout_to(path)
@wcpath = path.kind_of?(Pathname) ? path : Pathname.new(path)
answer = svn(:checkout, "--revision", revision, repository.url, path)
if answer =~ /Checked out revision (\d+)[.]/ then
if revision == "HEAD" then
@revision = $1.to_i
elsif revision != $1.to_i then
raise Failed, "Did not get the revision I wanted to checkout. Subversion checked out #{$1}, I wanted #{revision}"
end
else
raise Failed, "Could not checkout revision #{revision} from #{repository.url} to #{path}\n#{answer}"
end
end
def remember_values
str = svn(:info, "--revision", revision, repository.url)
raise Failed, "Could not get 'svn info' from #{repository.url} at revision #{revision}" if str.nil? || str.chomp.strip.empty?
info = YAML.load(str)
{ Piston::Svn::UUID => info["Repository UUID"],
Piston::Svn::REMOTE_REV => info["Revision"]}
end
def each
raise ArgumentError, "Revision #{revision} of #{repository.url} was never checked out -- can't iterate over files" unless @wcpath
svn(:ls, "--recursive", @wcpath).each do |relpath|
next if relpath =~ %r{/$}
yield relpath.chomp
end
end
def copy_to(relpath, abspath)
raise ArgumentError, "Revision #{revision} of #{repository.url} was never checked out -- can't iterate over files" unless @wcpath
Pathname.new(abspath).dirname.mkpath
FileUtils.cp(@wcpath + relpath, abspath)
end
end
end
end
| true |
350a0dae511f4a79c508a47d650a634a89229bcc
|
Ruby
|
michniewicz/TorrentClient
|
/lib/torrent_service.rb
|
UTF-8
| 5,375 | 2.609375 | 3 |
[] |
no_license
|
##
# Represents TorrentService class and its methods
#
class TorrentService
include NetworkHelper
# Connection handshake timeout in sec
HANDSHAKE_TIMEOUT = 5
def initialize(torrent_file)
@torrent_file = torrent_file
@files_to_load = []
@message_queue = Queue.new
@incoming_queue = Queue.new
@meta_info = parse_meta_info(File.open(@torrent_file))
@stop = false
@file_loader = nil
end
# parse meta info and set all variables that depend on that info
def init!
# just warn for now
PrettyLog.error('not enough free space') unless free_space_available?
@file_loader = FileLoader.new(@meta_info)
if @file_loader.content_exists?
@file_loader.restore_data
end
end
# start torrent client lifecycle
def start
init!
if @file_loader.completed?
PrettyLog.error('100%...seeding is still not implemented -- exit')
return
end
request_peers
@scheduler = Scheduler.new(@peers, @meta_info)
launch_processes
end
# stop downloading (currently unsafe)
def stop!
# check @file_loader loader was already initialized with data
if @file_loader
bytes = @file_loader.downloaded_bytes
params = TrackerInfo.tracker_params(@meta_info, bytes, :stopped)
NetworkHelper.get_request(@meta_info.announce, params)
end
PrettyLog.error(' ----- stop! method called -----')
@stop = true
ThreadHelper.exit_threads
end
# returns list of files described in metainfo
# @return [Array] files
def get_files_list
@meta_info.files
end
# set files selected for downloading
def set_priorities(files)
@files_to_load = files
# TODO call this before start download
end
private
def launch_processes
# TODO delete it when stable
Thread.abort_on_exception = true
@peers.each { |peer| peer.perform(@message_queue) }
run_lambda_in_thread(request_handler)
run_lambda_in_thread(incoming_message)
run_lambda_in_thread(file_loader)
end
# parse metainfo from given torrent file
# @param [String] torrent_file
def parse_meta_info(torrent_file)
MetaInfo.new(Bencode::Decoder.decode_file(torrent_file))
end
# lambda for RequestHandler object
def request_handler
-> { run(@scheduler.request_queue, nil, RequestHandler.new) }
end
# lambda for Message objects from array of messages
def incoming_message
-> { run(@message_queue, @incoming_queue, MessageHandler.new(@meta_info.piece_length)) }
end
# lambda for FileLoader and Scheduler objects
def file_loader
-> { run(@incoming_queue, nil, @file_loader, @scheduler) }
end
# run lambda block in a separate Thread
# @param [lambda] lambda_
def run_lambda_in_thread(lambda_)
Thread.new { lambda_.call }
end
# runs loop and listens for messages if messages exist in input queue
# @param [Queue] input
# @param [Queue] output
# @param [Array] handlers
def run(input, output = nil, *handlers)
loop do
# check to avoid race condition on threads exit in stop! method
break if @stop
message = input.pop
break unless message
if output
handlers.each { |handler| handler.process(message, output) }
else
handlers.each { |handler| handler.process(message) }
end
end
end
######## peers methods ##########
# set tracker params and set peers
def request_peers
bytes_so_far = @file_loader.downloaded_bytes
params = TrackerInfo.tracker_params(@meta_info, bytes_so_far, :started)
set_peers(params)
end
# performs request and unpacks peers host/port
def set_peers(params)
@peers = []
# peers: (binary model) the peers value is a string
# consisting of multiples of 6 bytes.
req = NetworkHelper.get_request(@meta_info.announce, params)
# split string per each 6 bytes
peers = Bencode::Decoder.decode(req)['peers'].scan(/.{6}/)
unpack_ports(peers).each do |host, port|
add_peer(host, port)
end
end
# handshake: <pstrlen><pstr><reserved><info_hash><peer_id>
# In version 1.0 of the BitTorrent protocol,
# pstrlen = 19 (x13 hex), and
# pstr = "BitTorrent protocol".
# reserved: eight (8) reserved bytes.
# All current implementations use all zeroes.
def add_peer(host, port)
begin
pstrlen = "\x13"
pstr = 'BitTorrent protocol'
reserved = "\x00\x00\x00\x00\x00\x00\x00\x00"
handshake = "#{pstrlen}#{pstr}#{reserved}#{@meta_info.info_hash}#{TrackerInfo::CLIENT_ID}"
Timeout.timeout(HANDSHAKE_TIMEOUT) { @peers << Peer.new(host, port, handshake, @meta_info.info_hash) }
rescue => exception
PrettyLog.error("#{__FILE__}:#{__LINE__} #{exception}")
end
end
def unpack_ports(peers)
# first 4 bytes of each peer are the IP address
# and last 2 bytes are the port number.
# All in network (big endian) notation
# no need to unpack host, it will be passed as a network byte
# ordered string to IPAddr::ntop
# result example: ["\xBC\x92\a\xA3", 6881] for single peer array
peers.map { |p| p.unpack('a4n') }
end
#################################
# checks if there is enough space on the hard drive
# @return true if available
def free_space_available?
info = StatVFS.new.info
free_bytes = info['f_bfree'] * info['f_bsize']
return free_bytes > @meta_info.total_size
end
end
| true |
9830b2000679c618dd4ba8c97f149c161580d5d5
|
Ruby
|
jeremyf/tor-probability
|
/lib/tor/probability/check.rb
|
UTF-8
| 2,951 | 3.1875 | 3 |
[] |
no_license
|
module Tor
module Probability
# A container for the different kinds of checks
module Check
# Originally extracted as a parameter object (because the
# `success_probability_for_given_check_or_later` method had too
# many parameters), this object helps encapsulate the data used
# to calculate each round's probability of success.
class Swn
PARAMETERS = [
:universe,
:modified_difficulty,
:reroll,
:chance_we_need_this_round,
:round,
:helpers
]
def initialize(**kwargs)
PARAMETERS.each do |param|
instance_variable_set("@#{param}", kwargs.fetch(param))
end
end
# @return [Universe] The universe of possible modified dice
# rolls.
attr_reader :universe
# @return [Integer] The check's Difficulty Class (DC) plus all
# of the modifiers (excluding those for rounds since dropping
# to 0 HP) affecting the 2d6 roll.
#
# @note for a Heal-2 medic with a Dex of +1 using a Lazurus
# Patch (DC 6) would have a modified_difficulty of
# 3. (e.g. 6 - 2 - 1 = 3)
#
# @note for an untrained medic with a Dex of -1 using a
# Lazurus Patch (DC 6) would have a modified_difficulty of
# 3. (e.g. 6 - (-1) - (-1) = 9)
attr_reader :modified_difficulty
# @return [Boolean] True if we allow a reroll.
attr_reader :reroll
# @return [Float] The probability that we need this round,
# range between 0.0 and 1.0.
attr_reader :chance_we_need_this_round
# @return [Integer] The round in which we start making checks;
# How many rounds prior did the victim drop to 0 HP/
attr_reader :round
# @return [HelperPool] Who are the helpers for this task
attr_reader :helpers
def next(**kwargs)
new_kwargs = {}
PARAMETERS.each do |param|
new_kwargs[param] = kwargs.fetch(param) do
instance_variable_get("@#{param}")
end
end
self.class.new(**new_kwargs)
end
# @return [Float]
def probability_of_success_this_round
dc = modified_difficulty + round
universe.chance_of_gt_or_eq_to(dc)
end
# @return [Float]
def chance_of_help_making_the_difference
dc = modified_difficulty + round
universe.chance_of_exactly(dc - 1) *
helpers.chance_someone_succeeds_at(dc)
end
# @param prob [Float] The probability of succeeding
#
# @return [Float]
def probability_of_reroll_makes_difference(prob:)
# If you don't get a re-roll, there's no chance of a reroll
# making the difference.
return 0.0 unless reroll
(1 - prob) * prob
end
end
end
end
end
| true |
eb574f1e536634b8efc1c09c68efff1eaa62c5a1
|
Ruby
|
torvick/panel_rh
|
/app/services/get_records.rb
|
UTF-8
| 658 | 2.6875 | 3 |
[] |
no_license
|
class GetRecords
def initialize(args)
@id_employee = args[:employee_id]
@id = args[:record_id]
@token = args[:current_user]
@options = {
headers: build_headers,
query:{}
}
end
# Public Interface
def self.send(*args)
new(*args).send!
end
def send!
@options[:query][:employee_id] = @id_employee if !@id_employee.nil?
HTTParty.get(build_url, @options)
end
def build_url
@id.nil? ? "#{ENV['URL_API']}/api/v1/registrations" : "#{ENV['URL_API']}/api/v1/registrations/#{@id}"
end
def build_headers
{
"Authorization" => "Bearer #{@token}"
}
end
end
| true |
6121612b099fa3c7ca85375e78dff09c3c54676b
|
Ruby
|
s1230057/Keisuke
|
/ITP1_2-B.rb
|
UTF-8
| 165 | 3.125 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
a, b, c = STDIN.gets.split.map(&:to_i)
a=b.to_i
b=b.to_i
c=b.to_i
puts(if a < b && b < c then
'Yes'
else
'No'
end)
| true |
5675b7a486f987438ef11871e3fc63db3251d7e9
|
Ruby
|
lime1024/rubybook
|
/chapter_04/4-3-7.rb
|
UTF-8
| 99 | 3.375 | 3 |
[] |
no_license
|
# [1, 2] と [3, 4] をつなげた配列を作って表示する
a = [1, 2]
b = [3, 4]
puts a + b
| true |
0c8c5ab427068ec75cdb39b927a3ae5ad6051c80
|
Ruby
|
ggustilo/phase-0
|
/week-5/group-research-methods/my_solution.rb
|
UTF-8
| 1,899 | 4 | 4 |
[
"MIT"
] |
permissive
|
# # Research Methods
# # I spent [] hours on this challenge.
# i_want_pets = ["I", "want", 3, "pets", "but", "only", "have", 2]
# my_family_pets_ages = {"Evi" => 6, "Ditto" => 3, "Hoobie" => 3, "George" => 12, "Bogart" => 4, "Poly" => 4, "Annabelle" => 0}
# # #
# Person 2
# pseudocode:
# iterate through the array
# if array item is a number,
# add thing_to_modify to the number
# else, leave the item alone
# return the array(?)
def my_array_modification_method!(source, thing_to_modify)
source.collect! do |item|
if item.is_a? Integer
item += thing_to_modify
else item
end
end
return source
end
# pseudocode:
# iterate through the hash
# add thing_to_modify to each hash value
# return the hash
def my_hash_modification_method!(source, thing_to_modify)
source.map do |k, v|
source[k] = v += thing_to_modify
end
return source
end
# Identify and describe the Ruby method(s) you implemented.
# I tried a bunch of different methods, but only some of them worked. Take a look below.
# Array methods:
# each : Doesn't work, because it doesn't permanently alter the array - non-destructive
# collect : Doesn't work, because it doesn't permanently alter the array - non-destructive
# collect! : Works - destructively alters the array
# map : Doesn't work, because it doesn't permanently alter the array - non-destructive
# map! : Works - destructively alters the array
#
# Hash methods:
# each : Works - destructively alters the array
# each_value : Doesn't work, because it doesn't permanently alter the array - non-destructive
# values : Doesn't work, because it doesn't permanently alter the array - non-destructive
# map : Works - destructively alters the array
# map! : Doesn't exist for hash
# collect : Works - destructively alters the array
# collect! : Doesn't exist for hash
| true |
b95b72b35150407c02778f608abd70a6d796d385
|
Ruby
|
reduviidae/module-one-holiday-project-dumbo-web-121018
|
/lib/user_total_score.rb
|
UTF-8
| 1,829 | 3.453125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# determines user mood
def user_total_score
# grabs the currently logged in user
user = User.all.find_by(logged_in: true)
# calculates cumulative average score and magnitude based on all liked quotes
score_sum = user.quotes.sum(:score)
magnitude_sum = user.quotes.sum(:score)
quote_count = user.quotes.length
score = score_sum / quote_count
magnitude = magnitude_sum / quote_count
# counts the number of quotes marked as positive, negative, and neutral
positive_count = user.quotes.where("sentiment = 'positive'").count
negative_count = user.quotes.where("sentiment = 'negative'").count
neutral_count = user.quotes.where("sentiment = 'neutral'").count
# performs simple analysis and returns results based on cumulative score and magnitude
case
when score > 0.5 && magnitude > 0.5
puts "Based on this sample of quotes, it would seem that #{user.name} is very positive!"
when score > 0.1 && magnitude > 0.2
puts "Based on this sample of quotes, it would seem that #{user.name} is somewhat positive."
when score < 0 && magnitude > 0.5
puts "Based on this sample of quotes, it would seem that #{user.name} is very negative."
when score < 0 && magnitude > 0.2
puts "Based on this sample of quotes, it would seem that #{user.name} is somewhat negative."
when (0..0.19).include?(magnitude)
puts "Based on this samle of quotes, it would seem that #{user.name} is pretty neutral"
when (0...0.1).include?(score) && magnitude > 0.2
puts "Based on this samle of quotes, it would seem that #{user.name} is a mixed bag!"
end
puts "Score: #{score}"
puts "Magnitude: #{magnitude}"
puts "#{user.name} has liked #{positive_count} positive quotes, #{negative_count} negative quotes, and #{neutral_count} neutral quotes."
# return to start menu
menu
end
| true |
96b5346e89fce231777323088d1a35d46863b334
|
Ruby
|
ngoalvin/jungle-rails
|
/spec/models/user_spec.rb
|
UTF-8
| 2,092 | 2.640625 | 3 |
[] |
no_license
|
require 'rails_helper'
RSpec.describe User, type: :model do
describe 'Validations' do
it "is valid with valid attributes" do
@user = User.new(name: "Alvin", email: "[email protected]", password: "123456789")
@user.save!
expect(@user).to be_valid
end
it "is valid with valid attributes" do
@user = User.new(name: "Alvin", email: "[email protected]", password: "123456789")
@user.save!
@user2 = User.new(name: "Alvin", email: "[email protected]", password: "123456789")
@user2.save
expect(@user2).to_not be_valid
end
it "is invalid with only name" do
@user = User.new(name: "Alvin")
@user.save
expect(@user).to_not be_valid
end
it "is invalid with only email" do
@user = User.new(email: "[email protected]")
@user.save
expect(@user).to_not be_valid
end
it "is invalid with only password" do
@user = User.new(password: "123456789")
@user.save
expect(@user).to_not be_valid
end
end
describe '.authenticate_with_credentials' do
it "logs user in with valid credentials" do
@user = User.new(name: "Alvin", email: "[email protected]", password: "123456789")
@user.save
user = User.authenticate_with_credentials("[email protected]", "123456789")
expect(user).to be == @user
end
it "does not log user in with invalid credentials" do
@user = User.new(name: "Alvin", email: "[email protected]", password: "123456789")
@user.save
user = User.authenticate_with_credentials("[email protected]", "1234")
expect(user).to_not be == @user
end
it "logs in user with caps" do
@user = User.new(name: "Alvin", email: "[email protected]", password: "123456789")
@user.save
user = User.authenticate_with_credentials("[email protected]", "123456789")
expect(user).to be == @user
end
it "logs in user with whitespace" do
@user = User.new(name: "Alvin", email: "[email protected]", password: "123456789")
@user.save
user = User.authenticate_with_credentials(" [email protected] ", "123456789")
expect(user).to be == @user
end
end
end
| true |
f0af6f4bde95637159c0142feb664f4b5cddbe60
|
Ruby
|
le3ah/LaughTracks
|
/spec/features/statistic_calculations_spec.rb
|
UTF-8
| 1,995 | 2.625 | 3 |
[] |
no_license
|
RSpec.describe "As a visitor" do
it "can see the average age of all comedians" do
Comedian.create(name: "Jim Carrey", age: 56, city: "Newmarket")
Comedian.create(name: "Demetri Martin", age: 45, city: "New York City")
Special.create(special_name: "All in Good Taste", run_time: 85)
Special.create(special_name: "Demetri Martin: The Overthinker", run_time: 54)
visit '/comedians'
within "#stats" do
expect(page).to have_content("The average age of all comedians on this site is #{Comedian.average_age}.")
expect(page).to have_content("#{Special.average_run_time} minutes.")
expect(page).to have_content("U.S. & Canada, including #{Comedian.unique_cities.join(', ')}.")
end
end
describe "As a visitor" do
it "they see the statistics of the comedians matching the specified age" do
comedian_1 = Comedian.create(name: "Dana Carvey", age: 63, city: "Missoula")
comedian_1.specials.create(special_name: "Straight White Male, 60", run_time: 64, thumbnail: "/images/specials/straigh-white-male-60.jpg")
comedian_2 = Comedian.create(name: "Jim Gaffigan", age: 52, city: "Elgin")
comedian_2.specials.create(special_name: "Cinco", run_time: 73, thumbnail: "/images/specials/Cinco.jpg")
comedian_2.specials.create(special_name: "Obsessed", run_time: 79, thumbnail: "/images/specials/Obsessed.jpg")
comedian_2.specials.create(special_name: "Jim Gaffigan: Mr. Universe", run_time: 74, thumbnail: "/images/specials/MrUniverse.jpg")
comedian_12 = Comedian.create(name: "Adam Sandler", age: 52, city: "Brooklyn")
comedian_12.specials.create(special_name: "100% Fresh", run_time: 73, thumbnail: "/images/specials/100-fresh.jpg")
visit '/comedians?age=52'
expect(page).to have_content("The average age of all comedians on this site is 52.")
expect(page).to have_content("74 minutes.")
expect(page).to have_content("U.S. & Canada, including Elgin", "Brooklyn")
expect(page).to have_content("this site is 4")
end
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.