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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9ca0b9215db85a09d1c6afaf350b4ab1eb804910
|
Ruby
|
JuliaPrussia/BasicRuby
|
/Carriage.rb
|
UTF-8
| 962
| 3.328125
| 3
|
[] |
no_license
|
require_relative 'modules/manufacturer_company'
require_relative 'modules/instance_counter'
require_relative 'modules/validate'
class Carriage
include ManufacturerCompany
include InstanceCounter
include Validate
attr_reader :num,
:type
NUM_TEMPLATE = /^[a-z\d]{3}$/
def initialize(num, space)
@num = num
@type
@space = space
@occupied_space = 0
validate!
register_instance
end
def takes_up_space(occupied)
if occupied <= all_free_space
@occupied_space += occupied
end
end
def all_free_space
@space - @occupied_space
end
def all_occupied_space
@occupied_space
end
protected
def validate!
raise "Неправильный формат номера!(формат номера ххх, где х-строчная буква латинского алфавита или цифра)" unless @num =~ NUM_TEMPLATE
end
end
| true
|
3e3ba7356faa492c68f940ae338f6989804ced43
|
Ruby
|
jhartwell/ironruby
|
/Tests/Experiments/Globals/Semicolon.rb
|
UTF-8
| 637
| 3.59375
| 4
|
[] |
no_license
|
puts "Initial value"
p $;
$x = "a"
$; = "b"
alias $old_slash $;
alias $; $x
p $;
puts "---"
p '123a456b789'.split # [123a456,789] -> ignores alias
puts "","---"
p $;.object_id == $;.object_id
alias $; $old_slash # restore $;
puts '-' * 20
$; = nil
p '123a456b789'.split # [123a456b789]
$; = 5
p '123a456b789'.split rescue p $! # `split': wrong argument type Fixnum (expected Regexp)
class S
def to_s; "a"; end
def to_str; "b"; end
end
$; = S.new
p '123a456b789'.split rescue p $! # ["123a456", "789"]
puts 'Done'
| true
|
426e66101b5a38329ee52569f02e2f22deec580b
|
Ruby
|
marcwright/WDI_ATL_1_Instructors
|
/REPO - DC - Students/w03/d01/Jacob/superhero/superheroes.rb
|
UTF-8
| 3,845
| 3.53125
| 4
|
[] |
no_license
|
require 'pg'
superhero_conn = PG.connect(:dbname => 'superheroes_db', :host => 'localhost')
def answer_to(question)
puts question
answer = gets.chomp
end
def menu_options
puts "Please select an option from the menu:"
puts "(I) Index - List all Super Heros"
puts "(C) Add a Super Hero"
puts "(R) View all info for a specific Super Hero"
puts "(U) Update a Super Hero"
puts "(D) Remove a Super Hero"
puts "(Q) Quit"
end
def list_heroes(connection)
puts connection.exec("SELECT superhero_name FROM superheroes;").values
end
def add_hero(connection)
name_input = answer_to("What is the name of this superhero?")
alter_ego_input = answer_to("What is the superhero's alter ego?")
power_input = answer_to("What is the superhero's superpower?")
cape_input = answer_to("Does this superhero have a cape? (y/n)")
if cape_input.downcase == 'y'
cape_input = true
else
cape_input = false
end
arch_nemesis_input = answer_to("Who is the superhero's arch nemesis?")
connection.exec("INSERT INTO superheroes (superhero_name, alter_ego, power, has_cape, arch_nemesis) VALUES ('#{name_input}', '#{alter_ego_input}', '#{power_input}', '#{cape_input}', '#{arch_nemesis_input}');")
end
def view_info(connection)
puts "Here are the superheroes:"
puts list_heroes(connection)
user_name_input = answer_to("Please enter the superhero whose information you'd like to view:")
results = connection.exec("SELECT*FROM superheroes WHERE superhero_name = '#{user_name_input}'")
puts results[0]
end
def update_hero(connection)
puts "Here are the superheroes:"
puts list_heroes(connection)
user_name_input = answer_to("Please enter the name of the superhero whose information you'd like to update:")
puts "Please chose the number corresponding to the attribute of #{user_name_input} you'd like to change:"
puts "1. Name"
puts "2. Alter Ego"
puts "3. Cape/No Cape"
puts "4. Superpower"
puts "5. Arch Nemesis"
attribute = gets.chomp.to_i
case attribute
when 1
new_name = answer_to("What would you like to change #{user_name_input}'s name to?")
connection.exec("UPDATE superheroes SET superhero_name = '#{new_name}' WHERE superhero_name = '#{user_name_input}';")
when 2
new_alter_ego = answer_to("What would you like to change #{user_name_input}'s alter ego to?")
connection.exec("UPDATE superheroes SET alter_ego = '#{new_alter_ego}' WHERE superhero_name = '#{user_name_input}';")
when 3
new_cape_status = answer_to("What would you like to change #{user_name_input}'s cape status to? (cape/no cape)")
if new_cape_status.downcase == "cape"
new_cape_status = true
else
new_cape_status = false
end
connection.exec("UPDATE superheroes SET has_cape = '#{new_cape_status}' WHERE superhero_name = '#{user_name_input}';")
when 4
new_superpower = answer_to("What would you like to change #{user_name_input}'s superpower to?")
connection.exec("UPDATE superheroes SET power = '#{new_superpower}' WHERE superhero_name = '#{user_name_input}';")
when 5
new_nemesis = answer_to("Who would you like to change #{user_name_input}'s arch-nemesis to?")
connection.exec("UPDATE superheroes SET arch_nemesis = '#{new_nemesis}' WHERE superhero_name = '#{user_name_input}';")
end
end
def remove_hero(connection)
name_delete = answer_to("Which hero would you like to remove?")
connection.exec("DELETE FROM superheroes WHERE superhero_name = '#{name_delete}'")
end
while true
menu_options
response = gets.chomp.downcase
break if response == 'q'
case response
when 'i'
list_heroes(superhero_conn)
when 'c'
add_hero(superhero_conn)
when 'r'
view_info(superhero_conn)
when 'u'
update_hero(superhero_conn)
when 'd'
remove_hero(superhero_conn)
end
end
| true
|
ab29d45bb523f5d7f0ef1f55c21f36220253e8c3
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/raindrops/dfc8c6a660b94175a9a3c2bc8cbc274e.rb
|
UTF-8
| 330
| 3.265625
| 3
|
[] |
no_license
|
require 'prime'
class Raindrops
RAINDROPS = {
3 => 'Pling',
5 => 'Plang',
7 => 'Plong'
}
def self.convert(num)
primes = num.prime_division.collect {|f| f[0] }
str = ''
RAINDROPS.each do |key,raindrop|
str << raindrop if primes.include? key
end
str.empty? ? num.to_s : str
end
end
| true
|
64a14b02871a54c5a6011f84ad9dfa359dbf6532
|
Ruby
|
aryazar86/ruby_fundamentals1
|
/exercise4.rb
|
UTF-8
| 208
| 3.421875
| 3
|
[] |
no_license
|
100.downto(1). each do |i|
multiple = false
if i%3 == 0
print "Bit"
multiple = true
end
if i%5 == 0
print "Maker"
multiple = true
end
if multiple == false
print "#{i}"
end
puts " "
end
| true
|
138c68beb2ac399bc2013bc2c98d90603074dfa3
|
Ruby
|
cruessler/lafamiglia.rb
|
/lib/researches.rb
|
UTF-8
| 924
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
module LaFamiglia
class Research
def key
"research_#{id}".to_sym
end
def name
@name ||= I18n.t "researches.#{key}"
end
def requirements_met? villa
villa.building_2 > 0
end
attr_accessor :id
attr_accessor :maxlevel
attr_writer :research_time, :costs
def research_time level
@research_time[level] / LaFamiglia.config.game_speed
end
def costs level
@costs[level]
end
end
@@researches ||= []
def @@researches.add
@@researches.push(Research.new)
yield @@researches.last
end
def @@researches.get_by_id research_id
@@researches.find do |r|
r.id == research_id
end
end
mattr_accessor :researches
module Researches
module Readers
def researches
LaFamiglia.researches.each_with_object({}) do |r, hash|
hash[r.key] = self.send(r.key)
end
end
end
end
end
| true
|
92d220546c9cfbf26f24ce474791303b738deece
|
Ruby
|
ivanternovyi/repo
|
/ts_shoulda.rb
|
UTF-8
| 1,224
| 3.03125
| 3
|
[] |
no_license
|
require 'test/unit'
require 'shoulda'
require_relative 'TennisScorer.rb'
class TennisScorerTest < Test::Unit::TestCase
def assert_score(target)
assert_equal(target, @ts.score)
end
context "Tennis scores" do
setup do
@ts = TennisScorer.new
end
should "start wit a score of 0-0" do
assert_score("0-0")
end
should "be 15-0 if server wins" do
@ts.give_point_to(:server)
assert_score("15-0")
end
should "be 0-15 if receiver wins" do
@ts.give_point_to(:receiver)
assert_score("0-15")
end
should "be 15-15 if both of them wins one point" do
@ts.give_point_to(:receiver)
@ts.give_point_to(:server)
assert_score("15-15")
end
should "be 45-0 after the server wins three points ahead" do
3.times do
@ts.give_point_to(:server)
end
assert_score("45-0")
end
should "be W-L after the server wins four points" do
4.times do
@ts.give_point_to(:server)
end
assert_score("W-L")
end
should "be L-W after the server wins four points" do
4.times do
@ts.give_point_to(:receiver)
end
assert_score("L-W")
end
end
end
| true
|
2f108a1c85f6dabb8a1f2418511f0c922b9997e2
|
Ruby
|
makeitgo/didyou
|
/app/models/counter_group.rb
|
UTF-8
| 329
| 2.578125
| 3
|
[] |
no_license
|
class CounterGroup < ActiveRecord::Base
has_many :counter_items
def summary_count
counter_items.inject(0) { |value, item| value += item.count }
end
def item(name)
if !counter_items.exists?(name: name)
counter_items.create(name: name, count: 0)
end
counter_items.where(name: name)
end
end
| true
|
0b23f930f30f4e5aebfde90c086db785a59a5f18
|
Ruby
|
jessicadavey/ls_small_problems_exercises
|
/medium_2/exercise_7.rb
|
UTF-8
| 263
| 3.59375
| 4
|
[] |
no_license
|
require 'date'
MONTHS = (1..12).to_a.freeze
def friday_13th(year)
thirteenths = MONTHS.map do |month|
Date.new(year, month, 13)
end
thirteenths.count(&:friday?)
end
puts friday_13th(2015) == 3
puts friday_13th(1986) == 1
puts friday_13th(2019) == 2
| true
|
7c8283088fa2d1e2093a219008f45b36c980492c
|
Ruby
|
jwoertink/shoes4
|
/lib/shoes/swt/text_fragment.rb
|
UTF-8
| 1,207
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
module Shoes
module Swt
class TextFragment
include Common::Child
attr_accessor :style, :widget
# Need the widget or text element to apply this new style to
def initialize(dsl, parent)
@dsl = dsl
@parent = parent
@style = ::Swt::Custom::StyleRange.new
end
def set_substring(index)
@style.start = index
@style.length = @dsl.text.length
end
def set_style(widget, index)
@widget = widget
#This number needs to be the index of @dsl.text in @widget.text
# can't just do a simple regex in case there's a string like
# para("test", "test", strong("test"), "test", "test")
set_substring(index)
@widget.style_range = @style
end
def width
@widget.size.x
end
def height
@widget.size.y
end
def move(left, top)
@widget.set_location(left, top) unless @widget.disposed?
end
end
class Strong < TextFragment
def initialize(dsl, parent)
super(dsl, parent)
@style.fontStyle = ::Swt::SWT::BOLD
end
end
end
end
| true
|
bd4018d9c45a07ce5055b086cca6b39bc4ee216c
|
Ruby
|
addisonmartin/AdventOfCode
|
/2020/1-1.rb
|
UTF-8
| 499
| 3.125
| 3
|
[] |
no_license
|
sum = 2020
def readInputsFromFile(path)
raw_inputs = []
File.readlines(path).each do |line|
raw_inputs << line.chomp.to_i
end
raw_inputs
end
inputs = readInputsFromFile('day_1_inputs.txt')
for input in inputs
for other_input in inputs
unless input == other_input
if input + other_input == sum
puts "#{input * other_input} = #{input} * #{other_input}"
puts "#{input + other_input} = #{input} + #{other_input}"
end
end
end
end
| true
|
8c871f77761c0b223acc7049292d4d3b92246fb9
|
Ruby
|
sonnym/array_decay
|
/lib/array_decay.rb
|
UTF-8
| 396
| 2.96875
| 3
|
[
"MIT"
] |
permissive
|
require_relative 'array_decay/version'
class Array
def decay!
ArrayDecay::Enumerator.new(self)
end
end
module ArrayDecay
class Enumerator
include Enumerable
attr_accessor :enumerator
def initialize(enumerator)
self.enumerator = enumerator
end
def each(&block)
until enumerator.empty?
block.call(enumerator.shift)
end
end
end
end
| true
|
cb52e9b852aacc409951c98d23c44731cfa6117d
|
Ruby
|
shved270189/ya_metrika
|
/lib/ya_metrika/client.rb
|
UTF-8
| 1,643
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
require 'ya_metrika/settings'
require 'net/http'
module YaMetrika
class Client
HOST = 'http://api-metrika.yandex.ru'
REST_METHODS = [:get, :post, :put, :delete]
def initialize(options = {})
options = YaMetrika::Settings.to_hash.merge(options)
@format = options[:format]
@oauth_token = options[:oauth_token]
@spells = Array.new
end
def method_missing(meth, *args, &block)
if YaMetrika::Client::REST_METHODS.include?(meth.to_sym)
rest(meth, *args, &block)
else
@spells << meth.to_s
@spells << args.first.to_s if args.first
self
end
end
private
def request_path(options)
[@spells.inject('') { |r, spell| r + '/' + spell }, '.', @format.to_s, request_params(options)].join
end
def request_url(options)
YaMetrika::Client::HOST + request_path(options)
end
def request_params(options)
options.inject("?oauth_token=#{@oauth_token}") { |res, option| res + "&#{option.to_a.first.join('=')}" }
end
def rest(meth, *args, &block)
url = request_url(args)
uri = URI(url)
@spells = Array.new
request = case meth
when :get
Net::HTTP::Get.new(uri)
when :post
Net::HTTP::Post.new(uri)
when :put
Net::HTTP::Put.new(uri)
when :delete
Net::HTTP::Delete.new(uri)
end
result = Net::HTTP.start(uri.hostname, uri.port) do |http|
http.request(request)
end
result
end
end
end
| true
|
02e7ce6397979a0f401b6f295ec184ee56011b82
|
Ruby
|
ChernayaJuly/Ruby
|
/lb1_z5.rb
|
UTF-8
| 191
| 3.578125
| 4
|
[] |
no_license
|
numb = ARGV[0]
numb = numb.to_i
def last_digit(x,q=10)
x % q
end
def digits_sum(x,q=10)
sum = 0
while x > 0
sum+= last_digit(x,q)
x /= q
end
sum
end
puts digits_sum(numb)
| true
|
4df791615e81c60e7b20a6908ffdc1123d553d27
|
Ruby
|
kennojc/online_arrays
|
/desafio1array.rb
|
UTF-8
| 807
| 4.375
| 4
|
[] |
no_license
|
#con map sumarle 1 a los elementos
def plus_one(a)
sum = a.map {|x| x+1 }
print sum
end
#con map pasarlos a float
def to_float(a)
floats = a.map {|x| x.to_f}
print floats
end
#Utilizando select descartar todos los elementos menores a 5 en el array.
def discard(a)
clean = a.select {|x| x >= 5}
print clean
end
#Utilizando inject sumar todos los valores del array.
def addition(a)
sum = a.inject(0) {|sum,x| sum + x}
print sum
end
#Utilizando .count contar todos los elementos menores que 5.
def small_numbers(a)
small = a.count {|x| x < 5}
print small
end
a = [1, 9 ,2, 10, 3, 7, 4, 6]
print plus_one (a)
puts "\n"
print to_float (a)
puts "\n"
print discard (a)
puts "\n"
print addition (a)
puts "\n"
print small_numbers (a)
puts "\n"
| true
|
7e98fb37e78273acea45fdb0700b48ed964a5d41
|
Ruby
|
intenex/aa-practice-test-generator
|
/problems/eight_queens.rb
|
UTF-8
| 686
| 4.03125
| 4
|
[] |
no_license
|
# Write a recursive method that generates the number of possible unique ways to
# place eight queens on a chess board such that no two queens are in
# the row, column, or diagonal. A skeleton for a possible solution is
# provided. Feel free to create your own solution from scratch.
class EightQueens
attr_accessor :rows, :diags1, :diags2
def initialize
@rows = Array.new(8, false)
@diags1 = Array.new(14, false)
@diags2 = Array.new(14, false)
end
def backtrack(row = 0, count = 0)
end
def is_not_under_attack(row, col)
end
def place_queen(row, col)
end
def remove_queen(row, col)
end
end
eight_queens = EightQueens.new()
eight_queens.backtrack
| true
|
5b0b7c8259a8f09f4836d68c7e09d6a8b7bfd11f
|
Ruby
|
Eulers-Bridge/isegoriaweb
|
/app/controllers/tickets_controller.rb
|
UTF-8
| 11,516
| 2.59375
| 3
|
[] |
no_license
|
class TicketsController < ApplicationController
#Set the default layout for this controller, the views from this controller are available when the user is looged in
layout 'application'
=begin
--------------------------------------------------------------------------------------------------------------------------------
Function to retrieve and list all the tickets from the model by its election id
--------------------------------------------------------------------------------------------------------------------------------
=end
def index
@menu='tickets' #Set the menu variable
$title=t(:title_tickets) #Set the title variable
if !check_session #Validate if the user session is active
return #If not force return to trigger the redirect of the check_session function
end
@page_aux = params[:page] #Retrieve the params from the query string
@election_id = params[:election_id] #Retrieve the params from the query string
@page = @page_aux =~ /\A\d+\z/ ? @page_aux.to_i : 0 #Validate if the page_aux param can be parsed as an integer, otherwise set it to cero
response = Ticket.all(session[:user],@election_id,@page) #Retrieve all the tickets from the model
if response[0] #Validate if the response was successfull
@tickets_list = response[1] #Get the tickets list from the response
@total_pages = response[3].to_i #Get the total numer of pages from the response
@previous_page = @page > 0 ? @page-1 : -1 #Calculate the previous page number, if we are at the first page, then it will set to minus one
@next_page = @page+1 < @total_pages ? @page+1 : -1 #Calculate the next page number, if we are at the last page, then it will set to minus one
elsif response[1] == '404'
return
elsif validate_authorized_access(response[1]) #If the response was unsucessful, validate if it was caused by unauthorized access to the app or expired session
flash[:danger] = t(:ticket_list_error_flash) #Set the error message to the user
redirect_to error_general_error_path #Redirect the user to the generic error page
else
return #If not force return to trigger the redirect of the check_session function
end
rescue #Error Handilng code
general_error_redirection('Controller: '+params[:controller]+'.'+action_name,$!)
end
=begin
--------------------------------------------------------------------------------------------------------------------------------
Function to redirect the user to the new ticket page
--------------------------------------------------------------------------------------------------------------------------------
=end
def new
@menu='tickets' #Set the menu variable
$title=t(:title_new_ticket) #Set the title variable
if !check_session #Validate if the user session is active
return #If not force return to trigger the redirect of the check_session function
end
@election_id = params[:election_id] #Retrieve the params from the query string
@ticket = Ticket.new #Set a new ticket object to be filled by the user form
@ticket.election_id = @election_id #Set the owner election id to the object before its created
rescue #Error Handilng code
general_error_redirection('Controller: '+params[:controller]+'.'+action_name,$!)
end
=begin
--------------------------------------------------------------------------------------------------------------------------------
Function to redirect the user to the edit ticket page
--------------------------------------------------------------------------------------------------------------------------------
=end
def edit
@menu='tickets' #Set the menu variable
$title=t(:title_edit_ticket) #Set the title variable
if !check_session #Validate if the user session is active
return #If not force return to trigger the redirect of the check_session function
end
@election_id = params[:election_id] #Retrieve the params from the query string
resp = Ticket.find(params[:id],session[:user]) #Retrieve the ticket to update
if resp[0] #Validate if the response was successfull
@ticket = resp[1] #Set the ticket object to fill the edit form
elsif validate_authorized_access(resp[1]) #If the response was unsucessful, validate if it was caused by unauthorized access to the app or expired session
flash[:danger] = t(:ticket_get_error_flash) #Set the error message for the user
redirect_to ticket_path #Redirect the user to edit ticket page
else
return #If not force return to trigger the redirect of the check_session function
end
rescue #Error Handilng code
general_error_redirection('Controller: '+params[:controller]+'.'+action_name,$!)
end
=begin
--------------------------------------------------------------------------------------------------------------------------------
Function to create a new Ticket
--------------------------------------------------------------------------------------------------------------------------------
=end
def create
if !check_session #Validate if the user session is active
return #If not force return to trigger the redirect of the check_session function
end
@ticket = Ticket.new(ticket_params) #Create a new ticket object with the parameters set by the user in the create form
resp = @ticket.save(session[:user]) #Save the new Ticket object
if resp[0] #Validate if the response was successfull
flash[:success] = t(:ticket_creation_success_flash, ticket: @ticket.name) #Set the success message for the user
redirect_to tickets_path(:election_id =>@ticket.election_id) #Redirect the user to the tickets list page
elsif validate_authorized_access(resp[1]) #If the response was unsucessful, validate if it was caused by unauthorized access to the app or expired session
if(resp[1].kind_of?(Array)) #If the response was unsucessful, validate if it was caused by an invalid Ticket object sent to the model. If so the server would have returned an array with the errors
flash[:warning] = Util.format_validation_errors(resp[1]) #Set the invalid object message for the user
end
flash[:danger] = t(:ticket_creation_error_flash) #Set the error message for the user
@ticket = Ticket.new #Reset the Ticket object to an empty one
redirect_to new_ticket_path #Redirect the user to the Ticket creation page
else
return #If not force return to trigger the redirect of the check_session function
end
rescue #Error Handilng code
general_error_redirection('Controller: '+params[:controller]+'.'+action_name,$!)
end
=begin
--------------------------------------------------------------------------------------------------------------------------------
Function to update a Ticket
--------------------------------------------------------------------------------------------------------------------------------
=end
def update
if !check_session #Validate if the user session is active
return #If not force return to trigger the redirect of the check_session function
end
resp = Ticket.find(params[:id],session[:user]) #Retrieve the original ticket object to update
if resp[0] #Validate if the response was successfull
@ticket = resp[1] #Set the ticket object to be updated
elsif validate_authorized_access(resp[1]) #If the response was unsucessful, validate if it was caused by unauthorized access to the app or expired session
flash[:danger] = t(:ticket_get_error_flash) #Set the error message for the user
redirect_to tickets_path #Redirect the user to the tickets list page
else
return #If not force return to trigger the redirect of the check_session function
end
resp2 = @ticket.update_attributes(ticket_params,session[:user]) #Update the ticket object
if resp2[0] #Validate if the response was successfull
flash[:success] = t(:ticket_modification_success_flash, ticket: @ticket.name) #Set the success message for the user
redirect_to tickets_path(:election_id =>@ticket.election_id) #Redirect the user to the tickets list page
elsif validate_authorized_access(resp[1]) #If the response was unsucessful, validate if it was caused by unauthorized access to the app or expired session
if(resp[1].kind_of?(Array)) #If the response was unsucessful, validate if it was caused by an invalid Ticket object sent to the model. If so the server would have returned an array with the errors
flash[:warning] = Util.format_validation_errors(resp[1]) #Set the invalid object message for the user
end
flash[:danger] = t(:ticket_modification_error_flash) #Set the error message for the user
redirect_to edit_ticket_path #Redirect the user to the Tickets edition page
else
return #If not force return to trigger the redirect of the check_session function
end
rescue #Error Handilng code
general_error_redirection('Controller: '+params[:controller]+'.'+action_name,$!)
end
=begin
--------------------------------------------------------------------------------------------------------------------------------
Function to delete a Ticket
--------------------------------------------------------------------------------------------------------------------------------
=end
def destroy
if !check_session #Validate if the user session is active
return #If not force return to trigger the redirect of the check_session function
end
resp = Ticket.find(params[:id],session[:user]) #Retrieve the original ticket object to update
if resp[0] #Validate if the response was successfull
@ticket = resp[1] #Set the ticket object to be deleted
elsif validate_authorized_access(resp[1]) #If the response was unsucessful, validate if it was caused by unauthorized access to the app or expired session
flash[:danger] = t(:ticket_get_error_flash) #Set the error message for the user
redirect_to tickets_path(:election_id =>@ticket.election_id) #Redirect the user to the tickets list page
else
return #If not force return to trigger the redirect of the check_session function
end
resp2 = @ticket.delete(session[:user]) #Delete the ticket object
if resp2[0] #Validate if the response was successfull
flash[:success] = t(:ticket_deletion_success_flash, ticket: @ticket.name) #Set the success message for the user
elsif validate_authorized_access(resp[1]) #If the response was unsucessful, validate if it was caused by unauthorized access to the app or expired session
flash[:danger] = t(:ticket_deletion_error_flash) #Set the error message for the user
else
return #If not force return to trigger the redirect of the check_session function
end
redirect_to tickets_path(:election_id =>@ticket.election_id) #Redirect the user to the tickets list page
rescue #Error Handilng code
general_error_redirection('Controller: '+params[:controller]+'.'+action_name,$!)
end
=begin
--------------------------------------------------------------------------------------------------------------------------------
Ticket Model parameters definition
--------------------------------------------------------------------------------------------------------------------------------
=end
private
def ticket_params
params.require(:ticket).permit(:name, :acronym, :photos, :information, :color, :candidates, :election_id, :number_of_supporters, :picture)
end
end
| true
|
597daf7fc9fe743281f314b6b52de1b952376ce6
|
Ruby
|
zpalmquist/reunion
|
/test/reunion_test.rb
|
UTF-8
| 576
| 2.65625
| 3
|
[] |
no_license
|
require 'minitest'
require 'minitest/test'
require 'minitest/autorun'
require './lib/reunion'
require './lib/activity'
class ReunionTest < Minitest::Test
def test_attributes_of_reunion
reunion = Reunion.new('montana', 'hiking')
assert_equal 'montana', reunion.location
assert_equal ['hiking'], reunion.activities
end
def test_we_can_add_activity
reunion = Reunion.new('montana', 'hiking')
activity_1 = Activity.new('huckleberry_hunt')
reunion.add_activities(activity_1)
assert_equal ['hiking', activity_1], reunion.activities
end
end
| true
|
85c2af8c2bb3d367bc668d601c86183b050d9e2a
|
Ruby
|
cglorious/prework-videos-intro-to-tests-online-web-sp-000
|
/conversions.rb
|
UTF-8
| 109
| 2.546875
| 3
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
GRAMS_PER_OUNCE = 28.3495 #constant variable
def ounces_to_grams(ounces)
ounces.to_f * GRAMS_PER_OUNCE
end
| true
|
4285af6f489cb7a570b3df49b5572d0d3622f359
|
Ruby
|
vvj5/wk2day1
|
/profile-info.rb
|
UTF-8
| 1,129
| 3.9375
| 4
|
[] |
no_license
|
puts "Would you like to play a game?"
enter = gets.chomp
if enter.include? "no"
puts "Please? I'm so lonely. Type 'k' to play a game with me."
else
puts "Oh good! Type 'k' to continue."
end
passcode = gets.chomp
if passcode.include? "k"
puts "Let's talk about you. "
else
puts "Try typing k again."
end
puts "What is your name?"
name = gets.chomp
puts "How old are you?"
age = gets.chomp
puts "What is your username?"
un = gets.chomp
puts "What city do you live in?"
city = gets.chomp
puts "What country do you live in?"
country = gets.chomp
puts "What is one of your 5 favorite foods?"
food1 = gets.chomp
puts "What is your second of 5 favorite foods?"
food2 = gets.chomp
puts "What is your third of 5 favorite foods?"
food3 = gets.chomp
puts "What is your fourth of 5 favorite foods?"
food4 = gets.chomp
puts "What is your fifth of 5 favorite foods?"
food5 = gets.chomp
print
"Your name is #{name}, you are #{age} years old, your username is #{un} and you live in #{city}, #{country}.
Your five favorite foods are: #{food1}, #{food2}, #{food3}, #{food4} and #{food5}.
Let's always be best friends.
Best friends... FOREVER."
| true
|
ed86856e55e35e58c28d646637ffc0429be6a5db
|
Ruby
|
smoreau-tj/bowling_rspec
|
/spec/frame_spec.rb
|
UTF-8
| 913
| 2.71875
| 3
|
[] |
no_license
|
require 'frame'
describe Frame do
describe "#frame_over?" do
context "when I bowl twice" do
before do
2.times { subject.bowl(0) }
end
it "is true" do
expect(subject.frame_over?).to eq(true)
end
end
context "when I bowl once" do
before do
subject.bowl(0)
end
it "is false" do
expect(subject.frame_over?).to eq(false)
end
end
context "when I bowl zero times" do
it "is false" do
expect(subject.frame_over?).to eq(false)
end
end
context "when I bowl a strike" do
before do
subject.bowl(10)
end
it "is true" do
expect(subject.frame_over?).to eq(true)
end
end
end
end
| true
|
29c23e0535f841f3699d4aa0b096aee8a4733ae1
|
Ruby
|
ralphreid/WDI_LDN_3_Work
|
/ralphreid/w1d4/homework/happitails_animal_shelter/data.rb
|
UTF-8
| 299
| 2.53125
| 3
|
[] |
no_license
|
require_relative 'shelter'
require_relative 'client'
require_relative 'animal'
$shelter = Shelter.new( "Happitails", "Main Street")
# add all the initial data
###example below 2 is the number of childern.......this helps show the §
# $shelter.clients['bob'] = Client.new('Bob', 22, 'male', 2)
| true
|
da8f335b1037d35c9c77fcc3a62f3160cc06a2f7
|
Ruby
|
upamune/itamae-osx
|
/common/formula.rb
|
UTF-8
| 174
| 2.921875
| 3
|
[] |
no_license
|
class Formula
attr_reader :package, :tap
def initialize(package, tap=nil)
@package = package
@tap = tap
end
def hasTap()
return !self.tap.nil?
end
end
| true
|
33e72f9b14db6baa7f6ab3bcb1466c5cb588744e
|
Ruby
|
freerange/mocha.methods
|
/Mocha/ParameterMatchers/Not/#matches?.rb
|
UTF-8
| 114
| 2.515625
| 3
|
[] |
no_license
|
def matches?(available_parameters)
parameter = available_parameters.shift
!@matcher.matches?([parameter])
end
| true
|
fd03110db21c45822c17b833d46bddfe2d4f350b
|
Ruby
|
phamv21/stp_minesweeper
|
/game.rb
|
UTF-8
| 6,173
| 3.25
| 3
|
[] |
no_license
|
require_relative 'board'
require_relative 'keypress'
require 'yaml'
class Game
attr_reader :board, :saved_board, :size
def initialize(size = get_val("please put yours desire size"))
@size = size
@board = Board.new(size)
@saved_board = ""
@time_start = 0
@time_stop = 0
@level = 0
end
def set_up_board
while true
val = get_val("please enter number of mines (a positive number less than #{size*size})")
break if val < (size*size)
end
@level = val
board.setup_mines(val)
board.scan_fringles
@time_start = Time.now
end
def cursor_play_turn
pos = [0,0]
board.cursor_highlight(pos)
board.render
x = 0
y = 0
until board.game_over?
puts "you can use the Arrow key to move the cursor \n and f for flag, r for reveal s for save the current game"
move = Keypress.pos_control
case move
when "UP"
x = parse_axis(x-1)
board.cursor_highlight([x,y])
board.render
when "DOWN"
x = parse_axis(x+1)
board.cursor_highlight([x,y])
board.render
when "RIGHT"
y = parse_axis(y+1)
board.cursor_highlight([x,y])
board.render
when "LEFT"
y = parse_axis(y-1)
board.cursor_highlight([x,y])
board.render
when "F"
board.flag([x,y])
board.render
when "R"
board.reveal([x,y])
board.render
when "RETURN"
board.reveal([x,y])
board.render
when "S"
@saved_board = board.to_yaml
board.render
else
puts "you put the wrong key"
end
end
system ('clear')
end
#for input from the commmand - currently not use
def play_turn
board.render
pos = get_pos
decision = get_decision
if decision == "r"
board.reveal(pos)
elsif decision == "f"
board.flag(pos)
else
@saved_board = board.to_yaml
end
end
def run
if saved_board == ""
set_up_board
end
#until board.game_over?
#play_turn
cursor_play_turn
#end
if board.finish
puts "You have step on mine, try again"
try_from_saved_point?
else
board.render
puts "Unbelievable! You are genius"
@time_stop = Time.now
data = "size:#{@size}-level:#{@level},time:#{@time_stop-@time_start}"
write_record("size:#{@size}-level:#{@level},#{@time_stop-@time_start}")
puts "Here is your record:"
print data
puts ""
puts "--------------"
puts "Here is the leaderboard of your current level:"
read_record("size:#{@size}-level:#{@level}")
end
end
def write_record(data)
File.write('record.txt',"#{data}\n" , mode:"a")
end
def read_record(curent_level)
leaderboard = Hash.new{|h,k| h[k] =[]}
levels_times = File.readlines("record.txt").map(&:chomp)
levels_times.each do |item|
data = item.split(",")
level,time = data
leaderboard[level] << time.to_f
end
print leaderboard[curent_level].sort[0..9]
puts
end
def load_saved_game
@board = YAML::unsafe_load(saved_board)
end
def try_from_saved_point?
respond = ""
if @saved_board != ""
while true
puts "do you want to load the saved game? yes or no"
print "> "
respond = gets.chomp
case respond
when "yes"
load_saved_game
system("clear")
run
break
when "no"
board.render
puts "too hard, I know"
break
else
puts "only yes or no please"
end
end
end
end
def get_decision
decision = ""
while true
puts "put f for flag, r for reveal s for save the current game."
print "> :"
decision = gets.chomp
case decision
when "f"
break
when "r"
break
when "s"
break
else
puts "you can only put: f or r or s"
end
end
decision
end
def get_pos
pos = nil
until pos && valid_pos?(pos)
begin
puts "Please enter a position on the board (e.g., '3,4')"
print "> "
pos = parse_pos(gets.chomp)
rescue
puts "you have entered wrong format of postition. Did you seperate them by , ?"
puts ""
pos = nil
end
end
pos
end
def get_val(promt)
val = nil
until val && valid_val?(val)
puts promt
print "> :"
val = parse_val(gets.chomp)
end
val
end
def parse_pos(string)
string.split(",").map{|char| Integer(char)}
end
def parse_val(string)
Integer(string)
end
def valid_pos?(pos)
pos.is_a?(Array)&& pos.length == 2 &&
pos.all?{|x| x.between?(0,size-1)}
end
def parse_axis(num)
return num if num.between?(0,size - 1)
return (size - 1) if num < 0
return 0 if num > (size - 1)
end
def valid_val?(val)
val.is_a?(Integer)
end
end
game = Game.new
game.run
| true
|
4064519484777dcd6c6ee4d5ab6986180044cfb1
|
Ruby
|
diegous/econocrawler
|
/renderer.rb
|
UTF-8
| 871
| 2.6875
| 3
|
[] |
no_license
|
require 'erb'
require 'json'
require 'byebug'
english = true
LANGUAGE = english ? 'english' : 'spanish'
BASE_URL = "http://economica.econo.unlp.edu.ar#{'/ing' if english}"
# Retrieve JSON
JSON_FILE = File.read("./result#{'_english' if english}.json")
publications = JSON.parse(JSON_FILE)
# Templates
PUBLICATION_TEMPLATE = File.read("./templates/#{LANGUAGE}/publication.md.erb")
ARTICLE_TEMPLATE = File.read("./templates/#{LANGUAGE}/article.html.erb")
# Create a file for each publication
publications.each do |publication|
@publication = publication
publication_text = ERB.new(PUBLICATION_TEMPLATE).result()
file_indentifier = "#{publication["volume"]}_#{publication["number"]}"
filename = "publication_#{file_indentifier.to_s.tr(' ', '_')}.md"
File.open("./result_files/#{LANGUAGE}/#{filename}", "w") do |file|
file.write(publication_text)
end
end
| true
|
99064be43a3904ef5d76080c569b02972d04e1c8
|
Ruby
|
kurage0516/furima-30952
|
/spec/models/user_spec.rb
|
UTF-8
| 4,781
| 2.546875
| 3
|
[] |
no_license
|
require 'rails_helper'
RSpec.describe User, type: :model do
before do
@user = FactoryBot.build(:user)
end
describe 'ユーザー新規登録' do
it 'nickname、email、password、password_confirmation、name、surname、name_ruby、surname_ruby、birthdayが存在すれば登録できる' do
expect(@user).to be_valid
end
it 'nicknameが空では登録できないこと' do
@user.nickname = nil
@user.valid?
expect(@user.errors.full_messages).to include("Nickname can't be blank")
end
it 'emailが空では登録できないこと' do
@user.email = nil
@user.valid?
expect(@user.errors.full_messages).to include("Email can't be blank")
end
it 'passwordが空では登録できないこと' do
@user.password = nil
@user.valid?
expect(@user.errors.full_messages).to include("Password can't be blank")
end
it 'nameが空では登録できないこと' do
@user.name = nil
@user.valid?
expect(@user.errors.full_messages).to include("Name can't be blank")
end
it 'surnameが空では登録できないこと' do
@user.surname = nil
@user.valid?
expect(@user.errors.full_messages).to include("Surname can't be blank")
end
it 'name_rubyが空では登録できないこと' do
@user.name_ruby = nil
@user.valid?
expect(@user.errors.full_messages).to include("Name ruby can't be blank")
end
it 'surname_rubyが空では登録できないこと' do
@user.surname_ruby = nil
@user.valid?
expect(@user.errors.full_messages).to include("Surname ruby can't be blank")
end
it 'birthdayが空では登録できないこと' do
@user.birthday = nil
@user.valid?
expect(@user.errors.full_messages).to include("Birthday can't be blank")
end
it '重複したemailが存在する場合登録できないこと' do
@user.save
another_user = FactoryBot.build(:user, email: @user.email)
another_user.valid?
expect(another_user.errors.full_messages).to include('Email has already been taken')
end
it 'emailは@を含む必要があること' do
@user.email = 'testtest.com'
@user.valid?
expect(@user.errors.full_messages).to include('Email is invalid')
end
it 'passwordが6文字以上であれば登録できること' do
@user.password = 'a2s3d4'
@user.password_confirmation = 'a2s3d4'
expect(@user).to be_valid
end
it 'passwordが5文字以下であれば登録できないこと' do
@user.password = '12345'
@user.password_confirmation = '12345'
@user.valid?
expect(@user.errors.full_messages).to include('Password is too short (minimum is 6 characters)')
end
it 'passwordとpassword_confirmationが不一致では登録できないこと' do
@user.password = '123456'
@user.password_confirmation = '1234567'
@user.valid?
expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password")
end
it 'passwordは英語のみでは登録できない' do
@user.password = 'testte'
@user.password_confirmation = 'testte'
@user.valid?
expect(@user.errors.full_messages).to include('Password is invalid')
end
it 'psswordは数字のみでは登録できない' do
@user.password = '123456'
@user.password_confirmation = '123456'
@user.valid?
expect(@user.errors.full_messages).to include('Password is invalid')
end
it 'passwordは全角では登録できない' do
@user.password = 'asdfgh'
@user.password_confirmation = 'asdfgh'
@user.valid?
expect(@user.errors.full_messages).to include('Password is invalid')
end
it 'nameは全角の漢字・平仮名・カタカナ以外では登録できないこと' do
@user.name = 'Test11'
@user.valid?
expect(@user.errors.full_messages).to include('Name is invalid')
end
it 'surnameは全角の漢字・平仮名・カタカナ以外では登録できないこと' do
@user.surname = 'Test11'
@user.valid?
expect(@user.errors.full_messages).to include('Surname is invalid')
end
it 'name_rubyは全角カタカナ以外では登録できないこと' do
@user.name_ruby = 'Test11'
@user.valid?
expect(@user.errors.full_messages).to include('Name ruby is invalid')
end
it 'surname_rubyは全角カタカナ以外では登録できないこと' do
@user.surname_ruby = 'Test11'
@user.valid?
expect(@user.errors.full_messages).to include('Surname ruby is invalid')
end
end
end
| true
|
5aa5d6e6758edca11b04fa74dbace188ceb9a3c4
|
Ruby
|
petrgazarov/Chess
|
/lib/sliding_piece.rb
|
UTF-8
| 520
| 3.1875
| 3
|
[] |
no_license
|
class SlidingPiece < Piece
def moves
result = []
deltas.each do |delta|
result += make_branch(delta)
end
result
end
private
def make_branch(delta)
result = []
1.upto(Board::SIZE - 1) do |idx|
pos = [(delta[0] * idx + position[0]), (delta[1] * idx + position[1])]
return result if !Board.on_board?(pos)
if occupied?(pos)
result << pos if !board[pos].same_color?(color)
return result
end
result << pos
end
result
end
end
| true
|
58de46d7374507d2c07cfdc81be7248ff04039d6
|
Ruby
|
flaco/Signed-Request-Parser
|
/parse_signed_request.rb
|
UTF-8
| 940
| 2.734375
| 3
|
[] |
no_license
|
# Parses Facebooks Signed Request Parameter and returns JSON
# Some borrowing from http://github.com/appoxy/mini_fb/blob/master/lib/mini_fb.rb && http://sunilarora.org/parsing-signedrequest-parameter-in-python-bas
require "openssl"
require "base64"
require "cgi"
require "yajl"
def base64_url_decode(st)
st = st + "=" * (4 - st.size % 4) unless st.size % 4 == 0
return Base64.decode64(st.tr("-_", "+/"))
end
def verify_signed_request(secret, sign, payload)
sig = base64_url_decode(sign)
expected_sig = OpenSSL::HMAC.digest('SHA256', secret, payload.tr("-_", "+/"))
return sig == expected_sig
end
def parse_signed_request
secret = "SECRET"
signed_request = "SIGNED_REQUEST_STRING"
sign, payload = signed_request.split(".")
data = Yajl::Parser.parse(base64_url_decode(payload))
if verify_signed_request(secret, sign, payload)
return "verified"
else
return "not verified"
end
end
parse_signed_request
| true
|
047483c510bcf5034cc06f9431c838e53cc420fe
|
Ruby
|
sassani134/crypto_J_S6
|
/app/service/scrapp_money.rb
|
UTF-8
| 1,360
| 3.171875
| 3
|
[] |
no_license
|
require 'nokogiri'
require 'open-uri'
class Scrapp_money
# frozen_string_literal: true
attr_accessor :hash, :name
def initialize(name_money="" ,url = "https://coinmarketcap.com/all/views/all/")
@url = url
@page = Nokogiri::HTML(open(@url))
@hash = {}
@name = []
@money_name= name_money
# on récupère le texte contenu dans la classe currency-name-container link-secondary
end
# Récupère un tableau contenant le nom des monnaies
def get_name_money
@name=@page.xpath('//a[@class="currency-name-container link-secondary"]').map { |link| link.text }
end
# Récupère un tableau contenant le prix des monnaies
def get_price_money
array = @page.css('.price').map { |link| link.text }
end
#cree un hash avec les tableaux name et price
def create_hash_name_price (name,price)
array_of_money = name.zip(price).map{|name, price| {name: name, price: price}}
array_of_money.select {|hash| hash[:name] == @money_name}[0]
end
# perform les fonctions
def perform
create_hash_name_price(get_name_money,get_price_money)
end
def save
@hash = perform
if @hash
money = Money.find_by name: @hash[:name]
if money
money.update_attributes(price: @hash[:price])
else
money = Money.create!(hash)
end
else
return false
end
end
end
| true
|
1c0dcd7442a0860384e06fecd10bcf705aa7319a
|
Ruby
|
ChristopherDurand/Exercises
|
/ruby/small-problems/advanced/e1.rb
|
UTF-8
| 967
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
TAG = /<(.+?)>/
WHOLE_TAG = /\<.+?\>/
WORDS = {"adjective" => %w(quick lazy sleepy ugly),
"noun" => %w(fox dog head leg cat tail),
"verb" => %w(spins bites licks hurdles),
"adverb" => %w(easily lazily noisly excitedly)}
def get_needed(text)
text.scan(TAG)
end
def prompt_user(needed)
indices = 0.upto(needed.size-1).to_a.shuffle
given = []
indices.each do |idx|
part = needed[idx]
vowel = part[0] =~ /[aeiou]/i ? true : false
print "Please give me a"
print "n" if vowel
spaces = " " * (10 - part.length - (vowel ? 1 : 0))
print " #{part}:#{spaces}==> "
given[idx] = gets.chomp
end
given
end
def random_fill(needed)
needed.map { |need| WORDS[need].sample }
end
def replace_blanks!(text, given)
text.gsub!(WHOLE_TAG) { given.shift }
end
text = open("madlib.txt").read
needed = get_needed(text).flatten #.shuffle
given = random_fill(needed)
replace_blanks!(text, given)
puts text
| true
|
007dc15328b6ff2e18935c85da26d0ea24710c06
|
Ruby
|
toptal/codeowners-checker
|
/spec/codeowners/reporter_spec.rb
|
UTF-8
| 2,077
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require 'codeowners/checker'
RSpec.describe Codeowners::Reporter do
describe '::print_delimiter_line' do
it 'raises the exception if unknow error type' do
expect do
described_class.print_delimiter_line(:foobar)
end.to raise_exception(ArgumentError, "unknown error type 'foobar'")
end
it 'puts missing_ref label' do
expect do
described_class.print_delimiter_line(:missing_ref)
end.to output(<<~OUTPUT).to_stdout
------------------------------
No owner defined
------------------------------
OUTPUT
end
it 'puts useless_pattern label' do
expect do
described_class.print_delimiter_line(:useless_pattern)
end.to output(<<~OUTPUT).to_stdout
------------------------------
Useless patterns
------------------------------
OUTPUT
end
it 'puts invalid_owner label' do
expect do
described_class.print_delimiter_line(:invalid_owner)
end.to output(<<~OUTPUT).to_stdout
------------------------------
Invalid owner
------------------------------
OUTPUT
end
it 'puts unrecognized_line label' do
expect do
described_class.print_delimiter_line(:unrecognized_line)
end.to output(<<~OUTPUT).to_stdout
------------------------------
Unrecognized line
------------------------------
OUTPUT
end
end
describe '::print_error' do
it 'puts common error' do
expect do
described_class.print_error(:unrecognized_line, 'foobar', ['baz'])
end.to output("foobar\n").to_stdout
end
it 'puts invalid_owner with missing' do
expect do
described_class.print_error(:invalid_owner, 'foobar', %w[baz gaz])
end.to output("foobar MISSING: baz, gaz\n").to_stdout
end
end
describe '::print' do
it 'forwards args to puts' do
expect do
described_class.print('foobar', 'baz')
end.to output("foobar\nbaz\n").to_stdout
end
end
end
| true
|
4e0a7e408a829ab639667a6b4a156145d6c62a8d
|
Ruby
|
sagarlekar/road_roller
|
/lib/road_roller.rb
|
UTF-8
| 4,732
| 3.546875
| 4
|
[] |
no_license
|
# Author - Sagar Arlekar
# Email - sagar.arlekar@gmail.com
require 'rgeo'
require 'rgeo/shapefile'
require 'road_roller_helper'
# * This class has methods to divide roads(RGeo::Feature::LineString) into points (RGeo::Feature::Point)
class RoadRoller
attr_accessor :shapefile, :filename, :id_field, :road_points
#
# * +filename+ - The path to the shape file. E.g. /home/user/bangalore_roads.shp. The name is stored in @filename
# * +id_field+ - The field name for the unique identifie for each record. Usually id or gid field. The name is stored in @id_field
#
def initialize(filename, id_field)
# absolute path to the shapefile e.g. /home/user/roads.shp
@filename = filename
@id_field = id_field
open_shapefile()
end
# Will open the shapefile identified by the name in @filename. The returned shapefile(RGeo::Shapefile) is stored in @shapefile.
def open_shapefile
@shapefile = RGeo::Shapefile::Reader.open(@filename)
end
# Will fetch each road (RGeo::Feature::LineString) in the shapefile and divide it into consecutive points(Point) at a distance - distance. This function inturn calls divide_linestring_into_points()
# to divide each road into points.
# * +distance+ - Distance in meters.
def divide_roads_into_points(distance)
@road_points = Hash.new()
@shapefile.each do |linestrings|
if linestrings.attributes.keys().include?(@id_field) == false
raise "Attribute #{@id_field} is not present in the file. Kindly pass the name of the unique field in RoadRoller.new(filename, id_field)."
end
linestrings.geometry.each do |linestring|
linestring_points = divide_linestring_into_points(linestring, distance)
@road_points[linestrings.attributes[@id_field]] = linestring_points
end
end
puts "road_points length = #{@road_points.length}"
return @road_points
end
# Will divide road (RGeo::Feature::LineString) into consecutive points(RGeo::Feature::Point) at a distance - distance. This function inturn calls divide_linestring_into_points()
# to divide each road into points. This method inturn calls divide_line_into_points()
# * +road+ - the Linestring representing the road. A road is a RGeo::Shapefile::Reader::Record object.
# * +distance+ - Distance in meters.
def divide_linestring_into_points(road, distance)
points = road.points
i = 0
linestring_points = []
while( i < points.length - 1)
start_point = points[i]
end_point = points[i+1]
distance_degrees = RoadRollerHelper.meters_to_degrees(distance, start_point.y)
#puts "%%%% #{RoadRollerHelper.get_line_length(start_point.y, start_point.x, end_point.y, end_point.x)} + #{distance_degrees}"
linestring_points = linestring_points + divide_line_into_points(start_point.y, start_point.x, end_point.y, end_point.x, distance_degrees)
i=i+1
end
puts "linestring_points = #{linestring_points.length}"
return linestring_points
end
# Will divide a line represented by (lat1, lon1) (lat2, lon2)
# * +distance+ - Distance in degree decimal. E.g. 73.143672.
def divide_line_into_points(lat1, lon1, lat2, lon2, distance)
# puts "in line #{lat1}, #{lon1}, #{lat2}, #{lon2}, #{distance}"
points = []
num_points = (RoadRollerHelper.get_line_length(lat1, lon1, lat2, lon2)/distance).to_i
i = 1
#puts "#{RoadRollerHelper.get_line_length(lat1, lon1, lat2, lon2)} #{distance}"
while (i <= num_points)
#puts "#{i} #{num_points}"
lat, lon = get_new_point(lat1, lon1, lat2, lon2, distance*i)
#puts "lat, lon => #{lat} #{lon}"
points.push([lat, lon])
i=i+1
end
puts "num_points = #{num_points} #{points.length}"
return points
end
# Given a line (lat1, lon1) (lat2, lon2) it will return a Point (lat, lon) at an distace 'distance'.
# * +distance+ - Distance in degree decimal. E.g. 73.143672.
def get_new_point(lat1, lon1, lat2, lon2, distance)
length = RoadRollerHelper.get_line_length(lat1, lon1, lat2, lon2)
fraction_length = distance/length
lat_new = lat1 + fraction_length * (lat2-lat1)
lon_new = lon1 + fraction_length * (lon2-lon1)
return lat_new, lon_new
end
# Writes points in @road_points to a file as CSVs. If the input file was named /home/user/test_data.shp the csv file will be named /home/user/test_data.csv
def export_as_csv()
dir = File.dirname(@filename)
filename = File.basename(@filename, ".shp")
filename = dir + "/" + filename + ".csv"
puts "filename " + filename
CSV.open(filename, "wb") do |csv|
@road_points.each do |id, points|
points.each do |point|
csv << [id, point[0], point[1]]
end
end
end
end
end
| true
|
80309ccaca89dc000ac2fe3a67cc6c82e63275c6
|
Ruby
|
BC-MAY-21-ROR/kata-02-el-juego-de-la-vida-dia-04-team05-dia-3
|
/spec/location_spec.rb
|
UTF-8
| 2,044
| 2.75
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require 'rspec'
require './lib/location'
describe Location do
before :all do
@north_west = Location::NORTHWEST
@north_east = Location::NORTHEAST
@south_west = Location::SOUTHWEST
@south_east = Location::SOUTHEAST
@center = Location::CENTER
@north = Location::NORTH
@south = Location::SOUTH
@east = Location::EAST
@west = Location::WEST
end
it 'NorthWest is located at (-1, 1)' do
location = Location::NORTHWEST
expect(location).to eq(@north_west)
end
it 'NorthEast is located at (1, 1)' do
location = Location::NORTHEAST
expect(location).to eq(@north_east)
end
it 'SouthWest is located at (-1, -1)' do
location = Location::SOUTHWEST
expect(location).to eq(@south_west)
end
it 'SouthEast is located at (1, -1)' do
location = Location::SOUTHEAST
expect(location).to eq(@south_east)
end
it 'Center is located at (0, 0)' do
location = Location::CENTER
expect(location).to eq(@center)
end
it 'North is located at (0, 1)' do
location = Location::NORTH
expect(location).to eq(@north)
end
it 'South is located at (0, -1)' do
location = Location::SOUTH
expect(location).to eq(@south)
end
it 'East is located at (1, 0)' do
location = Location::EAST
expect(location).to eq(@east)
end
it 'West is located at (-1, 0)' do
location = Location::WEST
expect(location).to eq(@west)
end
it 'location for 0, 1 is north' do
location = Location::NORTH
expect(location).to eq(@north)
end
it 'adding two locations returns a new location' do
result = Location.add(Location::SOUTH, Location::CENTER)
expect(result).to eq(Location::SOUTH)
end
it 'returns a list of offsets for any cell' do
offsets = Location::OFFSETS
expected = [Location::NORTHWEST, Location::NORTHEAST,
Location::SOUTHWEST, Location::SOUTHEAST, Location::NORTH,
Location::SOUTH, Location::EAST, Location::WEST]
expect(expected).to eq(offsets)
end
end
| true
|
131cb7e2ee16d3a06215881da0c1cc74a7371f96
|
Ruby
|
Elbakay/Exo_Ruby
|
/exo_09.rb
|
UTF-8
| 213
| 3.625
| 4
|
[] |
no_license
|
puts "Bonjour, quel est votre prénom ?"
print ">"
user_first_name = gets.chomp
puts "Quel est votre nom ?"
print ">"
user_last_name=gets.chomp
puts"Bonjour, "+user_first_name.capitalize+" "+user_last_name.upcase
| true
|
f9f21380380e32d813caa95b098b4dac9aebc630
|
Ruby
|
clothnetwork/cloth-ruby
|
/lib/cloth/client.rb
|
UTF-8
| 1,283
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
require 'json'
require 'typhoeus'
module Cloth
class Client
attr_reader :api_key
def initialize(api_key = nil)
@api_key = api_key || Cloth.api_key
raise Exception, "An API key must be set before the Cloth client can be used. Set an API key with 'Cloth.api_key = ...'" unless @api_key
end
def get(url, options = {})
JSON.parse(request(:get, url, options).run.body)
end
def post(url, options = {})
headers = { 'Content-Type': "application/x-www-form-urlencoded" }
JSON.parse(request(:post, url, options.merge({ headers: headers })).run.body)
end
def request(method, url, options = {})
fixed_url = url[0] == "/" ? url[1..-1] : url
url = [Cloth.api_url, fixed_url].join('/')
Typhoeus::Request.new(
url,
method: method,
body: options[:body],
params: options[:params],
headers: {
'Accept': 'application/json',
'Cloth-Api-Key': @api_key,
'Content-Type': 'application/json'
}.merge(options[:headers] || {})
)
end
class << self
def get(url, options = {})
Cloth.client.get(url, options)
end
def post(url, options = {})
Cloth.client.post(url, options)
end
end
end
end
| true
|
e4e6dbc9eaa26a0ff61a04e5dacefd8e96982f54
|
Ruby
|
naoki-k/Ruby-Cherry-Book
|
/chapter2/2.2.1.rb
|
UTF-8
| 498
| 4.1875
| 4
|
[] |
no_license
|
# to_sメソッド
# 数値や真偽値、正規表現もオブジェクトで、それぞれにメソッドを持つ
# 文字列に変換するメソッド
# 文字列
'1'.to_s
puts('1'.to_s)
# 数値
1.to_s
puts(1.to_s)
# nil
nil.to_s
puts(nil.to_s)
puts('_' + nil.to_s + '_')
# true
true.to_s
puts(true.to_s)
# false
false.to_s
puts(false.to_s)
# 正規表現
/\d+/.to_s
puts(/\d+/.to_s)
# to_sメソッドの引数
# 数値を16真数の文字列に変換する
10.to_s 16
puts(10.to_s(16))
| true
|
ec9a272a10f0adbf1966c8502aa699aad0a7ed37
|
Ruby
|
Cooky90/LaunchSchool
|
/ProgrammingFoundations-101/Small-Exercises/Easy-3/Exercise10.rb
|
UTF-8
| 208
| 3.234375
| 3
|
[] |
no_license
|
def palindromic_number?(number)
number.to_s.reverse == number.to_s
end
palindromic_number?(34543) == true
palindromic_number?(123210) == false
palindromic_number?(22) == true
palindromic_number?(5) == true
| true
|
97b8c5b3772a919291ada8a3adde82da1c89af1f
|
Ruby
|
Domitalk/OO-FlatironMifflin-dumbo-web-102819
|
/lib/Manager.rb
|
UTF-8
| 776
| 3.578125
| 4
|
[] |
no_license
|
class Manager
attr_reader :name, :department, :age
@@all = []
def initialize(name, department, age)
@name = name
@department = department
@age = age
@@all << self
end
def self.all
@@all
end
def employees
Employee.all.select do |instance|
instance.manager == self
end
end
def hire_employee(name, salary)
Employee.new(name, salary, self)
end
def self.all_departments
@@all.map { |instance| instance.department }.uniq
end
def self.average_age
count = 0
sub_total = 0.00
@@all.each do |instance|
sub_total += instance.age
count += 1
end
sub_total / count
end
end
| true
|
4c43d58e290d126082bfee9bfaf432929384d8d0
|
Ruby
|
oreills8/DistributedSystemsProject
|
/DirectoryServer/directoryClient.rb
|
UTF-8
| 1,599
| 2.78125
| 3
|
[] |
no_license
|
require './errors'
require './directory'
class Client
attr_accessor :connection, :ClientProxyJoinID, :ChatroomNumber, :error,
:updatingFile
def initialize(setJoinID, setConnection)
@joinID = setJoinID
@connection = setConnection
@ClientProxyJoinID = 0
@ChatroomNumber = 0
@error = Error.new()
@directory = Directory.new
@updatingFile = false
@fileToBeUpdated
end
def clientDisconnect()
@ClientProxyJoinID = 0
@ChatroomNumber = 0
@connection.close
end
def clientRespondMessage(text,iP,port)
@connection.puts "HELO #{text}\nIP:#{iP}\nPort:#{port}\nStudentID:10327713\n"
end
def releventInfo
if @ClientProxyJoinID == 0 and @ChatroomNumber == 0
return false
else
return true
end
end
def returnDirectory(inputFile)
if releventInfo
file = @directory.returnFile(inputFile)
if file
@connection.puts "CHATROOM: #{@ChatroomNubmer}\nJOIN_ID: #{@ClientProxyJoinID}\nDIRECTORY:#{file}\nSERVER:#{@directory.current_Location}\n"
else
@error.currentError = @error.error_FileNotInDirectory
@error.ErrorMessage(@connection)
end
else
@error.currentError = @error.error_NotAllReleventInfoReceivedByDirectoryServer
@error.ErrorMessage(@connection)
end
end
def updateFile(line)
@updatingFile = true
@fileToBeUpdated = line
end
def updateFileLocation(line)
@directory.updateFileLocationDirectory(@fileToBeUpdated,line)
end
end
| true
|
6e16d7510a1f55d57ef227c8b798b142adae3f8f
|
Ruby
|
peel3r/till_kata
|
/spec/receipt_spec.rb
|
UTF-8
| 1,640
| 3.0625
| 3
|
[] |
no_license
|
describe Receipt do
context 'Calculating line prices' do
let(:order_dbl){double :order}
let(:receipt){Receipt.new(order_dbl)}
it 'Returns a price for each item' do
expect(receipt.price_for('Cafe Latte')).to eq 4.75
end
it 'Returns a line price for an item and quantity' do
two_choc_mousses = {item: 'Choc Mousse', quantity: 2}
expect(receipt.line_price_for(two_choc_mousses)).to eq 16.40
end
end
context 'Calculating the total for an order' do
order = [{item: 'Tea', quantity: 1},{item: 'Cappucino', quantity: 3}]
let(:receipt){Receipt.new(order, 8.64)}
it 'Before taxes or discounts' do
expect(receipt.subtotal).to eq 15.20
end
it 'After taxes' do
expect(receipt.after_tax_total).to eq 16.51
end
end
context 'Calclating a discounted total' do
it '10% off when spending over £50' do
order = [{item: 'Choc Mudcake', quantity: 10}]
receipt = Receipt.new(order)
expect(receipt.subtotal).to eq 64
expect(receipt.discounted_total).to eq 60.80
end
it 'Item discount on muffins' do
order = [{item: 'Blueberry Muffin', quantity: 1}]
receipt = Receipt.new(order)
expect(receipt.subtotal).to eq 4.05
expect(receipt.discounted_total).to eq 3.64
end
end
context 'Generating the receipt' do
it 'Returns an itemized receipt' do
order = [{item: "Cafe Latte", quantity: 1}, {item: "Blueberry Muffin", quantity: 3}]
receipt = Receipt.new(order)
expect(receipt.generate).to eq ['Cafe Latte 1x 4.75', 'Blueberry Muffin 3x 4.05', 'Total 16.90']
end
end
end
| true
|
e8a62146ab701cdf912ec00ff02e2ce5a83f9100
|
Ruby
|
yoshikyoto/twitch-clipper
|
/src/cliper/service.rb
|
UTF-8
| 1,812
| 2.78125
| 3
|
[] |
no_license
|
require 'date'
require 'twitch-api'
require 'twitch-clipr'
module Cliper
class Service
def initialize(config)
@config = config
@twitch = Twitch::Client.new(client_id: config["twitch"]["client_id"])
@clipr = Twitch::Clipr::Client.new()
end
def search_clip_and_download_with_broadcasters(
broadcasters,
clips_count_each,
started_at,
ended_at)
now = Time.now.strftime("%Y%m%d%H%M%S")
puts "start: " + now
# ダウンロード先のディレクトリを作成
download_dir = @config["video"]["download_dir"] + "/" + now
Dir.mkdir(download_dir, 0755)
broadcasters.each { |broadcaster_name|
# ユーザー名からユーザーIDを引く
result = @twitch.get_users({login: broadcaster_name})
user = result.data[0]
puts("name: " + broadcaster_name)
puts("id: " + user.id)
# 直近1週間のclipを視聴数順に取得
result = @twitch.get_clips({
broadcaster_id: user.id,
started_at: started_at.rfc3339,
ended_at: ended_at.rfc3339,
first: clips_count_each,
})
# クリップをダウンロード
result.data.each{ |clip|
download_url = @clipr.get(clip.url)
puts("downloading: " + clip.url)
puts("view: " + clip.view_count.to_s)
# ダウンロードURL resource/今日の日付/配信者名-ClipId.mp4
download_path =
download_dir + "/" +
broadcaster_name + "-" +
clip.view_count.to_s + "views-" +
clip.id + ".mp4"
@clipr.download(download_url, download_path)
# 負荷軽減のため0.1秒sleep
sleep(0.1)
}
}
puts("end")
end
end
end
| true
|
4f530c66b22f701b7c295b52134de7a930f6ec48
|
Ruby
|
jsm125/triangle-classification-online-web-sp-000
|
/lib/triangle.rb
|
UTF-8
| 816
| 3.484375
| 3
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
require_relative '../lib/triangle'
class Triangle
attr_accessor :length_a, :length_b, :length_c
def initialize(length_a, length_b, length_c)
@length_a = length_a
@length_b = length_b
@length_c = length_c
end
def kind
if (@length_a <= 0) || (@length_b <= 0) || (@length_c <= 0)
raise TriangleError
elsif
(@length_a + @length_b <= @length_c) || (@length_a + @length_c <= @length_b) || (@length_b + @length_c <= @length_a)
raise TriangleError
else
if (@length_a == @length_b) && (@length_b == @length_c)
:equilateral
elsif (@length_a != @length_b) && (@length_b != @length_c) && (@length_a != @length_c)
:scalene
else :isosceles
end
end
end
class TriangleError < StandardError
end
end
| true
|
9391921cca696e991705a9212db4edc7137dd675
|
Ruby
|
ArayB/advent_of_code_2017
|
/lib/day_one/problem_one.rb
|
UTF-8
| 440
| 3.234375
| 3
|
[] |
no_license
|
module DayOne
class Problem1
def initialize(input)
@arr = input.split('').map { |x| x.to_i }
@matches = []
end
def run
process(@arr)
@matches.sum
end
def process(arr, last = nil)
head, *tail = arr
if head == last
@matches << head
end
return process(tail, head) unless tail.length.zero?
@matches << @arr.last if @arr.last == @arr.first
end
end
end
| true
|
164cdd7989b1d3566fff4e5710d39ef2424f8c73
|
Ruby
|
loschtreality/Chess_Ruby
|
/board.rb
|
UTF-8
| 2,232
| 3.53125
| 4
|
[] |
no_license
|
require_relative "pieces"
class Board
attr_reader :grid
def initialize(grid = Array.new(8) { Array.new(8) { NullPiece.instance } })
@grid = grid
end
def grid
@grid
end
def [](pos)
x,y = pos
@grid[x][y]
end
def []=(pos, value)
x, y = pos
@grid[x][y] = value
end
def dup
cpy = self.grid.map do |spot|
spot.map do |piece|
if piece.is_a? NullPiece
NullPiece.instance
else
(piece.class).new(piece.color, self, piece.pos)
end
end
end
Board.new(cpy)
end
def move_piece(color,from_pos,to_pos)
end
def move_piece!(color,from_pos,to_pos)
end
def in_check?(color)
king_pos = find_king(color)
op_color = ((color == :black) ? :white : :black)
@grid.each_index do |i|
@grid[i].each_index do |j|
if self[[i, j]].color == op_color
return true if (self[[i, j]].moves).include?(king_pos)
end
end
end
false
end
def checkmate?(color)
return false unless in_check?(color)
@grid.each_index do |i|
@grid[i].each_index do |j|
next if (self[[i,j]].color != color) || (self[[i,j]].is_a? (NullPiece))
return false unless (self[[i,j]].valid_moves.empty?)
end
end
true
end
protected
def find_king(color)
i = 0
while i < @grid.length
j = 0
while j < @grid.length
space = self[[i, j]]
return [i, j] if space.is_a?(King) && space.color == color
j += 1
end
i += 1
end
end
end
bo = Board.new
bo[[6, 2]] = King.new(:white, bo, [6, 2])
bo[[0, 0]] = Queen.new(:black, bo, [0, 0])
bo[[0, 1]] = Queen.new(:black, bo, [0, 1])
bo[[0, 2]] = Queen.new(:black, bo, [0, 2])
# bo[[5, 0]] = Rook.new(:black, bo, [5, 0])
# bo[[5, 2]] = Rook.new(:black, bo, [5, 2])
# bo[[1, 2]] = Rook.new(:black, bo, [1, 2])
# p bo.in_check?(:white)
# co = bo.dup
# co[[6,1]].color = :red
# co[[6,1]] = Pawn.new(:black, co, [6,1])
# p bo[[6,1]].checkmate?(:white)
# p bo[[6, 1]].moves
# p bo[[6, 1]].valid_moves
#p bo.checkmate?(:white)
# p bo[[6,1]].color
# p co[[6,1]].symbol
# p bo[[6, 1]].move_into_check?([6,2])
# p bo.checkmate?(:white)
p bo.checkmate?(:white)
| true
|
dc1d6676fc3abd359a9e942d1892db16a3db75ff
|
Ruby
|
tiltedlistener/NorthwestProgramming2016
|
/assignments/2_Ruby_intro.rb
|
UTF-8
| 401
| 3.625
| 4
|
[] |
no_license
|
###
# Copy each section separately and run through https://repl.it/languages/ruby
#
# When finished, try running the entire program through the REPL
###
########## Output
puts "Hello World!"
########## Assignment
a = 5
b = 6
########## Basic Math
a = 5
b = 6
a + b
########## Math Output
a = 5
b = 6
c = a + b
puts c
########## Math output with precedence
a = 3
b = 5
c = (a + b)/2 - b
puts c
| true
|
555828e3397d64183c805735252924dc64f345df
|
Ruby
|
lao9/complete_me
|
/lib/complete_me.rb
|
UTF-8
| 6,294
| 3.59375
| 4
|
[] |
no_license
|
require 'pry'
class CompleteMe
attr_accessor :dictionary, :count
def initialize
@dictionary = Node.new("")
@count = 0
@selection_hash = {}
end
def insert(word)
@dictionary.insert(word)
@count += 1
end
def populate(entry)
entry.split("\n").each do |word|
@dictionary.insert(word)
@count += 1
end
end
def suggest(entry)
collection = @dictionary.suggest(entry)
output = bubble_sort(collection, entry)
return output
end
def bubble_sort(collection, entry)
sorted = [collection.shift]
counter = 0
until collection[0] == nil
if @selection_hash.empty?
item_of_interest_1 = 0
elsif @selection_hash[entry][collection[0]] == nil
item_of_interest_1 = 0
else
item_of_interest_1 = @selection_hash[entry][collection[0]]
end
if @selection_hash.empty?
item_of_interest_2 = 0
elsif @selection_hash[entry][sorted[counter]] == nil
item_of_interest_2 = 0
else
item_of_interest_2 = @selection_hash[entry][sorted[counter]]
end
if item_of_interest_2 < item_of_interest_1
sorted.insert(counter, collection.shift)
counter = 0
else
counter += 1
end
if counter >= sorted.count
sorted.insert(counter, collection.shift)
counter = 0
end
end
return sorted
end
def select(entry, selection)
if @selection_hash[entry] != nil # if the hash with key (user entry) does exist
if @selection_hash[entry][selection] != nil # if the hash with key of user's selection does exist
@selection_hash[entry][selection] += 1
else # if the hash with key of user's selection does NOT exist
@selection_hash[entry][selection] = 1 # initialize nested hash value with count = 1
end
else # if the hash with key (user entry) does NOT exist
@selection_hash[entry] = {selection => 1} # initialize nested hash with key of selection and value with count = 1
end
end
end
class Node
attr_accessor :value, :children, :word, :parent
def initialize(value)
@value = value
@children = {}
@word = false
end
def insert(word)
# separate the first letter of the word from the rest of the word
first_letter = word[0]
rest_of_word = word[1..-1]
# with every insertion, we need to go through the word letter by letter
# so first we check if our current node's
# children hash has a key of the first letter
unless children[first_letter]
# if it does not, we create a new node and
# enter it as a value in our children has
# with the first letter as the key
children[first_letter] = Node.new(first_letter)
end
# now we check how much more of the word we have left
if rest_of_word.length.zero?
# if we don't have any word left,
# we set our current node's
# boolean for word completion to true
children[first_letter].word = true
else
# otherwise, we recurse through the insert function with the rest of the word
children[first_letter].insert(rest_of_word)
end
end
def suggest(entry)
# find starting node
node = self.find_starting_node(entry)
# initialize suggetion
suggestion = entry
sugg_arr = [] # "sugar" = suggestion array ;)
start_node = node
# test that the entry isn't also a word
sugg_arr = node.test_if_node_is_word(sugg_arr, suggestion)
# next evaluate how many children we have so we can iterate through them
sugg_arr = node.children_iterator(node, suggestion, sugg_arr)
# return our suggested array
return sugg_arr
end
def children_iterator(start_node, entry, sugg_arr)
key_arr = start_node.children.keys # create an array of all children
key_arr.each do |key|
# we re-initialize the suggestion and start_node
suggestion = entry
node = start_node
# then we run each child into the suggester builder
sugg_arr = node.suggester_builder(key, suggestion, node, sugg_arr)
end
# return our suggested array
return sugg_arr
end
def suggester_builder(key, suggestion, node, sugg_arr)
# while our children (key) exist
while key!=nil
# generate a new suggestion by adding the new key to that suggestion
suggestion = node.suggester_rolodex(suggestion, key)
# ensure that our key is not reset to nil
if node.node_rolodex(key).nil?
node = node
else
# otherwise move into our new suggestion's node
node = node.node_rolodex(key)
end
# check to see current suggestion is a word and shovel into sugar
sugg_arr = node.test_if_node_is_word(sugg_arr, suggestion)
# determine which child is next
if node.children.keys.length < 2
# if there's only one child (or none), we set that child to our current node
key = node.children.keys[0]
# if key = nil, the sugggester stops because the current node has ended
else
# if there is more than one child, we must go back to our children_iterator to pick which one
node.children_iterator(node, suggestion, sugg_arr)
key = nil
# once that is complete, we terminate the suggester for this branch
end
end
return sugg_arr
# return our suggested array
end
def test_if_node_is_word(sugg_arr, entry)
if word # if the current word is valid
sugg_arr << entry # shovel!
end
return sugg_arr
end
def find_starting_node(entry)
# rifle through our dictionary so we can start where the user wants us to
counter = 0
letter = entry[counter]
node = self
while letter != nil
# check to make sure node is not nil
if node.node_rolodex(letter).nil?
node = node
else
# set node to the next child of our user input
node = node.node_rolodex(letter)
end
counter += 1
letter = entry[counter]
end
return node
end
def node_rolodex(letter)
# changes our starting node to the node with that the input letter
starting_node = children[letter]
end
def suggester_rolodex(entry, letter)
# otherwise, we add the inputted letter key to our suggestion
suggestion = entry + letter
end
end
| true
|
695fd7f5345ecca6b8fe92a857160a9454861091
|
Ruby
|
am-team/luna_park
|
/lib/luna_park/http/request.rb
|
UTF-8
| 7,592
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require 'luna_park/http/send'
module LunaPark
module Http
class Request
# Business description for this request, help you
# make the domain model more expressive
#
# @example Get users request
# request = Request.new(
# title: 'Get users list',
# method: :get,
# url: 'https://example.com/users'
# )
#
# request.title # => 'Get users list'
attr_accessor :title
# Http method of current request, defines a set of
# request methods to indicate the desired action to
# be performed for a given resource
#
# @example Get users request
# request.method # => :get
#
# @example With argument (delegates `Object.method(name)` to save access to the original Ruby method)
# request.method(:foo) # => #<Method: LunaPark::Http::Request#foo>
def method(name = nil)
name.nil? ? @method : super(name)
end
attr_writer :method
# Http url to send request
#
# @example Get users request
# request.url # => 'http://example.com/users'
attr_accessor :url
# Body of http request (defaults is `nil`)
#
# @example Get users request
#
# request = Request.new(
# title: 'Get users list',
# method: :get,
# url: 'http://example.com/users',
# body: JSON.generate({message: 'Hello!'})
# )
# request.body # => "{\"message\":\"Hello!\"}"'
attr_accessor :body
# Http request headers (defaults is `{}`)
#
# @example Get users request
# json_request.headers # => {}
attr_accessor :headers
# Http read timeout, is the timeout for reading
# the answer. This is useful to make sure you will not
# get stuck half way in the reading process, or get
# stuck reading a 5 MB file when you're expecting 5 KB of JSON
# (default is 10)
#
# @example Get users request
# json_request.read_timout # => 10
attr_accessor :read_timeout
# Http open timeout, is the timeout for opening
# the connection. This is useful if you are calling
# servers with slow or shaky response times. (defaults is 10)
#
# @example Get users request
# json_request.open_timeout # => 10
attr_accessor :open_timeout
# Time when request is sent
#
# @example before request is sent
# request.sent_at # => nil
#
# @example after request has been sent
# request.sent_at # => 2020-05-04 16:56:20 +0300
attr_reader :sent_at
# Create new request
#
# @param title business description (see #title)
# @param method Http method of current request (see #method)
# @param url (see #url)
# @param body (see #body)
# @param headers (see #headers)
# @param read_timeout (see #read_timeout)
# @param open_timeout (see #open_timeout)
# @param driver is HTTP driver which use to send this request
# rubocop:disable Metrics/ParameterLists, Layout/LineLength
def initialize(title:, method: nil, url: nil, body: nil, headers: nil, open_timeout: nil, read_timeout: nil, driver:)
@title = title
@method = method
@url = url
@body = body
@headers = headers
@read_timeout = read_timeout
@open_timeout = open_timeout
@driver = driver
@sent_at = nil
end
# rubocop:enable Metrics/ParameterLists, Layout/LineLength
# Send current request (we cannot call this method `send` because it
# reserved word in ruby). It always return Response object, even if
# the server returned an error such as 404 or 502.
#
# @example correct answer
# request = Http::Request.new(
# title: 'Get users list',
# method: :get,
# url: 'http:://yandex.ru'
# )
# request.call # => <LunaPark::Http::Response @code=200 @body="Hello World!" @headers={}>
#
# @example Server unavailable
# request.call # => <LunaPark::Http::Response @code=503 @body="" @headers={}>
#
# After sending the request, the object is frozen. You should dup object to resend request.
#
# @note This method implements a facade pattern. And you better use it
# than call the Http::Send class directly.
#
# @return LunaPark::Http::Response
def call
@sent_at = Time.now
driver.call(self).tap { freeze }
end
# Send the current request. It returns a Response object only on a successful response.
# If the response failed, the call! method should raise an Erros::Http exception.
#
# After call! request you cannot change request attributes.
#
# @example correct answer
# request = Http::Request.new(
# title: 'Get users list',
# method: :get,
# url: 'https://example.com/users'
# )
# request.call # => <LunaPark::Http::Response @code=200 @body="Hello World!" @headers={}>
#
# @example Server unavailable
# request.call # => <LunaPark::Http::Response @code=503 @body="" @headers={}>
#
# After sending the request, the object is frozen. You should dup object to resend request.
#
# @note This method implements a facade pattern. And you better use it
# than call the Http::Send class directly.
#
# @return LunaPark::Http::Response
def call!
@sent_at = Time.now
driver.call!(self).tap { freeze }
end
# When object is duplicated, we should reset send timestamp
def initialize_dup(_other)
super
@sent_at = nil
end
# This method shows if this request has been already sent.
#
# @return Boolean
def sent?
!@sent_at.nil?
end
# This method return which driver are use, to send current request.
def driver
@driver ||= self.class.default_driver
end
# @example inspect get users index request
# request = LunaPark::Http::Request.new(
# title: 'Get users',
# method: :get,
# url: 'https://example.com/users'
# )
#
# request.inspect # => "<LunaPark::Http::Request @title=\"Get users\"
# # @url=\"http://localhost:8080/get_200\" @method=\"get\"
# # @headers=\"{}\" @body=\"\" @sent_at=\"\">"
def inspect
"<#{self.class.name} " \
"@title=#{title.inspect} " \
"@url=#{url.inspect} " \
"@method=#{method.inspect} " \
"@headers=#{headers.inspect} " \
"@body=#{body.inspect} " \
"@sent_at=#{sent_at.inspect}>"
end
# @example
# request.to_h # => {:title=>"Get users",
# :method=>:get,
# :url=>"http://localhost:8080/get_200",
# :body=>nil,
# :headers=>{},
# :read_timeout=>10,
# :open_timeout=>10}
def to_h
{
title: title,
method: method,
url: url,
body: body,
headers: headers,
read_timeout: read_timeout,
open_timeout: open_timeout,
sent_at: sent_at
}
end
end
end
end
| true
|
e50afea8b7b0cb298344b472bbfa886818adf5f7
|
Ruby
|
illustriam/mail-gpg
|
/lib/hkp.rb
|
UTF-8
| 4,118
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
require 'gpgme'
require 'openssl'
require 'net/http'
# simple HKP client for public key search and retrieval
class Hkp
class TooManyRedirects < StandardError; end
class InvalidResponse < StandardError; end
class Client
MAX_REDIRECTS = 3
def initialize(server, ssl_verify_mode: OpenSSL::SSL::VERIFY_PEER)
uri = URI server
@host = uri.host
@port = uri.port
@use_ssl = false
@ssl_verify_mode = ssl_verify_mode
# set port and ssl flag according to URI scheme
case uri.scheme.downcase
when 'hkp'
# use the HKP default port unless another port has been given
@port ||= 11371
when /\A(hkp|http)s\z/
# hkps goes through 443 by default
@port ||= 443
@use_ssl = true
end
@port ||= 80
end
def get(path, redirect_depth = 0)
Net::HTTP.start @host, @port, use_ssl: @use_ssl,
verify_mode: @ssl_verify_mode do |http|
request = Net::HTTP::Get.new path
response = http.request request
case response.code.to_i
when 200
return response.body
when 301, 302
if redirect_depth >= MAX_REDIRECTS
raise TooManyRedirects
else
http_get response['location'], redirect_depth + 1
end
else
raise InvalidResponse, response.code
end
end
end
end
def initialize(options = {})
if String === options
options = { keyserver: options }
end
@keyserver = options.delete(:keyserver) || lookup_keyserver || 'http://pool.sks-keyservers.net:11371'
@options = { raise_errors: true }.merge options
end
def raise_errors?
!!@options[:raise_errors]
end
#
# hkp.search 'user@host.com'
# will return an array of arrays, one for each matching key found, containing
# the key id as the first elment and any further info returned by the key
# server in the following elements.
# see http://tools.ietf.org/html/draft-shaw-openpgp-hkp-00#section-5.2 for
# what that *might* be. unfortunately key servers seem to differ in how much
# and what info they return besides the key id
def search(name)
[].tap do |results|
result = hkp_client.get "/pks/lookup?options=mr&search=#{URI.escape name}"
result.each_line do |l|
components = l.strip.split(':')
if components.shift == 'pub'
results << components
end
end if result
end
rescue
raise $! if raise_errors?
nil
end
# returns the key data as returned from the server as a string
def fetch(id)
result = hkp_client.get "/pks/lookup?options=mr&op=get&search=0x#{URI.escape id}"
return clean_key(result) if result
rescue Exception
raise $! if raise_errors?
nil
end
# fetches key data by id and imports the found key(s) into GPG, returning the full hex fingerprints of the
# imported key(s) as an array. Given there are no collisions with the id given / the server has returned
# exactly one key this will be a one element array.
def fetch_and_import(id)
if key = fetch(id)
GPGME::Key.import(key).imports.map(&:fpr)
end
rescue Exception
raise $! if raise_errors?
end
private
def hkp_client
@hkp_client ||= Client.new @keyserver, ssl_verify_mode: @options[:ssl_verify_mode]
end
def clean_key(key)
if key =~ /(-----BEGIN PGP PUBLIC KEY BLOCK-----.*-----END PGP PUBLIC KEY BLOCK-----)/m
return $1
end
end
def exec_cmd(cmd)
res = `#{cmd}`
return nil if $?.exitstatus != 0
res
end
def lookup_keyserver
url = nil
if res = exec_cmd("gpgconf --list-options gpgs 2>&1 | grep keyserver 2>&1")
url = URI.decode(res.split(":").last.split("\"").last.strip)
elsif res = exec_cmd("gpg --gpgconf-list 2>&1 | grep gpgconf-gpg.conf 2>&1")
conf_file = res.split(":").last.split("\"").last.strip
if res = exec_cmd("cat #{conf_file} 2>&1 | grep ^keyserver 2>&1")
url = res.split(" ").last.strip
end
end
url =~ /^(http|hkp)/ ? url : nil
end
end
| true
|
9f88fe24bca948fd30f2e7e99f9cec01bdf2adbd
|
Ruby
|
cddurbin/tic_tac_toe
|
/app/models/move.rb
|
UTF-8
| 542
| 2.671875
| 3
|
[] |
no_license
|
class Move < ActiveRecord::Base
attr_accessor :player1
belongs_to :user
belongs_to :game
def self.find_mark(game_id)
game = Game.find(game_id)
if game.moves.present?
if game.moves.last.mark == "x"
"o"
else
"x"
end
else
"x"
end
end
def self.computer_move(game_id)
game = Game.find(game_id)
positions_taken = game.moves.map { |move| move.position }
board = (0..8).to_a
available = board - positions_taken
available.sample
end
end
| true
|
9b09b7a98a53837fe75f6bb1fc6c14d34bb3b844
|
Ruby
|
KakeruYamamoto/peawork
|
/sample2.rb
|
UTF-8
| 3,642
| 3.34375
| 3
|
[] |
no_license
|
class VendingMachine
MONEY = [10, 50, 100, 500, 1000].freeze #0-1.10円玉、50円玉、100円玉、500円玉、1000円札を1つずつ投入できる。
def initialize
@slot_money = 0
@proceeds = 0
item = Item.new
@stock = [item.coke, item.redbull, item.water]
end
def current_slot_money #0-3.投入金額の総計を取得できる。
@slot_money
end
def slot_money(money) #0-2.投入は複数回できる。 1-1.想定外のもの(硬貨:1円玉、5円玉。お札:千円札以外のお札)が投入された場合は、投入金額に加算せず、それをそのまま釣り銭としてユーザに出力する。
if MONEY.include?(money)
@slot_money += money
self.can_purchase_list
nil
else
money
end
end
def return_money #0-4.払い戻し操作を行うと、投入金額の総計を釣り銭として出力する。
slot_money = @slot_money
@slot_money = 0
slot_money
end
#4-4.投入金額、在庫の点で購入可能なドリンクのリストを取得できる。
def can_purchase_list1. #3-1 投入金額、在庫の点で、コーラが購入できるかどうかを取得できる。
@can_purchase = []
@stock.map {|stock| #(stock[0,2][:price]).to_i
if stock != [] && @slot_money >= (stock[0][:price]).to_i #コーラの値段
@can_purchase << stock
else
@can_purchase << []
end #5-2.ジュースと投入金額が同じ場合、つまり、釣り銭0円の場合も、釣り銭0円と出力する。
} # 5-1.ジュース値段以上の投入金額が投入されている条件下で購入操作を行うと、釣り銭(投入金額とジュース値段の差分)を出力する。
end #3-5.払い戻し操作では現在の投入金額からジュース購入金額を引いた釣り銭を出力する。
#3-3.投入金額が足りない場合もしくは在庫がない場合、購入操作を行っても何もしない。
def purchase(x) #3-2.ジュース値段以上の投入金額が投入されている条件下で購入操作を行うと、ジュースの在庫を減らし、売り上げ金額を増やす。
if @can_purchase[x] != []
@slot_money -= (@can_purchase[x][0][:price]).to_i
@proceeds += (@can_purchase[x][0][:price]).to_i
@stock[x].shift
self.return_money
else
end
end
def current_proceeds #3-4.現在の売上金額を取得できる。
@proceeds
end
end
end
class Stocks #2-2 2.格納されているジュースの情報(値段と名前と在庫)を取得できる。
def stock_info(menu_price, menu_name, number)
menu = {price: "#{menu_price}",name: "#{menu_name}"}
stock = []
number.times do
stock << menu
end
stock
end
end
#4-1,2,3.ジュースを3種類管理できるようにする。/2.在庫にレッドブル(値段:200円、名前”レッドブル”)5本を追加する。/3.在庫に水(値段:100円、名前”水”)5本を追加する。
class Item #2-1 1.値段と名前の属性からなるジュースを1種類格納できる。初期状態で、コーラ(値段:120円、名前”コーラ”)を5本格納している。
def coke
stock = Stocks.new.stock_info(120, "coke", 5)
end
def redbull
stock = Stocks.new.stock_info(200, "Red Bull", 5)
end
def water
stock = Stocks.new.stock_info(100, "water", 5)
end
end
vm = VendingMachine.new
p vm.can_purchase_list1.
| true
|
d7430d8ac9b4c0ae3c54a4c9170f798b23b9f092
|
Ruby
|
wwit-atl/movie-archive
|
/bin/movie-archive
|
UTF-8
| 1,841
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
require 'wwit/archive'
require 'colorize'
opt = WWIT::Archive::Options.parse(ARGV)
if opt.verbose
puts 'Source directories are'.light_white + " #{opt.source.join(', ').green}"
puts 'Destination directory is'.light_white + " #{(opt.dest ? opt.dest : 'same as source file').green}"
puts 'Files '.light_white + (opt.cloud ? 'will also'.green : 'will not'.light_red) + ' be copied to the AWS Cloud Drive'.light_white
puts "We'll be working on files older than ".light_white +
opt.days.to_s.green + " day#{opt.days > 1 ? 's' : ''}".light_white if opt.days > 0
end
if opt.dryrun
print "\n" if opt.verbose
puts 'Hey! DRYRUN is enabled, NO filesystem changes will be made.'.light_yellow
print "\n" if opt.verbose
end
# Create our movies object -- which, in turn, contains each movie file in the given source dir(s)
movies = WWIT::Archive::Movies.new( opt.source, opt )
if movies.empty?
puts 'Hmm, no movie files were found. Check your source directories?'.light_red if opt.verbose
exit 1
end
puts "#{opt.present_verb} #{movies.count} files... " if opt.verbose
# Today's datetime
file_count = 0
# Process each movie file
movies.each do |movie|
new_filename = movie.newfilename( opt.dest || movie.directory )
# Make sure it's older than the days to keep
if opt.days > movie.age_in_days
puts "Skipped #{movie}: Too New (#{movie.age_in_days} days old)".light_red if opt.verbose
next
end
print "%s -> %s ( %s )\n" % [
(opt.debug ? movie.fullpath : movie.filename).light_blue,
new_filename.light_blue,
movie.size_to_s.light_black
] if opt.verbose
next if opt.dryrun
# Actually copy or move the file
movie.process( opt.copy, new_filename )
file_count += 1
end
puts "Complete - #{file_count} files #{opt.past_verb}".green if opt.verbose
exit 0
| true
|
feaf5224ca7c70bfdf08b03cf296b05a48618414
|
Ruby
|
jecrockett/Turing_Homework
|
/1014_looping.rb
|
UTF-8
| 743
| 4.46875
| 4
|
[] |
no_license
|
# 1 Easy Looping
5.times do
puts "Line"
end
#2 Looping with a condition
5.times do |i|
if i.even?
puts "Line is even"
else
puts "Line is odd"
end
end
# 3 Three Loops
5.times do |i|
puts "This is my output line #{i + 1}"
end
line = 0
while line < 5
line += 1
puts "This is my output line #{line}"
end
counter = 0
loop do
counter += 1
puts "This is my output line #{counter}"
if counter == 5
break
end
end
# 4 Rando-Guesser
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
loop do
secret_num = numbers.sample
puts "(The secret number is #{secret_num})"
guess = numbers.sample
puts "Guess is #{guess}"
if guess == secret_num
puts "You win!"
break
else
puts "Guess again!"
end
end
| true
|
36947b77daa437469d4fa11fbaac52a8323de165
|
Ruby
|
Muriel-Salvan/ruby-serial
|
/lib/ruby-serial/_object.rb
|
UTF-8
| 1,355
| 3.234375
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
# Instrument Object to get access to the list of instance variables to be serialized.
class Object
# Get the list of instance variables that are meant to be serialized
#
# Result::
# * <em>map<String,Object></em>: Set of instance variables, per name
def instance_vars_to_be_rubyserialized
# Compute the list of attributes to serialize
instance_var_names = []
klass = self.class
if !klass.rubyserial_only_lst.nil?
if klass.dont_rubyserial_lst.nil?
instance_var_names = klass.rubyserial_only_lst
else
instance_var_names = klass.rubyserial_only_lst - klass.dont_rubyserial_lst
end
elsif !klass.dont_rubyserial_lst.nil?
instance_var_names = instance_variables - klass.dont_rubyserial_lst
else
instance_var_names = instance_variables
end
# Compute the resulting map
instance_vars = {}
instance_var_names.each do |sym_var|
instance_vars[sym_var.to_s] = instance_variable_get(sym_var)
end
instance_vars
end
# Set the list of instance variables that were serialized
#
# Parameters::
# * *instance_vars* (<em>map<String,Object></em>): Set of instance variables, per name
def fill_instance_vars_from_rubyserial(instance_vars)
instance_vars.each do |var_name, value|
instance_variable_set(var_name.to_sym, value)
end
end
end
| true
|
86838c1296a3ef8297a09c810a56e4a86c5cf92d
|
Ruby
|
CoopTang/mod_2_ruby_challenge
|
/lib/round.rb
|
UTF-8
| 700
| 3.671875
| 4
|
[] |
no_license
|
class Round
attr_reader :guess, :code, :correct_elements, :correct_positions
def initialize(guess, code)
@guess = guess
@code = code
@correct_elements = calculate_correct_elements
@correct_positions = calculate_correct_positions
end
def correct?
@code == @guess
end
private
def calculate_correct_elements
total = 0
code = @code.chars
@guess.chars.each do |char|
index = code.find_index(char)
if index
total += 1
code.delete_at(index)
end
end
total
end
def calculate_correct_positions
total = 0
@guess.chars.each_index do |i|
total += 1 if @guess[i] == @code[i]
end
total
end
end
| true
|
75447feec8616e5ab665b13f0358dd1720cd8610
|
Ruby
|
tkengo/algorithms
|
/ruby/algorithms/sort/bubble_sort.rb
|
UTF-8
| 218
| 3.421875
| 3
|
[] |
no_license
|
class Array
def bubble_sort
a = self
(1..a.size).each do |i|
(a.size - i).times do |j|
if a[j] > a[j + 1]
a[j], a[j + 1] = a[j + 1], a[j]
end
end
end
a
end
end
| true
|
03ac323d4932f7fcaac40b03491f8ef9c70b474e
|
Ruby
|
FCSadoyama/api-oauth2-template
|
/app/services/authorizations/authenticators/password.rb
|
UTF-8
| 439
| 2.609375
| 3
|
[] |
no_license
|
module Authorizations
module Authenticators
class Password
def initialize(email:, password:)
@email = email
@password = password
end
def call
user if authenticated?
end
private
attr_reader :email, :password
def authenticated?
user.authenticate(password)
end
def user
@user ||= User.find_by(email: email)
end
end
end
end
| true
|
250779f9ad3be59bc7ada18f1306af3416b92a2d
|
Ruby
|
diegoarvz4/rspec-tictactoe
|
/lib/board.rb
|
UTF-8
| 329
| 3.390625
| 3
|
[
"MIT"
] |
permissive
|
require_relative 'ui.rb'
class Board
include UI
attr_reader :dimensions
def initialize
@dimensions= [0,1,2,3,4,5,6,7,8]
end
def set_cell(value, turn)
@dimensions[value] = turn
end
def is_full?
@dimensions.all? { |square| square.is_a?(String) }
end
end
| true
|
662b32660237ac565a1ea298c1fb249cce9c34b1
|
Ruby
|
tksasha/vm
|
/app/models/coin.rb
|
UTF-8
| 702
| 3.109375
| 3
|
[] |
no_license
|
# frozen_string_literal: true
class Coin < ApplicationModel
self.database = 'db/coins.yml'
class << self
def available
all.select { |_, value| value.positive? }
end
def push(coin)
return unless all.key? coin
all[coin] = quantity(coin) + 1
end
def pop(coin)
return unless all.key? coin
return unless all[coin].positive?
all[coin] = quantity(coin) - 1
end
def sum(value)
all
.select { |coin, _| coin <= value }
.sum { |coin, quantity| coin * quantity }
end
def sufficient?(value)
sum(value) >= value
end
private
def quantity(coin)
all.fetch(coin) { 0 }
end
end
end
| true
|
5e2b115baa30a3bc7bec6fa5e97231f49523ac2b
|
Ruby
|
ojnunez/movie_rental_store
|
/app/controllers/admins/api_v1/movies_controller.rb
|
UTF-8
| 2,031
| 2.53125
| 3
|
[] |
no_license
|
# frozen_string_literal: true
module Admins
module ApiV1
class MoviesController < Admins::ApiV1Controller
before_action :set_item, only: %i[update destroy]
# GET /admins/api/movies
def index
# Get movies that are available
@movies = Movie.order(title: :asc)
# Simple search if params availability comes in the url
if params[:availability] && params[:availability] == 'true'
@movies = @movies.where(availability: true)
elsif params[:availability] && params[:availability] == 'false'
@movies = @movies.where(availability: false)
end
render json: @movies.to_json
end
# POST /admins/api/movies
def create
@movie = Movie.new item_params
if @movie.save
render json: @movie.to_json,
status: :created
else
render json: @movie.errors, status: :unprocessable_entity
end
end
# PATCH /admins/api/movies/:id
def update
@movie.assign_attributes item_params.reject { |_, v| v.blank? }
# In the current API we allow the admin update any fields, to do that we
# need to remove all the blank params of the object, because we don't
# want to trigger any validations for the fields that we didn't send
if @movie.save
render json: @movie.to_json
else
render json: @movie.errors, status: :unprocessable_entity
end
end
# DELETE /admins/api/movies/:id
def destroy
# Destroy the movie once and for all and return a nice 200 OK header
@movie.destroy
render status: 200
end
private
# White list for allowed params.
def item_params
params.require(:movie).permit(:title, :description, :stock,
:sale_price, :rent_price, :availability, :cover)
end
# find item
def set_item
@movie = Movie.find(params[:id])
end
end
end
end
| true
|
af31f432bad80c2f580d97d98b95d260abb6ba51
|
Ruby
|
chrislomaxjones/Ruby-programs
|
/snippets/methods/break_procs.rb
|
UTF-8
| 1,952
| 4.375
| 4
|
[] |
no_license
|
# Procs.new is the iterator that break would return from
# By the time we invoke the proc obj, the iterator
# has already returned
# therefore it never makes sense to have a top-level
# break statement in a proc created with Proc.new
def test
puts "Entering method"
p = Proc.new { puts "Entering Proc"; break }
begin
p.call # => LocalJumpError
rescue
puts "We got an error breaking!"
end
puts "Exiting method"
end
test
# If we create a proc object with & argument to an
# iterator method, then we can invoke it and make
# the iterator return
def iterator(&proc)
puts "Entering iterator"
proc.call
puts "Exiting iterator" # This code is never executed
end
def test2
iterator { puts "Entering proc"; break }
end
test2
# Lambdas are method-like, so break doesn't make sense!
# break just acts like return
# note "Exiting lambda" is never printed in code below
def test3
puts "Entering test method"
l = ->{ puts "Entering lambda"; break; puts "Exiting lambda" }
l.call
puts "Exiting test method"
end
test3
# OTHER CONTROL STATEMENTS IN PROCS AND LAMBDAS
#----------------------------------------------
# NEXT
#-----
# a next statement causes the yield or call method method that
# invoked the block/proc/lambda to return
# if next is followed by an expression these are returned to yield
def triangles(n)
s = []
1.upto n do |i|
n, triangle_n = yield i
s << [n, triangle_n]
end
s
end
# Note how next works for block (as usual)
t = triangles(5) do |n|
next n, n*(n+1)/2 # => [[1, 1], [2, 3], [3, 6], [4, 10], [5, 15]]
end
puts t.to_s
# here in Proc
p = Proc.new {|n| next n, n*(n+1)/2 }
puts triangles(5, &p).to_s # => [[1, 1], [2, 3], [3, 6], [4, 10], [5, 15]]
# here in lambda
l = ->(n){ next n, n*(n+1)/2 }
puts triangles(5, &l).to_s # => [[1, 1], [2, 3], [3, 6], [4, 10], [5, 15]]
# REDO
#-----
# Works the same
# RETRY
#------
# Never allowed
# RAISE
#------
# Behaves the same in procs and lambdas.
| true
|
e42be20f3eb291a5a6d94d9d456cb91b4f67bb4d
|
Ruby
|
makiton/portfolio
|
/lib/portfolio/asset_class.rb
|
UTF-8
| 631
| 3.15625
| 3
|
[
"MIT"
] |
permissive
|
module Portfolio
class AssetClass
attr_accessor :name
attr_reader :histdata, :equity, :variance, :mean
def initialize(name:, histdata:)
@name = name
@histdata = histdata
end
def mean
@mean ||= histdata.sum.to_f / histdata.count
end
def equity
mean / histdata.first
end
def variance
@variance ||= histdata.map { |d| (d - mean) ** 2 }.sum / histdata.count
end
def covariance(another_class)
histdata.each_with_index { |d, i|
(d - mean) * (another_class.histdata[i] - another_class.mean)
}.sum.to_f / histdata.count
end
end
end
| true
|
336577c517ec5370eda21eea390132d581241a13
|
Ruby
|
schambon/pleo
|
/app/models/word.rb
|
UTF-8
| 319
| 3.109375
| 3
|
[] |
no_license
|
# a word (actually a stem) found in the text input
class Word
attr_accessor :stem, :char_position, :word_position, :as_found
def initialize(text, char_position, word_position)
@stem = Stemmer.new.stem text
@char_position = char_position
@word_position = word_position
@as_found = text
end
end
| true
|
2031163c77ff262a626132e6af4083eccc21e263
|
Ruby
|
kyokucho1989/ruby-kyozai
|
/ch2-1-1.rb
|
UTF-8
| 260
| 3.5
| 4
|
[] |
no_license
|
# require 'pry'
puts <<-text
おみくじを引いてみよう!
press enter
text
gets
select_num = rand(1..3)
# binding.pry
if select_num == 1
puts '大吉!!!'
elsif select_num == 2
puts '吉です'
elsif select_num == 3
puts '凶……。'
end
| true
|
7d4353291ce393123e49b879894b8b19f7ba81d5
|
Ruby
|
mugyu/algorithms
|
/ruby/list/queue.rb
|
UTF-8
| 976
| 3.84375
| 4
|
[] |
no_license
|
# リスト構造
# キュー
# First In First Out
# Singly-linked list
require 'pp'
class Queue
def initialize
@value = []
@next = []
@head = 0
@tail = -1
end
def enqueue(x)
p = @tail
@tail += 1
@value[@tail] = x
@next[@tail] = nil
@next[p] = @tail unless @head == @tail
end
def dequeue
return nil if @head > @tail
x = @value[@head]
p = @next[@head]
@value[@head] = nil
@next[@head] = nil
@head = p
x
end
def show
return nil if @head > @tail
p = @head
result = ""
while p
result << @value[p] + " "
p = @next[p]
end
result
end
def debug
puts "-" * 40
p show
p ["value", @value]
p [" next", @next]
p [" head", @head]
p [" tail", @tail]
end
end
queue = Queue.new
p queue.dequeue
queue.debug
queue.enqueue("a")
0.upto 8 do |i|
queue.debug
queue.enqueue((98 + i).chr)
end
queue.debug
p queue.dequeue
queue.debug
| true
|
f39b0ab6fbad7a23d4dedf9ee2b751d03ef421cb
|
Ruby
|
malachaifrazier/Beatstream
|
/test/api_test_helper.rb
|
UTF-8
| 626
| 2.515625
| 3
|
[
"LicenseRef-scancode-other-permissive"
] |
permissive
|
# API test helpers
def get_json(url)
get url, :format => :json
end
def post_json(url, data)
post url, data.to_json, { 'CONTENT_TYPE' => 'application/json' }
end
def put_json(url, data)
put url, data.to_json, { 'CONTENT_TYPE' => 'application/json' }
end
def delete_json(url)
delete url, :format => :json
end
def post_multipart(url, data)
post url, data, { 'CONTENT_TYPE' => 'multipart/form-data' }
end
def assert_put_json(url, data)
put_json url, data
res1 = json_response
get_json url
res2 = json_response
assert_equal res1, res2
end
def json_response
ActiveSupport::JSON.decode @response.body
end
| true
|
d78d7117a37835ba8f85a5f389ab2ec3639f5994
|
Ruby
|
cameronepstein/sam
|
/test.rb
|
UTF-8
| 427
| 3.859375
| 4
|
[] |
no_license
|
puts "hi, write something"
input = gets.chomp
if input.include?('0') || input.include?('1') || input.include?('2') || input.include?('3') || input.include?('4') || input.include?('5') || input.include?('6') || input.include?('7') || input.include?('8') || input.include?('9')
puts 'nice number bro'
if input.to_i < 50
puts 'and youre not greedy'
else
puts 'what the hell?'
end
else
puts 'number please'
end
| true
|
e75aa1cbf1163c5e1a7e6a92a8afb1279b938bbf
|
Ruby
|
nachiket87/RubyAlgorithms
|
/13-Coin/main.rb
|
UTF-8
| 474
| 3.15625
| 3
|
[] |
no_license
|
# frozen_string_literal: true
# not solved by me - Dynamic Programming est pas bonne
def change_possibilities_bottom_up(amount, denominations)
ways_of_doing_n_cents = [1] + Array.new(amount, 0)
denominations.each do |coin| # 1
(coin..amount).each do |higher_amount|
higher_amount_remainder = higher_amount - coin
ways_of_doing_n_cents[higher_amount] += ways_of_doing_n_cents[higher_amount_remainder]
end
end
ways_of_doing_n_cents[amount]
end
| true
|
628f8101c5937c9de55be3d1b1a4f02238a9987d
|
Ruby
|
Bhanditz/JS.coach
|
/project/test/helpers/time_helper_test.rb
|
UTF-8
| 1,133
| 2.71875
| 3
|
[] |
no_license
|
require "test_helper"
class TimeHelperTest < ActionView::TestCase
it "returns a relative time" do
relative_timestamp(Time.now).must_equal "today"
relative_timestamp(1.hour.ago).must_equal "today"
relative_timestamp(24.hours.ago).must_equal "yesterday"
relative_timestamp(1.day.ago).must_equal "yesterday"
relative_timestamp(2.days.ago).must_equal "2 days ago"
relative_timestamp(30.days.ago).must_equal "a month ago"
relative_timestamp(1.month.ago).must_equal "a month ago"
relative_timestamp(1.month.ago + 1.minute).must_equal "a month ago" # `time_ago_in_words` returns "30 days"
relative_timestamp(2.months.ago).must_equal "2 months ago"
relative_timestamp(12.months.ago).must_equal "a year ago"
relative_timestamp(1.year.ago).must_equal "a year ago"
relative_timestamp(1.year.ago + 1.minute).must_equal "a year ago" # `time_ago_in_words` returns "12 months"
relative_timestamp(2.years.ago).must_equal "2 years ago"
relative_timestamp(2.years.ago - 6.months).must_equal "2 years ago"
relative_timestamp(3.years.ago).must_equal "a long long time ago"
end
end
| true
|
eb20bcf93ce0b71a8f3935ff525e014e0e81309b
|
Ruby
|
lwangenheim/WGrubyist
|
/stack.rb
|
UTF-8
| 325
| 3.453125
| 3
|
[] |
no_license
|
require_relative "stacklike"
class Stack
include Stacklike
end
s = Stack.new
s.add_to_stack("item one")
s.add_to_stack("item two")
s.add_to_stack("item three")
puts "Objects currently on the stack: "
puts s.stack
taken = s.take_from_stack
puts "removed this object: "
puts taken
puts "now on stack: "
puts s.stack
| true
|
a449530886a7940dbfe05ccc7a4410cbba057589
|
Ruby
|
lroliphant/inject-challenge
|
/spec/injecty_spec.rb
|
UTF-8
| 391
| 2.984375
| 3
|
[] |
no_license
|
require 'injecty'
describe Array do
subject(:array) { [1, 2, 3] }
it { is_expected.to respond_to(:injecty).with(1).arguments }
describe '#injecty' do
# tests for the simplest thing array.inject will do
it 'kind of adds elements in the array and returns a single value' do
expect(array.injecty { |accumulator, iterated| accumulator + iterated }).to eq 6
end
end
end
| true
|
e83f80037a3f4dd7c1888758203e52bcfc6c91e2
|
Ruby
|
awochna/todotxt_rb
|
/spec/lib/todotxt_rb/list_spec.rb
|
UTF-8
| 2,529
| 3.0625
| 3
|
[] |
no_license
|
require 'spec_helper'
describe TodotxtRb::List do
def create_tasks
file = 'spec/todo.txt'
array = []
File.open(file) do |file|
file.each_line do |line|
array.push(TodotxtRb::Task.new(line.chomp))
end
end
array
end
it "takes an array of tasks" do
task = TodotxtRb::Task.new('Clean desk')
expect { TodotxtRb::List.new([task]) }.to_not raise_error
end
let!(:list) { TodotxtRb::List.new(create_tasks) }
subject { list }
specify "sanity" do
expect(list[0].to_str).to eq "(A) 2015-04-28 Clean desk @home"
end
describe "interface" do
it { is_expected.to respond_to :projects }
it { is_expected.to respond_to :contexts }
it { is_expected.to respond_to :completed }
it { is_expected.to respond_to :incomplete }
it { is_expected.to respond_to :length }
end
it "should contain tasks" do
list.each do |task|
expect(task).to be_instance_of TodotxtRb::Task
end
end
it { is_expected.to have_context '@work' }
it { is_expected.to have_context '@home' }
it { is_expected.to have_context '@boss' }
it { is_expected.to have_project '+NewApp' }
it { is_expected.to have_project '+NewSiteProject' }
it "can list it's projects" do
expect(list.projects).to eq ['+NewApp','+NewSiteProject']
end
it "can list it's contexts" do
expect(list.contexts).to eq ['@boss', '@home', '@work']
end
it "can give a new list of it's incomplete tasks" do
expect(list.incomplete.length).to eq 3
end
it "can give a new list of it's complete tasks" do
expect(list.completed.length).to eq 1
end
it "converts to string nicely" do
string = "(A) 2015-04-28 Clean desk @home"
expect(list.to_str).to include string
end
it "can list its priorities" do
expect(list.priorities).to include "A"
expect(list.priorities).to_not include "D"
end
describe "prints out" do
specify "nicely" do
string = "(A) 2015-04-28 Clean desk @home"
expect(list.to_s).to include string
end
specify "with line numbers" do
string = "1 (A) 2015-04-28 Clean desk @home"
expect(list.to_s).to include string
end
end
describe "can filter" do
specify "tasks with @work context" do
expect(list.filter('@work').length).to eq 3
end
specify "tasks with +NewSite project" do
expect(list.filter('+NewSite').length).to eq 1
end
specify "tasks with an arbitrary word" do
expect(list.filter('Clean').length).to eq 1
end
end
end
| true
|
ecdcac9ff942c9380ae7e500e13eef5f14a362c5
|
Ruby
|
modular-magician/magic-modules
|
/build/presubmit/perc_bar.rb
|
UTF-8
| 1,982
| 2.90625
| 3
|
[
"Apache-2.0"
] |
permissive
|
#!/bin/ruby
# Copyright 2017 Google Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module Google
class ProgressBar
BAD_COVERAGE = -5 # drop in 5% is really bad
GOOD_COVERAGE = 95 # happy if coverage is over 95%
COLOR_CYAN = "\x1b[36m"
COLOR_GREEN = "\x1b[32m"
COLOR_RED = "\x1b[31m"
COLOR_YELLOW = "\x1b[33m"
COLOR_NONE = "\x1b[0m"
COLOR_NO_COLOR = ''
def self.build(before, after, slots)
step = 100.0 / slots
real_delta = after - before
# If any delta, we should at minimum 1 char
delta = [(real_delta.abs / step).round, 1].max
base = [([before, after].min / step).round - 1, 0].max
gap = (slots - delta - base - 1)
color = if real_delta <= BAD_COVERAGE
COLOR_RED
elsif real_delta < 0
COLOR_YELLOW
elsif real_delta > 0 && after >= GOOD_COVERAGE
COLOR_GREEN
elsif real_delta > 0
COLOR_CYAN
else
COLOR_NO_COLOR
end
if before > after
"#{color}[#{'-' * base}|#{'X' * delta}#{' ' * gap}]#{COLOR_NONE}" \
elsif before == after
"#{color}[#{'-' * base}#{'-' * delta}|#{' ' * gap}]" \
else
"#{color}[#{'-' * base}|#{'+' * delta}#{' ' * gap}]#{COLOR_NONE}" \
end
end
end
end
# Launched from command line
if __FILE__ == $0
puts Google::ProgressBar.build(ARGV[0].to_f, ARGV[1].to_f, ARGV[2].to_f)
end
| true
|
18136c7b5f5decb494b24c5f138c413208dc9ca0
|
Ruby
|
brendanwb/exercises_for_programmers
|
/tip_calculator/ruby/tip_calc/lib/tip_calc.rb
|
UTF-8
| 434
| 3.4375
| 3
|
[] |
no_license
|
class TipCalc
attr_reader :tip, :total
def initialize(bill_amount, tip_rate)
@bill_amount = bill_amount
@tip_rate = tip_rate
@tip = 0
@total = 0
end
def process
@tip = process_tip
@total = process_total
end
private
def process_tip
(@bill_amount * (@tip_rate / 100.0)).round(2)
end
def process_total
(@bill_amount * (1 + (@tip_rate / 100.0))).round(2)
end
end
| true
|
5a1b8a8b6c16ee19182712633c9f31f2f991678c
|
Ruby
|
imanaa/rprojects
|
/bin/sudoku.rb
|
UTF-8
| 926
| 2.984375
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
#encoding: utf-8
###############################################################################
# sudoku.rb -- Solve a sudoku game
# Arguments:
#
#
# Copyright (C) 2012 Imad MANAA
# Last Modified : 13th, September 2012
# Version : 1.0
###############################################################################
require_relative "../lib/rprojects/sudoku"
include Sudoku
grid = Grid[
[nil,nil,3 ,nil,nil,nil,9 ,nil,nil],
[nil,nil,nil,9 ,nil,1 ,nil,nil,nil],
[nil,8 ,5 ,nil,nil,nil,2 ,7 ,nil],
[nil,2 ,nil,5 ,nil,9 ,nil,4 ,nil],
[nil,nil,nil,nil,1 ,nil,nil,nil,nil],
[nil,1 ,nil,4 ,nil,6 ,nil,8 ,nil],
[nil,7 ,1 ,nil,nil,nil,5 ,9 ,nil],
[nil,nil,nil,7 ,nil,8 ,nil,nil,nil],
[nil,nil,4 ,nil,nil,nil,6 ,nil,nil]
]
=begin
1.upto(1) do
line = readline.chomp!.strip!
end
=end
grid.solve
puts grid
| true
|
93f2ecfbd69e45ed6eb6df209c79846bb4390a67
|
Ruby
|
JoeG21/houston-se-071320
|
/04-object-relations-many-many/run.rb
|
UTF-8
| 839
| 2.96875
| 3
|
[] |
no_license
|
require 'pry'
require_relative './user'
require_relative './tweet'
require_relative './like'
naruto = User.new("Naruto")
sasuke = User.new("Sasuke")
sakura = User.new("Sakura")
t1 = naruto.post_tweet("This class is 🔥")
t2 = sasuke.post_tweet("First tweet ever!!")
t3 = sasuke.post_tweet("Objects...Classes...Methods...Self...What the heck?")
t4 = sakura.post_tweet("This is has_many - belongs_to!!")
naruto.like_tweet(t3)
sakura.like_tweet(t3)
# t3.likers => [ naruto, sakura ]
binding.pry
# puts "-----------------------------------------------------------------------"
# puts "| Tweets: |"
# puts "-----------------------------------------------------------------------"
#
# naruto.show_timeline
# sasuke.show_timeline
# sakura.show_timeline
#
# puts "-----------------------------------------------------------------------"
| true
|
662bda4d95cff867ab8cd25ba7a18ce091e7f361
|
Ruby
|
joan2kus/ChartDirector
|
/railsdemo/app/controllers/colorbar_controller.rb
|
UTF-8
| 1,622
| 2.609375
| 3
|
[
"IJG"
] |
permissive
|
require("chartdirector")
class ColorbarController < ApplicationController
def index()
@title = "Multi-Color Bar Chart"
@ctrl_file = File.expand_path(__FILE__)
@noOfCharts = 1
render :template => "templates/chartview"
end
#
# Render and deliver the chart
#
def getchart()
# The data for the bar chart
data = [85, 156, 179.5, 211, 123]
# The labels for the bar chart
labels = ["Mon", "Tue", "Wed", "Thu", "Fri"]
# The colors for the bar chart
colors = [0xb8bc9c, 0xa0bdc4, 0x999966, 0x333366, 0xc3c3e6]
# Create a XYChart object of size 300 x 220 pixels. Use golden background color.
# Use a 2 pixel 3D border.
c = ChartDirector::XYChart.new(300, 220, ChartDirector::goldColor(), -1, 2)
# Add a title box using 10 point Arial Bold font. Set the background color to
# metallic blue (9999FF) Use a 1 pixel 3D border.
c.addTitle("Daily Network Load", "arialbd.ttf", 10).setBackground(
ChartDirector::metalColor(0x9999ff), -1, 1)
# Set the plotarea at (40, 40) and of 240 x 150 pixels in size
c.setPlotArea(40, 40, 240, 150)
# Add a multi-color bar chart layer using the given data and colors. Use a 1 pixel
# 3D border for the bars.
c.addBarLayer3(data, colors).setBorderColor(-1, 1)
# Set the labels on the x axis.
c.xAxis().setLabels(labels)
# Output the chart
send_data(c.makeChart2(ChartDirector::PNG), :type => "image/png",
:disposition => "inline")
end
end
| true
|
2b06e1c79fc6e97e803bf136728897628c1a8ef1
|
Ruby
|
Joanne0330/student-directory
|
/directory_exercises.rb
|
UTF-8
| 3,343
| 3.40625
| 3
|
[] |
no_license
|
# students = [
# {name: "Dr. Hannibal Lecter", cohort: :november},
# {name: "Darth Vader", cohort: :november},
# {name: "Nurse Ratched", cohort: :november},
# {name: "Michael Corleone", cohort: :november},
# {name: "Alex DeLarge", cohort: :november},
# {name: "The Wicked Witch of the West", cohort: :november},
# {name: "Terminator", cohort: :november},
# {name: "Freddy Krueger", cohort: :november},
# {name: "The Joker", cohort: :november},
# {name: "Joffrey Baratheon", cohort: :november},
# {name: "Norman Bates", cohort: :november}
# ]
# I am not using bash but this code should works for the TL;DR s
# ection: def ask prompt, default = nil; unless default;
# return gets.chomp; end; return default; end; and you can use it
# like: ask 'what is your name' waits for your reply. ask 'what
# is your name', 'darek' this just return default value. Well, if
# that's code that you are looking for I will post it as answer
# and explain more (because comment section has character limits).
# ps. or little hackish way: def ask2 prompt, default = nil;
# default || gets.chomp; end;
# def input_students
# # default = nil
# students = []
# puts "Please enter the names of the students"
# name = gets.chomp
# puts "Please enter the month of your cohort"
# month = gets.chomp
# puts "To finish, just hit return twice"
# while !name.empty? do
# # add the student has to the array
# students << {name: name, cohort: month}
# puts "Now we have #{students.count} students"
# name = gets.chomp
# month = gets.chomp
# end
# combine two arrays into a hash
# while the name is not empty, repeat this code
# while !name.empty? do
# add the student has to the array
# return the array of students
# students
# end
# input_students
# def print(students)
# students.each do | student |
# puts "#{student[:name]} (#{student[:cohort]} cohort)"
# end
# end
# input_students
# print
# def input_students
# puts "Please enter the names of the students"
# puts "To finish, just hit return twice"
# # create an empty array
# students = []
# # get the first name
# name = gets.chomp
# # while the name is not empty, repeat this code
# while !name.empty? do
# # add the student has to the array
# students << {name: name, cohort: :november}
# puts "Now we have #{students.count} students"
# name = gets.chomp
# end
# # return the array of students
# students
# end
# # let's put all students into an array
# students = [
# {name: "Dr. Hannibal Lecter", cohort: :november},
# {name: "Darth Vader", cohort: :november},
# {name: "Nurse Ratched", cohort: :november},
# {name: "Michael Corleone", cohort: :november},
# {name: "Alex DeLarge", cohort: :november},
# {name: "The Wicked Witch of the West", cohort: :november},
# {name: "Terminator", cohort: :november},
# {name: "Freddy Krueger", cohort: :november},
# {name: "The Joker", cohort: :november},
# {name: "Joffrey Baratheon", cohort: :november},
# {name: "Norman Bates", cohort: :november}
# ]
# def print_header
# puts "The students of my cohort at Makers"
# puts "-------------"
# end
def print(students)
students.each do | student|
puts "#{student[:name].center(28)} (#{student[:cohort]} cohort)"
end
# end
# def print_footer(names)
# puts "Overall, we have #{names.count} great students"
# end
# #nothing happens until we call the methods
# students = input_students
# print_header
# print(students)
# print_footer(students)
| true
|
2d1362821e977722064a976adc252c8e48765309
|
Ruby
|
nachoal/pragmatic_studio
|
/studio_game/game_turn.rb
|
UTF-8
| 383
| 3.296875
| 3
|
[] |
no_license
|
require_relative 'die'
require_relative 'player'
require_relative 'treasure_trove'
module GameTurn
def self.take_turn(player)
die = Die.new
case die.roll
when 1..2
player.blam
when 3..4
puts "#{player.name} was skipped"
else
player.w00t
end
item = TreasureTrove.random
puts "#{player.name} found a #{item.name} woth #{item.point}."
end
end
| true
|
d04ddfde042cf0f5845503ebf9f0c7935c03e410
|
Ruby
|
OmarMAbbasi/Metaprogramming-Project
|
/lib/00_attr_accessor_object.rb
|
UTF-8
| 452
| 2.96875
| 3
|
[] |
no_license
|
require 'byebug'
class AttrAccessorObject
def self.my_attr_accessor(*names)
names.each do |ivar|
define_method("#{ivar}"){instance_variable_get("@#{ivar}") }
define_method("#{ivar}="){ |i| instance_variable_set("@#{ivar}", i) }
end
end
end
# class AnimalConstructor
# def self.be_a_god(species, sound)
# Object.const_set(species, Class.new{ define_method("#{sound}") {puts "#{sound}"} })
# end
# end
# 4:32 PM
| true
|
9f61fac2a8d2adf51cb77130810401c5db471ff9
|
Ruby
|
mugenup/html-pipeline-bungo
|
/lib/html/pipeline/bungo/dash_filter.rb
|
UTF-8
| 250
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
module HTML
class Pipeline
class DashFilter < TextFilter
def call
dash_filter(@text)
end
private
def dash_filter(text)
text.gsub(':--', "<span class='dash'>――</span>")
end
end
end
end
| true
|
20751e6480280ec91822fbbe088e7021abf721c2
|
Ruby
|
dtinth/codehew2016
|
/qualification_day2/01_review2[refactored].rb
|
UTF-8
| 500
| 3.53125
| 4
|
[] |
no_license
|
# NOTE: Refactored version
# Uses Array#reduce instead of imperative code and
# always use a Range in the reduction array.
def cont? x, y
y == x.end + 1
end
def succ x, y
(x.begin..y)
end
gets.to_i.times do
data = gets.split[1..-1].map(&:to_i).sort
out = data.reduce [ ] do |a, x|
if !a.empty? && cont?(a.last, x)
[*a[0...-1], succ(a.last, x)]
else
[*a, x..x]
end
end
puts out.map { |x| x.size > 1 ? "#{x.begin}->#{x.end}" : x.begin }.join(',')
end
| true
|
3f01786e03821e3661072fb2a064030782d50ac7
|
Ruby
|
mh-o/resume
|
/Undergrad CS1632 Software Quality Assurance/Deliverable 3/transaction_checker.rb
|
UTF-8
| 1,799
| 3.640625
| 4
|
[] |
no_license
|
class TransactionChecker
attr_accessor :people
def initialize
@people = {}
end
def check_transaction(arr)
i = 0
for x in arr
seperate_transactions = split_transactions(x)
if perform_transaction(seperate_transactions, i) == 1
return 1
end
i += 1
end
display_results()
return 0
end
def split_transactions(string)
return string.split(':')
end
def perform_transaction(arr, i)
for x in arr
temp_str = x.split('>')
payer = temp_str[0]
payee_and_payment = temp_str[1]
temp_str = payee_and_payment.split('(')
payee = temp_str[0]
payment = temp_str[1].chomp(')')
add_person(payer)
add_person(payee)
transfer_funds(payer, payee, payment)
if check_balance(payer, i) == 1
return 1
end
end
end
def add_person(person)
if (@people.key?(person)) == false
@people[person] = 0
end
end
def transfer_funds(payer, payee, payment)
payer_funds = @people[payer].to_i
payee_funds = @people[payee].to_i
if payer != "SYSTEM"
payer_funds = (payer_funds - payment.to_i)
end
if payer == payee # handle case where payer and payee are the same
return 0
end
payee_funds = (payee_funds + payment.to_i)
@people[payer] = payer_funds
@people[payee] = payee_funds
end
def display_results()
first = true
@people.each do |key, val|
if first
first = false
next
end
puts "#{key}: #{val} billcoins"
end
end
def check_balance(person, i)
balance = @people[person].to_i
if balance < 0
puts "Line #{i}: Invalid block, address #{person} has #{@people[person]} billcoins!"
return 1
else
return 0
end
end
end
| true
|
432b43921fd78c9c390104b13993940f43e30c43
|
Ruby
|
usman-tahir/rubyeuler
|
/happy_numbers.rb
|
UTF-8
| 510
| 3.984375
| 4
|
[] |
no_license
|
# http://rosettacode.org/wiki/Happy_numbers
def happy?(number)
while (number != 1) && (number != 89)
number = sum_square_digits(number)
end
number == 1
end
def sum_square_digits(number,accumulator=0)
number < 10 ? accumulator + (number ** 2) : ((number % 10) ** 2) + sum_square_digits(number/10,accumulator)
end
def find_happy_numbers(number,array=[],counter=1)
until array.count == number
array << counter if happy?(counter)
counter += 1
end
array
end
p find_happy_numbers(8)
| true
|
cfdc5d73660a9a01ef6c7e65712a1f6e8ad7e4bb
|
Ruby
|
piloulac/advent-code-2020
|
/day_1/part_2.rb
|
UTF-8
| 420
| 2.953125
| 3
|
[] |
no_license
|
# frozen_string_literal: true
file = File.join(File.dirname(__FILE__), 'input.txt')
input = File.open(file).readlines.map(&:chomp).map(&:to_i)
hash = {}
input.each do |val1|
input.each do |val2|
reste = 2020 - val1 - val2
hash[reste] = [val1, val2] if reste.positive?
end
end
input.each do |val|
if hash.key?(val) && !hash[val].include?(val)
puts (hash[val] + [val]).reduce(:*)
break
end
end
| true
|
d40070f6fe04dc60adba936affc406dcf2eb5b78
|
Ruby
|
Catamarander/Chess
|
/board.rb
|
UTF-8
| 4,129
| 3.640625
| 4
|
[] |
no_license
|
require_relative 'pieces/pieces.rb'
class Board
attr_accessor :chess_board, :cursor
def initialize(setup = true)
set_up_game(setup)
@cursor = [0, 0]
end
def self.on_board?(pos)
pos.all? { |coord| (0..7).cover? coord }
end
def move_piece!(from_pos, to_pos)
piece = self[from_pos]
self[to_pos] = piece
self[from_pos] = nil
piece.pos = to_pos
piece.moved = true if piece.is_a?(Pawn)
end
def move(from_pos, to_pos) # only used by valid_moves
piece = self[from_pos]
self[to_pos] = piece
self[from_pos] = nil
piece.pos = to_pos
end
def all_moves(piece)
piece.moves
end
def piece_at_position?(position)
!self[position].nil?
end
def dup_board
possible_board = Board.new(false)
flattened = chess_board.flatten.compact
flattened.each do |piece|
possible_board[piece.pos] = piece.class.new(possible_board, piece.pos, piece.color)
end
possible_board
end
def [](pos)
row, col = pos
chess_board[row][col]
end
def []=(pos, piece)
row, col = pos
chess_board[row][col] = piece
end
def add_piece(pos, piece)
self[pos] = piece
end
def cursor_position(input_letter)
case input_letter
when 'w'
cursor[0] -= 1
when 's'
cursor[0] += 1
when 'a'
cursor[1] -= 1
when 'd'
cursor[1] += 1
when 't'
cursor
when 'f'
cursor
when 'q'
raise "You quit"
end
end
def in_check?(color)
opponents = get_all_not_color(color)
king = king_position(color)
opponents.any? do |opp|
moves = all_moves(opp)
moves.include? king
end
end
def check_mate?(color)
teammates = get_all_color(color)
teammates.all? { |teammate| teammate.valid_moves.empty? }
end
def king_position(color)
get_all_color(color).select{ |el| el.is_a? King }[0].pos
end
def get_all_color(color)
flat_board = chess_board.flatten.compact
flat_board.select {|el| el.color == color }
end
def get_all_not_color(color)
flat_board = chess_board.flatten.compact
flat_board.select { |el| el.color != color }
end
def set_up_game(setup = true)
@chess_board = Array.new(8) { Array.new(8) { nil } }
if setup
["white", "black"].each do |color|
place_pawns(color)
place_pieces(color)
end
end
end
def place_pawns(color)
(color == "white") ? row = 1 : row = 6
8.times { |col| Pawn.new(self, [row, col], color)}
end
def place_pieces(color)
pieces = [Rook, Knight, Bishop, Queen, King, Bishop, Knight, Rook]
(color == "white") ? row = 0 : row = 7
pieces.each_with_index { |piece, col| piece.new(self, [row, col], color) }
end
#################
### RENDERING ###
#################
def render
letter_line = " A B C D E F G H"
white, black = "\u2654".encode('utf-8'), "\u265A".encode('utf-8')
board_without_letters = chess_board.map.with_index do |row, i|
add_numbers_to_row(row, i)
end
["", letter_line, board_without_letters, letter_line,
"", "White is #{white} Black is #{black}"].join("\n")
end
def add_numbers_to_row(row, i)
individual_line = [render_row(row, i)]
individual_line.map { |elem| "#{8 - i} #{elem} #{8 - i}"}
end
def render_row(row, i)
individual_row = row.map.with_index do |square, j|
render_square(square, i, j)
end
individual_row.join("")
end
def render_square(square, i, j)
if square
square.inspect.colorize(:background => decide_background_color(i, j))
else
' '.colorize(:background => decide_background_color(i, j))
end
end
def decide_background_color(i, j)
return :yellow if [i, j] == cursor
return :light_gray if (i + j).odd?
:blue
end
def self.render_position(ary)
grid_hash = Hash[0, "A", 1, "B", 2, "C", 3, "D",
4, "E", 5, "F", 6, "G", 7, "H"]
number_hash = Hash[0, 8, 1, 7, 2, 6, 3, 5, 4, 4, 5, 3, 6, 2, 7, 1]
ary.map do |computer_position|
number, letter = computer_position
"#{grid_hash[letter]}#{number_hash[number]}"
end
end
end
| true
|
37baa1dd9b1ed4666125b5a3f65f5f8204a80ec4
|
Ruby
|
artursmolin/Thinknetica-BlackJack
|
/message_panel.rb
|
UTF-8
| 1,366
| 3.21875
| 3
|
[] |
no_license
|
class MessagePanel
def new_game
p 'D you want to play a new game? Put yes, if you want to continue'
input = gets.chomp
if input != "yes"
p 'Thanks for game!'
exit
end
system('clear')
end
def player_name
p 'Please introduce yourself.'
end
def stop(player, dealer)
p '**********************************************'
p 'Game results: '
p "Dealer: #{dealer.cards_opened}, points: #{dealer.cards_sum}, bank: #{dealer.bank}"
p "Player: #{player.cards_opened}, points: #{player.cards_sum}, bank: #{player.bank}"
p '***********************************************'
end
def dashboard_first(player, dealer, game)
dealer_cards = dealer.cards_closed
p "Casino bank: #{game.bank}"
p "-------------------------"
p "Player cards: #{player.cards_opened} | bank: #{player.bank}"
p "Dealer cards: #{dealer_cards.join(' ')} | bank: #{dealer.bank}"
p "-------------------------"
end
def move_menu
p 'Your turn:'
p '1. Pass'
p '2. Take card'
p '3. Open cards'
end
def dealer_message(message)
p "Dealer is #{message}"
end
def dealer_winner
p 'Dealer win!'
system('clear')
end
def player_winner(player)
p "#{player.name} win!"
system('clear')
end
def draw_winner
p 'Draw!'
end
def game_end
p 'Game finished'
end
end
| true
|
37ca4175a1cb687e95f10b741e7c91e8d39d9006
|
Ruby
|
NiketaJen/reading-errors-and-debugging-using-pry-hou01-seng-ft-060120
|
/lib/pry_debugging.rb
|
UTF-8
| 66
| 2.546875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'pry'
def plus_two(num)
(num + 2)
end
binding.pry
| true
|
748ec13bbaf69d83be7dce85b740f1c57d9e0d18
|
Ruby
|
usernam3/meta_commit
|
/features/support/meta_commit_world.rb
|
UTF-8
| 1,265
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
module MetaCommitWorld
@git_repo_name
@configuration_name
def git_repo_name(repo_name)
@git_repo_name=repo_name
end
def configuration_name(config_name)
@configuration_name=config_name
end
def directory_option
repository_fixtures = File.join(File.dirname(File.dirname(__FILE__)), 'tmp', 'repositories')
full_repo_path = File.join(repository_fixtures, @git_repo_name)
"--directory=#{full_repo_path}"
end
def configuration_option
"" unless @configuration_name.nil?
end
def command_options
command_options=[]
command_options << directory_option unless @git_repo_name.nil?
command_options.join(' ')
end
def fixture_changelog_file_path(file)
File.join(File.dirname(File.dirname(__FILE__)), 'fixtures', 'changelogs', file)
end
def fixture_note_file_path(repository, object_id)
File.join(File.dirname(File.dirname(__FILE__)), 'fixtures', 'notes', repository, object_id)
end
def fixture_configuration_file(file_name)
File.join(File.dirname(File.dirname(__FILE__)), 'fixtures', 'configurations', file_name)
end
def repository_file_path(repository, file)
File.join(File.dirname(File.dirname(__FILE__)), 'tmp', 'repositories', repository, file)
end
end
World(MetaCommitWorld)
| true
|
5d445f6f049fb15c56af0ba1cbb5c151f8d86264
|
Ruby
|
Drewbie345/Library
|
/my-library.rb
|
UTF-8
| 2,776
| 3.84375
| 4
|
[] |
no_license
|
class Library
attr_accessor :name
# create new library
def initialize(name)
@name = name
@books = []
@book_status = Hash.new
@who_has_book = Hash.new
end
# add new books to library
def add_book(book)
@books << book
@book_status[book.title] = book.get_status
end
# get list of current books
def book_list
puts "Here are the books in our library:"
@books.each { |book| puts "#{book.name}" }
end
def check_book_status
@book_status.each { |k, v| puts "#{k}: #{v}" }
end
# get list of current available books
def available_books
puts "Available Books:"
@book_status.each { |k, v| puts "#{k}" if v == "available" }
end
# get list of current borrowed books
def borrowed_books
puts "Borrowed Books:"
@book_status.each { |k, v| puts "#{k}" if v == "checked_out" }
end
# get a list of books and associated borrowers who have them checked out
def who_has_what
@who_has_book.each do |k, v|
puts "#{k}: #{v}"
end
end
# check out books
def check_out(book, borrower)
borrower.add_my_books(book)
@who_has_book[borrower.name] = borrower.my_books
@number_of_books = borrower.my_books
if @who_has_book.has_key?(borrower.name) && @number_of_books.count <= 2
if book.get_status == "available"
book.change_status
if @book_status.has_key?(book.title)
@book_status[book.title] = book.get_status
end
puts "You've checked out #{book.title}"
else
puts "Not Available!"
end
else
puts "What a reader! You've got too many books!"
end
end
# check in books
def check_in(book, borrower)
book.change_status
@book_status.each do |key, value|
if key == book.title
value.replace "available"
end
end
if @who_has_book.has_key?(borrower.name)
@who_has_book.each do |key, value|
value.delete_if { |b| b == book.title }
end
end
end
# check book status
def is_available?(book)
puts "#{book.title}: #{book.get_status}"
end
end
class Borrower
attr_accessor :name
# create new borrower
def initialize(name)
@name = name
@my_books = []
end
# get borrower's checked-out books
def add_my_books(book)
@my_books << book.title
end
def my_books
@my_books
end
def print_my_books
@my_books.each { |book| puts "#{book}" }
end
end
class Book
attr_accessor :title, :author, :id, :status
# create new book
def initialize(title, author)
@title = title
@author = author
@status = "available"
@id = nil
end
# get book's current status
def get_status
status
end
# prints book's current status
def print_status
puts "#{status}"
end
# change book's current status
def change_status
if status.include?("available")
status = "checked_out"
elsif status.include?("checked_out")
status = "available"
end
end
end
| true
|
6db89eeff6a3231683f372c5c5eef8d230fa2b7e
|
Ruby
|
rramsden/dev-null-api
|
/app/models/key.rb
|
UTF-8
| 219
| 3.265625
| 3
|
[] |
no_license
|
require 'prime'
class Key
attr_reader :value
def initialize(value)
@value = value
end
def very_interesting?
primes.include?(@value.to_i)
end
private
def primes
Prime.first(1000)
end
end
| true
|
45cd9f433dab65e1a281522eea75511af3b9b024
|
Ruby
|
JBrabson/tee_vee
|
/lib/character.rb
|
UTF-8
| 209
| 3.046875
| 3
|
[] |
no_license
|
class Character
attr_reader :name,
:actor,
:salary
def initialize(name_pay)
@name = name_pay[:name]
@actor = name_pay[:actor]
@salary = name_pay[:salary]
end
end
| true
|
84ea821c1fb6518403af867fee184da1417371a4
|
Ruby
|
yuki3738/codility
|
/lessons/2-arrays/cyclic_rotation.rb
|
UTF-8
| 100
| 2.9375
| 3
|
[] |
no_license
|
def solution(a, k)
return a if a.empty?
k.times do
i = a.pop
a.unshift(i)
end
a
end
| true
|
506a3a4c18d765305de347956102042f20246ac1
|
Ruby
|
kierrakay/activerecord-tvshow-online-web-pt-081219
|
/app/models/show.rb
|
UTF-8
| 616
| 2.859375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Show < ActiveRecord::Base
def self.highest_rating
self.maximum(:rating)
end
def self.most_popular_show
#self.where(rating: highest_rating).first
#self.where(rating: highest_rating) returns aray but we want one instance thats why we have .first above
self.find_by(rating: highest_rating)
end
def self.lowest_rating
self.minimum(:rating)
end
def self.least_popular_show
self.find_by(rating: lowest_rating)
end
def self.ratings_sum
self.sum(:rating)
end
def self.popular_shows
self.where("rating > 5")
end
def self.shows_by_alphabetical_order
self.order("name ASC")
end
end
| true
|
61cfecc8a1937c1db7abb5736bfba1bd2310985b
|
Ruby
|
njch5/linked-lists
|
/lib/linked_list.rb
|
UTF-8
| 1,399
| 3.671875
| 4
|
[
"MIT"
] |
permissive
|
require_relative "node"
class LinkedList
attr_reader :head
def initialize
@head = nil
end
# Time complexity - O(1)
# Space complexity - O(1)
def add_first(data)
@head = Node.new(data, head)
end
# Time complexity - O(1)
# Space complexity - O(1)
def get_first
return @head if @head.nil?
return @head.data
end
# Time complexity - O(n) n is the size of the list
# Space complexity - O(1)
def length
count = 0
current = head
until current.nil?
count += 1
current = current.next
end
return count
end
# Time complexity - O(n) n is the length of the list
# Space complexity - O(1)
def add_last(data)
if !@head
@head = Node.new(data)
else
current = @head
while current.next
current = current.next
end
current.next = Node.new(data)
end
end
# Time complexity - O(n) where n is the length of the list
# Space complexity - O(1)
def get_last
return nil unless @head
current = @head
while current.next
current = current.next
end
return current.data
end
# Time complexity - O(n) where n is the index
# Space complexity - O(1)
def get_at_index(index)
return nil unless @head
current = @head
index.times do
return nil unless current.next
current = current.next
end
return current.data
end
end
| true
|
3388d18fda849fe63435bc102214919f22e7d06b
|
Ruby
|
schonfeld/middleman-hashicorp
|
/lib/middleman-hashicorp/releases.rb
|
UTF-8
| 757
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
require "open-uri"
class Middleman::HashiCorp::Releases
RELEASES_URL = "https://releases.hashicorp.com".freeze
class Build < Struct.new(:name, :version, :os, :arch, :url); end
def self.fetch(product, version)
url = "#{RELEASES_URL}/#{product}/#{version}/index.json"
r = JSON.parse(open(url).string,
create_additions: false,
symbolize_names: true,
)
# Convert the builds into the following format:
#
# {
# "os" => {
# "arch" => "https://download.url"
# }
# }
#
{}.tap do |h|
r[:builds].each do |b|
build = Build.new(*b.values_at(*Build.members))
h[build.os] ||= {}
h[build.os][build.arch] = build.url
end
end
end
end
| true
|
1b4636fdcfddc9fe398bb2470babf0759ee39b96
|
Ruby
|
shullmb/odin_oop
|
/mastermind/mind.rb
|
UTF-8
| 1,878
| 3.484375
| 3
|
[] |
no_license
|
module Mastermind
class Board
attr_accessor :pattern, :proposed, :guess
@@options = ["R","G","B","Y","W"]
@@screen_width = 100
def initialize
@pattern = Array.new(4)
@guess = 0
set_pattern
display_obscured_code
puts "Pattern Set!".center(@@screen_width)
puts "\n\n\n\n"
end
def choose_difficulty
puts "Easy, Normal, or Hard?".center(@@screen_width)
choice = gets.chomp.upcase[0]
case choice
when "E"
@guess = 16
when "N"
@guess = 12
when "H"
@guess = 8
else
puts "That is not a valid choice"
end
puts "You have #{@guess} guesses to determine the pattern".center(@@screen_width)
end
def display_obscured_code
puts "\n\n\n"
puts "|| X || X || X || X ||".center(@@screen_width)
puts "\n\n"
end
def display
puts %Q{
--- ---
|| || ||
--- --- || #{self.proposed[0]} || #{self.proposed[1]} || #{self.proposed[2]} || #{self.proposed[3]} ||
|| || ||
--- ---
}
puts "Guesses left: #{@guess}".center(@@screen_width)
puts "Proposed: #{self.proposed.join}".center(@@screen_width)
end
def prompt
print "Proposed pattern: "
@proposed = gets.chomp.upcase.split("")
end
def compare
self.pattern.each_with_index do |pattern_peg, pattern_index|
self.proposed.each_with_index do |guess, index|
if pattern_peg == guess && index == pattern_index
puts "black"
elsif pattern_peg == guess && index != pattern_index
puts "white"
else
puts "no match"
end
end
pattern_peg.include? self.proposed.join
end
@guess -= 1
end
private
def set_pattern
self.pattern.each_with_index do |value, index|
value = @@options.sample
self.pattern[index] = value
end
end
end
end
| true
|
1b6e940b4c3c6b62f2fe29bc73f6c8dc0e969422
|
Ruby
|
PinkDeer/ruby
|
/rubyschool/lesson06/app6.rb
|
UTF-8
| 1,948
| 4.03125
| 4
|
[] |
no_license
|
# Какую сумму будем откладывать в месяц:
# Сколько месяцев будем отклыдвать:
# Вывод:
# Накопления за 1 месяц:
# Накопления за 2 месяц:
# Мой вариант:
print "Какую сумму будем откладывать в месяц: "
sum = gets.chomp.to_i
print "Сколько месяцев будем отклыдвать: "
mm = gets.chomp.to_i
1.upto(mm) do |x|
puts "Накопления за #{x} месяц: #{sum*x}"
end
# Вариант Журавля
print "Какую сумму будем откладывать в месяц: "
x = gets.chomp.to_f
print "Сколько месяцев: "
n = gets.chomp.to_i
s = 0
1.upto(n) do |mm|
s = s + x
puts "Накопления за #{mm} месяц: #{s}"
end
# Домашнее задание:
# Сколько лет будем копить:
# Какую сумму будем откладывать в месяц:
# Вывод должен быть следующим
# Год 1 месяц 1, отложено: ...
# Год 1 месяц 2, отложено: ...
# Год 1 месяц 12, отложено: ...
# Год 2 месяц 1, отложено: ...
# Год 2 месяц 2, отложено: ...
# Год 2 месяц 12, отложено: ...
print "Сколько лет будем копить: "
year = gets.chomp.to_i
print "Какую сумму будем откладывать в месяц: "
x = gets.chomp.to_f
s = 0
1.upto(year) do |y|
1.upto(12) do |i|
s = s + x
puts "Год #{y} месяц #{i}: отложено #{s}"
end
end
# Вариант Журавля
print "Какую сумму будем откладывать в месяц: "
x = gets.chomp.to_f
print "Сколько лет будем откладывать: "
n = gets.chomp.to_i
s = 0
1.upto do |n|
1.upto(12) do |mm|
s = s + x
puts "Год #{n} месяц #{mm}, отложено: #{s}"
end
| true
|
b9595fb33c20693a2c307b94c53ad73ca8b2ed37
|
Ruby
|
deanwilson/puppet-ipv4_octet
|
/lib/puppet/parser/functions/ipv4_octet.rb
|
UTF-8
| 1,265
| 2.84375
| 3
|
[
"Apache-2.0"
] |
permissive
|
module Puppet
module Parser
module Functions
newfunction(:ipv4_octet, type: :rvalue, arity: 2, doc: <<-EOD
Returns the given octet of an IP Address.
$first = ipv4_octet('10.11.12.13', 0) # returns 10
$last = ipv4_octet('10.11.12.13', 3) # returns 13
This function does not yet allow you to extract subselections - such as [1..3]
EOD
) do |args|
unless args.length == 2
fail ArgumentError, "ipv4_octet(): wrong number of arguments (#{args.length} must be 2)"
end
ipaddress = args[0]
index = args[1].to_i
# load in the ip validation function from puppetlabs-stdlib
unless Puppet::Parser::Functions.function('is_ip_address')
fail Puppet::ParseError, 'ipv4_octet(): requires the puppetlabs-stdlib functions'
end
unless function_is_ip_address([ipaddress])
fail ArgumentError, "ipv4_octet(): [#{ipaddress}] is an invalid ip address"
end
allowed_index = [0, 1, 2, 3, -1]
unless allowed_index.include? index
fail ArgumentError, "ipv4_octet(): index must be one of #{allowed_index.join(',')}"
end
ipaddress.split('.')[index].to_i
end
end
end
end
| true
|
49d36f54b5ef9dee143f50b8de1b99ba29342b6c
|
Ruby
|
luanaAlm/Atividades-faculdade
|
/Ruby/EX2_F.rb
|
UTF-8
| 200
| 3.734375
| 4
|
[] |
no_license
|
puts "Digite o primeiro valor"
a = gets.chomp.to_i
puts "Digite o segundo valor"
b = gets.chomp.to_i
puts "Digite o terceiro valor"
c = gets.chomp.to_i
soma = a + b + c
if soma >= 100
puts soma
end
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.