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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
27ea8051a3584cc027ad05dfeabaf8d0179f9ad2 | Ruby | stevejackson/priphea | /app/services/embedded_art_extractor.rb | UTF-8 | 2,127 | 2.765625 | 3 | [] | no_license | class EmbeddedArtExtractor
attr_accessor :filename
def initialize(filename)
@filename = filename
end
def write_to_cache!
temporary_file = extract_picture_data_to_tmp_file
return nil unless temporary_file
write_cover_art_to_cache(temporary_file)
end
def write_cover_art_to_cache(temporary_file)
# now copy the /tmp file to the cover art cache and return it
if File.exist?(temporary_file)
md5 = Digest::MD5.hexdigest(File.read(temporary_file)) + File.extname(temporary_file)
destination = File.join(Settings.cover_art_cache, md5)
FileUtils.copy(temporary_file, destination)
return File.basename(destination)
else
Rails.logger.info "Failed to find or copy embedded art."
nil
end
end
def extract_picture_data_to_tmp_file
random_string = Random.rand(2000000).to_s
full_path_jpg = File.join("/", "tmp", "#{random_string}.jpg")
full_path_png = File.join("/", "tmp", "#{random_string}.png")
mime_type, picture_data = extract_cover_art_from_metadata
case mime_type
when 'image/jpeg'
write_image_to_file!(picture_data, full_path_jpg)
return full_path_jpg
when 'image/png'
write_image_to_file!(picture_data, full_path_png)
return full_path_png
end
end
def extract_cover_art_from_metadata
file_format = File.extname(@filename).downcase
if file_format == '.flac'
TagLib::FLAC::File.open(@filename) do |file|
if file.picture_list.length > 0
picture = file.picture_list.first
return [picture.mime_type, picture.data]
end
end
elsif file_format == '.mp3'
TagLib::MPEG::File.open(@filename) do |file|
tag = file.id3v2_tag
if tag && tag.frame_list('APIC').length > 0
cover = tag.frame_list('APIC').first
return [cover.mime_type, cover.picture]
end
end
else
raise "Unsupported MIME type in this song file"
end
end
def write_image_to_file!(cover_art_data, filename)
File.open(filename, 'wb') do |file|
file.write(cover_art_data)
end
end
end
| true |
8fbeee50a43e5177d95dd5b71d529bfcaacc715e | Ruby | blevy115/ruby_fundamentals1 | /exercise4-2.rb | UTF-8 | 154 | 3.53125 | 4 | [] | no_license | puts "What is your age?"
age = gets.to_i
diff = (age-25).abs
if age > 105
puts "I;m not sure I believe you"
else
puts "We are #{diff} years apart."
end
| true |
e592a1866e45cedc83c5bee164ae138d67662004 | Ruby | thisisDom/phase-0-tracks | /ruby/iteration_drill.rb | UTF-8 | 4,500 | 3.375 | 3 | [] | no_license | # Array Drills
zombie_apocalypse_supplies = ["hatchet", "rations", "water jug", "binoculars",
"shotgun", "compass", "CB radio", "batteries"]
# 1. Iterate through the zombie_apocalypse_supplies array,
# printing each item in the array separated by an asterisk
# ----
p zombie_apocalypse_supplies.join("*")
# ----
# 2. In order to keep yourself organized, sort your zombie_apocalypse_supplies
# in alphabetical order. Do not use any special built-in methods.
# ----
zombie_apocalypse_supplies.each do
index = 0
while index < zombie_apocalypse_supplies.size - 1
if zombie_apocalypse_supplies[index].downcase > zombie_apocalypse_supplies[index+1].downcase
zombie_apocalypse_supplies[index], zombie_apocalypse_supplies[index+1] = zombie_apocalypse_supplies[index+1],zombie_apocalypse_supplies[index]
end
index += 1
end
end
p zombie_apocalypse_supplies
# ----
# 3. Create a method to see if a particular item (string) is in the
# zombie_apocalypse_supplies. Do not use any special built-in methods.
# For instance: are boots in your list of supplies?
# ----
def in_list(item, array)
index = 0
in_array = nil
while index < array.size
break if item.downcase == array[index].downcase
index += 1
end
if index == array.size
return false
else
return true
end
end
# ----
# 4. You can't carry too many things, you've only got room in your pack for 5.
# Remove items in your zombie_apocalypse_supplies in any way you'd like,
# leaving only 5. Do not use any special built-in methods.
# ----
zombie_apocalypse_supplies.each do |value|
index = zombie_apocalypse_supplies.index(value)
if zombie_apocalypse_supplies.size > 5
zombie_apocalypse_supplies.delete_at(index)
end
end
# ----
# 5. You found another survivor! This means you can combine your supplies.
# Create a new combined supplies list out of your zombie_apocalypse_supplies
# and their supplies below. You should get rid of any duplicate items.
# Find the built-in method that helps you accomplish this in the Ruby
# documentation for Arrays.
# ----
other_survivor_supplies = [ "warm clothes", "rations", "compass", "camp stove",
"solar battery", "flashlight"]
combined_supplies = zombie_apocalypse_supplies.concat(other_survivor_supplies).uniq
# ----
# Hash Drills
extinct_animals = {
"Tasmanian Tiger" => 1936,
"Eastern Hare Wallaby" => 1890,
"Dodo" => 1662,
"Pyrenean Ibex" => 2000,
"Passenger Pigeon" => 1914,
"West African Black Rhinoceros" => 2011,
"Laysan Crake" => 1923
}
# 1. Iterate through extinct_animals hash, printing each key/value pair
# with a dash in between the key and value, and an asterisk between each pair.
# ----
extinct_animals.each do |animal, extinct_year|
print "#{animal}-#{extinct_year}*"
end
# 2. Keep only animals in extinct_animals if they were extinct before
# the year 2000. Do not use any special built-in methods.
# ----
extinct_before_2000 = {}
extinct_animals.each do |animal, extinct_year|
if(value<2000)
extinct_before_2000[animal] = extinct_year
end
end
# 3. Our calculations were completely off, turns out all of those animals went
# extinct 3 years before the date provided. Update the values in extinct_animals
# so they accurately reflect what year the animal went extinct.
# Do not use any special built-in methods.
# ----
extinct_animals.map do |animal, extinct_year|
extinct_animals[animal] = extinct_year - 3
end
# 4. You've heard that the following animals might be extinct, but you're not sure.
# Check if they're included in extinct_animals, one by one:
# "Andean Cat"
# "Dodo"
# "Saiga Antelope"
# Do not use any special built-in methods.
# ----
def in_extinct_animals(animal, extinct_animals)
in_extinct = false
extinct_animals.each do |extinct_animal, extinct_year|
if(extinct_animal.downcase == animal.downcase)
in_extinct = true
end
end
return in_extinct
end
puts in_extinct_animals("Andean Cat", extinct_animals)
puts in_extinct_animals("Dodo", extinct_animals)
puts in_extinct_animals("Saiga Antelope", extinct_animals)
# 5. We just found out that the Passenger Pigeon is actually not extinct!
# Remove them from extinct_animals and return the key value pair as a two item array.
# Find the built-in method that helps you accomplish this in the Ruby documentation
# for Hashes.
# ----
extinct_animals.select{|extinct_animal, extinct_year|
extinct_animal == "Passenger Pigeon"
}.flatten
| true |
c0ca7e14f73e05991fa0befaf55589382ee7d19d | Ruby | Steff01/First_ruby | /lib/00_hello.rb | UTF-8 | 255 | 3.953125 | 4 | [] | no_license | def ask_first_name
puts "What is your first name"
first_name = gets.chomp
return first_name
end
def say_hello(first_name)
puts "Bonjour, #{first_name}!"
end
def greet
first_name = ask_first_name
say_hello(first_name)
end
greet
| true |
a8d714b9d0a1f12ea47279e5c9bad4eb81f94d7b | Ruby | vinny13/RosettaCodeData | /Task/Read-a-configuration-file/Ruby/read-a-configuration-file.rb | UTF-8 | 562 | 2.640625 | 3 | [] | no_license | fullname = favouritefruit = needspeeling = seedsremoved = false
IO.foreach("fruit.conf") do |line|
line.chomp!
key, value = line.split(nil, 2)
case key
when /^([#;]|$)/; # ignore line
when "FULLNAME"; fullname = value
when "FAVOURITEFRUIT"; favouritefruit = value
when "NEEDSPEELING"; needspeeling = true
when "SEEDSREMOVED"; seedsremoved = true
when /^./; puts "#{key}: unknown key"
end
end
puts "fullname = #{fullname}"
puts "favouritefruit = #{favouritefruit}"
puts "needspeeling = #{needspeeling}"
puts "seedsremoved = #{seedsremoved}"
| true |
cbb16aee682f40c71a8e53328e4056ffd6af18f8 | Ruby | michaelginalick/phase_0_unit_2 | /week_5/3_guessing_game_solo_challenge/my_solution.rb | UTF-8 | 1,478 | 3.890625 | 4 | [] | no_license | # U2.W5: Build a simple guessing game SOLO CHALLENGE
# I worked on this challenge [by myself, with: ].
# 2. Pseudocode
# Input:
# Output:
# Steps:
# 3. Initial Solution
#Define an instance method GuessingGame#guess which takes an integer called guess as its input.
#guess should return the symbol :high if the guess is larger than the answer,
#:correct if the guess is equal to the answer,
#and :low if the guess is lower than the answer.
#Define an instance method GuessingGame#solved? which returns true if the most recent guess was correct
#and false otherwise.
class GuessingGame
def initialize(answer)
@answer = answer
end
def guess(num)
@num = num
if @num > @answer
return :high
else if
@num < @answer
return: low
if @num == @answer
return :true
else
return :false
end
def solved?
if @num == @answer
return :correct
else
return: false
end
return false unless @num == @answer
return true
end
# 4. Refactored Solution
class GuessingGame
def initialize(answer)
@answer = answer
end
def guess(num)
@num = num
if @num > @answer
return :high
else if
@num < @answer
return :low
else @num == @answer
return :correct
end
end
end
def solved?
return false unless @num == @answer
return true
end
end
# 1. DRIVER TESTS GO BELOW THIS LINE
# 5. Reflection
| true |
24447d077256f880308291c5fc96ff93c349cb14 | Ruby | marth00165/oo-inheritance-code-along-seattle-web-060319 | /lib/car.rb | UTF-8 | 184 | 2.734375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require_relative "./vehicle.rb"
require "pry"
class Car < Vehicle #inherited
def go
"VRRROOOOOOOOOOOOOOOOOOOOOOOM!!!!!" #edits the method from vehicle
end
end
binding.pry
0
| true |
67e1e274e59278876f5bcf5661f5ff59561b2f4f | Ruby | ljsuo/ProjectEulerProblems | /projeuler24/pe24.rb | UTF-8 | 218 | 3.9375 | 4 | [] | no_license |
arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
def permute(arr)
return arr.permutation.to_a
end
def find_mil(arr)
# Since indexed at 0, take index right before 1 million
return arr[999999]
end
puts find_mil(permute(arr)) | true |
fac4a5566e2b6b385e25d374a1c773f6090bdd0b | Ruby | jsvd/test-repo | /update_pr.rb | UTF-8 | 1,920 | 2.921875 | 3 | [
"Apache-2.0"
] | permissive | require 'json'
def find_gemspec_version
gemspec_path = Dir.glob("*.gemspec").first
spec = Gem::Specification::load(gemspec_path)
spec.version.to_s
end
def compute_next_version(version, bump_type)
major, minor, patch = version.segments
case bump_type
when "major"; major = major.to_i.succ.to_s; minor = patch = "0"
when "minor"; minor = minor.to_i.succ.to_s; patch = "0"
when "patch"; patch = patch.to_i.succ.to_s
end
Gem::Version.new([major, minor, patch].join("."))
end
def bump_gemspec_version!(current_version, next_version)
gemspec_path = if File.exist?("VERSION")
"VERSION"
elsif File.exist?("version")
"version"
else
Dir.glob("*.gemspec").first
end
source = IO.read(gemspec_path)
source.gsub!(current_version.to_s, next_version.to_s)
IO.write(gemspec_path, source)
end
def edit_changelog!(next_version)
source = IO.read("CHANGELOG.md")
IO.write("CHANGELOG.md", "## #{next_version.to_s}\n - TODO\n\n#{source}")
end
BUMP_MESSAGE_REGEX = /^bump\s+(?<bump_type>(?:major|minor|patch))$/
`git config --local user.email "$(git log --format='%ae' HEAD)"`
`git config --local user.name "$(git log --format='%an' HEAD)"`
event = JSON.parse(File.read(ENV['GITHUB_EVENT_PATH']))
event_name = ENV['GITHUB_EVENT_NAME']
body = event["comment"]["body"]
match = body.match(BUMP_MESSAGE_REGEX)
if match.nil?
$stderr.puts "❌ The bump argument must be either \"major\", \"minor\", or \"patch\""
exit(1)
end
bump_type = match["bump_type"]
gemspec_version = Gem::Version.new(find_gemspec_version())
puts "Current gemspec version in the gemspec is: #{gemspec_version}"
next_version = compute_next_version(gemspec_version, bump_type)
puts "next version is #{next_version}"
bump_gemspec_version!(gemspec_version, next_version)
gemspec_path = Dir.glob("*.gemspec").first
edit_changelog!(next_version)
`git commit -a -m "bump to #{next_version}"`
puts "✅ All done!" | true |
8c161bf4d5f28772ae70895bd479f767bf4426e2 | Ruby | riverans/videocache-ruby | /lib/ext.rb | UTF-8 | 220 | 2.53125 | 3 | [
"MIT"
] | permissive | #
# (C) Copyright Kulbir Saini <saini@saini.co.in>
# Product Website : http://cachevideos.com/
#
class NilClass
def integer?
false
end
end
class String
def integer?
!!(self =~ /\A(0(?![0-9]+)|[1-9]+[0-9]*)\Z/)
end
end
| true |
fdfff56b8d42ce30b109998ebd260b9a0a8ff056 | Ruby | rafaelfranca/chatstats | /app.rb | UTF-8 | 573 | 2.6875 | 3 | [] | no_license | require 'sinatra'
require 'json'
get '/:app/:name' do
users = {}
log = File.open("#{params[:name]}.txt", "rb").read
log.gsub!(/\r\n?/, "\n")
log.each_line do |line|
chat = line.split(":")
username = chat[0].force_encoding('utf-8')
if params[:app] == "whatsapp"
if /(\d{2}\/\d{2}\/\d{2}\s\d{2}:\d{2}:\s).*$/ =~ line
username = chat[2].force_encoding('utf-8')
else
next
end
end
if !users.include?(username)
users[username] = 0
end
users[username] += 1
end
# show hash
users.to_json
end | true |
f7b65853f7b413098e14af3e44634b9eb6955fe0 | Ruby | jeffcwolf/booktoread | /app/controllers/static_pages_controller.rb | UTF-8 | 4,095 | 2.765625 | 3 | [] | no_license | require 'open-uri'
require 'json'
class StaticPagesController < ApplicationController
def home
#Obtain book list names for subsequent use in API requests
@listnames_url = "http://api.nytimes.com/svc/books/v3/lists/names.json?api-key=#{NYT_BOOKSAPI_KEY}"
@raw_results_list = open(@listnames_url).read
@parsed_results_list = JSON.parse(@raw_results_list)
@listnames_full = @parsed_results_list["results"]
#Take full list and iterate through only the list names in each array
#Save those names in a new array
@listnames = []
@listnames_full.each do |list|
@listnames.push(list["list_name"])
end
#Create a sub-list of all the less common genres and save them here
#Create a sub-list of all the most common genres and save them here
#Replace spaces with hyphens and downcase (e.g. hardcover-fiction)
#to obtain URL-ready list names
@listnames_URL_ready = []
@listnames.each do |list_item|
@listnames_URL_ready.push(list_item.downcase.gsub(/\s/, '-'))
end
#Implement the API request for the list of Best Sellers by Genre
@booksapi_url = "http://api.nytimes.com/svc/books/v3/lists/#{@listnames_URL_ready[3]}.json?api-key=#{NYT_BOOKSAPI_KEY}"
@raw_results = open(@booksapi_url).read
@parsed_results = JSON.parse(@raw_results)
# @fiction_overview = @parsed_results["results"]["lists"][0]
# @nonfiction_overview = @parsed_results["results"]["lists"][1]
# @hardfiction_overview = @parsed_results["results"]["lists"][2]
# @hardnonfiction_overview = @parsed_results["results"]["lists"][3]
# @paperfiction_overview = @parsed_results["results"]["lists"][4]
# @massfiction_overview = @parsed_results["results"]["lists"][5]
# @papernonfiction_overview = @parsed_results["results"]["lists"][6]
# @efiction_overview = @parsed_results["results"]["lists"][7]
# @enonfiction_overview = @parsed_results["results"]["lists"][8]
# @advicehowto_overview = @parsed_results["results"]["lists"][9]
# @picturebooks_overview = @parsed_results["results"]["lists"][10]
# @childrenmiddlegrade_overview = @parsed_results["results"]["lists"][11]
# @youngadult_overview = @parsed_results["results"]["lists"][12]
# @childrenseries_overview = @parsed_results["results"]["lists"][13]
# @hardgraphics_overview = @parsed_results["results"]["lists"][14]
# @papergraphics_overview = @parsed_results["results"]["lists"][15]
# @manga_overview = @parsed_results["results"]["lists"][16]
# @animals_overview = @parsed_results["results"]["lists"][17]
# @business_overview = @parsed_results["results"]["lists"][18]
# @celebrities_overview = @parsed_results["results"]["lists"][19]
# @crimepunishment_overview = @parsed_results["results"]["lists"][20]
# @culture_overview = @parsed_results["results"]["lists"][21]
# @education_overview = @parsed_results["results"]["lists"][22]
# @espionage_overview = @parsed_results["results"]["lists"][23]
# @disastersadventures_overview = @parsed_results["results"]["lists"][24]
# @family_overview = @parsed_results["results"]["lists"][25]
# @fashionmanners_overview = @parsed_results["results"]["lists"][26]
# @foodfitness_overview = @parsed_results["results"]["lists"][27]
# @games_overview = @parsed_results["results"]["lists"][28]
# @health_overview = @parsed_results["results"]["lists"][29]
# @humor_overview = @parsed_results["results"]["lists"][30]
# @indigenous_overview = @parsed_results["results"]["lists"][31]
# @hardpolitical_overview = @parsed_results["results"]["lists"][32]
# @race_overview = @parsed_results["results"]["lists"][33]
# @relationships_overview = @parsed_results["results"]["lists"][34]
# @religion_overview = @parsed_results["results"]["lists"][35]
# @science_overview = @parsed_results["results"]["lists"][36]
# @sports_overview = @parsed_results["results"]["lists"][37]
# Travel Lists & Methods
@travel_overview = @parsed_results["results"]["books"]
end
def help
end
def about
end
end
| true |
809495c4988df342f789ed3fac35b4317a2f0558 | Ruby | chinchifou/Condingame_Geometry | /tests.rb | UTF-8 | 1,272 | 2.890625 | 3 | [
"MIT"
] | permissive | require 'minitest/autorun'
require_relative 'module_Geometry.rb'
include Geometry
class TestGeometry < Minitest::Test
# GENERAL TEST PATTERN
# test individual constructor
# normal value
# unexpected value
# impossible value
# test individiual modifiers
# test interactions
def test_solve_poly
assert_equal( [1/3.0, 1/2.0], solve_poly_2(36,-30,6) )
refute_equal( [5, 8], solve_poly_2(36,-30,6) )
end
def test_point
point_1 = Point.new(2,3)
assert_equal(2, point_1.x)
assert_equal(3, point_1.y)
assert_equal("(x : 2, y : 3)", point_1.inspect)
point_2 = Point.new(-2,1.5)
assert_equal(-2, point_2.x)
assert_equal(1.5, point_2.y)
assert_equal("(x : -2, y : 1.5)", point_2.inspect)
#TO DO impossible values
refute_equal(point_1, point_2)
assert_equal(Math.sqrt( (2+2)*(2+2) + (3-1.5)*(3-1.5) ), point_1.dist(point_2) )
point_3 = Point.new(2.0, 3.000)
assert_equal(point_1, point_3)
point_0 = Point.new(0,0)
point_4 = point_1.rotate(point_0,-90)
assert_equal(point_4, Point.new(3,-2))
point_5 = point_1.rotate(point_0,-180)
assert_equal(point_5, Point.new(-2,-3))
end
def test_vector
end
def test_line
end
def test_circle
end
end | true |
d54919229f59924f34da70e3bff62deb122dbf4a | Ruby | zandelisenekal/terminal_app_plant_pet | /src/new_game.rb | UTF-8 | 1,152 | 3.59375 | 4 | [] | no_license | require_relative "simulation_game.rb"
require 'tty-font'
require 'colorize'
font = TTY::Font.new(:doom)
puts font.write("Welcome!").colorize(:green)
# prints Welcome message to screen using gem when game starts
if ARGV[0] == "p"
# type 'p' in command line for a preview of your plant
puts "
{o}{o}{o}
| | |
\|/\|/\|/
[~~~~~~~~~]
|~~~~~~~|
|_______|
"
elsif ARGV.length == 2
daisie = Plant_pet.new(ARGV[0].to_i, ARGV[1].to_i)
daisie.new_game()
# will create the plant with the input given in the command line as water and growth levels
else
puts "Do you want to start a new game? (y)es or (n)o"
reply = gets.strip.downcase
# if no input was given in command line this runs
if reply == "y"
system("clear")
daisie = Plant_pet.new(1,1)
daisie.new_game()
# creates a Plant pet called daisie and calls new_game method which starts new game
# sets water_level and growth_level to 1 each
elsif reply == "n"
system "clear"
puts "Sorry to see you go, good bye."
else
puts "Invalid selection. Please try again. Type (y) to start a new game or (n) to exit."
end
end
| true |
19c1bd0ffd000d893bf4cb85dda0af87333914bf | Ruby | RanjunSingh/WeatherScraper | /Hello.rb | UTF-8 | 854 | 4.0625 | 4 | [] | no_license |
# basic output
puts "-----------------Output----------------"
puts "Hello World"
# basic input
puts "\n-----------------Input----------------"
puts "Input a number"
input = gets
puts "This was your number: " + input
# basic loop
puts "\n-----------------Iteration----------------"
puts "regular for, like python"
for i in 1..5 do
puts i
end
puts "alternate loop, for each"
# same as
(1..5).each { |i|
puts i
}
choice = 1
puts "\n-----------------Iteration - Until Loop----------------"
until choice == 0 do
puts "please input - (0 to quit)"
choice = gets.to_i
end
# branching
puts "\n-----------------Branching----------------"
puts "please enter a number"
input = gets.to_i
if input < 0
puts "input was negative"
elsif input == 0
puts "input was 0"
else
puts "input was positive"
end
=begin
This is embedded documentation.
=end
| true |
b79512a53442ebd796e29e9fb9b6a25d28a424bd | Ruby | saloni1911/warm-up-exercises | /26.6.17 - starbucks coffee/coffee.rb | UTF-8 | 4,244 | 4.09375 | 4 | [] | no_license | # https://gist.github.com/kasun-maldeni/b38a4bcdb17078f48b5179ff9fc85d21/
# Write a program that holds on to coffee orders.
# c1 = Coffee.new('latte','2 sugars','medium','Darryl')
# Write the .to_s method for this class so when you puts c1 you will have "Darryl's latte, medium, 2 sugars
require 'pry'
class Coffee
@@list = []
attr_accessor :type, :sugars, :size, :name
# class method
def self.all
@@list
end
# what attr_accessor :type does
# def type
# @type
# end
# def type=(value)
# @type = value
# end
def initialize(name, type, sugars, size)
@type = type
@sugars = sugars
@size = size
@name = name
@@list.push self
#same as above line, @@list << self
end
def to_s
puts "#{name}'s #{type}, #{size}, #{sugars} sugars."
end
end
# orders = []
print "What is your order? "
type = gets.chomp
print "How many sugars you want? "
sugars = gets.chomp.to_i
print "What size of coffee do you want? "
size = gets.chomp
print "What is your name? "
name = gets.chomp
order = Coffee.new(name, type, sugars, size)
# @@list.push(order)
# order.name = 'saloni'
# orders.push(order)
print order.to_s
# puts order
# @@list.push(order)
# binding.pry
print Coffee.all
# binding.pry
# Ruby Solution
# require 'pry'
# class Coffee
# # Class method to keep track of all coffees
# @@all_coffees = []
# # Cheater way to collect coffee
# attr_accessor :collected
# # Sets up the new coffee with arguments passed in
# def initialize(coffee, sugars, size, name)
# # Sets the new object's name to the misspelled version
# @name = misspell(name)
# @coffee = coffee
# # Makes sure the sugar number is an integer
# @sugars = sugars.to_i
# @size = size
# # Sets the order time to the creation date
# @ordered_at = Time.now
# # Sets the wait time to a random time between 2 and 5 mins in seconds
# @wait_time = (160..300).to_a.sample
# # Initializes the object as not collected
# @collected = false
# # Puts this coffee inside the class variable.
# # self here refers to the new object.
# @@all_coffees << self
# end
# # Method to check if coffee is ready
# def ready?
# # Checks if the time that ready? is called is passed the order time + wait time
# if Time.now > @ordered_at + @wait_time
# # Yells the order to collect
# puts "#{@coffee} for #{@name}???".upcase
# # Still returns true
# true
# else
# # Else returns false
# false
# end
# end
# # Class method to be able to call Coffee.collected_list
# # This makes more sense to call it on the class rather than the single coffee object
# # self here refers to the class, not the object
# def self.collected_list
# @@all_coffees.select {|coffee| coffee.collected == true}
# end
# def self.not_collected_list
# @@all_coffees.select {|coffee| coffee.collected == false}
# end
# # to_s method for human readble output to puts the object later
# def to_s
# "#{@name}'s #{@coffee}, #{@size}, #{@sugars} sugars."
# end
# # private means these methods will only be able to be used inside
# private
# def misspell(name)
# name.gsub(/[aeiouy]/, %w(a e i o u y).sample)
# # name.gsub(/^[aeiouy]/, %w(b c d f g h j k l m n p q r s t v w x y z).sample)
# end
# end
# c1 = Coffee.new('latte','2 sugars','medium','Darryl')
# c2 = Coffee.new('flat white', 'no sugar', 'large', 'Mary-Louise')
# c3 = Coffee.new('short black', 'no sugar', 'short', 'Matt')
# # p c1
# puts c1
# puts c2
# puts c3
# binding.pry
# JS Solution
# function Coffee(type, sugars, size, name) {
# this.type = type;
# this.sugars = sugars;
# this.size = size;
# this.name = name;
# this.ready = false;
# this.startMakingMyCoffee();
# }
# Coffee.prototype.printOrder = function() {
# console.log(this.name + '\'s ' + this.type + ', ' + this.size + ', ' + this.sugars + ' sugars.');
# };
# Coffee.prototype.startMakingMyCoffee = function() {
# that = this;
# setTimeout(function() {
# console.log(that.name + '\'s coffee is ready!');
# that.ready = true;
# }, 10000);
# };
# //testing it
# // h = new Coffee('latte', '2', 'medium', 'Harry');
# // h.printOrder();
| true |
ffafe9390d402f97f602d6cd7c4bf69767832739 | Ruby | crossmann/ruby-example | /Inheritance.rb | UTF-8 | 243 | 3.8125 | 4 | [] | no_license | # Sample example with inheritance of a class
class ParentClass
def sayHello
puts "Say hello from: #{self}"
end
end
p_inst = ParentClass.new
p_inst.sayHello
class ChildClass < ParentClass
end
c_inst = ChildClass.new
c_inst.sayHello
| true |
30eb792bd8444cde90c5624207a8f1ddbed1595f | Ruby | michael-sd/Ruby_Programs | /alcohol.rb | UTF-8 | 254 | 3.953125 | 4 | [] | no_license | def human_age(age)
if age < 21
return "You are not legally allowed to buy alcohol in the US"
else
return "You are legally allowed to buy alcohol in the US"
end
end
puts "What is your age?"
age = gets.chomp.to_f
puts human_age(age) | true |
a23b49094d2279431e1fde5027c4ac8577bdefdb | Ruby | func-i/painsquad | /app/services/pain_severity_service.rb | UTF-8 | 668 | 2.5625 | 3 | [] | no_license | class PainSeverityService
def self.analyze(submission)
new(submission).perform
end
def initialize(submission)
@submission = submission
end
def perform
set_pain_severity
end
private
def set_pain_severity
pain_severity = if @submission.current_pain_answer.value > 30
# => Notify the user 1 hour from now asking to follow up with the pain
Delayed::Job.enqueue(Workers::UserNotifier.new(@submission.user.id, "Hey recruit. You reported pain an hour ago. Tell us how you are doing now!"), run_at: 1.hour.from_now)
:moderate
else
:mild
end
@submission.update(pain_severity: pain_severity)
end
end
| true |
031b73be53b70b91e71adef80d834eaafd2e75a1 | Ruby | Stella-Nthenya/Ruby-Object-Oriented-Programming-Exercises | /120_oop_exercises/easy_1/refactoring_vehicles.rb | UTF-8 | 1,084 | 3.671875 | 4 | [] | no_license | # Consider the following classes:
class Vehicle
attr_reader :make, :model
def initialize(make, model) # can take additional parameter wheels here
@make = make
@model = model
# @wheels = wheels
end
def to_s
"#{make} #{model}"
end
end
class Car < Vehicle
# def initialize(make, model)
# super(make, model, 4)
# end
def wheels
4
end
end
class Motorcycle < Vehicle
def wheels
2
end
# def initialize(make, model)
# super(make, model, 2)
# end
end
class Truck < Vehicle
attr_reader :payload
def initialize(make, model, payload)
super(make, model) # super(make, model, 6)
@payload = payload
end
def wheels
6
end
end
# Refactor these classes so they all use a common superclass, and inherit behavior as needed.
# Would it make sense to define a wheels method in Vehicle even though all of the remaining classes would be overriding it? Why or why not? If you think it does make sense, what method body would you write?
# It is a good idea to include a @wheels instance variable within the Vehicles class. | true |
f0c77831d365ab93336cc429018ccdee54350992 | Ruby | juliannatetreault/ttt-10-current-player-bootcamp-prep-000 | /lib/current_player.rb | UTF-8 | 230 | 3.390625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def turn_count(board)
counter = 0
board.each do |character|
if character == "X" || character == "O"
counter += 1
end
end
counter
end
def current_player(board)
if turn_count(board) % 2 == 0
"X"
else
"O"
end
end | true |
3d8a9cea96e38e52c35f1b3a4b3d770b0151c746 | Ruby | benmerkel/lrthw | /chapter_3/ex3.rb | UTF-8 | 1,264 | 4.46875 | 4 | [] | no_license | # Several strings within don't use any interpolation so only
# single quotes were necessary.
# Outputs a string
puts 'I will now count my chickens:'
# This is dividing 30 by 6 and then adding 25
puts 'Hens', 25 + 30 / 6
# This is multiplying 25 by 3, then remainder of 75/4
# and subtracting that from 100
puts 'Roosters', 100 - 25 * 3 % 4
# Outputs a string
puts 'now I will count the eggs:'
# Gets remainder of 4/2 (which is zero) and integer of
# 1/4 (also zero) and the add/subtracts the rest of the numbers
puts 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# Outputs a string
puts 'Is it true that 3 + 2 < 5 - 7?'
# checks to see if 3+2 is less than 5-7.
# 5 is not less than -2 so it returns false.
puts 3 + 2 < 5 - 7
# Outputs a string and the sum of 3 + 2 on the next line
puts 'What is 3 + 2?', 3 + 2
# Outputs a string and the difference between 5 and 7 on the next line
puts 'What is 5 - 7?', 5 - 7
# Outputs a string
puts "Oh, that's why it's false."
# Outputs a string
puts 'how about some more.'
# Outputs a string with a true/false evaluation
puts 'Is it greater?', 5 > -2
# Outputs a string with a true/false evaluation
puts 'Is it greater or equal?', 5 >= -2
# Outputs a string with a true/false evaluation
puts 'Is it less or equal?', 5 <= -2
| true |
7040e49dd792f3ca650b99abaf745f2a6c5bdd25 | Ruby | Knolle-03/PT17 | /file_utils.rb | UTF-8 | 419 | 3.21875 | 3 | [] | no_license | class MyFileError < IOError; end
# rth
module FileUtils
def self.count_characters(filename)
raise MyFileError, "#{filename} is not valid" unless File.readable?(filename)
text = File.read(filename).delete(' ').split('')
hash = {}
text.each do |v|
hash[v] = 0 if hash[v].nil?
hash[v] += 1
end
hash
end
end
puts FileUtils.count_characters('data/gruselett.txt')
| true |
7129d5edc22b7b9a2ad66a634c95b09979b773e1 | Ruby | azhi/BSUIR_labs | /7sem/CSN/lab2/chat_serv_udp.rb | UTF-8 | 826 | 2.625 | 3 | [] | no_license | require 'socket'
require 'pry'
socket = Socket.new(:INET, :DGRAM)
local_adr = Addrinfo.udp("127.0.0.1", 2222)
@clients = []
@threads = []
socket.bind(local_adr)
begin
loop {
msg, client_adr = socket.recvfrom(255)
if msg.start_with?("REGISTER")
p new_client = {name: msg.sub('REGISTER ', '').chomp, addr: client_adr}
@clients << new_client
else
msg, to, msg = msg.match(/(.*?) (.*)/).to_a
from = @clients.find{ |client| client[:addr].to_s == client_adr.to_s }
to = to == 'ALL' ? @clients.reject{ |client| client[:name] == from[:name] } : @clients.find_all{ |client| client[:name] == to }
to.each do |client|
socket.send "FROM: #{from[:name]}\n" + msg, 0, client[:addr]
end
end
}
rescue SignalException
puts 'Got signal. Terminating.'
socket.close
end
| true |
dd0fc0b961ce36a20b1c9f26419507397d282de3 | Ruby | pancake-batfish/BankAccounts | /lib/checking_account.rb | UTF-8 | 816 | 3.328125 | 3 | [] | no_license | require_relative 'account'
module Bank
class CheckingAccount < Bank::Account
attr_accessor :checks_used
def initialize(id, balance)
super
reset_checks
end
def withdraw(amount)
@withdrawal_fee = 1
super
end
def withdraw_using_check(amount)
raise ArgumentError.new ("Withdrawal must be >=0") if amount < 0
balance_limit = -10
if @checks_used >= 3
withdrawal_fee = 2
else
withdrawal_fee = 0
end
if @balance - amount - withdrawal_fee < balance_limit
puts "This withdrawal would create a balance below #{balance_limit}."
@balance
else
@checks_used += 1
@balance -= (amount + withdrawal_fee)
end
end
def reset_checks
@checks_used = 0
end
end
end
| true |
84956961a6b945db10e88570530dc18d64dd3531 | Ruby | carlos-m-marques/kithward-api | /lib/tasks/dunno.rake | UTF-8 | 5,456 | 2.625 | 3 | [] | no_license | require 'listing_dictionary'
require 'community_dictionary'
require 'processing'
require 'converter'
require 'scriptster'
desc "Really dunno so far"
task :community_crunch => :environment do
processing = Processing.new(COMMUNITY)
processing.crunch
report = ""
community = Community.find(3770)
report << "Community "
report << "#{community.name} ".red
report << "mappings.\n\n".purple
community.data.each do |c_key, c_value|
report << "\n_________________________________________________\n".green
cd = processing.compiled_data_from_db
report << "#{c_key}: ".blue
report << " #{c_value}\n".red
report << "\n"
report << c_key.purple
report << "\n"
cd[c_key.to_sym].each do |key, value|
unless key == :values
if key == :data_type
report << "\t#{key}: ".blue
report << " #{value} ".red
report << "(#{processing.data_types[value.to_sym]})\n".green
else
report << "\t#{key}: ".blue
report << " #{value}\n".red
end
else
report << "\t#{key}: \n".blue
value.each do |key_value|
report << "\t\t#{key_value.keys[0]}: ".blue
report << " #{key_value.values[0]}\n".red
end
end
end
report << "\n_________________________________________________\n".green
end
puts report
# processing.report
end
task :dictionary_report => :environment do
processing = Processing.new(COMMUNITY)
processing.crunch
processing.report
end
task :report => :environment do
processing = Processing.new(COMMUNITY)
processing.crunch
dd = processing.compiled_data_from_db.map do |k, v|
[k, v] if v[:values]
end.compact.to_h
values = dd.map do |_, data|
data[:values].map(&:values).map(&:last)
end
ap values
end
task :community_simulation => :environment do
processing = Processing.new(COMMUNITY)
processing.crunch
report = ""
community = Community.find(3770)
report << "Community "
report << "#{community.name} ".red
report << "mappings.\n\n".purple
entity = Hash.new { |hash, key| hash[key] = Hash.new { |hash, key| hash[key] = Hash.new { |hash, key| hash[key] = '' } } }
community.data.each do |c_key, c_value|
cd = processing.compiled_data_from_db
next unless (
(cd[c_key.to_sym][:section_label] && !cd[c_key.to_sym][:section_label].is_a?(Array) && cd[c_key.to_sym][:section_label].length > 1) &&
(cd[c_key.to_sym][:group_name] && !cd[c_key.to_sym][:group_name].is_a?(Array) && cd[c_key.to_sym][:group_name].length > 1) &&
(cd[c_key.to_sym][:label] && !cd[c_key.to_sym][:label].is_a?(Array) && cd[c_key.to_sym][:label].length > 1)
)
entity[cd[c_key.to_sym][:section_label]][cd[c_key.to_sym][:group_name].capitalize][cd[c_key.to_sym][:label]] = c_value
end
puts JSON.pretty_generate(entity)
# puts report
# processing.report
end
task :listing_simulation => :environment do
processing = Processing.new(LISTING)
processing.crunch
report = ""
community = Community.find(3770).listings.each do |community|
report << "#{community.name}".red
entity = Hash.new { |hash, key| hash[key] = Hash.new { |hash, key| hash[key] = Hash.new { |hash, key| hash[key] = '' } } }
community.data.each do |c_key, c_value|
cd = processing.compiled_data_from_db
next unless (
(cd[c_key.to_sym][:section_label] && !cd[c_key.to_sym][:section_label].is_a?(Array) && cd[c_key.to_sym][:section_label].length > 1) &&
(cd[c_key.to_sym][:group_name] && !cd[c_key.to_sym][:group_name].is_a?(Array) && cd[c_key.to_sym][:group_name].length > 1) &&
(cd[c_key.to_sym][:label] && !cd[c_key.to_sym][:label].is_a?(Array) && cd[c_key.to_sym][:label].length > 1)
)
entity[cd[c_key.to_sym][:section_label]][cd[c_key.to_sym][:group_name].capitalize][cd[c_key.to_sym][:label]] = c_value
end
puts JSON.pretty_generate(entity)
end
# puts report
# processing.report
end
desc "Really dunno so far"
task :listings_crunch => :environment do
processing = Processing.new(LISTING)
processing.crunch
report = ""
Community.find(3770).listings.to_a[1..-1].each do |listing|
report << "Listing "
report << "#{listing.name} ".red
report << "mappings.\n\n".purple
listing.data.each do |l_key, l_value|
report << "\n_________________________________________________\n".green
cd = processing.compiled_data_from_db
report << "#{l_key}: ".blue
report << " #{l_value}\n".red
report << "\n"
report << l_key.purple
report << "\n"
cd[l_key.to_sym].each do |key, value|
unless key == :values
if key == :data_type
report << "\t#{key}: ".blue
report << " #{value} ".red
report << "(#{processing.data_types[value.to_sym]})\n".green
else
report << "\t#{key}: ".blue
report << " #{value}\n".red
end
else
report << "\t#{key}: \n".blue
value.each do |key_value|
report << "\t\t#{key_value.keys[0]}: ".blue
report << " #{key_value.values[0]}\n".red
end
end
end
report << "\n_________________________________________________\n".green
end
end
puts report
end
desc "Really dunno so far"
task :convert => :environment do
Scriptster.log :info, 'Starting converter...'
converter = Converter.new
converter.convert
end
| true |
46a8f74fb37639602c2069254c6a11fadc185cba | Ruby | cored/munchkins | /lib/munchkins/policies/games/maximum_amount_of_players.rb | UTF-8 | 300 | 2.609375 | 3 | [] | no_license | module Policies
module Games
class MaximumAmountOfPlayers
MAXIMUM_AMOUNT_OF_PLAYERS = 6
def self.validate(game)
if (game.players.count > MAXIMUM_AMOUNT_OF_PLAYERS)
"Maximum amount of players is #{MAXIMUM_AMOUNT_OF_PLAYERS}"
end
end
end
end
end
| true |
6bd11b7941b1b27fd406866961fe15c581a7e3b4 | Ruby | samuraraujo/SondaSerimi | /modules/alignment/DezhaoSong-aligner.rb | UTF-8 | 2,428 | 2.78125 | 3 | [] | no_license | #Key selection implemented at http://disi.unitn.it/~p2p/RelatedWork/Matching/70310640.pdf
#Automatically Generating Data Linkages Using a Domain-Independent Candidate Selection Approach
#Dezhao Song and Jeff Heflin
#Author: Samur Araujo
##########################################################################
class DezhaoSongBasedAligner < XAligner
def assingment(a,b)
a = preparedata(a)
b = preparedata(b)
alignment = []
puts "DEZHAO ALIGNER"
x = dezhao(a)
puts "SELECTED"
puts x
puts "DEZHAO ALIGNER 1"
y = dezhao(b)
puts "SELECTED 1"
puts y
exit
# puts "ALIGNMENT"
# puts alignment
return alignment.compact
end
def dezhao(a)
satisfied=false
alpha=0.7
beta=0.5
scores=Hash.new
keyset = a.map{|s,p,o| p}.uniq
while !satisfied and !keyset.empty?
keyset.each{|key|
disc = discriminability(a,key)
if disc < beta then
keyset.delete(key)
else
cover = coverage(a,key)
fl = (2 * disc * cover).to_f / (disc+cover).to_f
scores[key]=fl
if fl > alpha
satisfied = true
end
end
}
if !satisfied
dis_key = keyset.map{|key| discriminability(a,key)}
puts "dis_key"
puts dis_key
max = dis_key.max
puts max
dis_key = keyset[dis_key.index(max)]
puts "SELECTED"
puts dis_key
keyset.delete(dis_key)
keyset.map!{|x| dis_key.to_s + " " + x.to_s}
# puts "keyset"
# keyset.each{|x| puts "X"
# puts x}
a = update(dis_key,keyset, a)
end
end
# maxk = 0
# k = nil
# scores.keys.each{|key|
# if maxk < scores[key]
# maxk = scores[key]
# k=key
# end
# }
return scores.keys
end
def update(diskey,keyset, a)
b = []
sub = Hash.new
a.each{|s,p,o| sub[s]=o if p == diskey}
return a.map{|s,p,o|
[s, diskey.to_s + " " + p.to_s, sub[s].to_s + o.to_s] if p != diskey
}.compact
end
def discriminability(a,pred)
x = a.map{|s,p,o| o if p == pred}.uniq.compact.size.to_f / a.map{|s,p,o| s if p == pred}.uniq.compact.size.to_f
puts "DISCRIMINABILTY"
puts pred
puts x
return x
end
def coverage(a,pred)
a.map{|s,p,o| s if p == pred}.uniq.compact.size.to_f / a.map{|s,p,o| s }.uniq.compact.size.to_f
end
end
| true |
5edc6127be2e17a01f6360833769cc093bbfe33a | Ruby | mariasoria/ruby_education | /Scripts to learn/scope.rb | UTF-8 | 933 | 4.03125 | 4 | [] | no_license | # Publicos -> Public (por defecto)
# Privados -> Private (únicamente desde dentro de la clase). Clase hija también los hereda
# Protegidos -> Protected (puede llamarse desde otras clases siempre que sean del mismo tipo)
class Humano
def initialize
privado
end
def publico
puts "Soy publico"
end
private # todos los metodos a continuación serán privados
def privado
puts "Soy privado"
end
protected # todos los metodos a continuación serán protegidos
def protegido
puts "Soy protegido"
end
end
class Tutor < Humano
def initialize
@inner = Humano.new
end
def llamar_protegido
@inner.privado
end
end
class Alien
def initialize
end
def llamar_protegido
@inner.privado
end
end
tutor = Tutor.new
alien = Alien.new
puts tutor.is_a?(Humano)
puts alien.is_a?(Humano) | true |
5fa8a956e7b6975c82c91445a83eb6cff6121bfe | Ruby | onemonthweb/ruby-teaching | /3-variable.rb | UTF-8 | 69 | 2.875 | 3 | [] | no_license | a = 14
b = 5
puts a + b
puts a - b
puts a * b
puts a / b
puts a % b
| true |
b8f4b41909d064b9c6d9dcbadf60f965e3475aba | Ruby | bronzdoc/olery_gem | /lib/olery/scraper.rb | UTF-8 | 412 | 3.21875 | 3 | [
"MIT"
] | permissive | module Olery
# <Scraper> Will start scraping for data with the configured resources
class Scraper
attr_reader :word
def initialize(word)
@word = word
end
# Run the scraper
def run
Olery.configuration.resources.each do |resource|
puts "Looking for hotels in #{resource.host} that match the word \"#{@word}\""
resource.scrape @word
end
end
end
end
| true |
bfc2036c462887d4c0b8a619e5331048e392cce7 | Ruby | benjaminb10/Ui-Bibz | /lib/ui_bibz/ui/grid/grid.rb | UTF-8 | 2,765 | 2.984375 | 3 | [
"MIT"
] | permissive | module UiBibz::Ui
# Create a Grid
#
# This element is an extend of UiBibz::Ui::Component.
#
# ==== Attributes
#
# * +content+ - Content of element
# * +options+ - Options of element
# * +html_options+ - Html Options of element
#
# ==== Options
#
# You can add HTML attributes using the +html_options+.
# You can pass arguments in options attribute:
#
# ==== Signatures
#
# UiBibz::Ui::Grid.new().tap do |g|
# ...
# g.view content = nil, options = nil, html_options = nil, &block
# ...
# end
#
# ==== Exemples
#
# UiBibz::Ui::Grid.new().tap do |g|
# g.view num: 5, position: :left do
# 'left'
# end
# g.view position: :right do
# 'right'
# end
# g.view({ position: :top}, { class: 'success'}) do
# 'top'
# end
# g.view position: :center do
# 'center'
# end
# g.view position: :bottom do
# 'bottom'
# end
# end.render
#
class Grid < Component
COL_NUM = 12
def initialize content = nil, options = nil, html_options = nil, &block
super
@views = {}
end
def view content = nil, options = nil, html_options = nil, &block
o = content.kind_of?(Hash) ? content : options
c = UiBibz::Ui::Component.new content, options, html_options, &block
h = Hash[o[:position], { component: c, num: o[:num]}]
@views = @views.merge(h)
end
def render
define_col_nums
UiBibz::Ui::Row.new(class: 'grid') do
# top
concat top_view unless @views[:top].nil?
# left
concat left_view unless @views[:left].nil?
# center
concat center_view unless @views[:center].nil?
# right
concat right_view unless @views[:right].nil?
# bottom
concat bottom_view unless @views[:bottom].nil?
end.render
end
def view_by_num c, num, item_class
UiBibz::Ui::Col.new(c.content, c.options.merge({ num: num }), c.class_and_html_options(['col', item_class])).render
end
def top_view
view_by_num @views[:top][:component], COL_NUM, 'grid-top'
end
def bottom_view
view_by_num @views[:bottom][:component], COL_NUM, 'grid-bottom'
end
def left_view
view_by_num @views[:left][:component], @left_val, 'grid-left'
end
def center_view
view_by_num @views[:center][:component], COL_NUM-@left_val-@right_val, 'grid-center'
end
def right_view
view_by_num @views[:right][:component], @right_val, 'grid-right'
end
def define_col_nums
@left_val = @views[:left].nil? ? 0 : (@views[:left][:num] || 1)
@right_val = @views[:right].nil? ? 0 : (@views[:right][:num] || 1)
end
end
end
| true |
360ea14c9868a7ef34de38b32940847fd64f2d93 | Ruby | sularzyk/smartflix | /app/services/omdb_movie_creator.rb | UTF-8 | 713 | 2.75 | 3 | [] | no_license | # frozen_string_literal: true
require 'httparty'
class OmdbMovieCreator
include HTTParty
def initialize(omdb_response)
@omdb_response = omdb_response
end
def call
omdb_response['Response'] == 'True' ? add_movie_to_the_db : log
end
private
attr_reader :omdb_response
def log
title = omdb_response['Title']
Rails.logger.warn("Movie #{title} does not exist")
end
def add_movie_to_the_db
movie_data = prepare_data_from_api
movie = Movie.new(movie_data.except(:type))
movie.movie_type = movie_data[:type]
movie.save!
end
def prepare_data_from_api
omdb_response.parsed_response.transform_keys(&:underscore).symbolize_keys.except(:response)
end
end
| true |
ba5e90956e0d97b102fa6be29fdaea2e8b2dff49 | Ruby | psbora2/Compeitive-Coding-Problems-Ruby | /problems /stack/sliding-window-maximum.rb | UTF-8 | 965 | 3.8125 | 4 | [] | no_license | # https://leetcode.com/problems/sliding-window-maximum/
def max_sliding_window(nums, k)
result = []
sliding_window = []
nums.each_with_index do |el, index|
sliding_window = insert_in_sliding_window(nums, sliding_window, index, k, el)
if index >= k -1
result << nums[sliding_window.first]
end
end
return result
end
def insert_in_sliding_window(nums, sliding_window, index, k ,el)
if sliding_window.first && sliding_window.first <= index - k
sliding_window.delete_at(0)
end
if sliding_window.first == nil
sliding_window = [index]
elsif nums[sliding_window.first] <= el
sliding_window = [index]
elsif nums[sliding_window.first] > el
while sliding_window.last && nums[sliding_window.last] <= el
sliding_window.pop
end
sliding_window << index
end
return sliding_window
end
max_sliding_window([1,3,1,2,0,5], 3) | true |
a1cc5b142690ce3d3b0257a532dd311aa4351000 | Ruby | ottaviana/learnrubythehardway | /ex3_1.rb | UTF-8 | 121 | 3.40625 | 3 | [] | no_license | puts "Is it true that #{2 > 3} ?"
puts "Is it true that 2 is greater than 3? #{2 > 3}"
puts 20.3 - 10.5 / 3 + 6.4 - 0.45
| true |
750882a01473e3096763cd304f540dabece9a438 | Ruby | sblausten/learn-to-program | /10.3_shuffle.rb | UTF-8 | 495 | 4.09375 | 4 | [] | no_license | =begin
10.3
Shuffle. Now that you’ve finished your new sorting algorithm, how about
the opposite? Write a shuffle method that takes an array and returns a totally
shuffled version. As always, you’ll want to test it, but testing this
one is trickier: How can you test to make sure you are getting a perfect
shuffle? What would you even say a perfect shuffle would be? Now test
for it.
=end
def shuffle array
arr.sort_by{rand}
end
puts(shuffle(%w[1 2 3 4 5 6 7 8 9 10]))
| true |
a539f4a0afc6e90d7f78ff77ab8ce1b1a9ce9580 | Ruby | Zero-jp/Test_journal | /app.rb | UTF-8 | 2,608 | 2.640625 | 3 | [] | no_license | # frozen_string_literal: true
require 'forme'
require 'roda'
# Connecting all files in the "models" directory
require_relative 'models'
# Core class
class App < Roda
# Specifying the path to the root of the application
opts[:root] = __dir__ # Here it is write that the root of the app is that file
# Allows you to customize the application depending on the environment in which it was launched
plugin :environments
plugin :forme
plugin :render
# Development environment only
configure :development do
# Serving static files
plugin :public
opts[:serve_static] = true
end
# Storage of all test information
opts[:tests] = TestList.new([
Test.new('Лабораторная работа №1', '2020-04-05', 'Проверка знаний по языку Ruby'),
Test.new('Лабораторная работа №2', '2020-04-20', 'Проверка умения написать приложение на языке Ruby'),
Test.new('Финальный экзамен', '2020-06-20', 'Проверка всех знаний и умений')
])
route do |r|
# All requests would be processed
r.public if opts[:serve_static]
r.root do
'Hello, World!'
end
r.on 'tests' do
# @some_tests = [1, 2, 15]
# Displaying the page template inside the layout
# locals - sending data to the template
# view('tests', locals: { data: 'Данные из контроллера' })
# Adressing dyrectly to 'tests'
r.is do
@params = DryResultFormeAdapter.new(TestFilterFormSchema.call(r.params))
# Add filter
@filtered_tests = if @params.success?
opts[:tests].filter(@params[:date], @params[:description])
else
opts[:tests].all_tests
end
view('tests')
end
# Adressing to 'tests/new'
r.on 'new' do
r.get do
@params = {}
view('new_test')
end
r.post do
@params = DryResultFormeAdapter.new(NewTestForSchema.call(r.params))
if @params.success?
# Adding new test
opts[:tests].add_test(Test.new(@params[:name], @params[:date], @params[:description]))
r.redirect '/tests'
else
view('new_test')
end
end
end
end
end
end
| true |
7311cb9f607251ccce6428f6e398ae9c651ae12c | Ruby | PabloEPP/estructuras_de_control | /1_1_2.rb | UTF-8 | 145 | 3.34375 | 3 | [] | no_license | #Modifica el valor asignado a la variable 'a' para que se cumpla la condición.
a = 5
if a == 5
puts 'La condición es verdadera.'
end
| true |
bcade581b46b3a2a28387a4c060a7a01ff1a56e3 | Ruby | rafaeldl/Mithra | /core/gerador.rb | UTF-8 | 2,407 | 3.265625 | 3 | [] | no_license | require 'yaml'
def gera_individuo(turma)
individuo = []
5.times do |dia|
individuo[dia] = []
4.times do |periodo|
individuo[dia][periodo] = @disciplinas.sample
end
end
acertos = calcula_acertos(individuo, turma)
individuo = {individuo: individuo, acertos: acertos, turma: turma}
@melhor_individuo = individuo if @melhor_individuo.nil? || acertos > @melhor_individuo[:acertos]
individuo
end
def calcula_acertos(individuo, turma)
acerto = 0
disciplinas_quantidade = {}
5.times do |dia|
4.times do |periodo|
disciplinas_quantidade[individuo[dia][periodo]] = (disciplinas_quantidade[individuo[dia][periodo]] || 0) + 1
end
end
disciplinas_quantidade.each do |disciplina, quantidade|
acerto += 1 if quantidade == @turmas[turma][disciplina]
end
acerto
end
def cruzamento(x, y)
individuo = []
5.times do |dia|
individuo[dia] = []
4.times do |periodo|
individuo[dia][periodo] = if rand(1) == 1 then x[:individuo][dia][periodo] else y[:individuo][dia][periodo] end
end
end
acertos = calcula_acertos(individuo, x[:turma])
individuo = {individuo: individuo, acertos: acertos, turma: x[:turma]}
@melhor_individuo = individuo if @melhor_individuo.nil? || (acertos > @melhor_individuo[:acertos])
individuo
end
def nova_geracao(geracao)
nova_geracao = []
if geracao.empty?
# Primeira geracao
@turmas.each do |turma, disciplinas|
5000.times do
nova_geracao << gera_individuo(turma)
end
end
else
quantidade = geracao.size + rand(50)
quantidade.times do
nova_geracao << cruzamento(geracao.sample, geracao.sample)
end
end
nova_geracao
end
@turmas = YAML.load_file('modelos/turmas.yml')
@disciplinas = YAML.load_file('modelos/disciplinas.yml')
@individuos = []
@metas = {}
@melhor_individuo
geracao = []
# Calcula o valor maximo de acertos
@turmas.each do |turma, disciplinas|
disciplinas.each do |disciplina, quantidade|
@metas[turma] = (@metas[turma] || 0) + quantidade
end
end
@individuos << geracao
melhor_individuo = nil
10.times do |i|
geracao = nova_geracao(geracao)
puts "Geracao #{i} - tamanho #{geracao.size} - melhor #{@melhor_individuo[:acertos]}"
@individuos << geracao
break if @melhor_individuo && (@melhor_individuo[:acertos] == @metas[@melhor_individuo[:turma]])
end
puts @melhor_individuo[:acertos]
puts @melhor_individuo
| true |
5e51defdbd5459607ed2cfbd95975dd25c97faf9 | Ruby | mjsivertsen/doc_apppointment_scheduler | /app/models/appointment.rb | UTF-8 | 864 | 2.734375 | 3 | [] | no_license | class Appointment < ApplicationRecord
belongs_to :patient
belongs_to :doctor
# wanted to make the date and time not stupid and ugly but having a hard time figuring it out
# def convert_time(datetime)
# time = Time.parse(datetime).in_time_zone("Pacific Time (US & Canada)")
# time.strftime("%-d/%-m/%y: %H:%M %Z")
# end
# <%= link_to convert_time(timeslot.opening), [@place, timeslot] %>
# d = DateTime.new(2007,11,19,8,37,48,"-06:00")
# #=> #<DateTime: 2007-11-19T08:37:48-0600 ...>
# d.strftime("Printed on %m/%d/%Y") #=> "Printed on 11/19/2007"
# d.strftime("at %I:%M%p") #=> "at 08:37AM"
def self.plus
appointments = Appointment.all
appointments.map do |appointment|
{id: appointment.id, datetime: appointment.datetime, patient: appointment.patient, doctor: appointment.doctor}
end
end
end
| true |
6b397bceed813dbeda1e583e3c638167294a2c7c | Ruby | liviaishak/NutriLoop | /app/models/user.rb | UTF-8 | 1,825 | 2.5625 | 3 | [] | no_license | class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :fname, :lname, :age, :gender, :height, :weight, :physical_activity, presence: true
def total_cal
formula_female = (((weight * 4.35) + (height * 4.7)) - (age * 4.7)) + 655
formula_male = (((weight * 6.23) + (height * 12.7)) - (age * 6.8)) + 66
if gender == "female" && physical_activity == "none"
@total_cal = (formula_female * 1.2).to_d
elsif gender == "female" && physical_activity == "light"
@total_cal = (formula_female * 1.375).to_d
elsif gender == "female" && physical_activity == "moderate"
@total_cal = (formula_female * 1.55).to_d
elsif gender == "female" && physical_activity == "active"
@total_cal = (formula_female * 1.725).to_d
elsif gender == "male" && physical_activity == "none"
@total_cal = (formula_male * 1.2).to_d
elsif gender == "male" && physical_activity == "light"
@total_cal = (formula_male * 1.375).to_d
elsif gender == "male" && physical_activity == "moderate"
@total_cal = (formula_male * 1.55).to_d
else gender == "male" && physical_activity == "active"
@total_cal = (formula_male * 1.725).to_d
end
@total_cal
end
def total_carbs
tot_carb = @total_cal * 0.5
self.update_attributes(:carb => tot_carb)
carb
end
def total_proteins
tot_prot = @total_cal * 0.2
self.update_attributes(:protein => tot_prot)
protein
end
def total_fats
tot_fat = @total_cal * 0.3
self.update_attributes(:fat => tot_fat)
fat
end
end
| true |
5a5038c293b374d978e23fee95e55175b6dfb041 | Ruby | s11rikuya/ruby-perfect-lesson | /5-5-3-3.rb | UTF-8 | 156 | 2.9375 | 3 | [] | no_license |
hash = {foo: 1, bar: 2, baz: 3}
hash.select! {|key, val| val.odd?}
p hash
hash = {foo: 1, bar: 2, baz: 3}
hash.reject! {|key, val| val.odd?}
p hash
| true |
50e8721df3b1a1861642396db7721a250f52e2b9 | Ruby | augheywashu/gitish | /blobstore.rb | UTF-8 | 1,561 | 2.796875 | 3 | [
"BSD-3-Clause"
] | permissive | require 'gdbm'
require 'digest/sha1'
require 'fileutils'
class BlobStore
def initialize(store,options)
@storedir = options['storedir'] || raise("BlobStore: storedir option not defined")
FileUtils::mkdir_p(@storedir)
@store = store
@blobs = GDBM.new(File.join(@storedir,"blobs.db"),0666,options['readonly'] ? GDBM::READER : (GDBM::WRCREAT | GDBM::SYNC))
@flatdb = File.open(File.join(@storedir,"blobs.txt"),"a+") unless options['readonly']
@datasize = 0
end
def stats
["BlobStore: wrote #{@datasize.commaize} bytes to the store"]
end
def sync
@flatdb.fsync
@blobs.sync
@store.sync
end
def close
@blobs.close
@store.close
end
def has_shas?(shas, skip_cache)
for s in shas
if not @blobs.has_key?(s)
return false
end
end
return true
end
def write_commit(sha,message)
verify_shas!([sha])
File.open(File.join(@storedir,"commits"),'a+') do |f|
f.puts "#{sha} - #{message}"
end
end
def read_sha(sha)
@store.read(@blobs[sha])
end
def write(data,sha)
raise "BlobStore: write should not be asked to write data it already has #{sha}." if @blobs.has_key?(sha)
@datasize += data.size
storekey = @store.write(data)
@blobs[sha] = storekey.to_s
@flatdb.flock File::LOCK_EX
@flatdb.puts "#{sha} #{storekey.to_s}"
@flatdb.sync
@flatdb.flock File::LOCK_UN
sha
end
protected
def verify_shas!(shas)
raise "Could not find #{sha} in blobstore" unless self.has_shas?(shas,:bypass_cache)
end
end
| true |
32bc2f36d104c7fcec9a2079b962ebcff348123d | Ruby | EricMbouwe/Enumerables | /enumerable.rb | UTF-8 | 2,412 | 3.25 | 3 | [
"MIT"
] | permissive | module Enumerable
def my_each
return to_enum(__method__) unless block_given?
i = 0
while i < size
yield(to_a[i])
i += 1
end
self
end
def my_each_with_index
return to_enum(__method__) unless block_given?
i = 0
while i < size
yield(to_a[i], i)
i += 1
end
self
end
def my_select
return to_enum(__method__) unless block_given?
result = []
my_each do |item|
result << item if yield(item)
end
result
end
def my_all?(param = nil)
result = true
my_each do |value|
if block_given?
result = false unless yield(value)
elsif param.nil?
result = false unless value
else
result = false unless param === value
end
end
result
end
def my_any?(param = nil)
result = false
my_each do |value|
if block_given?
result = true if yield(value)
elsif param.nil?
result = true if value
elsif param === value
result = true
end
end
result
end
def my_none?(param = nil)
result = true
my_each do |value|
if block_given?
result = false if yield(value)
elsif param.nil?
result = false if value
elsif param === value
result = false
end
end
result
end
def my_count(param = nil)
count = 0
my_each do |item|
if param
count += 1 if item == param
elsif block_given?
count += 1 if yield(item)
else
count = length
end
end
count
end
def my_map(param = nil)
return to_enum(__method__) unless block_given?
arr = []
my_each do |item|
if param
a = param.call(item)
block_given? ? arr << a : arr
else
arr << yield(item)
end
end
arr
end
def my_inject(param1 = nil, param2 = nil)
if block_given?
my_each do |item|
param1 = param1.nil? ? to_a[0] : yield(param1, item)
end
param1
elsif param1
i = param2.nil? ? 1 : 0
accumulator = param2.nil? ? to_a[0] : param1
operator = param2.nil? ? param1 : param2
while i < size
accumulator = to_a[i].send(operator, accumulator)
i += 1
end
accumulator
else
to_enum(__method__)
end
end
end
# implementation of my_inject
def multiply_els(arr)
arr.my_inject('*')
end
| true |
fed3d7de00b39ae0b248797bf070cdc8f549298a | Ruby | Slothkrew/Napper | /app/models/nap.rb | UTF-8 | 433 | 2.5625 | 3 | [] | no_license | require 'data_mapper'
class Nap
include DataMapper::Resource
property :id, Serial
property :body, String, :required => true
property :author, String, :required => true
property :posted, DateTime
def posted_date
if posted
if DateTime.now.to_s.include? Date.today.to_s
posted.strftime("%T")
else
posted.strftime("%T %d/%m/%Y")
end
else
"In the past"
end
end
end | true |
babcb25aadf3ed21b8790eb71118eb745b73f25b | Ruby | jazziining/Ruby_Fundamentals2 | /exercise5.rb | UTF-8 | 249 | 4.125 | 4 | [] | no_license | #Methods
#Converts Fah to Cel
temp_fahrenheit = gets.to_i
def converts ( temp_fahrenheit )
temp_celsius = ( temp_fahrenheit - 32 ) * 5 / 9
puts "#{temp_fahrenheit} Fahrenheit equals to #{temp_celsius} celsius"
end
converts ( temp_fahrenheit )
| true |
c3a9c6a8a1595c65edd7b59b478ba63d89430323 | Ruby | jdunwoody/image_batch_processor | /spec/lib/models/camera_make_spec.rb | UTF-8 | 952 | 2.640625 | 3 | [] | no_license |
require './lib/models/camera_make'
module Models
describe CameraMake do
describe '#add_model' do
let(:camera_make) { CameraMake.new('Camera Name') }
it 'creates a camera model' do
model = camera_make.add_model('Camera Make', 'thumbnail')
expect(camera_make.models.size).to eq(1)
end
it 'returns the created camera model' do
model = camera_make.add_model('Camera Make', 'thumbnail')
expect(camera_make.models).to eq([model])
end
it 'populates thumbnails for this model' do
model = camera_make.add_model('Camera Make', 'thumbnail')
expect(model.thumbnails.urls.size).to eq(1)
end
end
describe '#name_matches?' do
it 'names match case insensitively, ignoring extra whitespace' do
camera_make = CameraMake.new('Camera Name')
expect(camera_make.name_matches?(' CaMeRa NaMe ')).to be_true
end
end
end
end
| true |
b6b0362d20c3d05e3fa4b842e59b48a90653b742 | Ruby | JS-Bogart/aA_Classwork | /W4D5/anagrams.rb | UTF-8 | 1,200 | 4.25 | 4 | [] | no_license | #TC O(n!), SC O(n!)
def first_anagram?(str1, str2)
return false if str1.length != str2.length
anagram = str1.chars.permutation(str1.length).map { |ele| ele.join("") }
anagram.include?(str2)
end
# p first_anagram?("gizmo", "sally") #=> false
# p first_anagram?("elvis", "lives") #=> true
#TC O(n^2), SC O(n)
def second_anagram?(str1, str2)
return false if str1.length != str2.length
str2_arr = str2.chars # O(n)
str1.each_char do |chr| #O(n)
idx = str2_arr.find_index(chr) # O(n)
return false if idx.nil?
str2_arr.delete_at(idx)
end
str2_arr.empty?
end
# p second_anagram?("gizmo", "sally") #=> false
# p second_anagram?("elvis", "lives") #=> true
#TC O(nlogn) SC O(n)
def third_anagram?(str1, str2)
str1.chars.sort == str2.chars.sort
end
# p third_anagram?("gizmo", "sally") #=> false
# p third_anagram?("elvis", "lives") #=> true
#TC O(n) SC O(n)
def fourth_anagram?(str1, str2)
h1 = Hash.new(0)
str1.each_char {|ch| h1[ch] += 1}
str2.each_char {|ch| h1[ch] -= 1}
h1.values.all? {|v| v == 0}
end
p fourth_anagram?("gizmo", "sally") #=> false
p fourth_anagram?("elvis", "lives") #=> true | true |
b21354b1fa8637406b77f3e25032071b74e74b79 | Ruby | castor4bit/leetcode | /0100/110.Balanced_Binary_Tree/test_110.rb | UTF-8 | 506 | 2.90625 | 3 | [] | no_license | require 'test/unit'
require './110'
require '../../structures/treenode'
class LeetCodeSolutionTest < Test::Unit::TestCase
def test_110
root = TreeNodeUtil.array_to_treenode([3, 9, 20, nil, nil, 15, 7])
assert_equal true, is_balanced(root)
root = TreeNodeUtil.array_to_treenode([1, 2, 2, 3, 3, nil, nil, 4, 4])
assert_equal false, is_balanced(root)
root = TreeNodeUtil.array_to_treenode([1, 2, 2, 3, nil, nil, 3, 4, nil, nil, 4])
assert_equal false, is_balanced(root)
end
end
| true |
dfdcc223095426ca64f1a39a6a39f08fdbd521d1 | Ruby | yasumasamakino/keiba | /batch/horseShisuuKeisanBatch.rb | UTF-8 | 36,942 | 2.765625 | 3 | [] | no_license | # URLにアクセスするためのライブラリの読み込み
require 'open-uri'
# Nokogiriライブラリの読み込み
require 'nokogiri'
require "date"
class Calculation
class << self
# def chakusaScoreCalc(score, sabunTimeSecond, addValue)
# if sabunTimeSecond < 0.1 then
# return score += 9
# elsif sabunTimeSecond == 0.1 then
# return score += 8
# else
# return score += addValue
# end
#
# end
def chakusaScoreCalc(score, sabunTimeSecond, subValue)
if sabunTimeSecond < 0.1 then
return score
elsif sabunTimeSecond >= 0.1 && sabunTimeSecond < 0.2 then
return score - (subValue /3).round(4)
elsif sabunTimeSecond >= 0.2 && sabunTimeSecond < 0.3 then
return score - (subValue /2).round(4)
else
return score - subValue
end
end
# def chakujunScore(chakujun, tousuu, raceRank, raceCount, thisRaceRank, sabunTimeSecond, rei, kobaFlag)
#
# score = 100
#
# if chakujun == 1 then
# score += 6
# if kobaFlag == true then
# score += 3
# end
# elsif chakujun == 2 then
# score = chakusaScoreCalc(score, sabunTimeSecond, 7)
# if kobaFlag == true then
# score += 2
# end
# elsif chakujun == 3 then
# score = chakusaScoreCalc(score, sabunTimeSecond, 6)
# if kobaFlag == true then
# score += 1
# end
# elsif chakujun == 4 then
# score = chakusaScoreCalc(score, sabunTimeSecond, 5)
# # if kobaFlag == true then
# # score += 2
# # end
# elsif chakujun == 5 then
# score = chakusaScoreCalc(score, sabunTimeSecond, 4)
# # if kobaFlag == true then
# # score += 2
# # end
# elsif chakujun == 6 then
# score = chakusaScoreCalc(score, sabunTimeSecond, 3)
# elsif chakujun == 7 then
# score = chakusaScoreCalc(score, sabunTimeSecond, 2)
# elsif chakujun == 8 then
# score = chakusaScoreCalc(score, sabunTimeSecond, 1)
# end
#
# #レース頭数でボーナス
# #14頭立て以上で掲示板ならボーナス
# if chakujun <= 5 then
# if tousuu >= 14 then
# score = score * 1.1
# elsif tousuu < 10 then
# score = score * 0.9
# end
# end
#
# #過去のレースで今回のレースより格上を走っているか
# raceRankDif = raceRank - thisRaceRank
#
# #レースランクボーナス
# if chakujun <= 8 then
# if raceRankDif == 1 then
# score = score * 1.1
# elsif raceRankDif == 2 then
# score = score * 1.2
# elsif raceRankDif == 3 then
# score = score * 1.3
# elsif raceRankDif == 4 then
# score = score * 1.4
# elsif raceRankDif == 5 then
# score = score * 1.5
# elsif raceRankDif == 6 then
# score = score * 1.6
# elsif raceRankDif == 7 then
# score = score * 1.7
# elsif raceRankDif == 8 then
# score = score * 1.8
# end
#
# #前走ならボーナス
# if raceCount == 1 then
# score = score * 1.1
# #2前走ならちょっとボーナス
# elsif raceCount == 2 then
# score = score * 1.05
# #2前前走ならちょっとボーナス
# elsif raceCount == 3 then
# score = score * 1.03
# end
#
# end
#
# return score
#
# end
def chakujunScore(chakujun, tousuu, raceRank, raceCount, thisRaceRank, sabunTimeSecond, rei, kobaFlag)
score = 1
raceScore = (score.to_f / tousuu.to_f).round(4)
if chakujun == 1 then
# score += 6
elsif chakujun == 2 then
score = chakusaScoreCalc(score, sabunTimeSecond, raceScore)
else
score = chakusaScoreCalc(score, sabunTimeSecond, (raceScore*(chakujun-1) ) )
end
if kobaFlag == true then
score = (score.to_f * 1.05).round(4)
end
#過去のレースで今回のレースより格上を走っているか
raceRankDif = raceRank - thisRaceRank
# p raceRankDif
#レースランクボーナス
if chakujun <= 8 then
if raceRankDif == 1 then
score = (score.to_f * 1.02).round(4)
elsif raceRankDif == 2 then
score = (score.to_f * 1.04).round(4)
elsif raceRankDif == 3 then
score = (score.to_f * 1.06).round(4)
elsif raceRankDif == 4 then
score = (score.to_f * 1.08).round(4)
elsif raceRankDif == 5 then
score = (score.to_f * 1.10).round(4)
elsif raceRankDif == 6 then
score = (score.to_f * 1.12).round(4)
elsif raceRankDif == 7 then
score = (score.to_f * 1.14).round(4)
elsif raceRankDif == 8 then
score = (score.to_f * 1.16).round(4)
elsif raceRankDif == -1 then
score = (score.to_f * 0.98).round(4)
elsif raceRankDif == -2 then
score = (score.to_f * 0.96).round(4)
elsif raceRankDif == -3 then
score = (score.to_f * 0.94).round(4)
elsif raceRankDif == -4 then
score = (score.to_f * 0.92).round(4)
elsif raceRankDif == -5 then
score = (score.to_f * 0.90).round(4)
end
end
# p "スコア" + score.to_s
return score
end
#馬の指数を計算する
def getUmaScore(umaCd, kaisaibi, thisRaceRank, bashoCd, kyori, babashurui, targetRaceRank, kishuCd)
#出走馬自身の情報を取得する
#↓暫定
sei = 0
#牝馬の場合は季節を考慮する
kaisaibiStr = kaisaibi.strftime("%Y/%m/%d")
zensouDate = nil
fromZensou = nil
@rows = RaceResult.find_by_sql(SqlCommand.getUmaPastRaceSql(umaCd, kaisaibiStr))
raceCount = 0
score = 0
anteiCnt_1 = 0
anteiCnt_2 = 0
kyakushitsuSum = 0.0
# p umaCd
#過去レースの分析
@rows.each do |row|
raceCount += 1
sei = row.sei
#レース情報の取得
@race = Race.where("racecd=:racecd",racecd:row.racecd)
raceRank = 0
@race.each do |raceRow|
raceRank = raceRow.raceRank
if raceCount == 1 then
zensouDate = raceRow.kaisaibi
end
end
if raceRank == 99 then
raceCount = raceCount -1
next
end
#レース頭数
tousuu = RaceResult.where("racecd=:racecd",racecd:row.racecd).count
#前走の1着との秒数差
kachiumaTimeSeconds = RaceResult.where("racecd=:racecd",racecd:row.racecd,).where("chakujun=:chakujun",chakujun:1)
sabunTimeSecond = row.timeSecond - kachiumaTimeSeconds[0].timeSecond
#3歳の場合、古馬との対決か
kobaFlag = false
kobaCount = 0
if row.rei == 3 then
kobaCount = RaceResult.where("racecd=:racecd",racecd:row.racecd,).where("rei>:rei",rei:3).count
if kobaCount > 0
kobaFlag = true
end
end
#前走のスコア
score += Calculation.chakujunScore(row.chakujun, tousuu, raceRank, raceCount, thisRaceRank, sabunTimeSecond, row.rei, kobaFlag)
# p score
# p row.time[0,1].to_i * 60 + row.time[2,2].to_i + row.time[5,1].to_f/10
#馬体重分析
#馬場得意不得意
#天気
#前走からの日数を取得しておく
if raceCount == 1 then
fromZensou = kaisaibi - zensouDate
end
# #安定感1
# if raceCount <= 3 then
# if row.chakujun <= 5 then
# anteiCnt_1 += 1
# end
# end
#安定感2
if raceCount <= 3 then
if row.chakujun <= 8 then
anteiCnt_2 += 1
end
end
end
if score == 0 then
return 0
end
score = (score.to_f / raceCount.to_f).round(4)
tokuiBasho = 0
#場所と距離の過去成績
@pastSameRaceRows = RaceResult.find_by_sql(SqlCommand.getUmaPastSameRaceSql(umaCd, bashoCd, kyori, babashurui, kaisaibiStr))
@pastSameRaceRows.each do |row|
if row.chakujun == 1
tokuiBasho += 1
end
end
#競馬場が得意か
if tokuiBasho >= 3 then
score = (score.to_f * 1.1).round(4)
elsif tokuiBasho >= 1
score = (score.to_f * 1.05).round(4)
end
#直近3走の安定感を評価
# if anteiCnt_1 == 3 then
# score = score * 1.05
# elsif anteiCnt_2 == 3 then
# score = score * 1.03
# end
if anteiCnt_2 == 3 then
score = (score.to_f * 1.1).round(4)
end
# #前走から90日以上空いている場合、減点
# if fromZensou.to_i >= 90 then
# score = score * 0.6
# end
return score
end
#馬の連対率を算出する
def getRentairitsuScore(debug, umaCd, kaisaibi, sei, rei, kinryou, bataijuu, bashoCd, babashurui, baban, kyori, kishuCd, choukyoushiCd)
if debug == 1 then
p "getRentairitsuScore:" + umaCd, kaisaibi, sei, rei, kinryou, bataijuu, bashoCd, babashurui, baban, kyori, kishuCd, choukyoushiCd
end
score = 0
rentaiScores = {}
#性別
seiRentairitsuSql = "select rentai from rentairitsus where name ='sei' and rentaiProp ='{$sei}' ".to_s.sub!("{$sei}", sei.to_s)
@seiRentairitsus = Rentairitsu.find_by_sql(seiRentairitsuSql)
@seiRentairitsus.each do |row|
if debug == 1 then
p "性別:" + row.rentai.to_s
end
rentaiScores["sei"] = row.rentai.round(4)
score = score + row.rentai.round(4)
end
#!!牡牝の月毎の連対率!!を追加する
seiMonthRentairitsuSql = "select rentai from rentairitsus where name ='sei_month' and rentaiProp ='{$sei_month}' ".to_s.sub!("{$sei_month}", sei.to_s+"_"+kaisaibi[5,2])
@seiMonthRentairitsus = Rentairitsu.find_by_sql(seiMonthRentairitsuSql)
@seiMonthRentairitsus.each do |row|
if debug == 1 then
p "牡牝の月毎:" + row.rentai.to_s
end
rentaiScores["seiMonth"] = row.rentai.round(4)
score = score + row.rentai.round(4)
end
#!!牡牝の馬場毎の連対率!!を追加する
seiBabashuruiRentairitsuSql = "select rentai from rentairitsus where name ='sei_babashurui' and rentaiProp ='{$sei_babashurui}' ".to_s.sub!("{$sei_babashurui}", sei.to_s+"_"+babashurui.to_s)
@seiBabashuruiRentairitsus = Rentairitsu.find_by_sql(seiBabashuruiRentairitsuSql)
@seiBabashuruiRentairitsus.each do |row|
if debug == 1 then
p "牡牝の馬場毎:" + row.rentai.to_s
end
rentaiScores["seiBabashurui"] = row.rentai.round(4)
score = score + row.rentai.round(4)
end
#年齢の連対率を反映
reiRentairitsuSql = "select rentai from rentairitsus where name ='rei' and rentaiProp ='{$rei}' ".sub!("{$rei}", rei.to_s)
@reiRentairitsus = Rentairitsu.find_by_sql(reiRentairitsuSql)
@reiRentairitsus.each do |row|
if debug == 1 then
p "年齢:" + row.rentai.to_s
end
rentaiScores["rei"] = row.rentai.round(4)
score = score + row.rentai.round(4)
end
#斤量の連対率を反映
kinryouRentairitsuSql = "select rentai from rentairitsus where name ='kinryou' and rentaiProp ='{$kinryou}' ".sub!("{$kinryou}", kinryou.to_s)
@kinryouRentairitsus = Rentairitsu.find_by_sql(kinryouRentairitsuSql)
@kinryouRentairitsus.each do |row|
if debug == 1 then
p "斤量:" + row.rentai.to_s
end
rentaiScores["kinryou"] = row.rentai.round(4)
score = score + row.rentai.round(4)
end
#馬体重の連対率を反映
bataijuu = bataijuu.to_i.round(-1)
bataijuuRentairitsuSql = "select rentai from rentairitsus where name ='bataijuu' and rentaiProp ='{$bataijuu}' ".sub!("{$bataijuu}", bataijuu.to_s)
@bataijuuRentairitsu = Rentairitsu.find_by_sql(bataijuuRentairitsuSql)
@bataijuuRentairitsu.each do |row|
if debug == 1 then
p "馬体重:" + row.rentai.to_s
end
rentaiScores["bataijuu"] = row.rentai.round(4)
score = score + row.rentai.round(4)
end
#馬番の連対率を反映
umabanRtKey = bashoCd.to_s + "_" + babashurui.to_s + "_" + baban.to_s
umabanRentairitsuSql = "select rentai from rentairitsus where name ='umaban' and rentaiProp ='{$umabanRtKey}' ".sub!("{$umabanRtKey}", umabanRtKey.to_s)
@umabanRentairitsu = Rentairitsu.find_by_sql(umabanRentairitsuSql)
@umabanRentairitsu.each do |row|
if debug == 1 then
p "馬番:" + row.rentai.to_s
end
rentaiScores["umaban"] = row.rentai.round(4)
score = score + row.rentai.round(4)
# umabanScores[baban] = row.rentai.round(4)
end
#脚質の連対率を反映
kyakushitsu = 0
@kyakushitsu = RentaibaTsuuka.find_by_sql(SqlCommand.getKyakushitsuSql(umaCd, kaisaibi))
@kyakushitsu.each do |row|
kyakushitsu = row.kyakushitsu
end
kyakushitsuRtKey = bashoCd.to_s + "_" + kyori.to_s + "_" + babashurui.to_s + "_" + kyakushitsu.to_s
kyakushitsuRentairitsuSql = "select rentai from rentairitsus where name ='kyakushitsu' and rentaiProp ='{$kyakushitsuRtKey}' ".sub!("{$kyakushitsuRtKey}", kyakushitsuRtKey.to_s)
@kyakushitsuRentairitsu = Rentairitsu.find_by_sql(kyakushitsuRentairitsuSql)
@kyakushitsuRentairitsu.each do |row|
if debug == 1 then
p "脚質:" + row.rentai.to_s
end
rentaiScores["kyakushitsu"] = row.rentai.round(4)
score = score + row.rentai.round(4)
end
#血統の連対率
bloedsCnt = 0
bloedsScore = 0
@bloeds = HorseBloed.where(umaCd:umaCd).where(parentKbn: 0).order(:sedai)
@bloeds.each do |row|
bloedUmaCd = row.bloedUmaCd
bloedRtKey = bashoCd.to_s + "_" + babashurui.to_s + "_" + kyori.to_s + "_" + bloedUmaCd.to_s
bloedRentairitsuSql = "select rentai from rentairitsus where name ='bloed_f' and rentaiProp ='{$bloedRtKey}' ".sub!("{$bloedRtKey}", bloedRtKey.to_s)
@bloedRentairitsu = Rentairitsu.find_by_sql(bloedRentairitsuSql)
@bloedRentairitsu.each do |row|
if debug == 1 then
p "血統:" + row.rentai.to_f.round(4).to_s
end
if bloedsCnt == 0 then
rentaiScores["bloed_f"] = row.rentai.round(4)
score = score + row.rentai.to_f.round(4)
# bloedMawariRtKey = babashurui.to_s + "_" + mawari.to_s + "_" + bloedUmaCd.to_s
# bloedMawariRentairitsuSql = "select rentai from rentairitsus where name ='bloed_f' and rentaiProp ='{$bloedMawariRtKey}' ".sub!("{$bloedMawariRtKey}", bloedMawariRtKey.to_s)
# p bloedMawariRentairitsuSql
# @bloedMawariRentairitsu = Rentairitsu.find_by_sql(bloedMawariRentairitsuSql)
# @bloedMawariRentairitsu.each do |mawariRow|
# rentaiScores["bloed_f_mawari"] = mawariRow.rentai.round(4)
# score = score + mawariRow.rentai.to_f.round(4)
# end
else
if row.rentai.to_f >= 0.25 then
bloedsScore += 1
end
end
bloedsCnt += 1
end
end
rentaiScores["bloedsScores"] = bloedsScore
#血統指数
if bloedsScore.to_i >= 5 then
score = score * 1.2
end
#騎手の連対率を反映
@kishuRentai = RaceResult.find_by_sql(SqlCommand.getKishuRentairitsuSql(kishuCd, kaisaibi))
@kishuRentai.each do |row|
if debug == 1 then
p "騎手:" + row.rentairitsu.to_s
end
rentaiScores["kishu"] = row.rentairitsu.to_f.round(4)
score = score + row.rentairitsu.to_f.round(4)
end
# #調教師の連対率を反映
# @choukyoushiRentai = RaceResult.find_by_sql(SqlCommand.getChoukyoushiRentairitsuSql(choukyoushiCd, kaisaibi))
# @choukyoushiRentai.each do |row|
# rentaiScores["choukyoushi"] = row.rentairitsu.to_f.round(4)
# score = score + row.rentairitsu.to_f.round(4)
# end
rentaiScores["sum"] = score
if debug == 1 then
p rentaiScores
end
return rentaiScores
end
def getKaishuuScore(score, umaCd, kyori, babashurui, debug)
kaishuuScores = {}
#スピード偏差値
speedHensaMax = HorseHensaValue.find_by_sql(SqlCommand.getUmaSpeedHensaSql(umaCd, kyori, babashurui))
kaishuuScores["speedHensa"] = speedHensaMax[0].speed
if kaishuuScores["speedHensa"] == nil then
speedHensaMax = HorseHensaValue.find_by_sql(SqlCommand.getUmaSpeedHensaSql(umaCd, kyori+200, babashurui))
kaishuuScores["speedHensa"] = speedHensaMax[0].speed
end
if kaishuuScores["speedHensa"] == nil then
speedHensaMax = HorseHensaValue.find_by_sql(SqlCommand.getUmaSpeedHensaSql(umaCd, kyori-200, babashurui))
kaishuuScores["speedHensa"] = speedHensaMax[0].speed
end
#上がり偏差値
agariHensaMax = HorseHensaAgariValue.find_by_sql(SqlCommand.getUmaAgariHensaSql(umaCd, kyori, babashurui))
kaishuuScores["agariHensas"] = agariHensaMax[0].speed
if kaishuuScores["agariHensas"] == nil then
agariHensaMax = HorseHensaAgariValue.find_by_sql(SqlCommand.getUmaAgariHensaSql(umaCd, kyori+200, babashurui))
kaishuuScores["agariHensas"] = agariHensaMax[0].speed
end
if kaishuuScores["agariHensas"] == nil then
agariHensaMax = HorseHensaAgariValue.find_by_sql(SqlCommand.getUmaAgariHensaSql(umaCd, kyori-200, babashurui))
kaishuuScores["agariHensas"] = agariHensaMax[0].speed
end
#回収率が高い
if kaishuuScores["speedHensa"] != nil then
if kaishuuScores["speedHensa"] == 44 || kaishuuScores["speedHensa"] == 50 || kaishuuScores["speedHensa"] == 53 then
if debug == 1 then
p "スピード偏差回収率ヒット!!"
end
score = score * 1.2
end
end
#回収率が高い
if kaishuuScores["agariHensas"] != nil then
if kaishuuScores["agariHensas"] >= 51 && kaishuuScores["agariHensas"] <= 54 then
if debug == 1 then
p "上がり偏差回収率ヒット!!"
end
score = score * 1.2
end
end
kaishuuScores["score"] = score
if debug == 1 then
p kaishuuScores
end
return kaishuuScores
end
end
end
class SqlCommand
class << self
def getUmaPastRaceSql(umaCd, kaisaibi)
#直近5レースを取得する
sql = "select a.* from race_results a "\
+ "join races b "\
+ "on a.racecd = b.racecd "\
+ "where umaCd = '{$umaCd}' "\
+ " and kaisaibi < '{$kaisaibi}' "\
+ " and chakujun > 0 "\
+ "order by b.kaisaibi desc limit 5"
sql = sql.sub!("{$umaCd}", umaCd)
sql = sql.sub!("{$kaisaibi}", kaisaibi)
return sql
end
def getUmaPastSameRaceSql(umaCd, bashoCd, kyori, babashurui, kaisaibi)
#同じ場所、距離、馬場のレース成績を取得する
sql = "select a.* from race_results a "\
+ "join races b "\
+ "on a.racecd = b.racecd "\
+ "where umaCd = '{$umaCd}' "\
+ " and b.bashoCd = '{$bashoCd}' "\
+ " and b.babashurui = '{$babashurui}' "\
+ " and b.kyori = '{$kyori}' "\
+ " and b.kaisaibi < '{$kaisaibi}' "\
+ "order by b.kaisaibi"
sql = sql.sub!("{$umaCd}", umaCd.to_s)
sql = sql.sub!("{$bashoCd}", bashoCd.to_s)
sql = sql.sub!("{$kyori}", kyori.to_s)
sql = sql.sub!("{$babashurui}", babashurui.to_s)
sql = sql.sub!("{$kaisaibi}", kaisaibi)
return sql
end
def getUmaSpeedHensaSql(umaCd, kyori, babashurui)
sql = "select kyori, max(speed) as speed from horse_hensa_values"\
+ " where umaCd = '{$umaCd}'"\
+ " and kyori = {$kyori}"\
+ " and babashurui = {$babashurui}"
sql = sql.sub!("{$umaCd}", umaCd.to_s)
sql = sql.sub!("{$kyori}", kyori.to_s)
sql = sql.sub!("{$babashurui}", babashurui.to_s)
return sql
end
def getUmaAgariHensaSql(umaCd, kyori, babashurui)
sql = "select kyori, max(speed) as speed from horse_hensa_agari_values"\
+ " where umaCd = '{$umaCd}'"\
+ " and kyori = {$kyori}"\
+ " and babashurui = {$babashurui}"
sql = sql.sub!("{$umaCd}", umaCd.to_s)
sql = sql.sub!("{$kyori}", kyori.to_s)
sql = sql.sub!("{$babashurui}", babashurui.to_s)
return sql
end
def getKishuKaishuritsuSql(kishuCd, kaisaibi)
kaisaibiBf = (kaisaibi[0,4].to_i - 1).to_s + kaisaibi[4,6]
sql = "select a.kishuCd, toushi, kaishu, round(kaishu/toushi*100,2) as kaishuritsu from "\
+ "(/*投資金額*/" \
+ "select kishuCd, count(*)*100 as toushi from race_results rr join races rc on rr.racecd = rc.racecd and rc.kaisaibi >= '{$kaisaibiBf}' and rc.kaisaibi <= '{$kaisaibi}' and kishuCd ='{$kishuCd}' group by kishuCd) a "\
+ "join (/*回収金額*/" \
+ "select kishuCd, sum(tanshou)*100 as kaishu from race_results rr join races rc on rr.racecd = rc.racecd and rc.kaisaibi >= '{$kaisaibiBf}' and rc.kaisaibi <= '{$kaisaibi}' and kishuCd ='{$kishuCd}' where chakujun =1 group by kishuCd) b "\
+ "on a.kishuCd = b.kishuCd "
sql = sql.sub!("{$kishuCd}", kishuCd.to_s)
sql = sql.sub!("{$kaisaibi}", kaisaibi)
sql = sql.sub!("{$kaisaibiBf}", kaisaibiBf)
sql = sql.sub!("{$kishuCd}", kishuCd.to_s)
sql = sql.sub!("{$kaisaibi}", kaisaibi)
sql = sql.sub!("{$kaisaibiBf}", kaisaibiBf)
return sql
end
def getKishuRentairitsuSql(kishuCd, kaisaibi)
kaisaibiBf = (kaisaibi[0,4].to_i - 1).to_s + kaisaibi[4,6]
sql = "select a.kishuCd, bosu, rentaisu, round(rentaisu/bosu,4) as rentairitsu from "\
+ "(/*母数*/ "\
+ "select kishuCd, count(*) as bosu from race_results rr join races rc on rr.racecd = rc.racecd and rc.kaisaibi >= '{$kaisaibiBf}' and rc.kaisaibi <= '{$kaisaibi}' and kishuCd ='{$kishuCd}' group by kishuCd) a "\
+ "join (/*連対数*/ "\
+ "select kishuCd, count(*) as rentaisu from race_results rr join races rc on rr.racecd = rc.racecd and rc.kaisaibi >= '{$kaisaibiBf}' and rc.kaisaibi <= '{$kaisaibi}' and rr.kishuCd ='{$kishuCd}' and rr.chakujun between 1 and 3 group by rr.kishuCd) b "\
+ "on a.kishuCd = b.kishuCd "
sql = sql.sub!("{$kishuCd}", kishuCd.to_s)
sql = sql.sub!("{$kaisaibi}", kaisaibi)
sql = sql.sub!("{$kaisaibiBf}", kaisaibiBf)
sql = sql.sub!("{$kishuCd}", kishuCd.to_s)
sql = sql.sub!("{$kaisaibi}", kaisaibi)
sql = sql.sub!("{$kaisaibiBf}", kaisaibiBf)
return sql
end
def getChoukyoushiRentairitsuSql(choukyoushiCd, kaisaibi)
kaisaibiBf = (kaisaibi[0,4].to_i - 1).to_s + kaisaibi[4,6]
sql = "select a.choukyoushiCd, bosu, rentaisu, round(rentaisu/bosu,4) as rentairitsu from "\
+ "(/*母数*/ "\
+ "select choukyoushiCd, count(*) as bosu from race_results rr join races rc on rr.racecd = rc.racecd and rc.kaisaibi >= '{$kaisaibiBf}' and rc.kaisaibi <= '{$kaisaibi}' and choukyoushiCd ='{$choukyoushiCd}' group by choukyoushiCd) a "\
+ "join (/*連対数*/ "\
+ "select choukyoushiCd, count(*) as rentaisu from race_results rr join races rc on rr.racecd = rc.racecd and rc.kaisaibi >= '{$kaisaibiBf}' and rc.kaisaibi <= '{$kaisaibi}' and rr.choukyoushiCd ='{$choukyoushiCd}' and rr.chakujun between 1 and 3 group by rr.choukyoushiCd) b "\
+ "on a.choukyoushiCd = b.choukyoushiCd "
sql = sql.sub!("{$choukyoushiCd}", choukyoushiCd.to_s)
sql = sql.sub!("{$kaisaibi}", kaisaibi)
sql = sql.sub!("{$kaisaibiBf}", kaisaibiBf)
sql = sql.sub!("{$choukyoushiCd}", choukyoushiCd.to_s)
sql = sql.sub!("{$kaisaibi}", kaisaibi)
sql = sql.sub!("{$kaisaibiBf}", kaisaibiBf)
return sql
end
def getKyakushitsuSql(umaCd, kaisaibi)
sql = "select "\
+ "round( "\
+ " avg( "\
+ " case when pa < 0.15 then "\
+ " 1 "\
+ " when pa > 0.15 and pa <= 0.30 then "\
+ " 2 "\
+ " when pa > 0.30 and pa <= 0.70 then "\
+ " 3 "\
+ " else "\
+ " 4 "\
+ " end "\
+ " ) "\
+ ", 0) as kyakushitsu "\
+ "from ( "\
+ " select "\
+ " rt.racecd, tousuu, round(avg(rt.position/tousuu), 2) as pa "\
+ " from rentaiba_tsuukas rt "\
+ " join race_tousuus racetousuu "\
+ " on rt.racecd = racetousuu.racecd "\
+ " and position IS NOT NULL "\
+ " join races "\
+ " on races.racecd = rt.racecd "\
+ " and races.kaisaibi <= '{$kaisaibi}' "\
+ " where rt.umaCd = '{$umaCd}' "\
+ " group by rt.racecd, tousuu "\
+ " order by rt.racecd desc limit 3 "\
+ ") a "
sql = sql.sub!("{$umaCd}", umaCd)
sql = sql.sub!("{$kaisaibi}", kaisaibi)
return sql
end
end
end
class HorseShisuuKeisanBatch
def self.execute
debug = 0
mailSend = true
thisKaisaibi = "2017/02/12"
nowTime = Time.now
mailHonbun = []
raceInfoArray = []
raceInfoArray.push(["c201705010611",7,1800,1])
raceInfoArray.push(["c201708020611",8,2200,1])
# raceInfoArray.push(["c201705010606",3,2400,1])
# raceInfoArray.push(["c201705010607",3,1400,0])
# raceInfoArray.push(["c201705010608",3,2100,0])
# raceInfoArray.push(["c201705010609",5,1400,1])
# raceInfoArray.push(["c201705010612",4,1600,1])
#
# raceInfoArray.push(["c201708020607",3,1900,0])
# raceInfoArray.push(["c201708020608",4,1800,0])
# raceInfoArray.push(["c201708020609",3,1600,1])
# raceInfoArray.push(["c201708020612",4,1200,0])
#
# raceInfoArray.push(["c201710010202",3,1000,0])
# raceInfoArray.push(["c201710010206",3,2600,1])
# raceInfoArray.push(["c201710010207",3,1700,0])
# raceInfoArray.push(["c201710010208",3,1200,1])
# raceInfoArray.push(["c201710010209",3,2000,1])
# raceInfoArray.push(["c201710010210",3,1200,1])
# raceInfoArray.push(["c201710010211",5,1700,0])
# raceInfoArray.push(["c201710010212",4,2000,1])
raceInfoArray.each do |raceInfo|
mailHonbunRow = []
raceId = raceInfo[0]
thisRaceRank = raceInfo[1]
thisKyori = raceInfo[2]
thisBabashurui = raceInfo[3]
url = 'http://race.netkeiba.com/?pid=race_old&id=' + raceId.to_s
thisBashoCd = raceId[5, 2]
charset = 'euc-jp'
html = open(url) do |f|
#charset = f.charset # 文字種別を取得
f.read # htmlを読み込んで変数htmlに渡す
end
#htmlをパース(解析)してオブジェクトを生成
doc = Nokogiri::HTML.parse(html, nil, charset)
#レース概要を取得
name = nil
description = nil
doc.xpath('//div[@class="data_intro"]').each do |node|
name = node.css('h1').inner_text
description = node.css('span').inner_text
end
#発走時刻
hassoujikoku = nil
hassoujikokuTime = nil
if description.match(/\d{2}:\d{2}/) != nil then
hassoujikoku = description.match(/\d{2}:\d{2}/)[0]
hassoujikokuTime = Time.parse(thisKaisaibi.to_s + " " + hassoujikoku.to_s)
end
p doc.title.gsub(/[\r\n]/,"")
if hassoujikokuTime > nowTime then
mailHonbunRow.push(doc.title.gsub(/[\r\n]/,""))
mailHonbunRow.push(description)
end
umaCdArray = []
kishuCdArray = []
choukyoushiCdArray = []
doc.css('a').each do |anchor|
umaCd = nil
if anchor[:href].include?("db.netkeiba.com/horse/") then
umaCd = anchor[:href].gsub(/[^0-9]/,"")
umaCdArray.push(umaCd)
end
if anchor[:href].include?("db.netkeiba.com/jockey/") then
kishuCd = anchor[:href].gsub(/[^0-9]/,"")
kishuCdArray.push(kishuCd)
end
if anchor[:href].include?("db.netkeiba.com/trainer/") then
choukyoushiCd = anchor[:href].gsub(/[^0-9]/,"")
choukyoushiCdArray.push(choukyoushiCd)
end
end
payTrs = doc.xpath('//*/table[@class="race_table_old nk_tb_common"]/tr')
seireiArray = []
kinryouArray = []
bataijuuArray = []
payTrs.each do |payTr|
if payTr.xpath('./td[4]').text != "" then
seireiArray.push(payTr.xpath('./td[4]').text)
end
if payTr.xpath('./td[5]').text != "" then
kinryouArray.push(payTr.xpath('./td[5]').text)
end
if payTr.xpath('./td[8]').text != "" then
bataijuuArray.push(payTr.xpath('./td[8]').text)
end
end
baban = 1
today = Date.parse(thisKaisaibi)
zensouDate = nil
fromZensou = 0
scores = {}
bloedsScores = {}
speedHensas = {}
agariHensas = {}
umabanScores = {}
for umaCd in umaCdArray do
score = Calculation.getUmaScore(umaCd, today, thisRaceRank, thisBashoCd, thisKyori, thisBabashurui, thisRaceRank, kishuCdArray[baban-1])
if debug == 1 then
p baban.to_s + "ー" + umaCd.to_s
end
if debug == 1 then
p score
end
#性別の連対率を反映
sei = 0
seiStr = seireiArray[baban-1][0, 1]
if seiStr == "牡" then
sei = 0
elsif seiStr == "牝"
sei = 1
else
sei = 2
end
bataijuu = 0
if bataijuuArray[baban-1] != nil && bataijuuArray[baban-1].to_f > 300 then
bataijuu = bataijuuArray[baban-1][0 ,3].to_i.round(-1)
else
pastBataijuuSql = "select rr.bataijuu as pastBataijuu from race_results rr join races rc on rr.racecd = rc.racecd where umaCd='{$umaCd}' order by rc.kaisaibi desc limit 5 ".sub!("{$umaCd}", umaCd.to_s)
@pastBataijuus = RaceResult.find_by_sql(pastBataijuuSql)
@pastBataijuus.each do |row|
if row.pastBataijuu != nil && row.pastBataijuu != 0 then
bataijuu = row.pastBataijuu
break
end
end
end
#年齢
rei = seireiArray[baban-1][1, 1]
rentaiScores = Calculation.getRentairitsuScore(debug, umaCd, thisKaisaibi, sei, rei, kinryouArray[baban-1], bataijuu.to_s, thisBashoCd, thisBabashurui, baban, thisKyori, kishuCdArray[baban -1], choukyoushiCdArray[baban-1])
#TODO バグっていたが結果的に回収率アップ?テストする。
score += score + rentaiScores["sum"].to_f
kaishuuScores = Calculation.getKaishuuScore(score, umaCd, thisKyori, thisBabashurui, debug)
score = kaishuuScores["score"].to_f
#馬番と指数のmapを作成してキーでソート
scores[baban] = score
baban += 1
end
#勝ち馬5頭を取得
loopCnt=0
scores.sort_by{|key, value| -value}.each do|key, value|
p key.to_s + " " + value.round(4).to_s
mailHonbunRow.push(key.to_s + " " + value.round(4).to_s)
loopCnt += 1
# if loopCnt == 3 then
# break
# end
# p key.to_s + " " + value.round(4).to_s
end
if hassoujikokuTime > nowTime then
mailHonbun.push(mailHonbunRow)
end
end
if mailSend && mailHonbun.size > 0 then
@mail = KaimeMailer.send_mail(mailHonbun).deliver
end
end
end
class KaishuritsuKeisanBatch
def self.execute
version = "0.68"
toushiGaku = 0
toushiRace = 0
kaishuGaku = 0
tekichuRace = 0
debug = 0
#まずは10年分
# @races = Race.find_by_sql("select * from races where kaisaibi >= '2015/01/01' and kaisaibi <= '2015/12/31' and babashurui <> 9 and raceRank = 1 order by kaisaibi")
@races = Race.find_by_sql("select * from races where kaisaibi >= '2016/01/01' and kaisaibi <= '2016/12/31' and raceRank between 3 and 9 and babashurui <> 9 order by kaisaibi")
# @races = Race.find_by_sql("select * from races where kaisaibi >= '2010/01/01' and kaisaibi <= '2015/12/31' and raceRank between 3 and 5 and bashocd in ('03') order by kaisaibi")
#レース数を取得する
@races.each do |race|
# if RaceResult.where("racecd=:racecd",racecd:race.racecd).count < 12 then
# next
# end
@raceResults = RaceResult.where("racecd=:racecd",racecd:race.racecd)
scores = {}
bloedsScores = {}
speedHensas = {}
agariHensas = {}
umabanScores = {}
@raceResults.each do |raceResult|
kaisaibiStr = race.kaisaibi.strftime("%Y/%m/%d")
#指数を算出
score = Calculation.getUmaScore(raceResult.umaCd, race.kaisaibi, race.raceRank, race.bashocd, race.kyori, race.babashurui, race.raceRank, raceResult.kishuCd)
#連対率を追加
rentaiScores = Calculation.getRentairitsuScore(debug, raceResult.umaCd, kaisaibiStr, raceResult.sei, raceResult.rei, raceResult.kinryou, raceResult.bataijuu, race.bashocd, race.babashurui, raceResult.umaban, race.kyori, raceResult.kishuCd, raceResult.choukyoushiCd, raceMawari)
score += score + rentaiScores["sum"].to_f
kaishuuScores = Calculation.getKaishuuScore(score, raceResult.umaCd, race.kyori, race.babashurui, debug)
score = kaishuuScores["score"].to_f
pastRaceUmaShisuu = PastRaceUmaShisuu.new(
racecd: raceResult.racecd,
chakujun: raceResult.chakujun,
shisuu: score,
fatherRt: rentaiScores["bloed_f"],
bloedsScore: rentaiScores["bloedsScore"],
speedHensa: kaishuuScores["speedHensas"],
agariHensa: kaishuuScores["agariHensas"],
version: version
)
pastRaceUmaShisuu.save
#馬番と指数のmapを作成してキーでソート
scores[raceResult.umaban] = score
end
# scores.sort_by{ |_, v| -v }
#勝ち馬5頭を取得
count = 0
yosouRentaiba = {}
scores.sort_by{|key, value| -value}.each do|key, value|
yosouRentaiba[key] = value
count += 1
# if count == 5 then
if count == 2 then
break
end
end
toushiGaku += 1000
toushiRace += 1
#レースの1,2着を取得
#指数マップと合致させる
topFlag = false
top = 0
topStr = 0
@raceResultsTop = RaceResult.where("racecd=:racecd",racecd:race.racecd).where("chakujun=:chakujun",chakujun:1)
if @raceResultsTop.count > 1 then
toushiGaku = toushiGaku - 1000
toushiRace = toushiRace - 1
next
end
@raceResultsTop.each do |top|
top = top.umaban.to_i
topStr += top
topFlag = yosouRentaiba.has_key?(top)
end
secFlag = false
sec = 0
secStr = 0
@raceResultsSec = RaceResult.where("racecd=:racecd",racecd:race.racecd).where("chakujun=:chakujun",chakujun:2)
if @raceResultsSec.count > 1 then
toushiGaku = toushiGaku - 1000
toushiRace = toushiRace - 1
next
end
@raceResultsSec.each do |sec|
sec = sec.umaban.to_i
secStr += sec
secFlag = yosouRentaiba.has_key?(sec)
end
# thdFlag = false
# thd = 0
# thdStr = 0
# @raceResultsThd = RaceResult.where("racecd=:racecd",racecd:race.racecd).where("chakujun=:chakujun",chakujun:3)
# if @raceResultsThd.count > 1 then
# toushiGaku = toushiGaku - 3500
# toushiRace = toushiRace - 1
# next
# end
# @raceResultsThd.each do |thd|
# thd = thd.umaban.to_i
# thdStr += thd
# thdFlag = yosouRentaiba.has_key?(thd)
# end
#2頭含まれていれば払い戻し金額取得して回収額にセット
haraimodoshi = 0
if topFlag && secFlag then
# if topFlag && secFlag && thdFlag then
# @pays = RacePayRaw.where("racecd=:racecd",racecd:race.racecd).where("bakenName=:bakenName",bakenName:"馬連")
# @pays = RacePayRaw.where("racecd=:racecd",racecd:race.racecd).where("bakenName=:bakenName",bakenName:"三連複")
@pays = RacePay.where("racecd=:racecd",racecd:race.racecd).where("bakenKbn=:bakenKbn",bakenKbn: 5)
@pays.each do |pay|
haraimodoshi = pay.pay.to_i * 10
kaishuGaku += pay.pay.to_i * 10
break
end
pastRaceTekichuu = PastRaceTekichuu.new(
racecd: race.racecd.to_s,
version: version
)
pastRaceTekichuu.save
#的中レースをインクリメント
tekichuRace += 1
tousuu = RaceResult.where("racecd=:racecd",racecd:race.racecd).count
p "raceCd:" + race.racecd.to_s + " 頭数:" + tousuu.to_s + " 1着-" + topStr.to_s + " 2着-" + secStr.to_s + " 払い戻し額:" + haraimodoshi.to_s
# p "raceCd:" + race.racecd.to_s + " 頭数:" + tousuu.to_s + " 1着-" + topStr.to_s + " 2着-" + secStr.to_s + " 3着-" + thdStr.to_s + " 払い戻し額:" + haraimodoshi.to_s
else
p "はずれ"
end
end
#投資金額 / 払い戻し金額して回収率
#レース / 的中レースして的中率
p "投資レース数:" + toushiRace.to_s
p "的中レース数:" + tekichuRace.to_s
# p "的中率:" + tekichuRace.div(toushiRace).to_f.to_s
p "投資額:" + toushiGaku.to_s
p "回収額:" + kaishuGaku.to_s
# p "回収率:" + ((kaishuGaku / toushiGaku).to_f * 100).to_s
p "バージョン:" + version.to_s
end
end
HorseShisuuKeisanBatch.execute
# KaishuritsuKeisanBatch.execute
| true |
3f9b210f64da2f178f7d0664f4df865aac71838f | Ruby | cachafla/dm-more | /dm-is-state_machine/lib/dm-is-state_machine/is/dsl/state_dsl.rb | UTF-8 | 1,180 | 2.59375 | 3 | [
"MIT"
] | permissive | module DataMapper
module Is
module StateMachine
# State DSL (Domain Specific Language)
module StateDsl
# Define a state of the system.
#
# Example:
#
# class TrafficLight
# include DataMapper::Resource
# property :id, Serial
# is :state_machine do
# state :green, :enter => Proc.new { |o| o.log("G") }
# state :yellow, :enter => Proc.new { |o| o.log("Y") }
# state :red, :enter => Proc.new { |o| o.log("R") }
#
# # event definitions go here...
# end
#
# def log(string)
# Merb::Logger.info(string)
# end
# end
def state(name, options = {})
unless state_machine_context?(:is)
raise InvalidContext, "Valid only in 'is :state_machine' block"
end
# ===== Setup context =====
machine = @is_state_machine[:machine]
state = Data::State.new(name, machine, options)
machine.states << state
end
end # StateDsl
end # StateMachine
end # Is
end # DataMapper
| true |
a84ecfe497153893675cd185f7cf24ab3d2255ca | Ruby | AlexanderCleasby/ruby-music-library-cli-online-web-pt-102218 | /lib/musicimporter.rb | UTF-8 | 272 | 2.8125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class MusicImporter
attr_reader :path
def initialize(path)
@path=path
end
def files
Dir[@path+"/*"].map{|filename| filename.split('/').last }
end
def import
self.files.each{|file| Song.create_from_filename(file)}
end
end | true |
7ca9c340a62c8780750a62cd0d0589021354e127 | Ruby | PeaWarriorLabs/ruby-oo-practice-flatiron-mifflin-exercise-nyc04-seng-ft-053120 | /lib/Manager.rb | UTF-8 | 1,022 | 3.515625 | 4 | [] | no_license | class Manager
attr_reader :name, :department, :age
@@all = []
def initialize(name, department, age)
@name = name
@department = department
@age = age
save
end
def save
self.class.all << self
end
def self.all
@@all
end
def employees
Employee.all.select do |employee|
employee.manager == self
end
end
def hire_employee(employee_name, employee_salary)
Employee.new(employee_name, employee_salary, self)
end
def self.all_departments
self.all.map do |manager|
manager.department
end
end
def self.average_age
self.total_ages/self.num_of_managers
end
private
def self.get_ages
self.all.map do |manager|
manager.age
end
end
def self.total_ages
get_ages.inject {|total_age, age| total_age + age}
end
def self.num_of_managers
self.all.count
end
end
| true |
50c21e9c2783780b58c864f29fe17aa16b5de174 | Ruby | ethransom/tic-tac-toe | /lib/player.rb | UTF-8 | 208 | 3.359375 | 3 | [
"MIT"
] | permissive | module TicTacToe
class Player
attr_reader :symbol
def initialize symbol
@symbol = symbol
end
def puts msg
Kernel::puts "#{@symbol.to_s}: #{msg}"
end
end
end
| true |
ac600b6c71296eec45ce5cd4148c945a63029679 | Ruby | makanazilla/RubyTheHW | /ex13.rb | UTF-8 | 341 | 3.46875 | 3 | [] | no_license | first, second, third = ARGV
puts "What's your first variable?"
first = $stdin.gets.chomp
puts "What's your second variable?"
second = $stdin.gets.chomp
puts "What's your third variable?"
third = $stdin.gets.chomp
puts "Your first variable is: #{first}"
puts "Your second variable is: #{second}"
puts "Your third variable is: #{third}"
| true |
0d36e09a25b62ce306e8fa8a8e4d1c04d395b257 | Ruby | musiccity365/pfwtfp-stats-with-subroutines-dc-web-mod1-repeat | /lib/stats.rb | UTF-8 | 1,410 | 3.5625 | 4 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'pry'
def mean(array)
sum = 0.0
array.each do |item|
sum += item
end
sum / array.size
end
def median(array)
order = array.sort!
median = (array.size - 1) / 2
if array.size.odd? #helper(array)
order[median]
else
median2 = median + 1
(order[median] + order[median2]) / 2.0
end
end
# array = [55, 96, 95, 13, 37]
# binding.pry
# def helper(array)
# array.size.odd?
# end
# puts helper([55,44])
# puts helper([55,44,33])
# puts median(array)
def mode(array)
array.group_by {|i| i }.max_by{|k, v| v.length}.first
end
# array = [63, 60, 1, 51, 90, 69, 97, 29, 24, 62, 7, 43, 33, 79, 48, 37, 20, 94, 49, 21, 78, 28, 54, 0, 64, 18, 63, 37, 56, 56, 71, 37, 46, 33, 1, 85, 74, 99, 91, 16, 80, 32, 16, 18, 75, 55, 96, 95, 13, 37, 30, 48, 61, 33, 52, 2, 28, 36, 90, 44, 48, 59, 74, 54, 91, 21, 56, 39, 29, 32, 48, 9, 33, 60, 88, 55, 11, 84, 10, 80, 76, 68, 44, 44, 19, 16, 98, 39, 50, 65, 35, 45, 52, 1, 18, 63, 2, 87, 99, 20]
# # binding.pry
# def helper(array)
# array.group_by {|i| i }.max_by{|k, v| v.length}.first
# end
# puts helper(array)
def standard_deviation(array)
m = mean(array)
sum = 0.0
array.each {|v| sum += (v-m)**2 }
average = sum / array.size
Math.sqrt(average)
end
# def sigma(array)
# Math.sqrt(standard_deviation(array))
# end
# puts standard_deviation(array)
# puts sigma(array) | true |
687af08f18e5a4236d3f678937548efc92b903c3 | Ruby | milodky/Ruby4Fun | /SpaceTest.rb | UTF-8 | 82 | 2.84375 | 3 | [] | no_license | def f(x)
x * x
end
if __FILE__ == $0
puts f(2 + 3) + 1
puts f (2 + 3) + 1
end
| true |
f7e9eadb574de144d7f10037a2dad2f1d5041d4a | Ruby | figuedmundo/QE_training_BDT_ruby | /Edmundo/tasks/practiceCelciusFahrenheit.rb | UTF-8 | 163 | 3.46875 | 3 | [] | no_license | def cel_to_fah(value)
((9 * value ) / 5.0) + 32
end
def fah_to_cel(value)
return ((5 * (value -32)) / 9.0)
end
puts cel_to_fah 99
puts(fah_to_cel 60) | true |
33253d57e841922aa94373e5f9887a5a30b7a089 | Ruby | bannio/mars | /spec/models/sales_order_line_spec.rb | UTF-8 | 1,457 | 2.609375 | 3 | [] | no_license | require 'spec_helper'
describe SalesOrderLine do
let(:sales_order) { create(:sales_order) }
before :each do
@attr = {
name: "item name",
description: "description of line",
quantity: 2,
unit_price: 2.0,
total: nil,
sales_order_id: sales_order.id
}
@sales_order = create(:sales_order)
end
it "is valid with these attributes" do
line = SalesOrderLine.new(@attr)
expect(line).to be_valid
end
it "requires a name" do
line = SalesOrderLine.new(@attr.merge(name: ''))
expect(line).to_not be_valid
end
it "calculates the total correctly" do
line = SalesOrderLine.new(@attr.merge(sales_order_id: @sales_order.id))
line.save
expect(line.total).to eq(4.0)
end
it "replaces nil with zero in quantity" do
line = SalesOrderLine.new(@attr.merge(quantity: '', sales_order_id: @sales_order.id))
expect(line).to be_valid
line.save
expect(line.quantity).to eq(0)
end
it "replaces nil with zero in price" do
line = SalesOrderLine.new(@attr.merge(unit_price: '', sales_order_id: @sales_order.id))
expect(line).to be_valid
line.save
expect(line.unit_price).to eq(0)
end
it "calculates the total correctly even with no inputs" do
line = SalesOrderLine.new(@attr.merge(unit_price: '', quantity: '', sales_order_id: @sales_order.id))
line.save
expect(line.total).to eq(0)
end
end
| true |
c4e9f42dff39c85de168c351c5608f86a56a5886 | Ruby | jack-nie/phone_list_checker | /lib/reader/txt_reader.rb | UTF-8 | 314 | 3.046875 | 3 | [] | no_license | module Reader
class TxtReader
attr_accessor :path
def initialize(path)
@path = path
end
def each_line
open { |file| file.each_line { |line| yield line if block_given? } }
end
private
def open
File.open(path, 'rb') { |file| yield file } if path
end
end
end
| true |
90dbed16aae57d6e6afb2d301332d43c8373ae56 | Ruby | eregon/adventofcode | /2020/16b.rb | UTF-8 | 1,088 | 2.625 | 3 | [] | no_license | fields, mine, others = File.read('16.txt').split("\n\n")
fields = fields.lines.map { |line|
name = line[/^([\w ]+):/, 1]
[name, line[/^[\w ]+: ((\d+-\d+)( or \d+-\d+)*)$/, 1].split(' or ').map { |range|
range =~ /(\d+)-(\d+)/ and ($1.to_i..$2.to_i)
}]
}
valid = fields.flat_map(&:last)
mine = mine.lines.drop(1)[0].chomp.split(',').map(&:to_i)
tickets = others.lines.drop(1).map { |line|
line.chomp.split(',').map(&:to_i)
}.reject { |ticket|
ticket.any? { |n| valid.none? { |range| range === n } }
}
to_assign = fields.dup
assignment = [nil] * fields.size
until to_assign.empty?
assignment.each_with_index { |assigned,i|
next if assigned
data = tickets.map { |ticket| ticket[i] }
matching_fields = to_assign.select { |name, ranges|
data.all? { |n| ranges.any? { |range| range === n } }
}
if matching_fields.size == 1
assignment[i] = to_assign.delete(matching_fields.first)
end
}
end
indices = assignment.map(&:first).map.with_index.to_a.select { |name,_| /^departure/ =~ name }.map(&:last)
p mine.values_at(*indices).reduce(:*)
| true |
f642a0a16685bf96132e81d5fa2ecd632f1b9690 | Ruby | swapnilp0x00/Splitbills | /app/models/bill.rb | UTF-8 | 1,091 | 2.53125 | 3 | [] | no_license | class Bill < ApplicationRecord
belongs_to :user , class_name: 'User', foreign_key: :user_id, primary_key: :id
has_many :bill_parts, class_name:"BillPart", foreign_key: :bill_id , primary_key: :id, inverse_of: :bill , dependent: :delete_all
# remember to uncomment
validates_presence_of :event, :date, :location, :total_amount, :user_id
accepts_nested_attributes_for :bill_parts,
reject_if: lambda{|attrs| attrs['participant_id'].blank? || attrs['amount'].blank?}
validates :total_amount, :numericality => { :greater_than_or_equal_to => 0 }
# work around
# There are always bill parts present on bill
after_initialize do |bill|
if bill.bill_parts.empty?
User.order(:id).each{|user| bill.bill_parts.build(participant_id:user.id) }
end
end
def get_total_bill_amount
total_bill_amount = BillPart.where(bill_id: self.id).sum(:amount)
end
def get_number_of_participants
number_of_participants = BillPart.where(bill_id: self.id).count
end
def get_split_per_head
self.get_total_bill_amount / self.get_number_of_participants
end
end
| true |
0444564d3d62b1dd9152e8f733a4c8960bce64f7 | Ruby | blairad/cinema_homework | /models/customer.rb | UTF-8 | 1,784 | 3.203125 | 3 | [] | no_license | require_relative('../db/sql_runner')
require_relative('./films')
require_relative('./tickets')
# require_relative('./customer')
require('pry')
class Customer
attr_reader :id
attr_accessor :funds, :name
def initialize(options)
@id = options['id'].to_i if options['id']
@name = options['name']
@funds = options['funds'].to_i
end
def save()
sql = "INSERT INTO customers
(
name,
funds
) VALUES
(
$1, $2
) RETURNING id"
values = [@name, @funds]
customers = SqlRunner.run(sql, values)
@id = customers[0]['id'].to_i
end
def update()
sql = "UPDATE customers SET (name, funds) = ($1, $2) WHERE id = $3"
values = [@name, @funds, @id]
SqlRunner.run(sql, values)
end
def tickets_bought()
sql = "SELECT films.* FROM films
INNER JOIN tickets
ON films.id = tickets.film_id
INNER JOIN customers
ON customers.id = tickets.customer_id
WHERE customers.id = $1 "
values = [@id]
ticket_data = SqlRunner.run(sql, values)
return Film.map_items(ticket_data)
end
#extension
def number_of_tickets()
sql = "SELECT * FROM tickets WHERE customer_id = $1"
values = [@id]
customer_ticket_data = SqlRunner.run(sql, values)
p customer_ticket_data.count{ |cust| Customer.new(cust)}
end
def buying_tickets
ticket_cost = se
end
def self.delete_all()
sql = "DELETE FROM customers"
SqlRunner.run(sql)
end
def self.all()
sql = "SELECT * FROM customers"
all_customers = SqlRunner.run(sql)
return self.map_items(all_customers)
end
def self.map_items(customer_data)
results = customer_data.map { |customer| Customer.new(customer) }
#p results
end
end
| true |
8ab164597d687589e871a288fea9353b05f0b0df | Ruby | PhilHuangSW/Leetcode | /repeated_substring_pattern.rb | UTF-8 | 1,620 | 4.40625 | 4 | [] | no_license | #################### REPEATED SUBSTRING PATTERN ####################
# Given a non-empty string check if it can be constructed by taking a
# substring of it and appending multiple copies of the substring together.
# You may assume the given string consists of lowercase English letters
# only and its length will not exceed 10000.
# Example 1:
# Input: "abab"
# Output: True
# Explanation: It's the substring "ab" twice.
# Example 2:
# Input: "aba"
# Output: False
# Example 3:
# Input: "abcabcabcabc"
# Output: True
# Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
#################### SOLUTION ####################
# @param {String} s
# @return {Boolean}
def repeated_substring_pattern(s)
return false if s.empty?
return false if s.size == 1
(0...s.size/2).each do |i|
# builds a substring up to half of string, so if
# str is "abcabcabc" it will build "a" then "ab"
# then "abc" then "abca" (assuming it hasn't returned true yet)
temp = s[0..i]
if (s.size%temp.size) == 0
if temp * (s.size/temp.size) == s
return true
end
end
end
false
end
s1 = "abc"
s2 = "abab"
s3 = "philipphilip"
s4 = "aba"
s5 = "abcabcabcabc"
puts "Expected: false -- Output: #{repeated_substring_pattern(s1)}"
puts "Expected: true -- Output: #{repeated_substring_pattern(s2)}"
puts "Expected: true -- Output: #{repeated_substring_pattern(s3)}"
puts "Expected: false -- Output: #{repeated_substring_pattern(s4)}"
puts "Expected: true -- Output: #{repeated_substring_pattern(s5)}"
| true |
60b47a4e942767c35f1e734436a82a3ef69878a1 | Ruby | skrepkoed/thinknetica_course | /RubyBasics/Lesson7/modules/railway_route_module.rb | UTF-8 | 2,032 | 2.984375 | 3 | [] | no_license | require_relative 'validation_module'
require 'pry'
module RailwayRoute
include Validations::RouteValidations
include ExceptionsModule::RailwayExceptions
# binding.pry
private
def create_route
validate_stations_amount(stations)
rescue InsufficientStationsAmount => e
puts e.message
create_station
retry
else
puts 'Please choose first station on the route:'
first_stattion = menu_list(stations, :name)
puts 'Please choose last station on the route:'
last_station = menu_list(stations.reject { |station| station == first_stattion }, :name)
route = Route.new(first_stattion, last_station)
routes << route
puts "Route #{route} was created."
end
def change_route
stages = ['Please choose the route:', 'Please choose what you want to do with the route:']
options = { 'Remove station from the route' => :remove_station, 'Add station to the route' => :add_station }
if routes.empty?
puts 'Please create route.'
create_route
else
options_list(stages, options, routes)
end
end
def remove_station(route)
if valid_transitional_stations_amount?(route.transitional_stations)
puts 'Please, choose station:'
station = menu_list(route.transitional_stations, :name)
route.remove_transitional_station(station)
begin
rescue FalliedChangeRoute => e
puts e.message
main_menu
else
puts "Station #{station.name} was removed from route."
end
else
main_menu
end
end
def add_station(route)
validate_available_stations(route)
rescue InsufficientStationsAmount => e
puts e.message
create_station
retry
else
puts 'Please, choose station:'
station = menu_list(available_stations(route), :name)
route.add_transitional_station station
puts "Station #{station.name} was added to route."
end
def available_stations(route)
stations.reject { |station| station == route.first_station || station == route.last_station }
end
end
| true |
18615cfd918c5a15ab122c6baaa0c9dec0383a41 | Ruby | kurukuruk/stoffle | /lib/stoffle/ast/binary_operator.rb | UTF-8 | 353 | 3.15625 | 3 | [] | no_license | class Stoffle::AST::BinaryOperator < Stoffle::AST::Expression
attr_accessor :operator, :left, :right
def initialize(operator, left = nil, right = nil)
@operator = operator
@left = left
@right = right
end
def ==(other)
operator == other&.operator && children == other&.children
end
def children
[left, right]
end
end
| true |
e772a121c45d129f312a87b01750931f0610eb4b | Ruby | ShishirSK/food-exercise-and-glycation | /blood-sugar-simulation.rb | UTF-8 | 7,186 | 3.453125 | 3 | [] | no_license | #!/usr/bin/env ruby
# CLI interface to accept records of food intake and
# exercise and simulate the blood sugar levels
require 'time'
require 'csv'
BASE_SUGAR_LEVEL = 80.0
# Inputs and reference data
@food_db = {}
@exercise_db = {}
@user_inputs = []
# Status mapping strcutures
@food_impact = {}
@exercise_impact = {}
@net_value_map = {}
# Variables
@food_impact_period = 120 # Food increases blood sugar over 2 hours
@exercise_impact_period = 60 # Exercise decreases blood sugar over 1 hour
@glycation_threshold = 150.0
@simulation_period = 0
@glycation_count = 0
# Initiates the script DB and waits for user input
def initialize_simulation(hours = 24)
load_db # Load food and exercise data
render_script_information # Show introductory information
get_user_inputs # Accept inputs from the user
# Initialize the tracking maps.
@simulation_period = hours * 60 # Convert to minutes
@food_impact = (0..@simulation_period).each_with_object(false).to_h
@exercise_impact = (0..@simulation_period).each_with_object(false).to_h
@net_value_map = (0..@simulation_period).each_with_object(0).to_h
blood_sugar_simulation #
end
# Driver method
def blood_sugar_simulation
parse_inputs # Parse and process inputs
simulate_sugar_levels # Simulate sugar levels and display output
end
# Get inputs from the user
def get_user_inputs
input = "begin"
while input != "exit" do
puts "Enter Food or Exercise with ID and timestamp in above mentioned format"
puts "Type exit to finish."
input = gets.chomp
@user_inputs << input unless input == "exit"
end
end
# Parse the user input and update food or exercise impact maps
def parse_inputs
@user_inputs.each do |input|
impact_factor, id, time = input.split(",").each {|x| x.strip!}
if (impact_factor.downcase == "food")
update_food_impact(id, time)
elsif (impact_factor.downcase == "exercise")
update_exercise_impact(id, time)
end
end
end
# Tracks minutes impacted by food consumption
# @param [String] food_id ID of the food consumed
# @param [String] eat_time Timestamp of food consumption
def update_food_impact(food_id, eat_time)
eat_time = Time.parse(eat_time)
start_time = (eat_time.hour * 60) + (eat_time.min)
end_time = start_time + @food_impact_period
increase_rate = sugar_increase_rate_by_food(food_id)
(start_time..end_time).each do |minute|
@food_impact[minute] = true
@net_value_map[minute] += increase_rate
end
end
# Tracks minutes impacted by exercise
# @param [String] ecx_id ID of the exercise performed
# @param [String] exc_time Timestamp of exercise
def update_exercise_impact(exc_id, exc_time)
exc_time = Time.parse(exc_time)
start_time = (exc_time.hour * 60) + (exc_time.min)
end_time = start_time + @exercise_impact_period
decrease_rate = sugar_decrease_rate_by_exercise(exc_id)
(start_time..end_time).each do |minute|
@exercise_impact[minute] = true
@net_value_map[minute] -= decrease_rate
end
end
# Calculated and stores the simulated rates of blood sugar
# level based on food consumed and exercise performed at any
# point of time, by the minute. Also normalization chart and
# keeps a glycation count.
def simulate_sugar_levels
net_change_rate = 0
minute = 0
current_sugar_level = BASE_SUGAR_LEVEL
simulated_sugar_levels = [] << current_sugar_level
# Calculate simulated sugar levels by the minute
while minute <= @simulation_period do
# Impact of food or exercise or both
if @food_impact[minute] || @exercise_impact[minute]
net_change_rate = @net_value_map[minute]
simulated_sugar_levels << (current_sugar_level += net_change_rate)
else # No impact of either food or sugar
current_sugar_level = normalize_sugar_level(current_sugar_level)
simulated_sugar_levels << (current_sugar_level)
end
@glycation_count += 1 if current_sugar_level > @glycation_threshold
minute += 1
end
# Extended period simulation if blood sugar level is not
# normalized by end of stated period
is_extended_simulation = current_sugar_level != BASE_SUGAR_LEVEL ? true : false
while current_sugar_level != BASE_SUGAR_LEVEL do
current_sugar_level = normalize_sugar_level(current_sugar_level)
simulated_sugar_levels << (current_sugar_level)
@glycation_count += 1 if current_sugar_level > @glycation_threshold
end
render_results(simulated_sugar_levels, is_extended_simulation)
end
# Returns sugar increase per minute on food intake
# @param [String] food_id ID of the food consumed
# @return [Float] Increase rate of sugar
def sugar_increase_rate_by_food(food_id)
@food_db.key?(food_id) ? (@food_db[food_id][:glycemic_index]).to_f / @food_impact_period : 0.0
end
# Returns sugar decrease per minute on food intake
# @param [String] exc_id ID of the exercise performed
# @return [Float] Decrease rate of sugar
def sugar_decrease_rate_by_exercise(exc_id)
@exercise_db.key?(exc_id) ? ((@exercise_db[exc_id][:exercise_index]).to_f / @exercise_impact_period) : 0.0
end
# Returns the current sugar level as it normalized
# to BASE_SUGAR_LEVEL
# @param [Float] current_sugar_level
# @return [Float] updated sugar level
def normalize_sugar_level(current_sugar_level)
if current_sugar_level.round == BASE_SUGAR_LEVEL
return current_sugar_level.round.to_f
elsif current_sugar_level.floor == BASE_SUGAR_LEVEL
return current_sugar_level.floor.to_f
else
(current_sugar_level.round > BASE_SUGAR_LEVEL) ? current_sugar_level -= 1 : current_sugar_level += 1
end
end
# Render the resuts
# @param [Array] sugar_levels_by_minute Simulated sugar levels
# @param [Boolean] is_extended_simulation Flag for note
def render_results(sugar_levels_by_minute, is_extended_simulation = false)
puts "Note: This simulation is for an extended period as blood levels had not normalized till the end of the default period." if is_extended_simulation
puts
puts sugar_levels_by_minute.inspect
puts
puts "Glycation count is at #{@glycation_count}"
puts
end
# Render the necessary information at the start of the script
def render_script_information
puts "* ---------------------------------------------------------------------------"
puts "* This is a CLI interface to accept records of food intake and exercise"
puts "* along with timestamps and simulate the blood sugar levels through the day."
puts "*"
puts "* Food intake information is to be entered as below"
puts '* "Food, 1, 2017-09-09 00:00:23 -0700"'
puts "*"
puts "* Exercise information is to be entered as below"
puts '* "Exercise, 1, 2017-09-09 01:45:23 -0700"'
puts "*"
puts "* ---------------------------------------------------------------------------"
puts
end
# Load food and Exercise data from CSV files
def load_db
# Load exercise data and populate the exercise_db hash
arr_of_exercises = CSV.read("./ExerciseDB.csv")
arr_of_exercises.delete_at(0)
arr_of_exercises.each do |arr|
@exercise_db[arr[0]] = {name: arr[1], exercise_index: arr[2].to_i}
end
# Load food data and populate the food_db hash
arr_of_food = CSV.read("./FoodDB.csv")
arr_of_food.delete_at(0)
arr_of_food.each do |arr|
@food_db[arr[0]] = {name: arr[1], glycemic_index: arr[2].to_i}
end
end
initialize_simulation
| true |
a48b07d5cf0cca0b882c73ba3da3767cfd60cf6b | Ruby | ppj/robot | /spec/board_spec.rb | UTF-8 | 5,687 | 2.8125 | 3 | [] | no_license | # frozen_string_literal: true
require_relative "../lib/board.rb"
require_relative "../lib/robot_placement_checker.rb"
require "rspec/its"
RSpec.describe Board do
subject(:board) { described_class.new }
describe "a new board" do
its(:max_x) { is_expected.to eq(5) }
its(:max_y) { is_expected.to eq(5) }
describe "cells" do
subject(:cells) { board.cells }
it "creates rows of cells" do
expect(cells.size).to eq(board.max_y + 1)
end
it "creates cells in each row", :aggregate_failures do
cells.each do |cell_row|
expect(cell_row.size).to eq(board.max_x + 1)
end
end
it "creates empty cells" do
board.cells.each do |cell_row|
cell_row.each do |cell|
expect(cell).to be_empty
end
end
end
end
end
describe "#cell_at_location" do
subject(:cell_at_location) { board.cell_at_location(x, y) }
context "when the x value is out of bounds" do
let(:x) { board.max_x + 1 }
let(:y) { board.max_y - 1 }
it { is_expected.to be(nil) }
end
context "when the y value is out of bounds" do
let(:x) { board.max_x - 1 }
let(:y) { board.max_y + 1 }
it { is_expected.to be(nil) }
end
context "when the location is inside the boundary" do
let(:x) { board.max_x }
let(:y) { board.max_y }
it { is_expected.to be_a(Board::Cell) }
end
end
describe "#cell_available?" do
subject(:cell_available?) { board.cell_available?(x, y) }
context "when the x value is greater than the max x of the board" do
let(:x) { board.max_x + 1 }
let(:y) { board.max_y - 1 }
it { is_expected.to be(false) }
end
context "when the x value is negative" do
let(:x) { -1 }
let(:y) { board.max_y - 1 }
it { is_expected.to be(false) }
end
context "when the y value is great than the max y of the board" do
let(:x) { board.max_x - 1 }
let(:y) { board.max_y + 1 }
it { is_expected.to be(false) }
end
context "when the y value is negative" do
let(:x) { board.max_x - 1 }
let(:y) { -1 }
it { is_expected.to be(false) }
end
context "when the location is inside the boundary" do
let(:x) { board.max_x }
let(:y) { board.max_y }
context "but the cell at the location is not empty" do
before do
# TODO: Replace once occupy cell is implemented
board.cell_at_location(x, y).robot = double
end
it { is_expected.to be(false) }
end
end
end
describe "#fill_location" do
subject(:fill_location) { board.fill_location(x: x, y: y, name: name, facing: facing) }
let(:x) { board.max_x }
let(:y) { board.max_y }
let(:name) { "iRoboto" }
let(:facing) { "facing" }
before do
allow(RobotPlacementChecker).to receive(:valid?).with(
facing: facing, board: board, x: x, y: y,
).and_return(placement_valid?)
end
let(:cell) { board.cell_at_location(x, y) }
context "when the robot placement information is not valid" do
let(:placement_valid?) { false }
it "does not attempt to put the robot in the cell" do
expect(cell).not_to receive(:robot)
fill_location
end
end
context "when the robot placement information is valid" do
let(:placement_valid?) { true }
context "when a robot with a provided name is already on the board" do
before do
old_cell.robot = robot
end
let(:old_cell) { board.cell_at_location(old_x, old_y) }
let(:old_x) { 0 }
let(:old_y) { 0 }
let(:robot) { double(name: name, "facing=": nil) }
it "removes the robot from the old location" do
fill_location
expect(old_cell).to be_empty
end
it "teleports it to the new location" do
fill_location
expect(cell.robot).to eq(robot)
end
it "assigns the specified direction to the teleported robot" do
fill_location
expect(robot).to have_received(:facing=).with(facing)
end
end
context "when a robot with a provided name is not on the board" do
before do
allow(Robot).to receive(:new).and_return(robot)
end
let(:robot) { double }
it "creates a new robot" do
expect(Robot).to receive(:new).with(name: name, facing: facing)
fill_location
end
it "adds the robot to the board successfully" do
expect(cell).to receive(:robot=).with(robot)
fill_location
end
end
end
end
describe "#robot_details" do
subject(:robot_details) { board.robot_details(name) }
let(:name) { "botbot" }
context "when a robot with the provided name is not on the board" do
it { is_expected.to be(nil) }
end
context "when a robot with the provided name is on the board" do
before do
board.fill_location(x: x, y: y, name: name, facing: facing)
end
let(:x) { 1 }
let(:y) { 1 }
let(:facing) { "NORTH" }
it { is_expected.to eq({ x: x, y: y, facing: facing }) }
end
end
describe "#robot" do
subject(:robot) { board.robot(name) }
let(:name) { "roboto" }
context "when a robot with the provided name is not on the board" do
it { is_expected.to be(nil) }
end
context "when a robot with the provided name is on the board" do
before do
board.fill_location(x: 1, y: 1, name: name, facing: "EAST")
end
it { is_expected.not_to be(nil) }
end
end
end
| true |
4a22b170658a3169106419752f52d4656e60ca9e | Ruby | firespring/mogbak | /lib/create.rb | UTF-8 | 1,873 | 2.6875 | 3 | [
"MIT"
] | permissive | #Creates a backup profile to be used by Backup
class Create
attr_accessor :db, :db_host, :db_port, :db_pass, :db_user, :domain, :tracker_host, :tracker_port, :workers
include Validations
#Run validations and create the backup profile
#@param [Hash] o hash containing the settings for the backup profile
def initialize(o = {})
@db = o[:db] if o[:db]
@db_host = o[:db_host] if o[:db_host]
@db_port = Integer(o[:db_port]) if o[:db_port]
@db_pass = o[:db_pass] if o[:db_pass]
@db_user = o[:db_user] if o[:db_user]
@domain = o[:domain] if o[:domain]
@tracker_ip = o[:tracker_ip] if o[:tracker_ip]
@tracker_port = o[:tracker_port] if o[:tracker_port]
#If settings.yml exists then this is an existing backup and you cannot run a create on top of it
raise 'Cannot run create on an existing backup. Try: mogbak backup #{$backup_path} to backup. If you want
to change settings on this backup profile you will have to edit #{$backup_path}/settings.yml manually.' if check_settings_file(nil)
check_backup_path
create_sqlite_db
connect_sqlite
migrate_sqlite
mogile_db_connect
mogile_tracker_connect
check_mogile_domain(@domain)
#Save settings
save_settings
end
#Save the settings for the backup into a yaml file (settings.yaml) so that an incremental can be ran without so many parameters
#@return [Bool] true or false
def save_settings
require 'yaml'
settings = {
'db' => @db,
'db_host' => @db_host,
'db_port' => @db_port,
'db_pass' => @db_pass,
'db_user' => @db_user,
'domain' => @domain,
'tracker_ip' => @tracker_ip,
'tracker_port' => @tracker_port,
'backup_path' => $backup_path
}
File.open("#{$backup_path}/settings.yml", 'w') do |file|
file.write settings.to_yaml
end
true
end
end
| true |
17ca3d4e5f42a07feb92ff82c2ec3eec1af84f63 | Ruby | leancloud/objc-sdk | /AVOS/.ci/UnitTestParser/xcresult.rb | UTF-8 | 13,448 | 2.546875 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | # copy from https://github.com/fastlane-community/trainer/blob/307d52bd6576ceefc40d3f57e34ce3653af10b6b/lib/trainer/xcresult.rb
module XCResult
# Model attributes and relationships taken from running the following command:
# xcrun xcresulttool formatDescription
class AbstractObject
attr_accessor :type
def initialize(data)
self.type = data["_type"]["_name"]
end
def fetch_value(data, key)
return (data[key] || {})["_value"]
end
def fetch_values(data, key)
return (data[key] || {})["_values"] || []
end
end
# - ActionTestPlanRunSummaries
# * Kind: object
# * Properties:
# + summaries: [ActionTestPlanRunSummary]
class ActionTestPlanRunSummaries < AbstractObject
attr_accessor :summaries
def initialize(data)
self.summaries = fetch_values(data, "summaries").map do |summary_data|
ActionTestPlanRunSummary.new(summary_data)
end
super
end
end
# - ActionAbstractTestSummary
# * Kind: object
# * Properties:
# + name: String?
class ActionAbstractTestSummary < AbstractObject
attr_accessor :name
def initialize(data)
self.name = fetch_value(data, "name")
super
end
end
# - ActionTestPlanRunSummary
# * Supertype: ActionAbstractTestSummary
# * Kind: object
# * Properties:
# + testableSummaries: [ActionTestableSummary]
class ActionTestPlanRunSummary < ActionAbstractTestSummary
attr_accessor :testable_summaries
def initialize(data)
self.testable_summaries = fetch_values(data, "testableSummaries").map do |summary_data|
ActionTestableSummary.new(summary_data)
end
super
end
end
# - ActionTestableSummary
# * Supertype: ActionAbstractTestSummary
# * Kind: object
# * Properties:
# + projectRelativePath: String?
# + targetName: String?
# + testKind: String?
# + tests: [ActionTestSummaryIdentifiableObject]
# + diagnosticsDirectoryName: String?
# + failureSummaries: [ActionTestFailureSummary]
# + testLanguage: String?
# + testRegion: String?
class ActionTestableSummary < ActionAbstractTestSummary
attr_accessor :project_relative_path
attr_accessor :target_name
attr_accessor :test_kind
attr_accessor :tests
def initialize(data)
self.project_relative_path = fetch_value(data, "projectRelativePath")
self.target_name = fetch_value(data, "targetName")
self.test_kind = fetch_value(data, "testKind")
self.tests = fetch_values(data, "tests").map do |tests_data|
ActionTestSummaryIdentifiableObject.create(tests_data, self)
end
super
end
def all_tests
return tests.map(&:all_subtests).flatten
end
end
# - ActionTestSummaryIdentifiableObject
# * Supertype: ActionAbstractTestSummary
# * Kind: object
# * Properties:
# + identifier: String?
class ActionTestSummaryIdentifiableObject < ActionAbstractTestSummary
attr_accessor :identifier
attr_accessor :parent
def initialize(data, parent)
self.identifier = fetch_value(data, "identifier")
self.parent = parent
super(data)
end
def all_subtests
raise "Not overridden"
end
def self.create(data, parent)
type = data["_type"]["_name"]
if type == "ActionTestSummaryGroup"
return ActionTestSummaryGroup.new(data, parent)
elsif type == "ActionTestMetadata"
return ActionTestMetadata.new(data, parent)
else
raise "Unsupported type: #{type}"
end
end
end
# - ActionTestSummaryGroup
# * Supertype: ActionTestSummaryIdentifiableObject
# * Kind: object
# * Properties:
# + duration: Double
# + subtests: [ActionTestSummaryIdentifiableObject]
class ActionTestSummaryGroup < ActionTestSummaryIdentifiableObject
attr_accessor :duration
attr_accessor :subtests
def initialize(data, parent)
self.duration = fetch_value(data, "duration").to_f
self.subtests = fetch_values(data, "subtests").map do |subtests_data|
ActionTestSummaryIdentifiableObject.create(subtests_data, self)
end
super(data, parent)
end
def all_subtests
return subtests.map(&:all_subtests).flatten
end
end
# - ActionTestMetadata
# * Supertype: ActionTestSummaryIdentifiableObject
# * Kind: object
# * Properties:
# + testStatus: String
# + duration: Double?
# + summaryRef: Reference?
# + performanceMetricsCount: Int
# + failureSummariesCount: Int
# + activitySummariesCount: Int
class ActionTestMetadata < ActionTestSummaryIdentifiableObject
attr_accessor :test_status
attr_accessor :duration
attr_accessor :performance_metrics_count
attr_accessor :failure_summaries_count
attr_accessor :activity_summaries_count
def initialize(data, parent)
self.test_status = fetch_value(data, "testStatus")
self.duration = fetch_value(data, "duration").to_f
self.performance_metrics_count = fetch_value(data, "performanceMetricsCount")
self.failure_summaries_count = fetch_value(data, "failureSummariesCount")
self.activity_summaries_count = fetch_value(data, "activitySummariesCount")
super(data, parent)
end
def all_subtests
return [self]
end
def find_failure(failures)
if self.test_status == "Failure"
# Tries to match failure on test case name
# Example TestFailureIssueSummary:
# producingTarget: "TestThisDude"
# test_case_name: "TestThisDude.testFailureJosh2()" (when Swift)
# or "-[TestThisDudeTests testFailureJosh2]" (when Objective-C)
# Example ActionTestMetadata
# identifier: "TestThisDude/testFailureJosh2()" (when Swift)
# or identifier: "TestThisDude/testFailureJosh2" (when Objective-C)
found_failure = failures.find do |failure|
# Clean test_case_name to match identifier format
# Sanitize for Swift by replacing "." for "/"
# Sanitize for Objective-C by removing "-", "[", "]", and replacing " " for ?/
sanitized_test_case_name = failure.test_case_name
.tr(".", "/")
.tr("-", "")
.tr("[", "")
.tr("]", "")
.tr(" ", "/")
self.identifier == sanitized_test_case_name
end
return found_failure
else
return nil
end
end
end
# - ActionsInvocationRecord
# * Kind: object
# * Properties:
# + metadataRef: Reference?
# + metrics: ResultMetrics
# + issues: ResultIssueSummaries
# + actions: [ActionRecord]
# + archive: ArchiveInfo?
class ActionsInvocationRecord < AbstractObject
attr_accessor :actions
attr_accessor :issues
def initialize(data)
self.actions = fetch_values(data, "actions").map do |action_data|
ActionRecord.new(action_data)
end
self.issues = ResultIssueSummaries.new(data["issues"])
super
end
end
# - ActionRecord
# * Kind: object
# * Properties:
# + schemeCommandName: String
# + schemeTaskName: String
# + title: String?
# + startedTime: Date
# + endedTime: Date
# + runDestination: ActionRunDestinationRecord
# + buildResult: ActionResult
# + actionResult: ActionResult
class ActionRecord < AbstractObject
attr_accessor :scheme_command_name
attr_accessor :scheme_task_name
attr_accessor :title
attr_accessor :build_result
attr_accessor :action_result
def initialize(data)
self.scheme_command_name = fetch_value(data, "schemeCommandName")
self.scheme_task_name = fetch_value(data, "schemeTaskName")
self.title = fetch_value(data, "title")
self.build_result = ActionResult.new(data["buildResult"])
self.action_result = ActionResult.new(data["actionResult"])
super
end
end
# - ActionResult
# * Kind: object
# * Properties:
# + resultName: String
# + status: String
# + metrics: ResultMetrics
# + issues: ResultIssueSummaries
# + coverage: CodeCoverageInfo
# + timelineRef: Reference?
# + logRef: Reference?
# + testsRef: Reference?
# + diagnosticsRef: Reference?
class ActionResult < AbstractObject
attr_accessor :result_name
attr_accessor :status
attr_accessor :issues
attr_accessor :timeline_ref
attr_accessor :log_ref
attr_accessor :tests_ref
attr_accessor :diagnostics_ref
def initialize(data)
self.result_name = fetch_value(data, "resultName")
self.status = fetch_value(data, "status")
self.issues = ResultIssueSummaries.new(data["issues"])
self.timeline_ref = Reference.new(data["timelineRef"]) if data["timelineRef"]
self.log_ref = Reference.new(data["logRef"]) if data["logRef"]
self.tests_ref = Reference.new(data["testsRef"]) if data["testsRef"]
self.diagnostics_ref = Reference.new(data["diagnosticsRef"]) if data["diagnosticsRef"]
super
end
end
# - Reference
# * Kind: object
# * Properties:
# + id: String
# + targetType: TypeDefinition?
class Reference < AbstractObject
attr_accessor :id
attr_accessor :target_type
def initialize(data)
self.id = fetch_value(data, "id")
self.target_type = TypeDefinition.new(data["targetType"]) if data["targetType"]
super
end
end
# - TypeDefinition
# * Kind: object
# * Properties:
# + name: String
# + supertype: TypeDefinition?
class TypeDefinition < AbstractObject
attr_accessor :name
attr_accessor :supertype
def initialize(data)
self.name = fetch_value(data, "name")
self.supertype = TypeDefinition.new(data["supertype"]) if data["supertype"]
super
end
end
# - DocumentLocation
# * Kind: object
# * Properties:
# + url: String
# + concreteTypeName: String
class DocumentLocation < AbstractObject
attr_accessor :url
attr_accessor :concrete_type_name
def initialize(data)
self.url = fetch_value(data, "url")
self.concrete_type_name = data["concreteTypeName"]["_value"]
super
end
end
# - IssueSummary
# * Kind: object
# * Properties:
# + issueType: String
# + message: String
# + producingTarget: String?
# + documentLocationInCreatingWorkspace: DocumentLocation?
class IssueSummary < AbstractObject
attr_accessor :issue_type
attr_accessor :message
attr_accessor :producing_target
attr_accessor :document_location_in_creating_workspace
def initialize(data)
self.issue_type = fetch_value(data, "issueType")
self.message = fetch_value(data, "message")
self.producing_target = fetch_value(data, "producingTarget")
self.document_location_in_creating_workspace = DocumentLocation.new(data["documentLocationInCreatingWorkspace"]) if data["documentLocationInCreatingWorkspace"]
super
end
end
# - ResultIssueSummaries
# * Kind: object
# * Properties:
# + analyzerWarningSummaries: [IssueSummary]
# + errorSummaries: [IssueSummary]
# + testFailureSummaries: [TestFailureIssueSummary]
# + warningSummaries: [IssueSummary]
class ResultIssueSummaries < AbstractObject
attr_accessor :analyzer_warning_summaries
attr_accessor :error_summaries
attr_accessor :test_failure_summaries
attr_accessor :warning_summaries
def initialize(data)
self.analyzer_warning_summaries = fetch_values(data, "analyzerWarningSummaries").map do |summary_data|
IssueSummary.new(summary_data)
end
self.error_summaries = fetch_values(data, "errorSummaries").map do |summary_data|
IssueSummary.new(summary_data)
end
self.test_failure_summaries = fetch_values(data, "testFailureSummaries").map do |summary_data|
TestFailureIssueSummary.new(summary_data)
end
self.warning_summaries = fetch_values(data, "warningSummaries").map do |summary_data|
IssueSummary.new(summary_data)
end
super
end
end
# - TestFailureIssueSummary
# * Supertype: IssueSummary
# * Kind: object
# * Properties:
# + testCaseName: String
class TestFailureIssueSummary < IssueSummary
attr_accessor :test_case_name
def initialize(data)
self.test_case_name = fetch_value(data, "testCaseName")
super
end
def failure_message
new_message = self.message
if self.document_location_in_creating_workspace
file_path = self.document_location_in_creating_workspace.url.gsub("file://", "")
new_message += " (#{file_path})"
end
return new_message
end
end
end | true |
73667c2973f105a92d6048b54fc5db02b2e8511b | Ruby | a1exwang/jumping_horses | /produce_data.rb | UTF-8 | 562 | 3.40625 | 3 | [] | no_license |
def near(a, b)
x = a.to_i / 10
y = a.to_i % 10
i = b.to_i / 10
j = b.to_i % 10
x - i != 0 && y - j != 0 && ((x-i).abs + (y-j).abs) == 3
end
def construct_table(size)
table = {}
size.times do |x|
size.times do |y|
if (x + y) % 2 == 0
line = {}
size.times do |i|
size.times do |j|
if (i + j) % 2 == 1 && near("#{x}#{y}", "#{i}#{j}")
line["#{i}#{j}"] = 1
end
end
end
table["#{x}#{y}"] = line if line.keys.count > 0
end
end
end
table
end | true |
73fa9d46e489e8b47b903329edefba4e4046e8d5 | Ruby | leo11511/eup_repos | /ruby/code/movie.rb | UTF-8 | 521 | 3.125 | 3 | [] | no_license | class Movie
# attr_writer :title
# attr_reader :title
attr_accessor :title
def initialize(ptitle, prank=0)
@title =ptitle.capitalize
@rank = prank
end
def status
hit? ? "Hit" : "Flop"
end
# # def title
# # @title
# # end
# attr_reader :title
# # def title=(ptitle)
# # @title = ptitle
# # end
# attr_writer :title
def thumbs_up
@rank += 1
#@rank = @rank + 1
end
def thumbs_down
@rank -= 1
end
def to_s
"#{@title} hat ein Ranking von: #{@rank}."
end
end | true |
7cbfa8ea2b39edc2e9fd6806e5e04d3b2624c6ec | Ruby | jackrobbins1/school-domain-chicago-web-career-040119 | /lib/school.rb | UTF-8 | 764 | 3.9375 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # code here!
require "pry"
class School
attr_reader :roster, :name
# @roster = {}
def initialize(name)
@name = name
@roster = {}
end
def add_student(name, grade)
unless roster.has_key?(grade)
roster[grade] = []
end
roster[grade] << name
end
def grade(num)
roster[num]
end
def sort
new_hash = {}
# binding.pry
roster.keys.sort.each {|el|
new_hash[el] = roster[el].sort
}
# roster.each { |keyz, valz|
# new_hash[keyz] << valz.sort
# }
new_hash
# binding.pry
end
end
school = School.new("Bayside High School")
school.add_student("Homer Simpson", 9)
school.add_student("Jeff Baird", 10)
school.add_student("Avi Flombaum", 10)
school.add_student("Blake Johnson", 7)
# binding.pry
"wacky"
| true |
669dc0f38a83ccc6da89eebc89774dddce9dde56 | Ruby | erikasinio/Test | /RUBY ACTIVITIES/ACTIVITY 4/confection.rb | UTF-8 | 334 | 3.296875 | 3 | [] | no_license | class Confection
def prepare
puts "Baking at 350 degrees for 25 minutes"
end
end
class Cupcake < Confection
def prepare
super
puts "Applying Frosting"
end
end
class BananaCake < Confection; end
cupcake = Cupcake.new
puts cupcake.prepare
banana_cake = BananaCake.new
puts banana_cake.prepare | true |
fe402d01681e71a43384afd64ce2b5f96b405958 | Ruby | Vizzuality/ushelf | /rmagick/ruby/1.8/gems/refinerycms-i18n-0.9.8.7/config/locales/cz.rb | UTF-8 | 5,191 | 2.765625 | 3 | [
"MIT"
] | permissive | # Czech translations for Ruby on Rails
# by Karel Minařík (karmi@karmi.cz)
{ :'cz' => {
# ActiveSupport
:support => {
:array => {
:two_words_connector => ' a ',
:sentence_connector => 'a',
:skip_last_comma => true
}
},
# Date
:date => {
:formats => {
:default => "%d. %m. %Y",
:short => "%d %b",
:long => "%d. %B %Y",
},
:day_names => %w{Neděle Pondělí Úterý Středa Čtvrtek Pátek Sobota},
:abbr_day_names => %w{Ne Po Út St Čt Pá So},
:month_names => %w{~ Leden Únor Březen Duben Květen Červen Červenec Srpen Září Říjen Listopad Prosinec},
:abbr_month_names => %w{~ Led Úno Bře Dub Kvě Čvn Čvc Srp Zář Říj Lis Pro},
:order => [:day, :month, :year]
},
# Time
:time => {
:formats => {
:default => "%a %d. %B %Y %H:%M %z",
:short => "%d. %m. %H:%M",
:long => "%A %d. %B %Y %H:%M",
},
:am => 'am',
:pm => 'pm'
},
# Numbers
:number => {
:format => {
:precision => 3,
:separator => '.',
:delimiter => ','
},
:currency => {
:format => {
:unit => 'Kč',
:precision => 2,
:format => '%n %u',
:separator => ",",
:delimiter => " ",
}
},
:human => {
:format => {
:precision => 1,
:delimiter => ''
},
:storage_units => {
:format => "%n %u",
:units => {
:byte => "B",
:kb => "KB",
:mb => "MB",
:gb => "GB",
:tb => "TB",
}
}
},
:percentage => {
:format => {
:delimiter => ''
}
},
:precision => {
:format => {
:delimiter => ''
}
}
},
# Distance of time ... helper
# NOTE: In Czech language, these values are different for the past and for the future. Preference has been given to past here.
:datetime => {
:distance_in_words => {
:half_a_minute => 'půl minutou',
:less_than_x_seconds => {
:one => 'asi před sekundou',
:other => 'asi před %{count} sekundami'
},
:x_seconds => {
:one => 'sekundou',
:other => '%{count} sekundami'
},
:less_than_x_minutes => {
:one => 'před necelou minutou',
:other => 'před ani ne %{count} minutami'
},
:x_minutes => {
:one => 'minutou',
:other => '%{count} minutami'
},
:about_x_hours => {
:one => 'asi hodinou',
:other => 'asi %{count} hodinami'
},
:x_days => {
:one => '24 hodinami',
:other => '%{count} dny'
},
:about_x_months => {
:one => 'asi měsícem',
:other => 'asi %{count} měsíci'
},
:x_months => {
:one => 'měsícem',
:other => '%{count} měsíci'
},
:about_x_years => {
:one => 'asi rokem',
:other => 'asi %{count} roky'
},
:over_x_years => {
:one => 'více než před rokem',
:other => 'více než %{count} roky'
}
}
},
# ActiveRecord validation messages
:activerecord => {
:errors => {
:messages => {
:inclusion => "není v seznamu povolených hodnot",
:exclusion => "je vyhrazeno pro jiný účel",
:invalid => "není platná hodnota",
:confirmation => "nebylo potvrzeno",
:accepted => "musí být potvrzeno",
:empty => "nesmí být prázdný/é",
:blank => "je povinná položka", # alternate formulation: "is required"
:too_long => "je příliš dlouhá/ý (max. %{count} znaků)",
:too_short => "je příliš krátký/á (min. %{count} znaků)",
:wrong_length => "nemá správnou délku (očekáváno %{count} znaků)",
:taken => "již databáze obsahuje",
:not_a_number => "není číslo",
:greater_than => "musí být větší než %{count}",
:greater_than_or_equal_to => "musí být větší nebo rovno %{count}",
:equal_to => "musí být rovno %{count}",
:less_than => "musí být méně než %{count}",
:less_than_or_equal_to => "musí být méně nebo rovno %{count}",
:odd => "musí být liché číslo",
:even => "musí být sudé číslo"
},
:template => {
:header => {
:one => "Při ukládání objektu %{model} došlo k chybám a nebylo jej možné uložit",
:other => "Při ukládání objektu %{model} došlo ke %{count} chybám a nebylo možné jej uložit"
},
:body => "Následující pole obsahují chybně vyplněné údaje:"
}
}
}
}
}
| true |
c5ae44bbbcd9db284e975d9a0ead984c8515de5a | Ruby | css1990x/EulerProblems | /euler_9/euler_9.rb | UTF-8 | 343 | 3.078125 | 3 | [] | no_license | def euler_9
(1...500).to_a.each do |a|
(1...500).to_a.each do |b|
(1...500).to_a.each do |c|
if ((a ** 2) + (b ** 2) == (c ** 2)) && ((a + b + c) == 1000)
return "the solution to euler 9 is #{(a * b * c)} "
end
end
end
end
end
p euler_9 | true |
1fbe4ca15e7c49e1f54907662910f3d55ea9be5b | Ruby | fionahiklas/wh-questions | /test/q2/test_calculate_coins_objects.rb | UTF-8 | 1,091 | 2.75 | 3 | [
"MIT"
] | permissive | require 'test/unit'
require 'q2/calculate_coins'
class TestCalculateCoinsObjects < Test::Unit::TestCase
def test_coin_and_multiplier_new
result = Q2::CoinAndMultiplier.new
assert(result!=nil, "Result was nil")
assert(result.coin_index == 0, "Coin index was #{result.coin_index}")
assert(result.multiplier == 0, "Multipler was #{result.multiplier}")
end
def test_coin_and_multiplier_new_with_values
result = Q2::CoinAndMultiplier.new(1,2)
assert(result!=nil, "Result was nil")
assert(result.coin_index == 1, "Coin index was #{result.coin_index}")
assert(result.multiplier == 2, "Multipler was #{result.multiplier}")
end
def test_combination_new
result = Q2::Combination.new
assert(result!=nil, "Result was nil")
assert(result.combinations == 0, "Combinations #{result.combinations}")
end
def test_combination_add
coin_and_multiplier = Q2::CoinAndMultiplier.new(3,5)
result = Q2::Combination.new
result.add(coin_and_multiplier)
assert(result.combinations == 1, "Combinations #{result.combinations}")
end
end
| true |
b8df7ec96efc677a387c1b51f5562f36bf659989 | Ruby | BrianTheCoder/cool_breeze | /lib/cool_breeze/association.rb | UTF-8 | 989 | 2.8125 | 3 | [
"MIT"
] | permissive | module CoolBreeze
class Association
include Enumerable
def initialize(klass, name, options = {})
@list_name = "#{name}_list"
@klass = klass
klass.instance_index :"#{name}_list", :list
end
def for(instance)
@list = instance.method(@list_name)
self
end
def add(obj)
@list.call.push(obj.key)
end
def remove(obj)
@list.call.remove(1,obj.key)
end
def destroy(obj)
remove(obj)
obj.destroy
end
def get(start = 0, stop = -1)
keys = @list.call.range(start, stop)
return [] if keys.blank?
keys.map{|k| @klass.get k}
end
def size
@list.call.length
end
def first
key = @list.call.range(0,1)
@klass.get(key) unless key.blank?
end
def each
values = @list.call.range(0,-1)
return if values.blank?
values.each do |val|
yield @klass.get val
end
end
end
end | true |
49e709262457268486080259a7ca6be9d919e762 | Ruby | bpeek/launch_school | /intro_to_programming_exercises/end_of_book_8.rb | UTF-8 | 340 | 2.5625 | 3 | [] | no_license | hash_1 = {crabs: "pinch", bees: "sting", squids: "strangle", boas: "squirt ink", penguins: "if is ain't black and white, peck, scratch, and bite"}
hash_2 = {:crabs => "pinch", :bees => "sting", :squids => "strangle", :boas => "squirt ink", :penguins => "if is ain't black and white, peck, scratch, and bite"}
print hash_1
puts
print hash_2 | true |
f222e1b979130012401c2ce9ce552d4cca7dc38c | Ruby | tatsuki-kamei/euler | /problem6.rb | UTF-8 | 154 | 3.46875 | 3 | [] | no_license | a = 0
b = 0
puts "計算したい数字を入力してください"
n = gets.to_i
n.times do |i|
a += (i+1)**2
b += i+1
end
b = b**2
sum = b -a
puts sum | true |
3cf4c91aa02363058cfb6eb445ae65011738727b | Ruby | kirster/test-guru | /app/models/badge_criteria_check.rb | UTF-8 | 1,455 | 2.703125 | 3 | [] | no_license | class BadgeCriteriaCheck
class << self
def check_criterias(user)
Badge.all.each do |badge|
case badge.rule_name
when 'Category' then category_rule(user, badge)
when 'Level' then level_rule(user, badge)
when 'Attempt' then attempt_rule(user, badge)
end
end
end
private
def category_rule(user, badge)
category = Category.find_by(title: badge.rule_value)
user.badges.push(badge) if passed_category_rule?(user, category)
end
def level_rule(user, badge)
level = badge.rule_value.to_i
user.badges.push(badge) if passed_level_rule?(user, level)
end
def attempt_rule(user, badge)
attempt = badge.rule_value.to_i
user.badges.push(badge) if passed_attempt_rule?(user, attempt)
end
def passed_category_rule?(user, category)
user.tests.where('category_id=? AND test_passages.success=?', category.id, true)
.pluck(:title).uniq.count == Test.for_category(category.title).count
end
def passed_level_rule?(user, level)
user.tests.where('level=? AND test_passages.success=?', level, true)
.pluck(:title).uniq.count == Test.for_level(level).count
end
def passed_attempt_rule?(user, attempt)
title = user.test_passages.last.test.title
user.tests.where('title=? AND test_passages.success=?', title, true).count == attempt
end
end
end | true |
9771d3b09d8da8a3c2fb1a7d1c0c05370325845d | Ruby | maciejk77/boris-bikes_pair | /spec/docking_station_spec.rb | UTF-8 | 1,370 | 2.84375 | 3 | [] | no_license | require './lib/docking_station'
# class ContainerHolder; include BikeContainer; end
# describe BikeContainer do
# let(:bike) { Bike.new }
# let(:holder) { ContainerHolder.new }
# it 'should accept a bike' do
# expect(holder.bike_count).to eq(0)
# holder.dock(bike)
# expect(holder.bike_count).to eq(1)
# end
describe DockingStation do
subject { described_class.new(capacity: 123) }
it 'can set a default capcity on initialising' do
expect(subject.capacity).to eq(123)
end
end
# require 'docking_station'
# describe DockingStation do
# it { is_expected.to respond_to :release_bike }
# it 'can dock a bike' do
# expect(subject.dock :bike).to be nil
# end
# it 'raises error when no bikes available' do
# expect { subject.release_bike }.to raise_error 'No Bikes Available'
# end
# it "releases bike that are not broken" do
# subject.dock double :bike, broken?: false
# bike = subject.release_bike
# expect(bike).not_to be_broken
# end
# it 'raises an error when full' do
# 20.times { subject.dock double :bike }
# expect { subject.dock double :bike }.to raise_error 'Station Full'
# end
# it 'does not release broken bikes' do
# broken_bike = double :bike, broken?: true
# subject.dock broken_bike
# expect { subject.release_bike }.to raise_error 'No Bikes Available'
# end
# end
| true |
b507c0a290d75733805362f0d97f9b5107fbb6d0 | Ruby | orfah/samples | /s/1/loadbalancer/lib/balancer/loadbalancer.rb | UTF-8 | 6,401 | 2.859375 | 3 | [] | no_license | #
# LoadBalancer class.
#
# Sits in front of any number of hosts, each of which must be
# configured with an address and healthcheck_target.
#
# LoadBalancer may be configured to return the next host as:
# - Round-Robin (default)
# - Load Feedback
# - Random
# - Asymetric Load
#
# A check of all host target files will be performed every +ttl+
# seconds, by default 300s. This check may also be triggered
# manually, and will reset the ttl timer.
#
# After checking hosts, the state of the world as seen by the balancer
# will be written to /tmp for inspection. State change notification
# for each host can be included by setting the alert_hook attribute.
#
# Hosts may be dynamically added or removed by calling add_host
# and remove_host, respectively.
#
# EX:
# lb = Balancer::LoadBalancer.new('my-balancer-cname')
# lb.hosts = [host1, host2, host3]
# next_host = lb.host
# next_next_host = lb.host
#
# lb.add_host host4
# lb.remove_host host1
#
# lb.state # [ host2.to_s, host3.to_s, host4.to_s ]
#
module Balancer
class LoadBalancer
attr_accessor :cname
attr_accessor :mode
attr_accessor :ttl
attr_accessor :persistent
attr_accessor :alert_hooks
ROUND_ROBIN_MODE = 'round-robin'
LFB_MODE = 'lfb'
RANDOM_MODE = 'random'
ASYM_MODE = 'asym'
def initialize(*args, &block)
if args.flatten.first.respond_to?(:each_pair)
init_with_hash(args.flatten.first)
else
cname = args.flatten[0].to_s
end
if block_given?
instance_eval(&block)
end
@hosts = []
@alert_hooks = []
@state_handler = pick_state_handler
@state_handler.name = cname
end
def pick_state_handler
$HANDLERS.each do |state_handler|
if state_handler.available?
return state_handler.new
end
end
raise RuntimeError, "No available state handler!"
end
def init_with_hash(hash)
hash.each_pair do |arg, value|
arg = arg.downcase.to_sym
send(arg.to_s + '=', value) if self.respond_to?(arg)
end
end
def config(config_path)
raise "Config file does not exist! #{config_path}" unless File.exist? config_path
c = YAML.load_file(config_path)
hosts = c.delete('hosts') || []
init_with_hash(c)
hosts.each do |h|
hh = Host.new(h)
add_host(hh)
end
end
# return the next host to route traffic to
def host(client=nil)
raise "No configured hosts!" if @hosts.length == 0
# check host state if ttl is expired
state
case mode
when ROUND_ROBIN_MODE
# hosts array is a computed attribute, so keep track of an index instead
@_host_index ||= 0
@_host_index %= hosts.length
h = hosts[@_host_index]
@_host_index += 1
when LFB_MODE
h = hosts.sort { |a, b| (b.load_target - b.load) <=> (a.load_target - a.load) }.first
when RANDOM_MODE
h = hosts.sample
when ASYM_MODE
total = hosts.reduce(0) { |sum, host| sum + host.asym_target }
loop_count = 0
until h
h = hosts.detect { |host| r = Kernel.rand(total) < host.asym_target }
# simple bailout if we looped and the rng bites us
h = hosts.first if loop_count > 10
loop_count += 1
end
end
if persistent and client
h = persist(client, h)
end
h
end
def hosts(include_down=false)
selected_hosts = include_down ? @hosts : @hosts.select { |h| h.up? }
# all down == all up
selected_hosts = @hosts if selected_hosts.empty?
selected_hosts
end
# more error checking here?
def hosts=(val)
@hosts = val
end
#
# Performs a polling of all hosts behind this load balancer.
#
def check
@state_handler.last_check = Time.now
hydra = Typhoeus::Hydra.new
@hosts.each do |h|
hydra.queue h.healthcheck_request
end
hydra.run
alert_state_change
log_state
end
def log_state
state = {}
@hosts.each do |h|
state[h.id] = h.state
end
write_state(state)
state
end
def alert_state_change
unless @alert_hooks.nil?
@alert_hooks.each do |alert_hook|
@hosts.each do |h|
if state[h.id] and state[h.id] != h.state
alert_hook.call(h)
end
end
end
end
true
end
# Print out the state of the hosts behind this load balancer.
# Kicks off a check if the ttl has expired.
def state
ttl_expired? ? check : @state_handler.read(state_path)
end
def ttl_expired?
last_check = @state_handler.last_check
last_check.nil? or last_check < (Time.now - ttl)
end
def mode
@mode || ROUND_ROBIN_MODE
end
def mode=(val)
# guarantee mode is valid
unless [ROUND_ROBIN_MODE, LFB_MODE, RANDOM_MODE, ASYM_MODE].include? val
val = ROUND_ROBIN_MODE
end
@mode = val
end
def persistent
@persistent || false
end
def persistent=(val)
@persistent = val
end
# default 5m ttl
def ttl
@ttl || 300
end
def ttl=(val)
val = 300 if val < 5
@ttl = val
end
def add_host(host)
@hosts << host
end
def remove_host(host)
@hosts.reject! { |h| h.hash == host.hash }
end
def write_state(state)
@state_handler.write(state_path, state)
if persistent and @persist_map
@state_handler.write(persist_map_path, @persist_map)
end
end
def state_path
"/tmp/#{cname}-balancer-state.json"
end
def persist_map_path
"/tmp/#{cname}-persist-map.json"
end
def persist(client, assigned_host, force=false)
@persist_map ||= @state_handler.read(persist_map_path)
mapped_host = find_host(@persist_map[client])
if force or mapped_host.nil? or mapped_host.down?
@persist_map[client] = assigned_host.hash
mapped_host = assigned_host
end
mapped_host
end
# assign host to client even if a previous match exists
def persist!(client, assigned_host)
persist(client, assigned_host, true)
end
def find_host(host_hash)
@hosts.find { |h| h.hash == host_hash }
end
end
end
| true |
4b9a82670593f14aaeac954737a565cc74bc9ada | Ruby | sarahl3/kwk-l1-looping-while-until-kwk-students-l1-bal-061818 | /lib/while.rb | UTF-8 | 121 | 2.5625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def using_while
levitation_force = 6
while levitation_force <= 9
puts "Wingardium Leviosa"
levitation_force += 1
end
| true |
30572674b90e0cd4b589625e899fdabcc505df7b | Ruby | jhartwell/ironruby | /Tests/Experiments/19/opt_block_reference.rb | UTF-8 | 181 | 2.890625 | 3 | [] | no_license | =begin
def foo
return 1,2,
end
def bar *args, &b
p args, b
end
x = -> {}
bar foo, not(), not(1), &x
=end
def foo
x = (1 ? return : return; 2)
end
foo | true |
db6333f05e21c999cbb3f18645a6f827dc6d996e | Ruby | shelleyyz/WDi28-Homework | /shelley_zhang/week_04/day_01/calculator.rb | UTF-8 | 3,570 | 4.40625 | 4 | [] | no_license | # Explanation
# You will be building a calculator. A calculator can perform multiple arithmetic operations. Your function should allow the user to choose which operation is expected, enter in the values to perform the operation on, and ultimately view the result.
# Specification:
# A user should be given a menu of operations
# A user should be able to choose from the menu
# A user should be able to enter numbers to perform the operation on
# A user should be shown the result
# This process should continue until the user selects a quit option from the menu
# Phase 1
# Calculator functionality
# Calculator should be able to do basic arithmetic (+,-, *, /)
# Mortgage Calculator
# Calculate the monthly required payment given the other variables as input (look up the necessary variables)
#
# BMI Calculator
# Calculate the body mass index (BMI) for an individual, given their height and weight
#
# Trip Calculator
# Calculate a trip time and cost given inputs for
#
# distance
# miles per gallon
# price per gallon
# speed in miles per hour
# require 'pry'
def show_menu
puts "Calculator"
puts "-=" * 40
puts "[a] - Addition"
puts "[b] - Substraction"
puts "[c] - Multiplication"
puts "[d] - Division"
puts "[e] - Exponent"
puts "[f] - Square Root"
puts "[g] - Mortgage"
puts "[h] - BMI"
puts "[i] - Trip"
puts "[q] - Quit"
print "Enter your selection: "
end
show_menu
menu_choice = gets.chomp.downcase
until menu_choice == 'q'
case menu_choice
when 'a'
puts "Enter your first number: "
a = gets.to_i
puts "Enter your second number: "
b = gets.to_i
a + b
puts "the answer is #{a + b}"
when 'b'
puts "Enter your first number: "
a = gets.to_i
puts "Enter your second number: "
b = gets.to_i
a - b
puts "the answer is #{a - b}"
when 'c'
puts "Enter your first number: "
a = gets.to_i
puts "Enter your second number: "
b = gets.to_i
puts "the answer is #{a * b}"
when 'd'
puts "Enter your first number: "
a = gets.to_i
puts "Enter your second number: "
b = gets.to_i
puts "the answer is #{a / b}"
when 'e'
puts "Enter your base number: "
a = gets.to_i
puts "Enter your exponent: "
b = gets.to_i
puts "the answer is #{a ** b}"
when 'f'
puts "Find the square root of: "
a = gets.to_i
puts "the answer is #{Integer.sqrt(a)}"
when 'g'
puts "Enter your principal: "
principal = gets.to_f
puts "Enter your annual interest: "
annual_interest = (gets.to_f) / 100
monthly_interest = annual_interest / 12
puts "Enter how many monthly payments: "
number_payments = gets.to_f * 12
monthly_payment = principal * ( ( monthly_interest * ((1 + monthly_interest) ** number_payments) ) / ( ( (1 + monthly_interest) ** number_payments) - 1) )
puts "the answer is #{monthly_payment}"
when 'h'
puts "Enter your weight in KG: "
weight = gets.to_f
puts "Enter your height in Metres: "
height = gets.to_f
puts "your BMI is #{(weight / (height ** 2))}"
when 'i'
puts "Enter your distance"
d = gets.to_f
puts "Enter your miles per gallon"
m = gets.to_f
puts "Enter your price per gallon"
p = gets.to_f
puts "Enter your speed in miles per hour"
s = gets.to_f
puts "your trip time is #{d / s}"
puts "your trip cost is #{p * m}"
else
puts "Invalid selection"
end
show_menu
menu_choice = gets.chomp.downcase
end
puts "Thank you for using crappy calculator."
#gem rainbow ruby - gem install rainbow and require rainbow
| true |
06495ec7c9ad5b99e01ad08033eac393c4025f72 | Ruby | deepigarg/rubyx | /lib/ruby/statement.rb | UTF-8 | 1,037 | 3.28125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | module Ruby
# Base class for all statements in the tree. Derived classes correspond to known language
# constructs
#
# Compilers or compiler passes are written by implementing methods.
#
class Statement
# Many statements exist in the sol layer in quite a similar arrangement
# Especially for different types of assignment we can abstract the creation
# of the sol, by using the right class to instantiate, the "sol_brother"
# Ie same class_name, but in the Sol module
def sol_brother
eval "Sol::#{class_name}"
end
# return the class name without the module
# used to evaluate the sol_brother
def class_name
self.class.name.split("::").last
end
# helper method for formatting source code
# depth is the depth in the tree (os the ast)
# and the string are the ones to be indented (2 spaces)
def at_depth(depth , lines)
prefix = " " * 2 * depth
strings = lines.split("\n")
strings.collect{|str| prefix + str}.join("\n")
end
end
end
| true |
e18099937d8bb60d2b1f2f260c446b9215cb7075 | Ruby | lbvf50mobile/til | /20230120_Friday/20230120.rb | UTF-8 | 801 | 3.46875 | 3 | [] | no_license | # Leetcode: 491. Non-decreasing Subsequences.
# https://leetcode.com/problems/non-decreasing-subsequences/
# = = = = = = = = = = = = = =
# Accepted.
# Thanks God, Jesus Christ!
# = = = = = = = = = = = = = =
# Runtime: 349 ms, faster than 100.00% of Ruby online submissions for Non-decreasing Subsequences.
# Memory Usage: 234.9 MB, less than 100.00% of Ruby online submissions for Non-decreasing Subsequences.
# @param {Integer[]} nums
# @return {Integer[][]}
def find_subsequences(nums)
require 'set'
@a = nums
@answer = Set.new()
@path = []
(0...@a.size-1).each do |i|
dfs(i)
end
return @answer.to_a
end
def dfs(i)
@path.push(@a[i])
if 1 < @path.size
@answer.add(@path.clone)
end
(i+1...@a.size).each do |j|
if @a[i] <= @a[j]
dfs(j)
end
end
@path.pop
end
| true |
f9a42980afd3a86bb5a0bff7d90174e61550270e | Ruby | arcanoid/facts_by_date | /lib/facts_by_date.rb | UTF-8 | 6,801 | 2.78125 | 3 | [
"MIT"
] | permissive | require "facts_by_date/version"
module FactsByDate
class Generator
ROOT = File.expand_path("../..", __FILE__)
def self.facts_for_today(options = {})
converted_date = Date.today
facts = []
if File.exist?("#{ROOT}/data/facts/#{converted_date.month}/#{converted_date.day}.json")
file = File.read("#{ROOT}/data/facts/#{converted_date.month}/#{converted_date.day}.json")
data_hash = JSON.parse(file)
facts = data_hash[0]['facts']
# if size option is provided retrieve information only for that size
if options[:size].nil?
facts
else
facts.take(options[:size])
end
else
[]
end
end
def self.facts_for_specific_date(date, options = {})
begin
converted_date = Date.parse(date)
if File.exist?("#{ROOT}/data/facts/#{converted_date.month}/#{converted_date.day}.json")
file = File.read("#{ROOT}/data/facts/#{converted_date.month}/#{converted_date.day}.json")
data_hash = JSON.parse(file)
facts = data_hash[0]['facts']
# if size option is provided retrieve information only for that size
if options[:size].nil?
facts
else
facts.take(options[:size])
end
else
[]
end
rescue ArgumentError
[]
end
end
def self.births_for_today(options = {})
converted_date = Date.today
facts = []
if File.exist?("#{ROOT}/data/births/#{converted_date.month}/#{converted_date.day}.json")
file = File.read("#{ROOT}/data/births/#{converted_date.month}/#{converted_date.day}.json")
data_hash = JSON.parse(file)
facts = data_hash['births']
# if size option is provided retrieve information only for that size
if options[:size].nil?
facts
else
facts.take(options[:size])
end
else
[]
end
end
def self.births_for_specific_date(date, options = {})
begin
converted_date = Date.parse(date)
if File.exist?("#{ROOT}/data/births/#{converted_date.month}/#{converted_date.day}.json")
file = File.read("#{ROOT}/data/births/#{converted_date.month}/#{converted_date.day}.json")
data_hash = JSON.parse(file)
facts = data_hash['births']
# if size option is provided retrieve information only for that size
if options[:size].nil?
facts
else
facts.take(options[:size])
end
else
[]
end
rescue ArgumentError
[]
end
end
def self.deaths_for_today(options = {})
converted_date = Date.today
facts = []
if File.exist?("#{ROOT}/data/deaths/#{converted_date.month}/#{converted_date.day}.json")
file = File.read("#{ROOT}/data/deaths/#{converted_date.month}/#{converted_date.day}.json")
data_hash = JSON.parse(file)
facts = data_hash['deaths']
# if size option is provided retrieve information only for that size
if options[:size].nil?
facts
else
facts.take(options[:size])
end
else
[]
end
end
def self.deaths_for_specific_date(date, options = {})
begin
converted_date = Date.parse(date)
if File.exist?("#{ROOT}/data/deaths/#{converted_date.month}/#{converted_date.day}.json")
file = File.read("#{ROOT}/data/deaths/#{converted_date.month}/#{converted_date.day}.json")
data_hash = JSON.parse(file)
facts = data_hash['deaths']
# if size option is provided retrieve information only for that size
if options[:size].nil?
facts
else
facts.take(options[:size])
end
else
[]
end
rescue ArgumentError
[]
end
end
def self.international_days_for_today(options = {})
converted_date = Date.today
facts = []
if File.exist?("#{ROOT}/data/international_days/#{converted_date.month}/#{converted_date.day}.json")
file = File.read("#{ROOT}/data/international_days/#{converted_date.month}/#{converted_date.day}.json")
data_hash = JSON.parse(file)
facts = data_hash['facts']
# if size option is provided retrieve information only for that size
if options[:size].nil?
facts
else
facts.take(options[:size])
end
else
[]
end
end
def self.international_days_for_specific_date(date, options = {})
begin
converted_date = Date.parse(date)
if File.exist?("#{ROOT}/data/international_days/#{converted_date.month}/#{converted_date.day}.json")
file = File.read("#{ROOT}/data/international_days/#{converted_date.month}/#{converted_date.day}.json")
data_hash = JSON.parse(file)
facts = data_hash['facts']
# if size option is provided retrieve information only for that size
if options[:size].nil?
facts
else
facts.take(options[:size])
end
else
[]
end
rescue ArgumentError
[]
end
end
def self.national_days_for_today(options = {})
converted_date = Date.today
facts = []
if File.exist?("#{ROOT}/data/national_days/#{converted_date.month}/#{converted_date.day}.json")
file = File.read("#{ROOT}/data/national_days/#{converted_date.month}/#{converted_date.day}.json")
data_hash = JSON.parse(file)
facts = data_hash['facts']
# if size option is provided retrieve information only for that size
if options[:size].nil?
facts
else
facts.take(options[:size])
end
else
[]
end
end
def self.national_days_for_specific_date(date, options = {})
begin
converted_date = Date.parse(date)
if File.exist?("#{ROOT}/data/national_days/#{converted_date.month}/#{converted_date.day}.json")
file = File.read("#{ROOT}/data/national_days/#{converted_date.month}/#{converted_date.day}.json")
data_hash = JSON.parse(file)
facts = data_hash['facts']
# if size option is provided retrieve information only for that size
if options[:size].nil?
facts
else
facts.take(options[:size])
end
else
[]
end
rescue ArgumentError
[]
end
end
def self.sources
file_to_read = "#{ROOT}/data/sources.json"
data = []
file = File.read(file_to_read)
data << JSON.parse(file).flatten
data.flatten
end
end
end
| true |
6cf64dfd78fd9c1097bd061bce7e09de6c952117 | Ruby | Angeldude/madlibs | /app/models/template.rb | UTF-8 | 1,168 | 3.21875 | 3 | [] | no_license | class Template < ApplicationRecord
def to_param
title.parameterize
end
def replace_words
original = template(story)
to_replace = words_to_replace(story)
{ original: original, replace: to_replace }
end
def final_story(replacer, indexed)
# replacer should be new inputs zipped with replace
result = story.clone
replacer.each_with_index do |replace, index|
if indexed[index].include?(':')
temp = replace[1].split(':').first
result.sub!(indexed[index], replace[0])
result.gsub!("((#{temp}))", replace[0])
else
result.sub!(indexed[index], replace[0])
end
end
result
end
private
# Small functions that work to remove the parens
# and leave the enclosed string intact
def remove_parens(str)
str.gsub(/[()]/, '')
end
def words_to_replace(str)
template(str).map do |s|
remove_parens(s)
end
end
def template(string)
string.scan(/\(\(.*?\)\)/m)
end
end
| true |
802f58094359187b3061dcd35e9bb2c0a44ce3c1 | Ruby | jerryzlau/july_cohort | /w5d4/intro_javascript_exercises/test.rb | UTF-8 | 1,258 | 3.484375 | 3 | [] | no_license | def twoSum(array)
indices = []
(0...array.length).each do |idx|
(idx+1...array.length).each do |idxx|
indices << [idx,idxx] if array[idx] + array[idxx] == 0
end
end
indices
end
def transpose(array)
result = Array.new(array[0].length) { Array.new(array.length) }
(0..array.length-1).each do |i|
(0..array[0].length-1).each do |j|
result[j][i] = array[i][j]
end
end
result
end
def bubbleSort(array)
array.length.times do
(0...array.length).each do |idx|
if idx+1 < array.length && array[idx] > array[idx+1]
array[idx], array[idx+1] = array[idx+1], array[idx]
end
end
end
array
end
def range(start, end_range)
return [start] if start == end_range
[start] + range(start + 1, end_range)
end
def fib(n)
return [0] if n == 1
return [0,1] if n == 2
result = fib(n-1)
next_fib = result.last + result[result.length - 2]
result << next_fib
end
def my_bsearch(array, target)
return nil if array.length == 0
mid = array.length/2
case array[mid] <=> target
when 0
return mid
when 1
return my_bsearch(array.dup.take(mid), target)
else
search_res = my_bsearch(array.dup.drop(mid+1), target)
search_res.nil? ? nil : mid + 1 + search_res
end
end
| true |
036bcf1fdd9cac7725448a4cc8174debdcb22f4a | Ruby | julissa/railsbridgeboston_dot_org | /lib/eventbrite.rb | UTF-8 | 1,165 | 2.640625 | 3 | [] | no_license | require "httparty"
require_relative "eventbrite/event"
require_relative "eventbrite/null_event"
class Eventbrite
include HTTParty
base_uri "https://www.eventbriteapi.com/v3"
def upcoming_event
event_list.first
end
private
def event_list
if user_events_response.success? && !events_from_response.empty?
events_from_response.map do |event|
Eventbrite::Event.new(event)
end
else
[Eventbrite::NullEvent.new]
end
end
def events_from_response
user_events_response["events"]
end
def user_events_response
@user_events_response ||= self.class.get(
events_owned_by_user_api_url,
query: credentials.merge(event_criteria)
)
end
def events_owned_by_user_api_url
"/users/#{user_id}/owned_events/"
end
def user_id
if user_response.success?
user_response["id"]
end
end
def user_response
@user_response ||= self.class.get(user_profile_api_url, query: credentials)
end
def user_profile_api_url
"/users/me"
end
def credentials
{ token: ENV.fetch("EVENTBRITE_ACCESS_TOKEN") }
end
def event_criteria
{ status: "live" }
end
end
| true |
5b2977194f769ad1f08b4d9147d4124741a90f41 | Ruby | yanisvieilly/first-shmup | /ship.rb | UTF-8 | 797 | 3.09375 | 3 | [] | no_license | class Ship
SPEED = 4
WIDTH = 32
HEIGHT = 32
def initialize(window)
@window = window
@image = Gosu::Image.new(@window, 'assets/ships.png', false, 80, 320, WIDTH, HEIGHT)
@x = @window.width / 2 - WIDTH / 2
@y = @window.height - HEIGHT - 18
end
def move_up
@y -= SPEED unless @y <= 0
end
def move_down
@y += SPEED unless @y >= @window.height - HEIGHT
end
def move_left
@x -= SPEED unless @x <= 0
end
def move_right
@x += SPEED unless @x >= @window.width - WIDTH
end
def update
move_up if @window.button_down? Gosu::KbUp
move_down if @window.button_down? Gosu::KbDown
move_left if @window.button_down? Gosu::KbLeft
move_right if @window.button_down? Gosu::KbRight
end
def draw
@image.draw(@x, @y, 1)
end
end
| true |
69285342cdd30c31828aa1033b1bea1dfe8cbaef | Ruby | shairontoledo/rghost | /lib/rghost/grid/field_format.rb | UTF-8 | 738 | 2.640625 | 3 | [] | no_license | $LOAD_PATH << File.dirname(__FILE__)+File::SEPARATOR+"../"
require 'rghost/ps_object'
require 'rghost/ruby_to_ps'
module RGhost::Grid
module FieldFormat
extend RGhost::RubyToPs
#Format Time/Date to %d/%m/%Y
def self.eurodate(value)
string(value.strftime("%d/%m/%Y"))
end
#Cut all blank spaces
def self.no_space(value)
string(value.to_s.gsub(/\s/,''))
end
def self.string(value)
to_string(value)
end
end
end
#Prototype to override format method.
class RGhost::Grid::FieldFormat::Custom
def initialize(value)
@value=value
end
def gs_format
RGhost::Grid::FieldFormat.string(self.format)
end
def format
@value.to_s
end
end
| true |
3e6fb0f239d3ad55ef902a5485dd5556494a6ee9 | Ruby | magic003/supergossip | /lib/supergossip/routing/on_routing.rb | UTF-8 | 5,972 | 2.640625 | 3 | [
"MIT"
] | permissive | require 'thread'
require 'socket'
require 'date'
module SuperGossip; module Routing
# This implements the routing algorithm for ordinary nodes.
class ONRouting < RoutingAlgorithm
# Initialization
def initialize(driver,supernode_table,protocol)
super(driver,supernode_table,protocol)
end
# Start the routing algorithm
def start
# 1. Get supernodes from cache or bootstrap node
# NOTE The +attempt_to_supernodes+ will block here until get
# some active supernodes. Ordinary nodes can work without
# supernodes.
Routing.log{|logger| logger.info(self.class) {"1. Getting SNs ..."}}
sns = attempt_fetch_supernodes
# 2. Connect to supernodes
Routing.log {|logger| logger.info(self.class) {"2. Connecting to SNs ..."}}
connect_supernodes(sns)
# 3. Start the background threads
@request_supernodes_thread = start_request_supernodes_thread
@compute_hits_thread = start_compute_hits_thread
# 4. Read messages from supernodes, and handle them.
@running = true
while @running
# Wait for message from other nodes
ready = select(@socks,nil,nil,@timeout)
readable = ready[0]
unless readable.nil?
readable.each do |sock|
if sock.eof? # The socket has disconnected
Routing.log {|logger| logger.info(self.class) {'Socket has disconnected.'}}
@lock.synchronize { @socks.delete(sock)}
# Remove it if it is in supernode table
@supernode_table.delete(sock.node) if @supernode_table.include?(sn.node)
sock.close
else # Message is ready for reading
msg = @protocol.read_message(sock)
unless msg.nil?
@bandwidth_manager.downloaded(msg.bytesize,Time.now-message.ftime.to_time) unless @bandwidth_manager.nil?
handle_message(msg,sock)
else
Routing.log {|logger| logger.error(self.class) {'The message read is nil.'}}
end
end
end
else # timeout
@socks.delete_if do |sock|
sock.closed? # Discarded by supernode table
end
end
end
end
# Stops the running algorithm and threads.
def stop
@request_supernodes_thread.exit
@compute_hits_thread.exit
@running = false
end
private
#########################
# Handle messages #
#########################
# Handle the received +message+.
def handle_message(message,sock)
if message.nil? or !message.respond_to?(:type)
Routing.log {|logger| logger.error(self.class) {"Not a correct message: #{message.to_s}."}}
return
end
case message.type
when Protocol::MessageType::PING
on_ping(message,sock)
when Protocol::MessageType::PONG
on_pong(message,sock)
when Protocol::MessageType::REQUEST_SUPERNODES
on_request_supernodes(message,sock)
when Protocol::MessageType::RESPONSE_SUPERNODES
on_response_supernodes(message,sock)
else
Routing.log{|logger| logger.error(self.class) {"Unknown message type: #{message.to_s}."}}
end
end
# Handle +Protocol::Ping+ message. *It does nothing because ordinary
# node dosen't accept such messages.*
def on_ping(message,sock)
# Do nothing
Routing.log {|logger| logger.warn(self.class) {"Ordinary node doesn't accept Ping messages."}}
end
# Handle +Protocol::Pong+ message. Read the routing properties
# (authority, hub and etc.) from the message, and estimate the scores
# of the nodes to determine whether adding it to the routing table.
def on_pong(message,sock)
score_h = estimate_hub_score(message.guid,message.hub)
score_a = estimate_authority_score(message.guid,message.authority)
# attempt to add into routing table
Routing.update_node_from_pong(sock.node,message)
sock.node.score_h = score_h
sock.node.score_a = score_a
result = @supernode_table.add(sock.node)
unless result or sock.closed?
sock.close
end
# add to supernode cache
@driver.save_supernode(sock.node)
# add to neighbor cache if it is
@driver.save_neighbor(sock.node) if @driver.neighbor?(sock.node.guid)
end
# Handle +Protocol::RequestSupernodes+ message.
# *It does nothing because ordinary node dosen't accept such
# messages.*
def on_request_supernodes(message,sock)
# Do nothing
Routing.log {|logger| logger.warn(self.class) {"Ordinary node doesn't accept RequestSupernodes messages."}}
end
# Handle +Protocol::ResponseSupernodes+ message. Get the responded
# supernodes and PING them.
def on_response_supernodes(message,sock)
# Delete the supernode which is currently connecting
message.supernodes.delete_if {|sn| @supernode_talbe.include?(sn)}
# Connect to the supernodes
connect_supernodes(message.supernodes)
end
end
end; end
| true |
6bdae0077a4d6b0bec050e08c84146c69332b21a | Ruby | tanakh/ICFP2011 | /comparator/play.rb | UTF-8 | 476 | 3.03125 | 3 | [] | no_license | #!/usr/bin/env ruby
if ARGV.length < 1
STDERR.puts <<USAGE
./play.rb log-filename
behave exactly as is recorded in log-filename
USAGE
exit
end
open(ARGV[0], 'r') {|fp|
while log = fp.gets
cmd = log[0]
line = log[1..-1]
case cmd
when ">"
puts line
STDOUT.flush
when "<"
line2 = STDIN.gets
unless line == line2
throw "input mismatch : expected '#{line[0..-2]}' : actual '#{line2[0..-2]}'"
end
end
end
}
| true |
efba382e17a4d12ded4107d1e7b0b6f439b15592 | Ruby | epalace510/pEuler | /largestPrimeFactor.rb | UTF-8 | 445 | 3.421875 | 3 | [] | no_license | #-- From the Project Euler series. This is question number 3, which can be found at https://projecteuler.net/problem=3
def factor(num)
for i in 2..num do
if num % i == 0
factor=i
break
end
end
reVal=[factor, num/factor]
return reVal
end
largestFactor=0
num = 600851475143
while num!=1 do
factors=factor(num)
if factors[0]>largestFactor
largestFactor=factors[0]
end
num=factors[1]
end
puts largestFactor
| true |
ff199c94b8d103f368869e5bebaf670204359b05 | Ruby | soitun/hashie | /lib/hashie/extensions/dash/predefined_values.rb | UTF-8 | 2,600 | 3.125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | module Hashie
module Extensions
module Dash
# Extends a Dash with the ability to accept only predefined values on a property.
#
# == Example
#
# class PersonHash < Hashie::Dash
# include Hashie::Extensions::Dash::PredefinedValues
#
# property :gender, values: [:male, :female, :prefer_not_to_say]
# property :age, values: (0..150) # a Range
# end
#
# person = PersonHash.new(gender: :male, age: -1)
# # => ArgumentError: The value '-1' is not accepted for property 'age'
module PredefinedValues
def self.included(base)
base.instance_variable_set(:@values_for_properties, {})
base.extend(ClassMethods)
base.include(InstanceMethods)
end
module ClassMethods
attr_reader :values_for_properties
def inherited(klass)
super
klass.instance_variable_set(:@values_for_properties, values_for_properties.dup)
end
def property(property_name, options = {})
super
return unless (predefined_values = options[:values])
assert_predefined_values!(predefined_values)
set_predefined_values(property_name, predefined_values)
end
private
def assert_predefined_values!(predefined_values)
return if supported_type?(predefined_values)
raise ArgumentError, %(`values` accepts an Array or a Range.)
end
def supported_type?(predefined_values)
[::Array, ::Range].any? { |klass| predefined_values.is_a?(klass) }
end
def set_predefined_values(property_name, predefined_values)
@values_for_properties[property_name] = predefined_values
end
end
module InstanceMethods
def initialize(*)
super
assert_property_values!
end
private
def assert_property_values!
self.class.values_for_properties.each_key do |property|
value = send(property)
if value && !values_for_properties(property).include?(value)
fail_property_value_error!(property)
end
end
end
def fail_property_value_error!(property)
raise ArgumentError, "Invalid value for property '#{property}'"
end
def values_for_properties(property)
self.class.values_for_properties[property]
end
end
end
end
end
end
| true |
ec3f5cabb5245f44b1186fb6fe0693ec71862960 | Ruby | roycetech/rast | /examples/quoted.rb | UTF-8 | 202 | 2.609375 | 3 | [] | no_license | # frozen_string_literal: true
class Quoted
def identify_sentence_type(sentence)
return 'exclamation' if (sentence[/.*!/])
return 'question' if (sentence[/.*\?/])
'statement'
end
end
| true |
10cff394f93a410db0cdb4b779223e479e72cbe8 | Ruby | Jacob-Co/intro_to_ruby | /ruby_basics/methods/exercise_day_or_night.rb | UTF-8 | 146 | 3.328125 | 3 | [] | no_license | daylight = [true, false].sample
def time_of_day(time)
puts "It's daytime!" if time
puts "It's nighttime!" if !time
end
time_of_day(daylight) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.