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 |
---|---|---|---|---|---|---|---|---|---|---|---|
0ebf2d537c55c6fdc5c39540c5cca9dd0ce10f01
|
Ruby
|
prcaen/psd-reader
|
/lib/psd/read/sections/header.rb
|
UTF-8
| 2,126 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
module Psd
module Read
module Sections
class Header
attr_reader :channels, :color_mode, :depth, :height, :version, :width
def initialize(stream)
LOG.info("### HEADER ###")
@stream = stream
end
def parse
signature = BinData::String.new(read_length: LENGTH_SIGNATURE).read(@stream).value
unless signature == SIGNATURE_PSD
raise SignatureMismatch.new("PSD/PSB signature mismatch")
end
@version = BinData::Uint16be.read(@stream).value
unless @version == VERSION_PSD || @version == VERSION_PSB
raise VersionMismatch.new("PSD/PSB version mismatch")
end
reserved = BinData::Uint48be.read(@stream).value
unless reserved == 0
raise Exception.new("Reserved header must be 0")
end
@channels = BinData::Uint16be.read(@stream).value
if channels < 1 || channels > 56
raise ChannelsRangeOutOfBounds.new("Channels supported is 1 to 56, excpected: #{channels}")
end
@height = BinData::Uint32be.read(@stream).value
@width = BinData::Uint32be.read(@stream).value
if version == VERSION_PSD
if width < 1 || width > PIXELS_MAX_PSD || height < 1 || height > PIXELS_MAX_PSD
raise SizeOutOfBounds.new("Out of bounds: width: #{width}px, height: #{height}px")
end
else
if width < 1 || width > PIXELS_MAX_PSB || height < 1 || height > PIXELS_MAX_PSB
raise SizeOutOfBounds.new("Out of bounds: width: #{width}px, height: #{height}px")
end
end
@depth = BinData::Uint16be.read(@stream).value
unless SUPPORTED_DEPTH.include? @depth
raise DepthNotSupported("Depth #{@depth} is not supported.")
end
@color_mode = BinData::Uint16be.read(@stream).value
unless COLOR_MODE.include? @color_mode
raise ColorModeNotSupported("Color mode #{@color_mode} is not supported.")
end
end
end
end
end
end
| true |
bdac2b0a10c432f53e745f6b8639c969f8f585d5
|
Ruby
|
Charliemowood/learn-ruby-the-hard-way
|
/ex3.rb
|
UTF-8
| 1,254 | 4.5 | 4 |
[] |
no_license
|
# the cars variable is assigned the value of 100
cars = 100
# the space_in_a_car variable is assigned the value of 4.0 because the average can be a decimal point. This is called a floating point.
space_in_a_car = 4.0
# ditto drivers without a floating points drivers can only be whole numbers. Also interesting to note that variables are like nouns.
drivers = 30
# ditto
passengers = 90
# Now we are using previously declared variables to make new variables using basic operators.
cars_not_driven = cars - drivers
# ditto
cars_driven = drivers
# ditto
carpool_capacity = cars_driven * space_in_a_car
# ditto
average_passengers_per_car = passengers / cars_driven
# Just an interesting note, to call a variable's value in a string, you use the notation: #{}.
puts "There are #{cars} cars available."
puts "There are only #{drivers} drivers available"
puts "There will be #{cars_not_driven} empty cars today."
puts "We can transport #{carpool_capacity} people today."
puts "We have #{passengers} to carpool today"
puts "We need to put about #{average_passengers_per_car} in each car."
# What is the difference between '=' and '=='? "=' Assigns value on the right, to variable on the left. '==' asks the questions whether the value are truly equal or not?
| true |
11239be1302e891229c9c5203a7b171c697c0f8e
|
Ruby
|
evawiedmann/rock-paper-scissors
|
/lib/rock_paper_scissors.rb
|
UTF-8
| 1,108 | 3.59375 | 4 |
[] |
no_license
|
class Game
@@weapons = {
"1" => "rock",
"2" => "scissors",
"3" => "paper"
}
def initialize(input)
@input = '1'
@input2 = '2'
@input3 = '3'
end
def throw(input)
# @random = rand(1..3).to_s
@random1 = '1'
@random2 = '2'
@random3 = '3'
if (@@weapons.fetch(@input) == 'rock') & (@@weapons.fetch(@random2) =='scissor')
puts "rock wins"
return 'rock wins'
elsif (@@weapons.fetch(@input) == 'rock') & (@@weapons.fetch(@random3) =='paper')
puts "paper wins"
return "paper wins"
elsif (@@weapons.fetch(@input) == 'rock') & (@@weapons.fetch(@random1) =='rock')
puts "tie"
return "tie"
elsif (@@weapons.fetch(@input2) == 'scissors') & (@@weapons.fetch(@random1) =='rock')
puts "rock wins"
return "rock wins"
elsif (@@weapons.fetch(@input2) == 'scissors') & (@@weapons.fetch(@random3) =='paper')
puts "scissors wins"
return "scissors"
elsif (@@weapons.fetch(@input2) == 'scissors') & (@@weapons.fetch(@random2) =='scissors')
puts "tie"
return "tie"
end
end
end
| true |
9aa969c5a09a6e12f68b9954419c12d6ddb38332
|
Ruby
|
UbuntuEvangelist/therubyracer
|
/vendor/cache/ruby/2.5.0/gems/fog-rackspace-0.1.6/lib/fog/rackspace/examples/compute_v2/delete_network.rb
|
UTF-8
| 2,212 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
# This example demonstrates deletes a private network and attaching it to a new server with the Rackpace Open Cloud
require 'rubygems' #required for Ruby 1.8.x
require 'fog'
def wait_for_server_deletion(server)
begin
server.wait_for { state = 'DELETED' }
rescue Fog::Compute::RackspaceV2::NotFound => e
# do nothing
end
end
# I have notice that cloud networks is slow to acknowledge deleted servers. This method tries to mitigate this.
def delete_network(network)
attempt = 0
begin
network.destroy
rescue Fog::Compute::RackspaceV2::ServiceError => e
if attempt == 3
puts "Unable to delete #{network.label}"
return false
end
puts "Network #{network.label} Delete Fail Attempt #{attempt}- #{e.inspect}"
attempt += 1
sleep 60
retry
end
return true
end
def get_user_input(prompt)
print "#{prompt}: "
gets.chomp
end
# Use username defined in ~/.fog file, if absent prompt for username.
# For more details on ~/.fog refer to http://fog.io/about/getting_started.html
def rackspace_username
Fog.credentials[:rackspace_username] || get_user_input("Enter Rackspace Username")
end
# Use api key defined in ~/.fog file, if absent prompt for api key
# For more details on ~/.fog refer to http://fog.io/about/getting_started.html
def rackspace_api_key
Fog.credentials[:rackspace_api_key] || get_user_input("Enter Rackspace API key")
end
# create Next Generation Cloud Server service
service = Fog::Compute.new({
:provider => 'rackspace',
:rackspace_username => rackspace_username,
:rackspace_api_key => rackspace_api_key,
:version => :v2, # Use Next Gen Cloud Servers
:rackspace_region => :ord #Use Chicago Region
})
# NOTE: The network must not be connected to any servers before deletion
# Find alpha bits server
server = service.servers.find {|s| s.name == 'alphabits'}
puts "\n"
if server
puts "Deleting alphabits server..."
server.destroy
else
puts "Unable to find server alphabits"
end
wait_for_server_deletion(server)
network = service.networks.find {|n| n.label == 'my_private_net'}
delete_network(network)
puts "The network '#{network.label}' has been successfully deleted"
| true |
6e49135dd5ff6631ef927c3e38f9510c6a55b0d7
|
Ruby
|
emegill/MorningProblems
|
/MorningProblem23/ruby.rb
|
UTF-8
| 648 | 4.375 | 4 |
[] |
no_license
|
# // A Fibonacci number is the sum of the previous two sequence numbers. Below is an example of the sequence:
#
# // 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, … Notice the sequence pattern is the sum of the previous two numbers?
# //
# // 0 + 1 = 1 1 + 1 = 2 1 + 2 = 3 2 + 3 = 5 3 + 5 = 8 …
#
#
# // Write a function that takes an integer and returns an array of Fibonacci numbers. The integer should be the length of the array. The first element should always be zero.
def fib(n)
if n == 0
return 0
end
if n == 1
return 1
end
if n >= 2
return fib(n-1) + (fib(n-2))
end
end
| true |
8f9e59ec5b3bd7e0ceaeafceafdf5191c59c80c9
|
Ruby
|
iachettifederico/trecs
|
/lib/trecs/strategies/fly_from_right_strategy.rb
|
UTF-8
| 1,165 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
require "strategies/strategy"
require "strategies/shell_command_strategy"
module TRecs
class FlyFromRightStrategy < Strategy
include ShellCommandStrategy
attr_reader :message
attr_reader :width
def initialize(options={})
@message = options.fetch(:message)
@width = options.fetch(:width) { 10 }
@width = @message.size if @width < @message.size
@command = options.fetch(:command) { nil }
end
def perform
time = 0
message.each_char.inject("") do |current_msg, current_char|
current_time(time)
current_content(current_msg)
save_frame
((width-1)-current_msg.size).downto(1) do |i|
time += recorder.step
content = current_msg + " " * i + current_char
current_time(time)
current_content(content)
save_frame
end
current_msg += current_char
time += recorder.step
content = current_msg
current_time(time)
current_content(content)
save_frame
time += recorder.step
content = current_msg
current_msg
end
end
end
end
| true |
c4dafc08d79469aa81a209054467c30e071dd0d3
|
Ruby
|
dbravman/phase-0-tracks
|
/ruby/arrays_drill.rb
|
UTF-8
| 1,987 | 4.8125 | 5 |
[] |
no_license
|
# At the top of your file, add a method that takes three items as parameters and returns an array of those items. So build_array(1, "two", nil) would return [1, "two", nil]. This won't take much code, but the syntax might feel a bit odd.
def build_array(a, b, c)
return_array = []
return_array << a
return_array << b
return_array << c
end
# 2.At the top of your file, add a method that takes an array and an item as parameters, and returns the array with the item added. So add_to_array([], "a") would return ["a"], and add_to_array(["a", "b", "c", 1, 2], 3) would return ["a", "b", "c", 1, 2, 3].
def add_to_array(arr, a)
return_array = arr
return_array << a
end
# 1.Initialize an empty array and store it in a variable (you can choose the name). Print the variable using p.
array_1 = []
p array_1
# 2.Add five items to your array. Print the array.
array_1 << "shoes" << "dragons" << "house" << "bat" << "pet"
# 3.Delete the item at index 2. Print the array.
array_1.delete_at(2)
p array_1
# 4.Insert a new item at index 2. Print the array.
array_1.insert(2, "bulls")
p array_1
# 5.Remove the first item of the array without having to refer to its index. Print the array.
array_1.delete(array_1.first)
p array_1
# 6.Ask the array whether it includes a certain item. Print the result of this method call (labeled so it prints as more than just an isolated boolean value without any context.)
if array_1.include?("bat")
puts "bat is in array"
else
puts "bat is not in the array"
end
# 7.Initialize another array that already has a few items in it.
array_2 = ["watches", "cardinals", "sign"]
# 8.Add the two arrays together and store them in a new variable. Print the new array.
array_3 = array_1 + array_2
p array_3
# At the bottom of the file, call the method to show that it works.
p build_array(1, "two", nil)
# Print a few test calls of the method.
p add_to_array([], "a")
p add_to_array(["a", "b", "c", 1, 2], 3)
| true |
feef14759927e05b305bc37859ec196928f6ae94
|
Ruby
|
developwithpassion/expansions
|
/lib/expansions/template_processors.rb
|
UTF-8
| 697 | 2.921875 | 3 |
[
"MIT"
] |
permissive
|
module Expansions
class TemplateProcessors
attr_reader :processors
def initialize(processors={})
@processors = processors
end
def get_processor_for(file_name)
template_type = File.extname(file_name).gsub(/\./,'').to_sym
raise "There is no processor for #{file_name}" unless processor?(template_type)
return processors[template_type]
end
def register_processor(template_type,processor)
raise "The processor for the template already exists" if processor?(template_type)
processors[template_type.to_sym] = processor
end
def processor?(template_type)
return processors.has_key?(template_type.to_sym)
end
end
end
| true |
ef827941dba9ea47df795ce59e8a4399bd3caa7a
|
Ruby
|
ryanespin/18xx
|
/assets/app/view/game/part/track.rb
|
UTF-8
| 2,866 | 2.59375 | 3 |
[
"LicenseRef-scancode-free-unknown",
"MIT"
] |
permissive
|
# frozen_string_literal: true
require 'lib/settings'
require 'view/game/part/track_node_path'
require 'view/game/part/track_offboard'
require 'view/game/part/track_stub'
module View
module Game
module Part
class Track < Snabberb::Component
include Lib::Settings
TRACK = {
color: '#000000',
width: 8,
dash: '0',
broad: {
color: '#000000',
width: 8,
dash: '0',
},
narrow: {
color: '#000000',
width: 8,
dash: '12',
},
dual: {
color: '#FFFFFF',
width: 8,
dash: '0',
},
}.freeze
needs :tile
needs :region_use
needs :routes
def render
# each route has an "entry" in this array; each "entry" is an array of
# the paths on that route that are also on this tile
#
# Array<Array<Path>>
@routes_paths = @routes.map { |route| route.paths_for(@tile.paths) }
paths_and_stubs = @tile.paths + @tile.stubs
path_indexes = paths_and_stubs.map { |p| [p, indexes_for(p)] }.to_h
sorted = paths_and_stubs
.flat_map { |path| path_indexes[path].map { |i| [path, i] } }
.sort_by { |_, index| index || -1 }
sorted.map do |path, index|
props = {
color: value_for_index(index, :color, path.track),
width: width_for_index(path, index, path_indexes),
dash: value_for_index(index, :dash, path.track),
}
if path.stub?
h(TrackStub, stub: path, region_use: @region_use, **props)
elsif path.offboard
h(TrackOffboard, offboard: path.offboard, path: path, region_use: @region_use, **props)
else
h(TrackNodePath, tile: @tile, path: path, region_use: @region_use, **props)
end
end
end
private
def indexes_for(path)
indexes = @routes_paths
.map.with_index
.select { |route_paths, _index| route_paths.any? { |p| path == p } }
.flat_map { |_, index| index }
indexes.empty? ? [nil] : indexes
end
def value_for_index(index, prop, track)
return TRACK[track][prop] if index && track == :narrow && prop == :dash
index ? route_prop(index, prop) : TRACK[track][prop]
end
def width_for_index(path, index, path_indexes)
multiplier =
if !index || path_indexes[path].one?
1
else
[1, 3 * path_indexes[path].reverse.index(index)].max
end
value_for_index(index, :width, path.track).to_f * multiplier.to_i
end
end
end
end
end
| true |
631d727fd0f4de60204e52769f8719c63c1189a1
|
Ruby
|
kghandhi/JazzCamp
|
/lib/camp_helpers.rb
|
UTF-8
| 1,841 | 2.71875 | 3 |
[] |
no_license
|
def zipper_split(sorted_students)
grouped = sorted_students.each_with_index.group_by { |student,rank| rank % 2 }
first_half = grouped[0].nil? ? [] : grouped[0].map(&:first)
second_half = grouped[1].nil? ? [] : grouped[1].map(&:first)
[first_half, second_half]
end
def in_groups(students, number)
division = students.length / number
modulo = students.length % number
groups = {}
start = 0
number.times do |class_level|
class_size = division + (modulo > 0 && modulo > class_level ? 1 : 0)
groups[class_level] = students[start...(start + class_size)]
start += class_size
end
groups
end
def class_label(human_readable, class_type, period, level, instrument=nil)
readable_class_name, ugly_class_name = nil
if class_type == :musicianship && !instrument.nil?
abreviation = {
:bass => "BS",
:drums => "DRM",
:guitar => "GUIT",
:piano => "PNO",
:saxophone => "SAX",
:trombone => "TB",
:trumpet => "TR",
}[instrument]
readable_class_name = (instrument.to_s + "_masterclass_#{level + 1}")
ugly_class_name = if level == 0
"MC#{abreviation}"
else
"MC#{abreviation}#{level}"
end
else
class_descriptor = case class_type
when :theory
"T"
when :musicianship
"M"
when :combo
"C"
when :split
"JT"
end
readable_class_name = "#{period}_#{class_type}_#{level + 1}"
ugly_class_name = "#{period[0].upcase}#{class_descriptor}%02d" % [level + 1]
end
class_name = human_readable ? readable_class_name : ugly_class_name
class_name.to_sym
end
| true |
57531a1ddab5190ca14bd892b11f3083330ce539
|
Ruby
|
jtibbertsma/stockfighter-solutions
|
/lib/stockfighter/request.rb
|
UTF-8
| 689 | 2.515625 | 3 |
[] |
no_license
|
require 'httparty'
module Stockfighter
class Request
include HTTParty
base_uri 'api.stockfighter.io'
headers 'X-Starfighter-Authorization' => Stockfighter::APIKey
class BadRequest < RuntimeError
end
class JSONOnly < HTTParty::Parser
def parse
json
end
end
parser JSONOnly
def self.venue_exists?(venue)
response = get "/ob/api/venues/#{venue}/heartbeat"
response.code == 200 ? true : false
end
def self.stock_list(venue)
response = get "/ob/api/venues/#{venue}/stocks"
raise BadRequest.new(response["error"]) if response.code != 200
response.parsed_response["symbols"]
end
end
end
| true |
a48c7f7590ab06bf53f7ecda76143665eaa6a2d3
|
Ruby
|
christopher-tero/Restaurant_finder_01
|
/lib/methods.rb
|
UTF-8
| 11,211 | 3.53125 | 4 |
[] |
no_license
|
require 'pry'
#note to us we have a global variable "$location" and "$name" ***caution***
#/// Intro ///
def intro
loading_2
puts `clear`
puts "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
puts "".center(236).blue_on_green
print "Welcome to Restaurant Sleuth!".center(118).blue_on_green
puts "".center(236).blue_on_green
sleep 1
print " Please enter your city:".center(118).blue_on_green
puts "".center(236).blue_on_green
puts "\n\n"
end
def available_cities
our_cities = CityRest.all.map do |restaurant|
restaurant.location.downcase
end
our_cities.uniq
end
def invalid_selection
puts `clear`
puts "\n\n\n\n\n\n\n\n\n\n"
puts "Please enter a valid selection".center(118).white_on_red
puts "\n\n"
sleep 1
end
def city_selector
$location = gets.chomp.downcase
puts "\n\n"
if available_cities.include?($location)
puts `clear`
puts "\n\n\n"
if $location == "new york"
nyc_ascii
elsif $location == "denver"
den_ascii_2
end
sleep 4
puts `clear`
puts "\n\n\n\n\n\n\n\n\n\n"
print "Get ready for some crazy random restaurants in #{$location.capitalize}!".center(118).green
puts "\n\n"
sleep 0.7
elsif $location == "exit"
exit_program
else
puts `clear`
puts "\n\n\n\n\n\n\n\n\n\n"
print "Sorry we are not available in your area yet. Enter another city or exit:".center(118).white_on_red
puts "\n\n"
city_selector
end
end
def select_user
puts "\n\n"
print "Please enter your name, type 'new user', or exit.".center(118).blue
puts "\n\n"
$name = gets.chomp.capitalize
puts ""
sleep 0.5
if User.exists?(name: $name)
puts `clear`
puts "\n\n\n\n\n\n\n\n\n\n"
print "Hello #{$name}! How can we help you today?".center(118).green
puts "\n\n"
elsif $name.downcase == "new user"
new_user
elsif $name.downcase == "exit"
exit_program
else
invalid_selection
select_user
end
end
def new_user
puts `clear`
puts "\n\n\n\n\n\n\n\n\n\n"
print "Welcome to our app! Please enter your name:".center(118).blue
puts "\n\n"
$name = gets.chomp.capitalize
puts ""
if User.exists?(name: $name)
puts "\n\n"
puts "Sorry! This User name is already taken. Please try again".center(118).white_on_red
puts "\n\n"
new_user
elsif $name == "exit"
exit_program
else
puts `clear`
puts "\n\n\n\n\n\n\n\n\n\n"
print "Hello #{$name}!".center(118).green
puts "\n\n"
User.create(name: $name)
sleep 1
end
end
def main_menu
puts ""
puts "Please select a number option from the menu below:".center(118).green
puts "\n\n"
puts "1 - Top 10 rated restaurants".center(118).green
puts "2 - Select a cuisine ".center(118).green
puts "3 - Select a price bracket ".center(118).green
puts "4 - Select a rating bracket ".center(118).green
puts "5 - Completely Random ".center(118).green
puts "6 - My favorites ".center(118).green
puts ""
puts "exit".center(118).green
puts "\n\n"
selection = gets.chomp
sleep 0.5
puts `clear`
case selection
when "1"
top_10
when "2"
cuisine
when "3"
price
when "4"
rating
when "5"
city_restaurants
when "6"
view_favorites
when "exit"
exit_program
else
invalid_selection
main_menu
end
end
def top_restaurant_name
CityRest.all.sort_by do |restaurant|
restaurant.rating
end
end
def top_10
puts "\n\n\n\n\n\n\n\n\n\n"
print "You selected top 10 restaurants for #{$location.capitalize}".center(118).green
puts "\n\n"
best_rest_name = top_restaurant_name.select do |restaurant|
restaurant.location.downcase == $location
end
best_rest_name.last(10).each do |restaurant|
puts "#{restaurant.name}".center(118).magenta
end
puts "\n\n"
end_of_method
end
def cuisine
puts "\n\n\n\n\n\n\n\n\n\n"
puts "You selected cuisine; please select one of the following numbers:".center(118).green
puts "\n\n"
puts "1 - American".center(118).green
puts "2 - Mexican ".center(118).green
puts "3 - Japanese".center(118).green
puts "4 - Italian ".center(118).green
puts "\n\n"
cuisine_choice = gets.chomp.to_i
if cuisine_choice == 1
cuisine_selection = "American"
elsif cuisine_choice == 2
cuisine_selection = "Mexican"
elsif cuisine_choice == 3
cuisine_selection = "Japanese"
elsif cuisine_choice == 4
cuisine_selection = "Italian"
end
cuisine_selection
cuisine_random = CityRest.all.select do |restaurant|
restaurant.name if restaurant.cuisine == cuisine_selection
end
rando_cuisine = cuisine_random.sample
case cuisine_choice.to_i
when 1
puts "Random American restaurant: ".center(118).green
puts ""
puts "name: #{rando_cuisine.name}, price: #{rando_cuisine.price}, rating: #{rando_cuisine.rating}".center(118).red
add_to_favorite($name, rando_cuisine)
when 2
puts "Random Mexican restaurant: ".center(118).green
puts ""
puts "name: #{rando_cuisine.name}, price: #{rando_cuisine.price}, rating: #{rando_cuisine.rating}".center(118).red
add_to_favorite($name, rando_cuisine)
when 3
puts "Random Japanese restaurant: ".center(118).green
puts ""
puts "name: #{rando_cuisine.name}, price: #{rando_cuisine.price}, rating: #{rando_cuisine.rating}".center(118).red
add_to_favorite($name, rando_cuisine)
when 4
puts "Random Italian restaurant: ".center(118).green
puts ""
puts "name: #{rando_cuisine.name}, price: #{rando_cuisine.price}, rating: #{rando_cuisine.rating}".center(118).red
add_to_favorite($name, rando_cuisine)
else
invalid_selection
cuisine
end
end_of_method
end
def price
puts "\n\n\n\n\n\n\n\n\n\n"
print "You selected price; please select your price bracket:".center(118).green
puts "\n\n"
puts "1 - Budget($) ".center(118).green
puts "2 - Mid-level($$) ".center(118).green
puts "3 - Extravagant($$$)".center(118).green
puts ""
puts "exit ".center(118).green
puts "\n\n"
price_range = gets.chomp
puts "\n\n"
price_random = CityRest.all.select do |restaurant|
restaurant if restaurant.price.length == price_range.to_i
end
restaurant_selection = price_random.sample
case price_range
when "1"
puts "You selected Budget($) restaurants".center(118).green
puts ""
puts "name: #{restaurant_selection.name}, rating: #{restaurant_selection.rating}".center(118).red
add_to_favorite($name, restaurant_selection)
when "2"
puts "You selected Moderately($$) priced restaurants".center(118).green
puts ""
puts "name: #{restaurant_selection.name}, rating: #{restaurant_selection.rating}".center(118).red
add_to_favorite($name, restaurant_selection)
when "3"
puts "You selected Extravagant($$$) restaurants".center(118).green
puts ""
puts "name: #{restaurant_selection.name}, rating: #{restaurant_selection.rating}".center(118).red
add_to_favorite($name, restaurant_selection)
when "exit"
end_of_method
else
invalid_selection
price
end
end_of_method
end
def rating
puts "\n\n\n\n\n\n\n\n\n\n"
puts "You selected rating; please select 3, 4, or 5 stars!".center(118).green
puts "\n\n"
rating_selection = gets.chomp
puts "\n\n"
stars_random = CityRest.all.select do |restaurant|
restaurant if restaurant.rating.to_i == rating_selection.to_i
end
#binding.pry
rando = stars_random.sample
case rating_selection
when "3"
puts "Three star restaurant:".center(118).green
puts ""
puts "name: #{rando.name}, price:#{rando.price}".center(118).red
add_to_favorite($name, rando)
when "4"
puts "Four star restaurant:".center(118).green
puts ""
puts "name: #{rando.name}, price:#{rando.price}".center(118).red
add_to_favorite($name, rando)
when "5"
puts "Five star restaurant:".center(118).green
puts ""
puts "name: #{rando.name}, price:#{rando.price}".center(118).red
add_to_favorite($name, rando)
when "exit"
end_of_method
else
invalid_selection
rating
end
end_of_method
end
def city_restaurants
rando = CityRest.all.select do |restaurant|
restaurant.location.downcase == $location
end
city_rando = rando.sample
puts "\n\n\n\n\n\n\n\n\n\n"
puts "Your randomly selected dinning option in #{$location} below!".center(118).green
puts ""
puts "name: #{city_rando.name}, price: #{city_rando.price}, rating: #{city_rando.rating}".center(118).red
add_to_favorite($name, city_rando)
end
def add_to_favorite(name, rando_cuisine)
puts ""
puts "Would you like to save to favorites? Please enter 'yes' or 'no'.".center(118).green
puts ""
answer = gets.chomp.downcase
if answer == "yes"
puts "Adding #{rando_cuisine.name} to your favorite list.".center(118).green
puts ""
sleep 2
user_id = User.find_by(name: $name).id
list = Favorite.all.select do |restaurant|
restaurant.user_id == user_id
end
if list.any? {|restaurant| restaurant[:city_rest_id] == rando_cuisine.id}
puts `clear`
puts "\n"
puts "This is already in your favorites list!".center(118).white_on_red
view_favorites
else
user = User.find_by(name: $name)
user_id = user.id
city_rest_id = rando_cuisine.id
name_id = rando_cuisine.name
location_id = rando_cuisine.location
price_id = rando_cuisine.price
rating_id = rando_cuisine.rating
cuisine_id = rando_cuisine.cuisine
Favorite.create(name: name_id, location: location_id, price: price_id, rating: rating_id, cuisine: cuisine_id, city_rest_id: city_rest_id, user_id: user_id)
puts `clear`
puts "\n\n\n\n\n\n\n\n\n\n"
puts "#{rando_cuisine.name} has been added to your favorites!".center(118).magenta
end_of_method
end
elsif answer == "no"
puts `clear`
puts "\n\n\n\n\n\n\n\n"
end_of_method
else
invalid_selection
add_to_favorite(name, rando_cuisine)
end
end
def view_favorites
puts "\n\n\n\n\n\n\n\n\n\n"
puts "Here are all your favorites:".center(118).green
puts "\n\n"
user_id = User.find_by(name: $name).id
list = Favorite.all.select do |restaurant|
restaurant.user_id == user_id
end
list2 = list.map do |restaurant|
"name: #{restaurant.name}, location: #{restaurant.location}, cuisine: #{restaurant.cuisine}, price: #{restaurant.price}, rating: #{restaurant.rating}".center(118).magenta
end
puts list2.uniq
#binding.pry
end_of_method
end
def exit_program
puts `clear`
puts "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
puts "Thank you for using Restaurant Sleuth!".center(118).green
puts "\n\n"
puts "See you soon!".center(118).green
puts "\n\n"
sleep 2
puts `clear`
exit
end
def end_of_method
puts "\n\n"
puts "Make another selection or exit?".center(118).green
puts "\n"
puts "1 - Make another selection".center(118).green
puts ""
puts "exit".center(118).green
end_select = gets.chomp.downcase
sleep 1
puts `clear`
case end_select
when "1"
puts "\n\n\n\n\n\n\n\n\n\n"
puts "What would you like to do next #{$name}?".center(118).green
puts ""
main_menu
when "exit"
exit_program
else
invalid_selection
end_of_method
end
end
| true |
9ff936d53b0ccc40a061014ee1d3d2c4a3f85fc6
|
Ruby
|
MidhunSukumaran/Datastructures-with-Ruby
|
/double_linked_list.rb
|
UTF-8
| 2,413 | 3.703125 | 4 |
[] |
no_license
|
class Node
attr_accessor :key,:next_node,:prev_node
def initialize(k=0)
@key = k
@next_node = nil
@prev_node = nil
end
end
class DoubleLinkedList
attr_accessor :root
def initialize(root)
@root = root
end
def self.create_linear_list(array)
root = Node.new(array.first)
linked = self.new(root)
prev = root
array[1..-1].each do |k|
current = Node.new(k)
prev.next_node = current
current.prev_node = prev
puts "current: #{current.key}, prev : #{prev.key}"
prev = current
end
return linked
end
def parse
visited = Array.new
current = self.root
list = Array.new
while !(current.nil? || (visited.include? current))
list << current.key
visited << current
current = current.next_node
end
return list
end
def reverse
current = self.root
temp = nil
while !current.nil?
puts "#{current.key}"
temp = current.prev_node
current.prev_node = current.next_node
current.next_node = temp
current = current.prev_node
end
self.root = temp.prev_node
end
def simple_reverse
list = self.parse
return list.reverse
end
def largest_element
self.parse.max
end
def smallest_element
self.parse.min
end
def is_loop_present
visited = Array.new
current = self.root
while !current.nil?
if (visited.include? current)
return true
end
visited << current
current = current.next_node
end
return false
end
def get_loop_start_double_pointer
current = self.root
slow = current
fast = current.next_node
while fast && fast.next_node
if slow == fast
break
end
slow = slow.next_node
fast = fast.next_node.next_node
end
if slow == fast
slow = self.root
while slow != fast.next_node
slow = slow.next_node
fast = fast.next_node
end
end
return fast.key
end
end
array = [5,6,7,8,9]
linked = DoubleLinkedList.create_linear_list(array)
puts "Linked list parse : #{linked.parse.join('<=>')}"
linked.reverse
puts "Linked list parse : #{linked.parse.join('<=>')}"
#puts "Linked list simple reverse : #{linked.simple_reverse.join('->')}"
#puts "is_loop_present : #{linked.is_loop_present}"
#puts "is_loop_present_double_pointer : #{linked.get_loop_start_double_pointer}"
| true |
08294b275fb18d32d4bf950858c3c08eeddf01ab
|
Ruby
|
draganglumac/algo1
|
/week6/median/median.rb
|
UTF-8
| 780 | 3.765625 | 4 |
[] |
no_license
|
require 'heap'
class Median
def initialize
reset
end
def reset
@lo_heap = Heap.new { |a, b| b <=> a }
@hi_heap = Heap.new { |a, b| a <=> b }
end
def median
size = (@lo_heap.heap.size + @hi_heap.heap.size)
if size % 2 == 1
m = (size + 1) / 2
else
m = size / 2
end
if m > @lo_heap.heap.size
@hi_heap.top
else
@lo_heap.top
end
end
def insert(n)
if @lo_heap.empty?
@lo_heap.insert n
elsif n > @lo_heap.top
@hi_heap.insert n
else
@lo_heap.insert n
end
if @lo_heap.heap.size > (@hi_heap.heap.size + 1)
@hi_heap.insert(@lo_heap.extract_top)
elsif @hi_heap.heap.size > (@lo_heap.heap.size + 1)
@lo_heap.insert(@hi_heap.extract_top)
end
end
end
| true |
de5366afc024888b545bb67d3fa7bc2e8f7ba9c0
|
Ruby
|
IgnacioEscobar/ProtoCool
|
/destroy_header.rb
|
UTF-8
| 758 | 2.890625 | 3 |
[] |
no_license
|
require 'json'
# Wrapper
wrapper =%{
#ifndef UTILIDADES_PROTOCOL_DESTROY_H_
#define UTILIDADES_PROTOCOL_DESTROY_H_
}
print wrapper
# Includes
includes =%{
#include <stdint.h>
}
print includes
# Seleccionar la base de conocimiento y parsear JSON
file = File.read("baseConocimiento.json")
hash = JSON.parse(file)
mensajes = hash["mensajes"]
puts "// Destroyer generico"
puts "void destroy(HEADER_T header,void* payload);"
puts "\n\n// Destroyers particulares"
# Por cada destroyer escribo el prototipo
mensajes.each do |mensaje|
# Obtener los datos
nombre = mensaje["nombre"]
campos = mensaje["campos"]
puts "void destroy_#{nombre}(payload_#{nombre}* payload);"
end
# Wrapper
wrapper =%{
#endif /* UTILIDADES_PROTOCOL_DESTROY_H_ */
}
print wrapper
| true |
9f2e6bdd6cfa11040785741787970257e1bc54e8
|
Ruby
|
unabl4/AoC
|
/2017/day17/part1/spinlock.rb
|
UTF-8
| 229 | 2.921875 | 3 |
[] |
no_license
|
def spinlock(step)
pos = 0
buffer = [0]
length = 1
value = 1
2017.times do
m = (pos + step) % length
pos = m+1 # next
buffer.insert(pos, value)
value += 1
length += 1
end
buffer[pos+1]
end
| true |
836b96fe0250e2aaa51741ece2a8a59a67b453da
|
Ruby
|
grcdeepak1/project_tdd_minesweeper
|
/spec/board_spec.rb
|
UTF-8
| 1,291 | 3 | 3 |
[] |
no_license
|
require_relative '../lib/board.rb'
require_relative '../lib/square.rb'
describe Board do
before(:each) do
subject.extend(Enumerable)
end
describe "#initialize" do
it "returns a board" do
expect(subject).to be_a(Board)
end
it "returns a board with 2d array of squares" do
expect(subject.matrix[0][0]).to be_a(Square)
end
it "returns a board with 2d array of 10x10 squares - rows" do
expect(subject.matrix.size).to eq(10)
end
it "returns a board with 2d array of 10x10 squares - cols" do
expect(subject.matrix[0].size).to eq(10)
end
it "should have 9 mines by default" do
expect(subject.select { |sq| sq.mine? }.size).to eq(9)
end
it "all the square should be in state :none" do
expect(subject.select { |sq| sq.state == :none }.size).to eq(100)
end
end
describe "#render" do
it "should show the remaining flags" do
expect(subject).to receive(:remaining_flags)
subject.render
end
end
describe "#winner?" do
it "There is a winner if all the mines are flaged and others are cleared" do
subject.select { |sq| sq.mine? }.each { |sq| sq.flag }
subject.select { |sq| !sq.mine? }.each { |sq| sq.clear }
expect(subject.winner?).to eq(true)
end
end
end
| true |
de048c9dbbba09a7b2766683a6030bc30bc651c7
|
Ruby
|
alancovarrubias/nba_react
|
/app/models/builder/quarter/player_stat.rb
|
UTF-8
| 1,349 | 2.5625 | 3 |
[] |
no_license
|
module Builder
module Quarter
class PlayerStat
UPDATE_ATTR = [:sp, :fgm, :fga, :thpm, :thpa, :ftm, :fta, :orb, :drb, :ast, :stl, :blk, :tov, :pf, :pts]
attr_accessor :player, :team, :idstr, :starter, :time
attr_accessor :sp, :fgm, :fga, :thpm, :thpa, :ftm, :fta, :orb, :drb, :ast, :stl, :blk, :tov, :pf, :pts
def initialize(season, game, player, quarter)
@season = season
@game = game
@player = player
@quarter = quarter
@team = player.team
@idstr = player.idstr
@starter = false
@time = 0
UPDATE_ATTR.each do |attr|
set_property(attr, 0)
end
end
def save
query = { season: @season, game: @game, model: @player, games_back: nil, season_stat: false, period: @quarter }
stat = ::Stat.find_or_create_by(query)
update_hash = attributes.select { |key, value| UPDATE_ATTR.include?(key) }
stat.update(update_hash)
end
def set_property(name, value)
prop_name = "@#{name}".to_sym # you need the property name, prefixed with a '@', as a symbol
self.instance_variable_set(prop_name, value)
end
def attributes
instance_variables.map do |var|
[var[1..-1].to_sym, instance_variable_get(var)]
end.to_h
end
end
end
end
| true |
9e90d8eb4f3c0c589e891606ac2283d3cc6ff021
|
Ruby
|
Xin00163/oystercard
|
/spec/journey_spec.rb
|
UTF-8
| 1,028 | 2.8125 | 3 |
[] |
no_license
|
require 'journey'
describe Journey do
let (:station) {double :station, zone: 1}
let (:station2) {double :station, zone: 1}
describe '#fare' do
subject {described_class.new(station)}
it 'should return the fare for the journey if touched in/out' do
journey = Journey.new(station)
journey.end_journey(station2)
expect(journey.fare).to eq Journey::MINIMUM_FARE
end
end
context 'if no touch out' do
subject {described_class.new(station)}
it 'exit station should have default value of nil' do
expect(subject.exit_station).to eq nil
end
it'should return penalty fare if no touch out' do
expect(subject.fare).to eq Journey::PENALTY_FARE
end
end
context 'if no touch in' do
it 'entry station should have default value of nil' do
expect(subject.entry_station).to eq nil
end
it 'should return penalty fare if no touch in' do
subject.end_journey(station2)
expect(subject.fare).to eq Journey::PENALTY_FARE
end
end
end
| true |
49fddd5ec8efb9853f31988c6f3916f487a6174b
|
Ruby
|
JamesClonk/ruby-sensei
|
/09_projects/lib/restaurant.rb
|
UTF-8
| 1,667 | 3.21875 | 3 |
[] |
no_license
|
class Restaurant
@@filepath = nil
def self.filepath=(path=nil)
@@filepath = File.join(APP_ROOT, path)
end
attr_accessor :name, :cuisine, :price
def self.file_exists?
if @@filepath && File.exists?(@@filepath)
return true
else
return false
end
end
def self.file_usable?
return false unless @@filepath
return false unless File.exists?(@@filepath)
return false unless File.readable?(@@filepath)
return false unless File.writable?(@@filepath)
return true
end
def self.create_file
File.open(@@filepath, 'w') unless file_exists?
return file_usable?
end
def self.saved_restaurants
restaurants = []
if file_usable?
file = File.new(@@filepath, 'r')
file.each_line do |line|
restaurants << Restaurant.build_from_line(line.chomp)
end
file.close
end
return restaurants
end
def initialize(args={})
@name = args[:name] || ""
@cuisine = args[:cuisine] || ""
@price = args[:price] || ""
end
def self.build_from_questions
values = {}
print "Restaurant name: "
values[:name] = gets.chomp.strip
print "Cuisine type: "
values[:cuisine] = gets.chomp.strip
print "Average price: "
values[:price] = gets.chomp.strip
return self.new(values)
end
def self.build_from_line(line)
@name, @cuisine, @price = line.split(";")
return Restaurant.new({name: @name, cuisine: @cuisine, price: @price})
end
def save
return false unless Restaurant.file_usable?
File.open(@@filepath, 'a') do |file|
file.puts "#{[@name, @cuisine, @price].join(";")}\n"
end
return true
end
end
| true |
cd50cbe6d46a1e3dd6a6a850d07d6ec5086a5116
|
Ruby
|
KrzaQ/AdventOfCode2015
|
/day03/main.rb
|
UTF-8
| 795 | 2.8125 | 3 |
[] |
no_license
|
T = File.read("data.txt")
def simPath(path)
path.each_char.inject({current: [0,0], total: { [0,0] => 1 }}){ |memo,c|
point = [{
'^' => [ 0, 1],
'>' => [ 1, 0],
'v' => [ 0, -1],
'<' => [-1, 0]
}[c], memo[:current]].transpose.map{ |n| n.inject(:+) }
memo[:total][point] = memo[:total].fetch(point, 0)+1
{
current: point,
total: memo[:total]
}
}
end
ThisYear = simPath(T)
NextYearSantasPath, NextYearRoboSantasPath = T.each_char.each_with_index.group_by{ |c, i|
i % 2
}.map{|unused, arr|
arr.map{ |c, i| c}.join
}
NextYearSanta = simPath(NextYearSantasPath)
NextYearRoboSanta = simPath(NextYearRoboSantasPath)
puts "Task 1: %s" % ThisYear[:total].size
puts "Task 2: %s" % NextYearSanta[:total].merge(NextYearRoboSanta[:total]){ |k, v1, v2| v1 + v2 }.size
| true |
f7b4bd19138c3fe299e8d0ba78a11b2590583e0d
|
Ruby
|
phelanjo/tier_list
|
/spec/models/list_spec.rb
|
UTF-8
| 3,107 | 2.8125 | 3 |
[] |
no_license
|
require "rails_helper"
RSpec.describe List do
let(:empty_team) { FactoryBot.build_stubbed(:list) }
let(:team_of_one) { FactoryBot.build_stubbed(:list, champions: [champion]) }
let(:team_of_three) { FactoryBot.build_stubbed(:list, champions: [champion, champion, champion]) }
let(:team1) { FactoryBot.build_stubbed(:list, champions: [jax, katarina, draven]) }
let(:team2) { FactoryBot.build_stubbed(:list, champions: [hecarim, zed, lucian]) }
let(:team3) { FactoryBot.build_stubbed(:list, champions: [lee_sin, ahri, jinx]) }
let(:first_10pt_team) { FactoryBot.build_stubbed(:list, champions: [jax, ahri, draven]) }
let(:second_10pt_team) { FactoryBot.build_stubbed(:list, champions: [hecarim, zed, lucian]) }
let(:champion) { FactoryBot.build_stubbed(:champion) }
let(:jax) { FactoryBot.build_stubbed(:champion, :jax) }
let(:katarina) { FactoryBot.build_stubbed(:champion, :katarina) }
let(:draven) { FactoryBot.build_stubbed(:champion, :draven) }
let(:hecarim) { FactoryBot.build_stubbed(:champion, :hecarim) }
let(:zed) { FactoryBot.build_stubbed(:champion, :zed) }
let(:lucian) { FactoryBot.build_stubbed(:champion, :lucian) }
let(:lee_sin) { FactoryBot.build_stubbed(:champion, :lee_sin) }
let(:ahri) { FactoryBot.build_stubbed(:champion, :ahri) }
let(:jinx) { FactoryBot.build_stubbed(:champion, :jinx) }
it "creates an empty list upon instantiation" do
expect(empty_team.empty?).to be_truthy
end
it "can add a champion to a list" do
expect(team_of_one.size()).to eq(1)
end
it "knows the size of a list" do
expect(team_of_three.size()).to eq(3)
end
it "can access a champion from a list" do
expect(team_of_one.champions[0]).to equal(champion)
end
it "can calculate the total score for a list" do
expect(team1).to have_total_score(7)
expect(team1).not_to have_total_score(4)
end
it "can calculate which list has a better score" do
expect(team1).to have_total_score(7)
expect(team2).to have_total_score(10)
expect(team1.battle(team2)).to eq(team2)
expect(team3).to have_total_score(12)
expect(team3.battle(team2)).to eq(team3)
end
it "does not return a winner if two lists have equal scores" do
expect(first_10pt_team.battle(second_10pt_team)).to eq(nil);
end
describe "fakes and mocks: " do
let(:big_dependency) {BigDependency.new}
let(:list_stub) {List.new}
let(:list_mock) {List.new}
it "returns the correct value from its perform method using an instance double" do
instance_twin = instance_double(List)
expect(instance_twin).to receive(:perform).and_return(42)
expect(instance_twin.perform(big_dependency)).to eq(42)
end
it "returns the correct value from its perform method using a stub" do
allow(list_stub).to receive(:perform).and_return(42)
expect(list_stub.perform(big_dependency)).to eq(42)
end
it "returns the correct value from its perform method using a mock" do
allow(list_stub).to receive(:perform).and_return(42)
expect(list_stub.perform(big_dependency)).to eq(42)
end
end
end
| true |
101f1abd4f83975c25cae08f5ee5211ce3ce6f8f
|
Ruby
|
ramky/learn_to_program
|
/chapter14/logger.rb
|
UTF-8
| 390 | 3.5625 | 4 |
[] |
no_license
|
$depth = 0
def log(description, &block)
#puts "Depth: #{$depth}"
puts ("\t" * $depth) + "Beginning #{description}"
$depth += 1
return_value = block.call
$depth -= 1
puts ("\t" * $depth) + "Returning #{return_value}, finished #{description}"
end
log 'outer' do
log 'inner 1' do
log 'inner 12' do
"Inner 12"
end
"Inner 1"
end
log 'inner 2' do
"Inner 2"
end
"Outer"
end
| true |
f315eac1b5b9090b554c613868f9e7089a39f413
|
Ruby
|
fUNCodeUNAL/Proyecto
|
/app/models/contest.rb
|
UTF-8
| 1,192 | 2.546875 | 3 |
[] |
no_license
|
class Contest < ApplicationRecord
belongs_to :teacher
attr_accessor :contest_running
validates :name, :start_date, :end_date, presence: { message: "es obligatorio" }
validate :dates_are_correct
validate :valid_initial_date, unless: :contest_running
has_many :problem_contest_relationships, dependent: :destroy
has_many :problems, through: :problem_contest_relationships
has_many :user_contest_relationships, dependent: :destroy
has_many :users, through: :user_contest_relationships
def dates_are_correct
# Esto es para evita que una persona temine un contest en tiempo anterior al actual
# pero posterior al start_date
cur_time = Time.new + 5*60
if start_date < end_date == false
errors.add(:start_date, 'debe ser antes de la fecha final')
elsif cur_time < end_date == false
errors.add(:end_date, 'El contest no puede terminar tan pronto')
end
end
def valid_initial_date
#Esto es para que el contest empiece minimo 5 minutos despues de la fecha actual
cur_time = Time.new + 5*60
if cur_time < start_date == false
errors.add(:start_date, 'debe ser al menos 5 minutos despues de la fecha actual')
end
end
end
| true |
97df7ef55c90a48d4dc43237c298c4613d0d705c
|
Ruby
|
Shahrene/Warmups
|
/lunch_orders/lunch_orders.rb
|
UTF-8
| 324 | 3.796875 | 4 |
[] |
no_license
|
require 'pry'
all_orders = ["name", "item"]
while true
puts "Enter a name for the order: "
name = gets.chomp
all_orders[name].push(name)
puts "#{name} wants to order: "
item = gets.chomp
all_orders[item].push(item)
puts "Add another item to the order y/n?: "
break if !gets.index ('y')
end
end
puts all_orders
| true |
2538307272d688c2eb60cd7b8172ea0bd4f40dfc
|
Ruby
|
srini91/euler-ruby
|
/prob37.rb
|
UTF-8
| 999 | 3.796875 | 4 |
[] |
no_license
|
# The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
# Find the sum of the only eleven primes that are both truncatable from left to right and right to left.
# NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.
beg = Time.now
def is_prime(x)
return false if x < 2
for i in (2..Math::sqrt(x).to_i)
return false if x % i == 0
end
return true
end
def is_prime_truncatable(x)
s = x.to_s
while s.size > 0
return false unless is_prime(s.to_i)
s = s[1..s.size-1]
end
s = x.to_s.chop
while s.size > 0
return false unless is_prime(s.to_i)
s.chop!
end
return true
end
sum = 0
i = 10
num_found = 0
while true
if is_prime_truncatable(i)
sum += i
num_found += 1
end
break if num_found == 11
i += 1
end
puts sum
puts (Time.now-beg)
| true |
c20f65fd3d26776cfa73f644759aea3d3651b038
|
Ruby
|
mick-mehigan/eventq
|
/eventq_rabbitmq/lib/eventq_rabbitmq/rabbitmq_queue_worker.rb
|
UTF-8
| 4,134 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
class RabbitMqQueueWorker
attr_accessor :is_running
def initialize
@threads = []
@is_running = false
@retry_exceeded_block = nil
end
def start(queue, options = {}, &block)
configure(queue, options)
puts '[QUEUE_WORKER] Listening for messages.'
raise 'Worker is already running.' if running?
@is_running = true
@threads = []
#loop through each thread count
@thread_count.times do
thr = Thread.new do
client = RabbitMqQueueClient.new
manager = RabbitMqQueueManager.new
#begin the queue loop for this thread
while true do
#check if the worker is still allowed to run and break out of thread loop if not
if !@is_running
break
end
channel = client.get_channel
#get the queue
q = manager.get_queue(channel, queue)
retry_exchange = manager.get_retry_exchange(channel, queue)
received = false
error = false
begin
delivery_info, properties, payload = q.pop(:manual_ack => true, :block => true)
#check that message was received
if payload != nil
message = Oj.load(payload)
puts "[QUEUE_WORKER] Message received. Retry Attempts: #{message.retry_attempts}"
puts properties
#begin worker block for queue message
begin
block.call(message.content, message.type, message.retry_attempts)
#accept the message as processed
channel.acknowledge(delivery_info.delivery_tag, false)
puts '[QUEUE_WORKER] Message acknowledged.'
received = true
rescue => e
puts '[QUEUE_WORKER] An unhandled error happened attempting to process a queue message.'
puts "Error: #{e}"
#reject the message to remove from queue
channel.reject(delivery_info.delivery_tag, false)
error = true
puts '[QUEUE_WORKER] Message rejected.'
#check if the message is allowed to be retried
if queue.allow_retry
puts '[QUEUE_WORKER] Checking retry attempts...'
if message.retry_attempts < queue.max_retry_attempts
puts'[QUEUE_WORKER] Incrementing retry attempts count.'
message.retry_attempts += 1
puts '[QUEUE_WORKER] Sending message for retry.'
retry_exchange.publish(Oj.dump(message))
puts '[QUEUE_WORKER] Published message to retry exchange.'
else
if @retry_exceeded_block != nil
@retry_exceeded_block.call(message)
else
raise "[QUEUE_WORKER] No retry exceeded block specified."
end
end
end
end
end
rescue Timeout::Error
puts 'Timeout occured attempting to pop a message from the queue.'
end
#check if any message was received
if !received && !error
puts "[QUEUE_WORKER] No message received. Sleeping for #{@sleep} seconds"
#no message received so sleep before attempting to pop another message from the queue
sleep(@sleep)
end
end
end
@threads.push(thr)
end
if options.key?(:wait) && options[:wait] == true
@threads.each { |thr| thr.join }
end
end
def stop
@is_running = false
@threads.each { |thr| thr.join }
end
def on_retry_exceeded(&block)
@retry_exceeded_block = block
end
def running?
@is_running
end
private
def configure(queue, options = {})
@queue = queue
#default thread count
@thread_count = 5
if options.key?(:thread_count)
@thread_count = options[:thread_count]
end
#default sleep time in seconds
@sleep = 15
if options.key?(:sleep)
@sleep = options[:sleep]
end
end
end
| true |
cabfb00a3a97210b994b761b702797cbeaa13052
|
Ruby
|
skyraseal/cp-learn-to-program
|
/example.rb
|
UTF-8
| 335 | 3.765625 | 4 |
[] |
no_license
|
#log exercise
#better logger included
$nesting = 0
def log(desc, &block)
puts " "*$nesting + "Starting \"#{desc}\" block..."
$nesting += 2
call_save = block.call
$nesting += -2
puts " "*$nesting + "...\"#{desc}\" finished! It returned: #{call_save}"
end
log("block 1") do
log("block 2") do
2+2
end
"joe mama"
end
| true |
ffe131b5bc7dbe985c145fd298ef14da50351bc3
|
Ruby
|
wpotratz/LS_3_More_Ruby_Topics
|
/3_practice/trinary.rb
|
UTF-8
| 501 | 3.453125 | 3 |
[] |
no_license
|
# trinary.rb
require 'pry'
class Trinary
def initialize(numeric_string)
@trinary_number = validate_string(numeric_string)
end
def to_decimal
return 0 if @trinary_number.nil?
reverse_number_str.each_with_index.reduce(0) do |decimal, (value, i)|
decimal + value.to_i*3**i
end
end
private
def reverse_number_str
@trinary_number.reverse.each_char
end
def validate_string(numeric_string)
numeric_string unless /[^012]/.match(numeric_string)
end
end
| true |
cc696ab5a01b3dabf28be1ced7e1d10db1d30f83
|
Ruby
|
hunaba/journee_test_ruby-
|
/lib/01_temperature.rb
|
UTF-8
| 773 | 3.828125 | 4 |
[] |
no_license
|
def ftoc(x)
y = (x - 32 ) * 5/9
return y
end
def ctof(y)
y = y.to_f
x = (y * 9/5) + 32
return x
end
=begin
B R O U I L L O N
def temperature
ftoc= (32 - 32) * 5/9
puts "freezing temperature is #{ftoc} °C."
end
puts temperature
def boiling
ftoc=(212 - 32 ) * 5/9
puts "boiling temperature is #{ftoc} °C."
end
puts boiling
def bodytemp
ftoc= (98.6 - 32 ) * 5/9
puts " body temperature is #{ftoc} °C"
end
puts bodytemp
def artitrary
ftoc= (68 - 32 ) * 5/9
puts "arbitrary temperature is #{ftoc} °C"
end
puts arbitrary
#describe "#ctof"
def temperature
ftoc= (32 - 32) * 5/9
puts "freezing temperature is #{ftoc} °C."
end
puts temperature
#convertir en float; mais il en faut au moins un en float dans l'opération
=end
| true |
7a9de0bc2b053b5bebdb2942bb078666caa1d7b3
|
Ruby
|
profh/67275_lecture_code
|
/rack_files/2-EnvReporter/app_extended.ru
|
UTF-8
| 780 | 3.21875 | 3 |
[] |
no_license
|
class EnvReporter
def initialize(app=nil)
# Allow for another app to be passed in
@app = app
end
def call(env)
# Set up basic output string
output = ""
unless @app.nil?
# if there is an app being passed in, use it's call method and
# get the response (third item in the response array) of the app
response = @app.call(env)[2]
response.each{ |val| output += "#{val}" }
end
# Add the information about each env var to output string
output += "<h3>LIST OF ENVIRONMENTAL VARIABLES:</h3><ul>"
env.keys.each{ |key| output += "<li>#{key} = #{env[key]}</li>" }
output += "</ul>"
# Return the formatted output
["200", {"Content-Type" => "text/html"}, [output]]
end
end
run EnvReporter.new
| true |
c97695ed27f13b986d488d0cfc4b8769a80641b2
|
Ruby
|
romimacca/fullstack-g29
|
/introduccion_ruby/desafios_arreglos_p2/grafico.rb
|
UTF-8
| 656 | 3.671875 | 4 |
[] |
no_license
|
data = [5, 3, 2, 5, 10, 19, 20]
def chart(data)
barra = ">"
barra_numero = " "
data.count.times do |i|
print '|'
data[i].times do |j|
if j < 10
print '**'
if data.max == data[i]
barra += '--'
barra_numero += (j+1).to_s+" "
end
else
print '***'
if data.max == data[i]
barra += '---'
barra_numero += (j+1).to_s+" "
end
end
end
print "\n"
end
puts barra
puts barra_numero
end
chart(data)
| true |
646accf7a8aaca93b1f7f2887fadc92a05f76510
|
Ruby
|
ander7en/backend
|
/app/models/nearest_driver.rb
|
UTF-8
| 587 | 3.109375 | 3 |
[] |
no_license
|
class NearestDriver
def self.getNearestDrivers(originLocation , driverList)
driversWithDistance = Hash.new
driverList.each do |driver|
target_location = {lng: driver.longitude , lat: driver.latitude }
#working on pure distance , later we can change to google api route
#distance = GoogleAPI.distance_considering_routes(originLocation, target_location)
distance = LocationUtility.distance(originLocation, target_location)
driversWithDistance[distance] = driver
end
driversWithDistance.sort_by { |k,v| k }.map {|k,v| v}
end
end
| true |
7f414660bf71d8218f3225b430c194e0e6bf5ba4
|
Ruby
|
rsanheim/isis
|
/examples/isis/runner_example.rb
|
UTF-8
| 3,660 | 2.5625 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
require File.join(File.dirname(__FILE__), *%w[.. example_helper])
describe Isis::Runner do
describe "run" do
it "should return the exit code" do
Isis::Runner.stubs(:exit).returns(256)
Isis::Runner.any_instance.stubs(:execute)
Isis::Runner.run.should == 256
end
it "should exit" do
Isis::Runner.expects(:exit)
Isis::Runner.any_instance.stubs(:execute)
Isis::Runner.run
end
end
describe "command lookup" do
it "finds the method matching the command" do
runner = Isis::Runner.new(["list"])
runner.expects(:list)
runner.execute
end
it "passes in any other options to the command" do
runner = Isis::Runner.new(["list", "--project_roots=src/foo"])
runner.expects(:list).with({:project_roots => "src/foo"}, [])
runner.execute
end
end
describe "get git repos" do
fit "should return paths that look like git repos" do
dot_git = stub(:directory? => true)
git_path = stub("git_path", :children => [dot_git])
non_git_path = stub("non_git_path", :children => ["readme"])
paths = [git_path, non_git_path]
Isis::Runner.filter_git_repos(paths).should == [git_path]
end
end
describe "list" do
pending "lists all git repos Isis knows about" do
runner = Isis::Runner.new
runner.list(:project_roots => "src/foo")
end
it "raises if project root does not exist" do
runner = Isis::Runner.new
lambda {
runner.list(:project_roots => "foo/baz")
}.should raise_error(ArgumentError, "Project root foo/baz is not a directory")
end
it "raises if there are no project roots" do
runner = Isis::Runner.new
lambda { runner.list() }.should raise_error(ArgumentError)
end
end
describe "fetch all" do
it "runs git fetch inside each directory within every git repo" do
runner = Isis::Runner.new
runner.expects(:all_git_repos).returns(["/projectx", "/projecty"])
runner.expects(:system).with("git", "--git-dir=/projectx", "fetch").returns(true)
runner.expects(:system).with("git", "--git-dir=/projecty", "fetch").returns(true)
runner.fetch_all.should == true
end
it "returns false if any of the fetches fail" do
runner = Isis::Runner.new
runner.expects(:all_git_repos).returns(["/projectx", "/projecty"])
runner.stubs(:system).returns(true, false)
runner.fetch_all.should == false
end
end
describe "git repo?" do
attr_reader :runner
before { @runner = Isis::Runner.new }
it "should be false if not a directory" do
path = stub(:directory? => false)
runner.git_repo?(path).should be_false
end
it "should be false if there is no .git entry" do
children = [stub(:basename => stub(:to_s => "foo")), stub(:basename => stub(:to_s => "bar"))]
path = stub(:directory? => true, :children => children)
runner.git_repo?(path).should be_false
end
it "should be false if there is a .git file (but not a directory)" do
children = [stub(:directory? => false, :basename => stub(:to_s => ".git")), stub(:basename => stub(:to_s => "bar"))]
path = stub(:directory? => true, :children => children)
runner.git_repo?(path).should be_false
end
it "should be true if there is a .git directory" do
children = [stub(:directory? => true, :basename => stub(:to_s => ".git")), stub(:basename => stub(:to_s => "bar"))]
path = stub(:directory? => true, :children => children)
runner.git_repo?(path).should be_true
end
end
end
| true |
35ff1a96a83488f420ff16a9ccbfea81d6ce3ee2
|
Ruby
|
dunkelbraun/turbo_test_constant_tracer
|
/test/unit/constructor_test.rb
|
UTF-8
| 7,803 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require "test_helper"
describe "Constructor" do
describe "#construct" do
test "constructs class for a string" do
class_constructor = TurboTest::ConstantTracer::Constructor.new(String)
class_constructor.construct
assert defined?(TurboTest::ConstantTracer::ProxyKlass::String)
end
test "constructs class for an array" do
class_constructor = TurboTest::ConstantTracer::Constructor.new(Array)
class_constructor.construct
assert defined?(TurboTest::ConstantTracer::ProxyKlass::Array)
end
test "constructs class for an integer" do
class_constructor = TurboTest::ConstantTracer::Constructor.new(Integer)
class_constructor.construct
assert defined?(TurboTest::ConstantTracer::ProxyKlass::Integer)
end
test "constructs class once" do
class_constructor = TurboTest::ConstantTracer::Constructor.new(String)
assert_output("", "") do
class_constructor.construct
class_constructor.construct
class_constructor.construct
end
end
end
describe "a constructed class" do
it "is a Delegator" do
class_constructor = TurboTest::ConstantTracer::Constructor.new(String)
class_constructor.construct
assert TurboTest::ConstantTracer::ProxyKlass::String.new("232").is_a?(Delegator)
end
it "has the original object class as a class instance variable" do
TurboTest::ConstantTracer::Constructor.new(String).construct
assert_equal String, TurboTest::ConstantTracer::ProxyKlass::String.turbo_test_proxied_class
end
end
describe "constructed class instance" do
it "can be only instantiated with an object of the proxied class" do
TurboTest::ConstantTracer::Constructor.new(String).construct
TurboTest::ConstantTracer::Constructor.new(Array).construct
exception = assert_raises TypeError do
TurboTest::ConstantTracer::ProxyKlass::String.new([])
end
assert_equal "Object class is not String", exception.message
exception = assert_raises TypeError do
TurboTest::ConstantTracer::ProxyKlass::Array.new("s")
end
assert_equal "Object class is not Array", exception.message
end
it "String class has the case equality of String" do
TurboTest::ConstantTracer::Constructor.new(String).construct
# rubocop:disable Style/CaseEquality
assert String === TurboTest::ConstantTracer::ProxyKlass::String.new("wewe")
# rubocop:enable Style/CaseEquality
end
test "Fixnum class has the case equality of Fixum" do
if RUBY_VERSION >= "2.4"
TurboTest::ConstantTracer::Constructor.new(Integer).construct
proxy_int = TurboTest::ConstantTracer::ProxyKlass::Integer.new(1)
else
# rubocop:disable Lint/UnifiedInteger
TurboTest::ConstantTracer::Constructor.new(Fixnum).construct
# rubocop:enable Lint/UnifiedInteger
proxy_int = TurboTest::ConstantTracer::ProxyKlass::Fixnum.new(1)
end
# rubocop:disable Style/CaseEquality
assert Integer === proxy_int
assert Numeric === proxy_int
assert Comparable === proxy_int
# rubocop:enable Style/CaseEquality
end
test "has the case equality of Comparable" do
if RUBY_VERSION >= "2.4"
TurboTest::ConstantTracer::Constructor.new(Integer).construct
proxy_int = TurboTest::ConstantTracer::ProxyKlass::Integer.new(1)
else
# rubocop:disable Lint/UnifiedInteger
TurboTest::ConstantTracer::Constructor.new(Fixnum).construct
# rubocop:enable Lint/UnifiedInteger
proxy_int = TurboTest::ConstantTracer::ProxyKlass::Fixnum.new(1)
end
# rubocop:disable Style/CaseEquality
assert Comparable === proxy_int
# rubocop:enable Style/CaseEquality
end
test "has the case equalit of Numeric" do
if RUBY_VERSION >= "2.4"
TurboTest::ConstantTracer::Constructor.new(Integer).construct
proxy_int = TurboTest::ConstantTracer::ProxyKlass::Integer.new(1)
else
# rubocop:disable Lint/UnifiedInteger
TurboTest::ConstantTracer::Constructor.new(Fixnum).construct
# rubocop:enable Lint/UnifiedInteger
proxy_int = TurboTest::ConstantTracer::ProxyKlass::Fixnum.new(1)
end
# rubocop:disable Style/CaseEquality
assert Numeric === proxy_int
# rubocop:enable Style/CaseEquality
end
test "original class has the case equality of the instance" do
TurboTest::ConstantTracer::Constructor.new(String).construct
# rubocop:disable Style/CaseEquality
refute TurboTest::ConstantTracer::ProxyKlass::String.new("wewe") === String
# rubocop:enable Style/CaseEquality
end
test "constructed class has case equality of the original class" do
TurboTest::ConstantTracer::Constructor.new(String).construct
assert TurboTest::ConstantTracer::ProxyKlass::String == String
refute TurboTest::ConstantTracer::ProxyKlass::String != String
end
test "original class has equality of the constructed class" do
TurboTest::ConstantTracer::Constructor.new(String).construct
assert String == TurboTest::ConstantTracer::ProxyKlass::String
refute String != TurboTest::ConstantTracer::ProxyKlass::String
end
test "has equality of instance of constructed class" do
TurboTest::ConstantTracer::Constructor.new(String).construct
proxy_string = TurboTest::ConstantTracer::ProxyKlass::String.new("a_string")
assert proxy_string == "a_string"
refute proxy_string != "a_string"
end
test "has equality of instance of the original class" do
TurboTest::ConstantTracer::Constructor.new(String).construct
proxy_string = TurboTest::ConstantTracer::ProxyKlass::String.new("a_string")
assert proxy_string == "a_string"
refute proxy_string != "a_string"
end
test "has spaceship oerator of the original class" do
TurboTest::ConstantTracer::Constructor.new(String).construct
proxy_string = TurboTest::ConstantTracer::ProxyKlass::String.new("ab")
assert_equal 0, "ab" <=> proxy_string
assert_equal(-1, "aa" <=> proxy_string)
assert_equal 1, "ac" <=> proxy_string
assert_equal 0, proxy_string <=> "ab"
assert_equal 1, proxy_string <=> "aa"
assert_equal(-1, proxy_string <=> "ac")
if RUBY_VERSION >= "2.4"
TurboTest::ConstantTracer::Constructor.new(Integer).construct
proxy_int = TurboTest::ConstantTracer::ProxyKlass::Integer.new(1)
else
# rubocop:disable Lint/UnifiedInteger
TurboTest::ConstantTracer::Constructor.new(Fixnum).construct
# rubocop:enable Lint/UnifiedInteger
proxy_int = TurboTest::ConstantTracer::ProxyKlass::Fixnum.new(1)
end
assert_equal 0, 1 <=> proxy_int
assert_equal(-1, 0 <=> proxy_int)
assert_equal 1, 2 <=> proxy_int
assert_equal 0, proxy_int <=> 1
assert_equal 1, proxy_int <=> 0
assert_equal(-1, proxy_int <=> 2)
end
test "can have a name" do
TurboTest::ConstantTracer::Constructor.new(String).construct
proxy_string = TurboTest::ConstantTracer::ProxyKlass::String.new("2323")
proxy_string.turbo_test_name = "a_name"
assert_equal "a_name", proxy_string.turbo_test_name
end
test "instruments method calls" do
TurboTest::ConstantTracer::Constructor.new(String).construct
original_string = "a_string"
proxy_string = TurboTest::ConstantTracer::ProxyKlass::String.new(original_string)
proxy_string.turbo_test_name = "MY_NAME"
proxy_string.turbo_test_path = __FILE__
TurboTest::ConstantTracer::EventPublisher.expects(:publish).with("MY_NAME", __FILE__)
proxy_string.to_s
end
end
end
| true |
dc54c66d434d33f8c53907b4fef596eae53dfe53
|
Ruby
|
ChristophPirringer/AnimalRescueProject
|
/spec/child_ticket_spec.rb
|
UTF-8
| 2,861 | 2.53125 | 3 |
[] |
no_license
|
require('spec_helper')
describe(ChildTicket) do
it {should belong_to (:good_samaritan)}
###############################################
#############__Object-Creation__###############
###############################################
before() do
@sighting = ChildTicket.new({:animal_type => "Dog", :description => "angry", :location => "here", :time => "afternoon", :picture => "none", :posession => true, :sex => "male", :news => true})
@sighting.save
end
###############################################
#############__Input-Validation__##############
###############################################
it("ensures an animal_type-entry exists") do
failed_sighting = ChildTicket.new({:animal_type => ""})
expect(failed_sighting.save()).to(eq(false))
end
it("ensures a description-entry exists") do
failed_sighting = ChildTicket.new({:description => ""})
expect(failed_sighting.save()).to(eq(false))
end
it("ensures a location-entry exists") do
failed_sighting = ChildTicket.new({:location => ""})
expect(failed_sighting.save()).to(eq(false))
end
it("ensures a time-entry exists") do
failed_sighting = ChildTicket.new({:time => nil})
expect(failed_sighting.save()).to(eq(false))
end
it("ensures a picture-entry exists") do
failed_sighting = ChildTicket.new({:picture => ""})
expect(failed_sighting.save()).to(eq(false))
end
it("ensures a posession-selection exists") do
failed_sighting = ChildTicket.new({:posession => nil})
expect(failed_sighting.save()).to(eq(false))
end
it("ensures an sex-entry exists") do
failed_sighting = ChildTicket.new({:sex => "", :news => nil})
expect(failed_sighting.save()).to(eq(false))
end
it("ensures an news-selection exists") do
failed_sighting = ChildTicket.new({:news => nil})
expect(failed_sighting.save()).to(eq(false))
end
###############################################
#########__Attribute-Verification__############
###############################################
it("ensures the sighting has a description as entered") do
expect(@sighting.description()).to(eq("angry"))
end
it("ensures the sighting has a location as entered") do
expect(@sighting.location()).to(eq("here"))
end
it("ensures the sighting has a time as entered") do
expect(@sighting.time()).to(eq("afternoon"))
end
it("ensures the sighting has a picture-entry as entered") do
expect(@sighting.picture()).to(eq("none"))
end
it("ensures the sighting has a posession-entry as entered") do
expect(@sighting.posession()).to(eq(true))
end
it("ensures the sighting has a sex as entered") do
expect(@sighting.sex()).to(eq("male"))
end
it("ensures the sighting has an news-status as entered") do
expect(@sighting.news()).to(eq(true))
end
end
| true |
ebba20a6b1bf1035d5af5b51574218967bc3755a
|
Ruby
|
cjunks94/orm-mapping-to-table-lab-dumbo-web-042318
|
/lib/student.rb
|
UTF-8
| 1,157 | 3.109375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Student
# Remember, you can access your database connection anywhere in this class
# with DB[:conn]
attr_accessor :name, :grade
attr_reader :id
@@id_count=1
def initialize(name, grade)
@name = name
@grade = grade
end
def self.id_count
@@id_count
end
def self.table_name
self.name.downcase + 's'
end
def self.create_table
sql = "CREATE TABLE IF NOT EXISTS #{table_name} (id INTEGER, name TEXT, grade TEXT)"
DB[:conn].execute(sql)
end
def self.drop_table
sql = "DROP TABLE IF EXISTS #{table_name}"
DB[:conn].execute(sql)
end
def save
sql = <<-SQL
INSERT INTO students (id, name, grade)
VALUES (?,?, ?)
SQL
last_id = DB[:conn].execute("SELECT last_insert_rowid() FROM students")
# [[]]
if last_id == []
@id=1
else
@id = last_id[0][0]+ 1
end
# @id = DB[:conn].execute("SELECT last_insert_rowid() FROM students")[0][0][0] + 1
DB[:conn].execute(sql, @id, self.name, self.grade)
# @@id_count +=1
end
def self.create(name:, grade:)
student = Student.new(name, grade)
student.save
student
end
end
| true |
98ddff82ac42469c9e3cf3de491eef2a0361d544
|
Ruby
|
wenbo/rubyg
|
/sample/CHAPTER13/242/use-kirbybase.18.rb
|
EUC-JP
| 5,250 | 3.1875 | 3 |
[] |
no_license
|
#!/usr/local/bin/ruby -Ke
require 'rubygems'
require 'kirbybase'
$KCODE='e' # nodisp
db = KirbyBase.new {|kb| kb.path = kb.memo_blob_path = "db" }
# ơ֥
db.drop_table :batters if db.table_exists? :batters # ¸ߤʤк
table = db.create_table(:batters, # battersȤơ֥
:name, :String, # ̾
:avg, :Float, # Ψ
:hr, :Integer, # ǿ
:rbi, :Integer) #
table.class # => KBTable
# ¸Υơ֥
table2 = db.get_table :batters
table2 == table # => true
# ơ֥ͤ
# ֤ͤꤹˡ
table.insert "¼", 0.312, 20, 96
# ϥå̾ꤹˡ
table.insert :name => "", :avg => 0.213, :hr => 33, :rbi => 88
# ¤Τꤹˡ
BatterStruct = Struct.new :name, :avg, :hr, :rbi
table.insert BatterStruct.new("¼", 0.201, 55, 100)
# ֥åǻꤹˡ
table.insert {|r| r.name = ""; r.avg = 0.344; r.hr = 34; r.rbi = 140 }
# ͤ
#
table.update(:rbi => 141) {|r| r.name == '' }
# ¼Ψ
table.update {|r| r.name == '¼'}.set {|r| r.avg = 0.199 }
# 䤤碌
# 쥳ɤ
table.select
# => [#<struct recno=1, name="¼", avg=0.312, hr=20, rbi=96>,
# #<struct recno=2, name="", avg=0.213, hr=33, rbi=88>,
# #<struct recno=3, name="¼", avg=0.199, hr=55, rbi=100>,
# #<struct recno=4, name="", avg=0.344, hr=34, rbi=141>]
table.select.class # => KBResultSet
table.select.class.superclass # => Array
# ̾
table.select.each do |r|
r.name # => "¼", "", "¼", ""
end
# nameȤåɤưŪɲäƤ
table.select.name # => ["¼", "", "¼", ""]
## KBResultSet#selectϥ֥åǾꤷ륫ǻꤷޤ
# 3Хå̾Ψ
table.select(:name, :avg) {|r| r.avg >= 0.3 }
# => [#<struct name="¼", avg=0.312>, #<struct name="", avg=0.344>]
# 3䡢30ǡ100Ӥ
table.select {|r| r.avg >= 0.3 and r.hr >= 30 and r.rbi >= 100 }
# => [#<struct recno=4, name="", avg=0.344, hr=34, rbi=141>]
# ̾Ψ
nm = ""
table.select(:name, :avg) {|r| r.name == nm }
# => [#<struct name="", avg=0.344>]
# Ȥ
# Ψ¤٤
table.select(:name, :avg).sort(-:avg)
# => [#<struct name="", avg=0.344>,
# #<struct name="¼", avg=0.312>,
# #<struct name="", avg=0.213>,
# #<struct name="¼", avg=0.199>]
# Ψ¤٤
table.select(:name, :rbi, :avg).sort(-:rbi, -:avg)
# => [#<struct name="", rbi=141, avg=0.344>,
# #<struct name="¼", rbi=100, avg=0.199>,
# #<struct name="¼", rbi=96, avg=0.312>,
# #<struct name="", rbi=88, avg=0.213>]
# 쥳ɥ֥ȤȤ
class Batter
def initialize(*args) @name, @avg, @hr, @rbi = args end
attr_reader :name, :avg, :hr, :rbi # ɤ߹ߥ
# KirbyBaseбʬ
attr_accessor :recno # ˺줺
def self.kb_create(recno, name, avg, hr, rbi) # KirbyBaseѥȥ饯
# Ruby 1.8.7ʹߤȡnew(name, avg, hr, rbi).tap{|o| o.recno = recno}פȤ롣
o = new(name, avg, hr, rbi); o.recno = recno; o
end
end
# battersƱƤǥ쥳ɥ饹Ȥơ֥
db.drop_table :batters2 if db.table_exists? :batters2
table2 = db.create_table(:batters2,
:name, :String,
:avg, :Float,
:hr, :Integer,
:rbi, :Integer) {|prop| prop.record_class = Batter }
# table쥳ɤtable2˥ԡ
table.select.each do |r|
table2.insert Batter.new(r.name, r.avg, r.hr, r.rbi)
end
# table2Υ쥳ɤ
table2.select
# => [#<Batter:0xb779f2a4 @avg=0.312, @hr=20, @name="¼", @rbi=96, @recno=1>,
# #<Batter:0xb779f060 @avg=0.213, @hr=33, @name="", @rbi=88, @recno=2>,
# #<Batter:0xb779ee1c @avg=0.199, @hr=55, @name="¼", @rbi=100, @recno=3>,
# #<Batter:0xb779ebd8 @avg=0.344, @hr=34, @name="", @rbi=141, @recno=4>]
table2.select {|r| r.avg >= 0.3 }
# => [#<Batter:0xb77978d8 @avg=0.312, @hr=20, @name="¼", @rbi=96, @recno=1>,
# #<Batter:0xb7797338 @avg=0.344, @hr=34, @name="", @rbi=141, @recno=4>]
# ΥΤߤϡ¾nilˤʤ롣
table2.select(:name) {|r| r.recno == 1}
# => [#<Batter:0xb779379c @avg=nil, @hr=nil, @name="¼", @rbi=nil, @recno=nil>]
# ɽ˽Ϥ
puts table2.select.to_report
# >> recno | name | avg | hr | rbi
# >> -------------------------------
# >> 1 | ¼ | 0.312 | 20 | 96
# >> 2 | | 0.213 | 33 | 88
# >> 3 | ¼ | 0.199 | 55 | 100
# >> 4 | | 0.344 | 34 | 141
| true |
427097cafc2208849795537af56cf11317b997ba
|
Ruby
|
SiCuellar/archerdx_challenge
|
/ruby/dna_seq_finder/lib/runner.rb
|
UTF-8
| 405 | 2.984375 | 3 |
[] |
no_license
|
require "./lib/dna_seq_finder"
puts "Welcome to the DNA sequence finder!"
puts "please place files needed for analysis in the fasta_files directory."
puts "please type in the name of the file you wish to analyze"
puts "\n"
file = gets.chomp
puts "\n"
dna_seq_finder = DnaSequenceFinder.new(file)
dna_seq_finder.file_update
puts "your file has been updated"
puts "Thanks for using DNA sequence finder!"
| true |
c0bd365e156a378e1b42d349ffe1ddc22afc82f0
|
Ruby
|
thnukid/facebook_data_analyzer
|
/classes/analyzeables/contacts.rb
|
UTF-8
| 1,198 | 2.890625 | 3 |
[] |
no_license
|
class Contacts < Analyzeable
def initialize(catalog:)
@catalog = catalog
@directory = "#{catalog}/html/"
@file_pattern = 'contact_info.htm'
@contacts = []
super()
end
def analyze
Dir.chdir(@directory) do
content = File.open(@file_pattern).read
doc = Nokogiri::HTML(content)
contacts_rows = doc.css('div.contents tr')
unique_contacts = contacts_rows.each_with_object({}) do |contact, seen_contacts|
text = contact.text
next if text == 'NameContacts'
seen_contacts[text] = Contact.parse(contact_text: text)
end
unique_contacts.values.each do |contact|
@contacts << contact
end
end
end
def export(package:)
contact_list_sheet(package: package)
end
private
def contact_list_sheet(package:)
package.workbook.add_worksheet(name: 'Contact list') do |sheet|
sheet.add_row ['Contact list']
sheet.add_row ["Facebook imported #{@contacts.length} of your contacts"]
sheet.add_row ['Name', 'Phone number']
@contacts.sort_by { |contact| contact.name }.each do |contact|
sheet.add_row [contact.name, contact.details]
end
end
end
end
| true |
2eeddf2721ae680efa46bbfe5c6898f38404d755
|
Ruby
|
BenKleinberg/ruby-dominion
|
/src/Cardlist.rb
|
UTF-8
| 8,614 | 3.28125 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
class Cardlist
attr_reader :supply
attr_reader :kingdom
attr_reader :back
##
## Setup Methods
##
def initialize
# Load the default cards
@supply = Array.new
supplyInitialize
@kingdom = Array.new
kingdomInitialize
@back = Card.new("Back", 0, 0, :trash)
@back.loadImage if @back.respond_to? "loadImage"
end
def addKingdom(kingdom)
@kingdom += kingdom
end
##
## Helper Methods
##
def getCard(name)
# Find a card by a given name
@supply.each do |card|
return card if card.name == name
end
@kingdom.each do |card|
return card if card.name == name
end
return nil
end
def kingdomSelect(count = 10)
# Pick a given number of kingdom cards for the game
kingdom = @kingdom.shuffle
@kingdom.clear
count.times do
card = kingdom.pop
@kingdom << card if card
end
@kingdom.sort!
end
##
## Initialize supply with base set cards
##
def supplyInitialize
#Treasure cards
text = "Gain 1 coin."
card = Treasure.new("Copper", 0, 60, 1)
card.initCon("C", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
@supply<< card
text = "Gain 2 coins."
card = Treasure.new("Silver", 3, 40, 2)
card.initCon("S", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
@supply<< card
text = "Gain 3 coins."
card = Treasure.new("Gold", 6, 30, 3)
card.initCon("G", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
@supply<< card
#Victory cards
text = "Worth 1 victory point."
card = Victory.new("Estate", 2, 1)
card.initCon("E", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
@supply<< card
text = "Worth 3 victory points."
card = Victory.new("Duchy", 5, 3)
card.initCon("D", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
@supply<< card
text = "Worth 6 victory points."
card = Victory.new("Province", 8, 6)
card.initCon("P", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
@supply<< card
#Curse cards
text = "Worth -1 victory point."
card = Curse.new("Curse", 0, 10, 1)
card.initCon("U", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
@supply<< card
end
##
## Initialize kingdom with base set cards
##
def kingdomInitialize
#Action cards
text = "Gain 1 card. Gain 2 actions."
card = Action.new("Village", 3)
card.initCon("V", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
def card.play(board)
board.drawCards 1
board.addActions 2
end
@kingdom<< card
text = "Gain 1 buy. Gain 2 coins."
card = Action.new("Woodcutter", 3)
card.initCon("W", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
def card.play(board)
board.addBuys 1
board.addCoins 2
end
@kingdom<< card
text = "Draw 3 cards."
card = Action.new("Smithy", 4)
card.initCon("Y", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
def card.play(board)
board.drawCards 3
end
@kingdom<< card
text = "Gain 2 actions. Gain 1 buy. Gain 2 coins."
card = Action.new("Festival", 5)
card.initCon("F", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
def card.play(board)
board.addActions 2
board.addBuys 1
board.addCoins 2
end
@kingdom<< card
text = "Draw 2 cards. Gain 1 action."
card = Action.new("Laboratory", 5)
card.initCon("L", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
def card.play(board)
board.drawCards 2
board.addActions 1
end
@kingdom<< card
text = "Draw 1 card. Gain 1 action. Gain 1 buy. Gain 1 coin."
card = Action.new("Market", 5)
card.initCon("M", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
def card.play(board)
board.drawCards 1
board.addActions 1
board.addBuys 1
board.addCoins 1
end
@kingdom<< card
text = "Trash up to 4 cards from your hand."
card = Action.new("Chapel", 2)
card.initCon("A", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
def card.play(board)
callback = Proc.new { |list| board.discardCards(list, :trash) if list.any? }
board.selectCards(callback, "Trash up to 4 cards from your hand.", 4)
end
@kingdom<< card
text = "Gain 1 action. Discard any number of cards. Gain 1 card per card discarded."
card = Action.new("Cellar", 2)
card.initCon("*", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
def card.play(board)
board.addActions 1
callback = Proc.new do |list|
if list.any?
board.discardCards list
board.drawCards list.size
end
end
board.selectCards(callback, "Discard any number of cards. Gain 1 card per card discarded.")
end
@kingdom<< card
text = "Trash a Copper card in your hand. If you do, gain 3 coins."
card = Action.new("Moneylender" , 4)
card.initCon("O", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
def card.play(board)
callback = Proc.new do |list|
if list.any?
board.discardCards list, :trash
board.addCoins 3
end
end
board.selectCards(callback, "Trash a Copper card in your hand. If you do, gain 3 coins.", 1) { |cardSelected| cardSelected.name == "Copper" }
end
@kingdom<< card
text = "Gain a card costing up to 4 coins"
card = Action.new("Workshop", 3)
card.initCon("K", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
def card.play(board)
board.buyMenu("Gain a card costing up to 4 coins.", true) { |cardSelected| cardSelected.cost <= 4 }
end
@kingdom<< card
text = "Trash this card. Gain a card costing up to 5 coins."
card = Action.new("Feast", 4, :trash)
card.initCon("T", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
def card.play(board)
board.buyMenu("Gain a card costing up to 5 coins.", true) { |cardSelected| cardSelected.cost <= 5 }
end
@kingdom<< card
text = "Draw 2 cards. Each other player gains a Curse card."
card = Attack.new("Witch", 5)
card.initCon("I", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
def card.play(board)
board.drawCards(2)
end
def card.attack(board)
board.addCard(board.getCard("Curse"), :discard, :passive)
end
@kingdom<< card
text = "Draw 4 cards. Gain 1 buy. Each other player draws a card."
card = Action.new("Council Room", 5)
card.initCon("@", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
def card.play(board)
board.drawCards(4)
board.addBuys(1)
board.drawCards(1, :passive)
end
@kingdom<< card
text = "Trash a Treasure card from your hand. Gain a Treasure card costing up to 3 coins more; put it into your hand."
card = Action.new("Mine", 5)
card.initCon("$", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
def card.play(board)
callback = Proc.new do |list|
if list.any?
board.discardCards(list, :trash)
maxCost = list[0].card.cost + 3
board.buyMenu("Gain a treasure card costing up to #{maxCost} coins.", true, :hand) { |cardSelected| cardSelected.cost <= maxCost }
end
end
board.selectCards(callback, "Trash a Treasure card from your hand.", 1) { |cardSelected| cardSelected.is_a? Treasure }
end
@kingdom<< card
text = "Draw 2 cards. While this card is in your hand, you are unaffected by Attack cards."
card = Reaction.new("Moat", 2)
card.initCon("~", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
def card.play(board)
board.drawCards(2)
end
@kingdom<< card
text = "Trash a card in your hand. Gain a card costing up to 2 coins more than the trashed card."
card = Action.new("Remodel", 4)
card.initCon("R", text) if card.respond_to? "initCon"
card.loadImage if card.respond_to? "loadImage"
def card.play(board)
callback = Proc.new do |list|
if(list.any?)
board.discardCards(list, :trash)
maxCost = list[0].card.cost + 2
board.buyMenu("Gain a card costing up to #{maxCost} coins.", true) { |cardSelected| cardSelected.cost <= maxCost }
end
end
board.selectCards(callback, "Trash a card in your hand.", 1)
end
@kingdom<< card
end
end
if __FILE__ == $0
end
| true |
ec74f195f01ef6b83a32ad0b8ce9013c0c635a3c
|
Ruby
|
skyxie/toys
|
/test_json/a.rb
|
UTF-8
| 302 | 3.328125 | 3 |
[] |
no_license
|
class A
def initialize a, b
@a = a
@b = b
end
def to_json(*args)
{'json_class' => self.class.name, 'a' => @a, 'b' => @b}.to_json(args)
end
def self.json_create(o)
new(o['a'], o['b'])
end
def to_s
"Hey, I'm an object! a=#{@a} b=#{@b}"
end
alias :inspect :to_s
end
| true |
5f2de0325c02d6c486b12b845a03251a9b534a6a
|
Ruby
|
bradyswenson/programming_foundations
|
/lesson_2/rock_paper_scissors.rb
|
UTF-8
| 1,914 | 3.84375 | 4 |
[] |
no_license
|
VALID_CHOICES = { 'r' => 'rock', 'p' => 'paper', 'sc' => 'scissors',
'l' => 'lizard', 'sp' => 'spock' }
score = { player: 0, computer: 0, tie: 0 }
def prompt(message)
Kernel.puts("=> #{message}")
end
def win?(first, second)
(first == 'rock' && second == 'scissors') ||
(first == 'rock' && second == 'lizard') ||
(first == 'paper' && second == 'rock') ||
(first == 'paper' && second == 'spock') ||
(first == 'scissors' && second == 'paper') ||
(first == 'scissors' && second == 'lizard') ||
(first == 'lizard' && second == 'paper') ||
(first == 'lizard' && second == 'spock') ||
(first == 'spock' && second == 'scissors') ||
(first == 'spock' && second == 'rock')
end
def tally_score(player, computer, score)
if win?(player, computer)
score[:player] += 1
elsif win?(computer, player)
score[:computer] += 1
else
score[:tie] += 1
end
end
def display_score(score)
prompt("You: #{score[:player]} | Computer: #{score[:computer]} | Ties: #{score[:tie]}")
end
def display_result(player, computer)
if win?(player, computer)
prompt('You won!')
elsif win?(computer, player)
prompt("Computer won!")
else
prompt("It's a tie!")
end
end
loop do
choice = ''
loop do
Kernel.puts("=> Choose one: (r)ock, (p)aper, (sc)issors, (l)izard, (sp)ock")
choice = Kernel.gets().chomp()
if VALID_CHOICES.key?(choice)
choice = VALID_CHOICES[choice]
break
else
prompt("Valid inputs are: r, p, sc, l, sp")
end
end
computer_choice = VALID_CHOICES[VALID_CHOICES.keys().sample()]
prompt("You chose #{choice}; computer chose #{computer_choice}")
display_result(choice, computer_choice)
tally_score(choice, computer_choice, score)
display_score(score)
prompt("Do you want to play again? (y/n)")
answer = Kernel.gets().chomp()
break unless answer.downcase().start_with?('y')
end
| true |
3721f063cbd2dc72dfaf0aa13a63f3b410390fee
|
Ruby
|
MattRedmon/pragmatic-programming-ruby
|
/chap_03.rb
|
UTF-8
| 5,643 | 3.953125 | 4 |
[] |
no_license
|
# CHAP 3 - CONTAINTERS, BLOCKS, AND ITERATORS
# ARRAYS
=begin
a = [ 3.14, "pie", 99 ]
a.type # => Array
a.length # => 3
a[0] # => 3.14
a[1] # => "pie"
a[2] # => 99
a[3] # => nil
b = Array.new
b.type # => Array
b.length # => 0
b[0] = "second"
b[1] = "array"
b # => ["second", "array"]
# Arrays are indexed using the [] operator which is actually a method in the class Array
# since [] is a method it can be over ridden in subclasses
# arrays can be accessed with negative numbers counting backwards from the end
a = [1,3,5,7,9]
a[-1] # => 9
a[-2] # => 7
a[-99] # => nil
# arrays can be accessed with a pair of numbers [start, count]
a = [1,3,5,7,9]
a[1,3] # => [3,5,7] start at position 1 and count out 3
a[3,1] # => [7] start at position 3 and count out 1
a[-3,2] # => [5,7] start at position -3 and count out 2
# arrays can be accessed using ranges with start and end position separated by either 2 or 3 periods
# the two period form includes the end position
# the three period form does not include the end position
a = [1,3,5,7,9]
a[1..3] # => [3,5,7]
a[1...3] # => [3,5]
a[3..3] # => [7]
a[-3..-1] # => [5,7,9]
# the [] operator has a corresponding []= operator which lets you set element in the array
a = [1,3,5,7,9]
a[1] = "bat" # => [1,"bat",5 7 9]
a[-3] = "cat" # => [1,"bat","cat",7,9]
a[3] = [9,8] # => [1,"bat","cat",[9,8],9]
a[6] = 99 # => [1,"bat", "cat",[9.8],9, nil, 99]
# if the index to []= is two numbers or a range then those elements in original array
# are replaced by whatever is on the right hand side of the assignment
a = [1,3,5,7,9]
a[2,2] = "cat" # => [1,3,"cat",9] start at position 2 and "cat" takes up two spots ousting 5 + 7
a[2,0] = "dog" # => [1,3,"dog","cat",9] start at position 2, take up zero spots, so adds another spots
a[1,1] = [9,8,7] # => [1,9,8,7,"dog","cat",9] start at postion 1 and add 3 nums into 1 spot
a[0..3] = [] # => ["dog", "cat",9] adds emtpy array into postions 0 through/including 3
# using array methods you can treat arrays as stacks, sets, queues, dequeues, and fifos
# HASHES
# hashes sometimes known as associative arrays or dictionaries
# while arrays indexed with integers, can index hash with objects of any type:
# strings, reg expressions, etc
# can create hash using hash literal with key value pairs between braces
h = { "dog" => "canine", "cat" => "feline", "donkey" => "asinine" }
h.length # => 3
h["dog"] # => "canine"
h["cow"] = "bovine"
h[12] = "dodecine"
h["cat"] = 99
h # => { "cow" => "bovine", "cat" => 99, 12 => "dodecine", "donkey" => "asinine", "dog" => "canine" }
# hashes have advantage that can use any object as the index
# main disadvantage is that hash elements are not ordered
# so can not easily use them as a stack or queues
# still hashes most common used data structure in Ruby
# methods needed to implement the songlist jukebox demo example
# append(aSong) => append the given song to the list
# deleteFirst() => remove the first song from the list, returning the song
# deleteLast() => remove the last song from the list, returning the song
# [anIndex] => return the song identified by anIndex which may by an integer index or song title
# the ability to append songs to the end and remove from both the front and end
# suggests a dequeue -- a double ended queue
=end
class SongList
def initialize
@songs = Array.new
end
end
class SongList
def append(aSong)
@songs.push(aSong)
self
end
end
class SongList
def deleteFirst
@songs.shift
end
def deleteLast
@songs.pop
end
end
list = SongList.new
append(Song.new("title1", "artist1", 1))
puts list
# our next method is [], which accesses elements by index. if the index is a number
# we just return the element at that postion
class SongList
def [](key)
if key.kind_of?(Integer)
@songs[key]
else
for i in [email protected]
return @songs[i] if key == @songs[i].name
end
end
return nil
end
end
# we need to add the ability to look up song by title, which involves
# scanning through songs in list checking the title of each
# above is one solution using a for loop in the else portion of the if statement
# below is another option using an iterator
# here the find method, an iterator from the Enumerable class, replaces the for loop above
# it asks the array to apply a test to each of its members
class Songlist
def [](key)
if key.kind_of?(Integer)
@songs[key]
else
result = @songs.find { |aSong| key == aSong.name }
end
return result
end
end
# from above we can use and if statement modifer to shorten the code even more
class SongList
def [](key)
return @songs[key] if key.kind_of?(Integer)
return @songs.find { |aSong| aSong.name == key }
end
end
# IMPLEMENTING ITERATORS
# iterator is simply a method that can invoke a block of code
# a block in Ruby is a way of grouping statement but
# not in conventional way as we might see in Java, C, or Perl
# first, a block may appear only in the source adjacent to amethod call
# the block is written starting on the same line as the methods parameter
# second, the code in the block is not executed at the time it is encountered
# instead Ruby remembers the context in which the block appears and then enters the method
# within the method, the block may be invoked almost as if it were a method itself
# whenever a yield is executed it invokes the code in the block,
# when the block exits, control picks back up immediatly after the yield
| true |
8165d1c6ff08f10a2c1577af3a7bcd4266cf314e
|
Ruby
|
ArwaMA/FinalProject
|
/CloneDetectionToolApproach/host.rb
|
UTF-8
| 900 | 2.984375 | 3 |
[] |
no_license
|
#! /usr/bin/env ruby
## Each commit in the host application is of type Host.
## It contains same as Commit class,
## similarity of clones in the host.
## list of files that have added/changed in the host commit and have clone codes with the donor commit that this host is part of,
## disyance measures, and total number of clones lines.
class Host < Commit
def initialize(cid, pname, date, number)
super(cid, pname, date, number)
@similarity = 0
@total_distance = 0
@nline = 0
@files = Array.new
end
def addfile(files)
@files = files
end
def add_total_distance(dis)
@total_distance = dis
end
def addSimilariy(sim)
@similarity = sim
end
def addNline(nline)
@nline = nline
end
def cid
@cid
end
def pname
@pname
end
def files
@files
end
def total_distance
@total_distance
end
def similarity
@similarity
end
def nline
@nline
end
end
| true |
f4a25afc383c8e6ca935214ad504910cb5281768
|
Ruby
|
Serummoner/joomlatools
|
/lib/jdt/manifest/referenced.rb
|
UTF-8
| 1,769 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
module Jdt
class Manifest
def referenced
list = []
# add files and media
@doc.css("files","media").each do |files|
parent_folder = files['folder']
files.css("filename").each do |file|
list << create_file_ref(file.text,parent_folder)
end
files.css("folder").each do |file|
list << create_folder_ref(file.text,parent_folder)
end
end
# scriptfile
@doc.css("scriptfile").each do |file|
list << create_file_ref(file.text)
end
return list
end
private
def create_file_ref(path, parent_folder = nil)
ref = Referenced.new
ref.path = path
ref.parent_folder = parent_folder
ref.type = :file
ref.extension_path = folder
return ref
end
def create_folder_ref(path, parent_folder = nil)
ref = Referenced.new
ref.path = path
ref.parent_folder = parent_folder
ref.type = :folder
ref.extension_path = folder
return ref
end
end
class Referenced
attr_accessor :parent_folder, :path, :type, :extension_path
def path_in_filesystem
"#{extension_path}/#{path_in_extension}"
end
def path_in_extension
if (parent_folder and parent_folder != "")
"#{parent_folder}/#{path}"
else
"#{path}"
end
end
def file?
type == :file
end
def folder?
type == :folder
end
def exists?
if (file?)
File.exists?(path_in_filesystem)
elsif (folder?)
Dir.exists?(path_in_filesystem)
else
raise RuntimeError("Neither file nor folder.")
end
end
def to_s
"Reference to #{type} #{path_in_extension}"
end
end
end
| true |
d02929378f2290d25c8b803c8d035da85adbb4a4
|
Ruby
|
nepeanwjdw/makers-bnb
|
/lib/Users.rb
|
UTF-8
| 2,004 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
require_relative 'database_connection'
require 'bcrypt'
# top level comment
class User
attr_reader :user_id, :name, :email
def initialize(user_id:, name:, email:)
@user_id = user_id
@name = name
@email = email
end
def self.create(name:, email:, password:)
return nil if User.retrieve_by_email(email: email)
hashed_password = BCrypt::Password.create(password)
result = DatabaseConnection.query("
INSERT INTO users (name, email, password)
VALUES('#{name.gsub("'","''")}', '#{email.gsub("'","''")}', '#{hashed_password}')
RETURNING user_id, name, email;
").first
User.new(
user_id: result['user_id'],
name: result['name'],
email: result['email']
)
end
def self.retrieve(user_id:)
return nil unless user_id
result = DatabaseConnection.query("
SELECT * FROM users
WHERE user_id = '#{user_id}';
").first
User.new(
user_id: result['user_id'],
name: result['name'],
email: result['email']
)
end
def self.retrieve_by_email(email:)
return nil unless email
result = DatabaseConnection.query("
SELECT * FROM users
WHERE email = '#{email}';
").first
p result
return if result == nil
User.new(
user_id: result['user_id'],
name: result['name'],
email: result['email']
)
end
def self.authenticate(email:, password:)
result = DatabaseConnection.query("
SELECT * FROM users
WHERE email = '#{email.gsub("'","''")}'
").first
return if result.nil?
return unless BCrypt::Password.new(result['password']) == password
User.new(
user_id: result['user_id'],
name: result['name'],
email: result['email']
)
end
def self.update_name_email(user_id:, new_name:, new_email:)
DatabaseConnection.query("
UPDATE users
SET name= '#{new_name.gsub("'","''")}', email= '#{new_email.gsub("'","''")}'
WHERE user_id = '#{user_id}';
")
end
end
| true |
03e2a4051149a492a32d14641a353e4186ea054c
|
Ruby
|
sharma7n/HackerRank
|
/Ruby/enumerables/enumerable_each_with_index.rb
|
UTF-8
| 226 | 3.09375 | 3 |
[
"MIT"
] |
permissive
|
def skip_animals(animals, skip)
# Your code here
filtered = []
animals.each_with_index do |animal, index|
if index >= skip
filtered.push("#{index}:#{animal}")
end
end
filtered
end
| true |
0c0a4fad04baa99b3190743accd8dc30d336b1b2
|
Ruby
|
mzahrada/Rectangles
|
/lib/rectangles/rectangle.rb
|
UTF-8
| 2,607 | 3.96875 | 4 |
[] |
no_license
|
module Rectangles
# Data object which represents 2D shape rectangle.
class Rectangle
# Error message raised when rectangle cannot be created cos its coordinates are wrong.
NOT_RECTANGLE_TEXT = 'Not rectangle.'
# Error message raised when squares do not overlap.
NO_OVERLAP_TEXT = 'Ctverce se ani nedotykaji.'
# Rectangle is represented by positions of sides.
attr_accessor :top, :bottom, :left, :right
# Rectangles area.
attr_accessor :area
# Creates new Rectangle object using sides and calculates its area.
# ---
# * Args::
# - _top_ top side
# - _bottom_ bottom side
# - _left_ left side
# - _right_ right side
# * Raises::
# - _NotRectangleError_ when given sides do not create rectangle
def initialize(top,bottom,left,right)
raise NotRectangleError.new(NOT_RECTANGLE_TEXT) if top < bottom || left > right
@area = (top - bottom) * (right - left)
@top = top
@bottom = bottom
@left = left
@right = right
end
# Creates new overlapping Rectangle between _this_ and _other_ Rectangle.
# * Args::
# - _other_ other Rectangle to be compared
# * Raises::
# - _NoOverlapError_ if rectangles do not overlap
def get_overlapping_rectangle(other)
if(@top > other.bottom && @bottom < other.top && @right > other.left && @left < other.right)
t = [@top,other.top].min
b = [@bottom,other.bottom].max
l = [@left,other.left].max
r = [@right,other.right].min
return Rectangle.new(t,b,l,r)
end
raise NoOverlapError.new(NO_OVERLAP_TEXT)
end
def to_s
return "[top: " + @top.to_s + ", bottom: " + @bottom.to_s + ", left: " + @left.to_s + ", right: " + @right.to_s + ", area: " + @area.to_s + "]"
end
class << self
# Creates new Rectangle object using midpoint _x_ and _y_ coordinate and _side_length_.
# ---
# * Args::
# - _mid_x_ x coordinate of midpoint
# - _mid_y_ y coordinate of midpoint
# - _side_length_ side length
# * Returns::
# - new _Rectangle_ object
def new_square_using_midpoint(mid_x, mid_y, side_length)
half = side_length/2.0
t = mid_y + half
b = mid_y - half
l = mid_x - half
r = mid_x + half
return Rectangle.new(t,b,l,r)
end
end
end
# Error class for signalizing rectangle errors.
class NotRectangleError < StandardError
end
# Error class for signalizing rectangles do not overlap.
class NoOverlapError < StandardError
end
end
| true |
3e98df71e5ffb2e35dad7a1c500be557307ba8bf
|
Ruby
|
George-Hudson/CloneWarz
|
/test/clone_warz/page_test.rb
|
UTF-8
| 1,565 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
require './test/test_helper'
require './lib/clone_warz/page'
class PageTest < Minitest::Test
def test_it_exists
assert Page
end
def test_it_initializes
data = {
id: 1,
title: "About",
url: "/about",
heading: "About",
img: nil,
body: "The Bike Depot is Denver's only non-profit bike shop.",
carousel_id: nil
}
assert_equal data[:title], Page.new(data).title
assert_equal data[:url], Page.new(data).url
assert_equal data[:heading], Page.new(data).heading
assert_equal data[:body], Page.new(data).body
assert_equal data[:id], Page.new(data).id
end
def test_edit_edits
data = {
id: 1,
title: "About",
url: "/about",
heading: "About",
img: nil,
body: "The Bike Depot is Denver's only non-profit bike shop.",
}
test_page = Page.new(data)
new_data = {
title: "About Us",
url: "/about-us",
heading: "About Us",
img: nil,
body: "We. Rock.",
}
test_page.edit(new_data)
assert_equal new_data[:title], test_page.title
assert_equal new_data[:url], test_page.url
assert_equal new_data[:heading], test_page.heading
assert_equal new_data[:body], test_page.body
assert_equal data[:id], test_page.id
end
def test_to_h_returns_a_hash
data = {
title: "About",
url: "/about",
heading: "About",
img: "",
body: "The Bike Depot is Denver's only non-profit bike shop.",
carousel_id: 0
}
assert_equal data, Page.new(data).to_h
end
end
| true |
36ddec3d7ba4f3bf968d268e4dadd0c97bbb6c22
|
Ruby
|
jamesdabbs/hydro
|
/lib/hydro/rule.rb
|
UTF-8
| 361 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
module Hydro
class Rule
attr_reader :ext, :to
def initialize opts={}
@ext = opts.fetch :ext
@to = opts.fetch :to
FileUtils.mkdir_p @to
end
def matches? object
if ext
object.key.end_with? ext
else
true
end
end
def location_for object
"#{to}/#{object.key}"
end
end
end
| true |
1485bccec771841816485977c86d0498b07b2282
|
Ruby
|
brianvh/dry-types
|
/spec/dry/types/sum_spec.rb
|
UTF-8
| 1,562 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
RSpec.describe Dry::Types::Sum do
describe '#[]' do
it 'works with two pass-through types' do
type = Dry::Types['int'] | Dry::Types['string']
expect(type[312]).to be(312)
expect(type['312']).to eql('312')
end
it 'works with two strict types' do
type = Dry::Types['strict.int'] | Dry::Types['strict.string']
expect(type[312]).to be(312)
expect(type['312']).to eql('312')
expect { type[{}] }.to raise_error(TypeError)
end
it 'works with nil and strict types' do
type = Dry::Types['nil'] | Dry::Types['strict.string']
expect(type[nil]).to be(nil)
expect(type['312']).to eql('312')
expect { type[{}] }.to raise_error(TypeError)
end
it 'is aliased as #call' do
type = Dry::Types['int'] | Dry::Types['string']
expect(type.call(312)).to be(312)
expect(type.call('312')).to eql('312')
end
end
describe '#default' do
it 'returns a default value sum type' do
type = (Dry::Types['nil'] | Dry::Types['string']).default('foo')
expect(type[nil]).to eql('foo')
end
it 'supports a sum type which includes a constructor type' do
type = (Dry::Types['form.nil'] | Dry::Types['form.int']).default(3)
expect(type['']).to be(3)
end
it 'supports a sum type which includes a constrained constructor type' do
type = (Dry::Types['strict.nil'] | Dry::Types['coercible.int']).default(3)
expect(type[nil]).to be(3)
expect(type['3']).to be(3)
expect(type['7']).to be(7)
end
end
end
| true |
908bd74cc127e1e591d5ca8e2daf06c59772cf36
|
Ruby
|
gadtfly/skilleo.me-challenges
|
/The Crazy Investor.rb
|
UTF-8
| 310 | 3.484375 | 3 |
[] |
no_license
|
WORD = "SKILLEO"
class SoupLetter
def initialize(s, w=6, h=6)
@s = s
@w, @h = w, h
end
def find(c)
n = @s.index(c)
r = n / @h + 1
c = n % @w + 1
"#{r}#{c}"
end
end
# gets = 'NO70JE3A4Z28X1GBQKFYLPDVWCSHUTM65R9I'
puts WORD.chars.map(&SoupLetter.new(gets).method(:find)).join
| true |
4dcc0033bd9c6932fc5c299e24a6eb6c3c41e431
|
Ruby
|
olliedavis/ruby-cs-projects
|
/binary_search_tree.rb
|
UTF-8
| 6,020 | 3.984375 | 4 |
[] |
no_license
|
class Node
attr_accessor :data, :left, :right
def initialize(data)
@data = data
@left = nil
@right = nil
end
end
class Tree
attr_accessor :root, :data
def initialize(array)
@data = array
@root = build_tree(data)
end
def build_tree(array)
return nil if array.empty? # repeats recursively until array is empty
arr = array.sort.uniq
mid = (arr.size - 1) / 2 # returns the middle index
root_node = Node.new(arr[mid]) # creates a root node from the middle index
root_node.left = build_tree(arr[0...mid]) # creates a left subtree from the left half of the array
root_node.right = build_tree(arr[(mid + 1)..-1]) # creates a right subtree from the right half of the array
root_node
end
def insert(value, node = root)
return nil if value == node.data # return nil if a new value isn't parsed
# if the new value is less than the root value,
# check if it there is another node to the left, if not, add the new value there
# if there is , loop the above until there is not.
# vice versa if the new value is greater than the root value
if value < node.data
node.left.nil? ? node.left = Node.new(value) : insert(value, node.left)
elsif value > node.data
node.right.nil? ? node.right = Node.new(value) : insert(value, node.right)
end
end
def delete(value, node = root)
return node if node.nil?
if value > node.data # if the value is more than the root node, start cascading down the right
node.right = delete(value, node.right)
elsif value < node.data # if the value is more than the root node, start cascading down the left
node.left = delete(value, node.left)
else
return node.right if node.left.nil? # if the value is more than the root node
return node.left if node.right.nil? # if the node has a right child but not a left child, delete the node and connect the right child to parent node
# if the node has two leaves, find the left most node/leaf and connect it the leaves to parent node, then delete the node
left_most_node = find_min_value_node(node.right)
node.data = left_most_node.data
node.right = delete(left_most_node.data, node.right)
end
node
end
def find_min_value_node(node)
node.left until node.left.nil?
node
end
def find(value, node = root)
return node if node.data == value || node.nil?
puts "value: #{value}"
puts "data: #{node.data}"
value < node.data ? find(value, node.left) : find(value, node.right)
end
def level_order(node = root)
queue = [] # temporary queue
data = [] # final array
queue << node # push the initial root_node into the que
until queue.empty? # keep running until queue is empty. If the queue is empty, there are no nodes left
temp = queue.shift # takes the first node in the queue
queue << temp.left if temp.left # add the left child node of the current node we pulled from the queue to the queue
queue << temp.right if temp.right # add the right child node of the node we pulled from the queue to the queue
data << temp.data # push the node to array and repeat
end
data # return the data array
end
# The left subtree is traversed first, then works its way up, pushing each node and it's children, then pushing the root node.
# Then traverses the right subtree, then works its way back up, pushing each node and it's children.
def in_order(node = root, array = [])
return if node.nil?
in_order(node.left, array) # traverse the whole left tree first
array << node.data # then push the node into the array when it reaches the leaf node
in_order(node.right, array) # then traverse the whole right tree
array
end
# Pushes the root node, then traverse the whole left subtree then the right subtree, pushing each node as it passes through
def pre_order(node = root, array = [])
return if node.nil?
array << node.data
pre_order(node.left, array)
pre_order(node.right, array)
array
end
# Traverses the whole left tree, pushing the child nodes then pushing the parent nodes
# Then traverses whole right tree, pushing the child nodes then pushing parent nodes
# Finally, pushed the root node
def post_order(node = root, array = [])
return if node.nil?
post_order(node.left, array)
post_order(node.right, array)
array << node.data
end
def height(node = root)
return -1 if node.nil?
[height(node.left), height(node.right)].max + 1
end
def depth(value, node = root)
depth = 0
temp_node = node
until temp_node == value
temp_node = temp_node.data > value ? temp_node.left : temp_node.right
depth += 1
end
depth
end
def balanced?(node = root)
root_left_depth = height(node.left)
root_right_depth = height(node.right)
diff = root_left_depth - root_right_depth
diff > -2 && diff < 2
end
def rebalance
self.data = level_order
self.root = build_tree(data)
end
end
def script
array = Array.new(15) { rand(1..100) }
tree = Tree.new(array)
puts tree.balanced? ? 'The tree is balanced' : 'The tree is not balanced'
puts "Level Order: #{tree.level_order}"
puts "In Order: #{tree.in_order}"
puts "Post Order: #{tree.post_order}"
puts "Pre Order #{tree.pre_order}"
puts 'inserting nodes 120, 145, 150, and 154 to tree to unbalance it'
tree.insert(120)
tree.insert(145)
tree.insert(150)
tree.insert(154)
puts 'testing..'
puts tree.balanced? ? 'The tree is still balanced' : 'The tree is no longer balanced'
puts 'rebalancing..'
tree.rebalance
puts tree.balanced? ? 'The tree is balanced again' : 'The tree is still not balanced'
puts "Level Order: #{tree.level_order}"
puts "In Order: #{tree.in_order}"
puts "Post Order: #{tree.post_order}"
puts "Pre Order #{tree.pre_order}"
puts "deleting 145"
tree.delete(145)
tree.rebalance
puts tree.in_order.any?(145) ? '145 still exists' : '145 removed'
end
script
| true |
a881d27a6f102b45a6c97b675d0a064b5512d9f1
|
Ruby
|
aminethedream/ruby-intro-to-arrays-lab-001
|
/lib/intro_to_arrays.rb
|
UTF-8
| 479 | 3.609375 | 4 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def instantiate_new_array
@my_new_array = Array.new
end
def array_with_two_elements
@my_two_array = Array.new
@my_two_array.push("a","b")
end
def first_element(argument)
argument[0]
end
def third_element(argument)
argument[2]
end
def last_element(argument)
argument[-1]
end
def first_element_with_array_methods(argument)
argument.first
end
def last_element_with_array_methods(argument)
argument.last
end
def length_of_array(argument)
argument.length
end
| true |
7ba43521e4e72fcadbc993d0c1246ce7d229b1eb
|
Ruby
|
pdrowr/bowling-test
|
/app/models/frame.rb
|
UTF-8
| 928 | 2.859375 | 3 |
[] |
no_license
|
class Frame < ApplicationRecord
belongs_to :game
include FrameUtils
def roll(pins_number)
raise 'Invalid roll.' if valid_pins?(pins_number)
update_roll(pins_number)
set_mark
set_pins_left(pins_number)
set_score(pins_number)
self.save
end
def get_frame(shift) # method to find a specific frame
game.frames[game.current_frame_number - 1 + shift]
end
def increment_score(score)
self.score += score
self.save
end
def set_score(pins_number)
self.increment_score(pins_number)
manage_score(pins_number)
end
def is_strike? #method that returns true if roll is a strike
self.mark.eql?('strike')
end
def is_spare? #method that returns true if roll is a spare
self.mark == 'spare'
end
def set_pins_left(pins_number) # method to set the quantity of pins left
self.pins_left -= pins_number
self.pins_left = 10 if last_frame_finished
end
end
| true |
b80b807f5b93baae031706637b7c08350191ebd0
|
Ruby
|
GentRyan/exenet_navi
|
/page.rb
|
UTF-8
| 2,335 | 2.953125 | 3 |
[] |
no_license
|
def bbs_mode(client, navi_name)
client_number = 1
puts("BBS being read")
log = File.new("bbslog","a")
log.puts((client_number.to_s) + " " + "Opened Connection")
client.puts("hs")
puts("Hand shake sent")
while true
num = client.gets.chomp()
break if num == "q"
file = File.new("news", "r")
news = file.readlines()
file.close
if (num) == "d"
then
puts("Sending news")
x = 1
i = 1
news.each do |line|
if i % 2 != 0 and line != "\n"
then
client.puts(x.to_s + " " + line)
x = x + 1
end
i = i + 1
end
client.puts("END")
end
if num == "p"
log.puts("Getting new post")
title = client.gets
message = client.gets.chomp
message = (message + " -" + navi_name + "\n")
news.insert(0,title)
news.insert(1,message)
log.puts("Added new post")
if message != ""
then
file = File.new("news", "w")
news.each { |line|
file.puts(line)
}
file.close()
end
end
if num.to_i != 0
then
news.insert(0,"")
news.insert(1,"")
log.puts("Sending line!")
num = num.to_i
line = news[num * 2]
client.puts(line)
line = news[num * 2 + 1]
client.puts(line)
log.puts("Sent line!")
news.delete_at(0)
news.delete_at(0)
client.puts("END")
end
end
client_number = client_number + 1
end
require 'socket' # Get sockets from stdlib
server = TCPServer.open(2000) # Socket to listen on port 2000
active_users = Array.new
loop { # Servers run forever
Thread.start(server.accept) do |client|
puts("Connection accepted")
client.puts("v")
navi_name = client.gets.chomp
active_users.push(navi_name)
puts(navi_name + " has jacked in")
client.puts("hs")
area_file = File.new("area","r")
area = area_file.readlines()
area_file.close
while true
cAction = client.gets.chomp()
if cAction == "a"
then
puts("Area file being read")
area.each { |line|
client.puts(line)
}
client.puts("END")
end
if cAction == "u"
puts("User list being read")
active_users.each { |user|
client.puts(user)
}
client.puts("END")
puts("User list ended")
end
if cAction == "bbs"
then
bbs_mode(client, navi_name)
end
break if cAction == "j"
end
active_users.delete(navi_name)
end
}
| true |
4cbfd58471d4759981aa789ff1e2697632236c84
|
Ruby
|
DeveloperAlan/WDI_SYD_7_Work
|
/w01/d01/eugenius/learning_new_strings.rb
|
UTF-8
| 562 | 3.296875 | 3 |
[] |
no_license
|
puts "Hello Scambank at your service, put in your pin please."
pin_number = gets.strip
pin_number.to_s
if pin_number == "000"
puts "Correct! Please stand by for assistance..."
puts "..." * 2000
else
puts "Hahah your PIN is #" + "#{pin_number}, you gonna get hacked!"
puts "Like-a-sumbawdy-fuck-u-bic-boi".upcase
p "Whachu gonna do? You gonna do something about it?"
reaction = gets.strip
if
reaction == "yes"
print "You better recognize foo!"
elsif
reaction == "no"
print "What! Imma Cap Yo Ass Foo!"
else
print "Yeah I didn't think so. Bye"
end
end
| true |
8431369442df249ee9374c2f758f746021965159
|
Ruby
|
tuzz/vivid
|
/lib/ease.rb
|
UTF-8
| 541 | 3.3125 | 3 |
[] |
no_license
|
# The different methods for easing are here:
# https://github.com/munshkr/easing-ruby/blob/master/lib/easing.rb
class Ease
attr_accessor :method, :duration
def initialize(method, duration)
self.method = coerce(method.to_s)
self.duration = duration
end
def at(time)
Easing.public_send(method, time, 0, 1, duration)
end
private
def coerce(method)
if method.start_with?("ease")
method.to_sym
elsif method.start_with?("linear")
:linear_tween
else
:"ease_#{method}"
end
end
end
| true |
3deceef54fd0e36996be6872447a2bc22c4888a6
|
Ruby
|
takkkun/peeek
|
/lib/peeek/supervisor.rb
|
UTF-8
| 3,030 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
require 'peeek/hooks'
class Peeek
class Supervisor
# Create a supervisor for instance methods.
#
# @return [Peeek::Supervisor] a supervisor for instance methods
def self.create_for_instance
new(:method_added)
end
# Create a supervisor for singleton methods.
#
# @return [Peeek::Supervisor] a supervisor for singleton methods
def self.create_for_singleton
new(:singleton_method_added)
end
# Initialize the supervisor.
#
# @param [Symbol] callback_name name of the method that is called when
# methods was added to object of a hook
def initialize(callback_name)
@callback_name = callback_name
@hooks = Hooks.new
@original_callbacks = {}
end
# @attribute [r] hooks
# @return [Peeek::Hooks] hooks that is registered to the supervisor
attr_reader :hooks
# @attribute [r] original_callbacks
# @return [Hash<Object, Method>] original callbacks of objects that is
# supervising
attr_reader :original_callbacks
# Add hooks to target that is supervised.
#
# @param [Array<Peeek::Hook>] hooks hooks that is supervised
def add(*hooks)
@hooks.push(*hooks)
hooks.map(&:object).uniq.each do |object|
@original_callbacks[object] = proceed(object) unless proceeded?(object)
end
self
end
alias << add
# Clear the hooks and the objects that is supervising.
def clear
@hooks.clear
define_callbacks(@original_callbacks).clear
self
end
# Run process while circumvent supervision.
#
# @yield any process that wants to run while circumvent supervision
def circumvent(&process)
current_callbacks = @original_callbacks.keys.map do |object|
[object, object.method(@callback_name)]
end
define_callbacks(@original_callbacks)
begin
@hooks.circumvent(&process)
ensure
define_callbacks(Hash[current_callbacks])
end
end
private
def proceeded?(object)
!!@original_callbacks[object]
end
def proceed(object)
supervisor = self
hooks = @hooks
original_callbacks = @original_callbacks
object.method(@callback_name).tap do |original_callback|
define_callback(object) do |method_name|
hook = hooks.get(self, method_name)
if hook
hooks.delete(hook)
unless hooks.get(self)
original_callback = original_callbacks.delete(self)
supervisor.__send__(:define_callback, self, &original_callback)
end
hook.link
end
original_callback[method_name]
end
end
end
def define_callback(object, &proc)
singleton_class = class << object; self end
singleton_class.__send__(:define_method, @callback_name, &proc)
end
def define_callbacks(callbacks)
callbacks.each do |object, callback|
define_callback(object, &callback)
end
end
end
end
| true |
67126a4aeaae81b59e2675b792a1cb2f7f9c0612
|
Ruby
|
JaciBrunning/Waitress
|
/lib/waitress/kernel.rb
|
UTF-8
| 6,837 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
# The Kernel Module provides global methods that will provide the 'builtins' for .wrb files
# and handlers. This is used to prevent verbose access of a namespace like Waitress::Global,
# and instead provide them here. Because requests are handled in new Processes, these values
# will change in each request and will not interfere.
module ::Kernel
# The +Waitress::Response+ object being used
def response_object
$RESPONSE
end
# The +Waitress::Request+ object being used
def request_object
$REQUEST
end
# Prepare the Kernel, by linking global variables
def kernel_prepare
$METHOD = get_method
$HEADERS = get_headers
$PATH = get_path
$URI = get_uri
$BODY = get_body
end
# Automatically load a library header into this file in the form of HTML.
# This will load a library in the VHost's libs/ folder, or any lib defined in the
# VHost's config.rb file with the name given. JS libraries will be linked with the
# <script> tag, whilst css files will be linked with the <link rel="stylesheet">
# tag. This is the recommended way of handling library loading.
# Params:
# +name+:: The name of the lib (the filename), or the name of the library as bound
# in the config.rb file.
def lib name
name = name.to_sym
type = $VHOST.libraries[name][:type]
libhome = $VHOST.liburi
if type == :js
echo "<script type='text/javascript' src='/#{libhome}/#{name}'></script>"
elsif type == :css
echo "<link rel='stylesheet' href='/#{libhome}/#{name}'></link>"
end
end
# Automatically load a Library Combo into this file. This will consecutively load
# all the libraries bound to the combination with the given name as defined in the
# VHost's config.rb file. This will call lib() for each of these libraries.
# Params:
# +name+:: The name of the combo to load
def combo name
name = name.to_sym
combo_arr = $VHOST.combos[name]
combo_arr.each do |n|
if $VHOST.combos.include? n.to_sym
combo(n)
else
lib(n)
end
end
end
# Include another .wrb, .rb or any other file in the load path of the VHost into this
# file. If this file is .wrb or .rb, it will be evaluated. If it is another type of file
# (e.g. html), it will be directly echoed to the output buffer
# Params:
# +filename+:: The name of the file, relative to the loadpath
def includes filename
Waitress::Chef.include_file filename
end
# Include another .wrb, .rb or any other file in this file. If this file is
# .wrb or .rb, it will be evaluated. If it is another type of file
# (e.g. html), it will be directly echoed to the output buffer
# Params:
# +filename+:: The absolute filename of the file to load, anywhere in the filesystem
def includes_file filename
Waitress::Chef.include_absfile filename
end
# The configuration for the VHost. As described in the +Waitress::VHost+ class,
# this data is set in the config.rb file and is then read out later by the
# server. Use this to configure constants such as Social Media links, and other details
def config
$VHOST.config
end
# Returns a Hash of the GET query of the request. This may be an empty array
# if querystring was present
def get
request_object.get_query
end
# Returns a Hash of the POST query of the request. This may be an empty array
# if the body is not a valid querystring, or an exception raised if there was
# an error in parsing.
def post
request_object.post_query
end
# Get a header from the HTTP Request. This will fetch the header by the given
# name from the request object. Keep in mind that in requests, Headers are fully
# capitalized and any hyphens replaced with underscores (e.g. Content-Type becomes
# CONTENT_TYPE)
def get_header name
request_object.headers[name]
end
# Return the full list of headers available in the request object.
def get_headers
request_object.headers
end
# Returns the HTTP method that was used to retrieve this page (GET, POST, UPDATE,
# DELETE, PUT, etc)
def get_method
request_object.method
end
# Get the path of this request. This is after a URL rewrite, and does not contain
# a querystring. Be careful with these, as they start with a "/" and if not joined
# correctly can cause issues in the root of your filesystem (use File.join) if you
# plan to use this
def get_path
request_object.path
end
# Get the URI of this request. Unlike the path, the URI is not modified after a rewrite,
# and does contain a querystring. Use this if you want the *original* path and query
# of the request before it was rewritten
def get_uri
request_object.uri
end
# Get the request body. In most cases, this will be blank, but for POST requests it may
# contain a querystring, and for PUT and UPDATE methods it may contain other data
def get_body
request_object.body
end
# Get the querystring object as a string before it is parsed
def get_querystring
request_object.querystring
end
# Set a response header. This will be joined when writing the response with the delimiter ": "
# as in regular HTTP Protocol fashion.
# Params:
# +name+:: The name of the header, e.g. "Content-Type"
# +value+:: The value of the header, e.g. "text/html"
def set_header name, value
response_object.header name, value
end
# Set the content-type of the response. This is a shortcut to the Content-Type
# header and takes the full content-type (not fileextension) as an argument
# Params:
# +raw_type+:: The mime type of the content, e.g. "text/html"
def set_content_type raw_type
response_object.mime_raw raw_type
end
# Set the content-type of the response. This is a shortcut to the Content-Type
# header, and will also lookup the fileextension in the +Waitress::Util+ mime-type
# lookup.
# Params:
# +extension+:: The file extension to map to a mimetype, e.g. ".html"
def file_ext extension
response_object.mime extension
end
# Write a string to the output buffer. This will write directly to the body of the
# response, similar to what 'print()' does for STDOUT. Use this to write data to the
# output stream
def echo obj
str = obj.to_s
write str
end
# Write a string to the output buffer, followed by a newline. Similar to echo(),
# this will write to the output buffer, but also adds a "\n". This does to the
# client output as 'puts()' does to STDOUT. Use this to write data to the output
# stream
def println obj
echo(obj.to_s + "\n")
end
# Write a set of bytes directly to the output stream. Use this if you don't want
# to cast to a string as echo() and println() do.
def write bytes
r = response_object
r.body "" if r.body_io.nil?
r.body_io.write bytes
end
end
| true |
f4e7465970c8e42448a33769c19de6cb95a00d68
|
Ruby
|
enkessler/cuke_slicer
|
/testing/file_helper.rb
|
UTF-8
| 533 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
require 'tmpdir'
module CukeSlicer
# A helper module that create files and directories during testing
module FileHelper
class << self
def created_directories
@created_directories ||= []
end
def create_directory(options = {})
options[:name] ||= 'test_directory'
options[:directory] ||= Dir.mktmpdir
path = "#{options[:directory]}/#{options[:name]}"
Dir.mkdir(path)
created_directories << options[:directory]
path
end
end
end
end
| true |
1a67365e50f5af223893ea920c03bb0e2d158bd6
|
Ruby
|
patrickcurl/CodeEvalSolutions
|
/Ruby/beautifulStrings.rb
|
UTF-8
| 1,968 | 3.84375 | 4 |
[] |
no_license
|
# BEAUTIFUL STRINGS
# CHALLENGE DESCRIPTION:
# Credits: This problem appeared in the Facebook Hacker Cup 2013 Hackathon.
# When John was a little kid he didn't have much to do. There was no internet, no Facebook, and no programs to hack on. So he did the only thing he could... he evaluated the beauty of strings in a quest to discover the most beautiful string in the world.
# Given a string s, little Johnny defined the beauty of the string as the sum of the beauty of the letters in it. The beauty of each letter is an integer between 1 and 26, inclusive, and no two letters have the same beauty. Johnny doesn't care about whether letters are uppercase or lowercase, so that doesn't affect the beauty of a letter. (Uppercase 'F' is exactly as beautiful as lowercase 'f', for example.)
# You're a student writing a report on the youth of this famous hacker. You found the string that Johnny considered most beautiful. What is the maximum possible beauty of this string?
# INPUT SAMPLE:
# Your program should accept as its first argument a path to a filename. Each line in this file has a sentence. E.g.
# ABbCcc
# Good luck in the Facebook Hacker Cup this year!
# Ignore punctuation, please :)
# Sometimes test cases are hard to make up.
# So I just go consult Professor Dalves
# OUTPUT SAMPLE:
# Print out the maximum beauty for the string. E.g.
# 152
# 754
# 491
# 729
# 646
# Submit your solution in a file (some file name).(py2| c| cpp| java| rb| pl| php| tcl| clj| js| scala| cs| m| py3| hs| go| bash| lua) or use the online editor.
def frequency(a)
a.group_by do |e|
e
end.map do |key, values|
[values.size]
end
end
File.open(ARGV[0]).each_line do |line|
a = line.downcase.gsub(/[^a-z]/, '').split('')
b = frequency(a).sort_by(&:last).reverse.flatten
count = 26
total = 0
b.each do |f|
total = total + (f*count)
count -= 1
end
print total
print "\n"
end
| true |
a8b4344d14f03e9336c102b82c8b7941c77aac61
|
Ruby
|
grzegorzzajac1989/theOdinProject
|
/ruby/building_blocks/stock_picker.rb
|
UTF-8
| 657 | 3.4375 | 3 |
[] |
no_license
|
def stock_picker( daily_price_array )
best_profit = 0
low_buy = 0
high_sell = 0
daily_price_array.each_with_index do |buy_price, buy_day|
daily_price_array.each_with_index do |sell_price, sell_day|
if buy_day < sell_day
profit = sell_price - buy_price
if profit > best_profit
best_profit = profit
low_buy = buy_day
high_sell = sell_day
end
end
end
end
puts "In this period, you should have bought on day #{low_buy} and should have sold on day #{high_sell}. This would have given a profit of $#{best_profit}"
end
stock_picker( [4, 5, 1, 17, 6, 24, 8, 7] )
stock_picker( [17, 3, 6, 9, 15, 8, 6, 1, 10] )
| true |
9849545263730cbcef6511d4221b38af8c52a12f
|
Ruby
|
aleandros/aleandros.github.io
|
/tasks.thor
|
UTF-8
| 1,201 | 2.78125 | 3 |
[] |
no_license
|
require 'time'
require 'fileutils'
class Blog < Thor
include Thor::Actions
desc 'post TITLE', 'Create a new post with current date'
def post(title)
@title = title
template('_templates/post.tt',
"_posts/#{date_string}-#{title_string}.markdown")
end
desc 'draft TITLE', 'Create a draft with given title'
def draft(title)
@title = title
template('_templates/draft.tt',
"_drafts/#{title_string}.markdown")
end
desc 'publish', 'Move a draft to the post folder, adding date'
def publish
drafts = Dir['_drafts/*.markdown']
abort 'No drafts' if drafts.empty?
drafts.each_with_index do |d, i|
puts "[#{i}] - #{File.basename(d)}"
end
selected = ask 'Please select a draft to publish',
limited_to: (0..drafts.size - 1).map(&:to_s)
file = drafts[selected.to_i]
dest = "_posts/#{date_string}-#{File.basename(file)}"
FileUtils.mv(file, dest)
say "Post #{dest} is created"
end
def self.source_root
File.dirname(__FILE__)
end
private
def title_string
@title.downcase.split(/\s/).join('-')
end
def date_string
Date.today.strftime('%Y-%m-%d')
end
end
| true |
d7549f921c5e60760be43beb908f0d102c243f08
|
Ruby
|
cantlin/tfl
|
/lib/main_line.rb
|
UTF-8
| 1,596 | 3 | 3 |
[] |
no_license
|
require 'date'
require 'uri'
require 'cgi'
class MainLine < App
attr_accessor :num_results
def set_defaults
self.num_results = 5
end
def departures station, num_results = nil
url = "http://ojp.nationalrail.co.uk/service/ldb/liveTrainsJson?departing=true&liveTrainsFrom=#{URI::encode(station)}&liveTrainsTo="
num_results = (num_results || self.num_results).to_i
if num_results > 50
$stderr.puts "Sorry, the maximum results to show is 50"
exit 1
end
request = Curl::Easy.new(url) do |curl|
curl.timeout = 10
end
begin
request.perform
departures = JSON.parse(request.body_str)
rescue Curl::Err::TimeoutError => e
$stderr.puts "Request timed out :("
exit 1
rescue StandardError => e
$stderr.puts e.message
exit 1
end
if departures['trains'].size == 0
puts "No departures listed for station \"#{station}\" :("
end
now = Time.now
i = 0
messages = []
departures['trains'].each do |t|
hour, minute = *t[1].split(':')
departure_time = Time.new(now.year, now.month, now.day, hour, minute)
interval = (departure_time - now).to_f / 60
if(interval > 0 && i < num_results)
i += 1
messages << CGI.unescapeHTML("#{t[1]} to #{t[2]} in #{(interval.to_i == 0 ? '<1 minute' : interval.to_i.to_s + ' minutes')}")
end
end
inner_div = "-" * (messages.sort_by {|m| m.length * -1 }.first.length + 4)
outer_div = inner_div.gsub("-", "=")
puts outer_div, " Departures from \"#{station}\"", inner_div
messages.each {|m| puts " " + m }
puts outer_div
end
end
| true |
c0366e9c644b52708e845b2cbbdc00fd3ba9da52
|
Ruby
|
ralphreid/WDI_LDN_3_Work
|
/ralphreid/w2d5/classwork/movies_app/model/movie.rb
|
UTF-8
| 1,241 | 3.0625 | 3 |
[] |
no_license
|
class Movie
def initialize connection
@connection = connection
end
def all
@connection.exec "SELECT * FROM movies" #retun is implicit in ruby
end
def find id
@movie = @connection.exec("SELECT * FROM movies WHERE id=#{id }").first
end
def create params # TIP - called the argument params so that there was nothing to change in the method when we main
@connection.exec("INSERT INTO movies (title, year, rated, poster, director, actors)
VALUES ('#{params[:title]}', '#{params[:year]}', '#{params[:rated]}', '#{params[:poster]}', '#{params[:director]}', '#{params[:actors]}') RETURNING id") [0]["id"]
end
def search query
@connection.exec "SELECT * FROM movies WHERE title ILIKE '%#{query}%'"
end
def find id
@connection.exec("SELECT * FROM movies WHERE id=#{id.to_i}").first
end
def update params
@connection.exec "UPDATE movies SET
title='#{params[:title]}',
year='#{params[:year]}',
rated='#{params[:rated]}',
poster='#{params[:poster]}',
director='#{params[:director]}',
actors='#{params[:actors]}'
WHERE id=#{params [:movie_id]}"
end
def delete id
@connection.exec "DELETE FROM movies WHERE id= #{id} "
end
end
| true |
d243d7046e07df14fef4165fb70bba7320a6d029
|
Ruby
|
18F/identity-idp
|
/app/components/step_indicator_component.rb
|
UTF-8
| 898 | 2.6875 | 3 |
[
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class StepIndicatorComponent < BaseComponent
attr_reader :current_step, :locale_scope, :tag_options
def initialize(steps:, current_step:, locale_scope: nil, **tag_options)
@steps = steps
@current_step = current_step
@locale_scope = locale_scope
@tag_options = tag_options
end
def css_class
['step-indicator', *tag_options[:class]]
end
def steps
@steps.map { |step| { status: step_status(step), title: step_title(step) }.merge(step) }
end
private
def step_status(step)
if step[:name] == current_step
:current
elsif step_index(step[:name]) < step_index(current_step)
:complete
end
end
def step_title(step)
if locale_scope
t(step[:name], scope: [:step_indicator, :flows, locale_scope])
else
step[:title]
end
end
def step_index(name)
@steps.index { |step| step[:name] == name }.to_i
end
end
| true |
e775c36bafdc661da60b376f114409812ecae8f3
|
Ruby
|
aaronjwagener/my_coop
|
/db/seeds.rb
|
UTF-8
| 1,183 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
User.create!(name: "Example User",
email: "[email protected]",
password: "password",
password_confirmation: "password",
admin: true)
99.times do |n|
name = Faker::Name.name
email = "example-#{n+1}@example.com"
password = "password"
User.create!(name: name,
email: email,
password: password,
password_confirmation: password)
end
# Coops
Coop.create!( name: "Example Coop",
description: "A democratic place!")
50.times do |n|
name = Faker::Company.name
description = Faker::Lorem.sentence(5)
Coop.create!(name: name,
description: description)
end
# Memberships
users = User.all
user = users.first
members = users[2..40]
coops = Coop.all
coop = coops.first
joined_coops = coops[1..7]
members.each { |new_member| coop.add_member(new_member) }
joined_coops.each { |new_coop| user.join_coop(new_coop) }
| true |
b803387f27cff5334527e4b0ba6040e0fc5f14c5
|
Ruby
|
cielavenir/procon
|
/codeforces/tyama_codeforces004C.rb
|
UTF-8
| 140 | 2.84375 | 3 |
[
"0BSD"
] |
permissive
|
#!/usr/bin/ruby
h={}
gets.to_i.times{|i|
x=s=gets.chomp
if !h[s]
h[s]=0
puts :OK
else
h[s]+=1
puts s+h[s].to_s
end
}
| true |
6d0173ea6831d1875437bb85b28f7a873d70acea
|
Ruby
|
Odebe/Tabi
|
/baka/paragraph.rb
|
UTF-8
| 152 | 2.59375 | 3 |
[] |
no_license
|
# frozen_string_literal: true
module Baka
class Paragraph
attr_reader :text
def initialize(text)
@text = text.strip
end
end
end
| true |
703ccc976fcdac6614259358fb2ffed67d0f5302
|
Ruby
|
jhbadger/scripts
|
/parseTIGRCoords
|
UTF-8
| 328 | 2.65625 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
# converts TIGR coords file to one that PyPhy, etc. can use
if (ARGV.size != 1)
STDERR.printf("usage: %s coord-file\n", $0)
exit(1)
end
file = ARGV.shift
orf = "00001"
File.new(file).each {|line|
start, stop = line.split(" ")
printf("%10s %6s %6s\n", "ORF" + orf, start, stop)
orf = orf.succ
}
| true |
1792ad150d66ea27d1993eb59f1b5ad8b2471002
|
Ruby
|
bver/GERET
|
/sample/santa_fe_ant_trail/animate.rb
|
UTF-8
| 321 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
$: << 'sample/santa_fe_ant_trail'
require 'ant'
abort "use:\n #$0 ant_code.rb\n" unless ARGV.size==1
code = IO.read ARGV[0]
ant = Ant.new
while ant.steps < Ant::MaxSteps
eval code
puts ant.show_scene
puts "food items consumed: #{ant.consumed_food}"
puts "steps elapsed: #{ant.steps}"
$stdin.gets
end
| true |
a324a11f492b87f4514ad52310830388b4b8b1a7
|
Ruby
|
carlosmartinez/questions-to-anki-cards
|
/app.rb
|
UTF-8
| 208 | 2.578125 | 3 |
[] |
no_license
|
input_lines = File.read("./input.txt").split("\n")
output_lines = input_lines.each_slice(3).map do |question, answer, _space|
"#{question};#{answer}"
end
File.write("./output.txt", output_lines.join("\n"))
| true |
1ecdf01f60701934956bf59728b9de500ed75ae1
|
Ruby
|
Kyle-Schiffli/Launch_101
|
/lesson_2/rock_paper_scissors.rb
|
UTF-8
| 888 | 3.71875 | 4 |
[] |
no_license
|
def prompt(message)
puts "=> #{message}"
end
def display_results(player, computer)
if (player == 'rock' && computer == "scissors") ||
(player == 'scissors' && computer == "paper") ||
(player == 'paper' && computer == "rock")
prompt('You Win!')
elsif (player == 'rock' && computer == "paper") ||
(player == 'scissors' && computer == "rock") ||
(player == 'paper' && computer == "scissors")
prompt('You Lose!')
else prompt('You Tie!')
end
end
VALID_CHOICES = ['rock', 'paper', 'scissors']
choice = ''
loop do
prompt("Choose one: #{VALID_CHOICES.join(', ')} ")
choice = gets.chomp
if VALID_CHOICES.include?(choice)
break
else
prompt("That's not a vaild choice")
end
end
computer_choice = VALID_CHOICES.sample
prompt("You choose #{choice}, computer choose #{computer_choice}")
display_results(choice,computer_choice)
| true |
a00469aa8d81416caafe743c525a086a4071ef3b
|
Ruby
|
MelahatMindivanli/odev-01ruby
|
/address_book.rb
|
UTF-8
| 731 | 3.78125 | 4 |
[] |
no_license
|
require 'csv'
require './person.rb'
class AddressBook
attr_accessor :people #Getter ve Setter
def initialize(csv_path) #Constructor
@people = []
#print '#'
CSV.foreach(csv_path,{ :col_sep => ',' }) do |row|
people.push(Person.new(row[0],row[1],row[2],row[3]))
end
end
def print_people
people.each do |person|
puts "# #{person.id},#{person.full_name},#{person.phone_number},#{person.city}"
end
end
def search_person(person_name)
people.each do |person|
if person.full_name.to_s.include? person_name
puts "# #{person.id},#{person.full_name},#{person.phone_number},#{person.city}"
end
end
puts "!!!!! Cannot find #{person_name} named person!"
end
end
| true |
97743c705a74a165653b4d6fb572c0c2131cf858
|
Ruby
|
morfious902002/spring_2012
|
/petstore/spec/support/basic_data_helpers.rb
|
UTF-8
| 394 | 2.578125 | 3 |
[] |
no_license
|
def get_key
@@key ||= 0
@@key += 1
@@key.to_s
end
def basic_pet_data(options = {})
{:name => "pet#{get_key}", :species => "dog"}.merge(options)
end
def basic_user_data(options = {})
{:email => "b#{get_key}@.test.com", :password_digest => "1234x#{get_key}"}.merge(options)
end
def new_valid_user
u = User.new(:email => "b#{get_key}@test.com")
u.password_digest = "1234x#{get_key}"
u
end
| true |
5d0e762b4d1220ebe394267f7bda5f16da6f240a
|
Ruby
|
lingzhuzi/one_config
|
/app/models/user.rb
|
UTF-8
| 852 | 2.71875 | 3 |
[] |
no_license
|
require 'digest'
class User < ApplicationRecord
validates :login, presence: true, uniqueness: true
validates :password, confirmation: true, length: { minimum: 6 }
validates :password_confirmation, presence: true
before_save :generate_salt
before_save :encrypt_password
def authenticate(password_text)
self.password == encrypt_with_salt(password_text)
end
private
def generate_salt
chars = '0123456789abcdefghijklmnopqrstuvwxyz`~!#$%^&*()_+-=[]{}\|;:,./<>?'
salt = ''
random = Random.new
32.times do
salt << chars[random.rand(chars.size)]
end
self.salt = Digest::SHA2.new(256).hexdigest(salt)
end
def encrypt_password
self.password = encrypt_with_salt(self.password)
end
def encrypt_with_salt(text)
Digest::SHA2.new(256).hexdigest("OneConfig_#{text}_#{self.salt}")
end
end
| true |
256e4399f53fcce9f126e1e5658eb9b879965039
|
Ruby
|
tenderlove/concurrent-ruby
|
/lib/concurrent/exchanger.rb
|
UTF-8
| 870 | 3.484375 | 3 |
[
"Ruby",
"MIT"
] |
permissive
|
module Concurrent
class Exchanger
EMPTY = Object.new
def initialize(opts = {})
@first = MVar.new(EMPTY, opts)
@second = MVar.new(MVar::EMPTY, opts)
end
# @param [Object] value the value to exchange with an other thread
# @param [Numeric] timeout the maximum time in second to wait for one other
# thread. nil (default value) means no timeout
# @return [Object] the value exchanged by the other thread; nil if timed out
def exchange(value, timeout = nil)
first = @first.take(timeout)
if first == MVar::TIMEOUT
nil
elsif first == EMPTY
@first.put value
second = @second.take timeout
if second == MVar::TIMEOUT
nil
else
second
end
else
@first.put EMPTY
@second.put value
first
end
end
end
end
| true |
5c43aef31cdc80f03488b74d00e326752ebdfe3a
|
Ruby
|
bweave/advent-of-code-2017
|
/test/day_5_test.rb
|
UTF-8
| 598 | 2.953125 | 3 |
[] |
no_license
|
require "byebug"
require "minitest/autorun"
require "minitest/pride"
require_relative "../day_5"
class Day5Test < Minitest::Test
def test_maze_steps
instructions = [0,3,0,1,-3]
assert 5, Maze.steps(instructions)
instructions = File.readlines("day_5_input.txt").map(&:to_i)
puts "\nsteps: #{Maze.steps(instructions)}\n"
end
def test_maze_strange_steps
instructions = [0,3,0,1,-3]
assert 10, Maze.strange_steps(instructions)
instructions = File.readlines("day_5_input.txt").map(&:to_i)
puts "\nstrange_steps: #{Maze.strange_steps(instructions)}\n"
end
end
| true |
d00de4c96bd55248adf819d985e81be245a9588c
|
Ruby
|
EricLarson2020/futbol
|
/lib/game_teams.rb
|
UTF-8
| 862 | 2.640625 | 3 |
[] |
no_license
|
class GameTeams
attr_reader :game_id, :team_id, :hoa, :result, :settled_in, :head_coach,
:goals, :shots, :tackles, :pim, :powerplayopportunities, :powerplaygoals,
:faceoffwinpercentage, :giveaways, :takeaways
def initialize(stats)
@game_id = stats[:game_id].to_i
@team_id = stats[:team_id].to_i
@hoa = stats[:hoa]
@result = stats[:result]
@settled_in = stats[:settled_in]
@head_coach = stats[:head_coach]
@goals = stats[:goals].to_i
@shots = stats[:shots].to_i
@tackles = stats[:tackles].to_i
@pim = stats[:pim].to_i
@powerplayopportunities = stats[:powerplayopportunities].to_i
@powerplaygoals = stats[:powerplaygoals].to_i
@faceoffwinpercentage = stats[:faceoffwinpercentage].to_f
@giveaways = stats[:giveaways].to_i
@takeaways = stats[:takeaways].to_i
end
end
| true |
16b8bab46c6d3a53f42775c0b497dd0e70ee4815
|
Ruby
|
jzajpt/persistence
|
/spec/unit/object_factory_spec.rb
|
UTF-8
| 1,351 | 2.53125 | 3 |
[] |
no_license
|
# encoding: utf-8
require 'spec_helper'
class PersistenceTestObject
attr_accessor :id
end
describe Persistence::ObjectFactory do
describe '#materialize' do
let(:factory) { Persistence::ObjectFactory.new hash }
let(:id) { BSON::ObjectId.new }
let(:hash) { { _type: 'PersistenceTestObject', _id: id, key_a: 'a', key_b: 'b' } }
it 'materializes object based on _type attribute' do
instance = PersistenceTestObject.new
PersistenceTestObject.should_receive(:new).and_return(instance)
factory.materialize
end
it 'assigns id to materialized object' do
object = factory.materialize
object.id.should eq(id)
end
it 'assigns @type to materialized object' do
object = factory.materialize
object.instance_variable_get(:@type).should eq(object.class.name)
end
it 'assigns values from hash to instance variables' do
object = factory.materialize
object.instance_variable_get(:"@key_a").should eq('a')
object.instance_variable_get(:"@key_b").should eq('b')
end
it 'does not assign @_type' do
object = factory.materialize
object.instance_variable_get(:"@_type").should be_nil
end
it 'does not assign @_id' do
object = factory.materialize
object.instance_variable_get(:"@_id").should be_nil
end
end
end
| true |
ac2cc4c5d5c5f97978ff93ad1088278045173680
|
Ruby
|
SlipperyJ/rubycode
|
/cars.rb
|
UTF-8
| 976 | 4.03125 | 4 |
[] |
no_license
|
class Car
#instance variables
@manufacturer = ""
@type = ""
@model = ""
@speed = 0
#Setter method
def set_manufacturer(manufacturer)
@manufacturer = manufacturer
end
#Getter method
def get_manufacturer
@manufacturer
end
def set_type(type)
@type = type
end
def set_type
@type
end
def set_model(model)
@model = model
end
def get_model
@model
end
def set_speed(speed)
@speed = speed
end
def get_speed
@speed
end
end
# assigning variable with frame of car class
car1 = Car.new
car2 = Car.new
car3 = Car.new
# calling setter method and passing argument"
car1.set_manufacturer("Ford")
car2.set_manufacturer("Jaguar")
car3.set_manufacturer("Porsche")
# create array with objects
collection_of_cars = [car1, car2, car3]
puts collection_of_cars
# for each variable do |"current array id"|, then define method
collection_of_cars.each do |current_car|
puts current_car.get_manufacturer
end
| true |
76b44e1b13835aa9d2a874b6b3a11df803732b27
|
Ruby
|
ty-doerschuk/phase-0
|
/week-6/guessing-game/my_solution.rb
|
UTF-8
| 3,485 | 4.5 | 4 |
[
"MIT"
] |
permissive
|
# Build a simple guessing game
# I worked on this challenge [by myself, with: ].
# I spent [#] hours on this challenge.
# Pseudocode
# Input: initialized with an integer called 'answer'
# Output: a symbol if the the integer is low, high, or correct
# Steps:
=begin
1. Define class method
2. DEFINE initialize with 'answer' for guessing game as input
3. DEFINE instance method guess with input 'guess'
4. create instance variable for guess
5. IF 'answer' is equal to 'guess'
6. RETURN correct symbol
7. ELSEIF 'answer' is less than 'guess'
8. RETURN high symbol
9. ELSE 'answer' is greater than 'guess'
10. return low symbol
11. DEFINE instance method solved as true or false
12. IF 'guess' is equal to 'answer'
13. RETURN true
14. ELSE 'guess' is not equal to 'answer'
15. RETURN false
=end
# Initial Solution
=begin
class GuessingGame
def initialize(answer)
@answer = answer
end
def guess(guess)
@guess = guess
if @answer == @guess
return :correct
elsif @answer < @guess
return :high
else @answer > @guess
return :low
end
end
def solved?
if @guess == @answer
return true
else @guess != @answer
return false
end
end
end
=end
# Make sure you define the other required methods, too
# Refactored Solution
class GuessingGame
def initialize(answer)
@answer = answer
end
def guess(guess)
@guess = guess
return :correct if @answer == @guess
@guess > @answer ? :high : :low
end
def solved?
@guess == @answer ? true : false
end
end
# Reflection
=begin
How do instance variables and methods represent the characteristics and behaviors (actions) of a real-world object?
Since instance variables are bound to the class, we can associate them with any characteristics or behavior inside. So if we think of console video games, we would want to categories them. Let’s say by console. After we have them divided by console let’s rate the best console game against another best console game. So in Ruby terms, it would be a Class VideoGame, we would have instance variables such as PlayStation or NES, then we would have methods determining which PlayStation or NES game are better than each other. The point I am trying to make is that instance variables and methods are all related because they are all under the same class. It’s up to us the programmer to manipulate the data to achieve we want to discover.
When should you use instance variables? What do they do for you?
When you need to class variable from another instance method inside a class. They save us time and confusion.
Explain how to use flow control. Did you have any trouble using it in this challenge? If so, what did you struggle with?
It’s the process of using control expression to manipulate your data. Since flow control is based around true or false, you can manipulate your data to go the place you want it to by yes or no. It keeps you on pace to your coding objective in my opinion. I did not have any trouble using flow control in this challenge. I kept it simple and just used if, elsif, or else to keep it easy to read and get a MVP.
Why do you think this code requires you to return symbols? What are the benefits of using symbols? Ruby symbols are immutable, which means they cannot be changed. This means they save memory. They were relevant to this challenge because :high, :low, and :correct didn’t not need to be manipulated, they just needed to be called.
=end
| true |
1e31d284150a5c21b5e9ccd67f449851da8fdc16
|
Ruby
|
plato721/head-first-design-ruby
|
/factory/spec/pizza_examples.rb
|
UTF-8
| 614 | 2.796875 | 3 |
[] |
no_license
|
shared_examples "a pizza" do |pizza|
it "can be cut" do
expect(pizza).to respond_to(:cut)
end
it "can be baked" do
expect(pizza).to respond_to(:bake)
end
it "can be boxed" do
expect(pizza).to respond_to(:box)
end
it "has a settable name" do
pizza.name = "Moses"
expect(pizza.name).to eql("Moses")
end
it "defines a prepare" do
expect(pizza).to respond_to(:prepare)
end
it "has ingredients" do
pizza.prepare
expect(pizza.ingredients.length > 0).to be_truthy
expect(pizza.ingredients.all? do |i|
i.is_a? Ingredient
end).to be_truthy
end
end
| true |
634631159f22a4e068a623f5be01b040065481b9
|
Ruby
|
andrewhao/cyclecity-core
|
/app/models/velocitas_core/gpx_downloader.rb
|
UTF-8
| 1,664 | 2.578125 | 3 |
[] |
no_license
|
# Downloads a URL to a local file on the worker
module VelocitasCore
class GpxDownloader
include Interactor
delegate :url, :filename, :attachment, to: :context
attr_accessor :response
#attr_accessor :url, :response, :filename
# @param [String] url The URL to the GPX file.
# @param [String] filename (Optional) The desired filename of the desired file.
# Otherwise, it gets the name of the MD5 sum of its file contents.
#def initialize(url, filename: filename)
# @url = url
# @filename = filename
# @response = nil
#end
def call
@response = connection.get(url)
if status == 200
context.file = save!
else
context.fail! message: "Download failed"
end
end
delegate :success?, to: :context
def status
response.try(:status)
end
private
def contents
@response.body
end
# Returns the handle to the File object that this file is downloaded to
def save!
path = File.join(basedir, computed_filename)
Rails.logger.info "Saved GPX file as #{path}"
file = File.new(path, 'wb')
file.write contents
file.close
file
end
def basedir
Rails.root.join("tmp")
end
def computed_filename
filename || "#{SecureRandom.hex(12)}.gpx"
end
def connection
@connnection ||= Faraday.new do |faraday|
faraday.request :url_encoded # form-encode POST params
faraday.response :logger # log requests to STDOUT
faraday.adapter Faraday.default_adapter # make requests with Net::HTTP
end
end
end
end
| true |
9e9ea7261a473a72f3f141abd6df2084a38961b0
|
Ruby
|
vamsipavanmahesh/problem-solving
|
/factorial.rb
|
UTF-8
| 162 | 4.03125 | 4 |
[] |
no_license
|
def factorial(n)
if n == 1
return 1
else
return n * factorial(n-1)
end
end
puts "enter a number to find the factorial for"
n = gets.to_i
puts factorial(n)
| true |
d09878fb53aa190286eb92c0eb799ce0c8d7e1e0
|
Ruby
|
Ingenico-ePayments/connect-sdk-ruby
|
/lib/ingenico/connect/sdk/defaultimpl/default_marshaller.rb
|
UTF-8
| 1,124 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
require 'json'
require 'singleton'
module Ingenico::Connect::SDK
module DefaultImpl
# marshals objects to and from JSON format.
# Currently supports marshalling and unmarshalling of classes that support class.new_from_hash and class#to_h
class DefaultMarshaller < Ingenico::Connect::SDK::Marshaller
include Singleton
# NOTE: this alias is needed to not break existing method calls depending on old interface
class << self
alias_method :INSTANCE, :instance
end
# Marshals the _request_object_ to a JSON string using request_object#to_h
def marshal(request_object)
JSON.pretty_generate(request_object.to_h)
end
# Unmarshals a JSON string into an object of type _klass_ using klass.new_from_hash
def unmarshal(json_string, klass)
if json_string.nil?
return nil
elsif json_string.length == 0
return ''
end
if klass.respond_to?(:new_from_hash)
klass.new_from_hash(JSON.load(json_string))
else
raise NotImplementedError
end
end
end
end
end
| true |
726e15288c3eb0c42cce98af7d987aae4cbe3429
|
Ruby
|
Brayan9105/Exercises
|
/classesExercise/even_fib.rb
|
UTF-8
| 883 | 3.46875 | 3 |
[] |
no_license
|
# frozen_string_literal: true
require 'minitest/autorun'
# Some documentation
class Fibonnaci
attr_reader :fibs_numbers
attr_reader :even_sum
def initialize
@fibs_numbers = [0, 1]
@i = 2
@even_sum = 0
end
def find_sequence(last_element)
if last_element > @i
loop do
@fibs_numbers[@i] = @fibs_numbers[@i - 2] + @fibs_numbers[@i - 1]
@i += 1
break if @i >= last_element + 2
end
sum_even_numbers
end
true
end
def sum_even_numbers
@even_sum = 0
@fibs_numbers.each do |number|
@even_sum += number if (number % 2).zero?
end
end
end
# Some documentation
class TestEvenFib < Minitest::Test
def setup
@my_fib = Fibonnaci.new
end
def test_find_sequence
assert_equal true, @my_fib.find_sequence(10)
end
def test_even_sum
assert_equal 0, @my_fib.even_sum
end
end
| true |
b41feea4779fb7eda3d2527b89d7a4752995b540
|
Ruby
|
TerribleDev/zanzibar
|
/lib/zanzibar/cli.rb
|
UTF-8
| 5,037 | 2.609375 | 3 |
[
"Apache-2.0"
] |
permissive
|
require 'thor'
require 'thor/actions'
require 'zanzibar/version'
require 'zanzibar/cli'
require 'zanzibar/ui'
require 'zanzibar/actions'
require 'zanzibar/error'
require 'zanzibar/defaults'
module Zanzibar
##
# The `zanzibar` binary/thor application main class.
# See http://whatisthor.com/ for information on syntax.
class Cli < Thor
include Thor::Actions
##
# The stream to which we are writing messages (usually stdout)
attr_accessor :ui
##
# Initialize the application and set some logging defaults
def initialize(*)
super
the_shell = (options['no-color'] ? Thor::Shell::Basic.new : shell)
@ui = Shell.new(the_shell)
@ui.be_quiet! if options['quiet']
@ui.debug! if options['verbose']
debug_header
end
##
# Print the version of the application
desc 'version', 'Display your Zanzibar verion'
def version
say "#{APPLICATION_NAME} Version: #{VERSION}"
end
##
# Generate a new blank Zanzifile
desc 'init', "Create an empty #{ZANZIFILE_NAME} in the current directory."
option 'verbose', type: :boolean, default: false, aliases: :v
option 'wsdl', type: :string, aliases: :w,
default: DEFAULT_WSDL % DEFAULT_SERVER,
desc: 'The URI of the WSDL file for your Secret Server instance'
option 'domain', type: :string, default: 'local', aliases: :d,
desc: 'The logon domain for your Secret Server account'
option 'force', type: :boolean, default: false, aliases: :f,
desc: 'Recreate the Zanzifile if one already exists.'
option 'secretdir', type: :string, default: 'secrets/', aliases: :s,
desc: 'The directory to which secrets should be downloaded.'
option 'ignoressl', type: :boolean, default: 'false', aliases: :k,
desc: 'Don\'t check the SSL certificate of Secret Server'
def init
run_action { init! }
end
##
# Fetch secrets declared in a local Zanzifle
desc 'bundle', "Fetch secrets declared in your #{ZANZIFILE_NAME}"
option 'verbose', type: :boolean, default: false, aliases: :v
def bundle
run_action { bundle! }
end
desc 'plunder', "Alias to `#{APPLICATION_NAME} bundle`", hide: true
option 'verbose', type: :boolean, default: false, aliases: :v
alias plunder bundle
desc 'install', "Alias to `#{APPLICATION_NAME} bundle`"
alias install bundle
##
# Redownload Zazifile secrets
desc 'update', "Redownload all secrets in your #{ZANZIFILE_NAME}"
option 'verbose', type: :boolean, default: false, aliases: :v
def update
run_action { update! }
end
desc 'get SECRETID', 'Fetch a single SECRETID from Secret Server'
option 'domain', type: :string, aliases: :d,
desc: 'The logon domain to use when logging in.'
option 'server', type: :string, aliases: :s,
desc: 'The Secret Server hostname or IP'
option 'wsdl', type: :string, aliases: :w,
desc: 'Full path to the Secret Server WSDL'
option 'ignoressl', type: :boolean, aliases: :k,
desc: 'Don\'t verify Secret Server\'s SSL certificate'
option 'filelabel', type: :string, aliases: :f,
desc: 'Specify a file (by label) to download'
option 'fieldlabel', type: :string, aliases: :l,
desc: 'Specify a field (by label) to get'
option 'username', type: :string, aliases: :u
option 'password', type: :string, aliases: :p
##
# Fetch a single secret specified on the commandline
def get(scrt_id)
run_action { get! scrt_id }
end
private
def debug_header
@ui.debug { "Running #{APPLICATION_NAME} in debug mode..." }
@ui.debug { "Ruby Version: #{RUBY_VERSION}" }
@ui.debug { "Ruby Platform: #{RUBY_PLATFORM}" }
@ui.debug { "#{APPLICATION_NAME} Version: #{VERSION}" }
end
##
# Run the specified action and rescue errors we
# explicitly send back to format them
def run_action(&_block)
yield
rescue ::Zanzibar::Error => e
@ui.error e
abort "Fatal error: #{e.message}"
end
def init!
say "Initializing a new #{ZANZIFILE_NAME} in the current directory..."
Actions::Init.new(@ui, options).run
say "Your #{ZANZIFILE_NAME} has been created!"
say 'You should check the settings and add your secrets.'
say 'Then run `zanzibar bundle` to fetch them.'
end
def bundle!
say "Checking for secrets declared in your #{ZANZIFILE_NAME}..."
Actions::Bundle.new(@ui, options).run
say 'Finished downloading secrets!'
end
def update!
say "Redownloading all secrets declared in your #{ZANZIFILE_NAME}..."
Actions::Bundle.new(@ui, options, update: true).run
say 'Finished downloading secrets!'
end
def get!(scrt_id)
say Actions::Get.new(@ui, options, scrt_id).run
end
end
end
| true |
edfd5670bbf57f32813ec7053f48fa57c82b83f5
|
Ruby
|
itggot-ludvig-ohlsson/standard-biblioteket
|
/lib/is_odd.rb
|
UTF-8
| 240 | 4.03125 | 4 |
[] |
no_license
|
# Public: Check if a number is odd.
#
# num - The Integer to be checked.
#
# Examples
#
# is_odd(1337)
# # => true
#
# is_odd(420)
# # => false
#
# Returns if the number is odd or not.
def is_odd(num)
return num % 2 == 1
end
| true |
8a25e649b8c678585f68721bc24fc938ac3c638c
|
Ruby
|
chrisbrickey/tdd-minesweeper
|
/lib/game.rb
|
UTF-8
| 604 | 3.765625 | 4 |
[] |
no_license
|
require 'board'
require 'tile'
class Game
def self.prompt_user
puts "What size of board do you want to play on? (type an integer between 3 and 100, inclusive)\n"
size = gets.chomp
while !size.to_i.between?(3, 100)
puts "Please type an integer between 3 and 100, inclusive.\n"
size = gets.chomp
end
size.to_i
end
# def self.play(size)
# board = Board.new(size)
# intro_board = board.display
# # intro_board = "X X\nX X\n"
# puts intro_board
# end
end
if __FILE__ == $0
size = Game.prompt_user
board = Board.new(size)
board.display
end
| true |
2593b63042775afdad44c62389e0f58c5e1835cd
|
Ruby
|
dhaas/limecast
|
/vendor/plugins/scenarios/lib/scenarios/extensions/symbol.rb
|
UTF-8
| 325 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
class Symbol
# Convert a symbol into the associated scenario class:
#
# :basic.to_scenario #=> BasicScenario
# :basic_scenario.to_scenario #=> BasicScenario
#
# Raises Scenario::NameError if the the scenario cannot be loacated in
# Scenario.load_paths.
def to_scenario
to_s.to_scenario
end
end
| true |
ffc566fdbd595b6e2b2c74bffa0dadaacb4c938c
|
Ruby
|
DomyDoo/Launch-School-Intro-to-Programming
|
/the-basics-exercises/exercises.rb
|
UTF-8
| 1,661 | 4.46875 | 4 |
[] |
no_license
|
# The exercises at the end of The Basics section
# Exercise 1
puts "\nAnswer to Exercise 1:"
first_name = "Domenic"
last_name = "Carobine"
puts first_name + " " + last_name
# Exercise 2
puts "\nAnswer to Exercise 2:"
num = 9934
puts "The number in the thousands place is: #{num / 1000}"
puts "The number in the hundreds place is: #{num % 1000 / 100}"
puts "The number in the tens place is: #{num % 100 / 10}"
puts "The number in the ones place is: #{num % 10}"
# Exercise 3
puts "\nAnswer to Exercise 3:"
movie_hash = {seven_samurai: 1954, jurassic_park: 1993, blade: 1998, blade_runner: 1982, the_incredibles: 2004}
movie_hash.each_value {|v| puts v}
# Exercise 4
puts "\nAnswer to Exercise 4:"
movie_date = []
movie_hash.each_value {|v| movie_date.push(v)}
movie_date.each {|date| puts date}
# Exercise 5
puts "\nAnswer to Exercise 5:"
starting_nums = [5, 6, 7, 8]
starting_nums.each do |i|
final = 1
(2..i).each do |j|
final = j * final
end
puts "The factorial of #{i} is #{final}"
end
# Exercise 6
puts "\nAnswer to Exercise 6:"
print "Enter a float number: "
num1 = gets.chomp.to_f
print "Enter a float number: "
num2 = gets.chomp.to_f
print "Enter a float number: "
num3 = gets.chomp.to_f
def square(num)
num ** 2
end
puts "The square of #{num1} is #{square(num1)}"
puts "The square of #{num2} is #{square(num2)}"
puts "The square of #{num3} is #{square(num3)}"
# Exercise 7
puts "\nAnswer to Exercise 7:"
puts "\tThe error message says that there is a ')' in the code when it was expecting a '}'."
puts "\tThis could have happened accidentaly when making a hash or when substituting an expression into a string"
| true |
f4ab3b5c6a62069a80b25c660280b3c574fc4623
|
Ruby
|
dtuite/wordpaths
|
/lib/string_refinements.rb
|
UTF-8
| 303 | 3.015625 | 3 |
[] |
no_license
|
module StringRefinements
refine String do
def split_before_each_char
0.upto(self.length).map { |i| [self[0...i], self[i..-1]] }
end
def split_around_each_char
self.chars.each_with_index.map do |char, i|
[self[0...i], char, self[(i+1)..-1]]
end
end
end
end
| true |
0cab706cb82259babdb6cfaa1e14b9f294537c9b
|
Ruby
|
bayendor/mastermind
|
/lib/game.rb
|
UTF-8
| 1,636 | 3.3125 | 3 |
[
"MIT"
] |
permissive
|
require_relative 'message_printer'
class Game
attr_accessor :command,
:guess,
:code,
:printer,
:turns,
:guess_checker,
:start_time,
:end_time
def initialize(printer = MessagePrinter.new)
@command = ''
@guess = ''
@code = new_code
@printer = printer
@turns = 1
end
def game_colors
%w(R Y G B)
end
def clear_screen
print "\e[2J\e[f"
end
def play
clear_screen
printer.game_intro
@start_time = Time.now
until win? || exit?
printer.turn_indicator(turns)
printer.game_command_request
@command = gets.upcase.strip
@guess = command
process_game_turn
end
end
def process_game_turn
case
when exit?
printer.game_quit
when win?
end_time = Time.now - @start_time
printer.game_win(code, turns, end_time)
when valid_turn_input?
check_guess
else
printer.not_a_valid_command(@guess.length)
end
end
def new_code
4.times.map do
game_colors.sample
end
end
def add_turn
@turns += 1
end
def win?
# p @code # for testing
@guess.chars == @code
end
def exit?
command == 'Q' || command == 'QUIT'
end
def valid_turn_input?
/[RBYG]{4}/ =~ @guess && @guess.length == 4
end
def check_guess
@guess_checker = GuessChecker.new(code, guess)
correct_color = guess_checker.color_only
correct_position = guess_checker.color_and_position
printer.turn_result(guess, correct_position, correct_color)
add_turn
end
end
| true |
d7683a037707b0a0bac68f0d0565cd8ffde33331
|
Ruby
|
apoc64/black_thursday
|
/lib/customer_repository.rb
|
UTF-8
| 834 | 2.90625 | 3 |
[] |
no_license
|
require 'csv'
require_relative 'customer'
require_relative 'repository'
# This class is a repo for customers
class CustomerRepository
include Repository
def initialize
@elements = {}
end
def build_elements_hash(elements)
elements.each do |element|
customer = Customer.new(element)
@elements[customer.id] = customer
end
end
def find_all_by_first_name(first_name)
all.find_all do |element|
element.first_name.downcase.include?(first_name.downcase)
end
end
def find_all_by_last_name(last_name)
all.find_all do |element|
element.last_name.downcase.include?(last_name.downcase)
end
end
def create(attributes)
create_id_number
attributes[:id] = create_id_number
customer = Customer.new(attributes)
@elements[create_id_number] = customer
end
end
| true |
7f51c12d2898e8689b060ed044aaa980dee6ec29
|
Ruby
|
mattcaesar/App-Academy
|
/3 Ruby/2 Ghost/v1 code/game.rb
|
UTF-8
| 2,096 | 3.8125 | 4 |
[] |
no_license
|
require './player.rb'
class Game
attr_reader :fragment
def initialize(player1_name, player2_name)
#@players = []
@player1 = Player.new(player1_name)
@player2 = Player.new(player2_name)
@fragment = []
@current_player = @player1
dictionary_arr = File.open('dictionary.txt').readlines.map(&:chomp)
@dictionary = Hash.new
dictionary_arr.each do |word|
@dictionary[word] = true
end
end
def player_turn
puts "#{@current_player.player_name}, enter a letter"
letter = gets.chomp
if valid_play?(letter)
@fragment << letter
# if !self.game_over?
# self.switch_player
# self.player_turn
# end
else
puts
puts 'invalid entry, try again'
puts
puts "Current word: #{@fragment.join('')}"
puts
self.player_turn
end
end
def switch_player
@previous_player = @current_player
if @current_player == @player1
@current_player = @player2
else
@current_player = @player1
end
end
def valid_play?(letter)
alpha = [*'a'..'z']
possible_word = @fragment.join('') + letter
if alpha.include?(letter.downcase) && @dictionary.keys.any? { |word| word[0...possible_word.length] == possible_word }
return true
end
false
end
def valid_word?(word)
@dictionary.has_key?(word)
end
def game_over?
if valid_word?(@fragment.join(''))
puts
puts "#{@previous_player.player_name}, you lose"
puts
return true
end
false
end
def play_round
while !self.game_over?
puts
puts "Current word: #{@fragment.join('')}"
puts
self.player_turn
self.switch_player
end
end
end
game = Game.new('matt', 'tammie')
game.play_round
| true |
78c3aeca73d3baa4ad00bedb8e2c2e2caa4f8978
|
Ruby
|
AndrewHannigan/studimetrics
|
/app/models/null_section_completion.rb
|
UTF-8
| 274 | 2.65625 | 3 |
[] |
no_license
|
class NullSectionCompletion
attr_accessor :section
delegate :name, to: :section, prefix: true
def initialize(section=nil)
self.section = section
end
def status
"Not Started"
end
def in_progress?
false
end
def completed?
false
end
end
| true |
7da5deb76e1597429eda1f9e2d8feeaf5eab23d0
|
Ruby
|
mredmond0919/LS1
|
/RB100/exercises/intro_book/exercises/loops2.rb
|
UTF-8
| 137 | 3.4375 | 3 |
[] |
no_license
|
while 1
puts "Type what ever you want and it repeats. Type STOP to stop"
text = gets.chomp
if text == "STOP"
break
end
puts text
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.