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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
b61499073929827d61855e01ea808d161e8f709d | Ruby | kt9302/Geopedia | /app/models/location.rb | UTF-8 | 4,663 | 2.515625 | 3 | [] | no_license | require 'rubygems'
require 'open-uri'
require 'json'
class Location < ActiveRecord::Base
attr_accessor :longitude, :latitude, :city, :county,:state, :country,:tag,:places
def initialize(location='berkeley ca', mul=false)
google_url='http://maps.googleapis.com/maps/api/geocode/json?'
match={:address =>location, :sensor=>false}
url=URI.escape(match.to_a.collect {|each| each.join('=')}.join('&'))
results=''
geo_results=JSON.parse(open(google_url+url).read)["results"]
if geo_results.length==1 || (geo_results.length>1 && mul)
@longitude=geo_results[0]["geometry"]["location"]["lng"].to_s
@latitude=geo_results[0]["geometry"]["location"]["lat"].to_s
newmatch={:latlng=>@latitude+","+@longitude, :sensor=>false}
newurl=URI.escape(newmatch.to_a.collect {|each| each.join('=')}.join('&'))
newresults=''
newresults=JSON.parse(open(google_url+newurl).read)["results"]
if newresults.length>0 and newresults[0]["address_components"].length>0
newresults[0]["address_components"].each do |i|
i["types"].each do |j|
if j=="locality"
@city=i["long_name"]
elsif j=="administrative_area_level_2"
if @city==nil
@city=i["long_name"]
else
@county=i["long_name"]
end
elsif j=="administrative_area_level_1"
@state=i["long_name"]
elsif j=="country"
@country=i["long_name"]
end
end
end
else
@tag="missing_address"
end
elsif geo_results.length >1
@tag="multiple"
@places=[]
geo_results.each do |result|
@places.push(Location.new(result["geometry"]["location"]["lat"].to_s+","+result["geometry"]["location"]["lng"].to_s, true))
end
else
@tag="none"
end
end
def get_info
wiki_url='http://en.wikipedia.org/w/api.php?'
hash={:format =>"json", :action=>"query", :list=>"search", :srsearch=>@city+", "+@state}
url=URI.escape(hash.to_a.collect {|each| each.join('=')}.join('&'))
info_results=JSON.parse(open(wiki_url+url).read)["query"]["search"]
return info_results
end
def get_weather
weather_url='http://api.wunderground.com/api/cd4162f7975b8de1/forecast/q/'
url=URI.escape(weather_url+@latitude+","+@longitude+'.json')
weather_results=JSON.parse(open(url).read)["forecast"]["txt_forecast"]["forecastday"]
return weather_results
end
def get_place_dining
place_url='https://maps.googleapis.com/maps/api/place/nearbysearch/json?'
match={:location =>@latitude+","+@longitude, :radius=>10000, :sensor=>false, :key=>'AIzaSyCnBGnZOGCUM-mbtHKY20KUW6xmbKr0ewY', :types=>"cafe|restaurant"}
url=URI.escape(match.to_a.collect {|each| each.join('=')}.join('&'))
place_results=JSON.parse(open(place_url+url).read)["results"]
end
def get_place_hiking
place_url='https://maps.googleapis.com/maps/api/place/nearbysearch/json?'
match={:location =>@latitude+","+@longitude, :radius=>10000, :sensor=>false, :key=>'AIzaSyCnBGnZOGCUM-mbtHKY20KUW6xmbKr0ewY', :types=>"park|campground"}
url=URI.escape(match.to_a.collect {|each| each.join('=')}.join('&'))
place_results=JSON.parse(open(place_url+url).read)["results"]
end
def get_place_shopping
place_url='https://maps.googleapis.com/maps/api/place/nearbysearch/json?'
match={:location =>@latitude+","+@longitude, :radius=>10000, :sensor=>false, :key=>'AIzaSyCnBGnZOGCUM-mbtHKY20KUW6xmbKr0ewY',:types=>"grocery_or_supermarket|florist|store|liquor_store"}
url=URI.escape(match.to_a.collect {|each| each.join('=')}.join('&'))
place_results=JSON.parse(open(place_url+url).read)["results"]
end
def get_place_lodging
place_url='https://maps.googleapis.com/maps/api/place/nearbysearch/json?'
match={:location =>@latitude+","+@longitude, :radius=>10000, :sensor=>false, :key=>'AIzaSyCnBGnZOGCUM-mbtHKY20KUW6xmbKr0ewY',:types=>"lodging"}
url=URI.escape(match.to_a.collect {|each| each.join('=')}.join('&'))
place_results=JSON.parse(open(place_url+url).read)["results"]
end
end
| true |
64a2c1e1f41ff87a61dd046159f792634d11bcf5 | Ruby | qqdipps/reverse_sentence | /lib/reverse_sentence.rb | UTF-8 | 849 | 4.1875 | 4 | [] | no_license | # A method to reverse the words in a sentence, in place.
# Time complexity: O(n) where n is the number of elems in string.
# Space complexity: O(1)
def reverse_sentence(my_sentence)
return if !my_sentence
return unreverse_each_word(reverse_string(my_sentence))
end
def unreverse_each_word(my_words)
left = 0
my_words_length = my_words.length
my_words_length.times do |i|
if my_words[i] == " " || i == my_words_length - 1
right = (i == (my_words_length - 1) ? i : i - 1)
reverse_string(my_words, right, left)
left = i + 1
end
end
return my_words
end
def reverse_string(my_words, right = nil, left = 0)
right ||= my_words.length - 1
((right + 1 - left) / 2).times do |j|
temp = my_words[left + j]
my_words[left + j] = my_words[right - j]
my_words[right - j] = temp
end
return my_words
end
| true |
9afb1b1832aac5b11263d26670cecefe5dfc32a7 | Ruby | kristenhazard/ruby-processing-play | /hazard/circle-triangle-recursion.rb | UTF-8 | 1,676 | 3.53125 | 4 | [] | no_license | class Circle
def initialize(x, y, radius)
@x = x
@y = y
@radius = radius
end
def draw(pointcount)
no_fill
angle = radians(pointcount)
# x = @x + (cos(angle) * @radius)
# y = @y + (sin(angle) * @radius)
arc @x, @y, @radius, @radius, 0, angle
if pointcount % 60 == 0
start_angle = radians(pointcount - 120)
end_angle = radians(pointcount)
line @x + (cos(start_angle) * @radius/2), @y + (sin(start_angle) * @radius/2),
@x + (cos(end_angle) * @radius/2), @y + (sin(end_angle) * @radius/2)
end
end
def finish
# I wanted to fill in all the objects, but the fill method does not work from here.
# noStroke
# fill(0, 0, 70, 70) Why does fill not work when called from here?
# ellipse(@x, @y, @radius, @radius)
end
def divide
[0,60,120,180,240,300].map do |degrees|
angle = radians(degrees)
radius = @radius * 1.0 / 3.0
x = @x + (cos(angle) * @radius/2) - (cos(angle) * radius/2)
y = @y + (sin(angle) * @radius/2) - (sin(angle) * radius/2)
Circle.new(x, y, radius)
end
end
end
def setup
@w = 750
@h = 750
@r = 30
@g = 50
@b = 100
@cx = 400
@cy = 400
size 800, 800
@transparency = 255
background 255
frame_rate 33
@deg = 0
# smooth # It turns out that smooth makes the lines thicker.
@circles = [Circle.new(@cx, @cy, @w)]
end
def draw
# fill 255, 200, 0, @transparency
@circles.each{|circle| circle.draw(@deg)}
@deg += 1
if @deg > 360
@deg = 0
@circles.each(&:finish)
@circles = @circles.map(&:divide).flatten
end
end
def mouse_pressed
no_loop
end
def mouse_released
loop
end | true |
2a9d700e76b8efc844b2b031ee1f59d77ce65e58 | Ruby | Thomasmclean993/Ruby-stretch | /Mastermind/main/main.rb | UTF-8 | 870 | 3.90625 | 4 | [] | no_license | #1/bin/env ruby
#will need to reference the modules for this file
puts "Welcome New Master!!"
puts "The game is simple, Guess the code and you win. You will have 12 attempts."
puts "THe code will be made up of four assorted colors."
puts "Red, white, blue and black. As you guess the right color in the right slot,"
puts "I'll let you know if your correct. Slowly but surely, Will reveal the color code."
puts " First, what will be your first guess?? >>>"
guess = gets.chomp
# Todo: Need to create a method that generates the random assortment of colors
#TODO: THe code will need to be able to separate the colors and match the approraite color from the guess and inform user of correct guess if mentioned slot.
case guess
when guess = code
"Congratulations on guess the code. Very impressive. "
else
"Try again, the code you guessed was incorrect."
| true |
fc18f9aa33c5d8456608890821cbb28810807374 | Ruby | Meeco/cryppo | /lib/cryppo/encryption_strategies/rsa4096.rb | UTF-8 | 1,655 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | module Cryppo
module EncryptionStrategies
class Rsa4096 < EncryptionStrategy
UnknownKeyPairType = Class.new(Cryppo::Error)
Cryppo::EncryptionStrategies::EncryptionStrategy.register(self)
def key_length
32 # this value has been chosen as it matches most of the AES cipher key lengths
end
def generate_key
rsa_key = OpenSSL::PKey::RSA.new(4096)
wrap_encryption_key(rsa_key)
end
def encrypt(rsa_key, data)
rsa_public_key = to_rsa(rsa_key).public_key
encrypted_data = rsa_public_key.public_encrypt(data, OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING)
EncryptionValues::EncryptedData.new(self, encrypted_data)
rescue UnknownKeyPairType => e
raise e
rescue => e
handle_encryption_error(e)
end
def decrypt(rsa_key, encrypted_data)
rsa_key = to_rsa(rsa_key)
rsa_key.private_decrypt(encrypted_data.encrypted_data, OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING)
rescue UnknownKeyPairType => e
raise e
rescue => e
handle_decryption_error(e)
end
def to_rsa(rsa_key)
rsa_key = unwrap_encryption_key(rsa_key)
case rsa_key
when OpenSSL::PKey::RSA
rsa_key
when String
OpenSSL::PKey::RSA.new(rsa_key)
else
raise
end
rescue => _e
raise UnknownKeyPairType, "Must be a PEM formatted string or an OpenSSL::PKey::RSA object: got %s" % [rsa_key]
end
def serialize_artefacts(_artefacts)
{}
end
def deserialize_artefacts(_payload)
{}
end
end
end
end
| true |
dec78d99fc86dbc38fe86a56c8c6d61c510d53e6 | Ruby | riakoronidi/homework_week2_day2 | /river.rb | UTF-8 | 318 | 3.15625 | 3 | [] | no_license | class River
attr_accessor :name
def initialize(name)
@name = name
@fish = ["Nemo", "Dory" , "Marlin", "Mr Puff", "Cleo"]
@stomach = []
end
def fish_in_river
@fish.count()
end
def fish_count
@bear.stomach << @fish.delete_at(-1)
fish_in_river()
@bear.food_count()
end
end
| true |
5bd7befcf65fdd3f83a494b439312bac2ca5b8a5 | Ruby | elrashid24/W1D5_Classwork | /lib/00_tree_node.rb | UTF-8 | 1,220 | 3.328125 | 3 | [] | no_license | require "byebug"
class PolyTreeNode
attr_reader :value, :parent, :children
def initialize(value)
@value = value
@parent = nil
@children = []
end
def parent=(passed_node)
old_parent = parent
@parent = passed_node
if !passed_node.nil?
old_parent.children.delete(self) unless old_parent == nil
parent.children << self unless parent.children.include? self
end
end
def add_child(child)
@children << child unless children.include?(child)
child.parent=(self)
end
def remove_child(child)
raise "Node is not a child" unless children.include?(child)
children.delete(child)
child.parent = nil
end
def dfs(target)
# debugger
return self if self.value == target
self.children.each do |child|
result = child.dfs(target)
return result if !result.nil?
end
nil
end
def bfs(target)
# debugger
q = Array.new
q.push(self)
# q.empty?
# q.push(3)
# value = q.shift
until q.empty?
node = q.shift
return node if node.value == target
node.children.each { |child| q.push(child) }
end
nil
end
# def inspect
# "{ Node Value=#{self.value.inspect} }"
# end
end | true |
7b034232861053db3a1687188866ad24a71caf50 | Ruby | Marc0969/ttt-3-display_board-example-ruby-intro-000 | /lib/display_board.rb | UTF-8 | 229 | 3.046875 | 3 | [] | no_license | # display_board method prints a 3x3 tic tac toe board
def display_board
puts "A 3x3 Tic Tac Toe Board"
puts " | | "
puts "-----------"
puts " | | "
puts "-----------"
puts " | | "
end
display_board
| true |
4159db1984e3ebe6a5d65723c1ad1be7904f3e2b | Ruby | pauldambra/adventofcode2016 | /day_21/rotate_by_steps.rb | UTF-8 | 589 | 3.453125 | 3 | [
"CC-BY-4.0"
] | permissive | class RotateBySteps
def self.scramble(s, instruction)
swapper = /rotate (left|right) (\d+) step/.match instruction
if swapper
dir = swapper.captures[0]
x = swapper.captures[1].to_i
x = x * -1 if dir == 'right'
s.chars.rotate(x).join('')
else
s
end
end
def self.unscramble(s, instruction)
swapper = /rotate (left|right) (\d+) step/.match instruction
if swapper
dir = swapper.captures[0]
x = swapper.captures[1].to_i
x = x * -1 if dir == 'left'
s.chars.rotate(x).join('')
else
s
end
end
end | true |
fdd7a6792d9da40babbd5c4c8f479574957667db | Ruby | Shopify/shopify-app-cli-extensions | /bin/shopify-cli-shell-support | UTF-8 | 2,522 | 2.703125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/ruby --disable-gems
module ShellSupportCLI
ROOT = File.expand_path('../..', __FILE__)
class << self
def call(*argv)
case argv.shift
when 'env'
usage_and_die unless (shellname = argv.shift)
env(shellname)
else
usage_and_die
end
end
private
# write out (to STDOUT) a list of instructions using a simple API
# implemented in each shell shim. This API consists of a small set of commands:
#
# shopify_cli__source <path>
# sources a script from the named path. literally just "source <path>".
#
# shopify_cli__append_path <path>
# append the named path to $PATH
#
# shopify_cli__prepend_path <path>
# prepend the named path to $PATH
#
# shopify_cli__setenv <k> <v>
# set the environment variable, e.g. export <k>=<v>
#
# shopify_cli__lazyload <command> <path>
# If <command> is not already defined, create a shell function which
# loads the actual implementation of the command from the named path.
# This is useful for rarely-used commands which must be provided, but
# take some time to load, and so should not be bothered with on shell
# startup. (e.g. nvm, and to a lesser degree, chruby)
def env(_shellname)
# EnvHelpers.source("sh/autocomplete/completion.#{shellname}")
EnvHelpers.setenv('USING_SHOPIFY_CLI', '1')
# Use Mac's default Android SDK location.
unless ENV.key?('NVM_DIR')
EnvHelpers.setenv('NVM_DIR', File.expand_path('~/.nvm'))
end
# EnvHelpers.lazyload('chruby', "'#{ROOT}/sh/chruby/chruby.sh'")
# EnvHelpers.lazyload("nvm", "'#{ROOT}/sh/nvm/nvm.sh' --no-use")
EnvHelpers.prepend_path("#{ROOT}/bin/user")
end
def usage_and_die
abort("usage: #{$PROGRAM_NAME} env <shellname>")
end
end
module EnvHelpers
class << self
def setenv(k, v)
puts %(shopify_cli__setenv "#{k}" "#{v}")
end
def source(rel_path)
abs_path = File.expand_path(rel_path, ROOT)
puts %(shopify_cli__source "#{abs_path}")
end
def append_path(path)
puts %(shopify_cli__append_path "#{path}") unless ENV['PATH'].include?(path)
end
def prepend_path(path)
puts %(shopify_cli__prepend_path "#{path}")
end
def lazyload(cmd, script)
puts %(shopify_cli__lazyload "#{cmd}" "#{script}")
end
end
end
end
ShellSupportCLI.call(*ARGV) if $PROGRAM_NAME == __FILE__
| true |
78f4e329dda7088c17287691ee0447e1c893d078 | Ruby | jamesgolick/conductor | /app/models/deployment_runner.rb | UTF-8 | 1,551 | 2.578125 | 3 | [
"MIT"
] | permissive | class DeploymentRunner
attr_reader :instances, :logger, :notifier
def initialize(*instances)
@instances = instances
@logger = DeploymentLogger.new(deployment_type, *instances)
@notifier = InstanceNotifier.new(self, *instances)
end
def perform_deployment
notifier.start
handle_result ssh_session.execute
end
def ssh_session
@ssh_session ||= create_ssh_session
end
protected
def deployment_type
raise NotImplementedError, "Subclasses must implement #deployment_type"
end
def handle_result(result)
result.successful? ? handle_success(result) : handle_failure(result)
end
def handle_success(result)
logger.system_message "Deployment ran successfully."
notifier.successful
end
def handle_failure(result)
logger.system_message failure_message(result)
event = result.cancelled? ? :cancelled : :failure
notifier.send(event, result.failed_hosts)
end
def create_ssh_session
returning build_ssh_session do |s|
s.before_command { |c| logger.system_message("Running command #{c}.") }
s.on_data { |host, stream, data| logger.log(host, stream, data) }
end
end
def build_ssh_session
raise NotImplementedError, "Implement #build_ssh_session in subclasses."
end
def failure_message(result)
verb = result.cancelled? ? "was cancelled" : "failed"
hosts = result.failed_hosts.join(', ')
"The deployment #{verb} because a command failed on [#{hosts}]."
end
end
| true |
237e9f6e19c6cbea9344b349e8609355ab0f92b9 | Ruby | nofxx/ubi | /spec/ubi/memorias/site_spec.rb | UTF-8 | 2,326 | 2.6875 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
describe Memoria::Site do
describe 'simple test' do
subject { Memoria::Site.parse('bla bla somesite.com') }
it { is_expected.to include(Memoria::Site) }
it { is_expected.to be_an Array }
it 'should have text reader method' do
expect(subject[0].text).to eq('http://somesite.com')
end
end
describe 'parsed' do
def parse(site)
Memoria::Site.parse(site).first.to_s
end
describe 'http' do
let(:parsed) { 'http://fubah.com' }
it { expect(parse('fubah.com')).to eq(parsed) }
it { expect(parse('fubah.com.')).to eq(parsed) }
it { expect(parse('(fubah.com.)')).to eq(parsed) }
it { expect(parse('@fubah.com')).to eq(parsed) } # 'http://@fubah.com') }
it { expect(parse('fu@fubah.com')).to eq(parsed) } # 'http://fu@fubah.com') }
it { expect(parse('http://fubah.com')).to eq(parsed) }
it { expect(parse('http://fubah.com/56')).to eq(parsed + '/56') }
end
describe 'https' do
let(:parsed) { 'https://fubah.com' }
it { expect(parse('https://fubah.com')).to eq(parsed) }
it { expect(parse('https://fubah.com?56')).to eq(parsed + '?56') }
end
describe 'subdomain' do
let(:parsed) { 'http://www.fubah.com' }
it { expect(parse('www.fubah.com')).to eq(parsed) }
it { expect(parse('http://www.fubah.com')).to eq(parsed) }
it { expect(parse('http://www.fubah.com/f?56')).to eq(parsed + '/f?56') }
end
end
describe 'valid http' do
%w(
oo.com
oo.org
oo.net
foo.net
foo.net
foo.net
foo.net
9foo.net
land.com.br
land.org.br
land.net.br
dom.land.co.uk
ad.dom.land.co.tk
http://foo.com
http://www.foo.com
).each do |good_site|
it "should correctly parse '#{good_site}'" do
res = Memoria::Site.parse(good_site)
good_site = "http://#{good_site}" if good_site !~ /http/
expect(res.first.to_s).to eq(good_site)
expect(res.size).to eq(1)
end
end
end
describe 'invalid' do
%w(
@foo
foo@foo
zumbi@.com
@11 53 2355
@11532355
).each do |bad_site|
it "should not parse '#{bad_site}'" do
expect(Memoria::Site.parse(bad_site).first).to be_nil
end
end
end
end
| true |
73f80fe836420874621a4227c47d15093aec99c3 | Ruby | aaroncallagher/intro_to_programming | /ch_the-basics/exercise2.rb | UTF-8 | 558 | 4.28125 | 4 | [] | no_license | print "Enter a 4 digit number:"
user_number = gets.chomp.to_i
number_in_thousands_place = user_number / 1000
number_in_hundreds_place = (user_number % 1000) / 100
number_in_tens_place = ((user_number % 1000) % 100) / 10
number_in_ones_place = (((user_number % 1000) % 100) % 10) / 1
puts "The number in the Thousands place is: #{number_in_thousands_place}"
puts "The number in the Hundreds place is: #{number_in_hundreds_place}"
puts "The number in the Tens place is: #{number_in_tens_place}"
puts "The number in the Ones place is: #{number_in_ones_place}" | true |
ab05b8e911eb48332203600267f59fdff0771d02 | Ruby | osiris43/Pool-Of-Greatness | /app/models/html_nba_player_stat.rb | UTF-8 | 1,840 | 2.71875 | 3 | [] | no_license | class HtmlNbaPlayerStat
def initialize(stat_element)
@stat = stat_element
end
def player_name
player_cell = @stat.search('//td')[0]
name = player_cell.search('//a').inner_html
if(name.nil? or name.empty?)
name = player_cell.inner_html
end
name
end
def minutes
time_played = @stat.search('//td')[2].inner_html
time_played.split(':')[0].to_i
end
def seconds
time_played = @stat.search('//td')[2].inner_html
time_played.split(':')[1].to_i
end
def FGM
field_goals = @stat.search('//td')[3].inner_html
field_goals.split('-')[0].to_i
end
def FGA
field_goals = @stat.search('//td')[3].inner_html
field_goals.split('-')[1].to_i
end
def threeGM
threes = @stat.search('//td')[4].inner_html
threes.split('-')[0].to_i
end
def threeGA
threes = @stat.search('//td')[4].inner_html
threes.split('-')[1].to_i
end
def FTM
free_throws = @stat.search('//td')[5].inner_html
free_throws.split('-')[0].to_i
end
def FTA
free_throws = @stat.search('//td')[5].inner_html
free_throws.split('-')[1].to_i
end
def ORB
@stat.search('//td')[7].inner_html.to_i
end
def DRB
@stat.search('//td')[8].inner_html.to_i
end
def assists
@stat.search('//td')[10].inner_html.to_i
end
def fouls
@stat.search('//td')[11].inner_html.to_i
end
def steals
@stat.search('//td')[12].inner_html.to_i
end
def turnovers
@stat.search('//td')[13].inner_html.to_i
end
def blocked_shots
@stat.search('//td')[14].inner_html.to_i
end
def had_blocked
@stat.search('//td')[15].inner_html.to_i
end
def points
@stat.search('//td')[16].inner_html.to_i
end
def player_url
if(@stat.at('a').nil?)
return ''
end
@stat.at('a')['href']
end
end
| true |
df6f57b35fa08507d2f6fb5802db4672b000eec7 | Ruby | blessedsoy/playlister-sinatra-wdf-000 | /app/models/concerns/slugifiable.rb | UTF-8 | 208 | 2.671875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | module Slugifiable
module InstanceMethods
def slug
self.name.downcase.gsub(" ", "-")
end
end
module ClassMethods
def find_by_slug(slug)
self.all.find{|obj| obj.slug == slug }
end
end
end | true |
136e139764e70f14b127e5ad3ca0fbf3c5b83467 | Ruby | morotsman/learning-ruby | /multis_state_tax_calculator/lib/tax_calculator.rb | UTF-8 | 895 | 3.734375 | 4 | [] | no_license | class State
def initialize(amount)
@amount = amount
end
def total
@amount + tax
end
def tax
0
end
end
class Wisconsin < State
@@tax_table = Hash.new(0.05)
@@tax_table["eau clair"] = 0.055
@@tax_table["dunn"] = 0.054
def initialize(amount, county)
super(amount)
@county = county.downcase
end
def tax
@amount*@@tax_table[@county]
end
end
class Illinois < State
TAX = 0.08
def initialize(amount)
super(amount)
end
def tax
@amount*TAX
end
end
class TaxCalculator
def self.calculate(amount, name_of_state, county = nil)
state = if(name_of_state.downcase == "wisconsin")
Wisconsin.new(amount, county)
elsif(name_of_state.downcase == "illinois")
Illinois.new(amount)
else
State.new(amount)
end
return state.total, state.tax
end
end
| true |
41166448be765839bed16e7226929c2d97fb9e53 | Ruby | dcoy/learning-ruby | /loops_and_iterators/map_loop.rb | UTF-8 | 326 | 3.96875 | 4 | [] | no_license | arr = ['1', '2', '3', '4', '5', '6', '4568', '1324', '4567']
# Style 1
p arr.map { |x| x.to_i }
# Style 2 - most popular
p arr.map(&:to_i)
puts ("a".."g").to_a.map { |i| i * 2 }
# Create a Hash from an array of integers
# Assigning array element to its integer
puts Hash[[1.1, 2.2, 3.5, 4, 5, 6.5].map { |x| [x,x.to_i] }]
| true |
fe8e514cff60aff6538fa046dee4382df55c66a0 | Ruby | asascience-open/CFPointConventions | /timeSeriesProfile/timeSeriesProfile-Ragged-SingleStation-H.5.3.rb | UTF-8 | 2,466 | 2.53125 | 3 | [] | no_license | #! ruby
require 'numru/netcdf'
require_relative '../utils'
include NumRu
readme = \
"
"
nc = CFNetCDF.new(__FILE__, readme)
file = nc.netcdf_file
file.put_att("featureType","timeSeriesProfile")
p = 4
o = 10 #UNLIMITED
name = 50
profile_dim = file.def_dim("profile",p)
obs_dim = file.def_dim("obs",o)
name_dim = file.def_dim("name_strlen",name)
lat = file.def_var("lat","float",[])
lat.put_att("units","degrees_north")
lat.put_att("long_name","station latitude")
lat.put_att("standard_name","latitude")
lon = file.def_var("lon","float",[])
lon.put_att("units","degrees_east")
lon.put_att("long_name","station longitude")
lon.put_att("standard_name","longitude")
stationinfo = file.def_var("station_info","int",[])
stationinfo.put_att("long_name","station info")
stationname = file.def_var("station_name","char",[name_dim])
stationname.put_att("cf_role", "timeseries_id")
stationname.put_att("long_name", "station name")
profile = file.def_var("profile","int",[profile_dim])
profile.put_att("cf_role", "profile_id")
time = file.def_var("time","int",[profile_dim])
time.put_att("long_name","time")
time.put_att("standard_name","time")
time.put_att("units","seconds since 1990-01-01 00:00:00")
time.put_att("missing_value",-999,"int")
rowsize = file.def_var("row_size","int",[profile_dim])
rowsize.put_att("long_name", "number of obs in this profile")
rowsize.put_att("sample_dimension", "obs")
height = file.def_var("height","sfloat",[obs_dim])
height.put_att("long_name","height above sea surface")
height.put_att("standard_name","height")
height.put_att("units","meters")
height.put_att("axis","Z")
height.put_att("positive","up")
temp = file.def_var("temperature","sfloat",[obs_dim])
temp.put_att("standard_name","sea_water_temperature")
temp.put_att("long_name","Water Temperature")
temp.put_att("units","Celsius")
temp.put_att("coordinates", "time lat lon height")
temp.put_att("missing_value",-999.9,"sfloat")
# Stop the definitions, lets write some data
file.enddef
lat.put([37.5])
lon.put([-76.5])
stationinfo.put([0])
profile.put([0,1,2,3])
rowsize.put([2,2,3,3])
blank = Array.new(name)
name1 = ("Station1".split(//).map!{|d|d.ord} + blank)[0..name-1]
stationname.put([name1])
time.put( NArray.int(p).indgen!*3600)
# row_size is 2,2,3,3
heights = [0.5,1.5] + [0.5,1.5] + [0.5,1.5,2.5] + [0.5,1.5,2.5]
temp_data = [6.7,6.9] + [6.8,7.9] + [6.8,7.9,8.4] + [5.7,9.2,8.3]
height.put(heights)
temp.put(temp_data)
file.close
nc.create_output | true |
66ffd3c8fa7e78c3cd83f523adbb5071d57d3e79 | Ruby | jayg20/todo-ruby-basics-online-web-prework | /lib/ruby_basics.rb | UTF-8 | 406 | 3.59375 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def division(num1, num2)
num1/num2= total
puts total
end
def assign_variable(value="Bob")
puts "#{value}"
end
def argue(phrase="I'm right and you're wrong!")
puts "#{phrase}"
end
def greeting(greeting="Hi there," name="Bobby!")
puts "#{greeting}, #{name}"
end
def return_a_value()
return "Nice!"
end
def last_evaluated_value()
return "expert"
end
def pizza_party
return "peppeproni"
end | true |
e1fc35ff23657034cf7126cd8eb165d5d9a804bb | Ruby | juani-garcia/POO_Ruby | /guias/tp9/ej5/bag_tester.rb | UTF-8 | 343 | 2.78125 | 3 | [] | no_license | require '../../tp8/ej3/point'
require_relative 'bag'
my_bag = Bag.new
my_bag.add(Point.new(0, 0))
my_bag.add(Point.new(1, 2))
my_bag.add(Point.new(3, 4))
my_bag.add(Point.new(1, 2))
puts my_bag
puts my_bag.size
puts my_bag.count(Point.new(1, 2))
puts my_bag.delete(Point.new(1, 2))
puts my_bag
puts my_bag.delete(Point.new(1, 2))
puts my_bag
| true |
0d31fd73d7a9bb0daab94d50f7e680a7f628bbaa | Ruby | preiser/project-euler-multiples-3-5-e-000 | /lib/oo_multiples.rb | UTF-8 | 505 | 3.78125 | 4 | [] | no_license | # Enter your object-oriented solution here!
class Multiples
def initialize(limit)
@limit = limit
end
def collect_multiples
num_array = []
num = 1
while num < @limit
if num % 3 == 0 || num % 5 == 0
num_array.push(num)
end
num += 1
end
return num_array
end
def sum_multiples()
num_array = []
num = 1
sum = 0
while num < @limit
if num % 3 == 0 || num % 5 == 0
num_array.push(num)
sum += num
end
num += 1
end
return sum
end
end
Multiples.new(10) | true |
782f8d0372c817aa8390a033aee554164134f96d | Ruby | Neilos/boris_bikes | /lib/headquarters.rb | UTF-8 | 310 | 2.546875 | 3 | [] | no_license | require_relative 'bike'
require_relative 'dockable'
class Headquarters
attr_reader :dockables
def initialize
@dockables = []
end
def all_docked_bikes
@dockables.map {|dockable| dockable.bikes}.flatten
end
def register(headquarters, object)
dockables << new_dockable
end
end | true |
a9f61a8bdd4b81b1dbbe195e2bf6b5b6aacf330c | Ruby | bookest/hiveminder | /test/test_hiveminder_task.rb | UTF-8 | 2,134 | 2.515625 | 3 | [] | no_license | require 'test/unit'
require 'hiveminder'
require 'mocha'
require 'active_resource/http_mock'
class TaskTest < Test::Unit::TestCase
def test_tags_are_expanded
task = Hiveminder::Task.new(:tags => "\"@foo\" \"bar\" \"one two\"")
assert_equal ["@foo", "bar", "one two"], task.tags
end
def test_tags_array_converted_to_string_on_save
task = Hiveminder::Task.new
task.stubs(:save_without_tags).returns(true)
task.tags = ["@foo", "baz"]
task.save
assert_equal "\"@foo\" \"baz\"", task.attributes['tags']
end
def test_locator
task = Hiveminder::Task.new(:id => "12354")
assert_equal task.locator, "F44"
end
end
class BraindumpTest < Test::Unit::TestCase
def setup
@task1 = { :id => 1, :summary => "foo", :tags => "\"@test\""}
@task2 = { :id => 2, :summary => "bar", :tags => "\"@test\""}
Hiveminder.sid = "123"
@headers = Hiveminder::Task.headers
end
def test_braindump_single_task
data = { :success => "1", :content => { :created => @task1 }, }.to_xml(:root => :data)
ActiveResource::HttpMock.respond_to do |mock|
mock.post "/=/action/ParseTasksMagically.xml", @headers, data, 200
end
tasks = Hiveminder::Task.braindump(@task1[:summary])
assert_equal tasks.length, 1
assert_equal tasks.first.summary, @task1[:summary]
end
def test_braindump_multiple_tasks
data = { :success => "1", :content => { :created => [ @task1, @task2 ] }, }.to_xml(:root => :data)
ActiveResource::HttpMock.respond_to do |mock|
mock.post "/=/action/ParseTasksMagically.xml", @headers, data, 200
end
tasks = Hiveminder::Task.braindump(@task1[:summary], @task2[:summary])
assert_equal tasks.length, 2
assert_equal tasks[0].summary, @task1[:summary]
assert_equal tasks[1].summary, @task2[:summary]
end
def test_braindump_returns_nil_on_error
data = { :success => "0", :content => { } }.to_xml(:root => :data)
ActiveResource::HttpMock.respond_to do |mock|
mock.post "/=/action/ParseTasksMagically.xml", @headers, data, 200
end
assert Hiveminder::Task.braindump(@task1[:summary]).nil?
end
end
| true |
fe839e45de2f0d755746a345ecd7dc12d397648c | Ruby | tanakh/ICFP2012 | /mapmaker.rb | UTF-8 | 1,156 | 3.03125 | 3 | [] | no_license | #!/usr/bin/env ruby
n = ARGV[0].to_i
10.times{|t|
w = n+rand(n)
h = n+rand(n)
ar = (0...h).map{|y| (0...w).map{|x| "."}}
# pats = [" ", "."," ", ".", "\\", "*", "#"].map{|c| [c,rand]}
pats = [" ", ".", "\\", "*", "#"].map{|c| [c,rand]}
50.times{
char = pats.sort_by{|c,hind|hind*rand}[0][0]
rate = 10 ** (-1-2 * rand)
p1 = 628 * rand
p2 = 628 * rand
kx1 = 10 ** (0.5 -2 * rand ) * (2*rand-1)
ky1 = 10 ** (0.5 -2 * rand ) * (2*rand-1)
kx2 = 10 ** (0.5 -2 * rand ) * (2*rand-1)
ky2 = 10 ** (0.5 -2 * rand ) * (2*rand-1)
(0...h).each{|y|
(0...w).each{|x|
val = Math::sin(x*kx1 + y*ky1 + p1) * Math::sin(x*kx2 + y*ky2 + p2)
ar[y][x] = char if val > 1-rate
}
}
}
(0...h).each{|y|
ar[y][0] = "#"
ar[y][w-1] = "#"
}
(0...w).each{|x|
ar[0][x] = "#"
ar[h-1][x] = "#"
}
100.times{|ctr|
x = 2+rand(w-4)
y = 2+rand(h-4)
if ar[y][x] == " " || ctr > 90
ar[y-1][x] = "R"
ar[y-0][x] = "\\"
ar[y+1][x] = "L"
break
end
}
open("randmap#{n}-#{t}.map",'w'){|fp|
fp.puts ar.map{|xs|xs.join}.join("\n")
}
}
| true |
5bd4a10e598f07aac2e896f2643a1c6886d482e4 | Ruby | chris510/aA-Classwork | /W3D5/DIY ADT/queue.rb | UTF-8 | 302 | 3.625 | 4 | [] | no_license | class Queue
attr_reader :array
def initialize
@array = []
end
def enqueue(el) #puts element into the end of the arr
array.push(el)
el
end
def dequeue #removes first element
array.shift
end
def peek
array.first #looks at the next element that is queue
end
end | true |
2d78a4fb5b6f69151e3fb878c38aac7a23300a25 | Ruby | christianchrr/prime-ruby-onl01-seng-ft-041320 | /prime.rb | UTF-8 | 196 | 3.484375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def prime?(number)
if number < 2
return false
end
(2...number).each do |num|
if number % num == 0
return false
end
end
return true
end
| true |
6a348f022594c4eca35e891ed00aad8dfa6b38ee | Ruby | rsnorman/julysoundcheck | /app/services/sheet_sync/sheet_row.rb | UTF-8 | 986 | 2.671875 | 3 | [] | no_license | module SheetSync
class SheetRow
ATTRIBUTE_COLUMNS = {
artist: 1,
album: 2,
genre: 3,
source: 4,
review: 5,
reviewer: 6,
date_reviewed: 7,
rating: 8,
aotm: 9,
recommended_by: 10
}.freeze
ATTRIBUTE_COLUMNS.each_pair do |attr, column_index|
define_method attr do |with_formula: false|
if with_formula
@worksheet.formula_value(row_index, column_index)
else
@worksheet.value(row_index, column_index)
end
end
define_method "#{attr}=" do |value|
@worksheet.set_value(row_index, column_index, value)
end
end
alias tweet review
attr_reader :row_index
def initialize(worksheet, row_index)
@worksheet = worksheet
@row_index = row_index
end
def delete(*_args)
ATTRIBUTE_COLUMNS.each_pair do |_attr, column_index|
@worksheet.set_value(row_index, column_index, nil)
end
end
end
end
| true |
672106abe0db11a24a44fe900ea1f48a7ec0a65f | Ruby | tadeusrox/hackerrank | /30_days_of_code/day20.rb | UTF-8 | 439 | 3.6875 | 4 | [] | no_license | #!/bin/ruby
n = gets.strip.to_i
a = gets.strip
a = a.split(' ').map(&:to_i)
total_swaps = 0
(0..n-1).each do |i|
swaps = 0
(0..n-2).each do |j|
if a[j] > a[j + 1]
temp = a[j]
a[j] = a[j + 1]
a[j + 1] = temp
swaps += 1
total_swaps += 1
end
end
if swaps == 0
break
end
end
puts "Array is sorted in #{total_swaps} swaps."
puts "First Element: #{a.first}"
puts "Last Element: #{a.last}"
| true |
14c28a214f47c90179627faa6991dd8c351af6ed | Ruby | ql/euler | /problem78.rb | UTF-8 | 1,058 | 3.578125 | 4 | [] | no_license | require 'euler_helper.rb'
NAME ="Investigating the number of ways in which coins can be separated into piles."
DESCRIPTION ="Find the least value of n for which p(n) is divisible by one million."
def c n, memo
count(n,n-1, memo) + 1
end
def count n, k, memo = {}
memo[[n,k]] ||= if k == 2
(n/2).floor + 1
else
(0..(n/k).floor).inject(0) {|acc, i| acc += count(n - k*i, k-1, memo) }
end
end
def p(n, memo={})
memo[n] ||= if n == 0
1
elsif n < 0
0
else
(1..n).inject(0) {|acc, k| acc += ((-1)**(k+1) ) * ((p(n-k*(3*k-1)/2.0, memo)) + p(n-k*(3*k+1)/2.0, memo)) }
end
end
def solve
memo = {}
i = 480
pp = p2(i, memo)
while pp % 1_000_000 != 0
i+=1
pp = p2(i, memo)
end
i
end
def penta q
(3*(q**2)-q)/2
end
def ubound n
((1+Math.sqrt(1+24*n)) / 6).ceil
end
def p2 n, memo = {}
return 0 if n < 0
memo[n] ||= if n == 0
1
else
(1..ubound(n)).inject(0) {|acc, i| acc += (-1)**(i+1)*p2(n-penta(i), memo) + (-1)**(i+1)*p2(n-penta(-i), memo) }
end
end
benchmark do
puts solve
end
| true |
85840a7cb4cec998b247e79528cc3063bf08d12a | Ruby | herrtreas/shortcut | /lib/shortcut/index.rb | UTF-8 | 734 | 2.703125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | module Shortcut
class Index
def self.load
if (File.exist?("/Users/andreas/.shortcut.index"))
puts "Loading index.."
lines = []
File.open("/Users/andreas/.shortcut.index", "r") do |f|
lines = f.readlines
end
else
puts "Updating index.."
lines = %x(find /Users/andreas/Development -type d).split("\n")
File.open("/Users/andreas/.shortcut.index", "w") do |f|
lines.each { |line| f << line + "\n"}
end
end
self.new(lines)
end
def initialize(lines)
@lines = lines
end
def find(search_term)
@lines.select do |line|
line.include?(search_term)
end
end
end
end | true |
c616f88e6eb7e0d7e40458a9104ac85eafb08981 | Ruby | asbudik/git_practice | /hello.rb | UTF-8 | 113 | 3.75 | 4 | [] | no_license | if 1 < 2
puts "yeah"
elsif 1 = 2
puts "ok"
else
puts "nah"
end
if 3 < 4
puts "yay"
else
puts "way"
end | true |
f6918be48682d4bbdb6775d71a7cdd79894e6470 | Ruby | aceofbassgreg/sentimental-writer | /app/services/twitter/importer.rb | UTF-8 | 1,779 | 2.890625 | 3 | [] | no_license | require 'forwardable'
class Twitter::Importer
extend Forwardable
delegate [:get] => :wrapper
extend Forwardable
attr_reader :wrapper
def initialize
@wrapper = Twitter::Wrapper.new
end
def load_tweets_for(subject)
15.times do
all_tweets_for(subject).each do |tweet|
store_all_data_from(tweet)
end
sleep 1
end
end
def all_tweets_for(subject)
get(subject).attrs.first.last
end
def store_all_data_from(tweet_data)
tweet_text = tweet_data[:text]
sentiment_score = Sentimental::Processor.new(tweet_text).get_score
tweet_record = store(tweet_data,sentiment_score)
return unless !!tweet_record.id
hashtags(tweet_data).each do |hashtag|
tweet_record.hashtags.create(name: hashtag[:text])
end
Topic.all.each do |topic|
if !!tweet_text.match((Regexp.new(Regexp.escape(topic.name), Regexp::IGNORECASE)))
TweetTopic.create(tweet_id: tweet_record.id, topic_id: topic.id)
end
end
Person.all.each do |person|
if !!tweet_text.match((Regexp.new(Regexp.escape(person.last), Regexp::IGNORECASE)))
Reference.create(tweet_id: tweet_record.id, person_id: person.id)
end
end
rescue
binding.pry
end
def store(tweet,sentiment_score)
::Tweet.create(
id_from_twitter: tweet[:id],
text: tweet[:text],
author_name: tweet[:user][:name],
author_screenname: tweet[:user][:screen_name],
author_location: tweet[:user][:location],
author_followers: tweet[:user][:followers_count],
retweet_count: tweet[:retweet_count],
favorite_count: tweet[:favorite_count],
sentiment_score: sentiment_score
)
end
def hashtags(tweet_data)
tweet_data[:entities][:hashtags]
end
end | true |
0c00264800e2c0335554b0016d0342c1e742748d | Ruby | neonwires/ttt-5-move-rb-q-000 | /lib/move.rb | UTF-8 | 401 | 3.296875 | 3 | [] | no_license | def display_board(board)
puts " #{board[0]} | #{board[1]} | #{board[2]} "
puts "-----------"
puts " #{board[3]} | #{board[4]} | #{board[5]} "
puts "-----------"
puts " #{board[6]} | #{board[7]} | #{board[8]} "
end
# code your move method here!
def move(board, movechoice, playertoken = "X")
movechoice = movechoice.to_i
movechoice = movechoice - 1
board [movechoice] = playertoken
end | true |
577660f093c019327651957a510ad2f1574a1b9f | Ruby | Prabhakarzx/Web-Scraper-Ruby-Capstone | /lib/team_scraper.rb | UTF-8 | 940 | 2.78125 | 3 | [
"MIT"
] | permissive | require_relative './constants.rb'
require_relative './parser.rb'
require_relative './file_handler'
require_relative './show_status.rb'
class TeamScraper < Parser
include ShowStatus
def initialize(url, league)
@url = url
@league = league
@team_hash = {}
parse_teams
end
private
def parse_teams
parsed_url = parse
table_rows = parsed_url.at('tbody').css('tr')
table_rows.length.times do |i|
@team_hash[table_rows[i].css('td')[0].text.strip] = {}
print_league_node(table_rows[i].css('td')[0].text.strip)
(TEAM_STAT_TYPE.length - 1).times do |j|
@team_hash[table_rows[i].css('td')[0].text.strip].merge!(TEAM_STAT_TYPE[j] => table_rows[i].css('td')[j].text)
end
@team_hash[table_rows[i].css('td')[0].text.strip].merge!(TEAM_STAT_TYPE[-1] => table_rows[i].css('td')[0].css('a').first['href'])
end
FileHandler.new(@team_hash, @league).teams_to_json
end
end
| true |
a2293ad2394fdee1108dcef363b0a84d1c098729 | Ruby | AlexeyShpavda/LearningRuby | /6)Redacted.rb | UTF-8 | 534 | 4.125 | 4 | [
"MIT"
] | permissive | =begin
Contents:
Getting the User's Input
The .split Method
Redacted!
Control Flow Know-How
=end
puts "### Getting the User's Input ###"
print "Text to search through: "
text = gets.chomp
print "Word to redact: "
redact = gets.chomp
puts "### The .split Method ###"
words = text.split(" ")
print words
puts
puts "### Redacted! ###"
words.each do |word|
print word
end
puts
puts "### Control Flow Know-How ###"
words.each do |word|
if word != redact
print word + " "
else
print "REDACTED "
end
end | true |
c56eb4d4807df749fba944893c01226349df838a | Ruby | KierranM/marry-me | /lib/marry/me.rb | UTF-8 | 838 | 3.359375 | 3 | [] | no_license | require 'marry/me/version'
require 'marry/me/simple_stable_marriage'
require 'marry/me/matchable'
require 'marry/me/logger'
module Marry
module Me
# Matches the 'partners' in pool_one to their optimal match in pool_two
# @param pool_one [Array<Matchable>] Pool of partners to match with pool_two
# @param pool_two [Array<Matchable>] Pool of partners to match with pool_one
# @param algorithm [Nil, #match] The algorithm that creates matches between partners.
# Defaults to the SimpleStableMarriage algorithm, but can be substituted
# with any class that accepts two parameters and has a match function
# @return [Hash { Partner => Partner }] A hash of Partner pairs
def self.match(pool_one, pool_two, algorithm = SimpleStableMarriage)
algorithm.new(pool_one, pool_two).match
end
end
end
| true |
2bceac6d1be230eb19c51b1ec0db0102f14f3d07 | Ruby | drusepth/inline-tests-gem | /lib/inline_test_failure.rb | UTF-8 | 429 | 2.8125 | 3 | [] | no_license | class InlineTestFailure < StandardError
attr_accessor :test_type, :lhs, :rhs, :description
def initialize(test_type=nil, lhs=nil, rhs=nil, description=nil)
super [
" #{description} FAILED:",
" test_type: #{test_type}",
" lhs: #{lhs}",
" rhs: #{rhs}"
].join "\n"
self.test_type = test_type
self.lhs = lhs
self.rhs = rhs
self.description = description
end
end | true |
5dd9e151a32c1ea958432544dae0211ddd1e48e7 | Ruby | GregoryJFischer/war_or_peace | /spec/deck_spec.rb | UTF-8 | 2,792 | 3.078125 | 3 | [] | no_license | require 'rspec'
require './lib/deck'
describe Deck do
describe "#initialize" do
it "is an instance of deck" do
card1 = Card.new(:diamond, 'Queen', 12)
card2 = Card.new(:spade, '3', 3)
card3 = Card.new(:heart, 'Ace', 14)
cards = [card1, card2, card3]
deck = Deck.new(cards)
expect(deck).to be_a Deck
end
it "has cards" do
card1 = Card.new(:diamond, 'Queen', 12)
card2 = Card.new(:spade, '3', 3)
card3 = Card.new(:heart, 'Ace', 14)
cards = [card1, card2, card3]
deck = Deck.new(cards)
expect(deck.cards).to eq cards
end
end
describe "#rank_of_card_at" do
it "gives rank of card" do
card1 = Card.new(:diamond, 'Queen', 12)
card2 = Card.new(:spade, '3', 3)
card3 = Card.new(:heart, 'Ace', 14)
cards = [card1, card2, card3]
deck = Deck.new(cards)
expect(deck.rank_of_card_at(1)).to eq 3
end
end
describe "#high_ranking_cards" do
it "picks high cards" do
card1 = Card.new(:diamond, 'Queen', 12)
card2 = Card.new(:spade, '3', 3)
card3 = Card.new(:heart, 'Ace', 14)
cards = [card1, card2, card3]
cards2 = [card1, card3]
deck = Deck.new(cards)
deck2 = Deck.new(cards2)
expect(deck.high_ranking_cards).to eq deck2.high_ranking_cards
expect(deck.high_ranking_cards).to be_a Array
expect(deck.high_ranking_cards.count).to eq 2
end
end
describe "#percent_high_ranking" do
it "gives percent of high ranking cards" do
card1 = Card.new(:diamond, 'Queen', 12)
card2 = Card.new(:spade, '3', 3)
card3 = Card.new(:heart, 'Ace', 14)
cards = [card1, card2, card3]
deck = Deck.new(cards)
expect(deck.percent_high_ranking).to eq 66.67
end
end
describe "#remove_card" do
it "removes top card" do
card1 = Card.new(:diamond, 'Queen', 12)
card2 = Card.new(:spade, '3', 3)
card3 = Card.new(:heart, 'Ace', 14)
cards = [card1, card2, card3]
cards2 = [card2, card3]
deck = Deck.new(cards)
deck2 = Deck.new(cards2)
deck.remove_card
expect(deck.cards).to eq deck2.cards
expect(deck.cards).to be_an Array
expect(deck.cards.count).to eq 2
end
end
describe "add_card" do
it "adds card to bottom" do
card1 = Card.new(:diamond, 'Queen', 12)
card2 = Card.new(:spade, '3', 3)
card3 = Card.new(:heart, 'Ace', 14)
card4 = Card.new(:club, '5', 5)
cards = [card1, card2, card3]
cards2 = [card1, card2, card3, card4]
deck = Deck.new(cards)
deck2 = Deck.new(cards2)
deck.add_card(card4)
expect(deck.cards).to eq deck2.cards
expect(deck.cards).to be_an Array
expect(deck.cards.count).to eq 4
end
end
end
| true |
9350d6fde3c398ad85c6123852c885459784a841 | Ruby | OwenKLenz/rb120_object_oriented_programming | /medium_1/deck_of_cards.rb | UTF-8 | 1,027 | 3.796875 | 4 | [] | no_license |
require 'set'
class Card
include Comparable
attr_reader :rank, :suit
CARD_RANKINGS = Set.new([2, 3, 4, 5, 6, 7, 8, 9, 10,
"Jack", "Queen", "King", "Ace"]).freeze
def initialize(rank, suit)
@rank = rank
@suit = suit
end
def <=>(other_card)
CARD_RANKINGS.find_index(self.rank) <=>
CARD_RANKINGS.find_index(other_card.rank)
end
def to_s
"#{rank} of #{suit}"
end
end
class Deck
RANKS = ((2..10).to_a + %w(Jack Queen King Ace)).freeze
SUITS = %w(Hearts Clubs Diamonds Spades).freeze
def initialize
@cards = create_deck
end
def create_deck
RANKS.product(SUITS).map { |rank, suit| Card.new(rank, suit) }.shuffle
end
def draw
@cards = create_deck if @cards.empty?
@cards.pop
end
end
deck = Deck.new
p deck
drawn = []
52.times { drawn << deck.draw }
p drawn
puts drawn.count { |card| card.rank == 5 } == 4
puts drawn.count { |card| card.suit == 'Hearts' } == 13
drawn2 = []
52.times { drawn2 << deck.draw }
puts drawn != drawn2 | true |
ecd27ea2c08f941f9daabb8f4a91ef86f29a5f28 | Ruby | cout/redtimer | /demos/256colors.rb | UTF-8 | 380 | 2.671875 | 3 | [
"MIT"
] | permissive | require 'curses'
screen = Curses.init_screen
begin
Curses.start_color
Curses.use_default_colors
Curses.curs_set(0)
Curses.noecho
window = Curses::Window.new(0, 0, 1, 2)
window.clear
window.setpos(0, 0)
for i in 0...256 do
Curses.init_pair(i, i, 0)
window.color_set(i)
window << i.to_s << ' '
end
window.getch
ensure
Curses.close_screen
end
| true |
9827959aa30827b256aeda26ac4b3db6701f9535 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/roman-numerals/c6ed64c2dbc645e38a854829b826d73e.rb | UTF-8 | 1,122 | 3.859375 | 4 | [] | no_license | # class Fixnum
# def to_roman
# roman_1000 + roman_100 + roman_10 + roman_1
# end
# private
# def roman_1000
# count = self / 1000
# 'M' * count
# end
# def roman_100
# count = (self % 1000) / 100
# convert(count, 'C', 'D', 'M')
# end
# def roman_10
# c = (self % 100) / 10
# convert(c, 'X', 'L', 'C')
# end
# def roman_1
# c = self % 10
# convert(c, 'I', 'V', 'X')
# end
# def convert(count, one_unit, five_unit, ten_unit)
# return one_unit + ten_unit if count == 9
# return five_unit + one_unit * (count-5) if count > 4
# return one_unit + five_unit if count == 4
# return one_unit * count
# end
# end
class Fixnum
arabic = [100, 90, 50, 40, 10, 9, 5, 4, 1]
roman = %w[C XC L XL X IX V IV I]
DIGITS = arabic.zip roman
def to_roman
result = ""
num = self
DIGITS.each do |limit, glyph|
while num >= limit
result << glyph
num -= limit
end
end
result
end
end
arabic = [10, 9, 5, 4, 1]
roman = %w[X IX V IV I]
arabic_to_roman = arabic.zip roman
p arabic_to_roman
p arabic
p roman
| true |
d3e2aa33f6a32af0d005a294920cd785a16de80d | Ruby | Numbericons/aa_online_W7D1 | /executing_time_difference.rb | UTF-8 | 1,716 | 3.828125 | 4 | [] | no_license | require 'byebug'
def my_min_p1(list)
list.each do |num|
return num if list.all? { |num_in| num_in >= num }
end
end
def my_min_p2(list)
minimum = nil
list.each do|num|
minimum = num if minimum.nil? || num < minimum
end
minimum
end
list = [ 0, 3, 5, 4, -5, 10, 1, 90 ]
# p "Below is a call to phase 1 of #my_min"
# p my_min_p1(list) # => -5
# p "Below is a call to phase 2 of #my_min"
# p my_min_p2(list) # => -5
def largest_contiguous_subsum(list)
sub_arrs = []
list.each_with_index do |el, i|
list.each_with_index do |el_in, j|
next if i > j
sub_arrs << list[i..j]
end
end
largest = nil
sub_arrs.each_with_index do |sub, i|
sum = sub.reduce(:+)
largest = sum if largest.nil? || sum > largest
end
largest
end
list = [2, 3, -6, 7, -6, 7]
p "Below is largest contiguous sum phase 1, should equal 8"
p largest_contiguous_subsum(list) # => 8 (from [7, -6, 7])
list = [-5, -1, -3]
p "Below is largest contiguous sum phase 1, should equal -1"
p largest_contiguous_subsum(list) # => -1 (from [-1])
def largest_contiguous_subsum_p2(list)
return list.max if list.all? { |num| num < 0 }
largest = list.first
current = list.first
list.drop(1).each do |num|
current = 0 if current < 0
current +=num
largest = current if current > largest
end
largest
end
list = [2, 3, -6, 7, -6, 7]
p "Below is largest contiguous sum phase 2, should equal 8"
p largest_contiguous_subsum_p2(list) # => 8 (from [7, -6, 7])
list = [-5, -1, -3]
p "Below is largest contiguous sum phase 2, should equal -1"
p largest_contiguous_subsum_p2(list) # => -1 (from [-1]) | true |
2e3db3bbe915c92217495ba1a524eed44d5dfe86 | Ruby | pecha7x/MyScratchpad | /NessGems/wx_sugar-0.1.22/lib/wx_sugar/string_each.rb | UTF-8 | 95 | 2.640625 | 3 | [
"MIT"
] | permissive | class String
def each
self.split("\n").each do |line|
yield line
end
end
end
| true |
ff916c9bef9975b9a722bd3c6fd0746bef0523b1 | Ruby | NCU-BRATS/Conflux | /app/policies/project_user_context.rb | UTF-8 | 205 | 2.578125 | 3 | [] | no_license | class ProjectUserContext
attr_reader :user, :project
def initialize( user, project )
@user = user
@project = project
end
def is_project_member?
@user.is_member?(@project)
end
end
| true |
a319ab700380e8456b9c22e8904869704128e44f | Ruby | krepflap/games_dice | /spec/reroll_rule_spec.rb | UTF-8 | 1,527 | 2.578125 | 3 | [
"MIT"
] | permissive | require 'helpers'
describe GamesDice::RerollRule do
describe "#new" do
it "should accept self-consistent operator/value pairs as a trigger" do
GamesDice::RerollRule.new( 5, :>, :reroll_subtract )
GamesDice::RerollRule.new( (1..5), :member?, :reroll_replace )
end
it "should reject inconsistent operator/value pairs for a trigger" do
lambda { GamesDice::RerollRule.new( 5, :member?, :reroll_subtract ) }.should raise_error( ArgumentError )
lambda { GamesDice::RerollRule.new( (1..5), :>, :reroll_replace ) }.should raise_error( ArgumentError )
end
it "should reject bad re-roll types" do
lambda { GamesDice::RerollRule.new( 5, :>, :reroll_again ) }.should raise_error( ArgumentError )
lambda { GamesDice::RerollRule.new( (1..5), :member?, 42 ) }.should raise_error( ArgumentError )
end
end
describe '#applies?' do
it "should return true if a trigger condition is met" do
rule = GamesDice::RerollRule.new( 5, :>, :reroll_subtract )
rule.applies?(4).should == true
rule = GamesDice::RerollRule.new( (1..5), :member?, :reroll_subtract )
rule.applies?(4).should == true
end
it "should return false if a trigger condition is not met" do
rule = GamesDice::RerollRule.new( 5, :>, :reroll_subtract )
rule.applies?(7).should == false
rule = GamesDice::RerollRule.new( (1..5), :member?, :reroll_subtract )
rule.applies?(6).should == false
end
end
end | true |
b3df9acbbb81a8da7deeb4076e7d8f27a763370e | Ruby | peterayeniofficial/oo-relationships-practice-london-web-102819 | /app/models/bakery/dessert.rb | UTF-8 | 210 | 2.9375 | 3 | [] | no_license | class Desert
attr_reader :desert, :bakery
@@all = []
def initialize(ingredients, bakery)
@ingredients = ingredients
@bakery = bakery
@@all << self
end
def self.all
@@all
end
end | true |
91309b688b93afaca5f847d9149c8fd5b2baf706 | Ruby | rathi2016/count-elements-web-0217 | /count_elements.rb | UTF-8 | 100 | 3.15625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def count_elements(array)
hash = Hash.new(0)
array.each do |ele|
hash[ele] +=1
end
hash
end
| true |
9aa93461b53bda46ca8d9ca38a8db3565ed11c59 | Ruby | julienemo/rails_api_devise_jwt_starter | /db/seeds.rb | UTF-8 | 204 | 2.53125 | 3 | [] | no_license | puts 'Creating users...'
n = 1
10.times do
User.create!(
username: "created_from_seed#{n}",
email: "seededuser#{n}@yopmail.com",
password: "111111"
)
n += 1
end
puts "#{User.all.size} users created"
| true |
81ea1e705b8bfcb66e1d6fc6c3e7f6cfd08ad321 | Ruby | pwentz/night_writer | /lib/decryption_formatter.rb | UTF-8 | 676 | 3 | 3 | [] | no_license | require_relative "braille_parser"
require 'pry'
class DecryptionFormatter
attr_reader :raw_braille, :parsed_content, :sorted_braille
def initialize
@sorted_braille = Array.new
end
def parse_braille(raw_braille)
braille_parser = BrailleParser.new
parsed_lines = raw_braille.split("\n")
parsed_letters = parsed_lines.map{|line| braille_parser.parse(line)}
@parsed_content = parsed_letters.map{|nest| nest.flatten}
end
def format_content
until @parsed_content.all?{|nests|nests.empty?}
@sorted_braille.push(@parsed_content.map {|line| line[0+0+0]})
@parsed_content.each {|letter| letter.shift}
end
@sorted_braille
end
end
| true |
f0cd2dc53e7676095b3e9711ead4a9ea42568098 | Ruby | JoshMacSween/odin | /caesar.rb | UTF-8 | 197 | 3.234375 | 3 | [] | no_license | def cipher(str, key)
alphabet = ("a".."z").to_a
alpha_shift = alphabet.rotate(key)
str.downcase.chars.map do |char|
alpha_shift[alphabet.index(char)]
end.join
end
cipher("hello", 2 )
| true |
e453b3723fe8a89f281734d7f0b7739a14adcbba | Ruby | rleer/diamondback-ruby | /tests/parser/large_examples/node.rb | UTF-8 | 1,578 | 3.171875 | 3 | [
"BSD-3-Clause"
] | permissive | require "rexml/parseexception"
module REXML
# Represents a node in the tree. Nodes are never encountered except as
# superclasses of other objects. Nodes have siblings.
module Node
# @return the next sibling (nil if unset)
def next_sibling_node
return nil if @parent.nil?
@parent[ @parent.index(self) + 1 ]
end
# @return the previous sibling (nil if unset)
def previous_sibling_node
return nil if @parent.nil?
ind = @parent.index(self)
return nil if ind == 0
@parent[ ind - 1 ]
end
def to_s indent=-1
rv = ""
write rv,indent
rv
end
def indent to, ind
if @parent and @parent.context and not @parent.context[:indentstyle].nil? then
indentstyle = @parent.context[:indentstyle]
else
indentstyle = ' '
end
to << indentstyle*ind unless ind<1
end
def parent?
false;
end
# Visit all subnodes of +self+ recursively
def each_recursive(&block) # :yields: node
self.elements.each {|node|
block.call(node)
node.each_recursive(&block)
}
end
# Find (and return) first subnode (recursively) for which the block
# evaluates to true. Returns +nil+ if none was found.
def find_first_recursive(&block) # :yields: node
each_recursive {|node|
return node if block.call(node)
}
return nil
end
# Returns the index that +self+ has in its parent's elements array, so that
# the following equation holds true:
#
# node == node.parent.elements[node.index_in_parent]
def index_in_parent
parent.index(self)+1
end
end
end
| true |
d7bd8c7d4b17e5fbe77fad8e35bc73b63a959674 | Ruby | toddsdarling/developers | /examples/ruby-single-user/app.rb | UTF-8 | 608 | 2.71875 | 3 | [] | no_license | require 'oauth'
require 'json'
CONSUMER_KEY = 'YOUR_CONSUMER_KEY'
CONSUMER_SECRET = 'YOUR_CONSUMER_SECRET'
# Get these from http://accesstoken.io
ACCESS_TOKEN_KEY = 'YOUR_ACCCESS_TOKEN_KEY'
ACCESS_TOKEN_SECRET = 'YOUR_ACCESSS_TOKEN_SECRET'
consumer = OAuth::Consumer.new(CONSUMER_KEY, CONSUMER_SECRET, site: 'https://services.planningcenteronline.com')
access_token = OAuth::AccessToken.from_hash(consumer, { oauth_token: ACCESS_TOKEN_KEY, oauth_token_secret: ACCESS_TOKEN_SECRET } )
response = access_token.get('/me.json')
me = JSON.parse(response.body)
puts "Hello " + me["first_name"]
| true |
f4b942d6a146f7b7b70f0c8b2301e52d056106e1 | Ruby | greytape/backend | /101-109 /easy4_9.rb | UTF-8 | 1,391 | 4.53125 | 5 | [] | no_license | # Approach
# - input: integer
# - output: string
# - use integer#/ and integer#% to get first value and remainder
# - will need to work out how long the integer is to know what to divide by
# - can then use 10 ^ intgr_size as divisor
# - probably use a dedicated method for this bit (maybe with recursion?)
# - then we'll get an array of numbers
# - use a hash again to convert individual digits to strings
# - then we iterate through these putting the elements as keys in a hash
# - then concatenate the values of the hash into a new string
# Code
INT_TO_STRINGS = {1=>'1',2=>'2',3=>'3',4=>'4',5=>'5',6=>'6',7=>'7',8=>'8',9=>'9',0=>'0'}
require 'pry'
def find_intgr_size(intgr)
array = []
counter = 1
loop do
array << counter
if intgr % counter == intgr
array.pop
break
end
counter *= 10
end
array
end
def integer_to_array(intgr)
div_arr = find_intgr_size(intgr)
new_array = []
while div_arr.length > 0
div = div_arr.pop
new_array << intgr / div
intgr = intgr % div
end
new_array
end
def integer_to_string(intgr)
return '0' if intgr == 0
arr = integer_to_array(intgr)
result = ''
while arr.length > 0
result << INT_TO_STRINGS[arr.shift]
end
result
end
p integer_to_string(0)
# Tests
# puts integer_to_string(4321) == '4321'
# puts integer_to_string(0) == '0'
# puts integer_to_string(5000) == '5000'
| true |
2694fb83c6fc752f660de1a718b8f0619e585ed6 | Ruby | Nejuf/Ruby-Blackjack | /src/ComputerPlayer.rb | UTF-8 | 886 | 3.140625 | 3 | [] | no_license | require('./src/Player')
class ComputerPlayer < Player
def initialize(name="computer")
super()
@name = name
end
def choose_play(hand, dealer_top_card=nil)
if @money <= 0
return { :action => :quit }
end
if hand.bet == 0
bet = @money/5
bet = bet <= 0 ? 1 : bet
return { :action => :bet, :amount => bet }
else
if hand.can_split?
if hand.points == 16 || hand.points == 14
return { :action => :split }
end
end
if dealer_top_card.rank == 1 || dealer_top_card.rank > 9
if hand.points < 17
return { :action => :hit }
else
return { :action => :stay }
end
else
if hand.points < 12
if hand.points < 10
return { :action => :hit }
else
return { :action => :double_down }
end
else
return { :action => :stay }
end
end
end
end
end | true |
933c2b9e350a30c79d78b4375b7ba7d2fd539637 | Ruby | pharhadnadi/kyubits | /hackerrank/euler/230/1_alpha_fib.rb | UTF-8 | 1,952 | 3.90625 | 4 | [] | no_license | # This problem is a programming version of Problem 230 from projecteuler.net
#
# For any two strings of digits, and , we define to be the sequence (, , , , , ) in which each term is the concatenation of the previous two.
#
# Further, we define to be the -th digit in the first term of that contains at least digits.
#
# Example:
#
# Let , . We wish to find , say.
#
# The first few terms of are:
#
# Then is the -th digit in the fifth term, which is .
#
# You are given triples . For all of them find .
#
# Input Format
#
# First line of each test file contains a single integer that is the number of triples. Then lines follow, each containing two strings of decimal digits and and positive integer .
#
# Constraints
#
# Output Format
#
# Print exactly lines with a single decimal digit on each: value of for the corresponding triple.
#
# Sample Input 0
# 2
# 1415926535 8979323846 35
# 1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679 8214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196 104683731294243150
#
# Sample Output 0
# 9
# 8
#
# Enter your code here. Read input from STDIN. Print output to STDOUT
def fib_get n, a, b
# return a[n-1] if n < a.size
# return b[n-1] if n-a.size < b.size
fib = []
fib[1] = a.size
fib[2] = b.size
i = fib_lim n, fib
fib_find n, i, a, b, fib
end
def fib_lim(n, fib)
if n <= fib[-1]
fib.size - 1
else
fib << fib[-1] + fib[-2]
fib_lim n, fib
end
end
def fib_find(n, i, a, b, fib)
if i == 1
a[n-1]
elsif i == 2
b[n-1]
else
an = fib[i - 2]
# bn = fib[i - 1]
if n <= an
fib_find(n, i - 2, a, b, fib)
else
fib_find(n - an, i - 1, a, b, fib)
end
end
end
q = gets.chomp.to_i
q.times do
a, b, n = gets.chomp.split
puts fib_get n.to_i, a, b
end
| true |
595016a4e6065af9e8e444e1867d744e9e7f473e | Ruby | 12Starlight/App-Academy-Master | /AppAcademyFoundations/W3D5/battleship_project/lib/board.rb | UTF-8 | 1,443 | 3.9375 | 4 | [] | no_license | class Board
# getters, # setters
attr_reader :size
# class method
def self.print_grid(grid)
grid.each do |row|
puts row.join(" ")
end
end
def initialize(n)
@grid = Array.new(n) { Array.new(n, :N) }
@size = n * n
end
# instance methods
def [](position)
row, col = position
@grid[row][col]
end
def []=(position, value)
row, col = position
@grid[row][col] = value
end
def num_ships
@grid.flatten.count { |elm| elm == :S }
end
def attack(position)
if self[position] == :S # Because I built the methods above, I do not need to add .grid and position has been defined already. So, I can just use the variable
self[position] = :H
puts "You sunk my battleship! :("
return true
else
self[position] = :X
return false
end
end
def place_random_ships
total = @size * 0.25
while self.num_ships < total
random_row = rand(0...@grid.length)
random_col = rand(0...@grid.length)
position = [random_row, random_col]
self[position] = :S
end
end
def hidden_ships_grid
@grid.map do |row|
row.map do |elm|
if elm == :S
:N
else
elm
end
end
end
end
def cheat
Board.print_grid(@grid)
end
def print
hidden_ships = self.hidden_ships_grid
Board.print_grid(hidden_ships)
end
end
| true |
62db274a1e84a44f732c67872daaad070cc9766b | Ruby | Castone22/word-counter-ruby | /counter.rb | UTF-8 | 769 | 3.421875 | 3 | [] | no_license | require 'json'
## Tool written to do word count on an input file.
## - Some considerations
## Words can be composites, including - or '
## Capitalization should be ignored.
## Output can be placed in a file type of choice
## -- In this regard I chose to go with json since some of that yaml reserved keys were making output look weird.
file_to_count = File.open('./countme.txt')
contents = file_to_count.read
contents.downcase!
pattern = /[^a-zA-Z0-9\-']/
contents.gsub!(pattern , ' ')
words = contents.split
results = {}
words.each do |word|
if results.has_key?(word)
results[word] += 1
else
results[word] = 1
end
end
results = results.sort_by {|_key, value| value}.reverse
File.write('out.json', JSON.pretty_generate(results.to_h))
| true |
a4431f1f4c30801c9a4937b2a33a82a6a2959ca8 | Ruby | simonkrausgit/the_odin_project | /ruby/building_blocks/spec/bubble_sort_spec.rb | UTF-8 | 984 | 3.328125 | 3 | [] | no_license | require_relative '../bubble_sort'
describe "#bubble_sort" do
it 'should return an Array' do
expect(bubble_sort([2,3])).to be_kind_of(Array)
end
it 'should sort an Array' do
expect(bubble_sort([3,2])).to eq([2,3])
end
it 'should sort an Array' do
expect(bubble_sort([3,2,1])).to eq([1,2,3])
end
it 'should sort an Array' do
expect(bubble_sort([4,3,78,2,0,2])).to eq([0,2,2,3,4,78])
end
end
describe '#bubble_sort_by' do
it 'should return an Array' do
expect(bubble_sort_by(["a","be"]) do |left,right|
left.length - right.length
end).to be_kind_of(Array)
end
it 'should sort by word length' do
expect(bubble_sort_by(["hi","hello","hey"]) do |left,right|
left.length - right.length
end).to eq(["hi", "hey", "hello"])
end
it 'should sort by word length reversed' do
expect(bubble_sort_by(["hi", "hey", "hello"]) do |left,right|
right.length - left.length
end).to eq(["hello", "hey", "hi"])
end
end
| true |
81776168f0d0b9a8abf5449c0d4bedce7e05f464 | Ruby | lrsousa/RubyStudies | /ruby/ruby restaurante_avancado.rb | UTF-8 | 1,327 | 3.703125 | 4 | [] | no_license | class Franquia
def initialize
@restaurantes = []
end
def adiciona(*restaurantes)
for restaurante in restaurantes
@restaurantes << restaurante
end
end
def mostra
@restaurantes.each do |r|
puts r.nome
end
end
def relatorio
@restaurantes.each do |r|
yield r
end
end
def expandir(restaurante)
def restaurante.cadastrar_vips
puts "Restaurante #{self.nome} agora com área VIP!"
end
end
def method_missing(name, *args)
@restaurantes.each do |r|
return "O restaurante #{r.nome} já foi cadastrado." if r.nome.eql? *args
end
return "O restaurante #{args[0]} não foi cadastrado ainda."
end
end
class Restaurante
attr_accessor :nome
def fechar_conta(dados)
puts "Conta fechado no valor de #{dados[:valor]} e com nota #{dados[:nota]}. Comentário: #{dados[:comentario]}"
end
end
restaurante_um = Restaurante.new
restaurante_um.nome = "Kenai"
restaurante_dois = Restaurante.new
restaurante_dois.nome = "Conchita"
restaurante_um.fechar_conta valor: 50, nota: 9, comentario: 'Gostei!'
franquia = Franquia.new
franquia.adiciona restaurante_um, restaurante_dois
franquia.relatorio do |r|
puts "Restaurante cadastrado: #{r.nome}"
end
franquia.expandir restaurante_um
restaurante_um.cadastrar_vips
puts franquia.ja_cadastrado?("Kenai")
puts franquia.ja_cadastrado?("Carol")
| true |
95420ce2ba00523a4b9247fb688a5453e73ab7ff | Ruby | elia/opal | /test/core/numeric/equal_value_spec.rb | UTF-8 | 213 | 3.125 | 3 | [
"MIT"
] | permissive | describe "Numeric#==" do
it "returns true if self has the same value as other" do
(1 == 1).should == true
(9 == 5).should == false
(9 == 9.0).should == true
(9 == 9.01).should == false
end
end | true |
d0bc215149177e65e240f104e02c4b7873432da7 | Ruby | sanger/print_my_barcode | /app/label_printer/label_printer/data_input.rb | UTF-8 | 448 | 2.546875 | 3 | [] | no_license | # frozen_string_literal: true
module LabelPrinter
##
# Manages the production of the text for the input for the printer.
# Turns the input values into a format which can be recognised by the printer.
module DataInput
##
# Produces a new data input object from input values and a label template
def self.build(label_template, input_values)
LabelPrinter::DataInput::Base.new(label_template, input_values)
end
end
end
| true |
b3221295a9c6dce8bac9f30953bac2bfb6076d7c | Ruby | eaball35/hotel | /lib/reservation.rb | UTF-8 | 480 | 3.171875 | 3 | [] | no_license | require_relative 'input_validation'
class Reservation
attr_reader :room, :booking_date_range, :price, :discount
def initialize(room:, booking_date_range:, discount: 0)
check_room?(room)
check_booking_date_range?(booking_date_range)
check_num?(discount)
@room = room
@booking_date_range = booking_date_range
@num_nights = booking_date_range.length
@discount = discount/100.0
@price = @room.cost * @num_nights * (1 - @discount)
end
end | true |
f0cd062c27f96b2d3d87b025b47000faced8a1f8 | Ruby | Eneroth3/townhouse-system | /src/ene_buildings/observers.rb | UTF-8 | 4,228 | 2.65625 | 3 | [
"MIT"
] | permissive | # Eneroth Townhouse System
# Copyright Julia Christina Eneroth, eneroth3@gmail.com
module EneBuildings
# Internal: Wrapper for all observer related code in plugin.
# Concentrating observers here that actually has to do with different classes
# still is cleaner and easier to maintain than spreading out observers and
# code attaching them to new models.
module Observers
# Whether observers are temporarily disabled or not.
@@disabled = false
# Keep track on active path length to differ entering from leaving.
@@previous_path_size ||= 0
def self.disabled?; @@disabled; end
def self.disabled=(v); @@disabled = v; end
def self.disable; @@disabled = true; end
def self.enable; @@disabled = false; end
def self.previous_path_size; @@previous_path_size; end
def self.previous_path_size=(v); @@previous_path_size = v; end
# Methods to be called from inside module.
# Add all model specific observers.
# Called when opening or creating a model.
def self.add_observers(model)
model.add_observer(MyModelObserver.new)
model.selection.add_observer(MySelectionObserver.new)
end
# Check if Building Group or Template ComponentInstance is being entered.
# Called wen changing active drawing context.
def self.check_if_entering(model)
path_size = (model.active_path || []).size
# Model.active_path Returns nil, not empty array, when in model root -_-.
if Observers.previous_path_size < path_size
# A group/component was entered.
e = model.active_path.last
if Building.group_is_building?(e)
# Entered group/component represents a building.
unless Building.onGroupEnter
Observers.disable
model.close_active
Observers.enable
path_size -= 1
end
elsif Template.component_is_template?(e)
# Entered group/component is an instance of a Template definition.
TemplateEditor.onComponentEnter
end
end
Observers.previous_path_size = path_size
end
# Observer classes.
# App observer adding model specific observers on all models.
class MyAppObserver < Sketchup::AppObserver
def onOpenModel(model)
return if Observers.disabled?
Observers.add_observers model
end
def onNewModel(model)
return if Observers.disabled?
Observers.add_observers model
end
# Call onOpenModel or onNewModel on startup.
def expectsStartupModelNotifications
true
end
end
# Model observer checking if a Building Group or Template ComponentDefinition
# is entered. Also updates template and part info dialog when drawing context
# changes or when undoing and redoing.
# Also saves data in part and template info dialogs to model before model is
# saved to disk.
# Also attach template data to template component instance when placed from
# component browser.
class MyModelObserver < Sketchup::ModelObserver
def onActivePathChanged(model)
return if Observers.disabled?
Observers.check_if_entering model
TemplateEditor.onActivePathChanged
end
def onPlaceComponent(instance)
return if Observers.disabled?
TemplateEditor.onPlaceComponent instance
end
def onPreSaveModel(*)
return if Observers.disabled?
TemplateEditor.onPreSaveModel
end
def onTransactionRedo(*)
return if Observers.disabled?
TemplateEditor.onUndoRedo
end
def onTransactionUndo(*)
return if Observers.disabled?
TemplateEditor.onUndoRedo
end
end
# Selection observer updating template and part info dialog when opened.
class MySelectionObserver < Sketchup::SelectionObserver
# Called on all selection changes EXCEPT when selection is completely
# emptied...
def onSelectionBulkChange(*)
return if Observers.disabled?
TemplateEditor.onSelectionChange
end
# ...in which case this is called instead.
def onSelectionCleared(*)
return if Observers.disabled?
TemplateEditor.onSelectionChange
end
end# Class
# Attach app observer if not already attached.
@@app_observer ||= nil
unless @@app_observer
@@app_observer = MyAppObserver.new
Sketchup.add_observer @@app_observer
end
end
end | true |
fdf1d72990e9ea6371f185d02c438473cb5e5226 | Ruby | KurisuLim/basic_ruby | /method.rb | UTF-8 | 210 | 4.125 | 4 | [] | no_license | # Methods
def sayhi
puts 'Hello User'
end
sayhi # calls the method
def sayhello(name='none', age=0)
puts "Hello #{name}, you are #{age.to_s}."
end
sayhello('John', 78)
sayhello # uses default values | true |
6876f92e58622b71ca97ae19f994e3df952edb97 | Ruby | alecnhall/sinatra-mvc-lab-online-web-pt-081219 | /models/piglatinizer.rb | UTF-8 | 469 | 3.59375 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class PigLatinizer
def piglatinize(input)
words = input.split(" ")
words.map do |word|
piglatinize_word(word)
end.join(" ")
end
private
def piglatinize_word(input)
first = input.match(/^[^AEIOUYaeiouy]+/)
if first
first = first[0]
rest = input[first.length..-1]
"#{rest}#{first}ay"
else
"#{input}way"
end
end
end | true |
935c89f9b31560b8d35c0cc4bcdee66e26c24ba4 | Ruby | RadoRado/playground | /ruby/hackbulgaria-problems/week3/1-GameOfLife/cell.rb | UTF-8 | 387 | 3.421875 | 3 | [] | no_license | # rubocop:disable Style/Documentation
module GameOfLife
class Cell
attr_accessor :is_alive, :x, :y
def initialize(x, y, is_alive = false)
@x = x
@y = y
@is_alive = is_alive
end
def die
@is_alive = false
end
def bring_to_life
@is_alive = true
end
def to_s
return '-' unless @is_alive
'*'
end
end
end
| true |
84246a807389246b34061c3190be74406cd0ac5b | Ruby | tchoutdara/week1brainteaser | /teaser_solution1.rb | UTF-8 | 815 | 4.03125 | 4 | [] | no_license | require 'pry'
def input
puts "Please enter a series of numbers"
@user_numbers = gets.split(' ').map { |x| x.to_i }
# @user_numbers = gets.split(' ').map(&:to_i)
puts "1) Highest Value or 2) Lowest Value"
choice = gets.strip
if choice === '1'
highest
elsif choice === '2'
lowest
else
puts 'Please Select Valid Option'
input
end
end
def highest
prev_num = @user_numbers[0]
@user_numbers.each do |next_num|
if next_num > prev_num
prev_num = next_num
end
end
puts "The highest number is #{prev_num}"
@user_numbers.clear
end
def lowest
prev_num = @user_numbers[0]
@user_numbers.each do |next_num|
if next_num < prev_num
prev_num = next_num
end
end
puts "The lowest number is #{prev_num}"
@user_numbers.clear
end
while true
input
end | true |
a433ffbfd565099f45824581e85c1856b51bb6e4 | Ruby | weymanf/interview_problems | /add_nums_to_words.rb | UTF-8 | 500 | 3.8125 | 4 | [] | no_license | #takes string and adds numbers after the words
# i.e "this is it"
# "this3 is2 it1"
def add_nums_to_words(str)
counter = 1
if str.reverse[0] != " "
str << "#{counter}"
counter += 1
end
reversed_str = str.reverse
reversed_str.split(//).map.with_index do | character, i |
if character == " " && reversed_str[i+1] != " "
counter += 1
"#{counter - 1}" + character
else
character
end
end.reverse.join("")
end # really gimmicky will improve later | true |
3297905fa895edc33c024a80599aac2ec22654c7 | Ruby | neontuna/project_viking_store | /app/models/credit_card.rb | UTF-8 | 505 | 2.75 | 3 | [] | no_license | class CreditCard < ActiveRecord::Base
belongs_to :user
has_many :orders
validates :card_number, :exp_month, :exp_year, :ccv, presence: true
validate :valid_card_number
def display_card_number
"Ending in #{card_number[-4..-1]}"
end
private
def valid_card_number
if !card_number.nil? && !@card_number.blank?
card_number.tr!(' -/', '')
unless (Math.log10(card_number.to_i).to_i + 1) == 16
errors.add(:card_number, "is invalid")
end
end
end
end
| true |
2ab6153de430b049fcf6f0e09058bfd27ff3694d | Ruby | Alex-Swann/advent_of_code_2020 | /Answers/1.rb | UTF-8 | 796 | 3.390625 | 3 | [] | no_license | def find_combo(arr, combo)
arr.combination(combo).any? do |*nums|
arr = nums[0]
if arr.reduce(&:+) == 2020
pp arr.reduce(&:*)
break
end
end
end
arr = File.readlines('../Test_Data/1.txt', chomp: true).map(&:to_i)
find_combo(arr, 3)
# O(n^2) Example
#
# require 'set'
#
# def find_combo(arr, sum)
# arr = arr.sort()
# arr_length = arr.length - 1
# (0..arr_length).each do |i|
# s = Set.new
# curr_sum = sum - arr[i]
# ((i + 1)..arr_length).each do |j|
# if s.include?(curr_sum - arr[j])
# pp arr[i] * arr[j] * (curr_sum - arr[j])
# return true
# end
# s.add(arr[j])
# end
# end
# false
# end
#
# arr = File.readlines('../Test_Data/1.txt').map { |x| x.gsub('\n', '').to_i }
#
# find_combo(arr, 2020)
| true |
74cf34eea62aa9466c381b5fe41bb74f5dfaeb00 | Ruby | Candillan/ruby-oo-complex-objects-school-domain-nyc-web-120919 | /lib/school.rb | UTF-8 | 429 | 3.546875 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # code here!
class School
def initialize(school_name, roster={})
@roster = roster
@school_name = school_name
end
attr_reader :school_name, :roster
def add_student(name, grade)
if !@roster[grade]
@roster[grade] = []
end
@roster[grade] << name
end
def grade(year)
@roster[year]
end
def sort
@roster.each do |grade, students|
@roster[grade].sort!
end
end
end | true |
948fdf8b0e1999e3d4eb81615a153325f87996f1 | Ruby | kontez/PM1-PT1 | /Aufgabe3/muster_ausgeben.rb | UTF-8 | 2,229 | 4 | 4 | [] | no_license | def dreieck(n, zeichen)
if ( n <= 0 )
puts "keine Ausgabe für n=#{n} möglich"
else
n.times do |i|
puts ("#{zeichen} "*(i+1))
end
end
end
def dreieck_alternierend(n, zeichen1, zeichen2)
max_l = n.to_s().size()
if ( n <= 0 )
puts "keine Ausgabe für n=#{n} möglich"
else
#header
printf("%-#{max_l}s ", " ")
n.times do |i|
printf("%-#{max_l}d ", i+1)
end
printf("\n")
#Zeilen
for i in (1..n)
#Nummern an der Seite
printf("%-#{max_l}d ", i)
i.times do |j|
if ((i+j)%2 == 0)
printf("%-#{max_l}s ", zeichen1)
#printf("%s\t",zeichen1)
else
printf("%-#{max_l}s ", zeichen2)
#printf("%s\t",zeichen2)
end
end
#newline
printf("\n")
end
end
end
def dreieck_alternierend_oben(n, zeichen1, zeichen2)
if ( n <= 0 )
puts "keine Ausgabe für n=#{n} möglich"
else
#Zeilen
n.downto(1) do |i|
#Leerzeichen am Anfang
printf("%s",(" "*(n-i)))
i.downto(1) do |j|
#Zeichen
if ((i+j)%2 == 0)
printf("%s ",zeichen1)
else
printf("%s ",zeichen2)
end
end
#newline
printf("\n")
end
end
end
def diagonale(n, zeichen, breite)
if (( n <= 0 ) || ( breite >= n ))
puts "keine Ausgabe für n=#{n} möglich"
else
#Erster Part
tmp = ( breite / 2 ) + 1
k = 0
tmp.upto(breite-1) do |i|
k += 1
puts ("#{zeichen} ")*i
end
#Mittlere Zeilen
(n-(k*2)).times do |i|
printf("%s",(" "*(i)))
puts ("#{zeichen} ")*breite
end
#Letzter Part
j = (n-(k*2))
(breite-1).downto(tmp) do |i|
printf("%s",(" "*j))
puts ("#{zeichen} ")*(i)
j += 1
end
end
end
#Tests
puts "[+] Testing dreieck, with values (1,:*) - (-5,:'(') - (5, :¬)"
dreieck(1, :*)
dreieck(-5,:'(')
dreieck(5, :¬)
puts "\n[+] Testing dreieck_alternierend with values (7, :-, :o)"
dreieck_alternierend(7, :-, :o)
puts "\n[+] Testing dreieck_alternierend_oben with values (9, :x, :'@')"
dreieck_alternierend_oben(9, :x, :'@')
puts "\n[+] Testing diagonale with values (7, :'o', 3)"
diagonale(7, :'o', 3)
| true |
e5ce57f18d55f57c26fcc2c2e1da3caf721d1378 | Ruby | urimikhli/PoS | /terminal.rb | UTF-8 | 732 | 2.734375 | 3 | [] | no_license | require_relative 'order.rb'
class Terminal
attr_reader :order, :price_list
def initialize
@price_list = PriceList.new
@order = Order.new(@price_list)
end
#new list and new order
def set_pricing(pricing_type='regular')
@price_list.set_price_list(pricing_type)
@order = Order.new(@price_list)
#price_list
end
def scan(item_code = '')
old_order_items = self.order.order.clone
status = @order.add_item(item_code)
{
before: old_order_items,
after: self.order.order
#status: status
}
end
def remove(item_code = '')
@order.delete_item(item_code)
end
def total
@order.total
end
def new_order
@order = Order.new(@price_list)
end
end
| true |
7d1cc19bd370fe0708d299f1d39be4c1aa01bfd5 | Ruby | maximkoo/ruby-repo | /Tk/Gosu/jump.rb | UTF-8 | 913 | 3.015625 | 3 | [] | no_license | require 'gosu'
class C1<Gosu::Window
def initialize width=400, height=400, fullscreen=false
super
self.caption="OLOLO";
@rock_image = Gosu::Image.new(self, '1.png')
@x=100
@y=100
@vy=10
end;
def button_down(id)
close if id==Gosu::KbEscape;
if id==Gosu::KbUp
puts :up
@y-=10
end
if id==Gosu::KbDown
puts :down
@y+=10
end
if id==Gosu::KbLeft
puts :left
@x-=10
end
if id==Gosu::KbRight
puts :right
@x+=10
end
if id==Gosu::KbSpace
puts :Space
@yi=@y
jump
end;
end;
def update
#puts "Testing fps for update"
end;
def draw
@rock_image.draw(@x, @y, 0)
#@x+=@v
end;
def jump
#while @y<=@yi do
@t=0
5.times do
puts "#{@t}."
@y=@y-@vy+(9*@t*@t).fdiv(2)
@t+=1
puts @y
sleep(0.3)
puts (9*@t*@t).fdiv(2)
end;
end;
end;
C1.new.show | true |
dec11b0faf5b45518f984f053e14101afb955be9 | Ruby | walidwahed/ls | /exercises/101-109_small_problems/additional_practice/easy8/09.rb | UTF-8 | 1,361 | 4.53125 | 5 | [] | no_license | # Double Char (Part 2)
# Write a method that takes a string, and returns a new string in which every consonant character is doubled. Vowels (a,e,i,o,u), digits, punctuation, and whitespace should not be doubled.
# Examples:
# - in: string
# - possible to have empty input
# - out: string
# - every consonant doubled
# - all other characters are not doubled
# - capitalization is preserved
# - algo
# - set a CONSTANT equal to the alphabet and delete vowels from it
# - alternatively, we could use regex
# - initialize an output string
# - iterate through each character in the input string
# - IF CONSTANT includes? downcase char then 2x char to the output string
# - ELSE move char to the output string
# - return output string
CONSONANTS = ('a'..'z').to_a.join.delete('aeiou').chars
CONSONANTS = %w[ b c d f g h j k l m n p q r s t v w x y z ]
def double_consonants(string)
output = ''
string.each_char do |char|
CONSONANTS.include?(char.downcase) ? output << char * 2 : output << char
end
output
end
def couble_consonants(string)
string.chars.map { |char| char =~ /[^aeiou_\W\d\s]/ ? char * 2 : char }.join
end
puts double_consonants('String') == "SSttrrinngg"
puts double_consonants("Hello-World!") == "HHellllo-WWorrlldd!"
puts double_consonants("July 4th") == "JJullyy 4tthh"
puts double_consonants('') == "" | true |
3718c1afd2ac2ffa082c36d98f10311af866dadf | Ruby | rorybot/bank-tech-test | /spec/deposits_spec.rb | UTF-8 | 1,056 | 2.59375 | 3 | [] | no_license | describe Account do
let(:test_account) { Account.new }
context 'when interacting with an account' do
it 'can track balance' do
2.times { test_account.change_balance(1000, '10-01-2012') }
expect(test_account.query_balance(test_account.transaction_history)).to eq 2000
end
it 'can store the amount and date and current balance of deposit' do
2.times { test_account.change_balance(1000, '10-01-2012') }
expect(test_account.transaction_history.first.amount).to eq 1000
expect(test_account.transaction_history.first.date.to_i).to eq 1_326_153_600
expect(test_account.transaction_history.first.date.year).to eq 2012
expect(test_account.transaction_history.first.balance).to eq 1000
end
it 'can make withdrawls from balance' do
test_account.change_balance(1000, '10-01-2012')
test_account.change_balance(2000, '13-01-2012')
test_account.change_balance(-500, '14-01-2012')
expect(test_account.query_balance(test_account.transaction_history)).to eq 2500
end
end
end
| true |
52a9c7799aa3e9427edc7eccffae1b2e9c2b6bc7 | Ruby | stardust789/programming_collective_intelligence | /similarity.rb | UTF-8 | 4,651 | 2.765625 | 3 | [] | no_license | class Similarity
attr_reader :critics, :films
def initialize
@critics = {
'lisa rose' => {
'lady in the water' => 2.5,
'snakes on a plane' => 3.5,
'just my luck' => 3.0,
'superman returns' => 3.5,
'you me and dupree' => 2.5,
'the night listener' => 3.0,
},
'gene seymour' => {
'lady in the water' => 3.0,
'snakes on a plane' => 3.5,
'just my luck' => 1.5,
'superman returns' => 5.0,
'you me and dupree' => 3.5,
'the night listener' => 3.0,
},
'michael phillips' => {
'lady in the water' => 2.5,
'snakes on a plane' => 3.0,
'superman returns' => 3.5,
'the night listener' => 4.0,
},
'claudia puig' => {
'snakes on a plane' => 3.5,
'just my luck' => 3.0,
'superman returns' => 4.0,
'you me and dupree' => 2.5,
'the night listener' => 4.5,
},
'mick lasalle' => {
'lady in the water' => 3.0,
'snakes on a plane' => 4.0,
'just my luck' => 2.0,
'superman returns' => 3.0,
'you me and dupree' => 2.0,
'the night listener' => 3.0,
},
'jack matthews' => {
'lady in the water' => 3.0,
'snakes on a plane' => 4.0,
'just my luck' => 2.0,
'superman returns' => 5.0,
'you me and dupree' => 3.5,
'the night listener' => 3.0,
},
'alex' => {
'snakes on a plane' => 4.5,
'you me and dupree' => 1.0,
'superman returns' => 4.0,
}
}
@films = transform_map(@critics)
end
def sim_distance(prefs, p1, p2)
similarities = similarities(p1, p2)
return 0 if similarities.size == 0
sum_of_squares = similarities.inject(0) do |memo, film|
memo += ((@critics[p1][film] - @critics[p2][film]) ** 2)
end
# puts sum_of_squares
# return 1.0 / (1 + Math.sqrt(sum_of_squares))
return 1.0 / (1 + (sum_of_squares))
end
def sim_pearson(prefs, p1, p2)
similarities = similarities(prefs, p1, p2)
n = similarities.size
return 0 if n == 0
sum1 = 0
sum2 = 0
sum1sq = 0
sum2sq = 0
p_sum = 0
similarities.each do |s|
sum1 += prefs[p1][s]
sum2 += prefs[p2][s]
sum1sq += prefs[p1][s] ** 2
sum2sq += prefs[p2][s] ** 2
p_sum += prefs[p1][s] * prefs[p2][s]
end
num = p_sum - ((sum1 * sum2)/n)
den = Math.sqrt((sum1sq - (sum1 ** 2)/n) * (sum2sq - (sum2 ** 2)/n))
return 0 if den == 0
num/den
end
def top_people_matches(person, n=3, func = :sim_pearson)
mapped = @critics.keys.map do |other|
[self.send(func, @critics, person, other), other] if person != other
end.compact.sort_by do |ar|
ar.first
end.reverse.slice(0, n)
end
def top_film_matches(film, n=3, func = :sim_pearson)
mapped = @films.keys.map do |other|
[self.send(func, @films, film, other), other] if film != other
end.compact.sort_by do |ar|
ar.first
end.reverse.slice(0, n)
end
def recommendations(prefs, item, func = :sim_pearson)
totals = Hash.new {|h, k| h[k] = 0 }
simsums = Hash.new {|h, k| h[k] = 0 }
prefs.each do |other, score_hash|
next if other == item
sim = send(func, prefs, item, other)
score_hash.each do |film, score|
next unless score == 0 or !prefs[item][film]
totals[film] += sim * score
simsums[film] += sim
end
end
rankings = []
totals.each do |film, total|
rankings<< [total/simsums[film], film]
end
rankings.sort_by do |ar|
ar.first
end.reverse
end
def show_all(method)
@critics.keys.combination(2).each do |x, y|
puts "#{x}, #{y} #{self.send(method, x, y)}"
end
end
private
def transform_map(m)
t = Hash.new {|h, k| h[k] = Hash.new {} }
m.each do |critic, score_map|
score_map.each do |film, score|
t[film][critic] = score
end
end
t
end
def similarities(prefs, p1, p2)
similarities = []
prefs[p1].each do |item, rating|
similarities << item if prefs[p2].has_key? item
end
similarities
end
end
sim = Similarity.new
# Similarity.new.show_all(:sim_distance)
# Similarity.new.show_all(:sim_pearson)
# puts sim.top_people_matches('alex', 3).inspect
# puts sim.top_film_matches('superman returns', 3).inspect
puts sim.recommendations(sim.critics, 'alex').inspect
# puts sim.recommendations(sim.films, 'just my luck').inspect
| true |
daad593e0116890b3abaea5f41a19bbe88116f0a | Ruby | hientuminh/SOLID_In_Ruby | /SRP/AuthenticatesUser/Not_SRP/authenticates_user.rb | UTF-8 | 312 | 2.578125 | 3 | [] | no_license | class AuthenticatesUser
def authenticate(email, password)
if matches?(email, password)
do_some_authentication
else
raise NotAllowedError
end
end
private
def matches?(email, password)
user = find_from_db(:user, email)
user.encrypted_password == encrypt(password)
end
end
| true |
b9ae2c23ecd325b743269a52504fe5149695e4ad | Ruby | ebenavides/TI3404-TPIV | /Main.rb | UTF-8 | 673 | 2.890625 | 3 | [] | no_license |
load 'TwitterAPI.rb'
load 'InstagramAPI.rb'
require 'twitter'
require 'instagram'
print "\nDigite el #hashtag\n"
hashtag = gets.chomp
print "\nDigite la cantidad \n"
quantity = gets.chomp
_twitter = TwitterAPI.new()
_instagram = InstagramAPI.new()
print "\nTwitter=================================="
_twitter.Search(hashtag,quantity)
print "\n\n\nInstagram============================"
_instagram.Search(hashtag,quantity)
get '/' do
erb:VentanaInicial
end
post '/Rtweet' do
_twitter.Search(hashtag,5)
redirect 'tweet'
end
get 'tweet' do
erb:tweet
end
post '/Rinstagram' do
_instagram.Search(tag,5)
redirect 'insta'
end
get '/insta' do
erb:insta
end
| true |
1ea35827d2cb5a562e8eee1bb7fa9cc496f288ac | Ruby | morag92/understanding_programming | /avengers.rb | UTF-8 | 240 | 2.59375 | 3 | [] | no_license | avengers = {
Iron_Man: {
name:"tony_stark",
moves:{
punch: 10,
kick: 100
}
},
Hulk: {
name:"Bruce_Banner",
moves:{
smash: 1000,
roll: 500
}
}
}
puts avengers [:Hulk][:moves][:smash]
| true |
65354c07319c309e2bd4c7d43376e7f14151f3d1 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/difference-of-squares/58118de88ed143609e5abf8235625790.rb | UTF-8 | 317 | 3.625 | 4 | [] | no_license | class Squares
attr_reader :n
def initialize(number)
@n = number
end
def square_of_sums
sum_of_numbers**2
end
def sum_of_squares
sum_of_numbers * (2 * n + 1) / 3
end
def difference
square_of_sums - sum_of_squares
end
private
def sum_of_numbers
n * (n + 1) / 2
end
end
| true |
37edaf6dd504a086446aaae756ef23cc9799bb86 | Ruby | darvs/advent-of-code | /2020/2001.rb/features/step_definitions/cucumber_steps.rb | UTF-8 | 242 | 2.890625 | 3 | [] | no_license | # frozen_string_literal: true
Given('the number in file {string}') do |string|
@expense = Expense.from_file(string)
end
Then('the multiplication of {int} numbers would be {int}') do |int, int2|
expect(@expense.run(int)).to eq(int2)
end
| true |
9170aab6029182e9cfe3c0769e19ff6b17c60c73 | Ruby | fakehatecrimes/fakehatecrimes | /app/helpers/application_helper.rb | UTF-8 | 6,274 | 2.640625 | 3 | [] | no_license | require "#{ Rails.root }/lib/calendar_date_select/lib/calendar_date_select.rb"
CalendarDateSelect.format = :american
HIT_THIS_BUTTON = "Fill in the form and hit this button"
SAVE_BUTTON = " Save "
SAVING_BE_PATIENT = "Saving - please be patient..."
SAVE_MEDIUM_BUTTON = "Save " + Article::DESCRIPTION.downcase
CLICK_HERE = " Click here "
SEARCH_BUTTON = " Then click here "
ADD_FAKE_BELOW = "Click here to enter a fake hate crime report"
# These two buttons must be labeled differently for the two forms in main/_form to work with fakes controller
ADD_FAKE_ABOVE = "Click here to add a fake hate crime report"
AGREE_TO_RULES_BELOW = "Check here if you have read the rules below and agree to them"
AGREE_TO_RULES_ABOVE = "Check here if you have read the rules above and agree to them"
MUST_BE_USER = "Please join this site and log in to add reports" # Don't say anything about 'administrator'
MUST_BE_ADMIN = MUST_BE_USER
SUSPECTED = 'suspected'
NOT_A_FAKE = 'not a hoax'
SMALL = 200
LARGE = 350
URL_SIZE = 200
LINK_SIZE = 50
TEXT_FIELD_SIZE = 128
NUM_PER_PAGE = 100
MAX_MEDIA = 50
DATE_REG = /^[A-Z][a-z].+ [0-9]+.+[0-9].+$/
INT_DATE_MSG = "(yyyy-mm-dd)"
USA_DATE_MSG = "(mm/dd/yyyy)"
# Hash extensions
class Hash
def revert
hash_new = Hash.new
self.each { |key, value|
if not hash_new.has_key?(key) then
hash_new[value] = key
end
}
return hash_new
end
KEYS = ['-', '=', '~', '_', '+', '#']
def recurse(pr=false, n=0, key='')
str = "\n"
spaces = ' ' * 2 * (1 + n)
each do |k, v|
if v.is_a? Hash
str += v.recurse(pr, n + 1, k)
else
s = "#{k}"
s = ":#{s}" if k.is_a? Symbol
pointer = KEYS[ n % KEYS.size ]
first = (key == '' ? '' : "#{key} #{pointer}>")
str += "#{spaces}#{first} #{s} #{pointer}> #{v}"
end
end
puts str + "\n" if (n == 0) and pr
str
end
def recurse!
recurse true
end
def remove_unnecessary_keys! # Remove some of the bumf that gets into a controller's params hash
delete :commit
delete :controller
delete :action
delete :utf8
delete :authenticity_token
delete :_method
delete 'commit' # The following deletes are unnecessary, if it's a HashWithIndifferentAccess
delete 'controller'
delete 'action'
delete 'utf8'
delete 'authenticity_token' # If any of these are not there, it doesn't do anything
delete '_method'
delete 'media_type_id'
delete 'reason'
delete 'date'
delete 'city'
delete 'state'
keys.each do |key|
if( key.to_s =~ /^media_id_[0-9]+$/ )
delete( key.to_s )
end
end
end
end
# String extensions
class String
def short
num = SMALL / 2
return self if self.size < num
self[ 0 .. num-1 ] + '...'
end
def shuffle
m = []
u = ''
until u.size == self.size
n = rand(self.size)
unless m.include? n
m << n
u << self[n]
end
end
u
end
def shuffle!
u = self.shuffle
u.size.times { |t| self[t..t] = u[t..t] }
end
# http://stackoverflow.com/questions/862140/hex-to-binary-in-ruby
def hex_2_bin
raise "Empty string is not a valid hexadecimal number" if self.size < 1
hex = self.upcase.split( '' )
hex.each { |ch| raise "#{self} is not a hexadecimal number" unless "ABCDEF0123456789".include? ch }
hex = self.upcase
hex = '0' + hex if((hex.length & 1) != 0)
hex.scan(/../).map{ |b| b.to_i(16) }.pack('C*')
end
def bin_2_hex
self.unpack('C*').map{ |b| "%02X" % b }.join('')
end
def to_b # to boolean - missing from Ruby
return nil if self.strip.empty?
return false if self.downcase.starts_with? 'f'
return false if self == '0' # the opposite of Ruby
return true if self.downcase.starts_with? 't'
return true if self == '1'
nil
end
end
class NilClass
def short
self
end
def to_b
false
end
end
def can_change?( model ) # e.g. was this report entered by this user or admin? (otherwise they can't edit or delete it)
# puts "can_change? model.class #{model.class} model.get(:id) #{model.get(:id)} model.get(:user_id) #{model.get(:user_id)} current_user.get_id #{current_user.get_id}"
return false unless current_user
return true if current_user.admin?
id = (model.class == User ? model.id : model.get( :user_id )) # Users don't have user ids, they just have ids
id == current_user.get_id
end
def can_delete?( model )
return false unless current_user
current_user.admin?
end
def flash_errs( model )
errs = ''
unless model.errors.empty?
errs = model.errors.collect { |k, v| "#{ k } #{ v }" }.join( '; ')
end
flash[:notice] = errs
errs
end
def word_link
"/images/word#{rand(16).to_s(16).upcase}.jpg"
end
FLASH_SPAN = '<span style="color: #F94909; font-size: 15px;">'
FAKES_LINK = '<h1>fake hate crimes: a database of <a href="/reports">hate crime hoaxes in the usa</a></h1>'
ENDOF_SPAN = '</span><br/>'
LONG_WORDS = "Not signed up: Email should look like an email address., Email can't be blank, Email is invalid, " +
"Password is too short (minimum is 4 characters), Password doesn't match confirmation, Password must " +
"have an upper and lower case letter and a number, and may have punctuation, Password confirmation " +
"is too short (minimum is 4 characters), Secret word - '' is not valid - try again"
MULTI_LINE = (LONG_WORDS.size.to_f / 2.8)
def flash_format( notice )
flash = notice
if flash.blank?
flash = FAKES_LINK
else
flash = FLASH_SPAN + flash + ENDOF_SPAN
end
size = 3 - ((flash.size / MULTI_LINE).to_i + 1)
size = 1 if size < 1
flash += "<br/>\n" * (size - 1)
flash
end
def fake_media(fake)
fakes_media = FakesMedium.all.select{ |fm| fm.fake_id == fake.id }.collect{ |fm| fm.medium_id }
media = Medium.all.select{ |m| fakes_media.include? m.id }
media
end
def medium_fakes(medium)
fakes_media = FakesMedium.all.select{ |fm| fm.medium_id == medium.id }.collect{ |fm| fm.fake_id }
fakes = Fake.all.select{ |f| fakes_media.include? f.id }
fakes
end
module ApplicationHelper
def absolute_path
"#{request.protocol}#{request.host}#{request.fullpath}"
end
end
| true |
a7c163966e9f1ebf1373107d16ccdba1fbf95db0 | Ruby | conyekwelu/rb101 | /euler/3.rb | UTF-8 | 699 | 4.21875 | 4 | [] | no_license | # Largest prime factor
#
# Problem 3
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143 ?
#
# algo:
# iterate from 1 up to input integer
# add to a factor array if factor of input
# select [prime factors], select max of prime factors
def is_prime?(num)
counter = 2
while counter < (num / 2)
return false if num % counter == 0
counter += 1
end
true
end
def largest_prime_factor(num)
largest_prime = 0
index = 1
while index < (num / 2)
largest_prime = index if num % index == 0 && is_prime?(index)
index += 1
end
largest_prime
end
p largest_prime_factor(13195)
p largest_prime_factor(600851475143)
| true |
fc8872e9707d06e02d03c61841553894e4816c58 | Ruby | joubin/gitlabhq | /lib/pager_duty/webhook_payload_parser.rb | UTF-8 | 1,809 | 2.5625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-SA-4.0"
] | permissive | # frozen_string_literal: true
module PagerDuty
class WebhookPayloadParser
SCHEMA_PATH = Rails.root.join('lib', 'pager_duty', 'validator', 'schemas', 'message.json')
def initialize(payload)
@payload = payload
end
def self.call(payload)
new(payload).call
end
def call
Array(payload['messages']).map { |msg| parse_message(msg) }.reject(&:empty?)
end
private
attr_reader :payload
def parse_message(message)
return {} unless valid_message?(message)
{
'event' => message['event'],
'incident' => parse_incident(message['incident'])
}
end
def parse_incident(incident)
{
'url' => incident['html_url'],
'incident_number' => incident['incident_number'],
'title' => incident['title'],
'status' => incident['status'],
'created_at' => incident['created_at'],
'urgency' => incident['urgency'],
'incident_key' => incident['incident_key'],
'assignees' => reject_empty(parse_assignees(incident)),
'impacted_services' => reject_empty(parse_impacted_services(incident))
}
end
def parse_assignees(incident)
Array(incident['assignments']).map do |a|
{
'summary' => a.dig('assignee', 'summary'),
'url' => a.dig('assignee', 'html_url')
}
end
end
def parse_impacted_services(incident)
Array(incident['impacted_services']).map do |is|
{
'summary' => is['summary'],
'url' => is['html_url']
}
end
end
def reject_empty(entities)
Array(entities).reject { |e| e['summary'].blank? && e['url'].blank? }
end
def valid_message?(message)
::JSONSchemer.schema(SCHEMA_PATH).valid?(message)
end
end
end
| true |
260720616f1e7742759c8d5618db4e86a5ad9fe7 | Ruby | bbensky/launch_school | /launch_school_lessons/101-109_small_problems/advanced_1/3_transpose_3x3.rb | UTF-8 | 1,309 | 4.25 | 4 | [] | no_license | # def transpose(matrix)
# transposed_matrix = []
# max_index = matrix.size - 1
# 0.upto(max_index) do |column|
# new_row = []
# matrix.each_index do |row|
# new_row << matrix[row][column]
# end
# transposed_matrix << new_row
# end
# transposed_matrix
# end
# alt w/ map
# def transpose(matrix)
# result = []
# (0..2).each do |column_index|
# new_row = (0..2).map { |row_index| matrix[row_index][column_index] }
# result << new_row
# end
# result
# end
# alt w/ map shorter
def transpose(matrix)
0.upto(matrix.size - 1).map do |col|
matrix.map do |row|
row[col]
end
end
end
matrix = [
[1, 5, 8],
[4, 7, 2],
[3, 9, 6]
]
new_matrix = transpose(matrix)
p new_matrix == [[1, 4, 3], [5, 7, 9], [8, 2, 6]]
p matrix == [[1, 5, 8], [4, 7, 2], [3, 9, 6]]
# further exploration: transpose! method
# def transpose!(matrix)
# max_index = matrix.size - 1
# (0..max_index).each do |first|
# second = first
# second.upto(max_index) do |second|
# matrix[first][second], matrix[second][first] = matrix[second][first], matrix[first][second]
# p matrix
# end
# end
# end
# matrix = [
# [1, 5, 8],
# [4, 7, 2],
# [3, 9, 6]
# ]
# transpose!(matrix)
# p matrix
# p matrix == [[1, 4, 3], [5, 7, 9], [8, 2, 6]]
| true |
14e16b72169692605ca18bc99386141daee9739c | Ruby | uk-gov-mirror/UKGovernmentBEIS.beis-report-official-development-assistance | /app/services/transaction_overview.rb | UTF-8 | 1,153 | 2.71875 | 3 | [
"MIT"
] | permissive | class TransactionOverview
def initialize(activity, report)
@activity = activity
@report = report
end
def all_quarters
group_fields = "transactions.financial_year, transactions.financial_quarter"
relation = transaction_relation
.group(group_fields)
.select("#{group_fields}, SUM(value) AS value")
AllQuarters.new(relation)
end
def value_for_report_quarter
value_for(**@report.own_financial_quarter)
end
def value_for(financial_quarter:, financial_year:)
transaction_relation
.where(financial_quarter: financial_quarter, financial_year: financial_year)
.sum(:value)
end
private
def transaction_relation
Transaction
.joins(:report)
.where(parent_activity_id: @activity.id)
.merge(Report.historically_up_to(@report))
end
class AllQuarters
def initialize(relation)
@index = {}
relation.each do |record|
@index[[record.financial_quarter, record.financial_year]] = record.value
end
end
def value_for(financial_quarter:, financial_year:)
@index.fetch([financial_quarter, financial_year], 0)
end
end
end
| true |
fea8ca415e382f54a9eda3c73ff439f5d1628cbc | Ruby | harisfi/CompetitiveProgramming | /HackerRank/30-Days-of-Code/Day20.rb | UTF-8 | 384 | 3.703125 | 4 | [] | no_license | #!/bin/ruby
n = gets.strip.to_i
a = gets.strip
a = a.split(' ').map(&:to_i)
swaps = 0
for i in 0..(n-1)
for j in 0..(n-2)
if a[j] > a[j+1]
a[j], a[j+1] = a[j+1], a[j]
swaps += 1
end
end
if swaps < 1
break
end
end
puts "Array is sorted in #{swaps} swaps."
puts "First Element: #{a[0]}"
puts "Last Element: #{a[n-1]}"
| true |
95487ab5abcc2adb903e0aa972b6e9a78e4c6d66 | Ruby | tobiasvl/pgnlint | /lib/pgnlint/parser.rb | UTF-8 | 2,522 | 2.578125 | 3 | [] | no_license | require 'parslet'
module PGNLint
class Parser < Parslet::Parser
rule(:space) { match("[[:space:]]").repeat(1) }
rule(:space?) { space.maybe }
root(:pgn_database)
rule(:pgn_database) do
pgn_game.as(:game).repeat.as(:database)
end
rule(:pgn_game) do
tag_section.as(:tags) >>
movetext_section >>
space?
end
rule(:tag_section) { tag_pair.repeat }
rule(:tag_pair) do
str("[") >>
tag_name.as(:tag_name) >>
space >> tag_value >>
str("]") >>
space?
end
rule(:tag_name) { match('[A-Za-z_]').repeat(1) }
rule(:tag_value) do
str('"') >>
match('[[:print:]&&[^"]]').repeat(1).as(:tag_value) >>
str('"')
end
rule(:movetext_section) do
element_sequence.as(:moves) >>
game_termination.as(:termination)
end
rule(:element_sequence) do
(element | variation.as(:variation) | comment >> space?).repeat
end
rule(:element) do
(move_number.as(:move_number) >> space?).maybe >>
san_move.as(:san_move) >> space? >>
(nag.as(:nag) >> space).maybe
end
rule(:string) { match('[[:print:]&&[^}]]').repeat(1) }
rule(:game_termination) { str('1-0') | str('0-1') | str('1/2-1/2') | str('*') }
rule(:move_number) { match('[0-9]').repeat(1) >> str('.').repeat(1) }
rule(:san_move) { (castle | pawn_move.as(:pawn) | major_move.as(:major) ) >> promotion.as(:promotion).maybe >> check.as(:check).maybe }
rule(:nag) { str('$') >> match('[0-9]').repeat(1) }
rule(:comment) { str("{") >> space? >> string.as(:comment) >> space? >> str("}") }
# TODO multiline comments
rule(:variation) { str("(") >> element_sequence >> str(")") >> space? }
rule(:check) { match('[+#]') }
rule(:promotion) { str('=') >> (str('B').as(:bishop) | str('N').as(:knight) | str('Q').as(:queen) | str('R').as(:rook)) }
rule(:major_move) do
match('[BKNQR]') >>
# TODO better optional from rank and file
str('x').maybe >>
match('[a-h]') >>
match('[1-8]') |
match('[BKNQR]') >>
match('[a-h]') >>
str('x').maybe >>
match('[a-h]') >>
match('[1-8]')
end
rule(:pawn_move) do
match('[a-h]') >>
(match('[1-8]') | str('x')) >>
(match('[a-h]') >> match('[1-8]')).maybe
end
rule(:castle) do
(str('O-O') | str('0-0')).as(:castle) >> space |
(str('O-O-O') | str('0-0-0')).as(:castle)
end
end
end
| true |
1f43ef63e866881d4ff757aa746b1c6038b80318 | Ruby | page-io/ruby-twig | /lib/twig/sandbox/security_policy.rb | UTF-8 | 2,761 | 2.765625 | 3 | [] | no_license | module Twig
module Sandbox
class SecurityPolicy
def initialize(allowed_tags = [], allowed_filters = [], allowed_methods = [], allowed_properties = [], allowed_functions = [])
@allowed_tags = allowed_tags
@allowedilters = allowed_filters
set_allowed_methods(allowed_methods)
@allowed_properties = allowed_properties
@allowed_functions = allowed_functions
end
def set_allowed_tags(tags)
@allowed_tags = tags
end
def set_allowed_filters(filters)
@allowedilters = filters
end
def set_allowed_methods(methods)
@allowed_methods = []
methods.each do |klass, m|
@allowed_methods[klass] = (m.is_a?(::Array) ? m : [m]).map(&:downcase)
end
end
def set_allowed_properties(properties)
@allowed_properties = properties;
end
def set_allowed_functions(functions)
@allowed_functions = functions
end
def check_security(tags, filters, functions)
tags.each do |tag|
unless @allowed_tags.include?(tag)
raise Twig::Sandbox::SecurityNotAllowedTagError.new("Tag \"#{tag}\" is not allowed.", tag)
end
end
filters.each do |filter|
unless @allowed_filters.include?(filter)
raise Twig::Sandbox::SecurityNotAllowedFilterError.new("Filter \"#{filter}\" is not allowed.", filter)
end
end
functions.each do |function|
unless @allowed_functions.include?(function)
raise Twig::Sandbox::SecurityNotAllowedFunctionError.new("Function \"#{function}\" is not allowed.", function)
end
end
end
def check_method_allowed(obj, method)
if obj.is_a?(Twig::Template) || obj.is_a?(Twig::Markup)
return true
end
allowed = false
method = method.downcase
@allowed_methods.each do |klass, methods|
if obj.is_a?(klass)
allowed = methods.include?(method)
break
end
end
unless allowed
raise Twig::Sandbox::SecurityError.new(sprintf('Calling "%s" method on a "%s" object is not allowed.', method, obj.class.name))
end
end
def check_property_allowed(obj, property)
allowed = false
@allowed_properties.each do |klass, properties|
if obj.is_a?(klass)
allowed = (properties.is_a?(::Array) ? properties : [properties]).include?(property)
break
end
end
unless allowed
raise Twig::Sandbox::SecurityError.new(sprintf('Calling "%s" property on a "%s" object is not allowed.', property, obj.class.name));
end
end
end
end
end
| true |
3b7d1012953064a044d1b67f4355c465cf4cb18f | Ruby | stefluu/aA-Classwork | /W2D2/Chess Game/Piece.rb | UTF-8 | 386 | 3.1875 | 3 | [] | no_license | require_relative "Board.rb"
class Piece
attr_reader :val
def initialize(val)
@valid_moves = []
@val = val
end
def valid_move?(end_pos)
true
#some list of valid ones, and check if the pos is there. return bool
end
def inspect
self.val.colorize()
end
def moves;end
end
class NullPiece < Piece
def initialize
@val = "N"
end
end
| true |
109519a05238879f7d1fdf60a61bccaff0689303 | Ruby | cescarez/string-manipulation-practice | /lib/reverse_sentence.rb | UTF-8 | 2,533 | 4.25 | 4 | [] | no_license | # A method to reverse the words in a sentence, in place.
# METHOD 1: USING .REPLACE, but is that an "in-place" reversal? Really it's a reversal in a new string and replacing the contents of the passed in object with the values of the new string....
# Time complexity: O(nm), where n is number of words in the sentence and m is the number of chars in the sentence
# Space complexity: O(n), where n is the number of words in the sentence
# sources: https://ruby-doc.org/core-2.6.5/String.html#method-i-split;https://ruby-doc.org/core-2.6.5/String.html#method-i-replace
# def reverse_sentence(my_sentence)
# if my_sentence
# new_sentence = my_sentence.split(/\ {1}/, my_sentence.length)
# i = 0
# j = new_sentence.length - 1
# while i <= j
# new_sentence[i], new_sentence[j] = new_sentence[j], new_sentence[i]
# j -= 1
# i += 1
# end
# my_sentence.replace new_sentence.join(' ')
# end
# return my_sentence
# end
# METHOD 2: NOT USING .REPLACE -- it's a plate of spaghetti
# Time complexity: O(nm), where n is number of words in the sentence and m is the number of chars in the sentence
# Space complexity: O(n), where n is the number of words in the sentence
def reverse_sentence(my_sentence)
if my_sentence
space_indices = get_num_spaces(my_sentence)
word_swap(my_sentence, space_indices)
end
end
def get_num_spaces(sentence)
original_sentence = sentence.dup
parsed_sentence = sentence.dup
space_indices = []
i = 0
while parsed_sentence.include?(' ')
space_index = space_indices[i - 1] ? space_indices[i - 1] + 1 : 0
space_index += (parsed_sentence =~ /\s/)
parsed_sentence = original_sentence[space_index + 1..-1]
space_indices << space_index
i += 1
end
return space_indices
end
def word_swap(sentence, space_indices)
original_sentence = sentence.dup
word_first = 0
unsorted_last = sentence.length - 1
num_words = space_indices.length + 1
num_words.times do |i|
if word_first < original_sentence.length
space_index = space_indices[i] ? space_indices[i] : original_sentence.length
word_last = space_index - 1
sentence[-space_index..unsorted_last] = original_sentence[word_first..word_last]
#use space_index, but make more negative since counting from string end starts at -1
if space_index < original_sentence.length
sentence[-space_index - 1] = " "
end
unsorted_last = original_sentence.length - (space_index + 2)
word_first = space_index + 1
end
end
end
| true |
61ca62339fb24d042d5b5f5bfc723471222e93c4 | Ruby | ssheehan1210/phase-0-tracks | /ruby/gps6/my_solution.rb | UTF-8 | 2,835 | 3.59375 | 4 | [] | no_license | # Virus Predictor
# I worked on this challenge [with: Yamini S., Sam Sheehan].
# We spent [#] hours on this challenge.
# EXPLANATION OF require_relative
# lists a relative path, includes it in the document if its accessible
# separate from 'require', in which you refer to an absolute path
# if not found, then it will try to access from $LOAD_PATH
require_relative 'state_data'
module Statistics
# takes in three variables, output stored in number of deaths
# prints separate string with results
def predicted_deaths
hash_new = {200 => 0.4, 150 => 0.3, 100 => 0.2, 50 => 0.1, 0 => 0.05}
number_of_deaths = 0
hash_new.each do |i,j|
if @population_density >= i
number_of_deaths = (@population * j).floor
break
end
end
print "#{@state} will lose #{number_of_deaths} people in this outbreak"
end
# takes in two variables, output stored in speed
# prints separate string with results
def speed_of_spread
hash_new = {200 => 0.5, 150 => 1.0, 100 => 1.5, 50 => 2.0, 0 => 2.5}
speed = 0.0
hash_new.each do |i,j|
if @population_density >= i
speed = j
break
end
end
puts " and will spread across the state in #{speed} months.\n\n"
end
end
class VirusPredictor
include Statistics
# initializes each instance, takes in three variables
# assigns three instance variables
def initialize(state_of_origin, population_density, population)
@state = state_of_origin
@population = population
@population_density = population_density
end
# first method takes in three instance variables
# second method takes in two instance variables
def virus_effects
predicted_deaths
speed_of_spread
end
# private
end
#=======================================================================
# DRIVER CODE
# initialize VirusPredictor for each state
STATE_DATA.each do |state,population|
current_state = VirusPredictor.new(state, population[:population_density], population[:population])
current_state.virus_effects
end
# alabama = VirusPredictor.new("Alabama", STATE_DATA["Alabama"][:population_density], STATE_DATA["Alabama"][:population])
# alabama.virus_effects
# jersey = VirusPredictor.new("New Jersey", STATE_DATA["New Jersey"][:population_density], STATE_DATA["New Jersey"][:population])
# jersey.virus_effects
# california = VirusPredictor.new("California", STATE_DATA["California"][:population_density], STATE_DATA["California"][:population])
# california.virus_effects
# alaska = VirusPredictor.new("Alaska", STATE_DATA["Alaska"][:population_density], STATE_DATA["Alaska"][:population])
# alaska.virus_effects
#=======================================================================
# Reflection Section
| true |
e0ff358aaaf5d0a2b35420d76bfa2195e30f3822 | Ruby | binitkumar/campusdream | /app/models/test_participation.rb | UTF-8 | 581 | 2.515625 | 3 | [] | no_license | class TestParticipation < ActiveRecord::Base
attr_accessible :question_paper_id, :score, :time_consumed, :user_id
belongs_to :question_paper
belongs_to :user
def self.current_participation(question_paper_id,user_id)
where(
question_paper_id: question_paper_id,
user_id: user_id
).first
end
def percentile
lesser_count = 0
question_paper.test_participations.each do |participation|
lesser_count += 1 if score >= participation.score
end
( lesser_count.to_f / question_paper.test_participations.length.to_f ) * 100
end
end
| true |
3d44156a6a97f58a25d3cf795aed0fa93decf3aa | Ruby | Shopify/redis-tools | /tools/bin/redis-slowlog | UTF-8 | 1,996 | 2.859375 | 3 | [] | no_license | #!/usr/bin/ruby
$LOAD_PATH << File.dirname(File.realpath(__FILE__)) + "/../lib"
require 'redis_tool'
require 'statsd'
class SlowLogger < RedisTool
class Entry < Struct.new(:id, :timestamp, :duration, :command_name, :arguments, :command, :command_raw)
def initialize(id, timestamp, duration, command)
super(id, timestamp, duration)
self.command_name = command.first
self.command = command.join(' ')
self.command_raw = command
if command.last.scrub =~ /\A\.\.\. \((\d+) more arguments\)\z/
self.arguments = command.count + $1.to_i - 2 # minus command (first) and "more arguments" (last)
else
self.arguments = command.count - 1 # minus command (first)
end
end
def log_params
to_h
end
unless instance_methods.include?(:to_h) # Ruby 2+
def to_h
Hash[each_pair.to_a]
end
end
end
def initialize(*args)
super(*args)
@max_seen_id = -1
@statsd = Statsd.new
@statsd.tags = ["port:#{@redis.client.port}"]
if instance = ENV['REDIS_INSTANCE']
@statsd.tags << "instance:#{instance}"
end
end
protected
def run_wrapped
unseen_slowlog_entries(1) # discard prior entries
loop do
output_slowlog(unseen_slowlog_entries)
sleep(5)
end
end
private
def output_slowlog(entries)
entries.each do |entry|
log("slowlog", entry.log_params)
opts = {:tags => ["command:#{entry.command_name}"]}
@statsd.increment('redis.slowlog.count', opts)
@statsd.histogram('redis.slowlog.duration', entry.duration, opts)
@statsd.histogram('redis.slowlog.arguments', entry.arguments, opts)
end
end
def unseen_slowlog_entries(count = 1000)
unseen = @redis.slowlog('get', count).take_while { |id, *_| id > @max_seen_id }
entries = unseen.reverse.map { |data| Entry.new(*data) }
@max_seen_id = entries.last.id unless entries.empty?
entries
end
end
SlowLogger.from_argv(*ARGV).run
| true |
a1a2d7c38401d09381ebc41464ab48d835950bb5 | Ruby | Fleurtam/fizz_buzz | /lib/fizz_buzz.rb | UTF-8 | 385 | 3.984375 | 4 | [] | no_license |
def fizz_buzz(number)
if number.is_a? String
'You should enter a number'
elsif number < 0
'You should enter a number'
elsif has_zero_remainder?(number, 15)
'fizz_buzz'
elsif has_zero_remainder?(number, 3)
'fizz'
elsif has_zero_remainder?(number, 5)
'buzz'
else
number
end
end
def has_zero_remainder?(number, divider)
number % divider == 0
end
| true |
cd21fe8e2f2c9637ac52c2f13f5dc2bc81b049f8 | Ruby | jacekm123/Zadania_Podstawowe | /zadanie2.rb | UTF-8 | 290 | 3.359375 | 3 | [] | no_license | #Zadanie2.
#Zadeklaruj zmienną przechowującą swoje imię, wypisz na ekran ostatnią literę swojego imienia.
imie = "Jacek"
jacek_tablica = imie.split("")
puts jacek_tablica
puts "Za pomoca elementu tablicy:"
puts jacek_tablica[4]
puts "Za pomoca metody last:"
puts jacek_tablica.last
| true |
7ca2cd20c181319178c233a3ff59fbc527a77536 | Ruby | xenfinity/Intro-to-Programming-Exercises | /4 - Loops & Iterators/3-Recursion.rb | UTF-8 | 167 | 3.421875 | 3 | [] | no_license | def count_down(num)
puts num
count_down(num-1) unless num == 0
end
def count_up(num)
count_up(num-1) unless num == 0
puts num
end
count_down(47)
count_up(47) | true |
f549801e9462df655febdf22cf3ec83099ed9f9f | Ruby | rednblack99/messenger-Wed | /spec/unit/message_unit_spec.rb | UTF-8 | 582 | 2.8125 | 3 | [] | no_license | require './lib/message.rb'
describe Message do
input = "this string is more than 20 characters"
let(:time_double) { DateTime.now.strftime("%d/%m/%Y %H:%M:%S:%L.%P") }
subject(:message) { described_class.create(:content => input) }
it 'stores given message as content' do
expect(message.content).to eq("this string is more than 20 characters")
end
it 'has time' do
time_double.freeze
expect(message).to have_attributes(:display_time => time_double)
end
it 'only displays first 20 characters' do
expect(message.preview.length).to eq(20)
end
end
| true |
6d38e00c6ce0a59f829472cc61cff3ed613fdfe9 | Ruby | fluffypancakes159/08zbuffer | /main.rb | UTF-8 | 5,187 | 2.75 | 3 | [] | no_license | require_relative 'line'
require_relative 'matrix'
require_relative 'transform'
require_relative 'curve'
require_relative 'solid'
require_relative 'polygon'
def main() # remember to change XRES and YRES
out = Array.new(YRES) {Array.new(XRES, [0, 0, 0])}
zbuffer = Array.new(YRES) {Array.new(XRES, nil)}
# transform = ident(4)
edges = Array.new(0)
triangles = Array.new(0)
stack = [ident(4)]
file_data = []
# script()
File.open('script.txt', 'r') {|file|
# File.open('lol.txt', 'r') {|file|
file.each_line { |line|
file_data.append(line.strip)
}
}
while file_data.length > 0
current = file_data.shift # pop first element off array
if current[0] == '#'
next # continue in python
=begin
elsif current == 'ident'
=end
transform = ident(4)
elsif current == 'scale'
factors = file_data.shift.split(" ")
stack[0] = mult(stack[0], scale(*factors))
elsif current == 'move'
dists = file_data.shift.split(" ")
stack[0] = mult(stack[0], trans(*dists))
elsif current == 'rotate'
args = file_data.shift.split(" ")
stack[0] = mult(stack[0], rot(*args))
=begin
elsif current == 'apply'
mult(transform, edges)
mult(transform, triangles)
=end
elsif current == 'display'
# out = Array.new(YRES) {Array.new(XRES, [0, 0, 0])}
# draw_matrix(out, edges, 0)
# draw_matrix(out, triangles, 1)
save_ppm(out, XRES, YRES)
`display image.ppm` # ` ` runs terminal commands
elsif current == 'save'
out_file = file_data.shift
# out = Array.new(YRES) {Array.new(XRES, [0, 0, 0])}
# draw_matrix(out, edges, 0)
# draw_matrix(out, triangles, 1)
save_ppm(out, XRES, YRES)
`convert image.ppm #{out_file}`
elsif current == 'line'
coords = file_data.shift.split(" ")
add_edge(edges, *(coords.map {|x| x.to_f}))
mult(stack[0], edges)
draw_matrix(out, edges, 0, zbuffer)
edges.clear
elsif current == 'circle'
args = file_data.shift.split(" ")
args.map! {|x| x.to_f} # ! actually replaces the array
add_circle(edges, *args)
mult(stack[0], edges)
draw_matrix(out, edges, 0, zbuffer)
edges.clear
elsif current == 'hermite'
args = file_data.shift.split(" ")
args.map! {|x| x.to_f}
add_hermite(edges, *args)
mult(stack[0], edges)
draw_matrix(out, edges, 0, zbuffer)
edges.clear
elsif current == 'bezier'
args = file_data.shift.split(" ")
args.map! {|x| x.to_f}
add_bezier(edges, *args)
mult(stack[0], edges)
draw_matrix(out, edges, 0, zbuffer)
edges.clear
elsif current == 'clear'
out = Array.new(YRES) {Array.new(XRES, [0, 0, 0])}
zbuffer = Array.new(YRES) {Array.new(XRES, nil)}
elsif current == 'box'
args = file_data.shift.split(" ")
args.map! {|x| x.to_f}
add_box(triangles, *args)
mult(stack[0], triangles)
draw_matrix(out, triangles, 1, zbuffer)
triangles.clear
elsif current == 'sphere'
args = file_data.shift.split(" ")
args.map! {|x| x.to_f}
add_sphere(triangles, 20, *args)
mult(stack[0], triangles)
draw_matrix(out, triangles, 1, zbuffer)
triangles.clear
elsif current == 'torus'
args = file_data.shift.split(" ")
args.map! {|x| x.to_f}
add_torus(triangles, 20, *args)
mult(stack[0], triangles)
draw_matrix(out, triangles, 1, zbuffer)
triangles.clear
elsif current == 'push'
stack.unshift(stack[0].map {|x| x})
elsif current == 'pop'
stack.shift
end
end
end
def save_ppm(ary, xdim, ydim)
File.open('image.ppm', 'w') {|file|
file.write("P3\n#{xdim}\n#{ydim}\n255\n")
ary.length.times {|i|
ary[i].length.times{|j|
3.times {|k|
# puts "#{i} #{j} #{k}"
file.write(ary[i][j][k].to_s + ' ')
}
}
}
}
end
def script()
stuff = [100, 200, 300, 400, 500]
File.open('script.txt', 'w') {|file|
stuff.length.times {|x|
x.times {|y|
file.write("bezier\n")
file.write("#{stuff[y]} 0 #{stuff[x]} #{stuff[x]} 0 #{stuff[y]} 0 0\n")
file.write("hermite\n")
file.write("0 #{stuff[y]} #{stuff[x]} #{stuff[x]} 100 100 -100 100\n")
}
}
file.write("display\n")
file.write("save\nimage.png")
}
end
main()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.